hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
7daf79cb315174437ca84aad9b0a1e0e48fc25ea7aa765ba567f0d3cbb5b5863 | # -*- coding: utf-8 -*-
import sys
from sympy.assumptions import Q
from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq
from sympy.functions import exp, factorial, factorial2, sin
from sympy.logic import And
from sympy.series import Limit
from sympy.testing.pytest import raises, skip
from sympy.parsing.sympy_parser import (
parse_expr, standard_transformations, rationalize, TokenError,
split_symbols, implicit_multiplication, convert_equals_signs,
convert_xor, function_exponentiation, lambda_notation, auto_symbol,
repeated_decimals, implicit_multiplication_application,
auto_number, factorial_notation, implicit_application,
_transformation, T
)
def test_sympy_parser():
x = Symbol('x')
inputs = {
'2*x': 2 * x,
'3.00': Float(3),
'22/7': Rational(22, 7),
'2+3j': 2 + 3*I,
'exp(x)': exp(x),
'x!': factorial(x),
'x!!': factorial2(x),
'(x + 1)! - 1': factorial(x + 1) - 1,
'3.[3]': Rational(10, 3),
'.0[3]': Rational(1, 30),
'3.2[3]': Rational(97, 30),
'1.3[12]': Rational(433, 330),
'1 + 3.[3]': Rational(13, 3),
'1 + .0[3]': Rational(31, 30),
'1 + 3.2[3]': Rational(127, 30),
'.[0011]': Rational(1, 909),
'0.1[00102] + 1': Rational(366697, 333330),
'1.[0191]': Rational(10190, 9999),
'10!': 3628800,
'-(2)': -Integer(2),
'[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
'Symbol("x").free_symbols': x.free_symbols,
"S('S(3).n(n=3)')": 3.00,
'factorint(12, visual=True)': Mul(
Pow(2, 2, evaluate=False),
Pow(3, 1, evaluate=False),
evaluate=False),
'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
'Q.even(x)': Q.even(x),
}
for text, result in inputs.items():
assert parse_expr(text) == result
raises(TypeError, lambda:
parse_expr('x', standard_transformations))
raises(TypeError, lambda:
parse_expr('x', transformations=lambda x,y: 1))
raises(TypeError, lambda:
parse_expr('x', transformations=(lambda x,y: 1,)))
raises(TypeError, lambda: parse_expr('x', transformations=((),)))
raises(TypeError, lambda: parse_expr('x', {}, [], []))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
def test_rationalize():
inputs = {
'0.123': Rational(123, 1000)
}
transformations = standard_transformations + (rationalize,)
for text, result in inputs.items():
assert parse_expr(text, transformations=transformations) == result
def test_factorial_fail():
inputs = ['x!!!', 'x!!!!', '(!)']
for text in inputs:
try:
parse_expr(text)
assert False
except TokenError:
assert True
def test_repeated_fail():
inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
'0.1[[1]]', '0x1.1[1]']
# All are valid Python, so only raise TypeError for invalid indexing
for text in inputs:
raises(TypeError, lambda: parse_expr(text))
inputs = ['0.1[', '0.1[1', '0.1[]']
for text in inputs:
raises((TokenError, SyntaxError), lambda: parse_expr(text))
def test_repeated_dot_only():
assert parse_expr('.[1]') == Rational(1, 9)
assert parse_expr('1 + .[1]') == Rational(10, 9)
def test_local_dict():
local_dict = {
'my_function': lambda x: x + 2
}
inputs = {
'my_function(2)': Integer(4)
}
for text, result in inputs.items():
assert parse_expr(text, local_dict=local_dict) == result
def test_local_dict_split_implmult():
t = standard_transformations + (split_symbols, implicit_multiplication,)
w = Symbol('w', real=True)
y = Symbol('y')
assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
def test_local_dict_symbol_to_fcn():
x = Symbol('x')
d = {'foo': Function('bar')}
assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
d = {'foo': Symbol('baz')}
raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
def test_global_dict():
global_dict = {
'Symbol': Symbol
}
inputs = {
'Q & S': And(Symbol('Q'), Symbol('S'))
}
for text, result in inputs.items():
assert parse_expr(text, global_dict=global_dict) == result
def test_issue_2515():
raises(TokenError, lambda: parse_expr('(()'))
raises(TokenError, lambda: parse_expr('"""'))
def test_issue_7663():
x = Symbol('x')
e = '2*(x+1)'
assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
assert parse_expr(e, evaluate=0).equals(2*(x+1))
def test_recursive_evaluate_false_10560():
inputs = {
'4*-3' : '4*-3',
'-4*3' : '(-4)*3',
"-2*x*y": '(-2)*x*y',
"x*-4*x": "x*(-4)*x"
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_function_evaluate_false():
inputs = [
'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
'exp(0)', 'log(0)', 'sqrt(0)',
]
for case in inputs:
expr = parse_expr(case, evaluate=False)
assert case == str(expr) != str(expr.doit())
assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
def test_issue_10773():
inputs = {
'-10/5': '(-10)/5',
'-10/-5' : '(-10)/(-5)',
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_split_symbols():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
xy = Symbol('xy')
assert parse_expr("xy") == xy
assert parse_expr("xy", transformations=transformations) == x*y
def test_split_symbols_function():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
f = Function('f')
assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
assert parse_expr("af(x+1)", transformations=transformations,
local_dict={'f':f}) == a*f(x+1)
def test_functional_exponent():
t = standard_transformations + (convert_xor, function_exponentiation)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
yfcn = Function('y')
assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
def test_match_parentheses_implicit_multiplication():
transformations = standard_transformations + \
(implicit_multiplication,)
raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
def test_convert_equals_signs():
transformations = standard_transformations + \
(convert_equals_signs, )
x = Symbol('x')
y = Symbol('y')
assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
assert parse_expr("(2*y = x) = False",
transformations=transformations) == Eq(Eq(2*y, x), False)
def test_parse_function_issue_3539():
x = Symbol('x')
f = Function('f')
assert parse_expr('f(x)') == f(x)
def test_split_symbols_numeric():
transformations = (
standard_transformations +
(implicit_multiplication_application,))
n = Symbol('n')
expr1 = parse_expr('2**n * 3**n')
expr2 = parse_expr('2**n3**n', transformations=transformations)
assert expr1 == expr2 == 2**n*3**n
expr1 = parse_expr('n12n34', transformations=transformations)
assert expr1 == n*12*n*34
def test_unicode_names():
assert parse_expr('α') == Symbol('α')
def test_python3_features():
# Make sure the tokenizer can handle Python 3-only features
if sys.version_info < (3, 7):
skip("test_python3_features requires Python 3.7 or newer")
assert parse_expr("123_456") == 123456
assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
def test_issue_19501():
x = Symbol('x')
eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
standard_transformations +
(implicit_multiplication_application,)))
assert eq.free_symbols == {x}
def test_parsing_definitions():
from sympy.abc import x
assert len(_transformation) == 12 # if this changes, extend below
assert _transformation[0] == lambda_notation
assert _transformation[1] == auto_symbol
assert _transformation[2] == repeated_decimals
assert _transformation[3] == auto_number
assert _transformation[4] == factorial_notation
assert _transformation[5] == implicit_multiplication_application
assert _transformation[6] == convert_xor
assert _transformation[7] == implicit_application
assert _transformation[8] == implicit_multiplication
assert _transformation[9] == convert_equals_signs
assert _transformation[10] == function_exponentiation
assert _transformation[11] == rationalize
assert T[:5] == T[0,1,2,3,4] == standard_transformations
t = _transformation
assert T[-1, 0] == (t[len(t) - 1], t[0])
assert T[:5, 8] == standard_transformations + (t[8],)
assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
|
75a7f3e347ba2a9910e3a72b9e83b29b19a7359a2d4cc409da10cfa4cda79018 | from sympy.testing.pytest import raises, XFAIL
from sympy.external import import_module
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.numbers import (E, oo)
from sympy.core.power import Pow
from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.complexes import (Abs, conjugate)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.integers import (ceiling, floor)
from sympy.functions.elementary.miscellaneous import (root, sqrt)
from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan)
from sympy.integrals.integrals import Integral
from sympy.series.limits import Limit
from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge
from sympy.physics.quantum.state import Bra, Ket
from sympy.abc import x, y, z, a, b, c, t, k, n
antlr4 = import_module("antlr4")
# disable tests if antlr4-python*-runtime is not present
if not antlr4:
disabled = True
theta = Symbol('theta')
f = Function('f')
# shorthand definitions
def _Add(a, b):
return Add(a, b, evaluate=False)
def _Mul(a, b):
return Mul(a, b, evaluate=False)
def _Pow(a, b):
return Pow(a, b, evaluate=False)
def _Sqrt(a):
return sqrt(a, evaluate=False)
def _Conjugate(a):
return conjugate(a, evaluate=False)
def _Abs(a):
return Abs(a, evaluate=False)
def _factorial(a):
return factorial(a, evaluate=False)
def _exp(a):
return exp(a, evaluate=False)
def _log(a, b):
return log(a, b, evaluate=False)
def _binomial(n, k):
return binomial(n, k, evaluate=False)
def test_import():
from sympy.parsing.latex._build_latex_antlr import (
build_parser,
check_antlr_version,
dir_latex_antlr
)
# XXX: It would be better to come up with a test for these...
del build_parser, check_antlr_version, dir_latex_antlr
# These LaTeX strings should parse to the corresponding SymPy expression
GOOD_PAIRS = [
(r"0", 0),
(r"1", 1),
(r"-3.14", -3.14),
(r"(-7.13)(1.5)", _Mul(-7.13, 1.5)),
(r"x", x),
(r"2x", 2*x),
(r"x^2", x**2),
(r"x^{3 + 1}", x**_Add(3, 1)),
(r"-c", -c),
(r"a \cdot b", a * b),
(r"a / b", a / b),
(r"a \div b", a / b),
(r"a + b", a + b),
(r"a + b - a", _Add(a+b, -a)),
(r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
(r"(x + y) z", _Mul(_Add(x, y), z)),
(r"\left(x + y\right) z", _Mul(_Add(x, y), z)),
(r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
(r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
(r"\left[x + y\right] z", _Mul(_Add(x, y), z)),
(r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)),
(r"1+1", _Add(1, 1)),
(r"0+1", _Add(0, 1)),
(r"1*2", _Mul(1, 2)),
(r"0*1", _Mul(0, 1)),
(r"x = y", Eq(x, y)),
(r"x \neq y", Ne(x, y)),
(r"x < y", Lt(x, y)),
(r"x > y", Gt(x, y)),
(r"x \leq y", Le(x, y)),
(r"x \geq y", Ge(x, y)),
(r"x \le y", Le(x, y)),
(r"x \ge y", Ge(x, y)),
(r"\lfloor x \rfloor", floor(x)),
(r"\lceil x \rceil", ceiling(x)),
(r"\langle x |", Bra('x')),
(r"| x \rangle", Ket('x')),
(r"\sin \theta", sin(theta)),
(r"\sin(\theta)", sin(theta)),
(r"\sin^{-1} a", asin(a)),
(r"\sin a \cos b", _Mul(sin(a), cos(b))),
(r"\sin \cos \theta", sin(cos(theta))),
(r"\sin(\cos \theta)", sin(cos(theta))),
(r"\frac{a}{b}", a / b),
(r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
(r"\frac{7}{3}", _Mul(7, _Pow(3, -1))),
(r"(\csc x)(\sec y)", csc(x)*sec(y)),
(r"\lim_{x \to 3} a", Limit(a, x, 3)),
(r"\lim_{x \rightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')),
(r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')),
(r"\infty", oo),
(r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)),
(r"\frac{d}{dx} x", Derivative(x, x)),
(r"\frac{d}{dt} x", Derivative(x, t)),
(r"f(x)", f(x)),
(r"f(x, y)", f(x, y)),
(r"f(x, y, z)", f(x, y, z)),
(r"\frac{d f(x)}{dx}", Derivative(f(x), x)),
(r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
(r"x \neq y", Unequality(x, y)),
(r"|x|", _Abs(x)),
(r"||x||", _Abs(Abs(x))),
(r"|x||y|", _Abs(x)*_Abs(y)),
(r"||x||y||", _Abs(_Abs(x)*_Abs(y))),
(r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)),
(r"\int x dx", Integral(x, x)),
(r"\int x d\theta", Integral(x, theta)),
(r"\int (x^2 - y)dx", Integral(x**2 - y, x)),
(r"\int x + a dx", Integral(_Add(x, a), x)),
(r"\int da", Integral(1, a)),
(r"\int_0^7 dx", Integral(1, (x, 0, 7))),
(r"\int_a^b x dx", Integral(x, (x, a, b))),
(r"\int^b_a x dx", Integral(x, (x, a, b))),
(r"\int_{a}^b x dx", Integral(x, (x, a, b))),
(r"\int^{b}_a x dx", Integral(x, (x, a, b))),
(r"\int_{a}^{b} x dx", Integral(x, (x, a, b))),
(r"\int^{b}_{a} x dx", Integral(x, (x, a, b))),
(r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
(r"\int (x+a)", Integral(_Add(x, a), x)),
(r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
(r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)),
(r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)),
(r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)),
(r"\int \frac{1}{a} + \frac{1}{b} dx",
Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
(r"\int \frac{3 \cdot d\theta}{\theta}",
Integral(3*_Pow(theta, -1), theta)),
(r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
(r"x_0", Symbol('x_{0}')),
(r"x_{1}", Symbol('x_{1}')),
(r"x_a", Symbol('x_{a}')),
(r"x_{b}", Symbol('x_{b}')),
(r"h_\theta", Symbol('h_{theta}')),
(r"h_{\theta}", Symbol('h_{theta}')),
(r"h_{\theta}(x_0, x_1)",
Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
(r"x!", _factorial(x)),
(r"100!", _factorial(100)),
(r"\theta!", _factorial(theta)),
(r"(x + 1)!", _factorial(_Add(x, 1))),
(r"(x!)!", _factorial(_factorial(x))),
(r"x!!!", _factorial(_factorial(_factorial(x)))),
(r"5!7!", _Mul(_factorial(5), _factorial(7))),
(r"\sqrt{x}", sqrt(x)),
(r"\sqrt{x + b}", sqrt(_Add(x, b))),
(r"\sqrt[3]{\sin x}", root(sin(x), 3)),
(r"\sqrt[y]{\sin x}", root(sin(x), y)),
(r"\sqrt[\theta]{\sin x}", root(sin(x), theta)),
(r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))),
(r"\overline{z}", _Conjugate(z)),
(r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))),
(r"\overline{x + y}", _Conjugate(_Add(x, y))),
(r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)),
(r"x < y", StrictLessThan(x, y)),
(r"x \leq y", LessThan(x, y)),
(r"x > y", StrictGreaterThan(x, y)),
(r"x \geq y", GreaterThan(x, y)),
(r"\mathit{x}", Symbol('x')),
(r"\mathit{test}", Symbol('test')),
(r"\mathit{TEST}", Symbol('TEST')),
(r"\mathit{HELLO world}", Symbol('HELLO world')),
(r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
(r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
(r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
(r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
(r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
(r"\sum_{n = 0}^{\infty} \frac{1}{n!}",
Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
(r"\prod_{a = b}^{c} x", Product(x, (a, b, c))),
(r"\prod_{a = b}^c x", Product(x, (a, b, c))),
(r"\prod^{c}_{a = b} x", Product(x, (a, b, c))),
(r"\prod^c_{a = b} x", Product(x, (a, b, c))),
(r"\exp x", _exp(x)),
(r"\exp(x)", _exp(x)),
(r"\ln x", _log(x, E)),
(r"\ln xy", _log(x*y, E)),
(r"\log x", _log(x, 10)),
(r"\log xy", _log(x*y, 10)),
(r"\log_{2} x", _log(x, 2)),
(r"\log_{a} x", _log(x, a)),
(r"\log_{11} x", _log(x, 11)),
(r"\log_{a^2} x", _log(x, _Pow(a, 2))),
(r"[x]", x),
(r"[a + b]", _Add(a, b)),
(r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)),
(r"\binom{n}{k}", _binomial(n, k)),
(r"\tbinom{n}{k}", _binomial(n, k)),
(r"\dbinom{n}{k}", _binomial(n, k)),
(r"\binom{n}{0}", _binomial(n, 0)),
(r"a \, b", _Mul(a, b)),
(r"a \thinspace b", _Mul(a, b)),
(r"a \: b", _Mul(a, b)),
(r"a \medspace b", _Mul(a, b)),
(r"a \; b", _Mul(a, b)),
(r"a \thickspace b", _Mul(a, b)),
(r"a \quad b", _Mul(a, b)),
(r"a \qquad b", _Mul(a, b)),
(r"a \! b", _Mul(a, b)),
(r"a \negthinspace b", _Mul(a, b)),
(r"a \negmedspace b", _Mul(a, b)),
(r"a \negthickspace b", _Mul(a, b)),
(r"\int x \, dx", Integral(x, x)),
(r"\log_2 x", _log(x, 2)),
(r"\log_a x", _log(x, a)),
(r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))),
]
def test_parseable():
from sympy.parsing.latex import parse_latex
for latex_str, sympy_expr in GOOD_PAIRS:
assert parse_latex(latex_str) == sympy_expr, latex_str
# These bad LaTeX strings should raise a LaTeXParsingError when parsed
BAD_STRINGS = [
r"(",
r")",
r"\frac{d}{dx}",
r"(\frac{d}{dx})",
r"\sqrt{}",
r"\sqrt",
r"\overline{}",
r"\overline",
r"{",
r"}",
r"\mathit{x + y}",
r"\mathit{21}",
r"\frac{2}{}",
r"\frac{}{2}",
r"\int",
r"!",
r"!0",
r"_",
r"^",
r"|",
r"||x|",
r"()",
r"((((((((((((((((()))))))))))))))))",
r"-",
r"\frac{d}{dx} + \frac{d}{dt}",
r"f(x,,y)",
r"f(x,y,",
r"\sin^x",
r"\cos^2",
r"@",
r"#",
r"$",
r"%",
r"&",
r"*",
r"" "\\",
r"~",
r"\frac{(2 + x}{1 - x)}",
]
def test_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
# At time of migration from latex2sympy, should fail but doesn't
FAILING_BAD_STRINGS = [
r"\cos 1 \cos",
r"f(,",
r"f()",
r"a \div \div b",
r"a \cdot \cdot b",
r"a // b",
r"a +",
r"1.1.1",
r"1 +",
r"a / b /",
]
@XFAIL
def test_failing_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in FAILING_BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
|
c8861d7e76875fd67ddfe0a67fac7d0bb7b2b10fb2dff954fba08645737858bf | from sympy.parsing.sym_expr import SymPyExpression
from sympy.testing.pytest import raises, XFAIL
from sympy.external import import_module
cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
if cin:
from sympy.codegen.ast import (Variable, String, Return,
FunctionDefinition, Integer, Float, Declaration, CodeBlock,
FunctionPrototype, FunctionCall, NoneToken, Assignment, Type,
IntBaseType, SignedIntType, UnsignedIntType, FloatType,
AddAugmentedAssignment, SubAugmentedAssignment,
MulAugmentedAssignment, DivAugmentedAssignment,
ModAugmentedAssignment, While)
from sympy.codegen.cnodes import (PreDecrement, PostDecrement,
PreIncrement, PostIncrement)
from sympy.core import (Add, Mul, Mod, Pow, Rational,
StrictLessThan, LessThan, StrictGreaterThan, GreaterThan,
Equality, Unequality)
from sympy.logic.boolalg import And, Not, Or
from sympy.core.symbol import Symbol
from sympy.logic.boolalg import (false, true)
import os
def test_variable():
c_src1 = (
'int a;' + '\n' +
'int b;' + '\n'
)
c_src2 = (
'float a;' + '\n'
+ 'float b;' + '\n'
)
c_src3 = (
'int a;' + '\n' +
'float b;' + '\n' +
'int c;'
)
c_src4 = (
'int x = 1, y = 6.78;' + '\n' +
'float p = 2, q = 9.67;'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
assert res1[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
)
assert res1[1] == Declaration(
Variable(
Symbol('b'),
type=IntBaseType(String('intc'))
)
)
assert res2[0] == Declaration(
Variable(
Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
)
assert res2[1] == Declaration(
Variable(
Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
)
assert res3[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
)
assert res3[1] == Declaration(
Variable(
Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
)
assert res3[2] == Declaration(
Variable(
Symbol('c'),
type=IntBaseType(String('intc'))
)
)
assert res4[0] == Declaration(
Variable(
Symbol('x'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res4[1] == Declaration(
Variable(
Symbol('y'),
type=IntBaseType(String('intc')),
value=Integer(6)
)
)
assert res4[2] == Declaration(
Variable(
Symbol('p'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.0', precision=53)
)
)
assert res4[3] == Declaration(
Variable(
Symbol('q'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('9.67', precision=53)
)
)
@XFAIL
def test_int():
c_src1 = 'int a = 1;'
c_src2 = (
'int a = 1;' + '\n' +
'int b = 2;' + '\n'
)
c_src3 = 'int a = 2.345, b = 5.67;'
c_src4 = 'int p = 6, q = 23.45;'
c_src5 = "int x = '0', y = 'a';"
c_src6 = "int r = true, s = false;"
# cin.TypeKind.UCHAR
c_src_type1 = (
"signed char a = 1, b = 5.1;"
)
# cin.TypeKind.SHORT
c_src_type2 = (
"short a = 1, b = 5.1;"
"signed short c = 1, d = 5.1;"
"short int e = 1, f = 5.1;"
"signed short int g = 1, h = 5.1;"
)
# cin.TypeKind.INT
c_src_type3 = (
"signed int a = 1, b = 5.1;"
"int c = 1, d = 5.1;"
)
# cin.TypeKind.LONG
c_src_type4 = (
"long a = 1, b = 5.1;"
"long int c = 1, d = 5.1;"
)
# cin.TypeKind.UCHAR
c_src_type5 = "unsigned char a = 1, b = 5.1;"
# cin.TypeKind.USHORT
c_src_type6 = (
"unsigned short a = 1, b = 5.1;"
"unsigned short int c = 1, d = 5.1;"
)
# cin.TypeKind.UINT
c_src_type7 = "unsigned int a = 1, b = 5.1;"
# cin.TypeKind.ULONG
c_src_type8 = (
"unsigned long a = 1, b = 5.1;"
"unsigned long int c = 1, d = 5.1;"
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
res6 = SymPyExpression(c_src6, 'c').return_expr()
res_type1 = SymPyExpression(c_src_type1, 'c').return_expr()
res_type2 = SymPyExpression(c_src_type2, 'c').return_expr()
res_type3 = SymPyExpression(c_src_type3, 'c').return_expr()
res_type4 = SymPyExpression(c_src_type4, 'c').return_expr()
res_type5 = SymPyExpression(c_src_type5, 'c').return_expr()
res_type6 = SymPyExpression(c_src_type6, 'c').return_expr()
res_type7 = SymPyExpression(c_src_type7, 'c').return_expr()
res_type8 = SymPyExpression(c_src_type8, 'c').return_expr()
assert res1[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res2[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res2[1] == Declaration(
Variable(
Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res3[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res3[1] == Declaration(
Variable(
Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(5)
)
)
assert res4[0] == Declaration(
Variable(
Symbol('p'),
type=IntBaseType(String('intc')),
value=Integer(6)
)
)
assert res4[1] == Declaration(
Variable(
Symbol('q'),
type=IntBaseType(String('intc')),
value=Integer(23)
)
)
assert res5[0] == Declaration(
Variable(
Symbol('x'),
type=IntBaseType(String('intc')),
value=Integer(48)
)
)
assert res5[1] == Declaration(
Variable(
Symbol('y'),
type=IntBaseType(String('intc')),
value=Integer(97)
)
)
assert res6[0] == Declaration(
Variable(
Symbol('r'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res6[1] == Declaration(
Variable(
Symbol('s'),
type=IntBaseType(String('intc')),
value=Integer(0)
)
)
assert res_type1[0] == Declaration(
Variable(
Symbol('a'),
type=SignedIntType(
String('int8'),
nbits=Integer(8)
),
value=Integer(1)
)
)
assert res_type1[1] == Declaration(
Variable(
Symbol('b'),
type=SignedIntType(
String('int8'),
nbits=Integer(8)
),
value=Integer(5)
)
)
assert res_type2[0] == Declaration(
Variable(
Symbol('a'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type2[1] == Declaration(
Variable(
Symbol('b'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type2[2] == Declaration(
Variable(Symbol('c'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type2[3] == Declaration(
Variable(
Symbol('d'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type2[4] == Declaration(
Variable(
Symbol('e'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type2[5] == Declaration(
Variable(
Symbol('f'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type2[6] == Declaration(
Variable(
Symbol('g'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type2[7] == Declaration(
Variable(
Symbol('h'),
type=SignedIntType(
String('int16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type3[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res_type3[1] == Declaration(
Variable(
Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(5)
)
)
assert res_type3[2] == Declaration(
Variable(
Symbol('c'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res_type3[3] == Declaration(
Variable(
Symbol('d'),
type=IntBaseType(String('intc')),
value=Integer(5)
)
)
assert res_type4[0] == Declaration(
Variable(
Symbol('a'),
type=SignedIntType(
String('int64'),
nbits=Integer(64)
),
value=Integer(1)
)
)
assert res_type4[1] == Declaration(
Variable(
Symbol('b'),
type=SignedIntType(
String('int64'),
nbits=Integer(64)
),
value=Integer(5)
)
)
assert res_type4[2] == Declaration(
Variable(
Symbol('c'),
type=SignedIntType(
String('int64'),
nbits=Integer(64)
),
value=Integer(1)
)
)
assert res_type4[3] == Declaration(
Variable(
Symbol('d'),
type=SignedIntType(
String('int64'),
nbits=Integer(64)
),
value=Integer(5)
)
)
assert res_type5[0] == Declaration(
Variable(
Symbol('a'),
type=UnsignedIntType(
String('uint8'),
nbits=Integer(8)
),
value=Integer(1)
)
)
assert res_type5[1] == Declaration(
Variable(
Symbol('b'),
type=UnsignedIntType(
String('uint8'),
nbits=Integer(8)
),
value=Integer(5)
)
)
assert res_type6[0] == Declaration(
Variable(
Symbol('a'),
type=UnsignedIntType(
String('uint16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type6[1] == Declaration(
Variable(
Symbol('b'),
type=UnsignedIntType(
String('uint16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type6[2] == Declaration(
Variable(
Symbol('c'),
type=UnsignedIntType(
String('uint16'),
nbits=Integer(16)
),
value=Integer(1)
)
)
assert res_type6[3] == Declaration(
Variable(
Symbol('d'),
type=UnsignedIntType(
String('uint16'),
nbits=Integer(16)
),
value=Integer(5)
)
)
assert res_type7[0] == Declaration(
Variable(
Symbol('a'),
type=UnsignedIntType(
String('uint32'),
nbits=Integer(32)
),
value=Integer(1)
)
)
assert res_type7[1] == Declaration(
Variable(
Symbol('b'),
type=UnsignedIntType(
String('uint32'),
nbits=Integer(32)
),
value=Integer(5)
)
)
assert res_type8[0] == Declaration(
Variable(
Symbol('a'),
type=UnsignedIntType(
String('uint64'),
nbits=Integer(64)
),
value=Integer(1)
)
)
assert res_type8[1] == Declaration(
Variable(
Symbol('b'),
type=UnsignedIntType(
String('uint64'),
nbits=Integer(64)
),
value=Integer(5)
)
)
assert res_type8[2] == Declaration(
Variable(
Symbol('c'),
type=UnsignedIntType(
String('uint64'),
nbits=Integer(64)
),
value=Integer(1)
)
)
assert res_type8[3] == Declaration(
Variable(
Symbol('d'),
type=UnsignedIntType(
String('uint64'),
nbits=Integer(64)
),
value=Integer(5)
)
)
@XFAIL
def test_float():
c_src1 = 'float a = 1.0;'
c_src2 = (
'float a = 1.25;' + '\n' +
'float b = 2.39;' + '\n'
)
c_src3 = 'float x = 1, y = 2;'
c_src4 = 'float p = 5, e = 7.89;'
c_src5 = 'float r = true, s = false;'
# cin.TypeKind.FLOAT
c_src_type1 = 'float x = 1, y = 2.5;'
# cin.TypeKind.DOUBLE
c_src_type2 = 'double x = 1, y = 2.5;'
# cin.TypeKind.LONGDOUBLE
c_src_type3 = 'long double x = 1, y = 2.5;'
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
res_type1 = SymPyExpression(c_src_type1, 'c').return_expr()
res_type2 = SymPyExpression(c_src_type2, 'c').return_expr()
res_type3 = SymPyExpression(c_src_type3, 'c').return_expr()
assert res1[0] == Declaration(
Variable(
Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.0', precision=53)
)
)
assert res2[0] == Declaration(
Variable(
Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.25', precision=53)
)
)
assert res2[1] == Declaration(
Variable(
Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.3900000000000001', precision=53)
)
)
assert res3[0] == Declaration(
Variable(
Symbol('x'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.0', precision=53)
)
)
assert res3[1] == Declaration(
Variable(
Symbol('y'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.0', precision=53)
)
)
assert res4[0] == Declaration(
Variable(
Symbol('p'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('5.0', precision=53)
)
)
assert res4[1] == Declaration(
Variable(
Symbol('e'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('7.89', precision=53)
)
)
assert res5[0] == Declaration(
Variable(
Symbol('r'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.0', precision=53)
)
)
assert res5[1] == Declaration(
Variable(
Symbol('s'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('0.0', precision=53)
)
)
assert res_type1[0] == Declaration(
Variable(
Symbol('x'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.0', precision=53)
)
)
assert res_type1[1] == Declaration(
Variable(
Symbol('y'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.5', precision=53)
)
)
assert res_type2[0] == Declaration(
Variable(
Symbol('x'),
type=FloatType(
String('float64'),
nbits=Integer(64),
nmant=Integer(52),
nexp=Integer(11)
),
value=Float('1.0', precision=53)
)
)
assert res_type2[1] == Declaration(
Variable(
Symbol('y'),
type=FloatType(
String('float64'),
nbits=Integer(64),
nmant=Integer(52),
nexp=Integer(11)
),
value=Float('2.5', precision=53)
)
)
assert res_type3[0] == Declaration(
Variable(
Symbol('x'),
type=FloatType(
String('float80'),
nbits=Integer(80),
nmant=Integer(63),
nexp=Integer(15)
),
value=Float('1.0', precision=53)
)
)
assert res_type3[1] == Declaration(
Variable(
Symbol('y'),
type=FloatType(
String('float80'),
nbits=Integer(80),
nmant=Integer(63),
nexp=Integer(15)
),
value=Float('2.5', precision=53)
)
)
@XFAIL
def test_bool():
c_src1 = (
'bool a = true, b = false;'
)
c_src2 = (
'bool a = 1, b = 0;'
)
c_src3 = (
'bool a = 10, b = 20;'
)
c_src4 = (
'bool a = 19.1, b = 9.0, c = 0.0;'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
assert res1[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=true
)
)
assert res1[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=false
)
)
assert res2[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=true)
)
assert res2[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=false
)
)
assert res3[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=true
)
)
assert res3[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=true
)
)
assert res4[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=true)
)
assert res4[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=true
)
)
assert res4[2] == Declaration(
Variable(Symbol('c'),
type=Type(String('bool')),
value=false
)
)
def test_function():
c_src1 = (
'void fun1()' + '\n' +
'{' + '\n' +
'int a;' + '\n' +
'}'
)
c_src2 = (
'int fun2()' + '\n' +
'{'+ '\n' +
'int a;' + '\n' +
'return a;' + '\n' +
'}'
)
c_src3 = (
'float fun3()' + '\n' +
'{' + '\n' +
'float b;' + '\n' +
'return b;' + '\n' +
'}'
)
c_src4 = (
'float fun4()' + '\n' +
'{}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
assert res1[0] == FunctionDefinition(
NoneToken(),
name=String('fun1'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
)
)
)
assert res2[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun2'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Return('a')
)
)
assert res3[0] == FunctionDefinition(
FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
name=String('fun3'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Return('b')
)
)
assert res4[0] == FunctionPrototype(
FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
name=String('fun4'),
parameters=()
)
def test_parameters():
c_src1 = (
'void fun1( int a)' + '\n' +
'{' + '\n' +
'int i;' + '\n' +
'}'
)
c_src2 = (
'int fun2(float x, float y)' + '\n' +
'{'+ '\n' +
'int a;' + '\n' +
'return a;' + '\n' +
'}'
)
c_src3 = (
'float fun3(int p, float q, int r)' + '\n' +
'{' + '\n' +
'float b;' + '\n' +
'return b;' + '\n' +
'}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
assert res1[0] == FunctionDefinition(
NoneToken(),
name=String('fun1'),
parameters=(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
),
),
body=CodeBlock(
Declaration(
Variable(
Symbol('i'),
type=IntBaseType(String('intc'))
)
)
)
)
assert res2[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun2'),
parameters=(
Variable(
Symbol('x'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
),
Variable(
Symbol('y'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
body=CodeBlock(
Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Return('a')
)
)
assert res3[0] == FunctionDefinition(
FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
name=String('fun3'),
parameters=(
Variable(
Symbol('p'),
type=IntBaseType(String('intc'))
),
Variable(
Symbol('q'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
),
Variable(
Symbol('r'),
type=IntBaseType(String('intc'))
)
),
body=CodeBlock(
Declaration(
Variable(
Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Return('b')
)
)
def test_function_call():
c_src1 = (
'int fun1(int x)' + '\n' +
'{' + '\n' +
'return x;' + '\n' +
'}' + '\n' +
'void caller()' + '\n' +
'{' + '\n' +
'int x = fun1(2);' + '\n' +
'}'
)
c_src2 = (
'int fun2(int a, int b, int c)' + '\n' +
'{' + '\n' +
'return a;' + '\n' +
'}' + '\n' +
'void caller()' + '\n' +
'{' + '\n' +
'int y = fun2(2, 3, 4);' + '\n' +
'}'
)
c_src3 = (
'int fun3(int a, int b, int c)' + '\n' +
'{' + '\n' +
'return b;' + '\n' +
'}' + '\n' +
'void caller()' + '\n' +
'{' + '\n' +
'int p;' + '\n' +
'int q;' + '\n' +
'int r;' + '\n' +
'int z = fun3(p, q, r);' + '\n' +
'}'
)
c_src4 = (
'int fun4(float a, float b, int c)' + '\n' +
'{' + '\n' +
'return c;' + '\n' +
'}' + '\n' +
'void caller()' + '\n' +
'{' + '\n' +
'float x;' + '\n' +
'float y;' + '\n' +
'int z;' + '\n' +
'int i = fun4(x, y, z)' + '\n' +
'}'
)
c_src5 = (
'int fun()' + '\n' +
'{' + '\n' +
'return 1;' + '\n' +
'}' + '\n' +
'void caller()' + '\n' +
'{' + '\n' +
'int a = fun()' + '\n' +
'}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
assert res1[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun1'),
parameters=(Variable(Symbol('x'),
type=IntBaseType(String('intc'))
),
),
body=CodeBlock(
Return('x')
)
)
assert res1[1] == FunctionDefinition(
NoneToken(),
name=String('caller'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('x'),
value=FunctionCall(String('fun1'),
function_args=(
Integer(2),
)
)
)
)
)
)
assert res2[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun2'),
parameters=(Variable(Symbol('a'),
type=IntBaseType(String('intc'))
),
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
),
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
body=CodeBlock(
Return('a')
)
)
assert res2[1] == FunctionDefinition(
NoneToken(),
name=String('caller'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('y'),
value=FunctionCall(
String('fun2'),
function_args=(
Integer(2),
Integer(3),
Integer(4)
)
)
)
)
)
)
assert res3[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun3'),
parameters=(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
),
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
),
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
body=CodeBlock(
Return('b')
)
)
assert res3[1] == FunctionDefinition(
NoneToken(),
name=String('caller'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('p'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('q'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('r'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('z'),
value=FunctionCall(
String('fun3'),
function_args=(
Symbol('p'),
Symbol('q'),
Symbol('r')
)
)
)
)
)
)
assert res4[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun4'),
parameters=(Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
),
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
),
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
body=CodeBlock(
Return('c')
)
)
assert res4[1] == FunctionDefinition(
NoneToken(),
name=String('caller'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('x'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Declaration(
Variable(Symbol('y'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Declaration(
Variable(Symbol('z'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('i'),
value=FunctionCall(String('fun4'),
function_args=(
Symbol('x'),
Symbol('y'),
Symbol('z')
)
)
)
)
)
)
assert res5[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('fun'),
parameters=(),
body=CodeBlock(
Return('')
)
)
assert res5[1] == FunctionDefinition(
NoneToken(),
name=String('caller'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
value=FunctionCall(String('fun'),
function_args=()
)
)
)
)
)
def test_parse():
c_src1 = (
'int a;' + '\n' +
'int b;' + '\n'
)
c_src2 = (
'void fun1()' + '\n' +
'{' + '\n' +
'int a;' + '\n' +
'}'
)
f1 = open('..a.h', 'w')
f2 = open('..b.h', 'w')
f1.write(c_src1)
f2. write(c_src2)
f1.close()
f2.close()
res1 = SymPyExpression('..a.h', 'c').return_expr()
res2 = SymPyExpression('..b.h', 'c').return_expr()
os.remove('..a.h')
os.remove('..b.h')
assert res1[0] == Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
)
assert res1[1] == Declaration(
Variable(
Symbol('b'),
type=IntBaseType(String('intc'))
)
)
assert res2[0] == FunctionDefinition(
NoneToken(),
name=String('fun1'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc'))
)
)
)
)
def test_binary_operators():
c_src1 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = 1;' + '\n' +
'}'
)
c_src2 = (
'void func()'+
'{' + '\n' +
'int a = 0;' + '\n' +
'a = a + 1;' + '\n' +
'a = 3*a - 10;' + '\n' +
'}'
)
c_src3 = (
'void func()'+
'{' + '\n' +
'int a = 10;' + '\n' +
'a = 1 + a - 3 * 6;' + '\n' +
'}'
)
c_src4 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'int b;' + '\n' +
'a = 100;' + '\n' +
'b = a*a + a*a + a + 19*a + 1 + 24;' + '\n' +
'}'
)
c_src5 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'int b;' + '\n' +
'int c;' + '\n' +
'int d;' + '\n' +
'a = 1;' + '\n' +
'b = 2;' + '\n' +
'c = b;' + '\n' +
'd = ((a+b)*(a+c))*((c-d)*(a+c));' + '\n' +
'}'
)
c_src6 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'int b;' + '\n' +
'int c;' + '\n' +
'int d;' + '\n' +
'a = 1;' + '\n' +
'b = 2;' + '\n' +
'c = 3;' + '\n' +
'd = (a*a*a*a + 3*b*b + b + b + c*d);' + '\n' +
'}'
)
c_src7 = (
'void func()'+
'{' + '\n' +
'float a;' + '\n' +
'a = 1.01;' + '\n' +
'}'
)
c_src8 = (
'void func()'+
'{' + '\n' +
'float a;' + '\n' +
'a = 10.0 + 2.5;' + '\n' +
'}'
)
c_src9 = (
'void func()'+
'{' + '\n' +
'float a;' + '\n' +
'a = 10.0 / 2.5;' + '\n' +
'}'
)
c_src10 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = 100 / 4;' + '\n' +
'}'
)
c_src11 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = 20 - 100 / 4 * 5 + 10;' + '\n' +
'}'
)
c_src12 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = (20 - 100) / 4 * (5 + 10);' + '\n' +
'}'
)
c_src13 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'int b;' + '\n' +
'float c;' + '\n' +
'c = b/a;' + '\n' +
'}'
)
c_src14 = (
'void func()'+
'{' + '\n' +
'int a = 2;' + '\n' +
'int d = 5;' + '\n' +
'int n = 10;' + '\n' +
'int s;' + '\n' +
's = (a/2)*(2*a + (n-1)*d);' + '\n' +
'}'
)
c_src15 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = 1 % 2;' + '\n' +
'}'
)
c_src16 = (
'void func()'+
'{' + '\n' +
'int a = 2;' + '\n' +
'int b;' + '\n' +
'b = a % 3;' + '\n' +
'}'
)
c_src17 = (
'void func()'+
'{' + '\n' +
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int c;' + '\n' +
'c = a % b;' + '\n' +
'}'
)
c_src18 = (
'void func()'+
'{' + '\n' +
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int mod = 1000000007;' + '\n' +
'int c;' + '\n' +
'c = (a + b * (100/a)) % mod;' + '\n' +
'}'
)
c_src19 = (
'void func()'+
'{' + '\n' +
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int mod = 1000000007;' + '\n' +
'int c;' + '\n' +
'c = ((a % mod + b % mod) % mod *(' \
'a % mod - b % mod) % mod) % mod;' + '\n' +
'}'
)
c_src20 = (
'void func()'+
'{' + '\n' +
'bool a' + '\n' +
'bool b;' + '\n' +
'a = 1 == 2;' + '\n' +
'b = 1 != 2;' + '\n' +
'}'
)
c_src21 = (
'void func()'+
'{' + '\n' +
'bool a;' + '\n' +
'bool b;' + '\n' +
'bool c;' + '\n' +
'bool d;' + '\n' +
'a = 1 == 2;' + '\n' +
'b = 1 <= 2;' + '\n' +
'c = 1 > 2;' + '\n' +
'd = 1 >= 2;' + '\n' +
'}'
)
c_src22 = (
'void func()'+
'{' + '\n' +
'int a = 1;' + '\n' +
'int b = 2;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'bool c7;' + '\n' +
'bool c8;' + '\n' +
'c1 = a == 1;' + '\n' +
'c2 = b == 2;' + '\n' +
'c3 = 1 != a;' + '\n' +
'c4 = 1 != b;' + '\n' +
'c5 = a < 0;' + '\n' +
'c6 = b <= 10;' + '\n' +
'c7 = a > 0;' + '\n' +
'c8 = b >= 11;' + '\n' +
'}'
)
c_src23 = (
'void func()'+
'{' + '\n' +
'int a = 3;' + '\n' +
'int b = 4;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'c1 = a == b;' + '\n' +
'c2 = a != b;' + '\n' +
'c3 = a < b;' + '\n' +
'c4 = a <= b;' + '\n' +
'c5 = a > b;' + '\n' +
'c6 = a >= b;' + '\n' +
'}'
)
c_src24 = (
'void func()'+
'{' + '\n' +
'float a = 1.25'
'float b = 2.5;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'c1 = a == 1.25;' + '\n' +
'c2 = b == 2.54;' + '\n' +
'c3 = 1.2 != a;' + '\n' +
'c4 = 1.5 != b;' + '\n' +
'}'
)
c_src25 = (
'void func()'+
'{' + '\n' +
'float a = 1.25' + '\n' +
'float b = 2.5;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'c1 = a == b;' + '\n' +
'c2 = a != b;' + '\n' +
'c3 = a < b;' + '\n' +
'c4 = a <= b;' + '\n' +
'c5 = a > b;' + '\n' +
'c6 = a >= b;' + '\n' +
'}'
)
c_src26 = (
'void func()'+
'{' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'c1 = true == true;' + '\n' +
'c2 = true == false;' + '\n' +
'c3 = false == false;' + '\n' +
'c4 = true != true;' + '\n' +
'c5 = true != false;' + '\n' +
'c6 = false != false;' + '\n' +
'}'
)
c_src27 = (
'void func()'+
'{' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'c1 = true && true;' + '\n' +
'c2 = true && false;' + '\n' +
'c3 = false && false;' + '\n' +
'c4 = true || true;' + '\n' +
'c5 = true || false;' + '\n' +
'c6 = false || false;' + '\n' +
'}'
)
c_src28 = (
'void func()'+
'{' + '\n' +
'bool a;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'c1 = a && true;' + '\n' +
'c2 = false && a;' + '\n' +
'c3 = true || a;' + '\n' +
'c4 = a || false;' + '\n' +
'}'
)
c_src29 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'c1 = a && 1;' + '\n' +
'c2 = a && 0;' + '\n' +
'c3 = a || 1;' + '\n' +
'c4 = 0 || a;' + '\n' +
'}'
)
c_src30 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'int b;' + '\n' +
'bool c;'+ '\n' +
'bool d;'+ '\n' +
'bool c1;' + '\n' +
'bool c2;' + '\n' +
'bool c3;' + '\n' +
'bool c4;' + '\n' +
'bool c5;' + '\n' +
'bool c6;' + '\n' +
'c1 = a && b;' + '\n' +
'c2 = a && c;' + '\n' +
'c3 = c && d;' + '\n' +
'c4 = a || b;' + '\n' +
'c5 = a || c;' + '\n' +
'c6 = c || d;' + '\n' +
'}'
)
c_src_raise1 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = -1;' + '\n' +
'}'
)
c_src_raise2 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = -+1;' + '\n' +
'}'
)
c_src_raise3 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = 2*-2;' + '\n' +
'}'
)
c_src_raise4 = (
'void func()'+
'{' + '\n' +
'int a;' + '\n' +
'a = (int)2.0;' + '\n' +
'}'
)
c_src_raise5 = (
'void func()'+
'{' + '\n' +
'int a=100;' + '\n' +
'a = (a==100)?(1):(0);' + '\n' +
'}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
res6 = SymPyExpression(c_src6, 'c').return_expr()
res7 = SymPyExpression(c_src7, 'c').return_expr()
res8 = SymPyExpression(c_src8, 'c').return_expr()
res9 = SymPyExpression(c_src9, 'c').return_expr()
res10 = SymPyExpression(c_src10, 'c').return_expr()
res11 = SymPyExpression(c_src11, 'c').return_expr()
res12 = SymPyExpression(c_src12, 'c').return_expr()
res13 = SymPyExpression(c_src13, 'c').return_expr()
res14 = SymPyExpression(c_src14, 'c').return_expr()
res15 = SymPyExpression(c_src15, 'c').return_expr()
res16 = SymPyExpression(c_src16, 'c').return_expr()
res17 = SymPyExpression(c_src17, 'c').return_expr()
res18 = SymPyExpression(c_src18, 'c').return_expr()
res19 = SymPyExpression(c_src19, 'c').return_expr()
res20 = SymPyExpression(c_src20, 'c').return_expr()
res21 = SymPyExpression(c_src21, 'c').return_expr()
res22 = SymPyExpression(c_src22, 'c').return_expr()
res23 = SymPyExpression(c_src23, 'c').return_expr()
res24 = SymPyExpression(c_src24, 'c').return_expr()
res25 = SymPyExpression(c_src25, 'c').return_expr()
res26 = SymPyExpression(c_src26, 'c').return_expr()
res27 = SymPyExpression(c_src27, 'c').return_expr()
res28 = SymPyExpression(c_src28, 'c').return_expr()
res29 = SymPyExpression(c_src29, 'c').return_expr()
res30 = SymPyExpression(c_src30, 'c').return_expr()
assert res1[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Assignment(Variable(Symbol('a')), Integer(1))
)
)
assert res2[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(0))),
Assignment(
Variable(Symbol('a')),
Add(Symbol('a'),
Integer(1))
),
Assignment(Variable(Symbol('a')),
Add(
Mul(
Integer(3),
Symbol('a')),
Integer(-10)
)
)
)
)
assert res3[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
),
Assignment(
Variable(Symbol('a')),
Add(
Symbol('a'),
Integer(-17)
)
)
)
)
assert res4[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(100)),
Assignment(
Variable(Symbol('b')),
Add(
Mul(
Integer(2),
Pow(
Symbol('a'),
Integer(2))
),
Mul(
Integer(20),
Symbol('a')),
Integer(25)
)
)
)
)
assert res5[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(1)),
Assignment(
Variable(Symbol('b')),
Integer(2)
),
Assignment(
Variable(Symbol('c')),
Symbol('b')),
Assignment(
Variable(Symbol('d')),
Mul(
Add(
Symbol('a'),
Symbol('b')),
Pow(
Add(
Symbol('a'),
Symbol('c')
),
Integer(2)
),
Add(
Symbol('c'),
Mul(
Integer(-1),
Symbol('d')
)
)
)
)
)
)
assert res6[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(1)
),
Assignment(
Variable(Symbol('b')),
Integer(2)
),
Assignment(
Variable(Symbol('c')),
Integer(3)
),
Assignment(
Variable(Symbol('d')),
Add(
Pow(
Symbol('a'),
Integer(4)
),
Mul(
Integer(3),
Pow(
Symbol('b'),
Integer(2)
)
),
Mul(
Integer(2),
Symbol('b')
),
Mul(
Symbol('c'),
Symbol('d')
)
)
)
)
)
assert res7[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Assignment(
Variable(Symbol('a')),
Float('1.01', precision=53)
)
)
)
assert res8[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Assignment(
Variable(Symbol('a')),
Float('12.5', precision=53)
)
)
)
assert res9[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Assignment(
Variable(Symbol('a')),
Float('4.0', precision=53)
)
)
)
assert res10[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(25)
)
)
)
assert res11[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(-95)
)
)
)
assert res12[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(-300)
)
)
)
assert res13[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('c'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Assignment(
Variable(Symbol('c')),
Mul(
Pow(
Symbol('a'),
Integer(-1)
),
Symbol('b')
)
)
)
)
assert res14[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
),
Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc')),
value=Integer(5)
)
),
Declaration(
Variable(Symbol('n'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
),
Declaration(
Variable(Symbol('s'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('s')),
Mul(
Rational(1, 2),
Symbol('a'),
Add(
Mul(
Integer(2),
Symbol('a')
),
Mul(
Symbol('d'),
Add(
Symbol('n'),
Integer(-1)
)
)
)
)
)
)
)
assert res15[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('a')),
Integer(1)
)
)
)
assert res16[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('b')),
Mod(
Symbol('a'),
Integer(3)
)
)
)
)
assert res17[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('c')),
Mod(
Symbol('a'),
Symbol('b')
)
)
)
)
assert res18[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
),
Declaration(
Variable(Symbol('mod'),
type=IntBaseType(String('intc')),
value=Integer(1000000007)
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('c')),
Mod(
Add(
Symbol('a'),
Mul(
Integer(100),
Pow(
Symbol('a'),
Integer(-1)
),
Symbol('b')
)
),
Symbol('mod')
)
)
)
)
assert res19[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
),
Declaration(
Variable(Symbol('mod'),
type=IntBaseType(String('intc')),
value=Integer(1000000007)
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc'))
)
),
Assignment(
Variable(Symbol('c')),
Mod(
Mul(
Add(
Symbol('a'),
Mul(Integer(-1),
Symbol('b')
)
),
Add(
Symbol('a'),
Symbol('b')
)
),
Symbol('mod')
)
)
)
)
assert res20[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('b'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('a')),
false
),
Assignment(
Variable(Symbol('b')),
true
)
)
)
assert res21[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('b'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('d'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('a')),
false
),
Assignment(
Variable(Symbol('b')),
true
),
Assignment(
Variable(Symbol('c')),
false
),
Assignment(
Variable(Symbol('d')),
false
)
)
)
assert res22[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c7'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c8'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Equality(
Symbol('a'),
Integer(1)
)
),
Assignment(
Variable(Symbol('c2')),
Equality(
Symbol('b'),
Integer(2)
)
),
Assignment(
Variable(Symbol('c3')),
Unequality(
Integer(1),
Symbol('a')
)
),
Assignment(
Variable(Symbol('c4')),
Unequality(
Integer(1),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c5')),
StrictLessThan(
Symbol('a'),
Integer(0)
)
),
Assignment(
Variable(Symbol('c6')),
LessThan(
Symbol('b'),
Integer(10)
)
),
Assignment(
Variable(Symbol('c7')),
StrictGreaterThan(
Symbol('a'),
Integer(0)
)
),
Assignment(
Variable(Symbol('c8')),
GreaterThan(
Symbol('b'),
Integer(11)
)
)
)
)
assert res23[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(4)
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Equality(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c2')),
Unequality(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c3')),
StrictLessThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c4')),
LessThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c5')),
StrictGreaterThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c6')),
GreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
)
assert res24[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
)
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Equality(
Symbol('a'),
Float('1.25', precision=53)
)
),
Assignment(
Variable(Symbol('c3')),
Unequality(
Float('1.2', precision=53),
Symbol('a')
)
)
)
)
assert res25[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.25', precision=53)
)
),
Declaration(
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.5', precision=53)
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')
)
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Equality(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c2')),
Unequality(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c3')),
StrictLessThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c4')),
LessThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c5')),
StrictGreaterThan(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c6')),
GreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
)
assert res26[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(), body=CodeBlock(
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
true
),
Assignment(
Variable(Symbol('c2')),
false
),
Assignment(
Variable(Symbol('c3')),
true
),
Assignment(
Variable(Symbol('c4')),
false
),
Assignment(
Variable(Symbol('c5')),
true
),
Assignment(
Variable(Symbol('c6')),
false
)
)
)
assert res27[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
true
),
Assignment(
Variable(Symbol('c2')),
false
),
Assignment(
Variable(Symbol('c3')),
false
),
Assignment(
Variable(Symbol('c4')),
true
),
Assignment(
Variable(Symbol('c5')),
true
),
Assignment(
Variable(Symbol('c6')),
false)
)
)
assert res28[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Symbol('a')
),
Assignment(
Variable(Symbol('c2')),
false
),
Assignment(
Variable(Symbol('c3')),
true
),
Assignment(
Variable(Symbol('c4')),
Symbol('a')
)
)
)
assert res29[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
Symbol('a')
),
Assignment(
Variable(Symbol('c2')),
false
),
Assignment(
Variable(Symbol('c3')),
true
),
Assignment(
Variable(Symbol('c4')),
Symbol('a')
)
)
)
assert res30[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc'))
)
),
Declaration(
Variable(Symbol('c'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('d'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c1'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c2'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c3'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c4'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c5'),
type=Type(String('bool'))
)
),
Declaration(
Variable(Symbol('c6'),
type=Type(String('bool'))
)
),
Assignment(
Variable(Symbol('c1')),
And(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c2')),
And(
Symbol('a'),
Symbol('c')
)
),
Assignment(
Variable(Symbol('c3')),
And(
Symbol('c'),
Symbol('d')
)
),
Assignment(
Variable(Symbol('c4')),
Or(
Symbol('a'),
Symbol('b')
)
),
Assignment(
Variable(Symbol('c5')),
Or(
Symbol('a'),
Symbol('c')
)
),
Assignment(
Variable(Symbol('c6')),
Or(
Symbol('c'),
Symbol('d')
)
)
)
)
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise3, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise4, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise5, 'c'))
@XFAIL
def test_var_decl():
c_src1 = (
'int b = 100;' + '\n' +
'int a = b;' + '\n'
)
c_src2 = (
'int a = 1;' + '\n' +
'int b = a + 1;' + '\n'
)
c_src3 = (
'float a = 10.0 + 2.5;' + '\n' +
'float b = a * 20.0;' + '\n'
)
c_src4 = (
'int a = 1 + 100 - 3 * 6;' + '\n'
)
c_src5 = (
'int a = (((1 + 100) * 12) - 3) * (6 - 10);' + '\n'
)
c_src6 = (
'int b = 2;' + '\n' +
'int c = 3;' + '\n' +
'int a = b + c * 4;' + '\n'
)
c_src7 = (
'int b = 1;' + '\n' +
'int c = b + 2;' + '\n' +
'int a = 10 * b * b * c;' + '\n'
)
c_src8 = (
'void func()'+
'{' + '\n' +
'int a = 1;' + '\n' +
'int b = 2;' + '\n' +
'int temp = a;' + '\n' +
'a = b;' + '\n' +
'b = temp;' + '\n' +
'}'
)
c_src9 = (
'int a = 1;' + '\n' +
'int b = 2;' + '\n' +
'int c = a;' + '\n' +
'int d = a + b + c;' + '\n' +
'int e = a*a*a + 3*a*a*b + 3*a*b*b + b*b*b;' + '\n'
'int f = (a + b + c) * (a + b - c);' + '\n' +
'int g = (a + b + c + d)*(a + b + c + d)*(a * (b - c));'
+ '\n'
)
c_src10 = (
'float a = 10.0;' + '\n' +
'float b = 2.5;' + '\n' +
'float c = a*a + 2*a*b + b*b;' + '\n'
)
c_src11 = (
'float a = 10.0 / 2.5;' + '\n'
)
c_src12 = (
'int a = 100 / 4;' + '\n'
)
c_src13 = (
'int a = 20 - 100 / 4 * 5 + 10;' + '\n'
)
c_src14 = (
'int a = (20 - 100) / 4 * (5 + 10);' + '\n'
)
c_src15 = (
'int a = 4;' + '\n' +
'int b = 2;' + '\n' +
'float c = b/a;' + '\n'
)
c_src16 = (
'int a = 2;' + '\n' +
'int d = 5;' + '\n' +
'int n = 10;' + '\n' +
'int s = (a/2)*(2*a + (n-1)*d);' + '\n'
)
c_src17 = (
'int a = 1 % 2;' + '\n'
)
c_src18 = (
'int a = 2;' + '\n' +
'int b = a % 3;' + '\n'
)
c_src19 = (
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int c = a % b;' + '\n'
)
c_src20 = (
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int mod = 1000000007;' + '\n' +
'int c = (a + b * (100/a)) % mod;' + '\n'
)
c_src21 = (
'int a = 100;' + '\n' +
'int b = 3;' + '\n' +
'int mod = 1000000007;' + '\n' +
'int c = ((a % mod + b % mod) % mod *(' \
'a % mod - b % mod) % mod) % mod;' + '\n'
)
c_src22 = (
'bool a = 1 == 2, b = 1 != 2;'
)
c_src23 = (
'bool a = 1 < 2, b = 1 <= 2, c = 1 > 2, d = 1 >= 2;'
)
c_src24 = (
'int a = 1, b = 2;' + '\n' +
'bool c1 = a == 1;' + '\n' +
'bool c2 = b == 2;' + '\n' +
'bool c3 = 1 != a;' + '\n' +
'bool c4 = 1 != b;' + '\n' +
'bool c5 = a < 0;' + '\n' +
'bool c6 = b <= 10;' + '\n' +
'bool c7 = a > 0;' + '\n' +
'bool c8 = b >= 11;'
)
c_src25 = (
'int a = 3, b = 4;' + '\n' +
'bool c1 = a == b;' + '\n' +
'bool c2 = a != b;' + '\n' +
'bool c3 = a < b;' + '\n' +
'bool c4 = a <= b;' + '\n' +
'bool c5 = a > b;' + '\n' +
'bool c6 = a >= b;'
)
c_src26 = (
'float a = 1.25, b = 2.5;' + '\n' +
'bool c1 = a == 1.25;' + '\n' +
'bool c2 = b == 2.54;' + '\n' +
'bool c3 = 1.2 != a;' + '\n' +
'bool c4 = 1.5 != b;'
)
c_src27 = (
'float a = 1.25, b = 2.5;' + '\n' +
'bool c1 = a == b;' + '\n' +
'bool c2 = a != b;' + '\n' +
'bool c3 = a < b;' + '\n' +
'bool c4 = a <= b;' + '\n' +
'bool c5 = a > b;' + '\n' +
'bool c6 = a >= b;'
)
c_src28 = (
'bool c1 = true == true;' + '\n' +
'bool c2 = true == false;' + '\n' +
'bool c3 = false == false;' + '\n' +
'bool c4 = true != true;' + '\n' +
'bool c5 = true != false;' + '\n' +
'bool c6 = false != false;'
)
c_src29 = (
'bool c1 = true && true;' + '\n' +
'bool c2 = true && false;' + '\n' +
'bool c3 = false && false;' + '\n' +
'bool c4 = true || true;' + '\n' +
'bool c5 = true || false;' + '\n' +
'bool c6 = false || false;'
)
c_src30 = (
'bool a = false;' + '\n' +
'bool c1 = a && true;' + '\n' +
'bool c2 = false && a;' + '\n' +
'bool c3 = true || a;' + '\n' +
'bool c4 = a || false;'
)
c_src31 = (
'int a = 1;' + '\n' +
'bool c1 = a && 1;' + '\n' +
'bool c2 = a && 0;' + '\n' +
'bool c3 = a || 1;' + '\n' +
'bool c4 = 0 || a;'
)
c_src32 = (
'int a = 1, b = 0;' + '\n' +
'bool c = false, d = true;'+ '\n' +
'bool c1 = a && b;' + '\n' +
'bool c2 = a && c;' + '\n' +
'bool c3 = c && d;' + '\n' +
'bool c4 = a || b;' + '\n' +
'bool c5 = a || c;' + '\n' +
'bool c6 = c || d;'
)
c_src_raise1 = (
"char a = 'b';"
)
c_src_raise2 = (
'int a[] = {10, 20};'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
res6 = SymPyExpression(c_src6, 'c').return_expr()
res7 = SymPyExpression(c_src7, 'c').return_expr()
res8 = SymPyExpression(c_src8, 'c').return_expr()
res9 = SymPyExpression(c_src9, 'c').return_expr()
res10 = SymPyExpression(c_src10, 'c').return_expr()
res11 = SymPyExpression(c_src11, 'c').return_expr()
res12 = SymPyExpression(c_src12, 'c').return_expr()
res13 = SymPyExpression(c_src13, 'c').return_expr()
res14 = SymPyExpression(c_src14, 'c').return_expr()
res15 = SymPyExpression(c_src15, 'c').return_expr()
res16 = SymPyExpression(c_src16, 'c').return_expr()
res17 = SymPyExpression(c_src17, 'c').return_expr()
res18 = SymPyExpression(c_src18, 'c').return_expr()
res19 = SymPyExpression(c_src19, 'c').return_expr()
res20 = SymPyExpression(c_src20, 'c').return_expr()
res21 = SymPyExpression(c_src21, 'c').return_expr()
res22 = SymPyExpression(c_src22, 'c').return_expr()
res23 = SymPyExpression(c_src23, 'c').return_expr()
res24 = SymPyExpression(c_src24, 'c').return_expr()
res25 = SymPyExpression(c_src25, 'c').return_expr()
res26 = SymPyExpression(c_src26, 'c').return_expr()
res27 = SymPyExpression(c_src27, 'c').return_expr()
res28 = SymPyExpression(c_src28, 'c').return_expr()
res29 = SymPyExpression(c_src29, 'c').return_expr()
res30 = SymPyExpression(c_src30, 'c').return_expr()
res31 = SymPyExpression(c_src31, 'c').return_expr()
res32 = SymPyExpression(c_src32, 'c').return_expr()
assert res1[0] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
)
assert res1[1] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Symbol('b')
)
)
assert res2[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res2[1] == Declaration(Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('a'),
Integer(1)
)
)
)
assert res3[0] == Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('12.5', precision=53)
)
)
assert res3[1] == Declaration(
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Mul(
Float('20.0', precision=53),
Symbol('a')
)
)
)
assert res4[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(83)
)
)
assert res5[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(-4836)
)
)
assert res6[0] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res6[1] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res6[2] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('b'),
Mul(
Integer(4),
Symbol('c')
)
)
)
)
assert res7[0] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res7[1] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('b'),
Integer(2)
)
)
)
assert res7[2] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Mul(
Integer(10),
Pow(
Symbol('b'),
Integer(2)
),
Symbol('c')
)
)
)
assert res8[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
),
Declaration(
Variable(Symbol('temp'),
type=IntBaseType(String('intc')),
value=Symbol('a')
)
),
Assignment(
Variable(Symbol('a')),
Symbol('b')
),
Assignment(
Variable(Symbol('b')),
Symbol('temp')
)
)
)
assert res9[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res9[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res9[2] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Symbol('a')
)
)
assert res9[3] == Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('a'),
Symbol('b'),
Symbol('c')
)
)
)
assert res9[4] == Declaration(
Variable(Symbol('e'),
type=IntBaseType(String('intc')),
value=Add(
Pow(
Symbol('a'),
Integer(3)
),
Mul(
Integer(3),
Pow(
Symbol('a'),
Integer(2)
),
Symbol('b')
),
Mul(
Integer(3),
Symbol('a'),
Pow(
Symbol('b'),
Integer(2)
)
),
Pow(
Symbol('b'),
Integer(3)
)
)
)
)
assert res9[5] == Declaration(
Variable(Symbol('f'),
type=IntBaseType(String('intc')),
value=Mul(
Add(
Symbol('a'),
Symbol('b'),
Mul(
Integer(-1),
Symbol('c')
)
),
Add(
Symbol('a'),
Symbol('b'),
Symbol('c')
)
)
)
)
assert res9[6] == Declaration(
Variable(Symbol('g'),
type=IntBaseType(String('intc')),
value=Mul(
Symbol('a'),
Add(
Symbol('b'),
Mul(
Integer(-1),
Symbol('c')
)
),
Pow(
Add(
Symbol('a'),
Symbol('b'),
Symbol('c'),
Symbol('d')
),
Integer(2)
)
)
)
)
assert res10[0] == Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('10.0', precision=53)
)
)
assert res10[1] == Declaration(
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.5', precision=53)
)
)
assert res10[2] == Declaration(
Variable(Symbol('c'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Add(
Pow(
Symbol('a'),
Integer(2)
),
Mul(
Integer(2),
Symbol('a'),
Symbol('b')
),
Pow(
Symbol('b'),
Integer(2)
)
)
)
)
assert res11[0] == Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('4.0', precision=53)
)
)
assert res12[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(25)
)
)
assert res13[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(-95)
)
)
assert res14[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(-300)
)
)
assert res15[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(4)
)
)
assert res15[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res15[2] == Declaration(
Variable(Symbol('c'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Mul(
Pow(
Symbol('a'),
Integer(-1)
),
Symbol('b')
)
)
)
assert res16[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res16[1] == Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc')),
value=Integer(5)
)
)
assert res16[2] == Declaration(
Variable(Symbol('n'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
)
assert res16[3] == Declaration(
Variable(Symbol('s'),
type=IntBaseType(String('intc')),
value=Mul(
Rational(1, 2),
Symbol('a'),
Add(
Mul(
Integer(2),
Symbol('a')
),
Mul(
Symbol('d'),
Add(
Symbol('n'),
Integer(-1)
)
)
)
)
)
)
assert res17[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res18[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res18[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Mod(
Symbol('a'),
Integer(3)
)
)
)
assert res19[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
)
assert res19[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res19[2] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Mod(
Symbol('a'),
Symbol('b')
)
)
)
assert res20[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
)
assert res20[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res20[2] == Declaration(
Variable(Symbol('mod'),
type=IntBaseType(String('intc')),
value=Integer(1000000007)
)
)
assert res20[3] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Mod(
Add(
Symbol('a'),
Mul(
Integer(100),
Pow(
Symbol('a'),
Integer(-1)
),
Symbol('b')
)
),
Symbol('mod')
)
)
)
assert res21[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
)
assert res21[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res21[2] == Declaration(
Variable(Symbol('mod'),
type=IntBaseType(String('intc')),
value=Integer(1000000007)
)
)
assert res21[3] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Mod(
Mul(
Add(
Symbol('a'),
Mul(
Integer(-1),
Symbol('b')
)
),
Add(
Symbol('a'),
Symbol('b')
)
),
Symbol('mod')
)
)
)
assert res22[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=false
)
)
assert res22[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=true
)
)
assert res23[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=true
)
)
assert res23[1] == Declaration(
Variable(Symbol('b'),
type=Type(String('bool')),
value=true
)
)
assert res23[2] == Declaration(
Variable(Symbol('c'),
type=Type(String('bool')),
value=false
)
)
assert res23[3] == Declaration(
Variable(Symbol('d'),
type=Type(String('bool')),
value=false
)
)
assert res24[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res24[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res24[2] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=Equality(
Symbol('a'),
Integer(1)
)
)
)
assert res24[3] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=Equality(
Symbol('b'),
Integer(2)
)
)
)
assert res24[4] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=Unequality(
Integer(1),
Symbol('a')
)
)
)
assert res24[5] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=Unequality(
Integer(1),
Symbol('b')
)
)
)
assert res24[6] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=StrictLessThan(Symbol('a'),
Integer(0)
)
)
)
assert res24[7] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=LessThan(
Symbol('b'),
Integer(10)
)
)
)
assert res24[8] == Declaration(
Variable(Symbol('c7'),
type=Type(String('bool')),
value=StrictGreaterThan(
Symbol('a'),
Integer(0)
)
)
)
assert res24[9] == Declaration(
Variable(Symbol('c8'),
type=Type(String('bool')),
value=GreaterThan(
Symbol('b'),
Integer(11)
)
)
)
assert res25[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res25[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(4)
)
)
assert res25[2] == Declaration(Variable(Symbol('c1'),
type=Type(String('bool')),
value=Equality(
Symbol('a'),
Symbol('b')
)
)
)
assert res25[3] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=Unequality(
Symbol('a'),
Symbol('b')
)
)
)
assert res25[4] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=StrictLessThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res25[5] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=LessThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res25[6] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=StrictGreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res25[7] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=GreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res26[0] == Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.25', precision=53)
)
)
assert res26[1] == Declaration(
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.5', precision=53)
)
)
assert res26[2] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=Equality(
Symbol('a'),
Float('1.25', precision=53)
)
)
)
assert res26[3] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=Equality(
Symbol('b'),
Float('2.54', precision=53)
)
)
)
assert res26[4] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=Unequality(
Float('1.2', precision=53),
Symbol('a')
)
)
)
assert res26[5] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=Unequality(
Float('1.5', precision=53),
Symbol('b')
)
)
)
assert res27[0] == Declaration(
Variable(Symbol('a'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('1.25', precision=53)
)
)
assert res27[1] == Declaration(
Variable(Symbol('b'),
type=FloatType(
String('float32'),
nbits=Integer(32),
nmant=Integer(23),
nexp=Integer(8)
),
value=Float('2.5', precision=53)
)
)
assert res27[2] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=Equality(
Symbol('a'),
Symbol('b')
)
)
)
assert res27[3] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=Unequality(
Symbol('a'),
Symbol('b')
)
)
)
assert res27[4] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=StrictLessThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res27[5] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=LessThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res27[6] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=StrictGreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res27[7] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=GreaterThan(
Symbol('a'),
Symbol('b')
)
)
)
assert res28[0] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=true
)
)
assert res28[1] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=false
)
)
assert res28[2] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=true
)
)
assert res28[3] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=false
)
)
assert res28[4] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=true
)
)
assert res28[5] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=false
)
)
assert res29[0] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=true
)
)
assert res29[1] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=false
)
)
assert res29[2] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=false
)
)
assert res29[3] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=true
)
)
assert res29[4] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=true
)
)
assert res29[5] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=false
)
)
assert res30[0] == Declaration(
Variable(Symbol('a'),
type=Type(String('bool')),
value=false
)
)
assert res30[1] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=Symbol('a')
)
)
assert res30[2] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=false
)
)
assert res30[3] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=true
)
)
assert res30[4] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=Symbol('a')
)
)
assert res31[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res31[1] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=Symbol('a')
)
)
assert res31[2] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=false
)
)
assert res31[3] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=true
)
)
assert res31[4] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=Symbol('a')
)
)
assert res32[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res32[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(0)
)
)
assert res32[2] == Declaration(
Variable(Symbol('c'),
type=Type(String('bool')),
value=false
)
)
assert res32[3] == Declaration(
Variable(Symbol('d'),
type=Type(String('bool')),
value=true
)
)
assert res32[4] == Declaration(
Variable(Symbol('c1'),
type=Type(String('bool')),
value=And(
Symbol('a'),
Symbol('b')
)
)
)
assert res32[5] == Declaration(
Variable(Symbol('c2'),
type=Type(String('bool')),
value=And(
Symbol('a'),
Symbol('c')
)
)
)
assert res32[6] == Declaration(
Variable(Symbol('c3'),
type=Type(String('bool')),
value=And(
Symbol('c'),
Symbol('d')
)
)
)
assert res32[7] == Declaration(
Variable(Symbol('c4'),
type=Type(String('bool')),
value=Or(
Symbol('a'),
Symbol('b')
)
)
)
assert res32[8] == Declaration(
Variable(Symbol('c5'),
type=Type(String('bool')),
value=Or(
Symbol('a'),
Symbol('c')
)
)
)
assert res32[9] == Declaration(
Variable(Symbol('c6'),
type=Type(String('bool')),
value=Or(
Symbol('c'),
Symbol('d')
)
)
)
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
def test_paren_expr():
c_src1 = (
'int a = (1);'
'int b = (1 + 2 * 3);'
)
c_src2 = (
'int a = 1, b = 2, c = 3;'
'int d = (a);'
'int e = (a + 1);'
'int f = (a + b * c - d / e);'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
assert res1[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res1[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(7)
)
)
assert res2[0] == Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(1)
)
)
assert res2[1] == Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(2)
)
)
assert res2[2] == Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Integer(3)
)
)
assert res2[3] == Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc')),
value=Symbol('a')
)
)
assert res2[4] == Declaration(
Variable(Symbol('e'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('a'),
Integer(1)
)
)
)
assert res2[5] == Declaration(
Variable(Symbol('f'),
type=IntBaseType(String('intc')),
value=Add(
Symbol('a'),
Mul(
Symbol('b'),
Symbol('c')
),
Mul(
Integer(-1),
Symbol('d'),
Pow(
Symbol('e'),
Integer(-1)
)
)
)
)
)
def test_unary_operators():
c_src1 = (
'void func()'+
'{' + '\n' +
'int a = 10;' + '\n' +
'int b = 20;' + '\n' +
'++a;' + '\n' +
'--b;' + '\n' +
'a++;' + '\n' +
'b--;' + '\n' +
'}'
)
c_src2 = (
'void func()'+
'{' + '\n' +
'int a = 10;' + '\n' +
'int b = -100;' + '\n' +
'int c = +19;' + '\n' +
'int d = ++a;' + '\n' +
'int e = --b;' + '\n' +
'int f = a++;' + '\n' +
'int g = b--;' + '\n' +
'bool h = !false;' + '\n' +
'bool i = !d;' + '\n' +
'bool j = !0;' + '\n' +
'bool k = !10.0;' + '\n' +
'}'
)
c_src_raise1 = (
'void func()'+
'{' + '\n' +
'int a = 10;' + '\n' +
'int b = ~a;' + '\n' +
'}'
)
c_src_raise2 = (
'void func()'+
'{' + '\n' +
'int a = 10;' + '\n' +
'int b = *&a;' + '\n' +
'}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
assert res1[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(20)
)
),
PreIncrement(Symbol('a')),
PreDecrement(Symbol('b')),
PostIncrement(Symbol('a')),
PostDecrement(Symbol('b'))
)
)
assert res2[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
),
Declaration(
Variable(Symbol('b'),
type=IntBaseType(String('intc')),
value=Integer(-100)
)
),
Declaration(
Variable(Symbol('c'),
type=IntBaseType(String('intc')),
value=Integer(19)
)
),
Declaration(
Variable(Symbol('d'),
type=IntBaseType(String('intc')),
value=PreIncrement(Symbol('a'))
)
),
Declaration(
Variable(Symbol('e'),
type=IntBaseType(String('intc')),
value=PreDecrement(Symbol('b'))
)
),
Declaration(
Variable(Symbol('f'),
type=IntBaseType(String('intc')),
value=PostIncrement(Symbol('a'))
)
),
Declaration(
Variable(Symbol('g'),
type=IntBaseType(String('intc')),
value=PostDecrement(Symbol('b'))
)
),
Declaration(
Variable(Symbol('h'),
type=Type(String('bool')),
value=true
)
),
Declaration(
Variable(Symbol('i'),
type=Type(String('bool')),
value=Not(Symbol('d'))
)
),
Declaration(
Variable(Symbol('j'),
type=Type(String('bool')),
value=true
)
),
Declaration(
Variable(Symbol('k'),
type=Type(String('bool')),
value=false
)
)
)
)
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c'))
raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c'))
def test_compound_assignment_operator():
c_src = (
'void func()'+
'{' + '\n' +
'int a = 100;' + '\n' +
'a += 10;' + '\n' +
'a -= 10;' + '\n' +
'a *= 10;' + '\n' +
'a /= 10;' + '\n' +
'a %= 10;' + '\n' +
'}'
)
res = SymPyExpression(c_src, 'c').return_expr()
assert res[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('a'),
type=IntBaseType(String('intc')),
value=Integer(100)
)
),
AddAugmentedAssignment(
Variable(Symbol('a')),
Integer(10)
),
SubAugmentedAssignment(
Variable(Symbol('a')),
Integer(10)
),
MulAugmentedAssignment(
Variable(Symbol('a')),
Integer(10)
),
DivAugmentedAssignment(
Variable(Symbol('a')),
Integer(10)
),
ModAugmentedAssignment(
Variable(Symbol('a')),
Integer(10)
)
)
)
def test_while_stmt():
c_src1 = (
'void func()'+
'{' + '\n' +
'int i = 0;' + '\n' +
'while(i < 10)' + '\n' +
'{' + '\n' +
'i++;' + '\n' +
'}'
'}'
)
c_src2 = (
'void func()'+
'{' + '\n' +
'int i = 0;' + '\n' +
'while(i < 10)' + '\n' +
'i++;' + '\n' +
'}'
)
c_src3 = (
'void func()'+
'{' + '\n' +
'int i = 10;' + '\n' +
'int cnt = 0;' + '\n' +
'while(i > 0)' + '\n' +
'{' + '\n' +
'i--;' + '\n' +
'cnt++;' + '\n' +
'}' + '\n' +
'}'
)
c_src4 = (
'int digit_sum(int n)'+
'{' + '\n' +
'int sum = 0;' + '\n' +
'while(n > 0)' + '\n' +
'{' + '\n' +
'sum += (n % 10);' + '\n' +
'n /= 10;' + '\n' +
'}' + '\n' +
'return sum;' + '\n' +
'}'
)
c_src5 = (
'void func()'+
'{' + '\n' +
'while(1);' + '\n' +
'}'
)
res1 = SymPyExpression(c_src1, 'c').return_expr()
res2 = SymPyExpression(c_src2, 'c').return_expr()
res3 = SymPyExpression(c_src3, 'c').return_expr()
res4 = SymPyExpression(c_src4, 'c').return_expr()
res5 = SymPyExpression(c_src5, 'c').return_expr()
assert res1[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(Symbol('i'),
type=IntBaseType(String('intc')),
value=Integer(0)
)
),
While(
StrictLessThan(
Symbol('i'),
Integer(10)
),
body=CodeBlock(
PostIncrement(
Symbol('i')
)
)
)
)
)
assert res2[0] == res1[0]
assert res3[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
Declaration(
Variable(
Symbol('i'),
type=IntBaseType(String('intc')),
value=Integer(10)
)
),
Declaration(
Variable(
Symbol('cnt'),
type=IntBaseType(String('intc')),
value=Integer(0)
)
),
While(
StrictGreaterThan(
Symbol('i'),
Integer(0)
),
body=CodeBlock(
PostDecrement(
Symbol('i')
),
PostIncrement(
Symbol('cnt')
)
)
)
)
)
assert res4[0] == FunctionDefinition(
IntBaseType(String('intc')),
name=String('digit_sum'),
parameters=(
Variable(
Symbol('n'),
type=IntBaseType(String('intc'))
),
),
body=CodeBlock(
Declaration(
Variable(
Symbol('sum'),
type=IntBaseType(String('intc')),
value=Integer(0)
)
),
While(
StrictGreaterThan(
Symbol('n'),
Integer(0)
),
body=CodeBlock(
AddAugmentedAssignment(
Variable(
Symbol('sum')
),
Mod(
Symbol('n'),
Integer(10)
)
),
DivAugmentedAssignment(
Variable(
Symbol('n')
),
Integer(10)
)
)
),
Return('sum')
)
)
assert res5[0] == FunctionDefinition(
NoneToken(),
name=String('func'),
parameters=(),
body=CodeBlock(
While(
Integer(1),
body=CodeBlock(
NoneToken()
)
)
)
)
else:
def test_raise():
from sympy.parsing.c.c_parser import CCodeConverter
raises(ImportError, lambda: CCodeConverter())
raises(ImportError, lambda: SymPyExpression(' ', mode = 'c'))
|
460c466974e29d6371fe04bf424ab857178496f00111234fcc24ecfb12d77182 | from sympy.parsing.mathematica import mathematica
from sympy.core.sympify import sympify
def test_mathematica():
d = {
'- 6x': '-6*x',
'Sin[x]^2': 'sin(x)**2',
'2(x-1)': '2*(x-1)',
'3y+8': '3*y+8',
'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
'x+y': 'x+y',
'355/113': '355/113',
'2.718281828': '2.718281828',
'Sin[12]': 'sin(12)',
'Exp[Log[4]]': 'exp(log(4))',
'(x+1)(x+3)': '(x+1)*(x+3)',
'Cos[ArcCos[3.6]]': 'cos(acos(3.6))',
'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
'2*Sin[x+y]': '2*sin(x+y)',
'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
'Sin[Cos[x]]': 'sin(cos(x))',
'2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259
'+Sqrt[2]': 'sqrt(2)',
'-Sqrt[2]': '-sqrt(2)',
'-1/Sqrt[2]': '-1/sqrt(2)',
'-(1/Sqrt[3])': '-(1/sqrt(3))',
'1/(2*Sqrt[5])': '1/(2*sqrt(5))',
'Mod[5,3]': 'Mod(5,3)',
'-Mod[5,3]': '-Mod(5,3)',
'(x+1)y': '(x+1)*y',
'x(y+1)': 'x*(y+1)',
'Sin[x]Cos[y]': 'sin(x)*cos(y)',
'Sin[x]**2Cos[y]**2': 'sin(x)**2*cos(y)**2',
'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)',
'x y': 'x*y',
'2 x': '2*x',
'x 8': 'x*8',
'2 8': '2*8',
'1 2 3': '1*2*3',
' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))',
'Log[2,4]': 'log(4,2)',
'Log[Log[2,4],4]': 'log(4,log(4,2))',
'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))',
'ArcSin[Cos[0]]': 'asin(cos(0))',
'Log2[16]': 'log(16,2)',
'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)',
'Min[1,-2,3]': 'Min(1,-2,3)',
'Exp[I Pi/2]': 'exp(I*pi/2)',
'ArcTan[x,y]': 'atan2(y,x)',
'Pochhammer[x,y]': 'rf(x,y)',
'ExpIntegralEi[x]': 'Ei(x)',
'SinIntegral[x]': 'Si(x)',
'CosIntegral[x]': 'Ci(x)',
'AiryAi[x]': 'airyai(x)',
'AiryAiPrime[5]': 'airyaiprime(5)',
'AiryBi[x]' :'airybi(x)',
'AiryBiPrime[7]' :'airybiprime(7)',
'LogIntegral[4]':' li(4)',
'PrimePi[7]': 'primepi(7)',
'Prime[5]': 'prime(5)',
'PrimeQ[5]': 'isprime(5)'
}
for e in d:
assert mathematica(e) == sympify(d[e])
|
b50b9415af18a9576c1cf39c52103094c281f14934f077a30e10c275af255ecd | import os
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.parsing.autolev import parse_autolev
antlr4 = import_module("antlr4")
if not antlr4:
disabled = True
FILE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
def _test_examples(in_filename, out_filename, test_name=""):
in_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
in_filename)
correct_file_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
out_filename)
with open(in_file_path) as f:
generated_code = parse_autolev(f, include_numeric=True)
with open(correct_file_path) as f:
for idx, line1 in enumerate(f):
if line1.startswith("#"):
break
try:
line2 = generated_code.split('\n')[idx]
assert line1.rstrip() == line2.rstrip()
except Exception:
msg = 'mismatch in ' + test_name + ' in line no: {0}'
raise AssertionError(msg.format(idx+1))
def test_rule_tests():
l = ["ruletest1", "ruletest2", "ruletest3", "ruletest4", "ruletest5",
"ruletest6", "ruletest7", "ruletest8", "ruletest9", "ruletest10",
"ruletest11", "ruletest12"]
for i in l:
in_filepath = i + ".al"
out_filepath = i + ".py"
_test_examples(in_filepath, out_filepath, i)
def test_pydy_examples():
l = ["mass_spring_damper", "chaos_pendulum", "double_pendulum",
"non_min_pendulum"]
for i in l:
in_filepath = os.path.join("pydy-example-repo", i + ".al")
out_filepath = os.path.join("pydy-example-repo", i + ".py")
_test_examples(in_filepath, out_filepath, i)
def test_autolev_tutorial():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'autolev-tutorial')
if os.path.isdir(dir_path):
l = ["tutor1", "tutor2", "tutor3", "tutor4", "tutor5", "tutor6",
"tutor7"]
for i in l:
in_filepath = os.path.join("autolev-tutorial", i + ".al")
out_filepath = os.path.join("autolev-tutorial", i + ".py")
_test_examples(in_filepath, out_filepath, i)
def test_dynamics_online():
dir_path = os.path.join(FILE_DIR, 'autolev', 'test-examples',
'dynamics-online')
if os.path.isdir(dir_path):
ch1 = ["1-4", "1-5", "1-6", "1-7", "1-8", "1-9_1", "1-9_2", "1-9_3"]
ch2 = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7", "2-8", "2-9",
"circular"]
ch3 = ["3-1_1", "3-1_2", "3-2_1", "3-2_2", "3-2_3", "3-2_4", "3-2_5",
"3-3"]
ch4 = ["4-1_1", "4-2_1", "4-4_1", "4-4_2", "4-5_1", "4-5_2"]
chapters = [(ch1, "ch1"), (ch2, "ch2"), (ch3, "ch3"), (ch4, "ch4")]
for ch, name in chapters:
for i in ch:
in_filepath = os.path.join("dynamics-online", name, i + ".al")
out_filepath = os.path.join("dynamics-online", name, i + ".py")
_test_examples(in_filepath, out_filepath, i)
def test_output_01():
"""Autolev example calculates the position, velocity, and acceleration of a
point and expresses in a single reference frame::
(1) FRAMES C,D,F
(2) VARIABLES FD'',DC''
(3) CONSTANTS R,L
(4) POINTS O,E
(5) SIMPROT(F,D,1,FD)
-> (6) F_D = [1, 0, 0; 0, COS(FD), -SIN(FD); 0, SIN(FD), COS(FD)]
(7) SIMPROT(D,C,2,DC)
-> (8) D_C = [COS(DC), 0, SIN(DC); 0, 1, 0; -SIN(DC), 0, COS(DC)]
(9) W_C_F> = EXPRESS(W_C_F>, F)
-> (10) W_C_F> = FD'*F1> + COS(FD)*DC'*F2> + SIN(FD)*DC'*F3>
(11) P_O_E>=R*D2>-L*C1>
(12) P_O_E>=EXPRESS(P_O_E>, D)
-> (13) P_O_E> = -L*COS(DC)*D1> + R*D2> + L*SIN(DC)*D3>
(14) V_E_F>=EXPRESS(DT(P_O_E>,F),D)
-> (15) V_E_F> = L*SIN(DC)*DC'*D1> - L*SIN(DC)*FD'*D2> + (R*FD'+L*COS(DC)*DC')*D3>
(16) A_E_F>=EXPRESS(DT(V_E_F>,F),D)
-> (17) A_E_F> = L*(COS(DC)*DC'^2+SIN(DC)*DC'')*D1> + (-R*FD'^2-2*L*COS(DC)*DC'*FD'-L*SIN(DC)*FD'')*D2> + (R*FD''+L*COS(DC)*DC''-L*SIN(DC)*DC'^2-L*SIN(DC)*FD'^2)*D3>
"""
if not antlr4:
skip('Test skipped: antlr4 is not installed.')
autolev_input = """\
FRAMES C,D,F
VARIABLES FD'',DC''
CONSTANTS R,L
POINTS O,E
SIMPROT(F,D,1,FD)
SIMPROT(D,C,2,DC)
W_C_F>=EXPRESS(W_C_F>,F)
P_O_E>=R*D2>-L*C1>
P_O_E>=EXPRESS(P_O_E>,D)
V_E_F>=EXPRESS(DT(P_O_E>,F),D)
A_E_F>=EXPRESS(DT(V_E_F>,F),D)\
"""
sympy_input = parse_autolev(autolev_input)
g = {}
l = {}
exec(sympy_input, g, l)
w_c_f = l['frame_c'].ang_vel_in(l['frame_f'])
# P_O_E> means "the position of point E wrt to point O"
p_o_e = l['point_e'].pos_from(l['point_o'])
v_e_f = l['point_e'].vel(l['frame_f'])
a_e_f = l['point_e'].acc(l['frame_f'])
# NOTE : The Autolev outputs above were manually transformed into
# equivalent SymPy physics vector expressions. Would be nice to automate
# this transformation.
expected_w_c_f = (l['fd'].diff()*l['frame_f'].x +
cos(l['fd'])*l['dc'].diff()*l['frame_f'].y +
sin(l['fd'])*l['dc'].diff()*l['frame_f'].z)
assert (w_c_f - expected_w_c_f).simplify() == 0
expected_p_o_e = (-l['l']*cos(l['dc'])*l['frame_d'].x +
l['r']*l['frame_d'].y +
l['l']*sin(l['dc'])*l['frame_d'].z)
assert (p_o_e - expected_p_o_e).simplify() == 0
expected_v_e_f = (l['l']*sin(l['dc'])*l['dc'].diff()*l['frame_d'].x -
l['l']*sin(l['dc'])*l['fd'].diff()*l['frame_d'].y +
(l['r']*l['fd'].diff() +
l['l']*cos(l['dc'])*l['dc'].diff())*l['frame_d'].z)
assert (v_e_f - expected_v_e_f).simplify() == 0
expected_a_e_f = (l['l']*(cos(l['dc'])*l['dc'].diff()**2 +
sin(l['dc'])*l['dc'].diff().diff())*l['frame_d'].x +
(-l['r']*l['fd'].diff()**2 -
2*l['l']*cos(l['dc'])*l['dc'].diff()*l['fd'].diff() -
l['l']*sin(l['dc'])*l['fd'].diff().diff())*l['frame_d'].y +
(l['r']*l['fd'].diff().diff() +
l['l']*cos(l['dc'])*l['dc'].diff().diff() -
l['l']*sin(l['dc'])*l['dc'].diff()**2 -
l['l']*sin(l['dc'])*l['fd'].diff()**2)*l['frame_d'].z)
assert (a_e_f - expected_a_e_f).simplify() == 0
|
049258e9ea2283d65fcd9ed3ce6085dd4e98f18e876dc7ca02cd42ae69386bc7 | from sympy.parsing.maxima import parse_maxima
from sympy.core.numbers import (E, Rational, oo)
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.abc import x
n = Symbol('n', integer=True)
def test_parser():
assert Abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5)
assert parse_maxima('13^26') == 91733330193268616658399616009
assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3, 2)
assert parse_maxima('log(%e)') == 1
def test_injection():
parse_maxima('c: x+1', globals=globals())
# c created by parse_maxima
assert c == x + 1 # noqa:F821
parse_maxima('g: sqrt(81)', globals=globals())
# g created by parse_maxima
assert g == 9 # noqa:F821
def test_maxima_functions():
assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1
assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2
assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2
assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \
-1 + 2*cos(x)**2 + 2*cos(x)*sin(x)
assert parse_maxima('solve(x^2-4,x)') == [-2, 2]
assert parse_maxima('limit((1+1/x)^x,x,inf)') == E
assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') is -oo
assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x))
assert parse_maxima('sum(k, k, 1, n)', name_dict=dict(
n=Symbol('n', integer=True),
k=Symbol('k', integer=True)
)) == (n**2 + n)/2
assert parse_maxima('product(k, k, 1, n)', name_dict=dict(
n=Symbol('n', integer=True),
k=Symbol('k', integer=True)
)) == factorial(n)
assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1
assert Abs( parse_maxima(
'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
|
b29e61cefe6c8955b7c549a1929d12d22680d02cfe3d50741ced730b4e29c58b | from sympy.external import import_module
from sympy.utilities.decorator import doctest_depends_on
@doctest_depends_on(modules=('antlr4',))
def parse_autolev(autolev_code, include_numeric=False):
"""Parses Autolev code (version 4.1) to SymPy code.
Parameters
=========
autolev_code : Can be an str or any object with a readlines() method (such as a file handle or StringIO).
include_numeric : boolean, optional
If True NumPy, PyDy, or other numeric code is included for numeric evaluation lines in the Autolev code.
Returns
=======
sympy_code : str
Equivalent SymPy and/or numpy/pydy code as the input code.
Example (Double Pendulum)
=========================
>>> my_al_text = ("MOTIONVARIABLES' Q{2}', U{2}'",
... "CONSTANTS L,M,G",
... "NEWTONIAN N",
... "FRAMES A,B",
... "SIMPROT(N, A, 3, Q1)",
... "SIMPROT(N, B, 3, Q2)",
... "W_A_N>=U1*N3>",
... "W_B_N>=U2*N3>",
... "POINT O",
... "PARTICLES P,R",
... "P_O_P> = L*A1>",
... "P_P_R> = L*B1>",
... "V_O_N> = 0>",
... "V2PTS(N, A, O, P)",
... "V2PTS(N, B, P, R)",
... "MASS P=M, R=M",
... "Q1' = U1",
... "Q2' = U2",
... "GRAVITY(G*N1>)",
... "ZERO = FR() + FRSTAR()",
... "KANE()",
... "INPUT M=1,G=9.81,L=1",
... "INPUT Q1=.1,Q2=.2,U1=0,U2=0",
... "INPUT TFINAL=10, INTEGSTP=.01",
... "CODE DYNAMICS() some_filename.c")
>>> my_al_text = '\\n'.join(my_al_text)
>>> from sympy.parsing.autolev import parse_autolev
>>> print(parse_autolev(my_al_text, include_numeric=True))
import sympy.physics.mechanics as _me
import sympy as _sm
import math as m
import numpy as _np
<BLANKLINE>
q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2')
q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1)
l, m, g = _sm.symbols('l m g', real=True)
frame_n = _me.ReferenceFrame('n')
frame_a = _me.ReferenceFrame('a')
frame_b = _me.ReferenceFrame('b')
frame_a.orient(frame_n, 'Axis', [q1, frame_n.z])
frame_b.orient(frame_n, 'Axis', [q2, frame_n.z])
frame_a.set_ang_vel(frame_n, u1*frame_n.z)
frame_b.set_ang_vel(frame_n, u2*frame_n.z)
point_o = _me.Point('o')
particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m'))
particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m'))
particle_p.point.set_pos(point_o, l*frame_a.x)
particle_r.point.set_pos(particle_p.point, l*frame_b.x)
point_o.set_vel(frame_n, 0)
particle_p.point.v2pt_theory(point_o,frame_n,frame_a)
particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b)
particle_p.mass = m
particle_r.mass = m
force_p = particle_p.mass*(g*frame_n.x)
force_r = particle_r.mass*(g*frame_n.x)
kd_eqs = [q1_d - u1, q2_d - u2]
forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))]
kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs)
fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList)
zero = fr+frstar
from pydy.system import System
sys = System(kane, constants = {l:1, m:1, g:9.81},
specifieds={},
initial_conditions={q1:.1, q2:.2, u1:0, u2:0},
times = _np.linspace(0.0, 10, 10/.01))
<BLANKLINE>
y=sys.integrate()
<BLANKLINE>
"""
_autolev = import_module(
'sympy.parsing.autolev._parse_autolev_antlr',
import_kwargs={'fromlist': ['X']})
if _autolev is not None:
return _autolev.parse_autolev(autolev_code, include_numeric)
|
85160bb45bd805a41a3c286deecc6d007948ef3f75f18a0f9f811d323da6145e | from sympy.external import import_module
autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
import_kwargs={'fromlist': ['AutolevParser']})
autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
import_kwargs={'fromlist': ['AutolevLexer']})
autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
import_kwargs={'fromlist': ['AutolevListener']})
AutolevParser = getattr(autolevparser, 'AutolevParser', None)
AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
def parse_autolev(autolev_code, include_numeric):
antlr4 = import_module('antlr4', warn_not_installed=True)
if not antlr4:
raise ImportError("Autolev parsing requires the antlr4 Python package,"
" provided by pip (antlr4-python2-runtime or"
" antlr4-python3-runtime) or"
" conda (antlr-python-runtime)")
try:
l = autolev_code.readlines()
input_stream = antlr4.InputStream("".join(l))
except Exception:
input_stream = antlr4.InputStream(autolev_code)
if AutolevListener:
from ._listener_autolev_antlr import MyListener
lexer = AutolevLexer(input_stream)
token_stream = antlr4.CommonTokenStream(lexer)
parser = AutolevParser(token_stream)
tree = parser.prog()
my_listener = MyListener(include_numeric)
walker = antlr4.ParseTreeWalker()
walker.walk(my_listener, tree)
return "".join(my_listener.output_code)
|
69be95e83d2e95bbce4071bf2a93f63b049a4cdeaf8ab6b19a95335830a3b67b | # Ported from latex2sympy by @augustt198
# https://github.com/augustt198/latex2sympy
# See license in LICENSE.txt
import sympy
from sympy.external import import_module
from sympy.printing.str import StrPrinter
from sympy.physics.quantum.state import Bra, Ket
from .errors import LaTeXParsingError
LaTeXParser = LaTeXLexer = MathErrorListener = None
try:
LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
except Exception:
pass
ErrorListener = import_module('antlr4.error.ErrorListener',
warn_not_installed=True,
import_kwargs={'fromlist': ['ErrorListener']}
)
if ErrorListener:
class MathErrorListener(ErrorListener.ErrorListener): # type: ignore
def __init__(self, src):
super(ErrorListener.ErrorListener, self).__init__()
self.src = src
def syntaxError(self, recog, symbol, line, col, msg, e):
fmt = "%s\n%s\n%s"
marker = "~" * col + "^"
if msg.startswith("missing"):
err = fmt % (msg, self.src, marker)
elif msg.startswith("no viable"):
err = fmt % ("I expected something else here", self.src, marker)
elif msg.startswith("mismatched"):
names = LaTeXParser.literalNames
expected = [
names[i] for i in e.getExpectedTokens() if i < len(names)
]
if len(expected) < 10:
expected = " ".join(expected)
err = (fmt % ("I expected one of these: " + expected, self.src,
marker))
else:
err = (fmt % ("I expected something else here", self.src,
marker))
else:
err = fmt % ("I don't understand this", self.src, marker)
raise LaTeXParsingError(err)
def parse_latex(sympy):
antlr4 = import_module('antlr4', warn_not_installed=True)
if None in [antlr4, MathErrorListener]:
raise ImportError("LaTeX parsing requires the antlr4 Python package,"
" provided by pip (antlr4-python2-runtime or"
" antlr4-python3-runtime) or"
" conda (antlr-python-runtime)")
matherror = MathErrorListener(sympy)
stream = antlr4.InputStream(sympy)
lex = LaTeXLexer(stream)
lex.removeErrorListeners()
lex.addErrorListener(matherror)
tokens = antlr4.CommonTokenStream(lex)
parser = LaTeXParser(tokens)
# remove default console error listener
parser.removeErrorListeners()
parser.addErrorListener(matherror)
relation = parser.math().relation()
expr = convert_relation(relation)
return expr
def convert_relation(rel):
if rel.expr():
return convert_expr(rel.expr())
lh = convert_relation(rel.relation(0))
rh = convert_relation(rel.relation(1))
if rel.LT():
return sympy.StrictLessThan(lh, rh)
elif rel.LTE():
return sympy.LessThan(lh, rh)
elif rel.GT():
return sympy.StrictGreaterThan(lh, rh)
elif rel.GTE():
return sympy.GreaterThan(lh, rh)
elif rel.EQUAL():
return sympy.Eq(lh, rh)
elif rel.NEQ():
return sympy.Ne(lh, rh)
def convert_expr(expr):
return convert_add(expr.additive())
def convert_add(add):
if add.ADD():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, rh, evaluate=False)
elif add.SUB():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False),
evaluate=False)
else:
return convert_mp(add.mp())
def convert_mp(mp):
if hasattr(mp, 'mp'):
mp_left = mp.mp(0)
mp_right = mp.mp(1)
else:
mp_left = mp.mp_nofunc(0)
mp_right = mp.mp_nofunc(1)
if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, rh, evaluate=False)
elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
else:
if hasattr(mp, 'unary'):
return convert_unary(mp.unary())
else:
return convert_unary(mp.unary_nofunc())
def convert_unary(unary):
if hasattr(unary, 'unary'):
nested_unary = unary.unary()
else:
nested_unary = unary.unary_nofunc()
if hasattr(unary, 'postfix_nofunc'):
first = unary.postfix()
tail = unary.postfix_nofunc()
postfix = [first] + tail
else:
postfix = unary.postfix()
if unary.ADD():
return convert_unary(nested_unary)
elif unary.SUB():
numabs = convert_unary(nested_unary)
# Use Integer(-n) instead of Mul(-1, n)
return -numabs
elif postfix:
return convert_postfix_list(postfix)
def convert_postfix_list(arr, i=0):
if i >= len(arr):
raise LaTeXParsingError("Index out of bounds")
res = convert_postfix(arr[i])
if isinstance(res, sympy.Expr):
if i == len(arr) - 1:
return res # nothing to multiply by
else:
if i > 0:
left = convert_postfix(arr[i - 1])
right = convert_postfix(arr[i + 1])
if isinstance(left, sympy.Expr) and isinstance(
right, sympy.Expr):
left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
right_syms = convert_postfix(arr[i + 1]).atoms(
sympy.Symbol)
# if the left and right sides contain no variables and the
# symbol in between is 'x', treat as multiplication.
if len(left_syms) == 0 and len(right_syms) == 0 and str(
res) == "x":
return convert_postfix_list(arr, i + 1)
# multiply by next
return sympy.Mul(
res, convert_postfix_list(arr, i + 1), evaluate=False)
else: # must be derivative
wrt = res[0]
if i == len(arr) - 1:
raise LaTeXParsingError("Expected expression for derivative")
else:
expr = convert_postfix_list(arr, i + 1)
return sympy.Derivative(expr, wrt)
def do_subs(expr, at):
if at.expr():
at_expr = convert_expr(at.expr())
syms = at_expr.atoms(sympy.Symbol)
if len(syms) == 0:
return expr
elif len(syms) > 0:
sym = next(iter(syms))
return expr.subs(sym, at_expr)
elif at.equality():
lh = convert_expr(at.equality().expr(0))
rh = convert_expr(at.equality().expr(1))
return expr.subs(lh, rh)
def convert_postfix(postfix):
if hasattr(postfix, 'exp'):
exp_nested = postfix.exp()
else:
exp_nested = postfix.exp_nofunc()
exp = convert_exp(exp_nested)
for op in postfix.postfix_op():
if op.BANG():
if isinstance(exp, list):
raise LaTeXParsingError("Cannot apply postfix to derivative")
exp = sympy.factorial(exp, evaluate=False)
elif op.eval_at():
ev = op.eval_at()
at_b = None
at_a = None
if ev.eval_at_sup():
at_b = do_subs(exp, ev.eval_at_sup())
if ev.eval_at_sub():
at_a = do_subs(exp, ev.eval_at_sub())
if at_b is not None and at_a is not None:
exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
elif at_b is not None:
exp = at_b
elif at_a is not None:
exp = at_a
return exp
def convert_exp(exp):
if hasattr(exp, 'exp'):
exp_nested = exp.exp()
else:
exp_nested = exp.exp_nofunc()
if exp_nested:
base = convert_exp(exp_nested)
if isinstance(base, list):
raise LaTeXParsingError("Cannot raise derivative to power")
if exp.atom():
exponent = convert_atom(exp.atom())
elif exp.expr():
exponent = convert_expr(exp.expr())
return sympy.Pow(base, exponent, evaluate=False)
else:
if hasattr(exp, 'comp'):
return convert_comp(exp.comp())
else:
return convert_comp(exp.comp_nofunc())
def convert_comp(comp):
if comp.group():
return convert_expr(comp.group().expr())
elif comp.abs_group():
return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
elif comp.atom():
return convert_atom(comp.atom())
elif comp.frac():
return convert_frac(comp.frac())
elif comp.binom():
return convert_binom(comp.binom())
elif comp.floor():
return convert_floor(comp.floor())
elif comp.ceil():
return convert_ceil(comp.ceil())
elif comp.func():
return convert_func(comp.func())
def convert_atom(atom):
if atom.LETTER():
subscriptName = ''
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = '_{' + StrPrinter().doprint(subscript) + '}'
return sympy.Symbol(atom.LETTER().getText() + subscriptName)
elif atom.SYMBOL():
s = atom.SYMBOL().getText()[1:]
if s == "infty":
return sympy.oo
else:
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
s += '_{' + subscriptName + '}'
return sympy.Symbol(s)
elif atom.NUMBER():
s = atom.NUMBER().getText().replace(",", "")
return sympy.Number(s)
elif atom.DIFFERENTIAL():
var = get_differential_var(atom.DIFFERENTIAL())
return sympy.Symbol('d' + var.name)
elif atom.mathit():
text = rule2text(atom.mathit().mathit_text())
return sympy.Symbol(text)
elif atom.bra():
val = convert_expr(atom.bra().expr())
return Bra(val)
elif atom.ket():
val = convert_expr(atom.ket().expr())
return Ket(val)
def rule2text(ctx):
stream = ctx.start.getInputStream()
# starting index of starting token
startIdx = ctx.start.start
# stopping index of stopping token
stopIdx = ctx.stop.stop
return stream.getText(startIdx, stopIdx)
def convert_frac(frac):
diff_op = False
partial_op = False
lower_itv = frac.lower.getSourceInterval()
lower_itv_len = lower_itv[1] - lower_itv[0] + 1
if (frac.lower.start == frac.lower.stop
and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
wrt = get_differential_var_str(frac.lower.start.text)
diff_op = True
elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
and frac.lower.start.text == '\\partial'
and (frac.lower.stop.type == LaTeXLexer.LETTER
or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
partial_op = True
wrt = frac.lower.stop.text
if frac.lower.stop.type == LaTeXLexer.SYMBOL:
wrt = wrt[1:]
if diff_op or partial_op:
wrt = sympy.Symbol(wrt)
if (diff_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.LETTER
and frac.upper.start.text == 'd'):
return [wrt]
elif (partial_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.SYMBOL
and frac.upper.start.text == '\\partial'):
return [wrt]
upper_text = rule2text(frac.upper)
expr_top = None
if diff_op and upper_text.startswith('d'):
expr_top = parse_latex(upper_text[1:])
elif partial_op and frac.upper.start.text == '\\partial':
expr_top = parse_latex(upper_text[len('\\partial'):])
if expr_top:
return sympy.Derivative(expr_top, wrt)
expr_top = convert_expr(frac.upper)
expr_bot = convert_expr(frac.lower)
inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
if expr_top == 1:
return inverse_denom
else:
return sympy.Mul(expr_top, inverse_denom, evaluate=False)
def convert_binom(binom):
expr_n = convert_expr(binom.n)
expr_k = convert_expr(binom.k)
return sympy.binomial(expr_n, expr_k, evaluate=False)
def convert_floor(floor):
val = convert_expr(floor.val)
return sympy.floor(val, evaluate=False)
def convert_ceil(ceil):
val = convert_expr(ceil.val)
return sympy.ceiling(val, evaluate=False)
def convert_func(func):
if func.func_normal():
if func.L_PAREN(): # function called with parenthesis
arg = convert_func_arg(func.func_arg())
else:
arg = convert_func_arg(func.func_arg_noparens())
name = func.func_normal().start.text[1:]
# change arc<trig> -> a<trig>
if name in [
"arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
]:
name = "a" + name[3:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name in ["arsinh", "arcosh", "artanh"]:
name = "a" + name[2:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name == "exp":
expr = sympy.exp(arg, evaluate=False)
if (name == "log" or name == "ln"):
if func.subexpr():
if func.subexpr().expr():
base = convert_expr(func.subexpr().expr())
else:
base = convert_atom(func.subexpr().atom())
elif name == "log":
base = 10
elif name == "ln":
base = sympy.E
expr = sympy.log(arg, base, evaluate=False)
func_pow = None
should_pow = True
if func.supexpr():
if func.supexpr().expr():
func_pow = convert_expr(func.supexpr().expr())
else:
func_pow = convert_atom(func.supexpr().atom())
if name in [
"sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
"tanh"
]:
if func_pow == -1:
name = "a" + name
should_pow = False
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if func_pow and should_pow:
expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr
elif func.LETTER() or func.SYMBOL():
if func.LETTER():
fname = func.LETTER().getText()
elif func.SYMBOL():
fname = func.SYMBOL().getText()[1:]
fname = str(fname) # can't be unicode
if func.subexpr():
subscript = None
if func.subexpr().expr(): # subscript is expr
subscript = convert_expr(func.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(func.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
fname += '_{' + subscriptName + '}'
input_args = func.args()
output_args = []
while input_args.args(): # handle multiple arguments to function
output_args.append(convert_expr(input_args.expr()))
input_args = input_args.args()
output_args.append(convert_expr(input_args.expr()))
return sympy.Function(fname)(*output_args)
elif func.FUNC_INT():
return handle_integral(func)
elif func.FUNC_SQRT():
expr = convert_expr(func.base)
if func.root:
r = convert_expr(func.root)
return sympy.root(expr, r, evaluate=False)
else:
return sympy.sqrt(expr, evaluate=False)
elif func.FUNC_OVERLINE():
expr = convert_expr(func.base)
return sympy.conjugate(expr, evaluate=False)
elif func.FUNC_SUM():
return handle_sum_or_prod(func, "summation")
elif func.FUNC_PROD():
return handle_sum_or_prod(func, "product")
elif func.FUNC_LIM():
return handle_limit(func)
def convert_func_arg(arg):
if hasattr(arg, 'expr'):
return convert_expr(arg.expr())
else:
return convert_mp(arg.mp_nofunc())
def handle_integral(func):
if func.additive():
integrand = convert_add(func.additive())
elif func.frac():
integrand = convert_frac(func.frac())
else:
integrand = 1
int_var = None
if func.DIFFERENTIAL():
int_var = get_differential_var(func.DIFFERENTIAL())
else:
for sym in integrand.atoms(sympy.Symbol):
s = str(sym)
if len(s) > 1 and s[0] == 'd':
if s[1] == '\\':
int_var = sympy.Symbol(s[2:])
else:
int_var = sympy.Symbol(s[1:])
int_sym = sym
if int_var:
integrand = integrand.subs(int_sym, 1)
else:
# Assume dx by default
int_var = sympy.Symbol('x')
if func.subexpr():
if func.subexpr().atom():
lower = convert_atom(func.subexpr().atom())
else:
lower = convert_expr(func.subexpr().expr())
if func.supexpr().atom():
upper = convert_atom(func.supexpr().atom())
else:
upper = convert_expr(func.supexpr().expr())
return sympy.Integral(integrand, (int_var, lower, upper))
else:
return sympy.Integral(integrand, int_var)
def handle_sum_or_prod(func, name):
val = convert_mp(func.mp())
iter_var = convert_expr(func.subeq().equality().expr(0))
start = convert_expr(func.subeq().equality().expr(1))
if func.supexpr().expr(): # ^{expr}
end = convert_expr(func.supexpr().expr())
else: # ^atom
end = convert_atom(func.supexpr().atom())
if name == "summation":
return sympy.Sum(val, (iter_var, start, end))
elif name == "product":
return sympy.Product(val, (iter_var, start, end))
def handle_limit(func):
sub = func.limit_sub()
if sub.LETTER():
var = sympy.Symbol(sub.LETTER().getText())
elif sub.SYMBOL():
var = sympy.Symbol(sub.SYMBOL().getText()[1:])
else:
var = sympy.Symbol('x')
if sub.SUB():
direction = "-"
else:
direction = "+"
approaching = convert_expr(sub.expr())
content = convert_mp(func.mp())
return sympy.Limit(content, var, approaching, direction)
def get_differential_var(d):
text = get_differential_var_str(d.getText())
return sympy.Symbol(text)
def get_differential_var_str(text):
for i in range(1, len(text)):
c = text[i]
if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
idx = i
break
text = text[idx:]
if text[0] == "\\":
text = text[1:]
return text
|
30c4c6166ea43977ac678ec420ff25a69b029ee25b58c893e7b58b56e3fca284 | from typing import Type
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.polys.polyroots import roots
from sympy.polys.polytools import (cancel, degree)
from sympy.core.containers import Tuple
from sympy.core.evalf import EvalfMixin
from sympy.core.logic import fuzzy_and
from sympy.core.numbers import Integer, ComplexInfinity
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify, _sympify
from sympy.polys import Poly, rootof
from sympy.series import limit
from sympy.matrices import ImmutableMatrix, eye
from sympy.matrices.expressions import MatMul, MatAdd
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel',
'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix']
def _roots(poly, var):
""" like roots, but works on higher-order polynomials. """
r = roots(poly, var, multiple=True)
n = degree(poly)
if len(r) != n:
r = [rootof(poly, var, k) for k in range(n)]
return r
class LinearTimeInvariant(Basic, EvalfMixin):
"""A common class for all the Linear Time-Invariant Dynamical Systems."""
_clstype: Type
# Users should not directly interact with this class.
def __new__(cls, *system, **kwargs):
if cls is LinearTimeInvariant:
raise NotImplementedError('The LTICommon class is not meant to be used directly.')
return super(LinearTimeInvariant, cls).__new__(cls, *system, **kwargs)
@classmethod
def _check_args(cls, args):
if not args:
raise ValueError("Atleast 1 argument must be passed.")
if not all(isinstance(arg, cls._clstype) for arg in args):
raise TypeError(f"All arguments must be of type {cls._clstype}.")
var_set = {arg.var for arg in args}
if len(var_set) != 1:
raise ValueError("All transfer functions should use the same complex variable"
f" of the Laplace transform. {len(var_set)} different values found.")
@property
def is_SISO(self):
"""Returns `True` if the passed LTI system is SISO else returns False."""
return self._is_SISO
class SISOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the SISO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = True
class MIMOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the MIMO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = False
SISOLinearTimeInvariant._clstype = SISOLinearTimeInvariant
MIMOLinearTimeInvariant._clstype = MIMOLinearTimeInvariant
def _check_other_SISO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], SISOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
def _check_other_MIMO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], MIMOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
class TransferFunction(SISOLinearTimeInvariant):
r"""
A class for representing LTI (Linear, time-invariant) systems that can be strictly described
by ratio of polynomials in the Laplace transform complex variable. The arguments
are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and
denominator polynomials of the ``TransferFunction`` respectively, and the third argument is
a complex variable of the Laplace transform used by these polynomials of the transfer function.
``num`` and ``den`` can be either polynomials or numbers, whereas ``var``
has to be a Symbol.
Explanation
===========
Generally, a dynamical system representing a physical model can be described in terms of Linear
Ordinary Differential Equations like -
$\small{b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y=
a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x}$
Here, $x$ is the input signal and $y$ is the output signal and superscript on both is the order of derivative
(not exponent). Derivative is taken with respect to the independent variable, $t$. Also, generally $m$ is greater
than $n$.
It is not feasible to analyse the properties of such systems in their native form therefore, we use
mathematical tools like Laplace transform to get a better perspective. Taking the Laplace transform
of both the sides in the equation (at zero initial conditions), we get -
$\small{\mathcal{L}[b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y]=
\mathcal{L}[a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x]}$
Using the linearity property of Laplace transform and also considering zero initial conditions
(i.e. $\small{y(0^{-}) = 0}$, $\small{y'(0^{-}) = 0}$ and so on), the equation
above gets translated to -
$\small{b_{m}\mathcal{L}[y^{\left(m\right)}]+\dots+b_{1}\mathcal{L}[y^{\left(1\right)}]+b_{0}\mathcal{L}[y]=
a_{n}\mathcal{L}[x^{\left(n\right)}]+\dots+a_{1}\mathcal{L}[x^{\left(1\right)}]+a_{0}\mathcal{L}[x]}$
Now, applying Derivative property of Laplace transform,
$\small{b_{m}s^{m}\mathcal{L}[y]+\dots+b_{1}s\mathcal{L}[y]+b_{0}\mathcal{L}[y]=
a_{n}s^{n}\mathcal{L}[x]+\dots+a_{1}s\mathcal{L}[x]+a_{0}\mathcal{L}[x]}$
Here, the superscript on $s$ is **exponent**. Note that the zero initial conditions assumption, mentioned above, is very important
and cannot be ignored otherwise the dynamical system cannot be considered time-independent and the simplified equation above
cannot be reached.
Collecting $\mathcal{L}[y]$ and $\mathcal{L}[x]$ terms from both the sides and taking the ratio
$\frac{ \mathcal{L}\left\{y\right\} }{ \mathcal{L}\left\{x\right\} }$, we get the typical rational form of transfer
function.
The numerator of the transfer function is, therefore, the Laplace transform of the output signal
(The signals are represented as functions of time) and similarly, the denominator
of the transfer function is the Laplace transform of the input signal. It is also a convention
to denote the input and output signal's Laplace transform with capital alphabets like shown below.
$H(s) = \frac{Y(s)}{X(s)} = \frac{ \mathcal{L}\left\{y(t)\right\} }{ \mathcal{L}\left\{x(t)\right\} }$
$s$, also known as complex frequency, is a complex variable in the Laplace domain. It corresponds to the
equivalent variable $t$, in the time domain. Transfer functions are sometimes also referred to as the Laplace
transform of the system's impulse response. Transfer function, $H$, is represented as a rational
function in $s$ like,
$H(s) =\ \frac{a_{n}s^{n}+a_{n-1}s^{n-1}+\dots+a_{1}s+a_{0}}{b_{m}s^{m}+b_{m-1}s^{m-1}+\dots+b_{1}s+b_{0}}$
Parameters
==========
num : Expr, Number
The numerator polynomial of the transfer function.
den : Expr, Number
The denominator polynomial of the transfer function.
var : Symbol
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
TypeError
When ``var`` is not a Symbol or when ``num`` or ``den`` is not a
number or a polynomial.
ValueError
When ``den`` is zero.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf1
TransferFunction(a + s, s**2 + s + 1, s)
>>> tf1.num
a + s
>>> tf1.den
s**2 + s + 1
>>> tf1.var
s
>>> tf1.args
(a + s, s**2 + s + 1, s)
Any complex variable can be used for ``var``.
>>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
>>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf3
TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p)
To negate a transfer function the ``-`` operator can be prepended:
>>> tf4 = TransferFunction(-a + s, p**2 + s, p)
>>> -tf4
TransferFunction(a - s, p**2 + s, p)
>>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s)
>>> -tf5
TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s)
You can use a Float or an Integer (or other constants) as numerator and denominator:
>>> tf6 = TransferFunction(1/2, 4, s)
>>> tf6.num
0.500000000000000
>>> tf6.den
4
>>> tf6.var
s
>>> tf6.args
(0.5, 4, s)
You can take the integer power of a transfer function using the ``**`` operator:
>>> tf7 = TransferFunction(s + a, s - a, s)
>>> tf7**3
TransferFunction((a + s)**3, (-a + s)**3, s)
>>> tf7**0
TransferFunction(1, 1, s)
>>> tf8 = TransferFunction(p + 4, p - 3, p)
>>> tf8**-1
TransferFunction(p - 3, p + 4, p)
Addition, subtraction, and multiplication of transfer functions can form
unevaluated ``Series`` or ``Parallel`` objects.
>>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> tf10 = TransferFunction(s - p, s + 3, s)
>>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s)
>>> tf12 = TransferFunction(1 - s, s**2 + 4, s)
>>> tf9 + tf10
Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - tf11
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s))
>>> tf9 * tf10
Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - (tf9 + tf12)
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s))
>>> tf10 - (tf9 * tf12)
Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> tf11 * tf10 * tf9
Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s))
>>> tf9 * tf11 + tf10 * tf12
Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> (tf9 + tf12) * (tf10 + tf11)
Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)))
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``.
>>> ((tf9 + tf10) * tf12).doit()
TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
>>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction)
TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
See Also
========
Feedback, Series, Parallel
References
==========
.. [1] https://en.wikipedia.org/wiki/Transfer_function
.. [2] https://en.wikipedia.org/wiki/Laplace_transform
"""
def __new__(cls, num, den, var):
num, den = _sympify(num), _sympify(den)
if not isinstance(var, Symbol):
raise TypeError("Variable input must be a Symbol.")
if den == 0:
raise ValueError("TransferFunction cannot have a zero denominator.")
if (((isinstance(num, Expr) and num.has(Symbol)) or num.is_number) and
((isinstance(den, Expr) and den.has(Symbol)) or den.is_number)):
obj = super(TransferFunction, cls).__new__(cls, num, den, var)
obj._num = num
obj._den = den
obj._var = var
return obj
else:
raise TypeError("Unsupported type for numerator or denominator of TransferFunction.")
@classmethod
def from_rational_expression(cls, expr, var=None):
r"""
Creates a new ``TransferFunction`` efficiently from a rational expression.
Parameters
==========
expr : Expr, Number
The rational expression representing the ``TransferFunction``.
var : Symbol, optional
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
ValueError
When ``expr`` is of type ``Number`` and optional parameter ``var``
is not passed.
When ``expr`` has more than one variables and an optional parameter
``var`` is not passed.
ZeroDivisionError
When denominator of ``expr`` is zero or it has ``ComplexInfinity``
in its numerator.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> expr1 = (s + 5)/(3*s**2 + 2*s + 1)
>>> tf1 = TransferFunction.from_rational_expression(expr1)
>>> tf1
TransferFunction(s + 5, 3*s**2 + 2*s + 1, s)
>>> expr2 = (a*p**3 - a*p**2 + s*p)/(p + a**2) # Expr with more than one variables
>>> tf2 = TransferFunction.from_rational_expression(expr2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
In case of conflict between two or more variables in a expression, SymPy will
raise a ``ValueError``, if ``var`` is not passed by the user.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1))
Traceback (most recent call last):
...
ValueError: Conflicting values found for positional argument `var` ({a, s}). Specify it manually.
This can be corrected by specifying the ``var`` parameter manually.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1), s)
>>> tf
TransferFunction(a*s + a, s**2 + s + 1, s)
``var`` also need to be specified when ``expr`` is a ``Number``
>>> tf3 = TransferFunction.from_rational_expression(10, s)
>>> tf3
TransferFunction(10, 1, s)
"""
expr = _sympify(expr)
if var is None:
_free_symbols = expr.free_symbols
_len_free_symbols = len(_free_symbols)
if _len_free_symbols == 1:
var = list(_free_symbols)[0]
elif _len_free_symbols == 0:
raise ValueError("Positional argument `var` not found in the TransferFunction defined. Specify it manually.")
else:
raise ValueError("Conflicting values found for positional argument `var` ({}). Specify it manually.".format(_free_symbols))
_num, _den = expr.as_numer_denom()
if _den == 0 or _num.has(ComplexInfinity):
raise ZeroDivisionError("TransferFunction cannot have a zero denominator.")
return cls(_num, _den, var)
@property
def num(self):
"""
Returns the numerator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s)
>>> G1.num
p*s + s**2 + 3
>>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p)
>>> G2.num
(p - 3)*(p + 5)
"""
return self._num
@property
def den(self):
"""
Returns the denominator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s)
>>> G1.den
p**3 - 2*p + 4
>>> G2 = TransferFunction(3, 4, s)
>>> G2.den
4
"""
return self._den
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by the polynomials of
the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G1.var
p
>>> G2 = TransferFunction(0, s - 5, s)
>>> G2.var
s
"""
return self._var
def _eval_subs(self, old, new):
arg_num = self.num.subs(old, new)
arg_den = self.den.subs(old, new)
argnew = TransferFunction(arg_num, arg_den, self.var)
return self if old == self.var else argnew
def _eval_evalf(self, prec):
return TransferFunction(
self.num._eval_evalf(prec),
self.den._eval_evalf(prec),
self.var)
def _eval_simplify(self, **kwargs):
tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom()
num_, den_ = tf[0], tf[1]
return TransferFunction(num_, den_, self.var)
def expand(self):
"""
Returns the transfer function with numerator and denominator
in expanded form.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s)
>>> G1.expand()
TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s)
>>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p)
>>> G2.expand()
TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p)
"""
return TransferFunction(expand(self.num), expand(self.den), self.var)
def dc_gain(self):
"""
Computes the gain of the response as the frequency approaches zero.
The DC gain is infinite for systems with pure integrators.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + 3, s**2 - 9, s)
>>> tf1.dc_gain()
-1/3
>>> tf2 = TransferFunction(p**2, p - 3 + p**3, p)
>>> tf2.dc_gain()
0
>>> tf3 = TransferFunction(a*p**2 - b, s + b, s)
>>> tf3.dc_gain()
(a*p**2 - b)/b
>>> tf4 = TransferFunction(1, s, s)
>>> tf4.dc_gain()
oo
"""
m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
return limit(m, self.var, 0)
def poles(self):
"""
Returns the poles of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.poles()
[-5, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.poles()
[I, I, -I, -I]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.poles()
[-p/a]
"""
return _roots(Poly(self.den, self.var), self.var)
def zeros(self):
"""
Returns the zeros of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.zeros()
[-3, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.zeros()
[1, 1]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.zeros()
[0, 0]
"""
return _roots(Poly(self.num, self.var), self.var)
def is_stable(self):
"""
Returns True if the transfer function is asymptotically stable; else False.
This would not check the marginal or conditional stability of the system.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy import symbols
>>> from sympy.physics.control.lti import TransferFunction
>>> q, r = symbols('q, r', negative=True)
>>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s)
>>> tf1.is_stable()
True
>>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s)
>>> tf2.is_stable()
False
>>> tf3 = TransferFunction(4, q*s - r, s)
>>> tf3.is_stable()
False
>>> tf4 = TransferFunction(p + 1, a*p - s**2, p)
>>> tf4.is_stable() is None # Not enough info about the symbols to determine stability
True
"""
return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles())
def __add__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Parallel(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be added with {}.".
format(type(other)))
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, -other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = [-i for i in list(other.args)]
return Parallel(self, *arg_list)
else:
raise ValueError("{} cannot be subtracted from a TransferFunction."
.format(type(other)))
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, (TransferFunction, Parallel)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Series(self, other)
elif isinstance(other, Series):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Series(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be multiplied with {}."
.format(type(other)))
__rmul__ = __mul__
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction)
and isinstance(other.args[1], (Series, TransferFunction))):
if not self.var == other.var:
raise ValueError("Both TransferFunction and Parallel should use the"
" same complex variable of the Laplace transform.")
if other.args[1] == self:
# plant and controller with unit feedback.
return Feedback(self, other.args[0])
other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1]
if other_arg_list == other.args[1]:
return Feedback(self, other_arg_list)
elif self in other_arg_list:
other_arg_list.remove(self)
else:
return Feedback(self, Series(*other_arg_list))
if len(other_arg_list) == 1:
return Feedback(self, *other_arg_list)
else:
return Feedback(self, Series(*other_arg_list))
else:
raise ValueError("TransferFunction cannot be divided by {}.".
format(type(other)))
__rtruediv__ = __truediv__
def __pow__(self, p):
p = sympify(p)
if not isinstance(p, Integer):
raise ValueError("Exponent must be an Integer.")
if p == 0:
return TransferFunction(1, 1, self.var)
elif p > 0:
num_, den_ = self.num**p, self.den**p
else:
p = abs(p)
num_, den_ = self.den**p, self.num**p
return TransferFunction(num_, den_, self.var)
def __neg__(self):
return TransferFunction(-self.num, self.den, self.var)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial is less than
or equal to degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf1.is_proper
False
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p)
>>> tf2.is_proper
True
"""
return degree(self.num, self.var) <= degree(self.den, self.var)
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial is strictly less
than degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_strictly_proper
False
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf2.is_strictly_proper
True
"""
return degree(self.num, self.var) < degree(self.den, self.var)
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial is equal to
degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_biproper
True
>>> tf2 = TransferFunction(p**2, p + a, p)
>>> tf2.is_biproper
False
"""
return degree(self.num, self.var) == degree(self.den, self.var)
def to_expr(self):
"""
Converts a ``TransferFunction`` object to SymPy Expr.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy import Expr
>>> tf1 = TransferFunction(s, a*s**2 + 1, s)
>>> tf1.to_expr()
s/(a*s**2 + 1)
>>> isinstance(_, Expr)
True
>>> tf2 = TransferFunction(1, (p + 3*b)*(b - p), p)
>>> tf2.to_expr()
1/((b - p)*(3*b + p))
>>> tf3 = TransferFunction((s - 2)*(s - 3), (s - 1)*(s - 2)*(s - 3), s)
>>> tf3.to_expr()
((s - 3)*(s - 2))/(((s - 3)*(s - 2)*(s - 1)))
"""
if self.num != 1:
return Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
else:
return Pow(self.den, -1, evaluate=False)
def _flatten_args(args, _cls):
temp_args = []
for arg in args:
if isinstance(arg, _cls):
temp_args.extend(arg.args)
else:
temp_args.append(arg)
return tuple(temp_args)
def _dummify_args(_arg, var):
dummy_dict = {}
dummy_arg_list = []
for arg in _arg:
_s = Dummy()
dummy_dict[_s] = var
dummy_arg = arg.subs({var: _s})
dummy_arg_list.append(dummy_arg)
return dummy_arg_list, dummy_dict
class Series(SISOLinearTimeInvariant):
r"""
A class for representing a series configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Series(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, SISO in this case.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> S1 = Series(tf1, tf2)
>>> S1
Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> S1.var
s
>>> S2 = Series(tf2, Parallel(tf3, -tf1))
>>> S2
Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> S2.var
s
>>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3))
>>> S3
Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> S3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> S3 = Series(tf1, tf2, -tf3)
>>> S3.doit()
TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> S4 = Series(tf2, Parallel(tf1, -tf3))
>>> S4.doit()
TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
MIMOSeries, Parallel, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Series)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Series(G1, G2).var
p
>>> Series(-G3, Parallel(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **kwargs):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Series(tf2, tf1).doit()
TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s)
>>> Series(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s)
"""
_num_arg = (arg.doit().num for arg in self.args)
_den_arg = (arg.doit().den for arg in self.args)
res_num = Mul(*_num_arg, evaluate=True)
res_den = Mul(*_den_arg, evaluate=True)
return TransferFunction(res_num, res_den, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
if isinstance(other, Parallel):
arg_list = list(other.args)
return Parallel(self, *arg_list)
return Parallel(self, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
arg_list = list(self.args)
return Series(*arg_list, other)
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2
and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
self_arg_list = set(list(self.args))
other_arg_list = set(list(other.args[1].args))
res = list(self_arg_list ^ other_arg_list)
if len(res) == 0:
return Feedback(self, other.args[0])
elif len(res) == 1:
return Feedback(self, *res)
else:
return Feedback(self, Series(*res))
else:
raise ValueError("This transfer function expression is invalid.")
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Mul(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> S1 = Series(-tf2, tf1)
>>> S1.is_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s)
>>> tf3 = TransferFunction(1, s**2 + s + 1, s)
>>> S1 = Series(tf1, tf2)
>>> S1.is_strictly_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
r"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p, s**2, s)
>>> tf3 = TransferFunction(s**2, 1, s)
>>> S1 = Series(tf1, -tf2)
>>> S1.is_biproper
False
>>> S2 = Series(tf2, tf3)
>>> S2.is_biproper
True
"""
return self.doit().is_biproper
def _mat_mul_compatible(*args):
"""To check whether shapes are compatible for matrix mul."""
return all(args[i].num_outputs == args[i+1].num_inputs for i in range(len(args)-1))
class MIMOSeries(MIMOLinearTimeInvariant):
r"""
A class for representing a series configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOSeries(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
``num_outputs`` of the MIMO system is not equal to the
``num_inputs`` of its adjacent MIMO system. (Matrix
multiplication constraint, basically)
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import MIMOSeries, TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> mat_a = Matrix([[5*s], [5]]) # 2 Outputs 1 Input
>>> mat_b = Matrix([[5, 1/(6*s**2)]]) # 1 Output 2 Inputs
>>> mat_c = Matrix([[1, s], [5/s, 1]]) # 2 Outputs 2 Inputs
>>> tfm_a = TransferFunctionMatrix.from_Matrix(mat_a, s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(mat_b, s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(mat_c, s)
>>> MIMOSeries(tfm_c, tfm_b, tfm_a)
MIMOSeries(TransferFunctionMatrix(((TransferFunction(1, 1, s), TransferFunction(s, 1, s)), (TransferFunction(5, s, s), TransferFunction(1, 1, s)))), TransferFunctionMatrix(((TransferFunction(5, 1, s), TransferFunction(1, 6*s**2, s)),)), TransferFunctionMatrix(((TransferFunction(5*s, 1, s),), (TransferFunction(5, 1, s),))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[5*s] [1 s]
[---] [5 1 ] [- -]
[ 1 ] [- ----] [1 1]
[ ] *[1 2] *[ ]
[ 5 ] [ 6*s ]{t} [5 1]
[ - ] [- -]
[ 1 ]{t} [s 1]{t}
>>> MIMOSeries(tfm_c, tfm_b, tfm_a).doit()
TransferFunctionMatrix(((TransferFunction(150*s**4 + 25*s, 6*s**3, s), TransferFunction(150*s**4 + 5*s, 6*s**2, s)), (TransferFunction(150*s**3 + 25, 6*s**3, s), TransferFunction(150*s**3 + 5, 6*s**2, s))))
>>> pprint(_, use_unicode=False) # (2 Inputs -A-> 2 Outputs) -> (2 Inputs -B-> 1 Output) -> (1 Input -C-> 2 Outputs) is equivalent to (2 Inputs -Series Equivalent-> 2 Outputs).
[ 4 4 ]
[150*s + 25*s 150*s + 5*s]
[------------- ------------]
[ 3 2 ]
[ 6*s 6*s ]
[ ]
[ 3 3 ]
[ 150*s + 25 150*s + 5 ]
[ ----------- ---------- ]
[ 3 2 ]
[ 6*s 6*s ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform.
``MIMOSeries(A, B)`` is not equivalent to ``A*B``. It is always in the reverse order, that is ``B*A``.
See Also
========
Series, MIMOParallel
"""
def __new__(cls, *args, evaluate=False):
cls._check_args(args)
if _mat_mul_compatible(*args):
obj = super().__new__(cls, *args)
else:
raise ValueError("Number of input signals do not match the number"
" of output signals of adjacent systems for some args.")
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> tfm_1 = TransferFunctionMatrix([[G1, G2, G3]])
>>> tfm_2 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> MIMOSeries(tfm_2, tfm_1).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the series system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the series system."""
return self.args[-1].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, cancel=False, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf2]])
>>> tfm2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf1]])
>>> MIMOSeries(tfm2, tfm1).doit()
TransferFunctionMatrix(((TransferFunction(2*(-p + s)*(s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)**2*(s**4 + 5*s + 6)**2, s), TransferFunction((-p + s)**2*(s**3 - 2)*(a*p**2 + b*s) + (-p + s)*(a*p**2 + b*s)**2*(s**4 + 5*s + 6), (-p + s)**3*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2)**2*(s**4 + 5*s + 6) + (s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6)**2, (-p + s)*(s**4 + 5*s + 6)**3, s), TransferFunction(2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in reversed(self.args))
if cancel:
res = MatMul(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
_dummy_args, _dummy_dict = _dummify_args(_arg, self.var)
res = MatMul(*_dummy_args, evaluate=True)
temp_tfm = TransferFunctionMatrix.from_Matrix(res, self.var)
return temp_tfm.subs(_dummy_dict)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
if isinstance(other, MIMOParallel):
arg_list = list(other.args)
return MIMOParallel(self, *arg_list)
return MIMOParallel(self, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
self_arg_list = list(self.args)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, *self_arg_list) # A*B = MIMOSeries(B, A)
arg_list = list(self.args)
return MIMOSeries(other, *arg_list)
def __neg__(self):
arg_list = list(self.args)
arg_list[0] = -arg_list[0]
return MIMOSeries(*arg_list)
class Parallel(SISOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Parallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1
Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> P1.var
s
>>> P2 = Parallel(tf2, Series(tf3, -tf1))
>>> P2
Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> P2.var
s
>>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
>>> P3
Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> P3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> Parallel(tf1, tf2, -tf3).doit()
TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(tf2, Series(tf1, -tf3)).doit()
TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Series, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Parallel)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Parallel(G1, G2).var
p
>>> Parallel(-G3, Series(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **kwargs):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Parallel(tf2, tf1).doit()
TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
"""
_arg = (arg.doit().to_expr() for arg in self.args)
res = Add(*_arg).as_numer_denom()
return TransferFunction(*res, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
self_arg_list = list(self.args)
return Parallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
if isinstance(other, Series):
arg_list = list(other.args)
return Series(self, *arg_list)
return Series(self, other)
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Add(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(-tf2, tf1)
>>> P1.is_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1.is_strictly_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p**2, p + s, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, -tf2)
>>> P1.is_biproper
True
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_biproper
False
"""
return self.doit().is_biproper
class MIMOParallel(MIMOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO Systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOParallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
All MIMO systems passed do not have same shape.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOParallel
>>> from sympy import Matrix, pprint
>>> expr_1 = 1/s
>>> expr_2 = s/(s**2-1)
>>> expr_3 = (2 + s)/(s**2 - 1)
>>> expr_4 = 5
>>> tfm_a = TransferFunctionMatrix.from_Matrix(Matrix([[expr_1, expr_2], [expr_3, expr_4]]), s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(Matrix([[expr_2, expr_1], [expr_4, expr_3]]), s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(Matrix([[expr_3, expr_4], [expr_1, expr_2]]), s)
>>> MIMOParallel(tfm_a, tfm_b, tfm_c)
MIMOParallel(TransferFunctionMatrix(((TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)), (TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)))), TransferFunctionMatrix(((TransferFunction(s, s**2 - 1, s), TransferFunction(1, s, s)), (TransferFunction(5, 1, s), TransferFunction(s + 2, s**2 - 1, s)))), TransferFunctionMatrix(((TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)), (TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[ 1 s ] [ s 1 ] [s + 2 5 ]
[ - ------] [------ - ] [------ - ]
[ s 2 ] [ 2 s ] [ 2 1 ]
[ s - 1] [s - 1 ] [s - 1 ]
[ ] + [ ] + [ ]
[s + 2 5 ] [ 5 s + 2 ] [ 1 s ]
[------ - ] [ - ------] [ - ------]
[ 2 1 ] [ 1 2 ] [ s 2 ]
[s - 1 ]{t} [ s - 1]{t} [ s - 1]{t}
>>> MIMOParallel(tfm_a, tfm_b, tfm_c).doit()
TransferFunctionMatrix(((TransferFunction(s**2 + s*(2*s + 2) - 1, s*(s**2 - 1), s), TransferFunction(2*s**2 + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s)), (TransferFunction(s**2 + s*(s + 2) + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s), TransferFunction(5*s**2 + 2*s - 3, s**2 - 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 2 / 2 \ ]
[ s + s*(2*s + 2) - 1 2*s + 5*s*\s - 1/ - 1]
[ -------------------- -----------------------]
[ / 2 \ / 2 \ ]
[ s*\s - 1/ s*\s - 1/ ]
[ ]
[ 2 / 2 \ 2 ]
[s + s*(s + 2) + 5*s*\s - 1/ - 1 5*s + 2*s - 3 ]
[--------------------------------- -------------- ]
[ / 2 \ 2 ]
[ s*\s - 1/ s - 1 ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Parallel, MIMOSeries
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, MIMOParallel)
cls._check_args(args)
if any(arg.shape != args[0].shape for arg in args):
raise TypeError("Shape of all the args is not equal.")
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the systems.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOParallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(p**2, p**2 - 1, p)
>>> tfm_a = TransferFunctionMatrix([[G1, G2], [G3, G4]])
>>> tfm_b = TransferFunctionMatrix([[G2, G1], [G4, G3]])
>>> MIMOParallel(tfm_a, tfm_b).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the parallel system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the parallel system."""
return self.args[0].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOParallel, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
>>> MIMOParallel(tfm_1, tfm_2).doit()
TransferFunctionMatrix(((TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in self.args)
res = MatAdd(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
self_arg_list = list(self.args)
return MIMOParallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
arg_list = list(other.args)
return MIMOSeries(*arg_list, self)
return MIMOSeries(other, self)
def __neg__(self):
arg_list = [-arg for arg in list(self.args)]
return MIMOParallel(*arg_list)
class Feedback(SISOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
SISO input/output systems.
The first argument, ``sys1``, is the feedforward part of the closed-loop
system or in simple words, the dynamical model representing the process
to be controlled. The second argument, ``sys2``, is the feedback system
and controls the fed back signal to ``sys1``. Both ``sys1`` and ``sys2``
can either be ``Series`` or ``TransferFunction`` objects.
Parameters
==========
sys1 : Series, TransferFunction
The feedforward path system.
sys2 : Series, TransferFunction, optional
The feedback path system (often a feedback controller).
It is the model sitting on the feedback path.
If not specified explicitly, the sys2 is
assumed to be unit (1.0) transfer function.
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
When a combination of ``sys1`` and ``sys2`` yields
zero denominator.
TypeError
When either ``sys1`` or ``sys2`` is not a ``Series`` or a
``TransferFunction`` object.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1
Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
>>> F1.var
s
>>> F1.args
(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
You can get the feedforward and feedback path systems by using ``.sys1`` and ``.sys2`` respectively.
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
You can get the resultant closed loop transfer function obtained by negative feedback
interconnection using ``.doit()`` method.
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> C = TransferFunction(5*s + 10, s + 10, s)
>>> F2 = Feedback(G*C, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s)
To negate a ``Feedback`` object, the ``-`` operator can be prepended:
>>> -F1
Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(10 - 5*s, s + 7, s), -1)
>>> -F2
Feedback(Series(TransferFunction(-1, 1, s), TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s)), TransferFunction(-1, 1, s), -1)
See Also
========
MIMOFeedback, Series, Parallel
"""
def __new__(cls, sys1, sys2=None, sign=-1):
if not sys2:
sys2 = TransferFunction(1, 1, sys1.var)
if not (isinstance(sys1, (TransferFunction, Series))
and isinstance(sys2, (TransferFunction, Series))):
raise TypeError("Unsupported type for `sys1` or `sys2` of Feedback.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if Mul(sys1.to_expr(), sys2.to_expr()).simplify() == sign:
raise ValueError("The equivalent system will have zero denominator.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
"""
Returns the feedforward system of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys1
TransferFunction(1, 1, p)
"""
return self.args[0]
@property
def sys2(self):
"""
Returns the feedback controller of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys2
Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p))
"""
return self.args[1]
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.var
s
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.var
p
"""
return self.sys1.var
@property
def sign(self):
"""
Returns the type of MIMO Feedback model. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
"""
Returns the sensitivity function of the feedback loop.
Sensitivity of a Feedback system is the ratio
of change in the open loop gain to the change in
the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - p, p + 2, p)
>>> F_1 = Feedback(P, C)
>>> F_1.sensitivity
1/((1 - p)*(5*p + 10)/((p + 2)*(p + 10)) + 1)
"""
return 1/(1 - self.sign*self.sys1.to_expr()*self.sys2.to_expr())
def doit(self, cancel=False, expand=False, **kwargs):
"""
Returns the resultant transfer function obtained by the
feedback interconnection.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> F2 = Feedback(G, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s)
Use kwarg ``expand=True`` to expand the resultant transfer function.
Use ``cancel=True`` to cancel out the common terms in numerator and
denominator.
>>> F2.doit(cancel=True, expand=True)
TransferFunction(2*s**2 + 5*s + 1, 3*s**2 + 7*s + 4, s)
>>> F2.doit(expand=True)
TransferFunction(2*s**4 + 9*s**3 + 17*s**2 + 17*s + 3, 3*s**4 + 13*s**3 + 27*s**2 + 29*s + 12, s)
"""
arg_list = list(self.sys1.args) if isinstance(self.sys1, Series) else [self.sys1]
# F_n and F_d are resultant TFs of num and den of Feedback.
F_n, unit = self.sys1.doit(), TransferFunction(1, 1, self.sys1.var)
if self.sign == -1:
F_d = Parallel(unit, Series(self.sys2, *arg_list)).doit()
else:
F_d = Parallel(unit, -Series(self.sys2, *arg_list)).doit()
_resultant_tf = TransferFunction(F_n.num * F_d.den, F_n.den * F_d.num, F_n.var)
if cancel:
_resultant_tf = _resultant_tf.simplify()
if expand:
_resultant_tf = _resultant_tf.expand()
return _resultant_tf
def _eval_rewrite_as_TransferFunction(self, num, den, sign, **kwargs):
return self.doit()
def __neg__(self):
return Feedback(-self.sys1, -self.sys2, self.sign)
def _is_invertible(a, b, sign):
"""
Checks whether a given pair of MIMO
systems passed is invertible or not.
"""
_mat = eye(a.num_outputs) - sign*(a.doit()._expr_mat)*(b.doit()._expr_mat)
_det = _mat.det()
return _det != 0
class MIMOFeedback(MIMOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
MIMO input/output systems.
Parameters
==========
sys1 : MIMOSeries, TransferFunctionMatrix
The MIMO system placed on the feedforward path.
sys2 : MIMOSeries, TransferFunctionMatrix
The system placed on the feedback path
(often a feedback controller).
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
Forward path model should have an equal number of inputs/outputs
to the feedback path outputs/inputs.
When product of ``sys1`` and ``sys2`` is not a square matrix.
When the equivalent MIMO system is not invertible.
TypeError
When either ``sys1`` or ``sys2`` is not a ``MIMOSeries`` or a
``TransferFunctionMatrix`` object.
Examples
========
>>> from sympy import Matrix, pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOFeedback
>>> plant_mat = Matrix([[1, 1/s], [0, 1]])
>>> controller_mat = Matrix([[10, 0], [0, 10]]) # Constant Gain
>>> plant = TransferFunctionMatrix.from_Matrix(plant_mat, s)
>>> controller = TransferFunctionMatrix.from_Matrix(controller_mat, s)
>>> feedback = MIMOFeedback(plant, controller) # Negative Feedback (default)
>>> pprint(feedback, use_unicode=False)
/ [1 1] [10 0 ] \-1 [1 1]
| [- -] [-- - ] | [- -]
| [1 s] [1 1 ] | [1 s]
|I + [ ] *[ ] | * [ ]
| [0 1] [0 10] | [0 1]
| [- -] [- --] | [- -]
\ [1 1]{t} [1 1 ]{t}/ [1 1]{t}
To get the equivalent system matrix, use either ``doit`` or ``rewrite`` method.
>>> pprint(feedback.doit(), use_unicode=False)
[1 1 ]
[-- -----]
[11 121*s]
[ ]
[0 1 ]
[- -- ]
[1 11 ]{t}
To negate the ``MIMOFeedback`` object, use ``-`` operator.
>>> neg_feedback = -feedback
>>> pprint(neg_feedback.doit(), use_unicode=False)
[-1 -1 ]
[--- -----]
[ 11 121*s]
[ ]
[ 0 -1 ]
[ - --- ]
[ 1 11 ]{t}
See Also
========
Feedback, MIMOSeries, MIMOParallel
"""
def __new__(cls, sys1, sys2, sign=-1):
if not (isinstance(sys1, (TransferFunctionMatrix, MIMOSeries))
and isinstance(sys2, (TransferFunctionMatrix, MIMOSeries))):
raise TypeError("Unsupported type for `sys1` or `sys2` of MIMO Feedback.")
if sys1.num_inputs != sys2.num_outputs or \
sys1.num_outputs != sys2.num_inputs:
raise ValueError("Product of `sys1` and `sys2` "
"must yield a square matrix.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if not _is_invertible(sys1, sys2, sign):
raise ValueError("Non-Invertible system inputted.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
r"""
Returns the system placed on the feedforward path of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2 + s + 1, s**2 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> F_1.sys1
TransferFunctionMatrix(((TransferFunction(s**2 + s + 1, s**2 - s + 1, s), TransferFunction(1, s, s)), (TransferFunction(1, s, s), TransferFunction(s**2 + s + 1, s**2 - s + 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[s + s + 1 1 ]
[---------- - ]
[ 2 s ]
[s - s + 1 ]
[ ]
[ 2 ]
[ 1 s + s + 1]
[ - ----------]
[ s 2 ]
[ s - s + 1]{t}
"""
return self.args[0]
@property
def sys2(self):
r"""
Returns the feedback controller of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2, s**3 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2)
>>> F_1.sys2
TransferFunctionMatrix(((TransferFunction(s**2, s**3 - s + 1, s), TransferFunction(1, 1, s)), (TransferFunction(1, 1, s), TransferFunction(1, s, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[ s 1]
[---------- -]
[ 3 1]
[s - s + 1 ]
[ ]
[ 1 1]
[ - -]
[ 1 s]{t}
"""
return self.args[1]
@property
def var(self):
r"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the MIMO feedback loop.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_1.var
p
"""
return self.sys1.var
@property
def sign(self):
r"""
Returns the type of feedback interconnection of two models. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
r"""
Returns the sensitivity function matrix of the feedback loop.
Sensitivity of a closed-loop system is the ratio of change
in the open loop gain to the change in the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_2 = MIMOFeedback(sys1, sys2) # Negative feedback
>>> pprint(F_1.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[- p + 3*p - 4*p + 3*p - 1 p - 2*p + 3*p - 3*p + 1 ]
[---------------------------- -----------------------------]
[ 4 3 2 5 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3*p]
[ ]
[ 4 3 2 3 2 ]
[ p - p - p + p 3*p - 6*p + 4*p - 1 ]
[ -------------------------- -------------------------- ]
[ 4 3 2 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3 ]
>>> pprint(F_2.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[p - 3*p + 2*p + p - 1 p - 2*p + 3*p - 3*p + 1]
[------------------------ --------------------------]
[ 4 3 5 4 2 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - p ]
[ ]
[ 4 3 2 4 3 ]
[ p - p - p + p 2*p - 3*p + 2*p - 1 ]
[ ------------------- --------------------- ]
[ 4 3 4 3 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - 1 ]
"""
_sys1_mat = self.sys1.doit()._expr_mat
_sys2_mat = self.sys2.doit()._expr_mat
return (eye(self.sys1.num_inputs) - \
self.sign*_sys1_mat*_sys2_mat).inv()
def doit(self, cancel=True, expand=False, **kwargs):
r"""
Returns the resultant transfer function matrix obtained by the
feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s, 1 - s, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(5, 1, s)
>>> tf4 = TransferFunction(s - 1, s, s)
>>> tf5 = TransferFunction(0, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf5], [tf5, tf5]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> pprint(F_1, use_unicode=False)
/ [ s 1 ] [5 0] \-1 [ s 1 ]
| [----- - ] [- -] | [----- - ]
| [1 - s s ] [1 1] | [1 - s s ]
|I - [ ] *[ ] | * [ ]
| [ 5 s - 1] [0 0] | [ 5 s - 1]
| [ - -----] [- -] | [ - -----]
\ [ 1 s ]{t} [1 1]{t}/ [ 1 s ]{t}
>>> pprint(F_1.doit(), use_unicode=False)
[ -s 1 - s ]
[ ------- ----------- ]
[ 6*s - 1 s*(1 - 6*s) ]
[ ]
[25*s*(s - 1) + 5*(1 - s)*(6*s - 1) (s - 1)*(6*s + 24)]
[---------------------------------- ------------------]
[ (1 - s)*(6*s - 1) s*(6*s - 1) ]{t}
If the user wants the resultant ``TransferFunctionMatrix`` object without
canceling the common factors then the ``cancel`` kwarg should be passed ``False``.
>>> pprint(F_1.doit(cancel=False), use_unicode=False)
[ 25*s*(1 - s) 25 - 25*s ]
[ -------------------- -------------- ]
[ 25*(1 - 6*s)*(1 - s) 25*s*(1 - 6*s) ]
[ ]
[s*(25*s - 25) + 5*(1 - s)*(6*s - 1) s*(s - 1)*(6*s - 1) + s*(25*s - 25)]
[----------------------------------- -----------------------------------]
[ (1 - s)*(6*s - 1) 2 ]
[ s *(6*s - 1) ]{t}
If the user wants the expanded form of the resultant transfer function matrix,
the ``expand`` kwarg should be passed as ``True``.
>>> pprint(F_1.doit(expand=True), use_unicode=False)
[ -s 1 - s ]
[ ------- ---------- ]
[ 6*s - 1 2 ]
[ - 6*s + s ]
[ ]
[ 2 2 ]
[- 5*s + 10*s - 5 6*s + 18*s - 24]
[----------------- ----------------]
[ 2 2 ]
[ - 6*s + 7*s - 1 6*s - s ]{t}
"""
_mat = self.sensitivity * self.sys1.doit()._expr_mat
_resultant_tfm = _to_TFM(_mat, self.var)
if cancel:
_resultant_tfm = _resultant_tfm.simplify()
if expand:
_resultant_tfm = _resultant_tfm.expand()
return _resultant_tfm
def _eval_rewrite_as_TransferFunctionMatrix(self, sys1, sys2, sign, **kwargs):
return self.doit()
def __neg__(self):
return MIMOFeedback(-self.sys1, -self.sys2, self.sign)
def _to_TFM(mat, var):
"""Private method to convert ImmutableMatrix to TransferFunctionMatrix efficiently"""
to_tf = lambda expr: TransferFunction.from_rational_expression(expr, var)
arg = [[to_tf(expr) for expr in row] for row in mat.tolist()]
return TransferFunctionMatrix(arg)
class TransferFunctionMatrix(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is only one argument, ``arg`` which is also the compulsory argument.
``arg`` is expected to be strictly of the type list of lists
which holds the transfer functions or reducible to transfer functions.
Parameters
==========
arg : Nested ``List`` (strictly).
Users are expected to input a nested list of ``TransferFunction``, ``Series``
and/or ``Parallel`` objects.
Examples
========
.. note::
``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects.
>>> from sympy.abc import s, p, a
>>> from sympy import pprint
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s)
>>> tf_3 = TransferFunction(3, s + 2, s)
>>> tf_4 = TransferFunction(-a + p, 9*s - 9, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)))
>>> tfm_1.var
s
>>> tfm_1.num_inputs
1
>>> tfm_1.num_outputs
3
>>> tfm_1.shape
(3, 1)
>>> tfm_1.args
(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),)
>>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]])
>>> tfm_2
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions
>>> tfm_2.transpose()
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(_, use_unicode=False)
[ 4 ]
[ a + s p - 3*p + 2 3 ]
[---------- ------------ ----- ]
[ 2 p + s s + 2 ]
[s + s + 1 ]
[ ]
[ 4 ]
[ -3 -a - s - p + 3*p - 2]
[ ----- ---------- --------------]
[ s + 2 2 p + s ]
[ s + s + 1 ]{t}
>>> tf_5 = TransferFunction(5, s, s)
>>> tf_6 = TransferFunction(5*s, (2 + s**2), s)
>>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s)
>>> tf_8 = TransferFunction(5, 1, s)
>>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]])
>>> tfm_3
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))))
>>> pprint(tfm_3, use_unicode=False)
[ 5 5*s ]
[ - ------]
[ s 2 ]
[ s + 2]
[ ]
[ 5 5 ]
[---------- - ]
[ / 2 \ 1 ]
[s*\s + 2/ ]{t}
>>> tfm_3.var
s
>>> tfm_3.shape
(2, 2)
>>> tfm_3.num_outputs
2
>>> tfm_3.num_inputs
2
>>> tfm_3.args
(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),)
To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation.
>>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes
TransferFunction(5, s*(s**2 + 2), s)
>>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col.
TransferFunction(5, s, s)
>>> tfm_3[:, 0] # gives the first column
TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),)))
>>> pprint(_, use_unicode=False)
[ 5 ]
[ - ]
[ s ]
[ ]
[ 5 ]
[----------]
[ / 2 \]
[s*\s + 2/]{t}
>>> tfm_3[0, :] # gives the first row
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),))
>>> pprint(_, use_unicode=False)
[5 5*s ]
[- ------]
[s 2 ]
[ s + 2]{t}
To negate a transfer function matrix, ``-`` operator can be prepended:
>>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]])
>>> -tfm_4
TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),)))
>>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]])
>>> -tfm_5
TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s))))
``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not
mutate your original ``TransferFunctionMatrix``.
>>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2.
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ a + s -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -a - s ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
>>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
``subs()`` also supports multiple substitutions.
>>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1
TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ s + 1 -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -s - 1 ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using
``doit()``.
>>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]])
>>> tfm_6
TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),))
>>> pprint(tfm_6, use_unicode=False)
[ -a + p 3 -a + p 3 ]
[-------*----- ------- + -----]
[9*s - 9 s + 2 9*s - 9 s + 2]{t}
>>> tfm_6.doit()
TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),))
>>> pprint(_, use_unicode=False)
[ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27]
[----------------- ----------------------------]
[(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t}
>>> tf_9 = TransferFunction(1, s, s)
>>> tf_10 = TransferFunction(1, s**2, s)
>>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]])
>>> tfm_7
TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s)))))
>>> pprint(tfm_7, use_unicode=False)
[ 1 1 ]
[---- - ]
[ 2 s ]
[s*s ]
[ ]
[ 1 1 1]
[ -- -- + -]
[ 2 2 s]
[ s s ]{t}
>>> tfm_7.doit()
TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s))))
>>> pprint(_, use_unicode=False)
[1 1 ]
[-- - ]
[ 3 s ]
[s ]
[ ]
[ 2 ]
[1 s + s]
[-- ------]
[ 2 3 ]
[s s ]{t}
Addition, subtraction, and multiplication of transfer function matrices can form
unevaluated ``Series`` or ``Parallel`` objects.
- For addition and subtraction:
All the transfer function matrices must have the same shape.
- For multiplication (C = A * B):
The number of inputs of the first transfer function matrix (A) must be equal to the
number of outputs of the second transfer function matrix (B).
Also, use pretty-printing (``pprint``) to analyse better.
>>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]])
>>> tfm_9 = TransferFunctionMatrix([[-tf_3]])
>>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]])
>>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]])
>>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]])
>>> tfm_8 + tfm_10
MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))))
>>> pprint(_, use_unicode=False)
[ 3 ] [ a + s ]
[ ----- ] [ ---------- ]
[ s + 2 ] [ 2 ]
[ ] [ s + s + 1 ]
[ 4 ] [ ]
[p - 3*p + 2] [ 4 ]
[------------] + [p - 3*p + 2]
[ p + s ] [------------]
[ ] [ p + s ]
[ -a - s ] [ ]
[ ---------- ] [ -a + p ]
[ 2 ] [ ------- ]
[ s + s + 1 ]{t} [ 9*s - 9 ]{t}
>>> -tfm_10 - tfm_8
MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),))))
>>> pprint(_, use_unicode=False)
[ -a - s ] [ -3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [- p + 3*p - 2]
[- p + 3*p - 2] + [--------------]
[--------------] [ p + s ]
[ p + s ] [ ]
[ ] [ a + s ]
[ a - p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
>>> tfm_12 * tfm_8
MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2]
[ ] *[------------]
[ 4 ] [ p + s ]
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_12 * tfm_8 * tfm_9
MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2] [ -3 ]
[ ] *[------------] *[-----]
[ 4 ] [ p + s ] [s + 2]{t}
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_10 + tfm_8*tfm_9
MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),)))))
>>> pprint(_, use_unicode=False)
[ a + s ] [ 3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [p - 3*p + 2] [ -3 ]
[p - 3*p + 2] + [------------] *[-----]
[------------] [ p + s ] [s + 2]{t}
[ p + s ] [ ]
[ ] [ -a - s ]
[ -a + p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function matrix using ``.doit()`` method or by
``.rewrite(TransferFunctionMatrix)``.
>>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit()
TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),)))
>>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix)
TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),)))
See Also
========
TransferFunction, MIMOSeries, MIMOParallel, Feedback
"""
def __new__(cls, arg):
expr_mat_arg = []
try:
var = arg[0][0].var
except TypeError:
raise ValueError("`arg` param in TransferFunctionMatrix should "
"strictly be a nested list containing TransferFunction objects.")
for row_index, row in enumerate(arg):
temp = []
for col_index, element in enumerate(row):
if not isinstance(element, SISOLinearTimeInvariant):
raise TypeError("Each element is expected to be of type `SISOLinearTimeInvariant`.")
if var != element.var:
raise ValueError("Conflicting value(s) found for `var`. All TransferFunction instances in "
"TransferFunctionMatrix should use the same complex variable in Laplace domain.")
temp.append(element.to_expr())
expr_mat_arg.append(temp)
if isinstance(arg, (list, Tuple)):
# Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested Python tuple
arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False)
obj = super(TransferFunctionMatrix, cls).__new__(cls, arg)
obj._expr_mat = ImmutableMatrix(expr_mat_arg)
return obj
@classmethod
def from_Matrix(cls, matrix, var):
"""
Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix of ``Expr`` objects.
Parameters
==========
matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements.
var : Symbol
Complex variable of the Laplace transform which will be used by the
all the ``TransferFunction`` objects in the ``TransferFunctionMatrix``.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> M = Matrix([[s, 1/s], [1/(s+1), s]])
>>> M_tf = TransferFunctionMatrix.from_Matrix(M, s)
>>> pprint(M_tf, use_unicode=False)
[ s 1]
[ - -]
[ 1 s]
[ ]
[ 1 s]
[----- -]
[s + 1 1]{t}
>>> M_tf.elem_poles()
[[[], [0]], [[-1], []]]
>>> M_tf.elem_zeros()
[[[0], []], [[], [0]]]
"""
return _to_TFM(matrix, var)
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions or
``Series``/``Parallel`` objects in a transfer function matrix.
Examples
========
>>> from sympy.abc import p, s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> S1 = Series(G1, G2)
>>> S2 = Series(-G3, Parallel(G2, -G1))
>>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> tfm1.var
p
>>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]])
>>> tfm2.var
p
>>> tfm3 = TransferFunctionMatrix([[G4]])
>>> tfm3.var
s
"""
return self.args[0][0][0].var
@property
def num_inputs(self):
"""
Returns the number of inputs of the system.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> G1 = TransferFunction(s + 3, s**2 - 3, s)
>>> G2 = TransferFunction(4, s**2, s)
>>> G3 = TransferFunction(p**2 + s**2, p - 3, s)
>>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]])
>>> tfm_1.num_inputs
3
See Also
========
num_outputs
"""
return self._expr_mat.shape[1]
@property
def num_outputs(self):
"""
Returns the number of outputs of the system.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix
>>> M_1 = Matrix([[s], [1/s]])
>>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s)
>>> print(TFM)
TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),)))
>>> TFM.num_outputs
2
See Also
========
num_inputs
"""
return self._expr_mat.shape[0]
@property
def shape(self):
"""
Returns the shape of the transfer function matrix, that is, ``(# of outputs, # of inputs)``.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p)
>>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p)
>>> tf3 = TransferFunction(3, 4, p)
>>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]])
>>> tfm1.shape
(1, 2)
>>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]])
>>> tfm2.shape
(2, 2)
"""
return self._expr_mat.shape
def __neg__(self):
neg = -self._expr_mat
return _to_TFM(neg, self.var)
@_check_other_MIMO
def __add__(self, other):
if not isinstance(other, MIMOParallel):
return MIMOParallel(self, other)
other_arg_list = list(other.args)
return MIMOParallel(self, *other_arg_list)
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
@_check_other_MIMO
def __mul__(self, other):
if not isinstance(other, MIMOSeries):
return MIMOSeries(other, self)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, self)
def __getitem__(self, key):
trunc = self._expr_mat.__getitem__(key)
if isinstance(trunc, ImmutableMatrix):
return _to_TFM(trunc, self.var)
return TransferFunction.from_rational_expression(trunc, self.var)
def transpose(self):
"""Returns the transpose of the ``TransferFunctionMatrix`` (switched input and output layers)."""
transposed_mat = self._expr_mat.transpose()
return _to_TFM(transposed_mat, self.var)
def elem_poles(self):
"""
Returns the poles of each element of the ``TransferFunctionMatrix``.
.. note::
Actual poles of a MIMO system are NOT the poles of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_poles()
[[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]]
See Also
========
elem_zeros
"""
return [[element.poles() for element in row] for row in self.doit().args[0]]
def elem_zeros(self):
"""
Returns the zeros of each element of the ``TransferFunctionMatrix``.
.. note::
Actual zeros of a MIMO system are NOT the zeros of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_zeros()
[[[], [-6]], [[-3], [4, 5]]]
See Also
========
elem_poles
"""
return [[element.zeros() for element in row] for row in self.doit().args[0]]
def _flat(self):
"""Returns flattened list of args in TransferFunctionMatrix"""
return [elem for tup in self.args[0] for elem in tup]
def _eval_evalf(self, prec):
"""Calls evalf() on each transfer function in the transfer function matrix"""
dps = prec_to_dps(prec)
mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=dps))
return _to_TFM(mat, self.var)
def _eval_simplify(self, **kwargs):
"""Simplifies the transfer function matrix"""
simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False))
return _to_TFM(simp_mat, self.var)
def expand(self, **hints):
"""Expands the transfer function matrix"""
expand_mat = self._expr_mat.expand(**hints)
return _to_TFM(expand_mat, self.var)
|
0ab3d849e745e3c16bc311ea80897a4943945c136635a322458d8b1da03f8940 | from sympy.core.numbers import I
from sympy.functions.elementary.exponential import (exp, log)
from sympy.polys.partfrac import apart
from sympy.core.symbol import Dummy
from sympy.external import import_module
from sympy.functions import arg, Abs
from sympy.integrals.transforms import _fast_inverse_laplace
from sympy.physics.control.lti import SISOLinearTimeInvariant
from sympy.plotting.plot import LineOver1DRangeSeries
from sympy.polys.polytools import Poly
from sympy.printing.latex import latex
__all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
'step_response_numerical_data', 'step_response_plot',
'impulse_response_numerical_data', 'impulse_response_plot',
'ramp_response_numerical_data', 'ramp_response_plot',
'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,))
numpy = import_module('numpy')
if matplotlib:
plt = matplotlib.pyplot
if numpy:
np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
def _check_system(system):
"""Function to check whether the dynamical system passed for plots is
compatible or not."""
if not isinstance(system, SISOLinearTimeInvariant):
raise NotImplementedError("Only SISO LTI systems are currently supported.")
sys = system.to_expr()
len_free_symbols = len(sys.free_symbols)
if len_free_symbols > 1:
raise ValueError("Extra degree of freedom found. Make sure"
" that there are no free symbols in the dynamical system other"
" than the variable of Laplace transform.")
if sys.has(exp):
raise NotImplementedError("Time delay terms are not supported.")
def pole_zero_numerical_data(system):
"""
Returns the numerical data of poles and zeros of the system.
It is internally used by ``pole_zero_plot`` to get the data
for plotting poles and zeros. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the pole-zero data is to be computed.
Returns
=======
tuple : (zeros, poles)
zeros = Zeros of the system. NumPy array of complex numbers.
poles = Poles of the system. NumPy array of complex numbers.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import pole_zero_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> pole_zero_numerical_data(tf1) # doctest: +SKIP
([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
See Also
========
pole_zero_plot
"""
_check_system(system)
system = system.doit() # Get the equivalent TransferFunction object.
num_poly = Poly(system.num, system.var).all_coeffs()
den_poly = Poly(system.den, system.var).all_coeffs()
num_poly = np.array(num_poly, dtype=np.float64)
den_poly = np.array(den_poly, dtype=np.float64)
zeros = np.roots(num_poly)
poles = np.roots(den_poly)
return zeros, poles
def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
show=True, **kwargs):
r"""
Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
A Pole-Zero plot is a graphical representation of a system's poles and
zeros. It is plotted on a complex plane, with circular markers representing
the system's zeros and 'x' shaped markers representing the system's poles.
Parameters
==========
system : SISOLinearTimeInvariant type systems
The system for which the pole-zero plot is to be computed.
pole_color : str, tuple, optional
The color of the pole points on the plot. Default color
is blue. The color can be provided as a matplotlib color string,
or a 3-tuple of floats each in the 0-1 range.
pole_markersize : Number, optional
The size of the markers used to mark the poles in the plot.
Default pole markersize is 10.
zero_color : str, tuple, optional
The color of the zero points on the plot. Default color
is orange. The color can be provided as a matplotlib color string,
or a 3-tuple of floats each in the 0-1 range.
zero_markersize : Number, optional
The size of the markers used to mark the zeros in the plot.
Default zero markersize is 7.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import pole_zero_plot
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> pole_zero_plot(tf1) # doctest: +SKIP
See Also
========
pole_zero_numerical_data
References
==========
.. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
"""
zeros, poles = pole_zero_numerical_data(system)
zero_real = np.real(zeros)
zero_imag = np.imag(zeros)
pole_real = np.real(poles)
pole_imag = np.imag(poles)
plt.plot(pole_real, pole_imag, 'x', mfc='none',
markersize=pole_markersize, color=pole_color)
plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
color=zero_color)
plt.xlabel('Real Axis')
plt.ylabel('Imaginary Axis')
plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def step_response_numerical_data(system, prec=8, lower_limit=0,
upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the step response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the unit step response data is to be computed.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the step response. NumPy array.
y = Amplitude-axis values of the points in the step response. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import step_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> step_response_numerical_data(tf1) # doctest: +SKIP
([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
[0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
See Also
========
step_response_plot
"""
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = system.to_expr()/(system.var)
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def step_response_plot(system, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the unit step response of a continuous-time system. It is
the response of the system when the input signal is a step function.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Step Response is to be computed.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import step_response_plot
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
>>> step_response_plot(tf1) # doctest: +SKIP
See Also
========
impulse_response_plot, ramp_response_plot
References
==========
.. [1] https://www.mathworks.com/help/control/ref/lti.step.html
"""
x, y = step_response_numerical_data(system, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def impulse_response_numerical_data(system, prec=8, lower_limit=0,
upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the impulse response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the impulse response data is to be computed.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the impulse response. NumPy array.
y = Amplitude-axis values of the points in the impulse response. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import impulse_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> impulse_response_numerical_data(tf1) # doctest: +SKIP
([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
[0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
See Also
========
impulse_response_plot
"""
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = system.to_expr()
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the unit impulse response (Input is the Dirac-Delta Function) of a
continuous-time system.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Impulse Response is to be computed.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import impulse_response_plot
>>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
>>> impulse_response_plot(tf1) # doctest: +SKIP
See Also
========
step_response_plot, ramp_response_plot
References
==========
.. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html
"""
x, y = impulse_response_numerical_data(system, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def ramp_response_numerical_data(system, slope=1, prec=8,
lower_limit=0, upper_limit=10, **kwargs):
"""
Returns the numerical values of the points in the ramp response plot
of a SISO continuous-time system. By default, adaptive sampling
is used. If the user wants to instead get an uniformly
sampled response, then ``adaptive`` kwarg should be passed ``False``
and ``nb_of_points`` must be passed as additional kwargs.
Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
for more details.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the ramp response data is to be computed.
slope : Number, optional
The slope of the input ramp function. Defaults to 1.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
kwargs :
Additional keyword arguments are passed to the underlying
:class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
Returns
=======
tuple : (x, y)
x = Time-axis values of the points in the ramp response plot. NumPy array.
y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
When ``lower_limit`` parameter is less than 0.
When ``slope`` is negative.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import ramp_response_numerical_data
>>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
>>> ramp_response_numerical_data(tf1) # doctest: +SKIP
(([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
[1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
See Also
========
ramp_response_plot
"""
if slope < 0:
raise ValueError("Slope must be greater than or equal"
" to zero.")
if lower_limit < 0:
raise ValueError("Lower limit of time must be greater "
"than or equal to zero.")
_check_system(system)
_x = Dummy("x")
expr = (slope*system.to_expr())/((system.var)**2)
expr = apart(expr, system.var, full=True)
_y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
**kwargs).get_points()
def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the ramp response of a continuous-time system.
Ramp function is defined as the straight line
passing through origin ($f(x) = mx$). The slope of
the ramp function can be varied by the user and
the default value is 1.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Ramp Response is to be computed.
slope : Number, optional
The slope of the input ramp function. Defaults to 1.
color : str, tuple, optional
The color of the line. Default is Blue.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
lower_limit : Number, optional
The lower limit of the plot range. Defaults to 0.
upper_limit : Number, optional
The upper limit of the plot range. Defaults to 10.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import ramp_response_plot
>>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
>>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
See Also
========
step_response_plot, ramp_response_plot
References
==========
.. [1] https://en.wikipedia.org/wiki/Ramp_function
"""
x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
plt.plot(x, y, color=color)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
if grid:
plt.grid()
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, **kwargs):
"""
Returns the numerical data of the Bode magnitude plot of the system.
It is internally used by ``bode_magnitude_plot`` to get the data
for plotting Bode magnitude plot. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the data is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
Returns
=======
tuple : (x, y)
x = x-axis values of the Bode magnitude plot.
y = y-axis values of the Bode magnitude plot.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
[-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
See Also
========
bode_magnitude_plot, bode_phase_numerical_data
"""
_check_system(system)
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
mag = 20*log(Abs(w_expr), 10)
return LineOver1DRangeSeries(mag,
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
color='b', show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the Bode magnitude plot of a continuous-time system.
See ``bode_plot`` for all the parameters.
"""
x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
final_exp=final_exp)
plt.plot(x, y, color=color, **kwargs)
plt.xscale('log')
plt.xlabel('Frequency (Hz) [Log Scale]')
plt.ylabel('Magnitude (dB)')
plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
if grid:
plt.grid(True)
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, **kwargs):
"""
Returns the numerical data of the Bode phase plot of the system.
It is internally used by ``bode_phase_plot`` to get the data
for plotting Bode phase plot. Users can use this data to further
analyse the dynamics of the system or plot using a different
backend/plotting-module.
Parameters
==========
system : SISOLinearTimeInvariant
The system for which the Bode phase plot data is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
Returns
=======
tuple : (x, y)
x = x-axis values of the Bode phase plot.
y = y-axis values of the Bode phase plot.
Raises
======
NotImplementedError
When a SISO LTI system is not passed.
When time delay terms are present in the system.
ValueError
When more than one free symbol is present in the system.
The only variable in the transfer function should be
the variable of the Laplace transform.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_phase_numerical_data
>>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
>>> bode_phase_numerical_data(tf1) # doctest: +SKIP
([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
[-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
See Also
========
bode_magnitude_plot, bode_phase_numerical_data
"""
_check_system(system)
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
phase = arg(w_expr)
return LineOver1DRangeSeries(phase,
(_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
def bode_phase_plot(system, initial_exp=-5, final_exp=5,
color='b', show_axes=False, grid=True, show=True, **kwargs):
r"""
Returns the Bode phase plot of a continuous-time system.
See ``bode_plot`` for all the parameters.
"""
x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
final_exp=final_exp)
plt.plot(x, y, color=color, **kwargs)
plt.xscale('log')
plt.xlabel('Frequency (Hz) [Log Scale]')
plt.ylabel('Phase (rad)')
plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
if grid:
plt.grid(True)
if show_axes:
plt.axhline(0, color='black')
plt.axvline(0, color='black')
if show:
plt.show()
return
return plt
def bode_plot(system, initial_exp=-5, final_exp=5,
grid=True, show_axes=False, show=True, **kwargs):
r"""
Returns the Bode phase and magnitude plots of a continuous-time system.
Parameters
==========
system : SISOLinearTimeInvariant type
The LTI SISO system for which the Bode Plot is to be computed.
initial_exp : Number, optional
The initial exponent of 10 of the semilog plot. Defaults to -5.
final_exp : Number, optional
The final exponent of 10 of the semilog plot. Defaults to 5.
show : boolean, optional
If ``True``, the plot will be displayed otherwise
the equivalent matplotlib ``plot`` object will be returned.
Defaults to True.
prec : int, optional
The decimal point precision for the point coordinate values.
Defaults to 8.
grid : boolean, optional
If ``True``, the plot will have a grid. Defaults to True.
show_axes : boolean, optional
If ``True``, the coordinate axes will be shown. Defaults to False.
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy.physics.control.control_plots import bode_plot
>>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
>>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
See Also
========
bode_magnitude_plot, bode_phase_plot
"""
plt.subplot(211)
bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
show=False, grid=grid, show_axes=show_axes,
**kwargs).title(f'Bode Plot of ${latex(system)}$', pad=20)
plt.subplot(212)
bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
show=False, grid=grid, show_axes=show_axes, **kwargs).title(None)
if show:
plt.show()
return
return plt
|
4ba7cf9246267d7f042c139cf44493fbc5e743582da523817ddd8ac0b18a758a | """A cache for storing small matrices in multiple formats."""
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.power import Pow
from sympy.functions.elementary.exponential import exp
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.matrixutils import (
to_sympy, to_numpy, to_scipy_sparse
)
class MatrixCache:
"""A cache for small matrices in different formats.
This class takes small matrices in the standard ``sympy.Matrix`` format,
and then converts these to both ``numpy.matrix`` and
``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for
future recovery.
"""
def __init__(self, dtype='complex'):
self._cache = {}
self.dtype = dtype
def cache_matrix(self, name, m):
"""Cache a matrix by its name.
Parameters
----------
name : str
A descriptive name for the matrix, like "identity2".
m : list of lists
The raw matrix data as a SymPy Matrix.
"""
try:
self._sympy_matrix(name, m)
except ImportError:
pass
try:
self._numpy_matrix(name, m)
except ImportError:
pass
try:
self._scipy_sparse_matrix(name, m)
except ImportError:
pass
def get_matrix(self, name, format):
"""Get a cached matrix by name and format.
Parameters
----------
name : str
A descriptive name for the matrix, like "identity2".
format : str
The format desired ('sympy', 'numpy', 'scipy.sparse')
"""
m = self._cache.get((name, format))
if m is not None:
return m
raise NotImplementedError(
'Matrix with name %s and format %s is not available.' %
(name, format)
)
def _store_matrix(self, name, format, m):
self._cache[(name, format)] = m
def _sympy_matrix(self, name, m):
self._store_matrix(name, 'sympy', to_sympy(m))
def _numpy_matrix(self, name, m):
m = to_numpy(m, dtype=self.dtype)
self._store_matrix(name, 'numpy', m)
def _scipy_sparse_matrix(self, name, m):
# TODO: explore different sparse formats. But sparse.kron will use
# coo in most cases, so we use that here.
m = to_scipy_sparse(m, dtype=self.dtype)
self._store_matrix(name, 'scipy.sparse', m)
sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)
# Save the common matrices that we will need
matrix_cache = MatrixCache()
matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]]))
matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1|
matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0|
matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0|
matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1|
matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]]))
matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]]))
matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]]))
matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]]))
matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]]))
matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]]))
matrix_cache.cache_matrix(
'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]))
matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
|
37acee57667106f33fe8b51a52103a4a3454bd9e4b791ca692dba024f0bc5ece | """Shor's algorithm and helper functions.
Todo:
* Get the CMod gate working again using the new Gate API.
* Fix everything.
* Update docstrings and reformat.
"""
import math
import random
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import log
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.core.numbers import igcd
from sympy.ntheory import continued_fraction_periodic as continued_fraction
from sympy.utilities.iterables import variations
from sympy.physics.quantum.gate import Gate
from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qft import QFT
from sympy.physics.quantum.qexpr import QuantumError
class OrderFindingException(QuantumError):
pass
class CMod(Gate):
"""A controlled mod gate.
This is black box controlled Mod function for use by shor's algorithm.
TODO: implement a decompose property that returns how to do this in terms
of elementary gates
"""
@classmethod
def _eval_args(cls, args):
# t = args[0]
# a = args[1]
# N = args[2]
raise NotImplementedError('The CMod gate has not been completed.')
@property
def t(self):
"""Size of 1/2 input register. First 1/2 holds output."""
return self.label[0]
@property
def a(self):
"""Base of the controlled mod function."""
return self.label[1]
@property
def N(self):
"""N is the type of modular arithmetic we are doing."""
return self.label[2]
def _apply_operator_Qubit(self, qubits, **options):
"""
This directly calculates the controlled mod of the second half of
the register and puts it in the second
This will look pretty when we get Tensor Symbolically working
"""
n = 1
k = 0
# Determine the value stored in high memory.
for i in range(self.t):
k += n*qubits[self.t + i]
n *= 2
# The value to go in low memory will be out.
out = int(self.a**k % self.N)
# Create array for new qbit-ket which will have high memory unaffected
outarray = list(qubits.args[0][:self.t])
# Place out in low memory
for i in reversed(range(self.t)):
outarray.append((out >> i) & 1)
return Qubit(*outarray)
def shor(N):
"""This function implements Shor's factoring algorithm on the Integer N
The algorithm starts by picking a random number (a) and seeing if it is
coprime with N. If it isn't, then the gcd of the two numbers is a factor
and we are done. Otherwise, it begins the period_finding subroutine which
finds the period of a in modulo N arithmetic. This period, if even, can
be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1.
These values are returned.
"""
a = random.randrange(N - 2) + 2
if igcd(N, a) != 1:
return igcd(N, a)
r = period_find(a, N)
if r % 2 == 1:
shor(N)
answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N))
return answer
def getr(x, y, N):
fraction = continued_fraction(x, y)
# Now convert into r
total = ratioize(fraction, N)
return total
def ratioize(list, N):
if list[0] > N:
return S.Zero
if len(list) == 1:
return list[0]
return list[0] + ratioize(list[1:], N)
def period_find(a, N):
"""Finds the period of a in modulo N arithmetic
This is quantum part of Shor's algorithm. It takes two registers,
puts first in superposition of states with Hadamards so: ``|k>|0>``
with k being all possible choices. It then does a controlled mod and
a QFT to determine the order of a.
"""
epsilon = .5
# picks out t's such that maintains accuracy within epsilon
t = int(2*math.ceil(log(N, 2)))
# make the first half of register be 0's |000...000>
start = [0 for x in range(t)]
# Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0>
factor = 1/sqrt(2**t)
qubits = 0
for arr in variations(range(2), t, repetition=True):
qbitArray = list(arr) + start
qubits = qubits + Qubit(*qbitArray)
circuit = (factor*qubits).expand()
# Controlled second half of register so that we have:
# |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n>
circuit = CMod(t, a, N)*circuit
# will measure first half of register giving one of the a**k%N's
circuit = qapply(circuit)
for i in range(t):
circuit = measure_partial_oneshot(circuit, i)
# Now apply Inverse Quantum Fourier Transform on the second half of the register
circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True)
for i in range(t):
circuit = measure_partial_oneshot(circuit, i + t)
if isinstance(circuit, Qubit):
register = circuit
elif isinstance(circuit, Mul):
register = circuit.args[-1]
else:
register = circuit.args[-1].args[-1]
n = 1
answer = 0
for i in range(len(register)/2):
answer += n*register[i + t]
n = n << 1
if answer == 0:
raise OrderFindingException(
"Order finder returned 0. Happens with chance %f" % epsilon)
#turn answer into r using continued fractions
g = getr(answer, 2**t, N)
return g
|
232eb2778d6510db82794e632d763b3b713f49cdd200708ddd7e5b134b108a25 | """An implementation of qubits and gates acting on them.
Todo:
* Update docstrings.
* Update tests.
* Implement apply using decompose.
* Implement represent using decompose or something smarter. For this to
work we first have to implement represent for SWAP.
* Decide if we want upper index to be inclusive in the constructor.
* Fix the printing of Rk gates in plotting.
"""
from sympy.core.expr import Expr
from sympy.core.numbers import (I, Integer, pi)
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import exp
from sympy.matrices.dense import Matrix
from sympy.functions import sqrt
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qexpr import QuantumError, QExpr
from sympy.matrices import eye
from sympy.physics.quantum.tensorproduct import matrix_tensor_product
from sympy.physics.quantum.gate import (
Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate
)
__all__ = [
'QFT',
'IQFT',
'RkGate',
'Rk'
]
#-----------------------------------------------------------------------------
# Fourier stuff
#-----------------------------------------------------------------------------
class RkGate(OneQubitGate):
"""This is the R_k gate of the QTF."""
gate_name = 'Rk'
gate_name_latex = 'R'
def __new__(cls, *args):
if len(args) != 2:
raise QuantumError(
'Rk gates only take two arguments, got: %r' % args
)
# For small k, Rk gates simplify to other gates, using these
# substitutions give us familiar results for the QFT for small numbers
# of qubits.
target = args[0]
k = args[1]
if k == 1:
return ZGate(target)
elif k == 2:
return PhaseGate(target)
elif k == 3:
return TGate(target)
args = cls._eval_args(args)
inst = Expr.__new__(cls, *args)
inst.hilbert_space = cls._eval_hilbert_space(args)
return inst
@classmethod
def _eval_args(cls, args):
# Fall back to this, because Gate._eval_args assumes that args is
# all targets and can't contain duplicates.
return QExpr._eval_args(args)
@property
def k(self):
return self.label[1]
@property
def targets(self):
return self.label[:1]
@property
def gate_name_plot(self):
return r'$%s_%s$' % (self.gate_name_latex, str(self.k))
def get_target_matrix(self, format='sympy'):
if format == 'sympy':
return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]])
raise NotImplementedError(
'Invalid format for the R_k gate: %r' % format)
Rk = RkGate
class Fourier(Gate):
"""Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
@classmethod
def _eval_args(self, args):
if len(args) != 2:
raise QuantumError(
'QFT/IQFT only takes two arguments, got: %r' % args
)
if args[0] >= args[1]:
raise QuantumError("Start must be smaller than finish")
return Gate._eval_args(args)
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
"""
Represents the (I)QFT In the Z Basis
"""
nqubits = options.get('nqubits', 0)
if nqubits == 0:
raise QuantumError(
'The number of qubits must be given as nqubits.')
if nqubits < self.min_qubits:
raise QuantumError(
'The number of qubits %r is too small for the gate.' % nqubits
)
size = self.size
omega = self.omega
#Make a matrix that has the basic Fourier Transform Matrix
arrayFT = [[omega**(
i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
matrixFT = Matrix(arrayFT)
#Embed the FT Matrix in a higher space, if necessary
if self.label[0] != 0:
matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
if self.min_qubits < nqubits:
matrixFT = matrix_tensor_product(
matrixFT, eye(2**(nqubits - self.min_qubits)))
return matrixFT
@property
def targets(self):
return range(self.label[0], self.label[1])
@property
def min_qubits(self):
return self.label[1]
@property
def size(self):
"""Size is the size of the QFT matrix"""
return 2**(self.label[1] - self.label[0])
@property
def omega(self):
return Symbol('omega')
class QFT(Fourier):
"""The forward quantum Fourier transform."""
gate_name = 'QFT'
gate_name_latex = 'QFT'
def decompose(self):
"""Decomposes QFT into elementary gates."""
start = self.label[0]
finish = self.label[1]
circuit = 1
for level in reversed(range(start, finish)):
circuit = HadamardGate(level)*circuit
for i in range(level - start):
circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit
for i in range((finish - start)//2):
circuit = SwapGate(i + start, finish - i - 1)*circuit
return circuit
def _apply_operator_Qubit(self, qubits, **options):
return qapply(self.decompose()*qubits)
def _eval_inverse(self):
return IQFT(*self.args)
@property
def omega(self):
return exp(2*pi*I/self.size)
class IQFT(Fourier):
"""The inverse quantum Fourier transform."""
gate_name = 'IQFT'
gate_name_latex = '{QFT^{-1}}'
def decompose(self):
"""Decomposes IQFT into elementary gates."""
start = self.args[0]
finish = self.args[1]
circuit = 1
for i in range((finish - start)//2):
circuit = SwapGate(i + start, finish - i - 1)*circuit
for level in range(start, finish):
for i in reversed(range(level - start)):
circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit
circuit = HadamardGate(level)*circuit
return circuit
def _eval_inverse(self):
return QFT(*self.args)
@property
def omega(self):
return exp(-2*pi*I/self.size)
|
28e7875dbe7686f47521b78dc25354df428f883f71bfb4b56b6768c2442a04b3 | """Hermitian conjugation."""
from sympy.core import Expr, Mul
from sympy.functions.elementary.complexes import adjoint
__all__ = [
'Dagger'
]
class Dagger(adjoint):
"""General Hermitian conjugate operation.
Explanation
===========
Take the Hermetian conjugate of an argument [1]_. For matrices this
operation is equivalent to transpose and complex conjugate [2]_.
Parameters
==========
arg : Expr
The SymPy expression that we want to take the dagger of.
Examples
========
Daggering various quantum objects:
>>> from sympy.physics.quantum.dagger import Dagger
>>> from sympy.physics.quantum.state import Ket, Bra
>>> from sympy.physics.quantum.operator import Operator
>>> Dagger(Ket('psi'))
<psi|
>>> Dagger(Bra('phi'))
|phi>
>>> Dagger(Operator('A'))
Dagger(A)
Inner and outer products::
>>> from sympy.physics.quantum import InnerProduct, OuterProduct
>>> Dagger(InnerProduct(Bra('a'), Ket('b')))
<b|a>
>>> Dagger(OuterProduct(Ket('a'), Bra('b')))
|b><a|
Powers, sums and products::
>>> A = Operator('A')
>>> B = Operator('B')
>>> Dagger(A*B)
Dagger(B)*Dagger(A)
>>> Dagger(A+B)
Dagger(A) + Dagger(B)
>>> Dagger(A**2)
Dagger(A)**2
Dagger also seamlessly handles complex numbers and matrices::
>>> from sympy import Matrix, I
>>> m = Matrix([[1,I],[2,I]])
>>> m
Matrix([
[1, I],
[2, I]])
>>> Dagger(m)
Matrix([
[ 1, 2],
[-I, -I]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
.. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
"""
def __new__(cls, arg):
if hasattr(arg, 'adjoint'):
obj = arg.adjoint()
elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'):
obj = arg.conjugate().transpose()
if obj is not None:
return obj
return Expr.__new__(cls, arg)
def __mul__(self, other):
from sympy.physics.quantum import IdentityOperator
if isinstance(other, IdentityOperator):
return self
return Mul(self, other)
adjoint.__name__ = "Dagger"
adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
|
93ca390f0af67a2dd1ce16fa679bb8a509cca27fe785f6a4e9f6db3eb466badb | from collections import deque
from random import randint
from sympy.external import import_module
from sympy.core.basic import Basic
from sympy.core.mul import Mul
from sympy.core.numbers import Number
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.dagger import Dagger
__all__ = [
# Public interfaces
'generate_gate_rules',
'generate_equivalent_ids',
'GateIdentity',
'bfs_identity_search',
'random_identity_search',
# "Private" functions
'is_scalar_sparse_matrix',
'is_scalar_nonsparse_matrix',
'is_degenerate',
'is_reducible',
]
np = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
"""Checks if a given scipy.sparse matrix is a scalar matrix.
A scalar matrix is such that B = bI, where B is the scalar
matrix, b is some scalar multiple, and I is the identity
matrix. A scalar matrix would have only the element b along
it's main diagonal and zeroes elsewhere.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
The tolerance value for zeroing out elements in the matrix.
Values in the range [-eps, +eps] will be changed to a zero.
"""
if not np or not scipy:
pass
matrix = represent(Mul(*circuit), nqubits=nqubits,
format='scipy.sparse')
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, int)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Due to floating pointing operations, must zero out
# elements that are "very" small in the dense matrix
# See parameter for default value.
# Get the ndarray version of the dense matrix
dense_matrix = matrix.todense().getA()
# Since complex values can't be compared, must split
# the matrix into real and imaginary components
# Find the real values in between -eps and eps
bool_real = np.logical_and(dense_matrix.real > -eps,
dense_matrix.real < eps)
# Find the imaginary values between -eps and eps
bool_imag = np.logical_and(dense_matrix.imag > -eps,
dense_matrix.imag < eps)
# Replaces values between -eps and eps with 0
corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
# Convert the matrix with real values into imaginary values
corrected_imag = corrected_imag * complex(1j)
# Recombine the real and imaginary components
corrected_dense = corrected_real + corrected_imag
# Check if it's diagonal
row_indices = corrected_dense.nonzero()[0]
col_indices = corrected_dense.nonzero()[1]
# Check if the rows indices and columns indices are the same
# If they match, then matrix only contains elements along diagonal
bool_indices = row_indices == col_indices
is_diagonal = bool_indices.all()
first_element = corrected_dense[0][0]
# If the first element is a zero, then can't rescale matrix
# and definitely not diagonal
if (first_element == 0.0 + 0.0j):
return False
# The dimensions of the dense matrix should still
# be 2^nqubits if there are elements all along the
# the main diagonal
trace_of_corrected = (corrected_dense/first_element).trace()
expected_trace = pow(2, nqubits)
has_correct_trace = trace_of_corrected == expected_trace
# If only looking for identity matrices
# first element must be a 1
real_is_one = abs(first_element.real - 1.0) < eps
imag_is_zero = abs(first_element.imag) < eps
is_one = real_is_one and imag_is_zero
is_identity = is_one if identity_only else True
return bool(is_diagonal and has_correct_trace and is_identity)
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
"""Checks if a given circuit, in matrix form, is equivalent to
a scalar value.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
This argument is ignored. It is just for signature compatibility with
is_scalar_sparse_matrix.
Note: Used in situations when is_scalar_sparse_matrix has bugs
"""
matrix = represent(Mul(*circuit), nqubits=nqubits)
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, Number)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Added up the diagonal elements
matrix_trace = matrix.trace()
# Divide the trace by the first element in the matrix
# if matrix is not required to be the identity matrix
adjusted_matrix_trace = (matrix_trace/matrix[0]
if not identity_only
else matrix_trace)
is_identity = matrix[0] == 1.0 if identity_only else True
has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
# The matrix is scalar if it's diagonal and the adjusted trace
# value is equal to 2^nqubits
return bool(
matrix.is_diagonal() and has_correct_trace and is_identity)
if np and scipy:
is_scalar_matrix = is_scalar_sparse_matrix
else:
is_scalar_matrix = is_scalar_nonsparse_matrix
def _get_min_qubits(a_gate):
if isinstance(a_gate, Pow):
return a_gate.base.min_qubits
else:
return a_gate.min_qubits
def ll_op(left, right):
"""Perform a LL operation.
A LL operation multiplies both left and right circuits
with the dagger of the left circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a LL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LL operation:
>>> from sympy.physics.quantum.identitysearch import ll_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> ll_op((x, y, z), ())
((Y(0), Z(0)), (X(0),))
>>> ll_op((y, z), (x,))
((Z(0),), (Y(0), X(0)))
"""
if (len(left) > 0):
ll_gate = left[0]
ll_gate_is_unitary = is_scalar_matrix(
(Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
if (len(left) > 0 and ll_gate_is_unitary):
# Get the new left side w/o the leftmost gate
new_left = left[1:len(left)]
# Add the leftmost gate to the left position on the right side
new_right = (Dagger(ll_gate),) + right
# Return the new gate rule
return (new_left, new_right)
return None
def lr_op(left, right):
"""Perform a LR operation.
A LR operation multiplies both left and right circuits
with the dagger of the left circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a LR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LR operation:
>>> from sympy.physics.quantum.identitysearch import lr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> lr_op((x, y, z), ())
((X(0), Y(0)), (Z(0),))
>>> lr_op((x, y), (z,))
((X(0),), (Z(0), Y(0)))
"""
if (len(left) > 0):
lr_gate = left[len(left) - 1]
lr_gate_is_unitary = is_scalar_matrix(
(Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
if (len(left) > 0 and lr_gate_is_unitary):
# Get the new left side w/o the rightmost gate
new_left = left[0:len(left) - 1]
# Add the rightmost gate to the right position on the right side
new_right = right + (Dagger(lr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def rl_op(left, right):
"""Perform a RL operation.
A RL operation multiplies both left and right circuits
with the dagger of the right circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a RL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RL operation:
>>> from sympy.physics.quantum.identitysearch import rl_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rl_op((x,), (y, z))
((Y(0), X(0)), (Z(0),))
>>> rl_op((x, y), (z,))
((Z(0), X(0), Y(0)), ())
"""
if (len(right) > 0):
rl_gate = right[0]
rl_gate_is_unitary = is_scalar_matrix(
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
if (len(right) > 0 and rl_gate_is_unitary):
# Get the new right side w/o the leftmost gate
new_right = right[1:len(right)]
# Add the leftmost gate to the left position on the left side
new_left = (Dagger(rl_gate),) + left
# Return the new gate rule
return (new_left, new_right)
return None
def rr_op(left, right):
"""Perform a RR operation.
A RR operation multiplies both left and right circuits
with the dagger of the right circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a RR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RR operation:
>>> from sympy.physics.quantum.identitysearch import rr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rr_op((x, y), (z,))
((X(0), Y(0), Z(0)), ())
>>> rr_op((x,), (y, z))
((X(0), Z(0)), (Y(0),))
"""
if (len(right) > 0):
rr_gate = right[len(right) - 1]
rr_gate_is_unitary = is_scalar_matrix(
(Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
if (len(right) > 0 and rr_gate_is_unitary):
# Get the new right side w/o the rightmost gate
new_right = right[0:len(right) - 1]
# Add the rightmost gate to the right position on the right side
new_left = left + (Dagger(rr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def generate_gate_rules(gate_seq, return_as_muls=False):
"""Returns a set of gate rules. Each gate rules is represented
as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
scalar value.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules.
A gate rule is an expression such as ABC = D or AB = CD, where
A, B, C, and D are gates. Each value on either side of the
equal sign represents a circuit. The four operations allow
one to find a set of equivalent circuits from a gate identity.
The letters denoting the operation tell the user what
activities to perform on each expression. The first letter
indicates which side of the equal sign to focus on. The
second letter indicates which gate to focus on given the
side. Once this information is determined, the inverse
of the gate is multiplied on both circuits to create a new
gate rule.
For example, given the identity, ABCD = 1, a LL operation
means look at the left value and multiply both left sides by the
inverse of the leftmost gate A. If A is Hermitian, the inverse
of A is still A. The resulting new rule is BCD = A.
The following is a summary of the four operations. Assume
that in the examples, all gates are Hermitian.
LL : left circuit, left multiply
ABCD = E -> AABCD = AE -> BCD = AE
LR : left circuit, right multiply
ABCD = E -> ABCDD = ED -> ABC = ED
RL : right circuit, left multiply
ABC = ED -> EABC = EED -> EABC = D
RR : right circuit, right multiply
AB = CD -> ABD = CDD -> ABD = C
The number of gate rules generated is n*(n+1), where n
is the number of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix
return_as_muls : bool
True to return a set of Muls; False to return a set of tuples
Examples
========
Find the gate rules of the current circuit using tuples:
>>> from sympy.physics.quantum.identitysearch import generate_gate_rules
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_gate_rules((x, x))
{((X(0),), (X(0),)), ((X(0), X(0)), ())}
>>> generate_gate_rules((x, y, z))
{((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
Find the gate rules of the current circuit using Muls:
>>> generate_gate_rules(x*x, return_as_muls=True)
{(1, 1)}
>>> generate_gate_rules(x*y*z, return_as_muls=True)
{(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
(1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
(Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
(X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
(Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
(Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
"""
if isinstance(gate_seq, Number):
if return_as_muls:
return {(S.One, S.One)}
else:
return {((), ())}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Each item in queue is a 3-tuple:
# i) first item is the left side of an equality
# ii) second item is the right side of an equality
# iii) third item is the number of operations performed
# The argument, gate_seq, will start on the left side, and
# the right side will be empty, implying the presence of an
# identity.
queue = deque()
# A set of gate rules
rules = set()
# Maximum number of operations to perform
max_ops = len(gate_seq)
def process_new_rule(new_rule, ops):
if new_rule is not None:
new_left, new_right = new_rule
if new_rule not in rules and (new_right, new_left) not in rules:
rules.add(new_rule)
# If haven't reached the max limit on operations
if ops + 1 < max_ops:
queue.append(new_rule + (ops + 1,))
queue.append((gate_seq, (), 0))
rules.add((gate_seq, ()))
while len(queue) > 0:
left, right, ops = queue.popleft()
# Do a LL
new_rule = ll_op(left, right)
process_new_rule(new_rule, ops)
# Do a LR
new_rule = lr_op(left, right)
process_new_rule(new_rule, ops)
# Do a RL
new_rule = rl_op(left, right)
process_new_rule(new_rule, ops)
# Do a RR
new_rule = rr_op(left, right)
process_new_rule(new_rule, ops)
if return_as_muls:
# Convert each rule as tuples into a rule as muls
mul_rules = set()
for rule in rules:
left, right = rule
mul_rules.add((Mul(*left), Mul(*right)))
rules = mul_rules
return rules
def generate_equivalent_ids(gate_seq, return_as_muls=False):
"""Returns a set of equivalent gate identities.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules and, subsequently, to locate equivalent
gate identities.
Note that all equivalent identities are reachable in n operations
from the starting gate identity, where n is the number of gates
in the sequence.
The max number of gate identities is 2n, where n is the number
of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix.
return_as_muls: bool
True to return as Muls; False to return as tuples
Examples
========
Find equivalent gate identities from the current circuit with tuples:
>>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_equivalent_ids((x, x))
{(X(0), X(0))}
>>> generate_equivalent_ids((x, y, z))
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
Find equivalent gate identities from the current circuit with Muls:
>>> generate_equivalent_ids(x*x, return_as_muls=True)
{1}
>>> generate_equivalent_ids(x*y*z, return_as_muls=True)
{X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
"""
if isinstance(gate_seq, Number):
return {S.One}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Filter through the gate rules and keep the rules
# with an empty tuple either on the left or right side
# A set of equivalent gate identities
eq_ids = set()
gate_rules = generate_gate_rules(gate_seq)
for rule in gate_rules:
l, r = rule
if l == ():
eq_ids.add(r)
elif r == ():
eq_ids.add(l)
if return_as_muls:
convert_to_mul = lambda id_seq: Mul(*id_seq)
eq_ids = set(map(convert_to_mul, eq_ids))
return eq_ids
class GateIdentity(Basic):
"""Wrapper class for circuits that reduce to a scalar value.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
Parameters
==========
args : Gate tuple
A variable length tuple of Gates that form an identity.
Examples
========
Create a GateIdentity and look at its attributes:
>>> from sympy.physics.quantum.identitysearch import GateIdentity
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> an_identity.circuit
X(0)*Y(0)*Z(0)
>>> an_identity.equivalent_ids
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
"""
def __new__(cls, *args):
# args should be a tuple - a variable length argument list
obj = Basic.__new__(cls, *args)
obj._circuit = Mul(*args)
obj._rules = generate_gate_rules(args)
obj._eq_ids = generate_equivalent_ids(args)
return obj
@property
def circuit(self):
return self._circuit
@property
def gate_rules(self):
return self._rules
@property
def equivalent_ids(self):
return self._eq_ids
@property
def sequence(self):
return self.args
def __str__(self):
"""Returns the string of gates in a tuple."""
return str(self.circuit)
def is_degenerate(identity_set, gate_identity):
"""Checks if a gate identity is a permutation of another identity.
Parameters
==========
identity_set : set
A Python set with GateIdentity objects.
gate_identity : GateIdentity
The GateIdentity to check for existence in the set.
Examples
========
Check if the identity is a permutation of another identity:
>>> from sympy.physics.quantum.identitysearch import (
... GateIdentity, is_degenerate)
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> id_set = {an_identity}
>>> another_id = (y, z, x)
>>> is_degenerate(id_set, another_id)
True
>>> another_id = (x, x)
>>> is_degenerate(id_set, another_id)
False
"""
# For now, just iteratively go through the set and check if the current
# gate_identity is a permutation of an identity in the set
for an_id in identity_set:
if (gate_identity in an_id.equivalent_ids):
return True
return False
def is_reducible(circuit, nqubits, begin, end):
"""Determines if a circuit is reducible by checking
if its subcircuits are scalar values.
Parameters
==========
circuit : Gate tuple
A tuple of Gates representing a circuit. The circuit to check
if a gate identity is contained in a subcircuit.
nqubits : int
The number of qubits the circuit operates on.
begin : int
The leftmost gate in the circuit to include in a subcircuit.
end : int
The rightmost gate in the circuit to include in a subcircuit.
Examples
========
Check if the circuit can be reduced:
>>> from sympy.physics.quantum.identitysearch import is_reducible
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> is_reducible((x, y, z), 1, 0, 3)
True
Check if an interval in the circuit can be reduced:
>>> is_reducible((x, y, z), 1, 1, 3)
False
>>> is_reducible((x, y, y), 1, 1, 3)
True
"""
current_circuit = ()
# Start from the gate at "end" and go down to almost the gate at "begin"
for ndx in reversed(range(begin, end)):
next_gate = circuit[ndx]
current_circuit = (next_gate,) + current_circuit
# If a circuit as a matrix is equivalent to a scalar value
if (is_scalar_matrix(current_circuit, nqubits, False)):
return True
return False
def bfs_identity_search(gate_list, nqubits, max_depth=None,
identity_only=False):
"""Constructs a set of gate identities from the list of possible gates.
Performs a breadth first search over the space of gate identities.
This allows the finding of the shortest gate identities first.
Parameters
==========
gate_list : list, Gate
A list of Gates from which to search for gate identities.
nqubits : int
The number of qubits the quantum circuit operates on.
max_depth : int
The longest quantum circuit to construct from gate_list.
identity_only : bool
True to search for gate identities that reduce to identity;
False to search for gate identities that reduce to a scalar.
Examples
========
Find a list of gate identities:
>>> from sympy.physics.quantum.identitysearch import bfs_identity_search
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> bfs_identity_search([x], 1, max_depth=2)
{GateIdentity(X(0), X(0))}
>>> bfs_identity_search([x, y, z], 1)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
Find a list of identities that only equal to 1:
>>> bfs_identity_search([x, y, z], 1, identity_only=True)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0))}
"""
if max_depth is None or max_depth <= 0:
max_depth = len(gate_list)
id_only = identity_only
# Start with an empty sequence (implicitly contains an IdentityGate)
queue = deque([()])
# Create an empty set of gate identities
ids = set()
# Begin searching for gate identities in given space.
while (len(queue) > 0):
current_circuit = queue.popleft()
for next_gate in gate_list:
new_circuit = current_circuit + (next_gate,)
# Determines if a (strict) subcircuit is a scalar matrix
circuit_reducible = is_reducible(new_circuit, nqubits,
1, len(new_circuit))
# In many cases when the matrix is a scalar value,
# the evaluated matrix will actually be an integer
if (is_scalar_matrix(new_circuit, nqubits, id_only) and
not is_degenerate(ids, new_circuit) and
not circuit_reducible):
ids.add(GateIdentity(*new_circuit))
elif (len(new_circuit) < max_depth and
not circuit_reducible):
queue.append(new_circuit)
return ids
def random_identity_search(gate_list, numgates, nqubits):
"""Randomly selects numgates from gate_list and checks if it is
a gate identity.
If the circuit is a gate identity, the circuit is returned;
Otherwise, None is returned.
"""
gate_size = len(gate_list)
circuit = ()
for i in range(numgates):
next_gate = gate_list[randint(0, gate_size - 1)]
circuit = circuit + (next_gate,)
is_scalar = is_scalar_matrix(circuit, nqubits, False)
return circuit if is_scalar else None
|
c3d6a3e5e70f151992096563998697c03e1ba50c5437ec32777413dca538bd9a | """Abstract tensor product."""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.sympify import sympify
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.state import Ket, Bra
from sympy.physics.quantum.matrixutils import (
numpy_ndarray,
scipy_sparse_matrix,
matrix_tensor_product
)
from sympy.physics.quantum.trace import Tr
__all__ = [
'TensorProduct',
'tensor_product_simp'
]
#-----------------------------------------------------------------------------
# Tensor product
#-----------------------------------------------------------------------------
_combined_printing = False
def combined_tensor_printing(combined):
"""Set flag controlling whether tensor products of states should be
printed as a combined bra/ket or as an explicit tensor product of different
bra/kets. This is a global setting for all TensorProduct class instances.
Parameters
----------
combine : bool
When true, tensor product states are combined into one ket/bra, and
when false explicit tensor product notation is used between each
ket/bra.
"""
global _combined_printing
_combined_printing = combined
class TensorProduct(Expr):
"""The tensor product of two or more arguments.
For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
or tensor product matrix. For other objects a symbolic ``TensorProduct``
instance is returned. The tensor product is a non-commutative
multiplication that is used primarily with operators and states in quantum
mechanics.
Currently, the tensor product distinguishes between commutative and
non-commutative arguments. Commutative arguments are assumed to be scalars
and are pulled out in front of the ``TensorProduct``. Non-commutative
arguments remain in the resulting ``TensorProduct``.
Parameters
==========
args : tuple
A sequence of the objects to take the tensor product of.
Examples
========
Start with a simple tensor product of SymPy matrices::
>>> from sympy import Matrix
>>> from sympy.physics.quantum import TensorProduct
>>> m1 = Matrix([[1,2],[3,4]])
>>> m2 = Matrix([[1,0],[0,1]])
>>> TensorProduct(m1, m2)
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[3, 0, 4, 0],
[0, 3, 0, 4]])
>>> TensorProduct(m2, m1)
Matrix([
[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4]])
We can also construct tensor products of non-commutative symbols:
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> tp = TensorProduct(A, B)
>>> tp
AxB
We can take the dagger of a tensor product (note the order does NOT reverse
like the dagger of a normal product):
>>> from sympy.physics.quantum import Dagger
>>> Dagger(tp)
Dagger(A)xDagger(B)
Expand can be used to distribute a tensor product across addition:
>>> C = Symbol('C',commutative=False)
>>> tp = TensorProduct(A+B,C)
>>> tp
(A + B)xC
>>> tp.expand(tensorproduct=True)
AxC + BxC
"""
is_commutative = False
def __new__(cls, *args):
if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)):
return matrix_tensor_product(*args)
c_part, new_args = cls.flatten(sympify(args))
c_part = Mul(*c_part)
if len(new_args) == 0:
return c_part
elif len(new_args) == 1:
return c_part * new_args[0]
else:
tp = Expr.__new__(cls, *new_args)
return c_part * tp
@classmethod
def flatten(cls, args):
# TODO: disallow nested TensorProducts.
c_part = []
nc_parts = []
for arg in args:
cp, ncp = arg.args_cnc()
c_part.extend(list(cp))
nc_parts.append(Mul._from_args(ncp))
return c_part, nc_parts
def _eval_adjoint(self):
return TensorProduct(*[Dagger(i) for i in self.args])
def _eval_rewrite(self, rule, args, **hints):
return TensorProduct(*args).expand(tensorproduct=True)
def _sympystr(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
if isinstance(self.args[i], (Add, Pow, Mul)):
s = s + '('
s = s + printer._print(self.args[i])
if isinstance(self.args[i], (Add, Pow, Mul)):
s = s + ')'
if i != length - 1:
s = s + 'x'
return s
def _pretty(self, printer, *args):
if (_combined_printing and
(all(isinstance(arg, Ket) for arg in self.args) or
all(isinstance(arg, Bra) for arg in self.args))):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print('', *args)
length_i = len(self.args[i].args)
for j in range(length_i):
part_pform = printer._print(self.args[i].args[j], *args)
next_pform = prettyForm(*next_pform.right(part_pform))
if j != length_i - 1:
next_pform = prettyForm(*next_pform.right(', '))
if len(self.args[i].args) > 1:
next_pform = prettyForm(
*next_pform.parens(left='{', right='}'))
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
pform = prettyForm(*pform.right(',' + ' '))
pform = prettyForm(*pform.left(self.args[0].lbracket))
pform = prettyForm(*pform.right(self.args[0].rbracket))
return pform
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (Add, Mul)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
else:
pform = prettyForm(*pform.right('x' + ' '))
return pform
def _latex(self, printer, *args):
if (_combined_printing and
(all(isinstance(arg, Ket) for arg in self.args) or
all(isinstance(arg, Bra) for arg in self.args))):
def _label_wrap(label, nlabels):
return label if nlabels == 1 else r"\left\{%s\right\}" % label
s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
len(arg.args)) for arg in self.args])
return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
self.args[0].rbracket_latex)
length = len(self.args)
s = ''
for i in range(length):
if isinstance(self.args[i], (Add, Mul)):
s = s + '\\left('
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
s = s + '{' + printer._print(self.args[i], *args) + '}'
if isinstance(self.args[i], (Add, Mul)):
s = s + '\\right)'
if i != length - 1:
s = s + '\\otimes '
return s
def doit(self, **hints):
return TensorProduct(*[item.doit(**hints) for item in self.args])
def _eval_expand_tensorproduct(self, **hints):
"""Distribute TensorProducts across addition."""
args = self.args
add_args = []
for i in range(len(args)):
if isinstance(args[i], Add):
for aa in args[i].args:
tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
if isinstance(tp, TensorProduct):
tp = tp._eval_expand_tensorproduct()
add_args.append(tp)
break
if add_args:
return Add(*add_args)
else:
return self
def _eval_trace(self, **kwargs):
indices = kwargs.get('indices', None)
exp = tensor_product_simp(self)
if indices is None or len(indices) == 0:
return Mul(*[Tr(arg).doit() for arg in exp.args])
else:
return Mul(*[Tr(value).doit() if idx in indices else value
for idx, value in enumerate(exp.args)])
def tensor_product_simp_Mul(e):
"""Simplify a Mul with TensorProducts.
Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
simple cases where the initial ``Mul`` only has scalars and raw
``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
``TensorProduct``s.
Parameters
==========
e : Expr
A ``Mul`` of ``TensorProduct``s to be simplified.
Returns
=======
e : Expr
A ``TensorProduct`` of ``Mul``s.
Examples
========
This is an example of the type of simplification that this function
performs::
>>> from sympy.physics.quantum.tensorproduct import \
tensor_product_simp_Mul, TensorProduct
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> C = Symbol('C',commutative=False)
>>> D = Symbol('D',commutative=False)
>>> e = TensorProduct(A,B)*TensorProduct(C,D)
>>> e
AxB*CxD
>>> tensor_product_simp_Mul(e)
(A*C)x(B*D)
"""
# TODO: This won't work with Muls that have other composites of
# TensorProducts, like an Add, Commutator, etc.
# TODO: This only works for the equivalent of single Qbit gates.
if not isinstance(e, Mul):
return e
c_part, nc_part = e.args_cnc()
n_nc = len(nc_part)
if n_nc == 0:
return e
elif n_nc == 1:
if isinstance(nc_part[0], Pow):
return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])
return e
elif e.has(TensorProduct):
current = nc_part[0]
if not isinstance(current, TensorProduct):
if isinstance(current, Pow):
if isinstance(current.base, TensorProduct):
current = tensor_product_simp_Pow(current)
else:
raise TypeError('TensorProduct expected, got: %r' % current)
n_terms = len(current.args)
new_args = list(current.args)
for next in nc_part[1:]:
# TODO: check the hilbert spaces of next and current here.
if isinstance(next, TensorProduct):
if n_terms != len(next.args):
raise QuantumError(
'TensorProducts of different lengths: %r and %r' %
(current, next)
)
for i in range(len(new_args)):
new_args[i] = new_args[i] * next.args[i]
else:
if isinstance(next, Pow):
if isinstance(next.base, TensorProduct):
new_tp = tensor_product_simp_Pow(next)
for i in range(len(new_args)):
new_args[i] = new_args[i] * new_tp.args[i]
else:
raise TypeError('TensorProduct expected, got: %r' % next)
else:
raise TypeError('TensorProduct expected, got: %r' % next)
current = next
return Mul(*c_part) * TensorProduct(*new_args)
elif e.has(Pow):
new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]
return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))
else:
return e
def tensor_product_simp_Pow(e):
"""Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""
if not isinstance(e, Pow):
return e
if isinstance(e.base, TensorProduct):
return TensorProduct(*[ b**e.exp for b in e.base.args])
else:
return e
def tensor_product_simp(e, **hints):
"""Try to simplify and combine TensorProducts.
In general this will try to pull expressions inside of ``TensorProducts``.
It currently only works for relatively simple cases where the products have
only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
of ``TensorProducts``. It is best to see what it does by showing examples.
Examples
========
>>> from sympy.physics.quantum import tensor_product_simp
>>> from sympy.physics.quantum import TensorProduct
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> C = Symbol('C',commutative=False)
>>> D = Symbol('D',commutative=False)
First see what happens to products of tensor products:
>>> e = TensorProduct(A,B)*TensorProduct(C,D)
>>> e
AxB*CxD
>>> tensor_product_simp(e)
(A*C)x(B*D)
This is the core logic of this function, and it works inside, powers, sums,
commutators and anticommutators as well:
>>> tensor_product_simp(e**2)
(A*C)x(B*D)**2
"""
if isinstance(e, Add):
return Add(*[tensor_product_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
if isinstance(e.base, TensorProduct):
return tensor_product_simp_Pow(e)
else:
return tensor_product_simp(e.base) ** e.exp
elif isinstance(e, Mul):
return tensor_product_simp_Mul(e)
elif isinstance(e, Commutator):
return Commutator(*[tensor_product_simp(arg) for arg in e.args])
elif isinstance(e, AntiCommutator):
return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
else:
return e
|
4c7d263c5dc393d98be5f6b685eb9a9a90e9c16171c61dc709c838836b8d43f1 | """The anti-commutator: ``{A,B} = A*B + B*A``."""
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.dagger import Dagger
__all__ = [
'AntiCommutator'
]
#-----------------------------------------------------------------------------
# Anti-commutator
#-----------------------------------------------------------------------------
class AntiCommutator(Expr):
"""The standard anticommutator, in an unevaluated state.
Explanation
===========
Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
This class returns the anticommutator in an unevaluated form. To evaluate
the anticommutator, use the ``.doit()`` method.
Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
arguments of the anticommutator are put into canonical order using
``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
Parameters
==========
A : Expr
The first argument of the anticommutator {A,B}.
B : Expr
The second argument of the anticommutator {A,B}.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.quantum import AntiCommutator
>>> from sympy.physics.quantum import Operator, Dagger
>>> x, y = symbols('x,y')
>>> A = Operator('A')
>>> B = Operator('B')
Create an anticommutator and use ``doit()`` to multiply them out.
>>> ac = AntiCommutator(A,B); ac
{A,B}
>>> ac.doit()
A*B + B*A
The commutator orders it arguments in canonical order:
>>> ac = AntiCommutator(B,A); ac
{A,B}
Commutative constants are factored out:
>>> AntiCommutator(3*x*A,x*y*B)
3*x**2*y*{A,B}
Adjoint operations applied to the anticommutator are properly applied to
the arguments:
>>> Dagger(AntiCommutator(A,B))
{Dagger(A),Dagger(B)}
References
==========
.. [1] https://en.wikipedia.org/wiki/Commutator
"""
is_commutative = False
def __new__(cls, A, B):
r = cls.eval(A, B)
if r is not None:
return r
obj = Expr.__new__(cls, A, B)
return obj
@classmethod
def eval(cls, a, b):
if not (a and b):
return S.Zero
if a == b:
return Integer(2)*a**2
if a.is_commutative or b.is_commutative:
return Integer(2)*a*b
# [xA,yB] -> xy*[A,B]
ca, nca = a.args_cnc()
cb, ncb = b.args_cnc()
c_part = ca + cb
if c_part:
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
# Canonical ordering of arguments
#The Commutator [A,B] is on canonical form if A < B.
if a.compare(b) == 1:
return cls(b, a)
def doit(self, **hints):
""" Evaluate anticommutator """
A = self.args[0]
B = self.args[1]
if isinstance(A, Operator) and isinstance(B, Operator):
try:
comm = A._eval_anticommutator(B, **hints)
except NotImplementedError:
try:
comm = B._eval_anticommutator(A, **hints)
except NotImplementedError:
comm = None
if comm is not None:
return comm.doit(**hints)
return (A*B + B*A).doit(**hints)
def _eval_adjoint(self):
return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
def _sympyrepr(self, printer, *args):
return "%s(%s,%s)" % (
self.__class__.__name__, printer._print(
self.args[0]), printer._print(self.args[1])
)
def _sympystr(self, printer, *args):
return "{%s,%s}" % (
printer._print(self.args[0]), printer._print(self.args[1]))
def _pretty(self, printer, *args):
pform = printer._print(self.args[0], *args)
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
pform = prettyForm(*pform.parens(left='{', right='}'))
return pform
def _latex(self, printer, *args):
return "\\left\\{%s,%s\\right\\}" % tuple([
printer._print(arg, *args) for arg in self.args])
|
e7378deb6b7fbf669beddb75c7bd56fe570183a704359e94d96943b70d5534aa | """Dirac notation for states."""
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.numbers import oo
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.printing.pretty.stringpict import stringPict
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
__all__ = [
'KetBase',
'BraBase',
'StateBase',
'State',
'Ket',
'Bra',
'TimeDepState',
'TimeDepBra',
'TimeDepKet',
'OrthogonalKet',
'OrthogonalBra',
'OrthogonalState',
'Wavefunction'
]
#-----------------------------------------------------------------------------
# States, bras and kets.
#-----------------------------------------------------------------------------
# ASCII brackets
_lbracket = "<"
_rbracket = ">"
_straight_bracket = "|"
# Unicode brackets
# MATHEMATICAL ANGLE BRACKETS
_lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
_rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
# LIGHT VERTICAL BAR
_straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
# Other options for unicode printing of <, > and | for Dirac notation.
# LEFT-POINTING ANGLE BRACKET
# _lbracket = "\u2329"
# _rbracket = "\u232A"
# LEFT ANGLE BRACKET
# _lbracket = "\u3008"
# _rbracket = "\u3009"
# VERTICAL LINE
# _straight_bracket = "\u007C"
class StateBase(QExpr):
"""Abstract base class for general abstract states in quantum mechanics.
All other state classes defined will need to inherit from this class. It
carries the basic structure for all other states such as dual, _eval_adjoint
and label.
This is an abstract base class and you should not instantiate it directly,
instead use State.
"""
@classmethod
def _operators_to_state(self, ops, **options):
""" Returns the eigenstate instance for the passed operators.
This method should be overridden in subclasses. It will handle being
passed either an Operator instance or set of Operator instances. It
should return the corresponding state INSTANCE or simply raise a
NotImplementedError. See cartesian.py for an example.
"""
raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
def _state_to_operators(self, op_classes, **options):
""" Returns the operators which this state instance is an eigenstate
of.
This method should be overridden in subclasses. It will be called on
state instances and be passed the operator classes that we wish to make
into instances. The state instance will then transform the classes
appropriately, or raise a NotImplementedError if it cannot return
operator instances. See cartesian.py for examples,
"""
raise NotImplementedError(
"Cannot map this state to operators. Method not implemented!")
@property
def operators(self):
"""Return the operator(s) that this state is an eigenstate of"""
from .operatorset import state_to_operators # import internally to avoid circular import errors
return state_to_operators(self)
def _enumerate_state(self, num_states, **options):
raise NotImplementedError("Cannot enumerate this state!")
def _represent_default_basis(self, **options):
return self._represent(basis=self.operators)
#-------------------------------------------------------------------------
# Dagger/dual
#-------------------------------------------------------------------------
@property
def dual(self):
"""Return the dual state of this one."""
return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
@classmethod
def dual_class(self):
"""Return the class used to construct the dual."""
raise NotImplementedError(
'dual_class must be implemented in a subclass'
)
def _eval_adjoint(self):
"""Compute the dagger of this state using the dual."""
return self.dual
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _pretty_brackets(self, height, use_unicode=True):
# Return pretty printed brackets for the state
# Ideally, this could be done by pform.parens but it does not support the angled < and >
# Setup for unicode vs ascii
if use_unicode:
lbracket, rbracket = self.lbracket_ucode, self.rbracket_ucode
slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
'\N{BOX DRAWINGS LIGHT VERTICAL}'
else:
lbracket, rbracket = self.lbracket, self.rbracket
slash, bslash, vert = '/', '\\', '|'
# If height is 1, just return brackets
if height == 1:
return stringPict(lbracket), stringPict(rbracket)
# Make height even
height += (height % 2)
brackets = []
for bracket in lbracket, rbracket:
# Create left bracket
if bracket in {_lbracket, _lbracket_ucode}:
bracket_args = [ ' ' * (height//2 - i - 1) +
slash for i in range(height // 2)]
bracket_args.extend(
[' ' * i + bslash for i in range(height // 2)])
# Create right bracket
elif bracket in {_rbracket, _rbracket_ucode}:
bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
bracket_args.extend([ ' ' * (
height//2 - i - 1) + slash for i in range(height // 2)])
# Create straight bracket
elif bracket in {_straight_bracket, _straight_bracket_ucode}:
bracket_args = [vert] * height
else:
raise ValueError(bracket)
brackets.append(
stringPict('\n'.join(bracket_args), baseline=height//2))
return brackets
def _sympystr(self, printer, *args):
contents = self._print_contents(printer, *args)
return '%s%s%s' % (self.lbracket, contents, self.rbracket)
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
# Get brackets
pform = self._print_contents_pretty(printer, *args)
lbracket, rbracket = self._pretty_brackets(
pform.height(), printer._use_unicode)
# Put together state
pform = prettyForm(*pform.left(lbracket))
pform = prettyForm(*pform.right(rbracket))
return pform
def _latex(self, printer, *args):
contents = self._print_contents_latex(printer, *args)
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
return '{%s%s%s}' % (self.lbracket_latex, contents, self.rbracket_latex)
class KetBase(StateBase):
"""Base class for Kets.
This class defines the dual property and the brackets for printing. This is
an abstract base class and you should not instantiate it directly, instead
use Ket.
"""
lbracket = _straight_bracket
rbracket = _rbracket
lbracket_ucode = _straight_bracket_ucode
rbracket_ucode = _rbracket_ucode
lbracket_latex = r'\left|'
rbracket_latex = r'\right\rangle '
@classmethod
def default_args(self):
return ("psi",)
@classmethod
def dual_class(self):
return BraBase
def __mul__(self, other):
"""KetBase*other"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, BraBase):
return OuterProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*KetBase"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, BraBase):
return InnerProduct(other, self)
else:
return Expr.__rmul__(self, other)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_innerproduct(self, bra, **hints):
"""Evaluate the inner product between this ket and a bra.
This is called to compute <bra|ket>, where the ket is ``self``.
This method will dispatch to sub-methods having the format::
``def _eval_innerproduct_BraClass(self, **hints):``
Subclasses should define these methods (one for each BraClass) to
teach the ket how to take inner products with bras.
"""
return dispatch_method(self, '_eval_innerproduct', bra, **hints)
def _apply_operator(self, op, **options):
"""Apply an Operator to this Ket.
This method will dispatch to methods having the format::
``def _apply_operator_OperatorName(op, **options):``
Subclasses should define these methods (one for each OperatorName) to
teach the Ket how operators act on it.
Parameters
==========
op : Operator
The Operator that is acting on the Ket.
options : dict
A dict of key/value pairs that control how the operator is applied
to the Ket.
"""
return dispatch_method(self, '_apply_operator', op, **options)
class BraBase(StateBase):
"""Base class for Bras.
This class defines the dual property and the brackets for printing. This
is an abstract base class and you should not instantiate it directly,
instead use Bra.
"""
lbracket = _lbracket
rbracket = _straight_bracket
lbracket_ucode = _lbracket_ucode
rbracket_ucode = _straight_bracket_ucode
lbracket_latex = r'\left\langle '
rbracket_latex = r'\right|'
@classmethod
def _operators_to_state(self, ops, **options):
state = self.dual_class()._operators_to_state(ops, **options)
return state.dual
def _state_to_operators(self, op_classes, **options):
return self.dual._state_to_operators(op_classes, **options)
def _enumerate_state(self, num_states, **options):
dual_states = self.dual._enumerate_state(num_states, **options)
return [x.dual for x in dual_states]
@classmethod
def default_args(self):
return self.dual_class().default_args()
@classmethod
def dual_class(self):
return KetBase
def __mul__(self, other):
"""BraBase*other"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, KetBase):
return InnerProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*BraBase"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, KetBase):
return OuterProduct(other, self)
else:
return Expr.__rmul__(self, other)
def _represent(self, **options):
"""A default represent that uses the Ket's version."""
from sympy.physics.quantum.dagger import Dagger
return Dagger(self.dual._represent(**options))
class State(StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class Ket(State, KetBase):
"""A general time-independent Ket in quantum mechanics.
Inherits from State and KetBase. This class should be used as the base
class for all physical, time-independent Kets in a system. This class
and its subclasses will be the main classes that users will use for
expressing Kets in Dirac notation [1]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Ket and looking at its properties::
>>> from sympy.physics.quantum import Ket
>>> from sympy import symbols, I
>>> k = Ket('psi')
>>> k
|psi>
>>> k.hilbert_space
H
>>> k.is_commutative
False
>>> k.label
(psi,)
Ket's know about their associated bra::
>>> k.dual
<psi|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.Bra'>
Take a linear combination of two kets::
>>> k0 = Ket(0)
>>> k1 = Ket(1)
>>> 2*I*k0 - 4*k1
2*I*|0> - 4*|1>
Compound labels are passed as tuples::
>>> n, m = symbols('n,m')
>>> k = Ket(n,m)
>>> k
|nm>
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Bra
class Bra(State, BraBase):
"""A general time-independent Bra in quantum mechanics.
Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
class and its subclasses will be the main classes that users will use for
expressing Bras in Dirac notation.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Bra and look at its properties::
>>> from sympy.physics.quantum import Bra
>>> from sympy import symbols, I
>>> b = Bra('psi')
>>> b
<psi|
>>> b.hilbert_space
H
>>> b.is_commutative
False
Bra's know about their dual Ket's::
>>> b.dual
|psi>
>>> b.dual_class()
<class 'sympy.physics.quantum.state.Ket'>
Like Kets, Bras can have compound labels and be manipulated in a similar
manner::
>>> n, m = symbols('n,m')
>>> b = Bra(n,m) - I*Bra(m,n)
>>> b
-I*<mn| + <nm|
Symbols in a Bra can be substituted using ``.subs``::
>>> b.subs(n,m)
<mm| - I*<mm|
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Ket
#-----------------------------------------------------------------------------
# Time dependent states, bras and kets.
#-----------------------------------------------------------------------------
class TimeDepState(StateBase):
"""Base class for a general time-dependent quantum state.
This class is used as a base class for any time-dependent state. The main
difference between this class and the time-independent state is that this
class takes a second argument that is the time in addition to the usual
label argument.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
"""
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def default_args(self):
return ("psi", "t")
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label of the state."""
return self.args[:-1]
@property
def time(self):
"""The time of the state."""
return self.args[-1]
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print_time(self, printer, *args):
return printer._print(self.time, *args)
_print_time_repr = _print_time
_print_time_latex = _print_time
def _print_time_pretty(self, printer, *args):
pform = printer._print(self.time, *args)
return pform
def _print_contents(self, printer, *args):
label = self._print_label(printer, *args)
time = self._print_time(printer, *args)
return '%s;%s' % (label, time)
def _print_label_repr(self, printer, *args):
label = self._print_sequence(self.label, ',', printer, *args)
time = self._print_time_repr(printer, *args)
return '%s,%s' % (label, time)
def _print_contents_pretty(self, printer, *args):
label = self._print_label_pretty(printer, *args)
time = self._print_time_pretty(printer, *args)
return printer._print_seq((label, time), delimiter=';')
def _print_contents_latex(self, printer, *args):
label = self._print_sequence(
self.label, self._label_separator, printer, *args)
time = self._print_time_latex(printer, *args)
return '%s;%s' % (label, time)
class TimeDepKet(TimeDepState, KetBase):
"""General time-dependent Ket in quantum mechanics.
This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
that should be used for Kets that vary with time. Its dual is a
``TimeDepBra``.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
Create a TimeDepKet and look at its attributes::
>>> from sympy.physics.quantum import TimeDepKet
>>> k = TimeDepKet('psi', 't')
>>> k
|psi;t>
>>> k.time
t
>>> k.label
(psi,)
>>> k.hilbert_space
H
TimeDepKets know about their dual bra::
>>> k.dual
<psi;t|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.TimeDepBra'>
"""
@classmethod
def dual_class(self):
return TimeDepBra
class TimeDepBra(TimeDepState, BraBase):
"""General time-dependent Bra in quantum mechanics.
This inherits from TimeDepState and BraBase and is the main class that
should be used for Bras that vary with time. Its dual is a TimeDepBra.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
>>> from sympy.physics.quantum import TimeDepBra
>>> b = TimeDepBra('psi', 't')
>>> b
<psi;t|
>>> b.time
t
>>> b.label
(psi,)
>>> b.hilbert_space
H
>>> b.dual
|psi;t>
"""
@classmethod
def dual_class(self):
return TimeDepKet
class OrthogonalState(State, StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class OrthogonalKet(OrthogonalState, KetBase):
"""Orthogonal Ket in quantum mechanics.
The inner product of two states with different labels will give zero,
states with the same label will give one.
>>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
>>> from sympy.abc import m, n
>>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
1
>>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
0
>>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
<n|m>
"""
@classmethod
def dual_class(self):
return OrthogonalBra
def _eval_innerproduct(self, bra, **hints):
if len(self.args) != len(bra.args):
raise ValueError('Cannot multiply a ket that has a different number of labels.')
for i in range(len(self.args)):
diff = self.args[i] - bra.args[i]
diff = diff.expand()
if diff.is_zero is False:
return 0
if diff.is_zero is None:
return None
return 1
class OrthogonalBra(OrthogonalState, BraBase):
"""Orthogonal Bra in quantum mechanics.
"""
@classmethod
def dual_class(self):
return OrthogonalKet
class Wavefunction(Function):
"""Class for representations in continuous bases
This class takes an expression and coordinates in its constructor. It can
be used to easily calculate normalizations and probabilities.
Parameters
==========
expr : Expr
The expression representing the functional form of the w.f.
coords : Symbol or tuple
The coordinates to be integrated over, and their bounds
Examples
========
Particle in a box, specifying bounds in the more primitive way of using
Piecewise:
>>> from sympy import Symbol, Piecewise, pi, N
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = Symbol('x', real=True)
>>> n = 1
>>> L = 1
>>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
>>> f = Wavefunction(g, x)
>>> f.norm
1
>>> f.is_normalized
True
>>> p = f.prob()
>>> p(0)
0
>>> p(L)
0
>>> p(0.5)
2
>>> p(0.85*L)
2*sin(0.85*pi)**2
>>> N(p(0.85*L))
0.412214747707527
Additionally, you can specify the bounds of the function and the indices in
a more compact way:
>>> from sympy import symbols, pi, diff
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> f(L+1)
0
>>> f(L-1)
sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
>>> f(-1)
0
>>> f(0.85)
sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
>>> f(0.85, n=1, L=1)
sqrt(2)*sin(0.85*pi)
>>> f.is_commutative
False
All arguments are automatically sympified, so you can define the variables
as strings rather than symbols:
>>> expr = x**2
>>> f = Wavefunction(expr, 'x')
>>> type(f.variables[0])
<class 'sympy.core.symbol.Symbol'>
Derivatives of Wavefunctions will return Wavefunctions:
>>> diff(f, x)
Wavefunction(2*x, x)
"""
#Any passed tuples for coordinates and their bounds need to be
#converted to Tuples before Function's constructor is called, to
#avoid errors from calling is_Float in the constructor
def __new__(cls, *args, **options):
new_args = [None for i in args]
ct = 0
for arg in args:
if isinstance(arg, tuple):
new_args[ct] = Tuple(*arg)
else:
new_args[ct] = arg
ct += 1
return super().__new__(cls, *new_args, **options)
def __call__(self, *args, **options):
var = self.variables
if len(args) != len(var):
raise NotImplementedError(
"Incorrect number of arguments to function!")
ct = 0
#If the passed value is outside the specified bounds, return 0
for v in var:
lower, upper = self.limits[v]
#Do the comparison to limits only if the passed symbol is actually
#a symbol present in the limits;
#Had problems with a comparison of x > L
if isinstance(args[ct], Expr) and \
not (lower in args[ct].free_symbols
or upper in args[ct].free_symbols):
continue
if (args[ct] < lower) == True or (args[ct] > upper) == True:
return S.Zero
ct += 1
expr = self.expr
#Allows user to make a call like f(2, 4, m=1, n=1)
for symbol in list(expr.free_symbols):
if str(symbol) in options.keys():
val = options[str(symbol)]
expr = expr.subs(symbol, val)
return expr.subs(zip(var, args))
def _eval_derivative(self, symbol):
expr = self.expr
deriv = expr._eval_derivative(symbol)
return Wavefunction(deriv, *self.args[1:])
def _eval_conjugate(self):
return Wavefunction(conjugate(self.expr), *self.args[1:])
def _eval_transpose(self):
return self
@property
def free_symbols(self):
return self.expr.free_symbols
@property
def is_commutative(self):
"""
Override Function's is_commutative so that order is preserved in
represented expressions
"""
return False
@classmethod
def eval(self, *args):
return None
@property
def variables(self):
"""
Return the coordinates which the wavefunction depends on
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x,y = symbols('x,y')
>>> f = Wavefunction(x*y, x, y)
>>> f.variables
(x, y)
>>> g = Wavefunction(x*y, x)
>>> g.variables
(x,)
"""
var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
return tuple(var)
@property
def limits(self):
"""
Return the limits of the coordinates which the w.f. depends on If no
limits are specified, defaults to ``(-oo, oo)``.
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, (x, 0, 1))
>>> f.limits
{x: (0, 1)}
>>> f = Wavefunction(x**2, x)
>>> f.limits
{x: (-oo, oo)}
>>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
>>> f.limits
{x: (-oo, oo), y: (-1, 2)}
"""
limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
for g in self._args[1:]]
return dict(zip(self.variables, tuple(limits)))
@property
def expr(self):
"""
Return the expression which is the functional form of the Wavefunction
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, x)
>>> f.expr
x**2
"""
return self._args[0]
@property
def is_normalized(self):
"""
Returns true if the Wavefunction is properly normalized
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.is_normalized
True
"""
return (self.norm == 1.0)
@property # type: ignore
@cacheit
def norm(self):
"""
Return the normalization of the specified functional form.
This function integrates over the coordinates of the Wavefunction, with
the bounds specified.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
sqrt(2)*sqrt(L)/2
"""
exp = self.expr*conjugate(self.expr)
var = self.variables
limits = self.limits
for v in var:
curr_limits = limits[v]
exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
return sqrt(exp)
def normalize(self):
"""
Return a normalized version of the Wavefunction
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = symbols('x', real=True)
>>> L = symbols('L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.normalize()
Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
"""
const = self.norm
if const is oo:
raise NotImplementedError("The function is not normalizable!")
else:
return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
def prob(self):
r"""
Return the absolute magnitude of the w.f., `|\psi(x)|^2`
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', real=True)
>>> n = symbols('n', integer=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.prob()
Wavefunction(sin(pi*n*x/L)**2, x)
"""
return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
|
b268d3a00d258fa85edb677d47ad442f6152357173f684c817cc7950e77844db | """Functions for reordering operator expressions."""
import warnings
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.physics.quantum import Operator, Commutator, AntiCommutator
from sympy.physics.quantum.boson import BosonOp
from sympy.physics.quantum.fermion import FermionOp
__all__ = [
'normal_order',
'normal_ordered_form'
]
def _expand_powers(factors):
"""
Helper function for normal_ordered_form and normal_order: Expand a
power expression to a multiplication expression so that that the
expression can be handled by the normal ordering functions.
"""
new_factors = []
for factor in factors.args:
if (isinstance(factor, Pow)
and isinstance(factor.args[1], Integer)
and factor.args[1] > 0):
for n in range(factor.args[1]):
new_factors.append(factor.args[0])
else:
new_factors.append(factor)
return new_factors
def _normal_ordered_form_factor(product, independent=False, recursive_limit=10,
_recursive_depth=0):
"""
Helper function for normal_ordered_form_factor: Write multiplication
expression with bosonic or fermionic operators on normally ordered form,
using the bosonic and fermionic commutation relations. The resulting
operator expression is equivalent to the argument, but will in general be
a sum of operator products instead of a simple product.
"""
factors = _expand_powers(product)
new_factors = []
n = 0
while n < len(factors) - 1:
if isinstance(factors[n], BosonOp):
# boson
if not isinstance(factors[n + 1], BosonOp):
new_factors.append(factors[n])
elif factors[n].is_annihilation == factors[n + 1].is_annihilation:
if (independent and
str(factors[n].name) > str(factors[n + 1].name)):
new_factors.append(factors[n + 1])
new_factors.append(factors[n])
n += 1
else:
new_factors.append(factors[n])
elif not factors[n].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n + 1].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n].args[0] != factors[n + 1].args[0]:
if independent:
c = 0
else:
c = Commutator(factors[n], factors[n + 1])
new_factors.append(factors[n + 1] * factors[n] + c)
else:
c = Commutator(factors[n], factors[n + 1])
new_factors.append(
factors[n + 1] * factors[n] + c.doit())
n += 1
elif isinstance(factors[n], FermionOp):
# fermion
if not isinstance(factors[n + 1], FermionOp):
new_factors.append(factors[n])
elif factors[n].is_annihilation == factors[n + 1].is_annihilation:
if (independent and
str(factors[n].name) > str(factors[n + 1].name)):
new_factors.append(factors[n + 1])
new_factors.append(factors[n])
n += 1
else:
new_factors.append(factors[n])
elif not factors[n].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n + 1].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n].args[0] != factors[n + 1].args[0]:
if independent:
c = 0
else:
c = AntiCommutator(factors[n], factors[n + 1])
new_factors.append(-factors[n + 1] * factors[n] + c)
else:
c = AntiCommutator(factors[n], factors[n + 1])
new_factors.append(
-factors[n + 1] * factors[n] + c.doit())
n += 1
elif isinstance(factors[n], Operator):
if isinstance(factors[n + 1], (BosonOp, FermionOp)):
new_factors.append(factors[n + 1])
new_factors.append(factors[n])
n += 1
else:
new_factors.append(factors[n])
else:
new_factors.append(factors[n])
n += 1
if n == len(factors) - 1:
new_factors.append(factors[-1])
if new_factors == factors:
return product
else:
expr = Mul(*new_factors).expand()
return normal_ordered_form(expr,
recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth + 1,
independent=independent)
def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10,
_recursive_depth=0):
"""
Helper function for normal_ordered_form: loop through each term in an
addition expression and call _normal_ordered_form_factor to perform the
factor to an normally ordered expression.
"""
new_terms = []
for term in expr.args:
if isinstance(term, Mul):
new_term = _normal_ordered_form_factor(
term, recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth, independent=independent)
new_terms.append(new_term)
else:
new_terms.append(term)
return Add(*new_terms)
def normal_ordered_form(expr, independent=False, recursive_limit=10,
_recursive_depth=0):
"""Write an expression with bosonic or fermionic operators on normal
ordered form, where each term is normally ordered. Note that this
normal ordered form is equivalent to the original expression.
Parameters
==========
expr : expression
The expression write on normal ordered form.
recursive_limit : int (default 10)
The number of allowed recursive applications of the function.
Examples
========
>>> from sympy.physics.quantum import Dagger
>>> from sympy.physics.quantum.boson import BosonOp
>>> from sympy.physics.quantum.operatorordering import normal_ordered_form
>>> a = BosonOp("a")
>>> normal_ordered_form(a * Dagger(a))
1 + Dagger(a)*a
"""
if _recursive_depth > recursive_limit:
warnings.warn("Too many recursions, aborting")
return expr
if isinstance(expr, Add):
return _normal_ordered_form_terms(expr,
recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth,
independent=independent)
elif isinstance(expr, Mul):
return _normal_ordered_form_factor(expr,
recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth,
independent=independent)
else:
return expr
def _normal_order_factor(product, recursive_limit=10, _recursive_depth=0):
"""
Helper function for normal_order: Normal order a multiplication expression
with bosonic or fermionic operators. In general the resulting operator
expression will not be equivalent to original product.
"""
factors = _expand_powers(product)
n = 0
new_factors = []
while n < len(factors) - 1:
if (isinstance(factors[n], BosonOp) and
factors[n].is_annihilation):
# boson
if not isinstance(factors[n + 1], BosonOp):
new_factors.append(factors[n])
else:
if factors[n + 1].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n].args[0] != factors[n + 1].args[0]:
new_factors.append(factors[n + 1] * factors[n])
else:
new_factors.append(factors[n + 1] * factors[n])
n += 1
elif (isinstance(factors[n], FermionOp) and
factors[n].is_annihilation):
# fermion
if not isinstance(factors[n + 1], FermionOp):
new_factors.append(factors[n])
else:
if factors[n + 1].is_annihilation:
new_factors.append(factors[n])
else:
if factors[n].args[0] != factors[n + 1].args[0]:
new_factors.append(-factors[n + 1] * factors[n])
else:
new_factors.append(-factors[n + 1] * factors[n])
n += 1
else:
new_factors.append(factors[n])
n += 1
if n == len(factors) - 1:
new_factors.append(factors[-1])
if new_factors == factors:
return product
else:
expr = Mul(*new_factors).expand()
return normal_order(expr,
recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth + 1)
def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0):
"""
Helper function for normal_order: look through each term in an addition
expression and call _normal_order_factor to perform the normal ordering
on the factors.
"""
new_terms = []
for term in expr.args:
if isinstance(term, Mul):
new_term = _normal_order_factor(term,
recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth)
new_terms.append(new_term)
else:
new_terms.append(term)
return Add(*new_terms)
def normal_order(expr, recursive_limit=10, _recursive_depth=0):
"""Normal order an expression with bosonic or fermionic operators. Note
that this normal order is not equivalent to the original expression, but
the creation and annihilation operators in each term in expr is reordered
so that the expression becomes normal ordered.
Parameters
==========
expr : expression
The expression to normal order.
recursive_limit : int (default 10)
The number of allowed recursive applications of the function.
Examples
========
>>> from sympy.physics.quantum import Dagger
>>> from sympy.physics.quantum.boson import BosonOp
>>> from sympy.physics.quantum.operatorordering import normal_order
>>> a = BosonOp("a")
>>> normal_order(a * Dagger(a))
Dagger(a)*a
"""
if _recursive_depth > recursive_limit:
warnings.warn("Too many recursions, aborting")
return expr
if isinstance(expr, Add):
return _normal_order_terms(expr, recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth)
elif isinstance(expr, Mul):
return _normal_order_factor(expr, recursive_limit=recursive_limit,
_recursive_depth=_recursive_depth)
else:
return expr
|
82a3fe0ee5b6f9073d063f6f0ba57d87703093603f976c68f3b1a251ea0e559a | """Operators and states for 1D cartesian position and momentum.
TODO:
* Add 3D classes to mappings in operatorset.py
"""
from sympy.core.numbers import (I, pi)
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.special.delta_functions import DiracDelta
from sympy.sets.sets import Interval
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.hilbert import L2
from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator
from sympy.physics.quantum.state import Ket, Bra, State
__all__ = [
'XOp',
'YOp',
'ZOp',
'PxOp',
'X',
'Y',
'Z',
'Px',
'XKet',
'XBra',
'PxKet',
'PxBra',
'PositionState3D',
'PositionKet3D',
'PositionBra3D'
]
#-------------------------------------------------------------------------
# Position operators
#-------------------------------------------------------------------------
class XOp(HermitianOperator):
"""1D cartesian position operator."""
@classmethod
def default_args(self):
return ("X",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _eval_commutator_PxOp(self, other):
return I*hbar
def _apply_operator_XKet(self, ket):
return ket.position*ket
def _apply_operator_PositionKet3D(self, ket):
return ket.position_x*ket
def _represent_PxKet(self, basis, *, index=1, **options):
states = basis._enumerate_state(2, start_index=index)
coord1 = states[0].momentum
coord2 = states[1].momentum
d = DifferentialOperator(coord1)
delta = DiracDelta(coord1 - coord2)
return I*hbar*(d*delta)
class YOp(HermitianOperator):
""" Y cartesian coordinate operator (for 2D or 3D systems) """
@classmethod
def default_args(self):
return ("Y",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PositionKet3D(self, ket):
return ket.position_y*ket
class ZOp(HermitianOperator):
""" Z cartesian coordinate operator (for 3D systems) """
@classmethod
def default_args(self):
return ("Z",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PositionKet3D(self, ket):
return ket.position_z*ket
#-------------------------------------------------------------------------
# Momentum operators
#-------------------------------------------------------------------------
class PxOp(HermitianOperator):
"""1D cartesian momentum operator."""
@classmethod
def default_args(self):
return ("Px",)
@classmethod
def _eval_hilbert_space(self, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PxKet(self, ket):
return ket.momentum*ket
def _represent_XKet(self, basis, *, index=1, **options):
states = basis._enumerate_state(2, start_index=index)
coord1 = states[0].position
coord2 = states[1].position
d = DifferentialOperator(coord1)
delta = DiracDelta(coord1 - coord2)
return -I*hbar*(d*delta)
X = XOp('X')
Y = YOp('Y')
Z = ZOp('Z')
Px = PxOp('Px')
#-------------------------------------------------------------------------
# Position eigenstates
#-------------------------------------------------------------------------
class XKet(Ket):
"""1D cartesian position eigenket."""
@classmethod
def _operators_to_state(self, op, **options):
return self.__new__(self, *_lowercase_labels(op), **options)
def _state_to_operators(self, op_class, **options):
return op_class.__new__(op_class,
*_uppercase_labels(self), **options)
@classmethod
def default_args(self):
return ("x",)
@classmethod
def dual_class(self):
return XBra
@property
def position(self):
"""The position of the state."""
return self.label[0]
def _enumerate_state(self, num_states, **options):
return _enumerate_continuous_1D(self, num_states, **options)
def _eval_innerproduct_XBra(self, bra, **hints):
return DiracDelta(self.position - bra.position)
def _eval_innerproduct_PxBra(self, bra, **hints):
return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar)
class XBra(Bra):
"""1D cartesian position eigenbra."""
@classmethod
def default_args(self):
return ("x",)
@classmethod
def dual_class(self):
return XKet
@property
def position(self):
"""The position of the state."""
return self.label[0]
class PositionState3D(State):
""" Base class for 3D cartesian position eigenstates """
@classmethod
def _operators_to_state(self, op, **options):
return self.__new__(self, *_lowercase_labels(op), **options)
def _state_to_operators(self, op_class, **options):
return op_class.__new__(op_class,
*_uppercase_labels(self), **options)
@classmethod
def default_args(self):
return ("x", "y", "z")
@property
def position_x(self):
""" The x coordinate of the state """
return self.label[0]
@property
def position_y(self):
""" The y coordinate of the state """
return self.label[1]
@property
def position_z(self):
""" The z coordinate of the state """
return self.label[2]
class PositionKet3D(Ket, PositionState3D):
""" 3D cartesian position eigenket """
def _eval_innerproduct_PositionBra3D(self, bra, **options):
x_diff = self.position_x - bra.position_x
y_diff = self.position_y - bra.position_y
z_diff = self.position_z - bra.position_z
return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff)
@classmethod
def dual_class(self):
return PositionBra3D
# XXX: The type:ignore here is because mypy gives Definition of
# "_state_to_operators" in base class "PositionState3D" is incompatible with
# definition in base class "BraBase"
class PositionBra3D(Bra, PositionState3D): # type: ignore
""" 3D cartesian position eigenbra """
@classmethod
def dual_class(self):
return PositionKet3D
#-------------------------------------------------------------------------
# Momentum eigenstates
#-------------------------------------------------------------------------
class PxKet(Ket):
"""1D cartesian momentum eigenket."""
@classmethod
def _operators_to_state(self, op, **options):
return self.__new__(self, *_lowercase_labels(op), **options)
def _state_to_operators(self, op_class, **options):
return op_class.__new__(op_class,
*_uppercase_labels(self), **options)
@classmethod
def default_args(self):
return ("px",)
@classmethod
def dual_class(self):
return PxBra
@property
def momentum(self):
"""The momentum of the state."""
return self.label[0]
def _enumerate_state(self, *args, **options):
return _enumerate_continuous_1D(self, *args, **options)
def _eval_innerproduct_XBra(self, bra, **hints):
return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar)
def _eval_innerproduct_PxBra(self, bra, **hints):
return DiracDelta(self.momentum - bra.momentum)
class PxBra(Bra):
"""1D cartesian momentum eigenbra."""
@classmethod
def default_args(self):
return ("px",)
@classmethod
def dual_class(self):
return PxKet
@property
def momentum(self):
"""The momentum of the state."""
return self.label[0]
#-------------------------------------------------------------------------
# Global helper functions
#-------------------------------------------------------------------------
def _enumerate_continuous_1D(*args, **options):
state = args[0]
num_states = args[1]
state_class = state.__class__
index_list = options.pop('index_list', [])
if len(index_list) == 0:
start_index = options.pop('start_index', 1)
index_list = list(range(start_index, start_index + num_states))
enum_states = [0 for i in range(len(index_list))]
for i, ind in enumerate(index_list):
label = state.args[0]
enum_states[i] = state_class(str(label) + "_" + str(ind), **options)
return enum_states
def _lowercase_labels(ops):
if not isinstance(ops, set):
ops = [ops]
return [str(arg.label[0]).lower() for arg in ops]
def _uppercase_labels(ops):
if not isinstance(ops, set):
ops = [ops]
new_args = [str(arg.label[0])[0].upper() +
str(arg.label[0])[1:] for arg in ops]
return new_args
|
7fc3be3d3c09d25ce28b17c07bc786b9a8cf31b9c085c77523b27fe70b9a9219 | """Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
from sympy.core.expr import Expr
from sympy.core.numbers import I
from sympy.core.singleton import S
from sympy.matrices.matrices import MatrixBase
from sympy.matrices import eye, zeros
from sympy.external import import_module
__all__ = [
'numpy_ndarray',
'scipy_sparse_matrix',
'sympy_to_numpy',
'sympy_to_scipy_sparse',
'numpy_to_sympy',
'scipy_sparse_to_sympy',
'flatten_scalar',
'matrix_dagger',
'to_sympy',
'to_numpy',
'to_scipy_sparse',
'matrix_tensor_product',
'matrix_zeros'
]
# Conditionally define the base classes for numpy and scipy.sparse arrays
# for use in isinstance tests.
np = import_module('numpy')
if not np:
class numpy_ndarray:
pass
else:
numpy_ndarray = np.ndarray # type: ignore
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
if not scipy:
class scipy_sparse_matrix:
pass
sparse = None
else:
sparse = scipy.sparse
# Try to find spmatrix.
if hasattr(sparse, 'base'):
# Newer versions have it under scipy.sparse.base.
scipy_sparse_matrix = sparse.base.spmatrix # type: ignore
elif hasattr(sparse, 'sparse'):
# Older versions have it under scipy.sparse.sparse.
scipy_sparse_matrix = sparse.sparse.spmatrix # type: ignore
def sympy_to_numpy(m, **options):
"""Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
if not np:
raise ImportError
dtype = options.get('dtype', 'complex')
if isinstance(m, MatrixBase):
return np.matrix(m.tolist(), dtype=dtype)
elif isinstance(m, Expr):
if m.is_Number or m.is_NumberSymbol or m == I:
return complex(m)
raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
def sympy_to_scipy_sparse(m, **options):
"""Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
if not np or not sparse:
raise ImportError
dtype = options.get('dtype', 'complex')
if isinstance(m, MatrixBase):
return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype))
elif isinstance(m, Expr):
if m.is_Number or m.is_NumberSymbol or m == I:
return complex(m)
raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
def scipy_sparse_to_sympy(m, **options):
"""Convert a scipy.sparse matrix to a SymPy matrix."""
return MatrixBase(m.todense())
def numpy_to_sympy(m, **options):
"""Convert a numpy matrix to a SymPy matrix."""
return MatrixBase(m)
def to_sympy(m, **options):
"""Convert a numpy/scipy.sparse matrix to a SymPy matrix."""
if isinstance(m, MatrixBase):
return m
elif isinstance(m, numpy_ndarray):
return numpy_to_sympy(m)
elif isinstance(m, scipy_sparse_matrix):
return scipy_sparse_to_sympy(m)
elif isinstance(m, Expr):
return m
raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
def to_numpy(m, **options):
"""Convert a sympy/scipy.sparse matrix to a numpy matrix."""
dtype = options.get('dtype', 'complex')
if isinstance(m, (MatrixBase, Expr)):
return sympy_to_numpy(m, dtype=dtype)
elif isinstance(m, numpy_ndarray):
return m
elif isinstance(m, scipy_sparse_matrix):
return m.todense()
raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
def to_scipy_sparse(m, **options):
"""Convert a sympy/numpy matrix to a scipy.sparse matrix."""
dtype = options.get('dtype', 'complex')
if isinstance(m, (MatrixBase, Expr)):
return sympy_to_scipy_sparse(m, dtype=dtype)
elif isinstance(m, numpy_ndarray):
if not sparse:
raise ImportError
return sparse.csr_matrix(m)
elif isinstance(m, scipy_sparse_matrix):
return m
raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
def flatten_scalar(e):
"""Flatten a 1x1 matrix to a scalar, return larger matrices unchanged."""
if isinstance(e, MatrixBase):
if e.shape == (1, 1):
e = e[0]
if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
if e.shape == (1, 1):
e = complex(e[0, 0])
return e
def matrix_dagger(e):
"""Return the dagger of a sympy/numpy/scipy.sparse matrix."""
if isinstance(e, MatrixBase):
return e.H
elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
return e.conjugate().transpose()
raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e)
# TODO: Move this into sympy.matricies.
def _sympy_tensor_product(*matrices):
"""Compute the kronecker product of a sequence of SymPy Matrices.
"""
from sympy.matrices.expressions.kronecker import matrix_kronecker_product
return matrix_kronecker_product(*matrices)
def _numpy_tensor_product(*product):
"""numpy version of tensor product of multiple arguments."""
if not np:
raise ImportError
answer = product[0]
for item in product[1:]:
answer = np.kron(answer, item)
return answer
def _scipy_sparse_tensor_product(*product):
"""scipy.sparse version of tensor product of multiple arguments."""
if not sparse:
raise ImportError
answer = product[0]
for item in product[1:]:
answer = sparse.kron(answer, item)
# The final matrices will just be multiplied, so csr is a good final
# sparse format.
return sparse.csr_matrix(answer)
def matrix_tensor_product(*product):
"""Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices."""
if isinstance(product[0], MatrixBase):
return _sympy_tensor_product(*product)
elif isinstance(product[0], numpy_ndarray):
return _numpy_tensor_product(*product)
elif isinstance(product[0], scipy_sparse_matrix):
return _scipy_sparse_tensor_product(*product)
def _numpy_eye(n):
"""numpy version of complex eye."""
if not np:
raise ImportError
return np.matrix(np.eye(n, dtype='complex'))
def _scipy_sparse_eye(n):
"""scipy.sparse version of complex eye."""
if not sparse:
raise ImportError
return sparse.eye(n, n, dtype='complex')
def matrix_eye(n, **options):
"""Get the version of eye and tensor_product for a given format."""
format = options.get('format', 'sympy')
if format == 'sympy':
return eye(n)
elif format == 'numpy':
return _numpy_eye(n)
elif format == 'scipy.sparse':
return _scipy_sparse_eye(n)
raise NotImplementedError('Invalid format: %r' % format)
def _numpy_zeros(m, n, **options):
"""numpy version of zeros."""
dtype = options.get('dtype', 'float64')
if not np:
raise ImportError
return np.zeros((m, n), dtype=dtype)
def _scipy_sparse_zeros(m, n, **options):
"""scipy.sparse version of zeros."""
spmatrix = options.get('spmatrix', 'csr')
dtype = options.get('dtype', 'float64')
if not sparse:
raise ImportError
if spmatrix == 'lil':
return sparse.lil_matrix((m, n), dtype=dtype)
elif spmatrix == 'csr':
return sparse.csr_matrix((m, n), dtype=dtype)
def matrix_zeros(m, n, **options):
""""Get a zeros matrix for a given format."""
format = options.get('format', 'sympy')
if format == 'sympy':
return zeros(m, n)
elif format == 'numpy':
return _numpy_zeros(m, n, **options)
elif format == 'scipy.sparse':
return _scipy_sparse_zeros(m, n, **options)
raise NotImplementedError('Invaild format: %r' % format)
def _numpy_matrix_to_zero(e):
"""Convert a numpy zero matrix to the zero scalar."""
if not np:
raise ImportError
test = np.zeros_like(e)
if np.allclose(e, test):
return 0.0
else:
return e
def _scipy_sparse_matrix_to_zero(e):
"""Convert a scipy.sparse zero matrix to the zero scalar."""
if not np:
raise ImportError
edense = e.todense()
test = np.zeros_like(edense)
if np.allclose(edense, test):
return 0.0
else:
return e
def matrix_to_zero(e):
"""Convert a zero matrix to the scalar zero."""
if isinstance(e, MatrixBase):
if zeros(*e.shape) == e:
e = S.Zero
elif isinstance(e, numpy_ndarray):
e = _numpy_matrix_to_zero(e)
elif isinstance(e, scipy_sparse_matrix):
e = _scipy_sparse_matrix_to_zero(e)
return e
|
661911ef84e10301e1da1a94e2e9500d00d751be2a185c6dc61dff71ebc72861 | """An implementation of gates that act on qubits.
Gates are unitary operators that act on the space of qubits.
Medium Term Todo:
* Optimize Gate._apply_operators_Qubit to remove the creation of many
intermediate Qubit objects.
* Add commutation relationships to all operators and use this in gate_sort.
* Fix gate_sort and gate_simp.
* Get multi-target UGates plotting properly.
* Get UGate to work with either sympy/numpy matrices and output either
format. This should also use the matrix slots.
"""
from itertools import chain
import random
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer)
from sympy.core.power import Pow
from sympy.core.numbers import Number
from sympy.core.singleton import S as _S
from sympy.core.sorting import default_sort_key
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
HermitianOperator)
from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
from sympy.physics.quantum.matrixcache import matrix_cache
from sympy.matrices.matrices import MatrixBase
from sympy.utilities.iterables import is_sequence
__all__ = [
'Gate',
'CGate',
'UGate',
'OneQubitGate',
'TwoQubitGate',
'IdentityGate',
'HadamardGate',
'XGate',
'YGate',
'ZGate',
'TGate',
'PhaseGate',
'SwapGate',
'CNotGate',
# Aliased gate names
'CNOT',
'SWAP',
'H',
'X',
'Y',
'Z',
'T',
'S',
'Phase',
'normalized',
'gate_sort',
'gate_simp',
'random_circuit',
'CPHASE',
'CGateS',
]
#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------
_normalized = True
def _max(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
def _min(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
def normalized(normalize):
"""Set flag controlling normalization of Hadamard gates by 1/sqrt(2).
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate.
Parameters
----------
normalize : bool
Should the Hadamard gate include the 1/sqrt(2) normalization factor?
When True, the Hadamard gate will have the 1/sqrt(2). When False, the
Hadamard gate will not have this factor.
"""
global _normalized
_normalized = normalize
def _validate_targets_controls(tandc):
tandc = list(tandc)
# Check for integers
for bit in tandc:
if not bit.is_Integer and not bit.is_Symbol:
raise TypeError('Integer expected, got: %r' % tandc[bit])
# Detect duplicates
if len(list(set(tandc))) != len(tandc):
raise QuantumError(
'Target/control qubits in a gate cannot be duplicated'
)
class Gate(UnitaryOperator):
"""Non-controlled unitary gate operator that acts on qubits.
This is a general abstract gate that needs to be subclassed to do anything
useful.
Parameters
----------
label : tuple, int
A list of the target qubits (as ints) that the gate will apply to.
Examples
========
"""
_label_separator = ','
gate_name = 'G'
gate_name_latex = 'G'
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Tuple(*UnitaryOperator._eval_args(args))
_validate_targets_controls(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.targets) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.label
@property
def gate_name_plot(self):
return r'$%s$' % self.gate_name_latex
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix rep. of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
raise NotImplementedError(
'get_target_matrix is not implemented in Gate.')
#-------------------------------------------------------------------------
# Apply
#-------------------------------------------------------------------------
def _apply_operator_IntQubit(self, qubits, **options):
"""Redirect an apply from IntQubit to Qubit"""
return self._apply_operator_Qubit(qubits, **options)
def _apply_operator_Qubit(self, qubits, **options):
"""Apply this gate to a Qubit."""
# Check number of qubits this gate acts on.
if qubits.nqubits < self.min_qubits:
raise QuantumError(
'Gate needs a minimum of %r qubits to act on, got: %r' %
(self.min_qubits, qubits.nqubits)
)
# If the controls are not met, just return
if isinstance(self, CGate):
if not self.eval_controls(qubits):
return qubits
targets = self.targets
target_matrix = self.get_target_matrix(format='sympy')
# Find which column of the target matrix this applies to.
column_index = 0
n = 1
for target in targets:
column_index += n*qubits[target]
n = n << 1
column = target_matrix[:, int(column_index)]
# Now apply each column element to the qubit.
result = 0
for index in range(column.rows):
# TODO: This can be optimized to reduce the number of Qubit
# creations. We should simply manipulate the raw list of qubit
# values and then build the new Qubit object once.
# Make a copy of the incoming qubits.
new_qubit = qubits.__class__(*qubits.args)
# Flip the bits that need to be flipped.
for bit in range(len(targets)):
if new_qubit[targets[bit]] != (index >> bit) & 1:
new_qubit = new_qubit.flip(targets[bit])
# The value in that row and column times the flipped-bit qubit
# is the result for that part.
result += column[index]*new_qubit
return result
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
format = options.get('format', 'sympy')
nqubits = options.get('nqubits', 0)
if nqubits == 0:
raise QuantumError(
'The number of qubits must be given as nqubits.')
# Make sure we have enough qubits for the gate.
if nqubits < self.min_qubits:
raise QuantumError(
'The number of qubits %r is too small for the gate.' % nqubits
)
target_matrix = self.get_target_matrix(format)
targets = self.targets
if isinstance(self, CGate):
controls = self.controls
else:
controls = []
m = represent_zbasis(
controls, targets, target_matrix, nqubits, format
)
return m
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _sympystr(self, printer, *args):
label = self._print_label(printer, *args)
return '%s(%s)' % (self.gate_name, label)
def _pretty(self, printer, *args):
a = stringPict(self.gate_name)
b = self._print_label_pretty(printer, *args)
return self._print_subscript_pretty(a, b)
def _latex(self, printer, *args):
label = self._print_label(printer, *args)
return '%s_{%s}' % (self.gate_name_latex, label)
def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
raise NotImplementedError('plot_gate is not implemented.')
class CGate(Gate):
"""A general unitary gate with control qubits.
A general control gate applies a target gate to a set of targets if all
of the control qubits have a particular values (set by
``CGate.control_value``).
Parameters
----------
label : tuple
The label in this case has the form (controls, gate), where controls
is a tuple/list of control qubits (as ints) and gate is a ``Gate``
instance that is the target operator.
Examples
========
"""
gate_name = 'C'
gate_name_latex = 'C'
# The values this class controls for.
control_value = _S.One
simplify_cgate = False
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# _eval_args has the right logic for the controls argument.
controls = args[0]
gate = args[1]
if not is_sequence(controls):
controls = (controls,)
controls = UnitaryOperator._eval_args(controls)
_validate_targets_controls(chain(controls, gate.targets))
return (Tuple(*controls), gate)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets) + len(self.controls)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(_max(self.controls), _max(self.targets)) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.gate.targets
@property
def controls(self):
"""A tuple of control qubits."""
return tuple(self.label[0])
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return self.label[1]
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
return self.gate.get_target_matrix(format)
def eval_controls(self, qubit):
"""Return True/False to indicate if the controls are satisfied."""
return all(qubit[bit] == self.control_value for bit in self.controls)
def decompose(self, **options):
"""Decompose the controlled gate into CNOT and single qubits gates."""
if len(self.controls) == 1:
c = self.controls[0]
t = self.gate.targets[0]
if isinstance(self.gate, YGate):
g1 = PhaseGate(t)
g2 = CNotGate(c, t)
g3 = PhaseGate(t)
g4 = ZGate(t)
return g1*g2*g3*g4
if isinstance(self.gate, ZGate):
g1 = HadamardGate(t)
g2 = CNotGate(c, t)
g3 = HadamardGate(t)
return g1*g2*g3
else:
return self
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _print_label(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return '(%s),%s' % (controls, gate)
def _pretty(self, printer, *args):
controls = self._print_sequence_pretty(
self.controls, ',', printer, *args)
gate = printer._print(self.gate)
gate_name = stringPict(self.gate_name)
first = self._print_subscript_pretty(gate_name, controls)
gate = self._print_parens_pretty(gate)
final = prettyForm(*first.right(gate))
return final
def _latex(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return r'%s_{%s}{\left(%s\right)}' % \
(self.gate_name_latex, controls, gate)
def plot_gate(self, circ_plot, gate_idx):
"""
Plot the controlled gate. If *simplify_cgate* is true, simplify
C-X and C-Z gates into their more familiar forms.
"""
min_wire = int(_min(chain(self.controls, self.targets)))
max_wire = int(_max(chain(self.controls, self.targets)))
circ_plot.control_line(gate_idx, min_wire, max_wire)
for c in self.controls:
circ_plot.control_point(gate_idx, int(c))
if self.simplify_cgate:
if self.gate.gate_name == 'X':
self.gate.plot_gate_plus(circ_plot, gate_idx)
elif self.gate.gate_name == 'Z':
circ_plot.control_point(gate_idx, self.targets[0])
else:
self.gate.plot_gate(circ_plot, gate_idx)
else:
self.gate.plot_gate(circ_plot, gate_idx)
#-------------------------------------------------------------------------
# Miscellaneous
#-------------------------------------------------------------------------
def _eval_dagger(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_dagger(self)
def _eval_inverse(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self.gate, HermitianOperator):
if exp == -1:
return Gate._eval_power(self, exp)
elif abs(exp) % 2 == 0:
return self*(Gate._eval_inverse(self))
else:
return self
else:
return Gate._eval_power(self, exp)
class CGateS(CGate):
"""Version of CGate that allows gate simplifications.
I.e. cnot looks like an oplus, cphase has dots, etc.
"""
simplify_cgate=True
class UGate(Gate):
"""General gate specified by a set of targets and a target matrix.
Parameters
----------
label : tuple
A tuple of the form (targets, U), where targets is a tuple of the
target qubits and U is a unitary matrix with dimension of
len(targets).
"""
gate_name = 'U'
gate_name_latex = 'U'
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
targets = args[0]
if not is_sequence(targets):
targets = (targets,)
targets = Gate._eval_args(targets)
_validate_targets_controls(targets)
mat = args[1]
if not isinstance(mat, MatrixBase):
raise TypeError('Matrix expected, got: %r' % mat)
dim = 2**len(targets)
if not all(dim == shape for shape in mat.shape):
raise IndexError(
'Number of targets must match the matrix size: %r %r' %
(targets, mat)
)
return (targets, mat)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args[0]) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def targets(self):
"""A tuple of target qubits."""
return tuple(self.label[0])
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix rep. of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
return self.label[1]
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _pretty(self, printer, *args):
targets = self._print_sequence_pretty(
self.targets, ',', printer, *args)
gate_name = stringPict(self.gate_name)
return self._print_subscript_pretty(gate_name, targets)
def _latex(self, printer, *args):
targets = self._print_sequence(self.targets, ',', printer, *args)
return r'%s_{%s}' % (self.gate_name_latex, targets)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
class OneQubitGate(Gate):
"""A single qubit unitary gate base class."""
nqubits = _S.One
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
def _eval_commutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return _S.Zero
return Operator._eval_commutator(self, other, **hints)
def _eval_anticommutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return Integer(2)*self*other
return Operator._eval_anticommutator(self, other, **hints)
class TwoQubitGate(Gate):
"""A two qubit unitary gate base class."""
nqubits = Integer(2)
#-----------------------------------------------------------------------------
# Single Qubit Gates
#-----------------------------------------------------------------------------
class IdentityGate(OneQubitGate):
"""The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = '1'
gate_name_latex = '1'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('eye2', format)
def _eval_commutator(self, other, **hints):
return _S.Zero
def _eval_anticommutator(self, other, **hints):
return Integer(2)*other
class HadamardGate(HermitianOperator, OneQubitGate):
"""The single qubit Hadamard gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
>>> from sympy import sqrt
>>> from sympy.physics.quantum.qubit import Qubit
>>> from sympy.physics.quantum.gate import HadamardGate
>>> from sympy.physics.quantum.qapply import qapply
>>> qapply(HadamardGate(0)*Qubit('1'))
sqrt(2)*|0>/2 - sqrt(2)*|1>/2
>>> # Hadamard on bell state, applied on 2 qubits.
>>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
>>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
sqrt(2)*|00>/2 + sqrt(2)*|11>/2
"""
gate_name = 'H'
gate_name_latex = 'H'
def get_target_matrix(self, format='sympy'):
if _normalized:
return matrix_cache.get_matrix('H', format)
else:
return matrix_cache.get_matrix('Hsqrt2', format)
def _eval_commutator_XGate(self, other, **hints):
return I*sqrt(2)*YGate(self.targets[0])
def _eval_commutator_YGate(self, other, **hints):
return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
def _eval_commutator_ZGate(self, other, **hints):
return -I*sqrt(2)*YGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
class XGate(HermitianOperator, OneQubitGate):
"""The single qubit X, or NOT, gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'X'
gate_name_latex = 'X'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('X', format)
def plot_gate(self, circ_plot, gate_idx):
OneQubitGate.plot_gate(self,circ_plot,gate_idx)
def plot_gate_plus(self, circ_plot, gate_idx):
circ_plot.not_point(
gate_idx, int(self.label[0])
)
def _eval_commutator_YGate(self, other, **hints):
return Integer(2)*I*ZGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class YGate(HermitianOperator, OneQubitGate):
"""The single qubit Y gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Y'
gate_name_latex = 'Y'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Y', format)
def _eval_commutator_ZGate(self, other, **hints):
return Integer(2)*I*XGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class ZGate(HermitianOperator, OneQubitGate):
"""The single qubit Z gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Z'
gate_name_latex = 'Z'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Z', format)
def _eval_commutator_XGate(self, other, **hints):
return Integer(2)*I*YGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
class PhaseGate(OneQubitGate):
"""The single qubit phase, or S, gate.
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'S'
gate_name_latex = 'S'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('S', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_TGate(self, other, **hints):
return _S.Zero
class TGate(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'T'
gate_name_latex = 'T'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('T', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_PhaseGate(self, other, **hints):
return _S.Zero
# Aliases for gate names.
H = HadamardGate
X = XGate
Y = YGate
Z = ZGate
T = TGate
Phase = S = PhaseGate
#-----------------------------------------------------------------------------
# 2 Qubit Gates
#-----------------------------------------------------------------------------
class CNotGate(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
========
>>> from sympy.physics.quantum.gate import CNOT
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import Qubit
>>> c = CNOT(1,0)
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|11>
"""
gate_name = 'CNOT'
gate_name_latex = 'CNOT'
simplify_cgate = True
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Gate._eval_args(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.label) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return (self.label[1],)
@property
def controls(self):
"""A tuple of control qubits."""
return (self.label[0],)
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return XGate(self.label[1])
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
# The default printing of Gate works better than those of CGate, so we
# go around the overridden methods in CGate.
def _print_label(self, printer, *args):
return Gate._print_label(self, printer, *args)
def _pretty(self, printer, *args):
return Gate._pretty(self, printer, *args)
def _latex(self, printer, *args):
return Gate._latex(self, printer, *args)
#-------------------------------------------------------------------------
# Commutator/AntiCommutator
#-------------------------------------------------------------------------
def _eval_commutator_ZGate(self, other, **hints):
"""[CNOT(i, j), Z(i)] == 0."""
if self.controls[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_TGate(self, other, **hints):
"""[CNOT(i, j), T(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_PhaseGate(self, other, **hints):
"""[CNOT(i, j), S(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_XGate(self, other, **hints):
"""[CNOT(i, j), X(j)] == 0."""
if self.targets[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_CNotGate(self, other, **hints):
"""[CNOT(i, j), CNOT(i,k)] == 0."""
if self.controls[0] == other.controls[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
class SwapGate(TwoQubitGate):
"""Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
========
"""
gate_name = 'SWAP'
gate_name_latex = 'SWAP'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('SWAP', format)
def decompose(self, **options):
"""Decompose the SWAP gate into CNOT gates."""
i, j = self.targets[0], self.targets[1]
g1 = CNotGate(i, j)
g2 = CNotGate(j, i)
return g1*g2*g1
def plot_gate(self, circ_plot, gate_idx):
min_wire = int(_min(self.targets))
max_wire = int(_max(self.targets))
circ_plot.control_line(gate_idx, min_wire, max_wire)
circ_plot.swap_point(gate_idx, min_wire)
circ_plot.swap_point(gate_idx, max_wire)
def _represent_ZGate(self, basis, **options):
"""Represent the SWAP gate in the computational basis.
The following representation is used to compute this:
SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
"""
format = options.get('format', 'sympy')
targets = [int(t) for t in self.targets]
min_target = _min(targets)
max_target = _max(targets)
nqubits = options.get('nqubits', self.min_qubits)
op01 = matrix_cache.get_matrix('op01', format)
op10 = matrix_cache.get_matrix('op10', format)
op11 = matrix_cache.get_matrix('op11', format)
op00 = matrix_cache.get_matrix('op00', format)
eye2 = matrix_cache.get_matrix('eye2', format)
result = None
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
product = nqubits*[eye2]
product[nqubits - min_target - 1] = i
product[nqubits - max_target - 1] = j
new_result = matrix_tensor_product(*product)
if result is None:
result = new_result
else:
result = result + new_result
return result
# Aliases for gate names.
CNOT = CNotGate
SWAP = SwapGate
def CPHASE(a,b): return CGateS((a,),Z(b))
#-----------------------------------------------------------------------------
# Represent
#-----------------------------------------------------------------------------
def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
"""Represent a gate with controls, targets and target_matrix.
This function does the low-level work of representing gates as matrices
in the standard computational basis (ZGate). Currently, we support two
main cases:
1. One target qubit and no control qubits.
2. One target qubits and multiple control qubits.
For the base of multiple controls, we use the following expression [1]:
1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
Parameters
----------
controls : list, tuple
A sequence of control qubits.
targets : list, tuple
A sequence of target qubits.
target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
The matrix form of the transformation to be performed on the target
qubits. The format of this matrix must match that passed into
the `format` argument.
nqubits : int
The total number of qubits used for the representation.
format : str
The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
Examples
========
References
----------
[1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
"""
controls = [int(x) for x in controls]
targets = [int(x) for x in targets]
nqubits = int(nqubits)
# This checks for the format as well.
op11 = matrix_cache.get_matrix('op11', format)
eye2 = matrix_cache.get_matrix('eye2', format)
# Plain single qubit case
if len(controls) == 0 and len(targets) == 1:
product = []
bit = targets[0]
# Fill product with [I1,Gate,I2] such that the unitaries,
# I, cause the gate to be applied to the correct Qubit
if bit != nqubits - 1:
product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
product.append(target_matrix)
if bit != 0:
product.append(matrix_eye(2**bit, format=format))
return matrix_tensor_product(*product)
# Single target, multiple controls.
elif len(targets) == 1 and len(controls) >= 1:
target = targets[0]
# Build the non-trivial part.
product2 = []
for i in range(nqubits):
product2.append(matrix_eye(2, format=format))
for control in controls:
product2[nqubits - 1 - control] = op11
product2[nqubits - 1 - target] = target_matrix - eye2
return matrix_eye(2**nqubits, format=format) + \
matrix_tensor_product(*product2)
# Multi-target, multi-control is not yet implemented.
else:
raise NotImplementedError(
'The representation of multi-target, multi-control gates '
'is not implemented.'
)
#-----------------------------------------------------------------------------
# Gate manipulation functions.
#-----------------------------------------------------------------------------
def gate_simp(circuit):
"""Simplifies gates symbolically
It first sorts gates using gate_sort. It then applies basic
simplification rules to the circuit, e.g., XGate**2 = Identity
"""
# Bubble sort out gates that commute.
circuit = gate_sort(circuit)
# Do simplifications by subing a simplification into the first element
# which can be simplified. We recursively call gate_simp with new circuit
# as input more simplifications exist.
if isinstance(circuit, Add):
return sum(gate_simp(t) for t in circuit.args)
elif isinstance(circuit, Mul):
circuit_args = circuit.args
elif isinstance(circuit, Pow):
b, e = circuit.as_base_exp()
circuit_args = (gate_simp(b)**e,)
else:
return circuit
# Iterate through each element in circuit, simplify if possible.
for i in range(len(circuit_args)):
# H,X,Y or Z squared is 1.
# T**2 = S, S**2 = Z
if isinstance(circuit_args[i], Pow):
if isinstance(circuit_args[i].base,
(HadamardGate, XGate, YGate, ZGate)) \
and isinstance(circuit_args[i].exp, Number):
# Build a new circuit taking replacing the
# H,X,Y,Z squared with one.
newargs = (circuit_args[:i] +
(circuit_args[i].base**(circuit_args[i].exp % 2),) +
circuit_args[i + 1:])
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, PhaseGate):
# Build a new circuit taking old circuit but splicing
# in simplification.
newargs = circuit_args[:i]
# Replace PhaseGate**2 with ZGate.
newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
(Integer(circuit_args[i].exp/2)), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, TGate):
# Build a new circuit taking all the old elements.
newargs = circuit_args[:i]
# Put an Phasegate in place of any TGate**2.
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
Integer(circuit_args[i].exp/2), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
return circuit
def gate_sort(circuit):
"""Sorts the gates while keeping track of commutation relations
This function uses a bubble sort to rearrange the order of gate
application. Keeps track of Quantum computations special commutation
relations (e.g. things that apply to the same Qubit do not commute with
each other)
circuit is the Mul of gates that are to be sorted.
"""
# Make sure we have an Add or Mul.
if isinstance(circuit, Add):
return sum(gate_sort(t) for t in circuit.args)
if isinstance(circuit, Pow):
return gate_sort(circuit.base)**circuit.exp
elif isinstance(circuit, Gate):
return circuit
if not isinstance(circuit, Mul):
return circuit
changes = True
while changes:
changes = False
circ_array = circuit.args
for i in range(len(circ_array) - 1):
# Go through each element and switch ones that are in wrong order
if isinstance(circ_array[i], (Gate, Pow)) and \
isinstance(circ_array[i + 1], (Gate, Pow)):
# If we have a Pow object, look at only the base
first_base, first_exp = circ_array[i].as_base_exp()
second_base, second_exp = circ_array[i + 1].as_base_exp()
# Use SymPy's hash based sorting. This is not mathematical
# sorting, but is rather based on comparing hashes of objects.
# See Basic.compare for details.
if first_base.compare(second_base) > 0:
if Commutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
circuit = Mul(*new_args)
changes = True
break
if AntiCommutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
sign = _S.NegativeOne**(first_exp*second_exp)
circuit = sign*Mul(*new_args)
changes = True
break
return circuit
#-----------------------------------------------------------------------------
# Utility functions
#-----------------------------------------------------------------------------
def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
"""Return a random circuit of ngates and nqubits.
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
gates.
Parameters
----------
ngates : int
The number of gates in the circuit.
nqubits : int
The number of qubits in the circuit.
gate_space : tuple
A tuple of the gate classes that will be used in the circuit.
Repeating gate classes multiple times in this tuple will increase
the frequency they appear in the random circuit.
"""
qubit_space = range(nqubits)
result = []
for i in range(ngates):
g = random.choice(gate_space)
if g == CNotGate or g == SwapGate:
qubits = random.sample(qubit_space, 2)
g = g(*qubits)
else:
qubit = random.choice(qubit_space)
g = g(qubit)
result.append(g)
return Mul(*result)
def zx_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
def zy_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to Y basis."""
return matrix_cache.get_matrix('ZY', format)
|
7aa8061cde62475f4bbb0088fdfc4b88c87d25964bb84d4274871465c24151c9 | """Logic for representing operators in state in various bases.
TODO:
* Get represent working with continuous hilbert spaces.
* Document default basis functionality.
"""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import I
from sympy.core.power import Pow
from sympy.integrals.integrals import integrate
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.matrixutils import flatten_scalar
from sympy.physics.quantum.state import KetBase, BraBase, StateBase
from sympy.physics.quantum.operator import Operator, OuterProduct
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators
__all__ = [
'represent',
'rep_innerproduct',
'rep_expectation',
'integrate_result',
'get_basis',
'enumerate_states'
]
#-----------------------------------------------------------------------------
# Represent
#-----------------------------------------------------------------------------
def _sympy_to_scalar(e):
"""Convert from a SymPy scalar to a Python scalar."""
if isinstance(e, Expr):
if e.is_Integer:
return int(e)
elif e.is_Float:
return float(e)
elif e.is_Rational:
return float(e)
elif e.is_Number or e.is_NumberSymbol or e == I:
return complex(e)
raise TypeError('Expected number, got: %r' % e)
def represent(expr, **options):
"""Represent the quantum expression in the given basis.
In quantum mechanics abstract states and operators can be represented in
various basis sets. Under this operation the follow transforms happen:
* Ket -> column vector or function
* Bra -> row vector of function
* Operator -> matrix or differential operator
This function is the top-level interface for this action.
This function walks the SymPy expression tree looking for ``QExpr``
instances that have a ``_represent`` method. This method is then called
and the object is replaced by the representation returned by this method.
By default, the ``_represent`` method will dispatch to other methods
that handle the representation logic for a particular basis set. The
naming convention for these methods is the following::
def _represent_FooBasis(self, e, basis, **options)
This function will have the logic for representing instances of its class
in the basis set having a class named ``FooBasis``.
Parameters
==========
expr : Expr
The expression to represent.
basis : Operator, basis set
An object that contains the information about the basis set. If an
operator is used, the basis is assumed to be the orthonormal
eigenvectors of that operator. In general though, the basis argument
can be any object that contains the basis set information.
options : dict
Key/value pairs of options that are passed to the underlying method
that finds the representation. These options can be used to
control how the representation is done. For example, this is where
the size of the basis set would be set.
Returns
=======
e : Expr
The SymPy expression of the represented quantum expression.
Examples
========
Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator
and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp``
method, the ket can be represented in the z-spin basis.
>>> from sympy.physics.quantum import Operator, represent, Ket
>>> from sympy import Matrix
>>> class SzUpKet(Ket):
... def _represent_SzOp(self, basis, **options):
... return Matrix([1,0])
...
>>> class SzOp(Operator):
... pass
...
>>> sz = SzOp('Sz')
>>> up = SzUpKet('up')
>>> represent(up, basis=sz)
Matrix([
[1],
[0]])
Here we see an example of representations in a continuous
basis. We see that the result of representing various combinations
of cartesian position operators and kets give us continuous
expressions involving DiracDelta functions.
>>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra
>>> X = XOp()
>>> x = XKet()
>>> y = XBra('y')
>>> represent(X*x)
x*DiracDelta(x - x_2)
>>> represent(X*x*y)
x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
"""
format = options.get('format', 'sympy')
if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
options['replace_none'] = False
temp_basis = get_basis(expr, **options)
if temp_basis is not None:
options['basis'] = temp_basis
try:
return expr._represent(**options)
except NotImplementedError as strerr:
#If no _represent_FOO method exists, map to the
#appropriate basis state and try
#the other methods of representation
options['replace_none'] = True
if isinstance(expr, (KetBase, BraBase)):
try:
return rep_innerproduct(expr, **options)
except NotImplementedError:
raise NotImplementedError(strerr)
elif isinstance(expr, Operator):
try:
return rep_expectation(expr, **options)
except NotImplementedError:
raise NotImplementedError(strerr)
else:
raise NotImplementedError(strerr)
elif isinstance(expr, Add):
result = represent(expr.args[0], **options)
for args in expr.args[1:]:
# scipy.sparse doesn't support += so we use plain = here.
result = result + represent(args, **options)
return result
elif isinstance(expr, Pow):
base, exp = expr.as_base_exp()
if format in ('numpy', 'scipy.sparse'):
exp = _sympy_to_scalar(exp)
base = represent(base, **options)
# scipy.sparse doesn't support negative exponents
# and warns when inverting a matrix in csr format.
if format == 'scipy.sparse' and exp < 0:
from scipy.sparse.linalg import inv
exp = - exp
base = inv(base.tocsc()).tocsr()
return base ** exp
elif isinstance(expr, TensorProduct):
new_args = [represent(arg, **options) for arg in expr.args]
return TensorProduct(*new_args)
elif isinstance(expr, Dagger):
return Dagger(represent(expr.args[0], **options))
elif isinstance(expr, Commutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B - B*A
elif isinstance(expr, AntiCommutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B + B*A
elif isinstance(expr, InnerProduct):
return represent(Mul(expr.bra, expr.ket), **options)
elif not isinstance(expr, (Mul, OuterProduct)):
# For numpy and scipy.sparse, we can only handle numerical prefactors.
if format in ('numpy', 'scipy.sparse'):
return _sympy_to_scalar(expr)
return expr
if not isinstance(expr, (Mul, OuterProduct)):
raise TypeError('Mul expected, got: %r' % expr)
if "index" in options:
options["index"] += 1
else:
options["index"] = 1
if not "unities" in options:
options["unities"] = []
result = represent(expr.args[-1], **options)
last_arg = expr.args[-1]
for arg in reversed(expr.args[:-1]):
if isinstance(last_arg, Operator):
options["index"] += 1
options["unities"].append(options["index"])
elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase):
options["index"] += 1
elif isinstance(last_arg, KetBase) and isinstance(arg, Operator):
options["unities"].append(options["index"])
elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
options["unities"].append(options["index"])
result = represent(arg, **options)*result
last_arg = arg
# All three matrix formats create 1 by 1 matrices when inner products of
# vectors are taken. In these cases, we simply return a scalar.
result = flatten_scalar(result)
result = integrate_result(expr, result, **options)
return result
def rep_innerproduct(expr, **options):
"""
Returns an innerproduct like representation (e.g. ``<x'|x>``) for the
given state.
Attempts to calculate inner product with a bra from the specified
basis. Should only be passed an instance of KetBase or BraBase
Parameters
==========
expr : KetBase or BraBase
The expression to be represented
Examples
========
>>> from sympy.physics.quantum.represent import rep_innerproduct
>>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
>>> rep_innerproduct(XKet())
DiracDelta(x - x_1)
>>> rep_innerproduct(XKet(), basis=PxOp())
sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi))
>>> rep_innerproduct(PxKet(), basis=XOp())
sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi))
"""
if not isinstance(expr, (KetBase, BraBase)):
raise TypeError("expr passed is not a Bra or Ket")
basis = get_basis(expr, **options)
if not isinstance(basis, StateBase):
raise NotImplementedError("Can't form this representation!")
if not "index" in options:
options["index"] = 1
basis_kets = enumerate_states(basis, options["index"], 2)
if isinstance(expr, BraBase):
bra = expr
ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0])
else:
bra = (basis_kets[1].dual if basis_kets[0]
== expr else basis_kets[0].dual)
ket = expr
prod = InnerProduct(bra, ket)
result = prod.doit()
format = options.get('format', 'sympy')
return expr._format_represent(result, format)
def rep_expectation(expr, **options):
"""
Returns an ``<x'|A|x>`` type representation for the given operator.
Parameters
==========
expr : Operator
Operator to be represented in the specified basis
Examples
========
>>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet
>>> from sympy.physics.quantum.represent import rep_expectation
>>> rep_expectation(XOp())
x_1*DiracDelta(x_1 - x_2)
>>> rep_expectation(XOp(), basis=PxOp())
<px_2|*X*|px_1>
>>> rep_expectation(XOp(), basis=PxKet())
<px_2|*X*|px_1>
"""
if not "index" in options:
options["index"] = 1
if not isinstance(expr, Operator):
raise TypeError("The passed expression is not an operator")
basis_state = get_basis(expr, **options)
if basis_state is None or not isinstance(basis_state, StateBase):
raise NotImplementedError("Could not get basis kets for this operator")
basis_kets = enumerate_states(basis_state, options["index"], 2)
bra = basis_kets[1].dual
ket = basis_kets[0]
return qapply(bra*expr*ket)
def integrate_result(orig_expr, result, **options):
"""
Returns the result of integrating over any unities ``(|x><x|)`` in
the given expression. Intended for integrating over the result of
representations in continuous bases.
This function integrates over any unities that may have been
inserted into the quantum expression and returns the result.
It uses the interval of the Hilbert space of the basis state
passed to it in order to figure out the limits of integration.
The unities option must be
specified for this to work.
Note: This is mostly used internally by represent(). Examples are
given merely to show the use cases.
Parameters
==========
orig_expr : quantum expression
The original expression which was to be represented
result: Expr
The resulting representation that we wish to integrate over
Examples
========
>>> from sympy import symbols, DiracDelta
>>> from sympy.physics.quantum.represent import integrate_result
>>> from sympy.physics.quantum.cartesian import XOp, XKet
>>> x_ket = XKet()
>>> X_op = XOp()
>>> x, x_1, x_2 = symbols('x, x_1, x_2')
>>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2))
x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2)
>>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2),
... unities=[1])
x*DiracDelta(x - x_2)
"""
if not isinstance(result, Expr):
return result
options['replace_none'] = True
if not "basis" in options:
arg = orig_expr.args[-1]
options["basis"] = get_basis(arg, **options)
elif not isinstance(options["basis"], StateBase):
options["basis"] = get_basis(orig_expr, **options)
basis = options.pop("basis", None)
if basis is None:
return result
unities = options.pop("unities", [])
if len(unities) == 0:
return result
kets = enumerate_states(basis, unities)
coords = [k.label[0] for k in kets]
for coord in coords:
if coord in result.free_symbols:
#TODO: Add support for sets of operators
basis_op = state_to_operators(basis)
start = basis_op.hilbert_space.interval.start
end = basis_op.hilbert_space.interval.end
result = integrate(result, (coord, start, end))
return result
def get_basis(expr, *, basis=None, replace_none=True, **options):
"""
Returns a basis state instance corresponding to the basis specified in
options=s. If no basis is specified, the function tries to form a default
basis state of the given expression.
There are three behaviors:
1. The basis specified in options is already an instance of StateBase. If
this is the case, it is simply returned. If the class is specified but
not an instance, a default instance is returned.
2. The basis specified is an operator or set of operators. If this
is the case, the operator_to_state mapping method is used.
3. No basis is specified. If expr is a state, then a default instance of
its class is returned. If expr is an operator, then it is mapped to the
corresponding state. If it is neither, then we cannot obtain the basis
state.
If the basis cannot be mapped, then it is not changed.
This will be called from within represent, and represent will
only pass QExpr's.
TODO (?): Support for Muls and other types of expressions?
Parameters
==========
expr : Operator or StateBase
Expression whose basis is sought
Examples
========
>>> from sympy.physics.quantum.represent import get_basis
>>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
>>> x = XKet()
>>> X = XOp()
>>> get_basis(x)
|x>
>>> get_basis(X)
|x>
>>> get_basis(x, basis=PxOp())
|px>
>>> get_basis(x, basis=PxKet)
|px>
"""
if basis is None and not replace_none:
return None
if basis is None:
if isinstance(expr, KetBase):
return _make_default(expr.__class__)
elif isinstance(expr, BraBase):
return _make_default(expr.dual_class())
elif isinstance(expr, Operator):
state_inst = operators_to_state(expr)
return (state_inst if state_inst is not None else None)
else:
return None
elif (isinstance(basis, Operator) or
(not isinstance(basis, StateBase) and issubclass(basis, Operator))):
state = operators_to_state(basis)
if state is None:
return None
elif isinstance(state, StateBase):
return state
else:
return _make_default(state)
elif isinstance(basis, StateBase):
return basis
elif issubclass(basis, StateBase):
return _make_default(basis)
else:
return None
def _make_default(expr):
# XXX: Catching TypeError like this is a bad way of distinguishing
# instances from classes. The logic using this function should be
# rewritten somehow.
try:
expr = expr()
except TypeError:
return expr
return expr
def enumerate_states(*args, **options):
"""
Returns instances of the given state with dummy indices appended
Operates in two different modes:
1. Two arguments are passed to it. The first is the base state which is to
be indexed, and the second argument is a list of indices to append.
2. Three arguments are passed. The first is again the base state to be
indexed. The second is the start index for counting. The final argument
is the number of kets you wish to receive.
Tries to call state._enumerate_state. If this fails, returns an empty list
Parameters
==========
args : list
See list of operation modes above for explanation
Examples
========
>>> from sympy.physics.quantum.cartesian import XBra, XKet
>>> from sympy.physics.quantum.represent import enumerate_states
>>> test = XKet('foo')
>>> enumerate_states(test, 1, 3)
[|foo_1>, |foo_2>, |foo_3>]
>>> test2 = XBra('bar')
>>> enumerate_states(test2, [4, 5, 10])
[<bar_4|, <bar_5|, <bar_10|]
"""
state = args[0]
if len(args) not in (2, 3):
raise NotImplementedError("Wrong number of arguments!")
if not isinstance(state, StateBase):
raise TypeError("First argument is not a state!")
if len(args) == 3:
num_states = args[2]
options['start_index'] = args[1]
else:
num_states = len(args[1])
options['index_list'] = args[1]
try:
ret = state._enumerate_state(num_states, **options)
except NotImplementedError:
ret = []
return ret
|
eddb2bd565094db74156747fb6e84416fd9f65d3fcf47728665b2af61db033a6 | """Quantum mechanical operators.
TODO:
* Fix early 0 in apply_operators.
* Debug and test apply_operators.
* Get cse working with classes in this file.
* Doctests and documentation of special methods for InnerProduct, Commutator,
AntiCommutator, represent, apply_operators.
"""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, expand)
from sympy.core.mul import Mul
from sympy.core.numbers import oo
from sympy.core.singleton import S
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
from sympy.matrices import eye
__all__ = [
'Operator',
'HermitianOperator',
'UnitaryOperator',
'IdentityOperator',
'OuterProduct',
'DifferentialOperator'
]
#-----------------------------------------------------------------------------
# Operators and outer products
#-----------------------------------------------------------------------------
class Operator(QExpr):
"""Base class for non-commuting quantum operators.
An operator maps between quantum states [1]_. In quantum mechanics,
observables (including, but not limited to, measured physical values) are
represented as Hermitian operators [2]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
Create an operator and examine its attributes::
>>> from sympy.physics.quantum import Operator
>>> from sympy import I
>>> A = Operator('A')
>>> A
A
>>> A.hilbert_space
H
>>> A.label
(A,)
>>> A.is_commutative
False
Create another operator and do some arithmetic operations::
>>> B = Operator('B')
>>> C = 2*A*A + I*B
>>> C
2*A**2 + I*B
Operators do not commute::
>>> A.is_commutative
False
>>> B.is_commutative
False
>>> A*B == B*A
False
Polymonials of operators respect the commutation properties::
>>> e = (A+B)**3
>>> e.expand()
A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
Operator inverses are handle symbolically::
>>> A.inv()
A**(-1)
>>> A*A.inv()
1
References
==========
.. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
.. [2] https://en.wikipedia.org/wiki/Observable
"""
@classmethod
def default_args(self):
return ("O",)
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
_label_separator = ','
def _print_operator_name(self, printer, *args):
return self.__class__.__name__
_print_operator_name_latex = _print_operator_name
def _print_operator_name_pretty(self, printer, *args):
return prettyForm(self.__class__.__name__)
def _print_contents(self, printer, *args):
if len(self.label) == 1:
return self._print_label(printer, *args)
else:
return '%s(%s)' % (
self._print_operator_name(printer, *args),
self._print_label(printer, *args)
)
def _print_contents_pretty(self, printer, *args):
if len(self.label) == 1:
return self._print_label_pretty(printer, *args)
else:
pform = self._print_operator_name_pretty(printer, *args)
label_pform = self._print_label_pretty(printer, *args)
label_pform = prettyForm(
*label_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(label_pform))
return pform
def _print_contents_latex(self, printer, *args):
if len(self.label) == 1:
return self._print_label_latex(printer, *args)
else:
return r'%s\left(%s\right)' % (
self._print_operator_name_latex(printer, *args),
self._print_label_latex(printer, *args)
)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_commutator(self, other, **options):
"""Evaluate [self, other] if known, return None if not known."""
return dispatch_method(self, '_eval_commutator', other, **options)
def _eval_anticommutator(self, other, **options):
"""Evaluate [self, other] if known."""
return dispatch_method(self, '_eval_anticommutator', other, **options)
#-------------------------------------------------------------------------
# Operator application
#-------------------------------------------------------------------------
def _apply_operator(self, ket, **options):
return dispatch_method(self, '_apply_operator', ket, **options)
def matrix_element(self, *args):
raise NotImplementedError('matrix_elements is not defined')
def inverse(self):
return self._eval_inverse()
inv = inverse
def _eval_inverse(self):
return self**(-1)
def __mul__(self, other):
if isinstance(other, IdentityOperator):
return self
return Mul(self, other)
class HermitianOperator(Operator):
"""A Hermitian operator that satisfies H == Dagger(H).
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
>>> from sympy.physics.quantum import Dagger, HermitianOperator
>>> H = HermitianOperator('H')
>>> Dagger(H)
H
"""
is_hermitian = True
def _eval_inverse(self):
if isinstance(self, UnitaryOperator):
return self
else:
return Operator._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self, UnitaryOperator):
if exp == -1:
return Operator._eval_power(self, exp)
elif abs(exp) % 2 == 0:
return self*(Operator._eval_inverse(self))
else:
return self
else:
return Operator._eval_power(self, exp)
class UnitaryOperator(Operator):
"""A unitary operator that satisfies U*Dagger(U) == 1.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator. For time-dependent operators, this will include the time.
Examples
========
>>> from sympy.physics.quantum import Dagger, UnitaryOperator
>>> U = UnitaryOperator('U')
>>> U*Dagger(U)
1
"""
def _eval_adjoint(self):
return self._eval_inverse()
class IdentityOperator(Operator):
"""An identity operator I that satisfies op * I == I * op == op for any
operator op.
Parameters
==========
N : Integer
Optional parameter that specifies the dimension of the Hilbert space
of operator. This is used when generating a matrix representation.
Examples
========
>>> from sympy.physics.quantum import IdentityOperator
>>> IdentityOperator()
I
"""
@property
def dimension(self):
return self.N
@classmethod
def default_args(self):
return (oo,)
def __init__(self, *args, **hints):
if not len(args) in (0, 1):
raise ValueError('0 or 1 parameters expected, got %s' % args)
self.N = args[0] if (len(args) == 1 and args[0]) else oo
def _eval_commutator(self, other, **hints):
return S.Zero
def _eval_anticommutator(self, other, **hints):
return 2 * other
def _eval_inverse(self):
return self
def _eval_adjoint(self):
return self
def _apply_operator(self, ket, **options):
return ket
def _eval_power(self, exp):
return self
def _print_contents(self, printer, *args):
return 'I'
def _print_contents_pretty(self, printer, *args):
return prettyForm('I')
def _print_contents_latex(self, printer, *args):
return r'{\mathcal{I}}'
def __mul__(self, other):
if isinstance(other, (Operator, Dagger)):
return other
return Mul(self, other)
def _represent_default_basis(self, **options):
if not self.N or self.N == oo:
raise NotImplementedError('Cannot represent infinite dimensional' +
' identity operator as a matrix')
format = options.get('format', 'sympy')
if format != 'sympy':
raise NotImplementedError('Representation in format ' +
'%s not implemented.' % format)
return eye(self.N)
class OuterProduct(Operator):
"""An unevaluated outer product between a ket and bra.
This constructs an outer product between any subclass of ``KetBase`` and
``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
operators in quantum expressions. For reference see [1]_.
Parameters
==========
ket : KetBase
The ket on the left side of the outer product.
bar : BraBase
The bra on the right side of the outer product.
Examples
========
Create a simple outer product by hand and take its dagger::
>>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
>>> from sympy.physics.quantum import Operator
>>> k = Ket('k')
>>> b = Bra('b')
>>> op = OuterProduct(k, b)
>>> op
|k><b|
>>> op.hilbert_space
H
>>> op.ket
|k>
>>> op.bra
<b|
>>> Dagger(op)
|b><k|
In simple products of kets and bras outer products will be automatically
identified and created::
>>> k*b
|k><b|
But in more complex expressions, outer products are not automatically
created::
>>> A = Operator('A')
>>> A*k*b
A*|k>*<b|
A user can force the creation of an outer product in a complex expression
by using parentheses to group the ket and bra::
>>> A*(k*b)
A*|k><b|
References
==========
.. [1] https://en.wikipedia.org/wiki/Outer_product
"""
is_commutative = False
def __new__(cls, *args, **old_assumptions):
from sympy.physics.quantum.state import KetBase, BraBase
if len(args) != 2:
raise ValueError('2 parameters expected, got %d' % len(args))
ket_expr = expand(args[0])
bra_expr = expand(args[1])
if (isinstance(ket_expr, (KetBase, Mul)) and
isinstance(bra_expr, (BraBase, Mul))):
ket_c, kets = ket_expr.args_cnc()
bra_c, bras = bra_expr.args_cnc()
if len(kets) != 1 or not isinstance(kets[0], KetBase):
raise TypeError('KetBase subclass expected'
', got: %r' % Mul(*kets))
if len(bras) != 1 or not isinstance(bras[0], BraBase):
raise TypeError('BraBase subclass expected'
', got: %r' % Mul(*bras))
if not kets[0].dual_class() == bras[0].__class__:
raise TypeError(
'ket and bra are not dual classes: %r, %r' %
(kets[0].__class__, bras[0].__class__)
)
# TODO: make sure the hilbert spaces of the bra and ket are
# compatible
obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
obj.hilbert_space = kets[0].hilbert_space
return Mul(*(ket_c + bra_c)) * obj
op_terms = []
if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
for ket_term in ket_expr.args:
for bra_term in bra_expr.args:
op_terms.append(OuterProduct(ket_term, bra_term,
**old_assumptions))
elif isinstance(ket_expr, Add):
for ket_term in ket_expr.args:
op_terms.append(OuterProduct(ket_term, bra_expr,
**old_assumptions))
elif isinstance(bra_expr, Add):
for bra_term in bra_expr.args:
op_terms.append(OuterProduct(ket_expr, bra_term,
**old_assumptions))
else:
raise TypeError(
'Expected ket and bra expression, got: %r, %r' %
(ket_expr, bra_expr)
)
return Add(*op_terms)
@property
def ket(self):
"""Return the ket on the left side of the outer product."""
return self.args[0]
@property
def bra(self):
"""Return the bra on the right side of the outer product."""
return self.args[1]
def _eval_adjoint(self):
return OuterProduct(Dagger(self.bra), Dagger(self.ket))
def _sympystr(self, printer, *args):
return printer._print(self.ket) + printer._print(self.bra)
def _sympyrepr(self, printer, *args):
return '%s(%s,%s)' % (self.__class__.__name__,
printer._print(self.ket, *args), printer._print(self.bra, *args))
def _pretty(self, printer, *args):
pform = self.ket._pretty(printer, *args)
return prettyForm(*pform.right(self.bra._pretty(printer, *args)))
def _latex(self, printer, *args):
k = printer._print(self.ket, *args)
b = printer._print(self.bra, *args)
return k + b
def _represent(self, **options):
k = self.ket._represent(**options)
b = self.bra._represent(**options)
return k*b
def _eval_trace(self, **kwargs):
# TODO if operands are tensorproducts this may be will be handled
# differently.
return self.ket._eval_trace(self.bra, **kwargs)
class DifferentialOperator(Operator):
"""An operator for representing the differential operator, i.e. d/dx
It is initialized by passing two arguments. The first is an arbitrary
expression that involves a function, such as ``Derivative(f(x), x)``. The
second is the function (e.g. ``f(x)``) which we are to replace with the
``Wavefunction`` that this ``DifferentialOperator`` is applied to.
Parameters
==========
expr : Expr
The arbitrary expression which the appropriate Wavefunction is to be
substituted into
func : Expr
A function (e.g. f(x)) which is to be replaced with the appropriate
Wavefunction when this DifferentialOperator is applied
Examples
========
You can define a completely arbitrary expression and specify where the
Wavefunction is to be substituted
>>> from sympy import Derivative, Function, Symbol
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy.physics.quantum.qapply import qapply
>>> f = Function('f')
>>> x = Symbol('x')
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
>>> w = Wavefunction(x**2, x)
>>> d.function
f(x)
>>> d.variables
(x,)
>>> qapply(d*w)
Wavefunction(2, x)
"""
@property
def variables(self):
"""
Returns the variables with which the function in the specified
arbitrary expression is evaluated
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Symbol, Function, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
>>> d.variables
(x,)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.variables
(x, y)
"""
return self.args[-1].args
@property
def function(self):
"""
Returns the function which is to be replaced with the Wavefunction
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Function, Symbol, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
>>> d.function
f(x)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.function
f(x, y)
"""
return self.args[-1]
@property
def expr(self):
"""
Returns the arbitrary expression which is to have the Wavefunction
substituted into it
Examples
========
>>> from sympy.physics.quantum.operator import DifferentialOperator
>>> from sympy import Function, Symbol, Derivative
>>> x = Symbol('x')
>>> f = Function('f')
>>> d = DifferentialOperator(Derivative(f(x), x), f(x))
>>> d.expr
Derivative(f(x), x)
>>> y = Symbol('y')
>>> d = DifferentialOperator(Derivative(f(x, y), x) +
... Derivative(f(x, y), y), f(x, y))
>>> d.expr
Derivative(f(x, y), x) + Derivative(f(x, y), y)
"""
return self.args[0]
@property
def free_symbols(self):
"""
Return the free symbols of the expression.
"""
return self.expr.free_symbols
def _apply_operator_Wavefunction(self, func):
from sympy.physics.quantum.state import Wavefunction
var = self.variables
wf_vars = func.args[1:]
f = self.function
new_expr = self.expr.subs(f, func(*var))
new_expr = new_expr.doit()
return Wavefunction(new_expr, *wf_vars)
def _eval_derivative(self, symbol):
new_expr = Derivative(self.expr, symbol)
return DifferentialOperator(new_expr, self.args[-1])
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print(self, printer, *args):
return '%s(%s)' % (
self._print_operator_name(printer, *args),
self._print_label(printer, *args)
)
def _print_pretty(self, printer, *args):
pform = self._print_operator_name_pretty(printer, *args)
label_pform = self._print_label_pretty(printer, *args)
label_pform = prettyForm(
*label_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(label_pform))
return pform
|
96b3b93dba2c95f7ec851c44429f4bc2dcd60bbbd8d3d3466302192acdba0239 | """Qubits for quantum computing.
Todo:
* Finish implementing measurement logic. This should include POVM.
* Update docstrings.
* Update tests.
"""
import math
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.exponential import log
from sympy.core.basic import sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.matrices import Matrix, zeros
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.state import Ket, Bra, State
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.matrixutils import (
numpy_ndarray, scipy_sparse_matrix
)
from mpmath.libmp.libintmath import bitcount
__all__ = [
'Qubit',
'QubitBra',
'IntQubit',
'IntQubitBra',
'qubit_to_matrix',
'matrix_to_qubit',
'matrix_to_density',
'measure_all',
'measure_partial',
'measure_partial_oneshot',
'measure_all_oneshot'
]
#-----------------------------------------------------------------------------
# Qubit Classes
#-----------------------------------------------------------------------------
class QubitState(State):
"""Base class for Qubit and QubitBra."""
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# If we are passed a QubitState or subclass, we just take its qubit
# values directly.
if len(args) == 1 and isinstance(args[0], QubitState):
return args[0].qubit_values
# Turn strings into tuple of strings
if len(args) == 1 and isinstance(args[0], str):
args = tuple(args[0])
args = sympify(args)
# Validate input (must have 0 or 1 input)
for element in args:
if element not in (S.Zero, S.One):
raise ValueError(
"Qubit values must be 0 or 1, got: %r" % element)
return args
@classmethod
def _eval_hilbert_space(cls, args):
return ComplexSpace(2)**len(args)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def dimension(self):
"""The number of Qubits in the state."""
return len(self.qubit_values)
@property
def nqubits(self):
return self.dimension
@property
def qubit_values(self):
"""Returns the values of the qubits as a tuple."""
return self.label
#-------------------------------------------------------------------------
# Special methods
#-------------------------------------------------------------------------
def __len__(self):
return self.dimension
def __getitem__(self, bit):
return self.qubit_values[int(self.dimension - bit - 1)]
#-------------------------------------------------------------------------
# Utility methods
#-------------------------------------------------------------------------
def flip(self, *bits):
"""Flip the bit(s) given."""
newargs = list(self.qubit_values)
for i in bits:
bit = int(self.dimension - i - 1)
if newargs[bit] == 1:
newargs[bit] = 0
else:
newargs[bit] = 1
return self.__class__(*tuple(newargs))
class Qubit(QubitState, Ket):
"""A multi-qubit ket in the computational (z) basis.
We use the normal convention that the least significant qubit is on the
right, so ``|00001>`` has a 1 in the least significant qubit.
Parameters
==========
values : list, str
The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
Examples
========
Create a qubit in a couple of different ways and look at their attributes:
>>> from sympy.physics.quantum.qubit import Qubit
>>> Qubit(0,0,0)
|000>
>>> q = Qubit('0101')
>>> q
|0101>
>>> q.nqubits
4
>>> len(q)
4
>>> q.dimension
4
>>> q.qubit_values
(0, 1, 0, 1)
We can flip the value of an individual qubit:
>>> q.flip(1)
|0111>
We can take the dagger of a Qubit to get a bra:
>>> from sympy.physics.quantum.dagger import Dagger
>>> Dagger(q)
<0101|
>>> type(Dagger(q))
<class 'sympy.physics.quantum.qubit.QubitBra'>
Inner products work as expected:
>>> ip = Dagger(q)*q
>>> ip
<0101|0101>
>>> ip.doit()
1
"""
@classmethod
def dual_class(self):
return QubitBra
def _eval_innerproduct_QubitBra(self, bra, **hints):
if self.label == bra.label:
return S.One
else:
return S.Zero
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
"""Represent this qubits in the computational basis (ZGate).
"""
_format = options.get('format', 'sympy')
n = 1
definite_state = 0
for it in reversed(self.qubit_values):
definite_state += n*it
n = n*2
result = [0]*(2**self.dimension)
result[int(definite_state)] = 1
if _format == 'sympy':
return Matrix(result)
elif _format == 'numpy':
import numpy as np
return np.matrix(result, dtype='complex').transpose()
elif _format == 'scipy.sparse':
from scipy import sparse
return sparse.csr_matrix(result, dtype='complex').transpose()
def _eval_trace(self, bra, **kwargs):
indices = kwargs.get('indices', [])
#sort index list to begin trace from most-significant
#qubit
sorted_idx = list(indices)
if len(sorted_idx) == 0:
sorted_idx = list(range(0, self.nqubits))
sorted_idx.sort()
#trace out for each of index
new_mat = self*bra
for i in range(len(sorted_idx) - 1, -1, -1):
# start from tracing out from leftmost qubit
new_mat = self._reduced_density(new_mat, int(sorted_idx[i]))
if (len(sorted_idx) == self.nqubits):
#in case full trace was requested
return new_mat[0]
else:
return matrix_to_density(new_mat)
def _reduced_density(self, matrix, qubit, **options):
"""Compute the reduced density matrix by tracing out one qubit.
The qubit argument should be of type Python int, since it is used
in bit operations
"""
def find_index_that_is_projected(j, k, qubit):
bit_mask = 2**qubit - 1
return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit)
old_matrix = represent(matrix, **options)
old_size = old_matrix.cols
#we expect the old_size to be even
new_size = old_size//2
new_matrix = Matrix().zeros(new_size)
for i in range(new_size):
for j in range(new_size):
for k in range(2):
col = find_index_that_is_projected(j, k, qubit)
row = find_index_that_is_projected(i, k, qubit)
new_matrix[i, j] += old_matrix[row, col]
return new_matrix
class QubitBra(QubitState, Bra):
"""A multi-qubit bra in the computational (z) basis.
We use the normal convention that the least significant qubit is on the
right, so ``|00001>`` has a 1 in the least significant qubit.
Parameters
==========
values : list, str
The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
See also
========
Qubit: Examples using qubits
"""
@classmethod
def dual_class(self):
return Qubit
class IntQubitState(QubitState):
"""A base class for qubits that work with binary representations."""
@classmethod
def _eval_args(cls, args, nqubits=None):
# The case of a QubitState instance
if len(args) == 1 and isinstance(args[0], QubitState):
return QubitState._eval_args(args)
# otherwise, args should be integer
elif not all(isinstance(a, (int, Integer)) for a in args):
raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),))
# use nqubits if specified
if nqubits is not None:
if not isinstance(nqubits, (int, Integer)):
raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits))
if len(args) != 1:
raise ValueError(
'too many positional arguments (%s). should be (number, nqubits=n)' % (args,))
return cls._eval_args_with_nqubits(args[0], nqubits)
# For a single argument, we construct the binary representation of
# that integer with the minimal number of bits.
if len(args) == 1 and args[0] > 1:
#rvalues is the minimum number of bits needed to express the number
rvalues = reversed(range(bitcount(abs(args[0]))))
qubit_values = [(args[0] >> i) & 1 for i in rvalues]
return QubitState._eval_args(qubit_values)
# For two numbers, the second number is the number of bits
# on which it is expressed, so IntQubit(0,5) == |00000>.
elif len(args) == 2 and args[1] > 1:
return cls._eval_args_with_nqubits(args[0], args[1])
else:
return QubitState._eval_args(args)
@classmethod
def _eval_args_with_nqubits(cls, number, nqubits):
need = bitcount(abs(number))
if nqubits < need:
raise ValueError(
'cannot represent %s with %s bits' % (number, nqubits))
qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]
return QubitState._eval_args(qubit_values)
def as_int(self):
"""Return the numerical value of the qubit."""
number = 0
n = 1
for i in reversed(self.qubit_values):
number += n*i
n = n << 1
return number
def _print_label(self, printer, *args):
return str(self.as_int())
def _print_label_pretty(self, printer, *args):
label = self._print_label(printer, *args)
return prettyForm(label)
_print_label_repr = _print_label
_print_label_latex = _print_label
class IntQubit(IntQubitState, Qubit):
"""A qubit ket that store integers as binary numbers in qubit values.
The differences between this class and ``Qubit`` are:
* The form of the constructor.
* The qubit values are printed as their corresponding integer, rather
than the raw qubit values. The internal storage format of the qubit
values in the same as ``Qubit``.
Parameters
==========
values : int, tuple
If a single argument, the integer we want to represent in the qubit
values. This integer will be represented using the fewest possible
number of qubits.
If a pair of integers and the second value is more than one, the first
integer gives the integer to represent in binary form and the second
integer gives the number of qubits to use.
List of zeros and ones is also accepted to generate qubit by bit pattern.
nqubits : int
The integer that represents the number of qubits.
This number should be passed with keyword ``nqubits=N``.
You can use this in order to avoid ambiguity of Qubit-style tuple of bits.
Please see the example below for more details.
Examples
========
Create a qubit for the integer 5:
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.qubit import Qubit
>>> q = IntQubit(5)
>>> q
|5>
We can also create an ``IntQubit`` by passing a ``Qubit`` instance.
>>> q = IntQubit(Qubit('101'))
>>> q
|5>
>>> q.as_int()
5
>>> q.nqubits
3
>>> q.qubit_values
(1, 0, 1)
We can go back to the regular qubit form.
>>> Qubit(q)
|101>
Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.
So, the code below yields qubits 3, not a single bit ``1``.
>>> IntQubit(1, 1)
|3>
To avoid ambiguity, use ``nqubits`` parameter.
Use of this keyword is recommended especially when you provide the values by variables.
>>> IntQubit(1, nqubits=1)
|1>
>>> a = 1
>>> IntQubit(a, nqubits=1)
|1>
"""
@classmethod
def dual_class(self):
return IntQubitBra
def _eval_innerproduct_IntQubitBra(self, bra, **hints):
return Qubit._eval_innerproduct_QubitBra(self, bra)
class IntQubitBra(IntQubitState, QubitBra):
"""A qubit bra that store integers as binary numbers in qubit values."""
@classmethod
def dual_class(self):
return IntQubit
#-----------------------------------------------------------------------------
# Qubit <---> Matrix conversion functions
#-----------------------------------------------------------------------------
def matrix_to_qubit(matrix):
"""Convert from the matrix repr. to a sum of Qubit objects.
Parameters
----------
matrix : Matrix, numpy.matrix, scipy.sparse
The matrix to build the Qubit representation of. This works with
SymPy matrices, numpy matrices and scipy.sparse sparse matrices.
Examples
========
Represent a state and then go back to its qubit form:
>>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit
>>> from sympy.physics.quantum.represent import represent
>>> q = Qubit('01')
>>> matrix_to_qubit(represent(q))
|01>
"""
# Determine the format based on the type of the input matrix
format = 'sympy'
if isinstance(matrix, numpy_ndarray):
format = 'numpy'
if isinstance(matrix, scipy_sparse_matrix):
format = 'scipy.sparse'
# Make sure it is of correct dimensions for a Qubit-matrix representation.
# This logic should work with sympy, numpy or scipy.sparse matrices.
if matrix.shape[0] == 1:
mlistlen = matrix.shape[1]
nqubits = log(mlistlen, 2)
ket = False
cls = QubitBra
elif matrix.shape[1] == 1:
mlistlen = matrix.shape[0]
nqubits = log(mlistlen, 2)
ket = True
cls = Qubit
else:
raise QuantumError(
'Matrix must be a row/column vector, got %r' % matrix
)
if not isinstance(nqubits, Integer):
raise QuantumError('Matrix must be a row/column vector of size '
'2**nqubits, got: %r' % matrix)
# Go through each item in matrix, if element is non-zero, make it into a
# Qubit item times the element.
result = 0
for i in range(mlistlen):
if ket:
element = matrix[i, 0]
else:
element = matrix[0, i]
if format in ('numpy', 'scipy.sparse'):
element = complex(element)
if element != 0.0:
# Form Qubit array; 0 in bit-locations where i is 0, 1 in
# bit-locations where i is 1
qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)]
qubit_array.reverse()
result = result + element*cls(*qubit_array)
# If SymPy simplified by pulling out a constant coefficient, undo that.
if isinstance(result, (Mul, Add, Pow)):
result = result.expand()
return result
def matrix_to_density(mat):
"""
Works by finding the eigenvectors and eigenvalues of the matrix.
We know we can decompose rho by doing:
sum(EigenVal*|Eigenvect><Eigenvect|)
"""
from sympy.physics.quantum.density import Density
eigen = mat.eigenvects()
args = [[matrix_to_qubit(Matrix(
[vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0]
if (len(args) == 0):
return S.Zero
else:
return Density(*args)
def qubit_to_matrix(qubit, format='sympy'):
"""Converts an Add/Mul of Qubit objects into it's matrix representation
This function is the inverse of ``matrix_to_qubit`` and is a shorthand
for ``represent(qubit)``.
"""
return represent(qubit, format=format)
#-----------------------------------------------------------------------------
# Measurement
#-----------------------------------------------------------------------------
def measure_all(qubit, format='sympy', normalize=True):
"""Perform an ensemble measurement of all qubits.
Parameters
==========
qubit : Qubit, Add
The qubit to measure. This can be any Qubit or a linear combination
of them.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
=======
result : list
A list that consists of primitive states and their probabilities.
Examples
========
>>> from sympy.physics.quantum.qubit import Qubit, measure_all
>>> from sympy.physics.quantum.gate import H
>>> from sympy.physics.quantum.qapply import qapply
>>> c = H(0)*H(1)*Qubit('00')
>>> c
H(0)*H(1)*|00>
>>> q = qapply(c)
>>> measure_all(q)
[(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)]
"""
m = qubit_to_matrix(qubit, format)
if format == 'sympy':
results = []
if normalize:
m = m.normalized()
size = max(m.shape) # Max of shape to account for bra or ket
nqubits = int(math.log(size)/math.log(2))
for i in range(size):
if m[i] != 0.0:
results.append(
(Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))
)
return results
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def measure_partial(qubit, bits, format='sympy', normalize=True):
"""Perform a partial ensemble measure on the specified qubits.
Parameters
==========
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
bits : tuple
The qubits to measure.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
=======
result : list
A list that consists of primitive states and their probabilities.
Examples
========
>>> from sympy.physics.quantum.qubit import Qubit, measure_partial
>>> from sympy.physics.quantum.gate import H
>>> from sympy.physics.quantum.qapply import qapply
>>> c = H(0)*H(1)*Qubit('00')
>>> c
H(0)*H(1)*|00>
>>> q = qapply(c)
>>> measure_partial(q, (0,))
[(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)]
"""
m = qubit_to_matrix(qubit, format)
if isinstance(bits, (SYMPY_INTS, Integer)):
bits = (int(bits),)
if format == 'sympy':
if normalize:
m = m.normalized()
possible_outcomes = _get_possible_outcomes(m, bits)
# Form output from function.
output = []
for outcome in possible_outcomes:
# Calculate probability of finding the specified bits with
# given values.
prob_of_outcome = 0
prob_of_outcome += (outcome.H*outcome)[0]
# If the output has a chance, append it to output with found
# probability.
if prob_of_outcome != 0:
if normalize:
next_matrix = matrix_to_qubit(outcome.normalized())
else:
next_matrix = matrix_to_qubit(outcome)
output.append((
next_matrix,
prob_of_outcome
))
return output
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def measure_partial_oneshot(qubit, bits, format='sympy'):
"""Perform a partial oneshot measurement on the specified qubits.
A oneshot measurement is equivalent to performing a measurement on a
quantum system. This type of measurement does not return the probabilities
like an ensemble measurement does, but rather returns *one* of the
possible resulting states. The exact state that is returned is determined
by picking a state randomly according to the ensemble probabilities.
Parameters
----------
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
bits : tuple
The qubits to measure.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
-------
result : Qubit
The qubit that the system collapsed to upon measurement.
"""
import random
m = qubit_to_matrix(qubit, format)
if format == 'sympy':
m = m.normalized()
possible_outcomes = _get_possible_outcomes(m, bits)
# Form output from function
random_number = random.random()
total_prob = 0
for outcome in possible_outcomes:
# Calculate probability of finding the specified bits
# with given values
total_prob += (outcome.H*outcome)[0]
if total_prob >= random_number:
return matrix_to_qubit(outcome.normalized())
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def _get_possible_outcomes(m, bits):
"""Get the possible states that can be produced in a measurement.
Parameters
----------
m : Matrix
The matrix representing the state of the system.
bits : tuple, list
Which bits will be measured.
Returns
-------
result : list
The list of possible states which can occur given this measurement.
These are un-normalized so we can derive the probability of finding
this state by taking the inner product with itself
"""
# This is filled with loads of dirty binary tricks...You have been warned
size = max(m.shape) # Max of shape to account for bra or ket
nqubits = int(math.log(size, 2) + .1) # Number of qubits possible
# Make the output states and put in output_matrices, nothing in them now.
# Each state will represent a possible outcome of the measurement
# Thus, output_matrices[0] is the matrix which we get when all measured
# bits return 0. and output_matrices[1] is the matrix for only the 0th
# bit being true
output_matrices = []
for i in range(1 << len(bits)):
output_matrices.append(zeros(2**nqubits, 1))
# Bitmasks will help sort how to determine possible outcomes.
# When the bit mask is and-ed with a matrix-index,
# it will determine which state that index belongs to
bit_masks = []
for bit in bits:
bit_masks.append(1 << bit)
# Make possible outcome states
for i in range(2**nqubits):
trueness = 0 # This tells us to which output_matrix this value belongs
# Find trueness
for j in range(len(bit_masks)):
if i & bit_masks[j]:
trueness += j + 1
# Put the value in the correct output matrix
output_matrices[trueness][i] = m[i]
return output_matrices
def measure_all_oneshot(qubit, format='sympy'):
"""Perform a oneshot ensemble measurement on all qubits.
A oneshot measurement is equivalent to performing a measurement on a
quantum system. This type of measurement does not return the probabilities
like an ensemble measurement does, but rather returns *one* of the
possible resulting states. The exact state that is returned is determined
by picking a state randomly according to the ensemble probabilities.
Parameters
----------
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
-------
result : Qubit
The qubit that the system collapsed to upon measurement.
"""
import random
m = qubit_to_matrix(qubit)
if format == 'sympy':
m = m.normalized()
random_number = random.random()
total = 0
result = 0
for i in m:
total += i*i.conjugate()
if total > random_number:
break
result += 1
return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1)))
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
|
2b8b66c9660c960ce44d35e3b3cd8fcc40bc554e239b627a42273862600ced24 | """Symbolic inner product."""
from sympy.core.expr import Expr
from sympy.functions.elementary.complexes import conjugate
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import KetBase, BraBase
__all__ = [
'InnerProduct'
]
# InnerProduct is not an QExpr because it is really just a regular commutative
# number. We have gone back and forth about this, but we gain a lot by having
# it subclass Expr. The main challenges were getting Dagger to work
# (we use _eval_conjugate) and represent (we can use atoms and subs). Having
# it be an Expr, mean that there are no commutative QExpr subclasses,
# which simplifies the design of everything.
class InnerProduct(Expr):
"""An unevaluated inner product between a Bra and a Ket [1].
Parameters
==========
bra : BraBase or subclass
The bra on the left side of the inner product.
ket : KetBase or subclass
The ket on the right side of the inner product.
Examples
========
Create an InnerProduct and check its properties:
>>> from sympy.physics.quantum import Bra, Ket
>>> b = Bra('b')
>>> k = Ket('k')
>>> ip = b*k
>>> ip
<b|k>
>>> ip.bra
<b|
>>> ip.ket
|k>
In simple products of kets and bras inner products will be automatically
identified and created::
>>> b*k
<b|k>
But in more complex expressions, there is ambiguity in whether inner or
outer products should be created::
>>> k*b*k*b
|k><b|*|k>*<b|
A user can force the creation of a inner products in a complex expression
by using parentheses to group the bra and ket::
>>> k*(b*k)*b
<b|k>*|k>*<b|
Notice how the inner product <b|k> moved to the left of the expression
because inner products are commutative complex numbers.
References
==========
.. [1] https://en.wikipedia.org/wiki/Inner_product
"""
is_complex = True
def __new__(cls, bra, ket):
if not isinstance(ket, KetBase):
raise TypeError('KetBase subclass expected, got: %r' % ket)
if not isinstance(bra, BraBase):
raise TypeError('BraBase subclass expected, got: %r' % ket)
obj = Expr.__new__(cls, bra, ket)
return obj
@property
def bra(self):
return self.args[0]
@property
def ket(self):
return self.args[1]
def _eval_conjugate(self):
return InnerProduct(Dagger(self.ket), Dagger(self.bra))
def _sympyrepr(self, printer, *args):
return '%s(%s,%s)' % (self.__class__.__name__,
printer._print(self.bra, *args), printer._print(self.ket, *args))
def _sympystr(self, printer, *args):
sbra = printer._print(self.bra)
sket = printer._print(self.ket)
return '%s|%s' % (sbra[:-1], sket[1:])
def _pretty(self, printer, *args):
# Print state contents
bra = self.bra._print_contents_pretty(printer, *args)
ket = self.ket._print_contents_pretty(printer, *args)
# Print brackets
height = max(bra.height(), ket.height())
use_unicode = printer._use_unicode
lbracket, _ = self.bra._pretty_brackets(height, use_unicode)
cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode)
# Build innerproduct
pform = prettyForm(*bra.left(lbracket))
pform = prettyForm(*pform.right(cbracket))
pform = prettyForm(*pform.right(ket))
pform = prettyForm(*pform.right(rbracket))
return pform
def _latex(self, printer, *args):
bra_label = self.bra._print_contents_latex(printer, *args)
ket = printer._print(self.ket, *args)
return r'\left\langle %s \right. %s' % (bra_label, ket)
def doit(self, **hints):
try:
r = self.ket._eval_innerproduct(self.bra, **hints)
except NotImplementedError:
try:
r = conjugate(
self.bra.dual._eval_innerproduct(self.ket.dual, **hints)
)
except NotImplementedError:
r = None
if r is not None:
return r
return self
|
011d95a39b96fe2e18bf837e617a5ee1e6795a06bd54c947b18ea43ac0065e87 | from sympy.core.expr import Expr
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices.dense import Matrix
from sympy.printing.pretty.stringpict import prettyForm
from sympy.core.containers import Tuple
from sympy.utilities.iterables import is_sequence
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.matrixutils import (
numpy_ndarray, scipy_sparse_matrix,
to_sympy, to_numpy, to_scipy_sparse
)
__all__ = [
'QuantumError',
'QExpr'
]
#-----------------------------------------------------------------------------
# Error handling
#-----------------------------------------------------------------------------
class QuantumError(Exception):
pass
def _qsympify_sequence(seq):
"""Convert elements of a sequence to standard form.
This is like sympify, but it performs special logic for arguments passed
to QExpr. The following conversions are done:
* (list, tuple, Tuple) => _qsympify_sequence each element and convert
sequence to a Tuple.
* basestring => Symbol
* Matrix => Matrix
* other => sympify
Strings are passed to Symbol, not sympify to make sure that variables like
'pi' are kept as Symbols, not the SymPy built-in number subclasses.
Examples
========
>>> from sympy.physics.quantum.qexpr import _qsympify_sequence
>>> _qsympify_sequence((1,2,[3,4,[1,]]))
(1, 2, (3, 4, (1,)))
"""
return tuple(__qsympify_sequence_helper(seq))
def __qsympify_sequence_helper(seq):
"""
Helper function for _qsympify_sequence
This function does the actual work.
"""
#base case. If not a list, do Sympification
if not is_sequence(seq):
if isinstance(seq, Matrix):
return seq
elif isinstance(seq, str):
return Symbol(seq)
else:
return sympify(seq)
# base condition, when seq is QExpr and also
# is iterable.
if isinstance(seq, QExpr):
return seq
#if list, recurse on each item in the list
result = [__qsympify_sequence_helper(item) for item in seq]
return Tuple(*result)
#-----------------------------------------------------------------------------
# Basic Quantum Expression from which all objects descend
#-----------------------------------------------------------------------------
class QExpr(Expr):
"""A base class for all quantum object like operators and states."""
# In sympy, slots are for instance attributes that are computed
# dynamically by the __new__ method. They are not part of args, but they
# derive from args.
# The Hilbert space a quantum Object belongs to.
__slots__ = ('hilbert_space')
is_commutative = False
# The separator used in printing the label.
_label_separator = ''
@property
def free_symbols(self):
return {self}
def __new__(cls, *args, **kwargs):
"""Construct a new quantum object.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
quantum object. For a state, this will be its symbol or its
set of quantum numbers.
Examples
========
>>> from sympy.physics.quantum.qexpr import QExpr
>>> q = QExpr(0)
>>> q
0
>>> q.label
(0,)
>>> q.hilbert_space
H
>>> q.args
(0,)
>>> q.is_commutative
False
"""
# First compute args and call Expr.__new__ to create the instance
args = cls._eval_args(args, **kwargs)
if len(args) == 0:
args = cls._eval_args(tuple(cls.default_args()), **kwargs)
inst = Expr.__new__(cls, *args)
# Now set the slots on the instance
inst.hilbert_space = cls._eval_hilbert_space(args)
return inst
@classmethod
def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
"""Create new instance of this class with hilbert_space and args.
This is used to bypass the more complex logic in the ``__new__``
method in cases where you already have the exact ``hilbert_space``
and ``args``. This should be used when you are positive these
arguments are valid, in their final, proper form and want to optimize
the creation of the object.
"""
obj = Expr.__new__(cls, *args, **old_assumptions)
obj.hilbert_space = hilbert_space
return obj
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label is the unique set of identifiers for the object.
Usually, this will include all of the information about the state
*except* the time (in the case of time-dependent objects).
This must be a tuple, rather than a Tuple.
"""
if len(self.args) == 0: # If there is no label specified, return the default
return self._eval_args(list(self.default_args()))
else:
return self.args
@property
def is_symbolic(self):
return True
@classmethod
def default_args(self):
"""If no arguments are specified, then this will return a default set
of arguments to be run through the constructor.
NOTE: Any classes that override this MUST return a tuple of arguments.
Should be overridden by subclasses to specify the default arguments for kets and operators
"""
raise NotImplementedError("No default arguments for this class!")
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_adjoint(self):
obj = Expr._eval_adjoint(self)
if obj is None:
obj = Expr.__new__(Dagger, self)
if isinstance(obj, QExpr):
obj.hilbert_space = self.hilbert_space
return obj
@classmethod
def _eval_args(cls, args):
"""Process the args passed to the __new__ method.
This simply runs args through _qsympify_sequence.
"""
return _qsympify_sequence(args)
@classmethod
def _eval_hilbert_space(cls, args):
"""Compute the Hilbert space instance from the args.
"""
from sympy.physics.quantum.hilbert import HilbertSpace
return HilbertSpace()
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
# Utilities for printing: these operate on raw SymPy objects
def _print_sequence(self, seq, sep, printer, *args):
result = []
for item in seq:
result.append(printer._print(item, *args))
return sep.join(result)
def _print_sequence_pretty(self, seq, sep, printer, *args):
pform = printer._print(seq[0], *args)
for item in seq[1:]:
pform = prettyForm(*pform.right(sep))
pform = prettyForm(*pform.right(printer._print(item, *args)))
return pform
# Utilities for printing: these operate prettyForm objects
def _print_subscript_pretty(self, a, b):
top = prettyForm(*b.left(' '*a.width()))
bot = prettyForm(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.below(top))
def _print_superscript_pretty(self, a, b):
return a**b
def _print_parens_pretty(self, pform, left='(', right=')'):
return prettyForm(*pform.parens(left=left, right=right))
# Printing of labels (i.e. args)
def _print_label(self, printer, *args):
"""Prints the label of the QExpr
This method prints self.label, using self._label_separator to separate
the elements. This method should not be overridden, instead, override
_print_contents to change printing behavior.
"""
return self._print_sequence(
self.label, self._label_separator, printer, *args
)
def _print_label_repr(self, printer, *args):
return self._print_sequence(
self.label, ',', printer, *args
)
def _print_label_pretty(self, printer, *args):
return self._print_sequence_pretty(
self.label, self._label_separator, printer, *args
)
def _print_label_latex(self, printer, *args):
return self._print_sequence(
self.label, self._label_separator, printer, *args
)
# Printing of contents (default to label)
def _print_contents(self, printer, *args):
"""Printer for contents of QExpr
Handles the printing of any unique identifying contents of a QExpr to
print as its contents, such as any variables or quantum numbers. The
default is to print the label, which is almost always the args. This
should not include printing of any brackets or parenteses.
"""
return self._print_label(printer, *args)
def _print_contents_pretty(self, printer, *args):
return self._print_label_pretty(printer, *args)
def _print_contents_latex(self, printer, *args):
return self._print_label_latex(printer, *args)
# Main printing methods
def _sympystr(self, printer, *args):
"""Default printing behavior of QExpr objects
Handles the default printing of a QExpr. To add other things to the
printing of the object, such as an operator name to operators or
brackets to states, the class should override the _print/_pretty/_latex
functions directly and make calls to _print_contents where appropriate.
This allows things like InnerProduct to easily control its printing the
printing of contents.
"""
return self._print_contents(printer, *args)
def _sympyrepr(self, printer, *args):
classname = self.__class__.__name__
label = self._print_label_repr(printer, *args)
return '%s(%s)' % (classname, label)
def _pretty(self, printer, *args):
pform = self._print_contents_pretty(printer, *args)
return pform
def _latex(self, printer, *args):
return self._print_contents_latex(printer, *args)
#-------------------------------------------------------------------------
# Methods from Basic and Expr
#-------------------------------------------------------------------------
def doit(self, **kw_args):
return self
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_default_basis(self, **options):
raise NotImplementedError('This object does not have a default basis')
def _represent(self, *, basis=None, **options):
"""Represent this object in a given basis.
This method dispatches to the actual methods that perform the
representation. Subclases of QExpr should define various methods to
determine how the object will be represented in various bases. The
format of these methods is::
def _represent_BasisName(self, basis, **options):
Thus to define how a quantum object is represented in the basis of
the operator Position, you would define::
def _represent_Position(self, basis, **options):
Usually, basis object will be instances of Operator subclasses, but
there is a chance we will relax this in the future to accommodate other
types of basis sets that are not associated with an operator.
If the ``format`` option is given it can be ("sympy", "numpy",
"scipy.sparse"). This will ensure that any matrices that result from
representing the object are returned in the appropriate matrix format.
Parameters
==========
basis : Operator
The Operator whose basis functions will be used as the basis for
representation.
options : dict
A dictionary of key/value pairs that give options and hints for
the representation, such as the number of basis functions to
be used.
"""
if basis is None:
result = self._represent_default_basis(**options)
else:
result = dispatch_method(self, '_represent', basis, **options)
# If we get a matrix representation, convert it to the right format.
format = options.get('format', 'sympy')
result = self._format_represent(result, format)
return result
def _format_represent(self, result, format):
if format == 'sympy' and not isinstance(result, Matrix):
return to_sympy(result)
elif format == 'numpy' and not isinstance(result, numpy_ndarray):
return to_numpy(result)
elif format == 'scipy.sparse' and \
not isinstance(result, scipy_sparse_matrix):
return to_scipy_sparse(result)
return result
def split_commutative_parts(e):
"""Split into commutative and non-commutative parts."""
c_part, nc_part = e.args_cnc()
c_part = list(c_part)
return c_part, nc_part
def split_qexpr_parts(e):
"""Split an expression into Expr and noncommutative QExpr parts."""
expr_part = []
qexpr_part = []
for arg in e.args:
if not isinstance(arg, QExpr):
expr_part.append(arg)
else:
qexpr_part.append(arg)
return expr_part, qexpr_part
def dispatch_method(self, basename, arg, **options):
"""Dispatch a method to the proper handlers."""
method_name = '%s_%s' % (basename, arg.__class__.__name__)
if hasattr(self, method_name):
f = getattr(self, method_name)
# This can raise and we will allow it to propagate.
result = f(arg, **options)
if result is not None:
return result
raise NotImplementedError(
"%s.%s cannot handle: %r" %
(self.__class__.__name__, basename, arg)
)
|
d1e3d3d99a5f4a6ace665a00556dd658a56ad092f84a1e383b9749534fd58f0f | """Grover's algorithm and helper functions.
Todo:
* W gate construction (or perhaps -W gate based on Mermin's book)
* Generalize the algorithm for an unknown function that returns 1 on multiple
qubit states, not just one.
* Implement _represent_ZGate in OracleGate
"""
from sympy.core.numbers import pi
from sympy.core.sympify import sympify
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import eye
from sympy.core.numbers import NegativeOne
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.operator import UnitaryOperator
from sympy.physics.quantum.gate import Gate
from sympy.physics.quantum.qubit import IntQubit
__all__ = [
'OracleGate',
'WGate',
'superposition_basis',
'grover_iteration',
'apply_grover'
]
def superposition_basis(nqubits):
"""Creates an equal superposition of the computational basis.
Parameters
==========
nqubits : int
The number of qubits.
Returns
=======
state : Qubit
An equal superposition of the computational basis with nqubits.
Examples
========
Create an equal superposition of 2 qubits::
>>> from sympy.physics.quantum.grover import superposition_basis
>>> superposition_basis(2)
|0>/2 + |1>/2 + |2>/2 + |3>/2
"""
amp = 1/sqrt(2**nqubits)
return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)])
class OracleGate(Gate):
"""A black box gate.
The gate marks the desired qubits of an unknown function by flipping
the sign of the qubits. The unknown function returns true when it
finds its desired qubits and false otherwise.
Parameters
==========
qubits : int
Number of qubits.
oracle : callable
A callable function that returns a boolean on a computational basis.
Examples
========
Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.grover import OracleGate
>>> f = lambda qubits: qubits == IntQubit(2)
>>> v = OracleGate(2, f)
>>> qapply(v*IntQubit(2))
-|2>
>>> qapply(v*IntQubit(3))
|3>
"""
gate_name = 'V'
gate_name_latex = 'V'
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# TODO: args[1] is not a subclass of Basic
if len(args) != 2:
raise QuantumError(
'Insufficient/excessive arguments to Oracle. Please ' +
'supply the number of qubits and an unknown function.'
)
sub_args = (args[0],)
sub_args = UnitaryOperator._eval_args(sub_args)
if not sub_args[0].is_Integer:
raise TypeError('Integer expected, got: %r' % sub_args[0])
if not callable(args[1]):
raise TypeError('Callable expected, got: %r' % args[1])
return (sub_args[0], args[1])
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**args[0]
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def search_function(self):
"""The unknown function that helps find the sought after qubits."""
return self.label[1]
@property
def targets(self):
"""A tuple of target qubits."""
return sympify(tuple(range(self.args[0])))
#-------------------------------------------------------------------------
# Apply
#-------------------------------------------------------------------------
def _apply_operator_Qubit(self, qubits, **options):
"""Apply this operator to a Qubit subclass.
Parameters
==========
qubits : Qubit
The qubit subclass to apply this operator to.
Returns
=======
state : Expr
The resulting quantum state.
"""
if qubits.nqubits != self.nqubits:
raise QuantumError(
'OracleGate operates on %r qubits, got: %r'
% (self.nqubits, qubits.nqubits)
)
# If function returns 1 on qubits
# return the negative of the qubits (flip the sign)
if self.search_function(qubits):
return -qubits
else:
return qubits
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_ZGate(self, basis, **options):
"""
Represent the OracleGate in the computational basis.
"""
nbasis = 2**self.nqubits # compute it only once
matrixOracle = eye(nbasis)
# Flip the sign given the output of the oracle function
for i in range(nbasis):
if self.search_function(IntQubit(i, nqubits=self.nqubits)):
matrixOracle[i, i] = NegativeOne()
return matrixOracle
class WGate(Gate):
"""General n qubit W Gate in Grover's algorithm.
The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
Parameters
==========
nqubits : int
The number of qubits to operate on
"""
gate_name = 'W'
gate_name_latex = 'W'
@classmethod
def _eval_args(cls, args):
if len(args) != 1:
raise QuantumError(
'Insufficient/excessive arguments to W gate. Please ' +
'supply the number of qubits to operate on.'
)
args = UnitaryOperator._eval_args(args)
if not args[0].is_Integer:
raise TypeError('Integer expected, got: %r' % args[0])
return args
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def targets(self):
return sympify(tuple(reversed(range(self.args[0]))))
#-------------------------------------------------------------------------
# Apply
#-------------------------------------------------------------------------
def _apply_operator_Qubit(self, qubits, **options):
"""
qubits: a set of qubits (Qubit)
Returns: quantum object (quantum expression - QExpr)
"""
if qubits.nqubits != self.nqubits:
raise QuantumError(
'WGate operates on %r qubits, got: %r'
% (self.nqubits, qubits.nqubits)
)
# See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result
# Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis
# state and phi is the superposition of basis states (see function
# create_computational_basis above)
basis_states = superposition_basis(self.nqubits)
change_to_basis = (2/sqrt(2**self.nqubits))*basis_states
return change_to_basis - qubits
def grover_iteration(qstate, oracle):
"""Applies one application of the Oracle and W Gate, WV.
Parameters
==========
qstate : Qubit
A superposition of qubits.
oracle : OracleGate
The black box operator that flips the sign of the desired basis qubits.
Returns
=======
Qubit : The qubits after applying the Oracle and W gate.
Examples
========
Perform one iteration of grover's algorithm to see a phase change::
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.grover import OracleGate
>>> from sympy.physics.quantum.grover import superposition_basis
>>> from sympy.physics.quantum.grover import grover_iteration
>>> numqubits = 2
>>> basis_states = superposition_basis(numqubits)
>>> f = lambda qubits: qubits == IntQubit(2)
>>> v = OracleGate(numqubits, f)
>>> qapply(grover_iteration(basis_states, v))
|2>
"""
wgate = WGate(oracle.nqubits)
return wgate*oracle*qstate
def apply_grover(oracle, nqubits, iterations=None):
"""Applies grover's algorithm.
Parameters
==========
oracle : callable
The unknown callable function that returns true when applied to the
desired qubits and false otherwise.
Returns
=======
state : Expr
The resulting state after Grover's algorithm has been iterated.
Examples
========
Apply grover's algorithm to an even superposition of 2 qubits::
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.grover import apply_grover
>>> f = lambda qubits: qubits == IntQubit(2)
>>> qapply(apply_grover(f, 2))
|2>
"""
if nqubits <= 0:
raise QuantumError(
'Grover\'s algorithm needs nqubits > 0, received %r qubits'
% nqubits
)
if iterations is None:
iterations = floor(sqrt(2**nqubits)*(pi/4))
v = OracleGate(nqubits, oracle)
iterated = superposition_basis(nqubits)
for iter in range(iterations):
iterated = grover_iteration(iterated, v)
iterated = qapply(iterated)
return iterated
|
bc21fc73816ee6572b4f43ecb81a842bb7969f21ed091c15c78c128777f4ecc1 | from itertools import product
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import expand
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import log
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.operator import HermitianOperator
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy
from sympy.physics.quantum.tensorproduct import TensorProduct, tensor_product_simp
from sympy.physics.quantum.trace import Tr
class Density(HermitianOperator):
"""Density operator for representing mixed states.
TODO: Density operator support for Qubits
Parameters
==========
values : tuples/lists
Each tuple/list should be of form (state, prob) or [state,prob]
Examples
========
Create a density operator with 2 states represented by Kets.
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d
Density((|0>, 0.5),(|1>, 0.5))
"""
@classmethod
def _eval_args(cls, args):
# call this to qsympify the args
args = super()._eval_args(args)
for arg in args:
# Check if arg is a tuple
if not (isinstance(arg, Tuple) and len(arg) == 2):
raise ValueError("Each argument should be of form [state,prob]"
" or ( state, prob )")
return args
def states(self):
"""Return list of all states.
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.states()
(|0>, |1>)
"""
return Tuple(*[arg[0] for arg in self.args])
def probs(self):
"""Return list of all probabilities.
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.probs()
(0.5, 0.5)
"""
return Tuple(*[arg[1] for arg in self.args])
def get_state(self, index):
"""Return specific state by index.
Parameters
==========
index : index of state to be returned
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.states()[1]
|1>
"""
state = self.args[index][0]
return state
def get_prob(self, index):
"""Return probability of specific state by index.
Parameters
===========
index : index of states whose probability is returned.
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.probs()[1]
0.500000000000000
"""
prob = self.args[index][1]
return prob
def apply_op(self, op):
"""op will operate on each individual state.
Parameters
==========
op : Operator
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> from sympy.physics.quantum.operator import Operator
>>> A = Operator('A')
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.apply_op(A)
Density((A*|0>, 0.5),(A*|1>, 0.5))
"""
new_args = [(op*state, prob) for (state, prob) in self.args]
return Density(*new_args)
def doit(self, **hints):
"""Expand the density operator into an outer product format.
Examples
========
>>> from sympy.physics.quantum.state import Ket
>>> from sympy.physics.quantum.density import Density
>>> from sympy.physics.quantum.operator import Operator
>>> A = Operator('A')
>>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
>>> d.doit()
0.5*|0><0| + 0.5*|1><1|
"""
terms = []
for (state, prob) in self.args:
state = state.expand() # needed to break up (a+b)*c
if (isinstance(state, Add)):
for arg in product(state.args, repeat=2):
terms.append(prob*self._generate_outer_prod(arg[0],
arg[1]))
else:
terms.append(prob*self._generate_outer_prod(state, state))
return Add(*terms)
def _generate_outer_prod(self, arg1, arg2):
c_part1, nc_part1 = arg1.args_cnc()
c_part2, nc_part2 = arg2.args_cnc()
if (len(nc_part1) == 0 or len(nc_part2) == 0):
raise ValueError('Atleast one-pair of'
' Non-commutative instance required'
' for outer product.')
# Muls of Tensor Products should be expanded
# before this function is called
if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1
and len(nc_part2) == 1):
op = tensor_product_simp(nc_part1[0]*Dagger(nc_part2[0]))
else:
op = Mul(*nc_part1)*Dagger(Mul(*nc_part2))
return Mul(*c_part1)*Mul(*c_part2) * op
def _represent(self, **options):
return represent(self.doit(), **options)
def _print_operator_name_latex(self, printer, *args):
return r'\rho'
def _print_operator_name_pretty(self, printer, *args):
return prettyForm('\N{GREEK SMALL LETTER RHO}')
def _eval_trace(self, **kwargs):
indices = kwargs.get('indices', [])
return Tr(self.doit(), indices).doit()
def entropy(self):
""" Compute the entropy of a density matrix.
Refer to density.entropy() method for examples.
"""
return entropy(self)
def entropy(density):
"""Compute the entropy of a matrix/density object.
This computes -Tr(density*ln(density)) using the eigenvalue decomposition
of density, which is given as either a Density instance or a matrix
(numpy.ndarray, sympy.Matrix or scipy.sparse).
Parameters
==========
density : density matrix of type Density, SymPy matrix,
scipy.sparse or numpy.ndarray
Examples
========
>>> from sympy.physics.quantum.density import Density, entropy
>>> from sympy.physics.quantum.spin import JzKet
>>> from sympy import S
>>> up = JzKet(S(1)/2,S(1)/2)
>>> down = JzKet(S(1)/2,-S(1)/2)
>>> d = Density((up,S(1)/2),(down,S(1)/2))
>>> entropy(d)
log(2)/2
"""
if isinstance(density, Density):
density = represent(density) # represent in Matrix
if isinstance(density, scipy_sparse_matrix):
density = to_numpy(density)
if isinstance(density, Matrix):
eigvals = density.eigenvals().keys()
return expand(-sum(e*log(e) for e in eigvals))
elif isinstance(density, numpy_ndarray):
import numpy as np
eigvals = np.linalg.eigvals(density)
return -np.sum(eigvals*np.log(eigvals))
else:
raise ValueError(
"numpy.ndarray, scipy.sparse or SymPy matrix expected")
def fidelity(state1, state2):
""" Computes the fidelity [1]_ between two quantum states
The arguments provided to this function should be a square matrix or a
Density object. If it is a square matrix, it is assumed to be diagonalizable.
Parameters
==========
state1, state2 : a density matrix or Matrix
Examples
========
>>> from sympy import S, sqrt
>>> from sympy.physics.quantum.dagger import Dagger
>>> from sympy.physics.quantum.spin import JzKet
>>> from sympy.physics.quantum.density import fidelity
>>> from sympy.physics.quantum.represent import represent
>>>
>>> up = JzKet(S(1)/2,S(1)/2)
>>> down = JzKet(S(1)/2,-S(1)/2)
>>> amp = 1/sqrt(2)
>>> updown = (amp*up) + (amp*down)
>>>
>>> # represent turns Kets into matrices
>>> up_dm = represent(up*Dagger(up))
>>> down_dm = represent(down*Dagger(down))
>>> updown_dm = represent(updown*Dagger(updown))
>>>
>>> fidelity(up_dm, up_dm)
1
>>> fidelity(up_dm, down_dm) #orthogonal states
0
>>> fidelity(up_dm, updown_dm).evalf().round(3)
0.707
References
==========
.. [1] https://en.wikipedia.org/wiki/Fidelity_of_quantum_states
"""
state1 = represent(state1) if isinstance(state1, Density) else state1
state2 = represent(state2) if isinstance(state2, Density) else state2
if not isinstance(state1, Matrix) or not isinstance(state2, Matrix):
raise ValueError("state1 and state2 must be of type Density or Matrix "
"received type=%s for state1 and type=%s for state2" %
(type(state1), type(state2)))
if state1.shape != state2.shape and state1.is_square:
raise ValueError("The dimensions of both args should be equal and the "
"matrix obtained should be a square matrix")
sqrt_state1 = state1**S.Half
return Tr((sqrt_state1*state2*sqrt_state1)**S.Half).doit()
|
4be55bdd50231795e378cd291d0d2a2edaff9f37f6ade2061e2d3b553a85d779 | """
qasm.py - Functions to parse a set of qasm commands into a SymPy Circuit.
Examples taken from Chuang's page: http://www.media.mit.edu/quanta/qasm2circ/
The code returns a circuit and an associated list of labels.
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
__all__ = [
'Qasm',
]
from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE
from sympy.physics.quantum.circuitplot import Mz
def read_qasm(lines):
return Qasm(*lines.splitlines())
def read_qasm_file(filename):
return Qasm(*open(filename).readlines())
def prod(c):
p = 1
for ci in c:
p *= ci
return p
def flip_index(i, n):
"""Reorder qubit indices from largest to smallest.
>>> from sympy.physics.quantum.qasm import flip_index
>>> flip_index(0, 2)
1
>>> flip_index(1, 2)
0
"""
return n-i-1
def trim(line):
"""Remove everything following comment # characters in line.
>>> from sympy.physics.quantum.qasm import trim
>>> trim('nothing happens here')
'nothing happens here'
>>> trim('something #happens here')
'something '
"""
if not '#' in line:
return line
return line.split('#')[0]
def get_index(target, labels):
"""Get qubit labels from the rest of the line,and return indices
>>> from sympy.physics.quantum.qasm import get_index
>>> get_index('q0', ['q0', 'q1'])
1
>>> get_index('q1', ['q0', 'q1'])
0
"""
nq = len(labels)
return flip_index(labels.index(target), nq)
def get_indices(targets, labels):
return [get_index(t, labels) for t in targets]
def nonblank(args):
for line in args:
line = trim(line)
if line.isspace():
continue
yield line
return
def fullsplit(line):
words = line.split()
rest = ' '.join(words[1:])
return fixcommand(words[0]), [s.strip() for s in rest.split(',')]
def fixcommand(c):
"""Fix Qasm command names.
Remove all of forbidden characters from command c, and
replace 'def' with 'qdef'.
"""
forbidden_characters = ['-']
c = c.lower()
for char in forbidden_characters:
c = c.replace(char, '')
if c == 'def':
return 'qdef'
return c
def stripquotes(s):
"""Replace explicit quotes in a string.
>>> from sympy.physics.quantum.qasm import stripquotes
>>> stripquotes("'S'") == 'S'
True
>>> stripquotes('"S"') == 'S'
True
>>> stripquotes('S') == 'S'
True
"""
s = s.replace('"', '') # Remove second set of quotes?
s = s.replace("'", '')
return s
class Qasm:
"""Class to form objects from Qasm lines
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
def __init__(self, *args, **kwargs):
self.defs = {}
self.circuit = []
self.labels = []
self.inits = {}
self.add(*args)
self.kwargs = kwargs
def add(self, *lines):
for line in nonblank(lines):
command, rest = fullsplit(line)
if self.defs.get(command): #defs come first, since you can override built-in
function = self.defs.get(command)
indices = self.indices(rest)
if len(indices) == 1:
self.circuit.append(function(indices[0]))
else:
self.circuit.append(function(indices[:-1], indices[-1]))
elif hasattr(self, command):
function = getattr(self, command)
function(*rest)
else:
print("Function %s not defined. Skipping" % command)
def get_circuit(self):
return prod(reversed(self.circuit))
def get_labels(self):
return list(reversed(self.labels))
def plot(self):
from sympy.physics.quantum.circuitplot import CircuitPlot
circuit, labels = self.get_circuit(), self.get_labels()
CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits)
def qubit(self, arg, init=None):
self.labels.append(arg)
if init: self.inits[arg] = init
def indices(self, args):
return get_indices(args, self.labels)
def index(self, arg):
return get_index(arg, self.labels)
def nop(self, *args):
pass
def x(self, arg):
self.circuit.append(X(self.index(arg)))
def z(self, arg):
self.circuit.append(Z(self.index(arg)))
def h(self, arg):
self.circuit.append(H(self.index(arg)))
def s(self, arg):
self.circuit.append(S(self.index(arg)))
def t(self, arg):
self.circuit.append(T(self.index(arg)))
def measure(self, arg):
self.circuit.append(Mz(self.index(arg)))
def cnot(self, a1, a2):
self.circuit.append(CNOT(*self.indices([a1, a2])))
def swap(self, a1, a2):
self.circuit.append(SWAP(*self.indices([a1, a2])))
def cphase(self, a1, a2):
self.circuit.append(CPHASE(*self.indices([a1, a2])))
def toffoli(self, a1, a2, a3):
i1, i2, i3 = self.indices([a1, a2, a3])
self.circuit.append(CGateS((i1, i2), X(i3)))
def cx(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, X(fj)))
def cz(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, Z(fj)))
def defbox(self, *args):
print("defbox not supported yet. Skipping: ", args)
def qdef(self, name, ncontrols, symbol):
from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate
ncontrols = int(ncontrols)
command = fixcommand(name)
symbol = stripquotes(symbol)
if ncontrols > 0:
self.defs[command] = CreateCGate(symbol)
else:
self.defs[command] = CreateOneQubitGate(symbol)
|
6636f67111a78950d5e9edf98233f8b84a48e30d02ed81902045d179aabfcfe1 | """1D quantum particle in a box."""
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.sets.sets import Interval
from sympy.physics.quantum.operator import HermitianOperator
from sympy.physics.quantum.state import Ket, Bra
from sympy.physics.quantum.constants import hbar
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.hilbert import L2
m = Symbol('m')
L = Symbol('L')
__all__ = [
'PIABHamiltonian',
'PIABKet',
'PIABBra'
]
class PIABHamiltonian(HermitianOperator):
"""Particle in a box Hamiltonian operator."""
@classmethod
def _eval_hilbert_space(cls, label):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PIABKet(self, ket, **options):
n = ket.label[0]
return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
class PIABKet(Ket):
"""Particle in a box eigenket."""
@classmethod
def _eval_hilbert_space(cls, args):
return L2(Interval(S.NegativeInfinity, S.Infinity))
@classmethod
def dual_class(self):
return PIABBra
def _represent_default_basis(self, **options):
return self._represent_XOp(None, **options)
def _represent_XOp(self, basis, **options):
x = Symbol('x')
n = Symbol('n')
subs_info = options.get('subs', {})
return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)
def _eval_innerproduct_PIABBra(self, bra):
return KroneckerDelta(bra.label[0], self.label[0])
class PIABBra(Bra):
"""Particle in a box eigenbra."""
@classmethod
def _eval_hilbert_space(cls, label):
return L2(Interval(S.NegativeInfinity, S.Infinity))
@classmethod
def dual_class(self):
return PIABKet
|
ec888d9c5631c62f447c494216d30b11071c6fa9c1fa321eab8c7722522accab | """The commutator: [A,B] = A*B - B*A."""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.operator import Operator
__all__ = [
'Commutator'
]
#-----------------------------------------------------------------------------
# Commutator
#-----------------------------------------------------------------------------
class Commutator(Expr):
"""The standard commutator, in an unevaluated state.
Explanation
===========
Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
class returns the commutator in an unevaluated form. To evaluate the
commutator, use the ``.doit()`` method.
Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
arguments of the commutator are put into canonical order using ``__cmp__``.
If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
Parameters
==========
A : Expr
The first argument of the commutator [A,B].
B : Expr
The second argument of the commutator [A,B].
Examples
========
>>> from sympy.physics.quantum import Commutator, Dagger, Operator
>>> from sympy.abc import x, y
>>> A = Operator('A')
>>> B = Operator('B')
>>> C = Operator('C')
Create a commutator and use ``.doit()`` to evaluate it:
>>> comm = Commutator(A, B)
>>> comm
[A,B]
>>> comm.doit()
A*B - B*A
The commutator orders it arguments in canonical order:
>>> comm = Commutator(B, A); comm
-[A,B]
Commutative constants are factored out:
>>> Commutator(3*x*A, x*y*B)
3*x**2*y*[A,B]
Using ``.expand(commutator=True)``, the standard commutator expansion rules
can be applied:
>>> Commutator(A+B, C).expand(commutator=True)
[A,C] + [B,C]
>>> Commutator(A, B+C).expand(commutator=True)
[A,B] + [A,C]
>>> Commutator(A*B, C).expand(commutator=True)
[A,C]*B + A*[B,C]
>>> Commutator(A, B*C).expand(commutator=True)
[A,B]*C + B*[A,C]
Adjoint operations applied to the commutator are properly applied to the
arguments:
>>> Dagger(Commutator(A, B))
-[Dagger(A),Dagger(B)]
References
==========
.. [1] https://en.wikipedia.org/wiki/Commutator
"""
is_commutative = False
def __new__(cls, A, B):
r = cls.eval(A, B)
if r is not None:
return r
obj = Expr.__new__(cls, A, B)
return obj
@classmethod
def eval(cls, a, b):
if not (a and b):
return S.Zero
if a == b:
return S.Zero
if a.is_commutative or b.is_commutative:
return S.Zero
# [xA,yB] -> xy*[A,B]
ca, nca = a.args_cnc()
cb, ncb = b.args_cnc()
c_part = ca + cb
if c_part:
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
# Canonical ordering of arguments
# The Commutator [A, B] is in canonical form if A < B.
if a.compare(b) == 1:
return S.NegativeOne*cls(b, a)
def _expand_pow(self, A, B, sign):
exp = A.exp
if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
# nothing to do
return self
base = A.base
if exp.is_negative:
base = A.base**-1
exp = -exp
comm = Commutator(base, B).expand(commutator=True)
result = base**(exp - 1) * comm
for i in range(1, exp):
result += base**(exp - 1 - i) * comm * base**i
return sign*result.expand()
def _eval_expand_commutator(self, **hints):
A = self.args[0]
B = self.args[1]
if isinstance(A, Add):
# [A + B, C] -> [A, C] + [B, C]
sargs = []
for term in A.args:
comm = Commutator(term, B)
if isinstance(comm, Commutator):
comm = comm._eval_expand_commutator()
sargs.append(comm)
return Add(*sargs)
elif isinstance(B, Add):
# [A, B + C] -> [A, B] + [A, C]
sargs = []
for term in B.args:
comm = Commutator(A, term)
if isinstance(comm, Commutator):
comm = comm._eval_expand_commutator()
sargs.append(comm)
return Add(*sargs)
elif isinstance(A, Mul):
# [A*B, C] -> A*[B, C] + [A, C]*B
a = A.args[0]
b = Mul(*A.args[1:])
c = B
comm1 = Commutator(b, c)
comm2 = Commutator(a, c)
if isinstance(comm1, Commutator):
comm1 = comm1._eval_expand_commutator()
if isinstance(comm2, Commutator):
comm2 = comm2._eval_expand_commutator()
first = Mul(a, comm1)
second = Mul(comm2, b)
return Add(first, second)
elif isinstance(B, Mul):
# [A, B*C] -> [A, B]*C + B*[A, C]
a = A
b = B.args[0]
c = Mul(*B.args[1:])
comm1 = Commutator(a, b)
comm2 = Commutator(a, c)
if isinstance(comm1, Commutator):
comm1 = comm1._eval_expand_commutator()
if isinstance(comm2, Commutator):
comm2 = comm2._eval_expand_commutator()
first = Mul(comm1, c)
second = Mul(b, comm2)
return Add(first, second)
elif isinstance(A, Pow):
# [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
return self._expand_pow(A, B, 1)
elif isinstance(B, Pow):
# [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
return self._expand_pow(B, A, -1)
# No changes, so return self
return self
def doit(self, **hints):
""" Evaluate commutator """
A = self.args[0]
B = self.args[1]
if isinstance(A, Operator) and isinstance(B, Operator):
try:
comm = A._eval_commutator(B, **hints)
except NotImplementedError:
try:
comm = -1*B._eval_commutator(A, **hints)
except NotImplementedError:
comm = None
if comm is not None:
return comm.doit(**hints)
return (A*B - B*A).doit(**hints)
def _eval_adjoint(self):
return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
def _sympyrepr(self, printer, *args):
return "%s(%s,%s)" % (
self.__class__.__name__, printer._print(
self.args[0]), printer._print(self.args[1])
)
def _sympystr(self, printer, *args):
return "[%s,%s]" % (
printer._print(self.args[0]), printer._print(self.args[1]))
def _pretty(self, printer, *args):
pform = printer._print(self.args[0], *args)
pform = prettyForm(*pform.right(prettyForm(',')))
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
pform = prettyForm(*pform.parens(left='[', right=']'))
return pform
def _latex(self, printer, *args):
return "\\left[%s,%s\\right]" % tuple([
printer._print(arg, *args) for arg in self.args])
|
42eb9cbe60040e6287855094151a8f15b7992b18975a13bc2d05003f224ff2dc | """Quantum mechanical angular momemtum."""
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer, Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.simplify.simplify import simplify
from sympy.matrices import zeros
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import pretty_symbol
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.operator import (HermitianOperator, Operator,
UnitaryOperator)
from sympy.physics.quantum.state import Bra, Ket, State
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.cg import CG
from sympy.physics.quantum.qapply import qapply
__all__ = [
'm_values',
'Jplus',
'Jminus',
'Jx',
'Jy',
'Jz',
'J2',
'Rotation',
'WignerD',
'JxKet',
'JxBra',
'JyKet',
'JyBra',
'JzKet',
'JzBra',
'JzOp',
'J2Op',
'JxKetCoupled',
'JxBraCoupled',
'JyKetCoupled',
'JyBraCoupled',
'JzKetCoupled',
'JzBraCoupled',
'couple',
'uncouple'
]
def m_values(j):
j = sympify(j)
size = 2*j + 1
if not size.is_Integer or not size > 0:
raise ValueError(
'Only integer or half-integer values allowed for j, got: : %r' % j
)
return size, [j - i for i in range(int(2*j + 1))]
#-----------------------------------------------------------------------------
# Spin Operators
#-----------------------------------------------------------------------------
class SpinOpBase:
"""Base class for spin operators."""
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def name(self):
return self.args[0]
def _print_contents(self, printer, *args):
return '%s%s' % (self.name, self._coord)
def _print_contents_pretty(self, printer, *args):
a = stringPict(str(self.name))
b = stringPict(self._coord)
return self._print_subscript_pretty(a, b)
def _print_contents_latex(self, printer, *args):
return r'%s_%s' % ((self.name, self._coord))
def _represent_base(self, basis, **options):
j = options.get('j', S.Half)
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
result[p, q] = me
return result
def _apply_op(self, ket, orig_basis, **options):
state = ket.rewrite(self.basis)
# If the state has only one term
if isinstance(state, State):
ret = (hbar*state.m)*state
# state is a linear combination of states
elif isinstance(state, Sum):
ret = self._apply_operator_Sum(state, **options)
else:
ret = qapply(self*state)
if ret == self*state:
raise NotImplementedError
return ret.rewrite(orig_basis)
def _apply_operator_JxKet(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_TensorProduct(self, tp, **options):
# Uncoupling operator is only easily found for coordinate basis spin operators
# TODO: add methods for uncoupling operators
if not isinstance(self, (JxOp, JyOp, JzOp)):
raise NotImplementedError
result = []
for n in range(len(tp.args)):
arg = []
arg.extend(tp.args[:n])
arg.append(self._apply_operator(tp.args[n]))
arg.extend(tp.args[n + 1:])
result.append(tp.__class__(*arg))
return Add(*result).expand()
# TODO: move this to qapply_Mul
def _apply_operator_Sum(self, s, **options):
new_func = qapply(self*s.function)
if new_func == self*s.function:
raise NotImplementedError
return Sum(new_func, *s.limits)
def _eval_trace(self, **options):
#TODO: use options to use different j values
#For now eval at default basis
# is it efficient to represent each time
# to do a trace?
return self._represent_default_basis().trace()
class JplusOp(SpinOpBase, Operator):
"""The J+ operator."""
_coord = '+'
basis = 'Jz'
def _eval_commutator_JminusOp(self, other):
return 2*hbar*JzOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
result *= KroneckerDelta(m, mp + 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) + I*JyOp(args[0])
class JminusOp(SpinOpBase, Operator):
"""The J- operator."""
_coord = '-'
basis = 'Jz'
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
result *= KroneckerDelta(m, mp - 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) - I*JyOp(args[0])
class JxOp(SpinOpBase, HermitianOperator):
"""The Jx operator."""
_coord = 'x'
basis = 'Jx'
def _eval_commutator_JyOp(self, other):
return I*hbar*JzOp(self.name)
def _eval_commutator_JzOp(self, other):
return -I*hbar*JyOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp + jm)/Integer(2)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp + jm)/Integer(2)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp + jm)/Integer(2)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) + JminusOp(args[0]))/2
class JyOp(SpinOpBase, HermitianOperator):
"""The Jy operator."""
_coord = 'y'
basis = 'Jy'
def _eval_commutator_JzOp(self, other):
return I*hbar*JxOp(self.name)
def _eval_commutator_JxOp(self, other):
return -I*hbar*J2Op(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp - jm)/(Integer(2)*I)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
class JzOp(SpinOpBase, HermitianOperator):
"""The Jz operator."""
_coord = 'z'
basis = 'Jz'
def _eval_commutator_JxOp(self, other):
return I*hbar*JyOp(self.name)
def _eval_commutator_JyOp(self, other):
return -I*hbar*JxOp(self.name)
def _eval_commutator_JplusOp(self, other):
return hbar*JplusOp(self.name)
def _eval_commutator_JminusOp(self, other):
return -hbar*JminusOp(self.name)
def matrix_element(self, j, m, jp, mp):
result = hbar*mp
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
class J2Op(SpinOpBase, HermitianOperator):
"""The J^2 operator."""
_coord = '2'
def _eval_commutator_JxOp(self, other):
return S.Zero
def _eval_commutator_JyOp(self, other):
return S.Zero
def _eval_commutator_JzOp(self, other):
return S.Zero
def _eval_commutator_JplusOp(self, other):
return S.Zero
def _eval_commutator_JminusOp(self, other):
return S.Zero
def _apply_operator_JxKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JxKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def matrix_element(self, j, m, jp, mp):
result = (hbar**2)*j*(j + 1)
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _print_contents_pretty(self, printer, *args):
a = prettyForm(str(self.name))
b = prettyForm('2')
return a**b
def _print_contents_latex(self, printer, *args):
return r'%s^2' % str(self.name)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
a = args[0]
return JzOp(a)**2 + \
S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
class Rotation(UnitaryOperator):
"""Wigner D operator in terms of Euler angles.
Defines the rotation operator in terms of the Euler angles defined by
the z-y-z convention for a passive transformation. That is the coordinate
axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
this new coordinate system is rotated about the new y'-axis, giving new
x''-y''-z'' axes. Then this new coordinate system is rotated about the
z''-axis. Conventions follow those laid out in [1]_.
Parameters
==========
alpha : Number, Symbol
First Euler Angle
beta : Number, Symbol
Second Euler angle
gamma : Number, Symbol
Third Euler angle
Examples
========
A simple example rotation operator:
>>> from sympy import pi
>>> from sympy.physics.quantum.spin import Rotation
>>> Rotation(pi, 0, pi/2)
R(pi,0,pi/2)
With symbolic Euler angles and calculating the inverse rotation operator:
>>> from sympy import symbols
>>> a, b, c = symbols('a b c')
>>> Rotation(a, b, c)
R(a,b,c)
>>> Rotation(a, b, c).inverse()
R(-c,-b,-a)
See Also
========
WignerD: Symbolic Wigner-D function
D: Wigner-D function
d: Wigner small-d function
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
@classmethod
def _eval_args(cls, args):
args = QExpr._eval_args(args)
if len(args) != 3:
raise ValueError('3 Euler angles required, got: %r' % args)
return args
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def alpha(self):
return self.label[0]
@property
def beta(self):
return self.label[1]
@property
def gamma(self):
return self.label[2]
def _print_operator_name(self, printer, *args):
return 'R'
def _print_operator_name_pretty(self, printer, *args):
if printer._use_unicode:
return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
else:
return prettyForm("R ")
def _print_operator_name_latex(self, printer, *args):
return r'\mathcal{R}'
def _eval_inverse(self):
return Rotation(-self.gamma, -self.beta, -self.alpha)
@classmethod
def D(cls, j, m, mp, alpha, beta, gamma):
"""Wigner D-function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> alpha, beta, gamma = symbols('alpha beta gamma')
>>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
WignerD(1, 1, 0, pi, pi/2, -pi)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, alpha, beta, gamma)
@classmethod
def d(cls, j, m, mp, beta):
"""Wigner small-d function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters with the alpha and gamma angles
given as 0.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
beta : Number, Symbol
Second Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> beta = symbols('beta')
>>> Rotation.d(1, 1, 0, pi/2)
WignerD(1, 1, 0, 0, pi/2, 0)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, 0, beta, 0)
def matrix_element(self, j, m, jp, mp):
result = self.__class__.D(
jp, m, mp, self.alpha, self.beta, self.gamma
)
result *= KroneckerDelta(j, jp)
return result
def _represent_base(self, basis, **options):
j = sympify(options.get('j', S.Half))
# TODO: move evaluation up to represent function/implement elsewhere
evaluate = sympify(options.get('doit'))
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
if evaluate:
result[p, q] = me.doit()
else:
result[p, q] = me
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
def _apply_operator_JxKet(self, ket, **options):
return self._apply_operator_uncoupled(JxKet, ket, **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_operator_uncoupled(JyKet, ket, **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_operator_uncoupled(JzKet, ket, **options)
def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp, jn, coupling))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(
j, mp, jn, coupling), (mp, -j, j))
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JxKetCoupled, ket, **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JyKetCoupled, ket, **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JzKetCoupled, ket, **options)
class WignerD(Expr):
r"""Wigner-D function
The Wigner D-function gives the matrix elements of the rotation
operator in the jm-representation. For the Euler angles `\alpha`,
`\beta`, `\gamma`, the D-function is defined such that:
.. math ::
<j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
Where the rotation operator is as defined by the Rotation class [1]_.
The Wigner D-function defined in this way gives:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the Wigner small-d function, which is given by Rotation.d.
The Wigner small-d function gives the component of the Wigner
D-function that is determined by the second Euler angle. That is the
Wigner D-function is:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the small-d function. The Wigner D-function is given by
Rotation.D.
Note that to evaluate the D-function, the j, m and mp parameters must
be integer or half integer numbers.
Parameters
==========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Evaluate the Wigner-D matrix elements of a simple rotation:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi
>>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
>>> rot
WignerD(1, 1, 0, pi, pi/2, 0)
>>> rot.doit()
sqrt(2)/2
Evaluate the Wigner-d matrix elements of a simple rotation
>>> rot = Rotation.d(1, 1, 0, pi/2)
>>> rot
WignerD(1, 1, 0, 0, pi/2, 0)
>>> rot.doit()
-sqrt(2)/2
See Also
========
Rotation: Rotation operator
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, *args, **hints):
if not len(args) == 6:
raise ValueError('6 parameters expected, got %s' % args)
args = sympify(args)
evaluate = hints.get('evaluate', False)
if evaluate:
return Expr.__new__(cls, *args)._eval_wignerd()
return Expr.__new__(cls, *args)
@property
def j(self):
return self.args[0]
@property
def m(self):
return self.args[1]
@property
def mp(self):
return self.args[2]
@property
def alpha(self):
return self.args[3]
@property
def beta(self):
return self.args[4]
@property
def gamma(self):
return self.args[5]
def _latex(self, printer, *args):
if self.alpha == 0 and self.gamma == 0:
return r'd^{%s}_{%s,%s}\left(%s\right)' % \
(
printer._print(self.j), printer._print(
self.m), printer._print(self.mp),
printer._print(self.beta) )
return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
(
printer._print(
self.j), printer._print(self.m), printer._print(self.mp),
printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
def _pretty(self, printer, *args):
top = printer._print(self.j)
bot = printer._print(self.m)
bot = prettyForm(*bot.right(','))
bot = prettyForm(*bot.right(printer._print(self.mp)))
pad = max(top.width(), bot.width())
top = prettyForm(*top.left(' '))
bot = prettyForm(*bot.left(' '))
if pad > top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
if pad > bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if self.alpha == 0 and self.gamma == 0:
args = printer._print(self.beta)
s = stringPict('d' + ' '*pad)
else:
args = printer._print(self.alpha)
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.beta)))
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.gamma)))
s = stringPict('D' + ' '*pad)
args = prettyForm(*args.parens())
s = prettyForm(*s.above(top))
s = prettyForm(*s.below(bot))
s = prettyForm(*s.right(args))
return s
def doit(self, **hints):
hints['evaluate'] = True
return WignerD(*self.args, **hints)
def _eval_wignerd(self):
j = sympify(self.j)
m = sympify(self.m)
mp = sympify(self.mp)
alpha = sympify(self.alpha)
beta = sympify(self.beta)
gamma = sympify(self.gamma)
if alpha == 0 and beta == 0 and gamma == 0:
return KroneckerDelta(m, mp)
if not j.is_number:
raise ValueError(
'j parameter must be numerical to evaluate, got %s' % j)
r = 0
if beta == pi/2:
# Varshalovich Equation (5), Section 4.16, page 113, setting
# alpha=gamma=0.
for k in range(2*j + 1):
if k > j + mp or k > j - m or k < mp - m:
continue
r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
else:
# Varshalovich Equation(5), Section 4.7.2, page 87, where we set
# beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
# then we use the Eq. (1), Section 4.4. page 79, to simplify:
# d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
# This happens to be almost the same as in Eq.(10), Section 4.16,
# except that we need to substitute -mp for mp.
size, mvals = m_values(j)
for mpp in mvals:
r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
Rotation.d(j, mpp, -mp, pi/2).doit()
# Empirical normalization factor so results match Varshalovich
# Tables 4.3-4.12
# Note that this exact normalization does not follow from the
# above equations
r = r*I**(2*j - m - mp)*(-1)**(2*m)
# Finally, simplify the whole expression
r = simplify(r)
r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
return r
Jx = JxOp('J')
Jy = JyOp('J')
Jz = JzOp('J')
J2 = J2Op('J')
Jplus = JplusOp('J')
Jminus = JminusOp('J')
#-----------------------------------------------------------------------------
# Spin States
#-----------------------------------------------------------------------------
class SpinState(State):
"""Base class for angular momentum states."""
_label_separator = ','
def __new__(cls, j, m):
j = sympify(j)
m = sympify(m)
if j.is_number:
if 2*j != int(2*j):
raise ValueError(
'j must be integer or half-integer, got: %s' % j)
if j < 0:
raise ValueError('j must be >= 0, got: %s' % j)
if m.is_number:
if 2*m != int(2*m):
raise ValueError(
'm must be integer or half-integer, got: %s' % m)
if j.is_number and m.is_number:
if abs(m) > j:
raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
if int(j - m) != j - m:
raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
return State.__new__(cls, j, m)
@property
def j(self):
return self.label[0]
@property
def m(self):
return self.label[1]
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(2*label[0] + 1)
def _represent_base(self, **options):
j = self.j
m = self.m
alpha = sympify(options.get('alpha', 0))
beta = sympify(options.get('beta', 0))
gamma = sympify(options.get('gamma', 0))
size, mvals = m_values(j)
result = zeros(size, 1)
# breaks finding angles on L930
for p, mval in enumerate(mvals):
if m.is_number:
result[p, 0] = Rotation.D(
self.j, mval, self.m, alpha, beta, gamma).doit()
else:
result[p, 0] = Rotation.D(self.j, mval,
self.m, alpha, beta, gamma)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBra, **options)
return self._rewrite_basis(Jx, JxKet, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBra, **options)
return self._rewrite_basis(Jy, JyKet, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBra, **options)
return self._rewrite_basis(Jz, JzKet, **options)
def _rewrite_basis(self, basis, evect, **options):
from sympy.physics.quantum.represent import represent
j = self.j
args = self.args[2:]
if j.is_number:
if isinstance(self, CoupledSpinState):
if j == int(j):
start = j**2
else:
start = (2*j - 1)*(2*j + 1)/4
else:
start = 0
vect = represent(self, basis=basis, **options)
result = Add(
*[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
return uncouple(result)
return result
else:
i = 0
mi = symbols('mi')
# make sure not to introduce a symbol already in the state
while self.subs(mi, 0) != self:
i += 1
mi = symbols('mi%d' % i)
break
# TODO: better way to get angles of rotation
if isinstance(self, CoupledSpinState):
test_args = (0, mi, (0, 0))
else:
test_args = (0, mi)
if isinstance(self, Ket):
angles = represent(
self.__class__(*test_args), basis=basis)[0].args[3:6]
else:
angles = represent(self.__class__(
*test_args), basis=basis)[0].args[0].args[3:6]
if angles == (0, 0, 0):
return self
else:
state = evect(j, mi, *args)
lt = Rotation.D(j, mi, self.m, *angles)
return Sum(lt*state, (mi, -j, j))
def _eval_innerproduct_JxBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JxOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JyBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JyOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JzBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JzOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_trace(self, bra, **hints):
# One way to implement this method is to assume the basis set k is
# passed.
# Then we can apply the discrete form of Trace formula here
# Tr(|i><j| ) = \Sum_k <k|i><j|k>
#then we do qapply() on each each inner product and sum over them.
# OR
# Inner product of |i><j| = Trace(Outer Product).
# we could just use this unless there are cases when this is not true
return (bra*self).doit()
class JxKet(SpinState, Ket):
"""Eigenket of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxBra
@classmethod
def coupled_class(self):
return JxKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JxOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(beta=pi/2, **options)
class JxBra(SpinState, Bra):
"""Eigenbra of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxKet
@classmethod
def coupled_class(self):
return JxBraCoupled
class JyKet(SpinState, Ket):
"""Eigenket of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyBra
@classmethod
def coupled_class(self):
return JyKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JyOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBra(SpinState, Bra):
"""Eigenbra of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyKet
@classmethod
def coupled_class(self):
return JyBraCoupled
class JzKet(SpinState, Ket):
"""Eigenket of Jz.
Spin state which is an eigenstate of the Jz operator. Uncoupled states,
that is states representing the interaction of multiple separate spin
states, are defined as a tensor product of states.
Parameters
==========
j : Number, Symbol
Total spin angular momentum
m : Number, Symbol
Eigenvalue of the Jz spin operator
Examples
========
*Normal States:*
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKet, JxKet
>>> from sympy import symbols
>>> JzKet(1, 0)
|1,0>
>>> j, m = symbols('j m')
>>> JzKet(j, m)
|j,m>
Rewriting the JzKet in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKet's
>>> JzKet(1,1).rewrite("Jx")
|1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx, Jz
>>> represent(JzKet(1,-1), basis=Jx)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
Apply innerproducts between states:
>>> from sympy.physics.quantum.innerproduct import InnerProduct
>>> from sympy.physics.quantum.spin import JxBra
>>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
>>> i
<1,1|1,1>
>>> i.doit()
1/2
*Uncoupled States:*
Define an uncoupled state as a TensorProduct between two Jz eigenkets:
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> TensorProduct(JzKet(1,0), JzKet(1,1))
|1,0>x|1,1>
>>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
|j1,m1>x|j2,m2>
A TensorProduct can be rewritten, in which case the eigenstates that make
up the tensor product is rewritten to the new basis:
>>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
|1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
The represent method for TensorProduct's gives the vector representation of
the state. Note that the state in the product basis is the equivalent of the
tensor product of the vector representation of the component eigenstates:
>>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
Matrix([
[0],
[0],
[0],
[1],
[0],
[0],
[0],
[0],
[0]])
>>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0]])
See Also
========
JzKetCoupled: Coupled eigenstates
sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
uncouple: Uncouples states given coupling parameters
couple: Couples uncoupled states
"""
@classmethod
def dual_class(self):
return JzBra
@classmethod
def coupled_class(self):
return JzKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(**options)
class JzBra(SpinState, Bra):
"""Eigenbra of Jz.
See the JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JzKet
@classmethod
def coupled_class(self):
return JzBraCoupled
# Method used primarily to create coupled_n and coupled_jn by __new__ in
# CoupledSpinState
# This same method is also used by the uncouple method, and is separated from
# the CoupledSpinState class to maintain consistency in defining coupling
def _build_coupled(jcoupling, length):
n_list = [ [n + 1] for n in range(length) ]
coupled_jn = []
coupled_n = []
for n1, n2, j_new in jcoupling:
coupled_jn.append(j_new)
coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
n_list[n_sort[0] - 1] = n_sort
return coupled_n, coupled_jn
class CoupledSpinState(SpinState):
"""Base class for coupled angular momentum states."""
def __new__(cls, j, m, jn, *jcoupling):
# Check j and m values using SpinState
SpinState(j, m)
# Build and check coupling scheme from arguments
if len(jcoupling) == 0:
# Use default coupling scheme
jcoupling = []
for n in range(2, len(jn)):
jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
jcoupling.append( (1, len(jn), j) )
elif len(jcoupling) == 1:
# Use specified coupling scheme
jcoupling = jcoupling[0]
else:
raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
# Check arguments have correct form
if not isinstance(jn, (list, tuple, Tuple)):
raise TypeError('jn must be Tuple, list or tuple, got %s' %
jn.__class__.__name__)
if not isinstance(jcoupling, (list, tuple, Tuple)):
raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
jcoupling.__class__.__name__)
if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
raise TypeError(
'All elements of jcoupling must be list, tuple or Tuple')
if not len(jn) - 1 == len(jcoupling):
raise ValueError('jcoupling must have length of %d, got %d' %
(len(jn) - 1, len(jcoupling)))
if not all(len(x) == 3 for x in jcoupling):
raise ValueError('All elements of jcoupling must have length 3')
# Build sympified args
j = sympify(j)
m = sympify(m)
jn = Tuple( *[sympify(ji) for ji in jn] )
jcoupling = Tuple( *[Tuple(sympify(
n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
# Check values in coupling scheme give physical state
if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
raise ValueError('Indices in jcoupling must be integers')
if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
jvals = list(jn)
for n, (n1, n2) in enumerate(coupled_n):
j1 = jvals[min(n1) - 1]
j2 = jvals[min(n2) - 1]
j3 = coupled_jn[n]
if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
if j1 + j2 < j3:
raise ValueError('All couplings must have j1+j2 >= j3, '
'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
if abs(j1 - j2) > j3:
raise ValueError("All couplings must have |j1+j2| <= j3, "
"in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
if int(j1 + j2) == j1 + j2:
pass
jvals[min(n1 + n2) - 1] = j3
if len(jcoupling) > 0 and jcoupling[-1][2] != j:
raise ValueError('Last j value coupled together must be the final j of the state')
# Return state
return State.__new__(cls, j, m, jn, jcoupling)
def _print_label(self, printer, *args):
label = [printer._print(self.j), printer._print(self.m)]
for i, ji in enumerate(self.jn, start=1):
label.append('j%d=%s' % (
i, printer._print(ji)
))
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
label.append('j(%s)=%s' % (
','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
))
return ','.join(label)
def _print_label_pretty(self, printer, *args):
label = [self.j, self.m]
for i, ji in enumerate(self.jn, start=1):
symb = 'j%d' % i
symb = pretty_symbol(symb)
symb = prettyForm(symb + '=')
item = prettyForm(*symb.right(printer._print(ji)))
label.append(item)
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
symb = prettyForm('j' + n + '=')
item = prettyForm(*symb.right(printer._print(jn)))
label.append(item)
return self._print_sequence_pretty(
label, self._label_separator, printer, *args
)
def _print_label_latex(self, printer, *args):
label = [
printer._print(self.j, *args),
printer._print(self.m, *args)
]
for i, ji in enumerate(self.jn, start=1):
label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(str(i) for i in sorted(n1 + n2))
label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
return self._label_separator.join(label)
@property
def jn(self):
return self.label[2]
@property
def coupling(self):
return self.label[3]
@property
def coupled_jn(self):
return _build_coupled(self.label[3], len(self.label[2]))[1]
@property
def coupled_n(self):
return _build_coupled(self.label[3], len(self.label[2]))[0]
@classmethod
def _eval_hilbert_space(cls, label):
j = Add(*label[2])
if j.is_number:
return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
else:
# TODO: Need hilbert space fix, see issue 5732
# Desired behavior:
#ji = symbols('ji')
#ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
# Temporary fix:
return ComplexSpace(2*j + 1)
def _represent_coupled_base(self, **options):
evect = self.uncoupled_class()
if not self.j.is_number:
raise ValueError(
'State must not have symbolic j value to represent')
if not self.hilbert_space.dimension.is_number:
raise ValueError(
'State must not have symbolic j values to represent')
result = zeros(self.hilbert_space.dimension, 1)
if self.j == int(self.j):
start = self.j**2
else:
start = (2*self.j - 1)*(1 + 2*self.j)/4
result[start:start + 2*self.j + 1, 0] = evect(
self.j, self.m)._represent_base(**options)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBraCoupled, **options)
return self._rewrite_basis(Jx, JxKetCoupled, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBraCoupled, **options)
return self._rewrite_basis(Jy, JyKetCoupled, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBraCoupled, **options)
return self._rewrite_basis(Jz, JzKetCoupled, **options)
class JxKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxBraCoupled
@classmethod
def uncoupled_class(self):
return JxKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(beta=pi/2, **options)
class JxBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxKetCoupled
@classmethod
def uncoupled_class(self):
return JxBra
class JyKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyBraCoupled
@classmethod
def uncoupled_class(self):
return JyKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyKetCoupled
@classmethod
def uncoupled_class(self):
return JyBra
class JzKetCoupled(CoupledSpinState, Ket):
r"""Coupled eigenket of Jz
Spin state that is an eigenket of Jz which represents the coupling of
separate spin spaces.
The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
are the total angular momentum quantum numbers, as used for normal states
(e.g. JzKet).
The other required parameter in ``jn``, which is a tuple defining the `j_n`
angular momentum quantum numbers of the product spaces. So for example, if
a state represented the coupling of the product basis state
`\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
for this state would be ``(j1,j2)``.
The final option is ``jcoupling``, which is used to define how the spaces
specified by ``jn`` are coupled, which includes both the order these spaces
are coupled together and the quantum numbers that arise from these
couplings. The ``jcoupling`` parameter itself is a list of lists, such that
each of the sublists defines a single coupling between the spin spaces. If
there are N coupled angular momentum spaces, that is ``jn`` has N elements,
then there must be N-1 sublists. Each of these sublists making up the
``jcoupling`` parameter have length 3. The first two elements are the
indices of the product spaces that are considered to be coupled together.
For example, if we want to couple `j_1` and `j_4`, the indices would be 1
and 4. If a state has already been coupled, it is referenced by the
smallest index that is coupled, so if `j_2` and `j_4` has already been
coupled to some `j_{24}`, then this value can be coupled by referencing it
with index 2. The final element of the sublist is the quantum number of the
coupled state. So putting everything together, into a valid sublist for
``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
with quantum number `j_{12}` with the value ``j12``, the sublist would be
``(1,2,j12)``, N-1 of these sublists are used in the list for
``jcoupling``.
Note the ``jcoupling`` parameter is optional, if it is not specified, the
default coupling is taken. This default value is to coupled the spaces in
order and take the quantum number of the coupling to be the maximum value.
For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
`j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
`j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
correspond to this is:
``((1,2,j1+j2),(1,3,j1+j2+j3))``
Parameters
==========
args : tuple
The arguments that must be passed are ``j``, ``m``, ``jn``, and
``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
value is the eigenvalue of the Jz spin operator. The ``jn`` list are
the j values of argular momentum spaces coupled together. The
``jcoupling`` parameter is an optional parameter defining how the spaces
are coupled together. See the above description for how these coupling
parameters are defined.
Examples
========
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKetCoupled
>>> from sympy import symbols
>>> JzKetCoupled(1, 0, (1, 1))
|1,0,j1=1,j2=1>
>>> j, m, j1, j2 = symbols('j m j1 j2')
>>> JzKetCoupled(j, m, (j1, j2))
|j,m,j1=j1,j2=j2>
Defining coupled spin states for more than 2 coupled spaces with various
coupling parameters:
>>> JzKetCoupled(2, 1, (1, 1, 1))
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
|2,1,j1=1,j2=1,j3=1,j(2,3)=1>
Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKetCoupled
>>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
|1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
The rewrite method can be used to convert a coupled state to an uncoupled
state. This is done by passing coupled=False to the rewrite function:
>>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
-sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx
>>> from sympy import S
>>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
Matrix([
[ 0],
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
See Also
========
JzKet: Normal spin eigenstates
uncouple: Uncoupling of coupling spin states
couple: Coupling of uncoupled spin states
"""
@classmethod
def dual_class(self):
return JzBraCoupled
@classmethod
def uncoupled_class(self):
return JzKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(**options)
class JzBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jz.
See the JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JzKetCoupled
@classmethod
def uncoupled_class(self):
return JzBra
#-----------------------------------------------------------------------------
# Coupling/uncoupling
#-----------------------------------------------------------------------------
def couple(expr, jcoupling_list=None):
""" Couple a tensor product of spin states
This function can be used to couple an uncoupled tensor product of spin
states. All of the eigenstates to be coupled must be of the same class. It
will return a linear combination of eigenstates that are subclasses of
CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
coefficients.
Parameters
==========
expr : Expr
An expression involving TensorProducts of spin states to be coupled.
Each state must be a subclass of SpinState and they all must be the
same class.
jcoupling_list : list or tuple
Elements of this list are sub-lists of length 2 specifying the order of
the coupling of the spin spaces. The length of this must be N-1, where N
is the number of states in the tensor product to be coupled. The
elements of this sublist are the same as the first two elements of each
sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
parameter is not specified, the default value is taken, which couples
the first and second product basis spaces, then couples this new coupled
space to the third product space, etc
Examples
========
Couple a tensor product of numerical states for two spaces:
>>> from sympy.physics.quantum.spin import JzKet, couple
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
-sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
Numerical coupling of three spaces using the default coupling method, i.e.
first and second spaces couple, then this couples to the third space:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
Perform this same coupling, but we define the coupling to first couple
the first and third spaces:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
Couple a tensor product of symbolic states:
>>> from sympy import symbols
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
"""
a = expr.atoms(TensorProduct)
for tp in a:
# Allow other tensor products to be in expression
if not all(isinstance(state, SpinState) for state in tp.args):
continue
# If tensor product has all spin states, raise error for invalid tensor product state
if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
raise TypeError('All states must be the same basis')
expr = expr.subs(tp, _couple(tp, jcoupling_list))
return expr
def _couple(tp, jcoupling_list):
states = tp.args
coupled_evect = states[0].coupled_class()
# Define default coupling if none is specified
if jcoupling_list is None:
jcoupling_list = []
for n in range(1, len(states)):
jcoupling_list.append( (1, n + 1) )
# Check jcoupling_list valid
if not len(jcoupling_list) == len(states) - 1:
raise TypeError('jcoupling_list must be length %d, got %d' %
(len(states) - 1, len(jcoupling_list)))
if not all( len(coupling) == 2 for coupling in jcoupling_list):
raise ValueError('Each coupling must define 2 spaces')
if any(n1 == n2 for n1, n2 in jcoupling_list):
raise ValueError('Spin spaces cannot couple to themselves')
if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
j_test = [0]*len(states)
for n1, n2 in jcoupling_list:
if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
j_test[max(n1, n2) - 1] = -1
# j values of states to be coupled together
jn = [state.j for state in states]
mn = [state.m for state in states]
# Create coupling_list, which defines all the couplings between all
# the spaces from jcoupling_list
coupling_list = []
n_list = [ [i + 1] for i in range(len(states)) ]
for j_coupling in jcoupling_list:
# Least n for all j_n which is coupled as first and second spaces
n1, n2 = j_coupling
# List of all n's coupled in first and second spaces
j1_n = list(n_list[n1 - 1])
j2_n = list(n_list[n2 - 1])
coupling_list.append( (j1_n, j2_n) )
# Set new j_n to be coupling of all j_n in both first and second spaces
n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
if all(state.j.is_number and state.m.is_number for state in states):
# Numerical coupling
# Iterate over difference between maximum possible j value of each coupling and the actual value
diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
coupling[1] ] ) for coupling in coupling_list ]
result = []
for diff in range(diff_max[-1] + 1):
# Determine available configurations
n = len(coupling_list)
tot = binomial(diff + n - 1, diff)
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
# Skip the configuration if non-physical
# This is a lazy check for physical states given the loose restrictions of diff_max
if any(d > m for d, m in zip(diff_list, diff_max)):
continue
# Determine term
cg_terms = []
coupled_j = list(jn)
jcoupling = []
for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
j3 = j1 + j2 - coupling_diff
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
# Better checks that state is physical
if any(abs(term[5]) > term[4] for term in cg_terms):
continue
if any(term[0] + term[2] < term[4] for term in cg_terms):
continue
if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
continue
coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
cg_terms = []
jcoupling = []
sum_terms = []
coupled_j = list(jn)
for j1_n, j2_n in coupling_list:
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
if len(j1_n + j2_n) == len(states):
j3 = symbols('j')
else:
j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
j3 = symbols(j3_name)
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
sum_terms.append((j3, m3, j1 + j2))
coeff = Mul( *[ CG(*term) for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
return Sum(coeff*state, *sum_terms)
def uncouple(expr, jn=None, jcoupling_list=None):
""" Uncouple a coupled spin state
Gives the uncoupled representation of a coupled spin state. Arguments must
be either a spin state that is a subclass of CoupledSpinState or a spin
state that is a subclass of SpinState and an array giving the j values
of the spaces that are to be coupled
Parameters
==========
expr : Expr
The expression containing states that are to be coupled. If the states
are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
must be defined. If the states are a subclass of CoupledSpinState,
``jn`` and ``jcoupling`` will be taken from the state.
jn : list or tuple
The list of the j-values that are coupled. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jn`` parameter of JzKetCoupled.
jcoupling_list : list or tuple
The list defining how the j-values are coupled together. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
Examples
========
Uncouple a numerical state using a CoupledSpinState state:
>>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
>>> from sympy import S
>>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Perform the same calculation using a SpinState state:
>>> from sympy.physics.quantum.spin import JzKet
>>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
>>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Perform the same calculation using a SpinState state:
>>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Uncouple a symbolic state using a CoupledSpinState state:
>>> from sympy import symbols
>>> j,m,j1,j2 = symbols('j m j1 j2')
>>> uncouple(JzKetCoupled(j, m, (j1, j2)))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
Perform the same calculation using a SpinState state
>>> uncouple(JzKet(j, m), (j1, j2))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
"""
a = expr.atoms(SpinState)
for state in a:
expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
return expr
def _uncouple(state, jn, jcoupling_list):
if isinstance(state, CoupledSpinState):
jn = state.jn
coupled_n = state.coupled_n
coupled_jn = state.coupled_jn
evect = state.uncoupled_class()
elif isinstance(state, SpinState):
if jn is None:
raise ValueError("Must specify j-values for coupled state")
if not isinstance(jn, (list, tuple)):
raise TypeError("jn must be list or tuple")
if jcoupling_list is None:
# Use default
jcoupling_list = []
for i in range(1, len(jn)):
jcoupling_list.append(
(1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
if not isinstance(jcoupling_list, (list, tuple)):
raise TypeError("jcoupling must be a list or tuple")
if not len(jcoupling_list) == len(jn) - 1:
raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
evect = state.__class__
else:
raise TypeError("state must be a spin state")
j = state.j
m = state.m
coupling_list = []
j_list = list(jn)
# Create coupling, which defines all the couplings between all the spaces
for j3, (n1, n2) in zip(coupled_jn, coupled_n):
# j's which are coupled as first and second spaces
j1 = j_list[n1[0] - 1]
j2 = j_list[n2[0] - 1]
# Build coupling list
coupling_list.append( (n1, n2, j1, j2, j3) )
# Set new value in j_list
j_list[min(n1 + n2) - 1] = j3
if j.is_number and m.is_number:
diff_max = [ 2*x for x in jn ]
diff = Add(*jn) - m
n = len(jn)
tot = binomial(diff + n - 1, diff)
result = []
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
if any(d > p for d, p in zip(diff_list, diff_max)):
continue
cg_terms = []
for coupling in coupling_list:
j1_n, j2_n, j1, j2, j3 = coupling
m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
state = TensorProduct(
*[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
m_str = "m1:%d" % (len(jn) + 1)
mvals = symbols(m_str)
cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
return Sum(cg_coeff*state, *sum_terms)
def _confignum_to_difflist(config_num, diff, list_len):
# Determines configuration of diffs into list_len number of slots
diff_list = []
for n in range(list_len):
prev_diff = diff
# Number of spots after current one
rem_spots = list_len - n - 1
# Number of configurations of distributing diff among the remaining spots
rem_configs = binomial(diff + rem_spots - 1, diff)
while config_num >= rem_configs:
config_num -= rem_configs
diff -= 1
rem_configs = binomial(diff + rem_spots - 1, diff)
diff_list.append(prev_diff - diff)
return diff_list
|
8d161a7dc48736544aec3d6197eba9443e12648602985a503aa7c450d590e895 | """Matplotlib based plotting of quantum circuits.
Todo:
* Optimize printing of large circuits.
* Get this to work with single gates.
* Do a better job checking the form of circuits to make sure it is a Mul of
Gates.
* Get multi-target gates plotting.
* Get initial and final states to plot.
* Get measurements to plot. Might need to rethink measurement as a gate
issue.
* Get scale and figsize to be handled in a better way.
* Write some tests/examples!
"""
from typing import List, Dict as tDict
from sympy.core.mul import Mul
from sympy.external import import_module
from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
from sympy.core.core import BasicMeta
from sympy.core.assumptions import ManagedProperties
__all__ = [
'CircuitPlot',
'circuit_plot',
'labeller',
'Mz',
'Mx',
'CreateOneQubitGate',
'CreateCGate',
]
np = import_module('numpy')
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,)) # This is raised in environments that have no display.
if np and matplotlib:
pyplot = matplotlib.pyplot
Line2D = matplotlib.lines.Line2D
Circle = matplotlib.patches.Circle
#from matplotlib import rc
#rc('text',usetex=True)
class CircuitPlot:
"""A class for managing a circuit plot."""
scale = 1.0
fontsize = 20.0
linewidth = 1.0
control_radius = 0.05
not_radius = 0.15
swap_delta = 0.05
labels = [] # type: List[str]
inits = {} # type: tDict[str, str]
label_buffer = 0.5
def __init__(self, c, nqubits, **kwargs):
if not np or not matplotlib:
raise ImportError('numpy or matplotlib not available.')
self.circuit = c
self.ngates = len(self.circuit.args)
self.nqubits = nqubits
self.update(kwargs)
self._create_grid()
self._create_figure()
self._plot_wires()
self._plot_gates()
self._finish()
def update(self, kwargs):
"""Load the kwargs into the instance dict."""
self.__dict__.update(kwargs)
def _create_grid(self):
"""Create the grid of wires."""
scale = self.scale
wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
self._wire_grid = wire_grid
self._gate_grid = gate_grid
def _create_figure(self):
"""Create the main matplotlib figure."""
self._figure = pyplot.figure(
figsize=(self.ngates*self.scale, self.nqubits*self.scale),
facecolor='w',
edgecolor='w'
)
ax = self._figure.add_subplot(
1, 1, 1,
frameon=True
)
ax.set_axis_off()
offset = 0.5*self.scale
ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
ax.set_aspect('equal')
self._axes = ax
def _plot_wires(self):
"""Plot the wires of the circuit diagram."""
xstart = self._gate_grid[0]
xstop = self._gate_grid[-1]
xdata = (xstart - self.scale, xstop + self.scale)
for i in range(self.nqubits):
ydata = (self._wire_grid[i], self._wire_grid[i])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
if self.labels:
init_label_buffer = 0
if self.inits.get(self.labels[i]): init_label_buffer = 0.25
self._axes.text(
xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
render_label(self.labels[i],self.inits),
size=self.fontsize,
color='k',ha='center',va='center')
self._plot_measured_wires()
def _plot_measured_wires(self):
ismeasured = self._measurements()
xstop = self._gate_grid[-1]
dy = 0.04 # amount to shift wires when doubled
# Plot doubled wires after they are measured
for im in ismeasured:
xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
# Also double any controlled lines off these wires
for i,g in enumerate(self._gates()):
if isinstance(g, (CGate, CGateS)):
wires = g.controls + g.targets
for wire in wires:
if wire in ismeasured and \
self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
ydata = min(wires), max(wires)
xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def _gates(self):
"""Create a list of all gates in the circuit plot."""
gates = []
if isinstance(self.circuit, Mul):
for g in reversed(self.circuit.args):
if isinstance(g, Gate):
gates.append(g)
elif isinstance(self.circuit, Gate):
gates.append(self.circuit)
return gates
def _plot_gates(self):
"""Iterate through the gates and plot each of them."""
for i, gate in enumerate(self._gates()):
gate.plot_gate(self, i)
def _measurements(self):
"""Return a dict {i:j} where i is the index of the wire that has
been measured, and j is the gate where the wire is measured.
"""
ismeasured = {}
for i,g in enumerate(self._gates()):
if getattr(g,'measurement',False):
for target in g.targets:
if target in ismeasured:
if ismeasured[target] > i:
ismeasured[target] = i
else:
ismeasured[target] = i
return ismeasured
def _finish(self):
# Disable clipping to make panning work well for large circuits.
for o in self._figure.findobj():
o.set_clip_on(False)
def one_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a single qubit gate."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
self._axes.text(
x, y, t,
color='k',
ha='center',
va='center',
bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
size=self.fontsize
)
def two_qubit_box(self, t, gate_idx, wire_idx):
"""Draw a box for a two qubit gate. Doesn't work yet.
"""
# x = self._gate_grid[gate_idx]
# y = self._wire_grid[wire_idx]+0.5
print(self._gate_grid)
print(self._wire_grid)
# unused:
# obj = self._axes.text(
# x, y, t,
# color='k',
# ha='center',
# va='center',
# bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
# size=self.fontsize
# )
def control_line(self, gate_idx, min_wire, max_wire):
"""Draw a vertical control line."""
xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
line = Line2D(
xdata, ydata,
color='k',
lw=self.linewidth
)
self._axes.add_line(line)
def control_point(self, gate_idx, wire_idx):
"""Draw a control point."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.control_radius
c = Circle(
(x, y),
radius*self.scale,
ec='k',
fc='k',
fill=True,
lw=self.linewidth
)
self._axes.add_patch(c)
def not_point(self, gate_idx, wire_idx):
"""Draw a NOT gates as the circle with plus in the middle."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
radius = self.not_radius
c = Circle(
(x, y),
radius,
ec='k',
fc='w',
fill=False,
lw=self.linewidth
)
self._axes.add_patch(c)
l = Line2D(
(x, x), (y - radius, y + radius),
color='k',
lw=self.linewidth
)
self._axes.add_line(l)
def swap_point(self, gate_idx, wire_idx):
"""Draw a swap point as a cross."""
x = self._gate_grid[gate_idx]
y = self._wire_grid[wire_idx]
d = self.swap_delta
l1 = Line2D(
(x - d, x + d),
(y - d, y + d),
color='k',
lw=self.linewidth
)
l2 = Line2D(
(x - d, x + d),
(y + d, y - d),
color='k',
lw=self.linewidth
)
self._axes.add_line(l1)
self._axes.add_line(l2)
def circuit_plot(c, nqubits, **kwargs):
"""Draw the circuit diagram for the circuit with nqubits.
Parameters
==========
c : circuit
The circuit to plot. Should be a product of Gate instances.
nqubits : int
The number of qubits to include in the circuit. Must be at least
as big as the largest `min_qubits`` of the gates.
"""
return CircuitPlot(c, nqubits, **kwargs)
def render_label(label, inits={}):
"""Slightly more flexible way to render labels.
>>> from sympy.physics.quantum.circuitplot import render_label
>>> render_label('q0')
'$\\\\left|q0\\\\right\\\\rangle$'
>>> render_label('q0', {'q0':'0'})
'$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
"""
init = inits.get(label)
if init:
return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
return r'$\left|%s\right\rangle$' % label
def labeller(n, symbol='q'):
"""Autogenerate labels for wires of quantum circuits.
Parameters
==========
n : int
number of qubits in the circuit.
symbol : string
A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
>>> from sympy.physics.quantum.circuitplot import labeller
>>> labeller(2)
['q_1', 'q_0']
>>> labeller(3,'j')
['j_2', 'j_1', 'j_0']
"""
return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
class Mz(OneQubitGate):
"""Mock-up of a z measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mz'
gate_name_latex='M_z'
class Mx(OneQubitGate):
"""Mock-up of an x measurement gate.
This is in circuitplot rather than gate.py because it's not a real
gate, it just draws one.
"""
measurement = True
gate_name='Mx'
gate_name_latex='M_x'
class CreateOneQubitGate(ManagedProperties):
def __new__(mcl, name, latexname=None):
if not latexname:
latexname = name
return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,),
{'gate_name': name, 'gate_name_latex': latexname})
def CreateCGate(name, latexname=None):
"""Use a lexical closure to make a controlled gate.
"""
if not latexname:
latexname = name
onequbitgate = CreateOneQubitGate(name, latexname)
def ControlledGate(ctrls,target):
return CGate(tuple(ctrls),onequbitgate(target))
return ControlledGate
|
1f06787e5b57a287b6e38f8657fe533fd599cbbeb0c8fd3cf84c4cf8d7eea4ef | from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import sympify
from sympy.matrices import Matrix
def _is_scalar(e):
""" Helper method used in Tr"""
# sympify to set proper attributes
e = sympify(e)
if isinstance(e, Expr):
if (e.is_Integer or e.is_Float or
e.is_Rational or e.is_Number or
(e.is_Symbol and e.is_commutative)
):
return True
return False
def _cycle_permute(l):
""" Cyclic permutations based on canonical ordering
Explanation
===========
This method does the sort based ascii values while
a better approach would be to used lexicographic sort.
TODO: Handle condition such as symbols have subscripts/superscripts
in case of lexicographic sort
"""
if len(l) == 1:
return l
min_item = min(l, key=default_sort_key)
indices = [i for i, x in enumerate(l) if x == min_item]
le = list(l)
le.extend(l) # duplicate and extend string for easy processing
# adding the first min_item index back for easier looping
indices.append(len(l) + indices[0])
# create sublist of items with first item as min_item and last_item
# in each of the sublist is item just before the next occurrence of
# minitem in the cycle formed.
sublist = [[le[indices[i]:indices[i + 1]]] for i in
range(len(indices) - 1)]
# we do comparison of strings by comparing elements
# in each sublist
idx = sublist.index(min(sublist))
ordered_l = le[indices[idx]:indices[idx] + len(l)]
return ordered_l
def _rearrange_args(l):
""" this just moves the last arg to first position
to enable expansion of args
A,B,A ==> A**2,B
"""
if len(l) == 1:
return l
x = list(l[-1:])
x.extend(l[0:-1])
return Mul(*x).args
class Tr(Expr):
""" Generic Trace operation than can trace over:
a) SymPy matrix
b) operators
c) outer products
Parameters
==========
o : operator, matrix, expr
i : tuple/list indices (optional)
Examples
========
# TODO: Need to handle printing
a) Trace(A+B) = Tr(A) + Tr(B)
b) Trace(scalar*Operator) = scalar*Trace(Operator)
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy import symbols, Matrix
>>> a, b = symbols('a b', commutative=True)
>>> A, B = symbols('A B', commutative=False)
>>> Tr(a*A,[2])
a*Tr(A)
>>> m = Matrix([[1,2],[1,1]])
>>> Tr(m)
2
"""
def __new__(cls, *args):
""" Construct a Trace object.
Parameters
==========
args = SymPy expression
indices = tuple/list if indices, optional
"""
# expect no indices,int or a tuple/list/Tuple
if (len(args) == 2):
if not isinstance(args[1], (list, Tuple, tuple)):
indices = Tuple(args[1])
else:
indices = Tuple(*args[1])
expr = args[0]
elif (len(args) == 1):
indices = Tuple()
expr = args[0]
else:
raise ValueError("Arguments to Tr should be of form "
"(expr[, [indices]])")
if isinstance(expr, Matrix):
return expr.trace()
elif hasattr(expr, 'trace') and callable(expr.trace):
#for any objects that have trace() defined e.g numpy
return expr.trace()
elif isinstance(expr, Add):
return Add(*[Tr(arg, indices) for arg in expr.args])
elif isinstance(expr, Mul):
c_part, nc_part = expr.args_cnc()
if len(nc_part) == 0:
return Mul(*c_part)
else:
obj = Expr.__new__(cls, Mul(*nc_part), indices )
#this check is needed to prevent cached instances
#being returned even if len(c_part)==0
return Mul(*c_part)*obj if len(c_part) > 0 else obj
elif isinstance(expr, Pow):
if (_is_scalar(expr.args[0]) and
_is_scalar(expr.args[1])):
return expr
else:
return Expr.__new__(cls, expr, indices)
else:
if (_is_scalar(expr)):
return expr
return Expr.__new__(cls, expr, indices)
@property
def kind(self):
expr = self.args[0]
expr_kind = expr.kind
return expr_kind.element_kind
def doit(self, **kwargs):
""" Perform the trace operation.
#TODO: Current version ignores the indices set for partial trace.
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy.physics.quantum.operator import OuterProduct
>>> from sympy.physics.quantum.spin import JzKet, JzBra
>>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1)))
>>> t.doit()
1
"""
if hasattr(self.args[0], '_eval_trace'):
return self.args[0]._eval_trace(indices=self.args[1])
return self
@property
def is_number(self):
# TODO : improve this implementation
return True
#TODO: Review if the permute method is needed
# and if it needs to return a new instance
def permute(self, pos):
""" Permute the arguments cyclically.
Parameters
==========
pos : integer, if positive, shift-right, else shift-left
Examples
========
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy import symbols
>>> A, B, C, D = symbols('A B C D', commutative=False)
>>> t = Tr(A*B*C*D)
>>> t.permute(2)
Tr(C*D*A*B)
>>> t.permute(-2)
Tr(C*D*A*B)
"""
if pos > 0:
pos = pos % len(self.args[0].args)
else:
pos = -(abs(pos) % len(self.args[0].args))
args = list(self.args[0].args[-pos:] + self.args[0].args[0:-pos])
return Tr(Mul(*(args)))
def _hashable_content(self):
if isinstance(self.args[0], Mul):
args = _cycle_permute(_rearrange_args(self.args[0].args))
else:
args = [self.args[0]]
return tuple(args) + (self.args[1], )
|
c5fa6a4ba7b5ec863a66f4abd9e570559db7cdaba43c8c521aa87bf95a8b8ce4 | #TODO:
# -Implement Clebsch-Gordan symmetries
# -Improve simplification method
# -Implement new simpifications
"""Clebsch-Gordon Coefficients."""
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Wild, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
from sympy.printing.precedence import PRECEDENCE
__all__ = [
'CG',
'Wigner3j',
'Wigner6j',
'Wigner9j',
'cg_simp'
]
#-----------------------------------------------------------------------------
# CG Coefficients
#-----------------------------------------------------------------------------
class Wigner3j(Expr):
"""Class for the Wigner-3j symbols.
Explanation
===========
Wigner 3j-symbols are coefficients determined by the coupling of
two angular momenta. When created, they are expressed as symbolic
quantities that, for numerical parameters, can be evaluated using the
``.doit()`` method [1]_.
Parameters
==========
j1, m1, j2, m2, j3, m3 : Number, Symbol
Terms determining the angular momentum of coupled angular momentum
systems.
Examples
========
Declare a Wigner-3j coefficient and calculate its value
>>> from sympy.physics.quantum.cg import Wigner3j
>>> w3j = Wigner3j(6,0,4,0,2,0)
>>> w3j
Wigner3j(6, 0, 4, 0, 2, 0)
>>> w3j.doit()
sqrt(715)/143
See Also
========
CG: Clebsch-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, j1, m1, j2, m2, j3, m3):
args = map(sympify, (j1, m1, j2, m2, j3, m3))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def m1(self):
return self.args[1]
@property
def j2(self):
return self.args[2]
@property
def m2(self):
return self.args[3]
@property
def j3(self):
return self.args[4]
@property
def m3(self):
return self.args[5]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.m1)),
(printer._print(self.j2), printer._print(self.m2)),
(printer._print(self.j3), printer._print(self.m3)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens())
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j3,
self.m1, self.m2, self.m3))
return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
class CG(Wigner3j):
r"""Class for Clebsch-Gordan coefficient.
Explanation
===========
Clebsch-Gordan coefficients describe the angular momentum coupling between
two systems. The coefficients give the expansion of a coupled total angular
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
coefficients are defined as [1]_:
.. math ::
C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
Parameters
==========
j1, m1, j2, m2 : Number, Symbol
Angular momenta of states 1 and 2.
j3, m3: Number, Symbol
Total angular momentum of the coupled system.
Examples
========
Define a Clebsch-Gordan coefficient and evaluate its value
>>> from sympy.physics.quantum.cg import CG
>>> from sympy import S
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
>>> cg
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
>>> cg.doit()
sqrt(3)/2
>>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
sqrt(2)/2
Compare [2]_.
See Also
========
Wigner3j: Wigner-3j symbols
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
.. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
<https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
2020, 083C01 (2020).
"""
precedence = PRECEDENCE["Pow"] - 1
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
def _pretty(self, printer, *args):
bot = printer._print_seq(
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
top = printer._print_seq((self.j3, self.m3), delimiter=',')
pad = max(top.width(), bot.width())
bot = prettyForm(*bot.left(' '))
top = prettyForm(*top.left(' '))
if not pad == bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if not pad == top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
s = stringPict('C' + ' '*pad)
s = prettyForm(*s.below(bot))
s = prettyForm(*s.above(top))
return s
def _latex(self, printer, *args):
label = map(printer._print, (self.j3, self.m3, self.j1,
self.m1, self.j2, self.m2))
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
class Wigner6j(Expr):
"""Class for the Wigner-6j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j, j23):
args = map(sympify, (j1, j2, j12, j3, j, j23))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j(self):
return self.args[4]
@property
def j23(self):
return self.args[5]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.j3)),
(printer._print(self.j2), printer._print(self.j)),
(printer._print(self.j12), printer._print(self.j23)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12,
self.j3, self.j, self.j23))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
class Wigner9j(Expr):
"""Class for the Wigner-9j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j4(self):
return self.args[4]
@property
def j34(self):
return self.args[5]
@property
def j13(self):
return self.args[6]
@property
def j24(self):
return self.args[7]
@property
def j(self):
return self.args[8]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = (
(printer._print(
self.j1), printer._print(self.j3), printer._print(self.j13)),
(printer._print(
self.j2), printer._print(self.j4), printer._print(self.j24)),
(printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(3) ])
D = None
for i in range(3):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
self.j4, self.j34, self.j13, self.j24, self.j))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
def cg_simp(e):
"""Simplify and combine CG coefficients.
Explanation
===========
This function uses various symmetry and properties of sums and
products of Clebsch-Gordan coefficients to simplify statements
involving these terms [1]_.
Examples
========
Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
2*a+1
>>> from sympy.physics.quantum.cg import CG, cg_simp
>>> a = CG(1,1,0,0,1,1)
>>> b = CG(1,0,0,0,1,0)
>>> c = CG(1,-1,0,0,1,-1)
>>> cg_simp(a+b+c)
3
See Also
========
CG: Clebsh-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
if isinstance(e, Add):
return _cg_simp_add(e)
elif isinstance(e, Sum):
return _cg_simp_sum(e)
elif isinstance(e, Mul):
return Mul(*[cg_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
return Pow(cg_simp(e.base), e.exp)
else:
return e
def _cg_simp_add(e):
#TODO: Improve simplification method
"""Takes a sum of terms involving Clebsch-Gordan coefficients and
simplifies the terms.
Explanation
===========
First, we create two lists, cg_part, which is all the terms involving CG
coefficients, and other_part, which is all other terms. The cg_part list
is then passed to the simplification methods, which return the new cg_part
and any additional terms that are added to other_part
"""
cg_part = []
other_part = []
e = expand(e)
for arg in e.args:
if arg.has(CG):
if isinstance(arg, Sum):
other_part.append(_cg_simp_sum(arg))
elif isinstance(arg, Mul):
terms = 1
for term in arg.args:
if isinstance(term, Sum):
terms *= _cg_simp_sum(term)
else:
terms *= term
if terms.has(CG):
cg_part.append(terms)
else:
other_part.append(terms)
else:
cg_part.append(arg)
else:
other_part.append(arg)
cg_part, other = _check_varsh_871_1(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_871_2(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_872_9(cg_part)
other_part.append(other)
return Add(*cg_part) + Add(*other_part)
def _check_varsh_871_1(term_list):
# Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
expr = lt*CG(a, alpha, b, 0, a, alpha)
simp = (2*a + 1)*KroneckerDelta(b, 0)
sign = lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
def _check_varsh_871_2(term_list):
# Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
expr = lt*CG(a, alpha, a, -alpha, c, 0)
simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
sign = (-1)**(a - alpha)*lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
def _check_varsh_872_9(term_list):
# Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
# Case alpha==alphap, beta==betap
# For numerical alpha,beta
expr = lt*CG(a, alpha, b, beta, c, gamma)**2
simp = 1
sign = lt/abs(lt)
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# For symbolic alpha,beta
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# Case alpha!=alphap or beta!=betap
# Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
# For numerical alpha,alphap,beta,betap
expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
sign = sympify(1)
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other3 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
# For symbolic alpha,alphap,beta,betap
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other4 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
return term_list, other1 + other2 + other4
def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
""" Checks for simplifications that can be made, returning a tuple of the
simplified list of terms and any terms generated by simplification.
Parameters
==========
expr: expression
The expression with Wild terms that will be matched to the terms in
the sum
simp: expression
The expression with Wild terms that is substituted in place of the CG
terms in the case of simplification
sign: expression
The expression with Wild terms denoting the sign that is on expr that
must match
lt: expression
The expression with Wild terms that gives the leading term of the
matched expr
term_list: list
A list of all of the terms is the sum to be simplified
variables: list
A list of all the variables that appears in expr
dep_variables: list
A list of the variables that must match for all the terms in the sum,
i.e. the dependent variables
build_index_expr: expression
Expression with Wild terms giving the number of elements in cg_index
index_expr: expression
Expression with Wild terms giving the index terms have when storing
them to cg_index
"""
other_part = 0
i = 0
while i < len(term_list):
sub_1 = _check_cg(term_list[i], expr, len(variables))
if sub_1 is None:
i += 1
continue
if not sympify(build_index_expr.subs(sub_1)).is_number:
i += 1
continue
sub_dep = [(x, sub_1[x]) for x in dep_variables]
cg_index = [None]*build_index_expr.subs(sub_1)
for j in range(i, len(term_list)):
sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
if sub_2 is None:
continue
if not sympify(index_expr.subs(sub_dep).subs(sub_2)).is_number:
continue
cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
if not any(i is None for i in cg_index):
min_lt = min(*[ abs(term[2]) for term in cg_index ])
indices = [ term[0] for term in cg_index]
indices.sort()
indices.reverse()
[ term_list.pop(j) for j in indices ]
for term in cg_index:
if abs(term[2]) > min_lt:
term_list.append( (term[2] - min_lt*term[3])*term[1] )
other_part += min_lt*(sign*simp).subs(sub_1)
else:
i += 1
return term_list, other_part
def _check_cg(cg_term, expr, length, sign=None):
"""Checks whether a term matches the given expression"""
# TODO: Check for symmetries
matches = cg_term.match(expr)
if matches is None:
return
if sign is not None:
if not isinstance(sign, tuple):
raise TypeError('sign must be a tuple')
if not sign[0] == (sign[1]).subs(matches):
return
if len(matches) == length:
return matches
def _cg_simp_sum(e):
e = _check_varsh_sum_871_1(e)
e = _check_varsh_sum_871_2(e)
e = _check_varsh_sum_872_4(e)
return e
def _check_varsh_sum_871_1(e):
a = Wild('a')
alpha = symbols('alpha')
b = Wild('b')
match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
if match is not None and len(match) == 2:
return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
return e
def _check_varsh_sum_871_2(e):
a = Wild('a')
alpha = symbols('alpha')
c = Wild('c')
match = e.match(
Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
if match is not None and len(match) == 2:
return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
return e
def _check_varsh_sum_872_4(e):
alpha = symbols('alpha')
beta = symbols('beta')
a = Wild('a')
b = Wild('b')
c = Wild('c')
cp = Wild('cp')
gamma = Wild('gamma')
gammap = Wild('gammap')
cg1 = CG(a, alpha, b, beta, c, gamma)
cg2 = CG(a, alpha, b, beta, cp, gammap)
match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
if match1 is not None and len(match1) == 6:
return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
if match2 is not None and len(match2) == 4:
return S.One
return e
def _cg_list(term):
if isinstance(term, CG):
return (term,), 1, 1
cg = []
coeff = 1
if not isinstance(term, (Mul, Pow)):
raise NotImplementedError('term must be CG, Add, Mul or Pow')
if isinstance(term, Pow) and sympify(term.exp).is_number:
if sympify(term.exp).is_number:
[ cg.append(term.base) for _ in range(term.exp) ]
else:
return (term,), 1, 1
if isinstance(term, Mul):
for arg in term.args:
if isinstance(arg, CG):
cg.append(arg)
else:
coeff *= arg
return cg, coeff, coeff/abs(coeff)
|
b2f733359f3ad4147d2a2320dd0bbcc8edcb8023e451d36c667b296875639fbf | """Fermionic quantum operators."""
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.physics.quantum import Operator
from sympy.physics.quantum import HilbertSpace, Ket, Bra
from sympy.functions.special.tensor_functions import KroneckerDelta
__all__ = [
'FermionOp',
'FermionFockKet',
'FermionFockBra'
]
class FermionOp(Operator):
"""A fermionic operator that satisfies {c, Dagger(c)} == 1.
Parameters
==========
name : str
A string that labels the fermionic mode.
annihilation : bool
A bool that indicates if the fermionic operator is an annihilation
(True, default value) or creation operator (False)
Examples
========
>>> from sympy.physics.quantum import Dagger, AntiCommutator
>>> from sympy.physics.quantum.fermion import FermionOp
>>> c = FermionOp("c")
>>> AntiCommutator(c, Dagger(c)).doit()
1
"""
@property
def name(self):
return self.args[0]
@property
def is_annihilation(self):
return bool(self.args[1])
@classmethod
def default_args(self):
return ("c", True)
def __new__(cls, *args, **hints):
if not len(args) in [1, 2]:
raise ValueError('1 or 2 parameters expected, got %s' % args)
if len(args) == 1:
args = (args[0], S.One)
if len(args) == 2:
args = (args[0], Integer(args[1]))
return Operator.__new__(cls, *args)
def _eval_commutator_FermionOp(self, other, **hints):
if 'independent' in hints and hints['independent']:
# [c, d] = 0
return S.Zero
return None
def _eval_anticommutator_FermionOp(self, other, **hints):
if self.name == other.name:
# {a^\dagger, a} = 1
if not self.is_annihilation and other.is_annihilation:
return S.One
elif 'independent' in hints and hints['independent']:
# {c, d} = 2 * c * d, because [c, d] = 0 for independent operators
return 2 * self * other
return None
def _eval_anticommutator_BosonOp(self, other, **hints):
# because fermions and bosons commute
return 2 * self * other
def _eval_commutator_BosonOp(self, other, **hints):
return S.Zero
def _eval_adjoint(self):
return FermionOp(str(self.name), not self.is_annihilation)
def _print_contents_latex(self, printer, *args):
if self.is_annihilation:
return r'{%s}' % str(self.name)
else:
return r'{{%s}^\dagger}' % str(self.name)
def _print_contents(self, printer, *args):
if self.is_annihilation:
return r'%s' % str(self.name)
else:
return r'Dagger(%s)' % str(self.name)
def _print_contents_pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
if self.is_annihilation:
return pform
else:
return pform**prettyForm('\N{DAGGER}')
class FermionFockKet(Ket):
"""Fock state ket for a fermionic mode.
Parameters
==========
n : Number
The Fock state number.
"""
def __new__(cls, n):
if n not in (0, 1):
raise ValueError("n must be 0 or 1")
return Ket.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return FermionFockBra
@classmethod
def _eval_hilbert_space(cls, label):
return HilbertSpace()
def _eval_innerproduct_FermionFockBra(self, bra, **hints):
return KroneckerDelta(self.n, bra.n)
def _apply_operator_FermionOp(self, op, **options):
if op.is_annihilation:
if self.n == 1:
return FermionFockKet(0)
else:
return S.Zero
else:
if self.n == 0:
return FermionFockKet(1)
else:
return S.Zero
class FermionFockBra(Bra):
"""Fock state bra for a fermionic mode.
Parameters
==========
n : Number
The Fock state number.
"""
def __new__(cls, n):
if n not in (0, 1):
raise ValueError("n must be 0 or 1")
return Bra.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return FermionFockKet
|
5c0f58c42373be3d06d2fdb0f2933105194aac10afa41e75fff7fab1292fc6c2 | """Primitive circuit operations on quantum circuits."""
from functools import reduce
from sympy.core.sorting import default_sort_key
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.utilities import numbered_symbols
from sympy.physics.quantum.gate import Gate
__all__ = [
'kmp_table',
'find_subcircuit',
'replace_subcircuit',
'convert_to_symbolic_indices',
'convert_to_real_indices',
'random_reduce',
'random_insert'
]
def kmp_table(word):
"""Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
Note: This is applicable to strings or
quantum circuits represented as tuples.
"""
# Current position in subcircuit
pos = 2
# Beginning position of candidate substring that
# may reappear later in word
cnd = 0
# The 'partial match' table that helps one determine
# the next location to start substring search
table = list()
table.append(-1)
table.append(0)
while pos < len(word):
if word[pos - 1] == word[cnd]:
cnd = cnd + 1
table.append(cnd)
pos = pos + 1
elif cnd > 0:
cnd = table[cnd]
else:
table.append(0)
pos = pos + 1
return table
def find_subcircuit(circuit, subcircuit, start=0, end=0):
"""Finds the subcircuit in circuit, if it exists.
Explanation
===========
If the subcircuit exists, the index of the start of
the subcircuit in circuit is returned; otherwise,
-1 is returned. The algorithm that is implemented
is the Knuth-Morris-Pratt algorithm.
Parameters
==========
circuit : tuple, Gate or Mul
A tuple of Gates or Mul representing a quantum circuit
subcircuit : tuple, Gate or Mul
A tuple of Gates or Mul to find in circuit
start : int
The location to start looking for subcircuit.
If start is the same or past end, -1 is returned.
end : int
The last place to look for a subcircuit. If end
is less than 1 (one), then the length of circuit
is taken to be end.
Examples
========
Find the first instance of a subcircuit:
>>> from sympy.physics.quantum.circuitutils import find_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)
>>> subcircuit = Z(0)*Y(0)
>>> find_subcircuit(circuit, subcircuit)
1
Find the first instance starting at a specific position:
>>> find_subcircuit(circuit, subcircuit, start=1)
1
>>> find_subcircuit(circuit, subcircuit, start=2)
-1
>>> circuit = circuit*subcircuit
>>> find_subcircuit(circuit, subcircuit, start=2)
4
Find the subcircuit within some interval:
>>> find_subcircuit(circuit, subcircuit, start=2, end=2)
-1
"""
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
return -1
if end < 1:
end = len(circuit)
# Location in circuit
pos = start
# Location in the subcircuit
index = 0
# 'Partial match' table
table = kmp_table(subcircuit)
while (pos + index) < end:
if subcircuit[index] == circuit[pos + index]:
index = index + 1
else:
pos = pos + index - table[index]
index = table[index] if table[index] > -1 else 0
if index == len(subcircuit):
return pos
return -1
def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
"""Replaces a subcircuit with another subcircuit in circuit,
if it exists.
Explanation
===========
If multiple instances of subcircuit exists, the first instance is
replaced. The position to being searching from (if different from
0) may be optionally given. If subcircuit cannot be found, circuit
is returned.
Parameters
==========
circuit : tuple, Gate or Mul
A quantum circuit.
subcircuit : tuple, Gate or Mul
The circuit to be replaced.
replace : tuple, Gate or Mul
The replacement circuit.
pos : int
The location to start search and replace
subcircuit, if it exists. This may be used
if it is known beforehand that multiple
instances exist, and it is desirable to
replace a specific instance. If a negative number
is given, pos will be defaulted to 0.
Examples
========
Find and remove the subcircuit:
>>> from sympy.physics.quantum.circuitutils import replace_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
>>> subcircuit = Z(0)*Y(0)
>>> replace_subcircuit(circuit, subcircuit)
(X(0), H(0), X(0), H(0), Y(0))
Remove the subcircuit given a starting search point:
>>> replace_subcircuit(circuit, subcircuit, pos=1)
(X(0), H(0), X(0), H(0), Y(0))
>>> replace_subcircuit(circuit, subcircuit, pos=2)
(X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
Replace the subcircuit:
>>> replacement = H(0)*Z(0)
>>> replace_subcircuit(circuit, subcircuit, replace=replacement)
(X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
"""
if pos < 0:
pos = 0
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if isinstance(replace, Mul):
replace = replace.args
elif replace is None:
replace = ()
# Look for the subcircuit starting at pos
loc = find_subcircuit(circuit, subcircuit, start=pos)
# If subcircuit was found
if loc > -1:
# Get the gates to the left of subcircuit
left = circuit[0:loc]
# Get the gates to the right of subcircuit
right = circuit[loc + len(subcircuit):len(circuit)]
# Recombine the left and right side gates into a circuit
circuit = left + replace + right
return circuit
def _sympify_qubit_map(mapping):
new_map = {}
for key in mapping:
new_map[key] = sympify(mapping[key])
return new_map
def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
"""Returns the circuit with symbolic indices and the
dictionary mapping symbolic indices to real indices.
The mapping is 1 to 1 and onto (bijective).
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects, or a Mul
start : Symbol
An optional starting symbolic index
gen : object
An optional numbered symbol generator
qubit_map : dict
An existing mapping of symbolic indices to real indices
All symbolic indices have the format 'i#', where # is
some number >= 0.
"""
if isinstance(seq, Mul):
seq = seq.args
# A numbered symbol generator
index_gen = numbered_symbols(prefix='i', start=-1)
cur_ndx = next(index_gen)
# keys are symbolic indices; values are real indices
ndx_map = {}
def create_inverse_map(symb_to_real_map):
rev_items = lambda item: tuple([item[1], item[0]])
return dict(map(rev_items, symb_to_real_map.items()))
if start is not None:
if not isinstance(start, Symbol):
msg = 'Expected Symbol for starting index, got %r.' % start
raise TypeError(msg)
cur_ndx = start
if gen is not None:
if not isinstance(gen, numbered_symbols().__class__):
msg = 'Expected a generator, got %r.' % gen
raise TypeError(msg)
index_gen = gen
if qubit_map is not None:
if not isinstance(qubit_map, dict):
msg = ('Expected dict for existing map, got ' +
'%r.' % qubit_map)
raise TypeError(msg)
ndx_map = qubit_map
ndx_map = _sympify_qubit_map(ndx_map)
# keys are real indices; keys are symbolic indices
inv_map = create_inverse_map(ndx_map)
sym_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
result = convert_to_symbolic_indices(item.args,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif isinstance(item, (tuple, Tuple)):
result = convert_to_symbolic_indices(item,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif item in inv_map:
sym_item = inv_map[item]
else:
cur_ndx = next(gen)
ndx_map[cur_ndx] = item
inv_map[item] = cur_ndx
sym_item = cur_ndx
if isinstance(item, Gate):
sym_item = item.__class__(*sym_item)
sym_seq = sym_seq + (sym_item,)
return sym_seq, ndx_map, cur_ndx, index_gen
def convert_to_real_indices(seq, qubit_map):
"""Returns the circuit with real indices.
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects or a Mul
qubit_map : dict
A dictionary mapping symbolic indices to real indices.
Examples
========
Change the symbolic indices to real integers:
>>> from sympy import symbols
>>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
>>> from sympy.physics.quantum.gate import X, Y, H
>>> i0, i1 = symbols('i:2')
>>> index_map = {i0 : 0, i1 : 1}
>>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
(X(0), Y(1), H(0), X(1))
"""
if isinstance(seq, Mul):
seq = seq.args
if not isinstance(qubit_map, dict):
msg = 'Expected dict for qubit_map, got %r.' % qubit_map
raise TypeError(msg)
qubit_map = _sympify_qubit_map(qubit_map)
real_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
real_item = convert_to_real_indices(item.args, qubit_map)
elif isinstance(item, (tuple, Tuple)):
real_item = convert_to_real_indices(item, qubit_map)
else:
real_item = qubit_map[item]
if isinstance(item, Gate):
real_item = item.__class__(*real_item)
real_seq = real_seq + (real_item,)
return real_seq
def random_reduce(circuit, gate_ids, seed=None):
"""Shorten the length of a quantum circuit.
Explanation
===========
random_reduce looks for circuit identities in circuit, randomly chooses
one to remove, and returns a shorter yet equivalent circuit. If no
identities are found, the same circuit is returned.
Parameters
==========
circuit : Gate tuple of Mul
A tuple of Gates representing a quantum circuit
gate_ids : list, GateIdentity
List of gate identities to find in circuit
seed : int or list
seed used for _randrange; to override the random selection, provide a
list of integers: the elements of gate_ids will be tested in the order
given by the list
"""
from sympy.testing.randtest import _randrange
if not gate_ids:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
ids = flatten_ids(gate_ids)
# Create the random integer generator with the seed
randrange = _randrange(seed)
# Look for an identity in the circuit
while ids:
i = randrange(len(ids))
id = ids.pop(i)
if find_subcircuit(circuit, id) != -1:
break
else:
# no identity was found
return circuit
# return circuit with the identity removed
return replace_subcircuit(circuit, id)
def random_insert(circuit, choices, seed=None):
"""Insert a circuit into another quantum circuit.
Explanation
===========
random_insert randomly chooses a location in the circuit to insert
a randomly selected circuit from amongst the given choices.
Parameters
==========
circuit : Gate tuple or Mul
A tuple or Mul of Gates representing a quantum circuit
choices : list
Set of circuit choices
seed : int or list
seed used for _randrange; to override the random selections, give
a list two integers, [i, j] where i is the circuit location where
choice[j] will be inserted.
Notes
=====
Indices for insertion should be [0, n] if n is the length of the
circuit.
"""
from sympy.testing.randtest import _randrange
if not choices:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
# get the location in the circuit and the element to insert from choices
randrange = _randrange(seed)
loc = randrange(len(circuit) + 1)
choice = choices[randrange(len(choices))]
circuit = list(circuit)
circuit[loc: loc] = choice
return tuple(circuit)
# Flatten the GateIdentity objects (with gate rules) into one single list
def flatten_ids(ids):
collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
key=default_sort_key)
ids = reduce(collapse, ids, [])
ids.sort(key=default_sort_key)
return ids
|
b95af75491eb2b396d7180bbc24b8cc6ba7e50346569128af36aa576f8c16d93 | """Hilbert spaces for quantum mechanics.
Authors:
* Brian Granger
* Matt Curry
"""
from functools import reduce
from sympy.core.basic import Basic
from sympy.core.numbers import oo
from sympy.core.sympify import sympify
from sympy.sets.sets import Interval
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError
__all__ = [
'HilbertSpaceError',
'HilbertSpace',
'TensorProductHilbertSpace',
'TensorPowerHilbertSpace',
'DirectSumHilbertSpace',
'ComplexSpace',
'L2',
'FockSpace'
]
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpaceError(QuantumError):
pass
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpace(Basic):
"""An abstract Hilbert space for quantum mechanics.
In short, a Hilbert space is an abstract vector space that is complete
with inner products defined [1]_.
Examples
========
>>> from sympy.physics.quantum.hilbert import HilbertSpace
>>> hs = HilbertSpace()
>>> hs
H
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
"""Return the Hilbert dimension of the space."""
raise NotImplementedError('This Hilbert space has no dimension.')
def __add__(self, other):
return DirectSumHilbertSpace(self, other)
def __radd__(self, other):
return DirectSumHilbertSpace(other, self)
def __mul__(self, other):
return TensorProductHilbertSpace(self, other)
def __rmul__(self, other):
return TensorProductHilbertSpace(other, self)
def __pow__(self, other, mod=None):
if mod is not None:
raise ValueError('The third argument to __pow__ is not supported \
for Hilbert spaces.')
return TensorPowerHilbertSpace(self, other)
def __contains__(self, other):
"""Is the operator or state in this Hilbert space.
This is checked by comparing the classes of the Hilbert spaces, not
the instances. This is to allow Hilbert Spaces with symbolic
dimensions.
"""
if other.hilbert_space.__class__ == self.__class__:
return True
else:
return False
def _sympystr(self, printer, *args):
return 'H'
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER H}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{H}'
class ComplexSpace(HilbertSpace):
"""Finite dimensional Hilbert space of complex vectors.
The elements of this Hilbert space are n-dimensional complex valued
vectors with the usual inner product that takes the complex conjugate
of the vector on the right.
A classic example of this type of Hilbert space is spin-1/2, which is
``ComplexSpace(2)``. Generalizing to spin-s, the space is
``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
direct product space ``ComplexSpace(2)**N``.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.quantum.hilbert import ComplexSpace
>>> c1 = ComplexSpace(2)
>>> c1
C(2)
>>> c1.dimension
2
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> c2
C(n)
>>> c2.dimension
n
"""
def __new__(cls, dimension):
dimension = sympify(dimension)
r = cls.eval(dimension)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, dimension)
return obj
@classmethod
def eval(cls, dimension):
if len(dimension.atoms()) == 1:
if not (dimension.is_Integer and dimension > 0 or dimension is oo
or dimension.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
'be a positive integer, oo, or a Symbol: %r'
% dimension)
else:
for dim in dimension.atoms():
if not (dim.is_Integer or dim is oo or dim.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
' contain integers, oo, or a Symbol: %r'
% dim)
@property
def dimension(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "%s(%s)" % (self.__class__.__name__,
printer._print(self.dimension, *args))
def _sympystr(self, printer, *args):
return "C(%s)" % printer._print(self.dimension, *args)
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER C}'
pform_exp = printer._print(self.dimension, *args)
pform_base = prettyForm(ustr)
return pform_base**pform_exp
def _latex(self, printer, *args):
return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
class L2(HilbertSpace):
"""The Hilbert space of square integrable functions on an interval.
An L2 object takes in a single SymPy Interval argument which represents
the interval its functions (vectors) are defined on.
Examples
========
>>> from sympy import Interval, oo
>>> from sympy.physics.quantum.hilbert import L2
>>> hs = L2(Interval(0,oo))
>>> hs
L2(Interval(0, oo))
>>> hs.dimension
oo
>>> hs.interval
Interval(0, oo)
"""
def __new__(cls, interval):
if not isinstance(interval, Interval):
raise TypeError('L2 interval must be an Interval instance: %r'
% interval)
obj = Basic.__new__(cls, interval)
return obj
@property
def dimension(self):
return oo
@property
def interval(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _sympystr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _pretty(self, printer, *args):
pform_exp = prettyForm('2')
pform_base = prettyForm('L')
return pform_base**pform_exp
def _latex(self, printer, *args):
interval = printer._print(self.interval, *args)
return r'{\mathcal{L}^2}\left( %s \right)' % interval
class FockSpace(HilbertSpace):
"""The Hilbert space for second quantization.
Technically, this Hilbert space is a infinite direct sum of direct
products of single particle Hilbert spaces [1]_. This is a mess, so we have
a class to represent it directly.
Examples
========
>>> from sympy.physics.quantum.hilbert import FockSpace
>>> hs = FockSpace()
>>> hs
F
>>> hs.dimension
oo
References
==========
.. [1] https://en.wikipedia.org/wiki/Fock_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
return oo
def _sympyrepr(self, printer, *args):
return "FockSpace()"
def _sympystr(self, printer, *args):
return "F"
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER F}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{F}'
class TensorProductHilbertSpace(HilbertSpace):
"""A tensor product of Hilbert spaces [1]_.
The tensor product between Hilbert spaces is represented by the
operator ``*`` Products of the same Hilbert space will be combined into
tensor powers.
A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. In addition, multiplication of
``HilbertSpace`` objects will automatically return this tensor product
object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c*f
>>> hs
C(2)*F
>>> hs.dimension
oo
>>> hs.spaces
(C(2), F)
>>> c1 = ComplexSpace(2)
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> hs = c1*c2
>>> hs
C(2)*C(n)
>>> hs.dimension
2*n
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, TensorProductHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be multiplied by \
other Hilbert spaces: %r' % arg)
#combine like arguments into direct powers
comb_args = []
prev_arg = None
for new_arg in new_args:
if prev_arg is not None:
if isinstance(new_arg, TensorPowerHilbertSpace) and \
isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg.base:
prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
elif isinstance(new_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg:
prev_arg = prev_arg**(new_arg.exp + 1)
elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg == prev_arg.base:
prev_arg = new_arg**(prev_arg.exp + 1)
elif new_arg == prev_arg:
prev_arg = new_arg**2
else:
comb_args.append(prev_arg)
prev_arg = new_arg
elif prev_arg is None:
prev_arg = new_arg
comb_args.append(prev_arg)
if recall:
return TensorProductHilbertSpace(*comb_args)
elif len(comb_args) == 1:
return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if oo in arg_list:
return oo
else:
return reduce(lambda x, y: x*y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this tensor product."""
return self.args
def _spaces_printer(self, printer, *args):
spaces_strs = []
for arg in self.args:
s = printer._print(arg, *args)
if isinstance(arg, DirectSumHilbertSpace):
s = '(%s)' % s
spaces_strs.append(s)
return spaces_strs
def _sympyrepr(self, printer, *args):
spaces_reprs = self._spaces_printer(printer, *args)
return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = self._spaces_printer(printer, *args)
return '*'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
else:
pform = prettyForm(*pform.right(' x '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\otimes '
return s
class DirectSumHilbertSpace(HilbertSpace):
"""A direct sum of Hilbert spaces [1]_.
This class uses the ``+`` operator to represent direct sums between
different Hilbert spaces.
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. Also, addition of
``HilbertSpace`` objects will automatically return a direct sum object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c+f
>>> hs
C(2)+F
>>> hs.dimension
oo
>>> list(hs.spaces)
[C(2), F]
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, DirectSumHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, HilbertSpace):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be summed with other \
Hilbert spaces: %r' % arg)
if recall:
return DirectSumHilbertSpace(*new_args)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if oo in arg_list:
return oo
else:
return reduce(lambda x, y: x + y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this direct sum."""
return self.args
def _sympyrepr(self, printer, *args):
spaces_reprs = [printer._print(arg, *args) for arg in self.args]
return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = [printer._print(arg, *args) for arg in self.args]
return '+'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
else:
pform = prettyForm(*pform.right(' + '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\oplus '
return s
class TensorPowerHilbertSpace(HilbertSpace):
"""An exponentiated Hilbert space [1]_.
Tensor powers (repeated tensor products) are represented by the
operator ``**`` Identical Hilbert spaces that are multiplied together
will be automatically combined into a single tensor power object.
Any Hilbert space, product, or sum may be raised to a tensor power. The
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
tensor power (number).
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> n = symbols('n')
>>> c = ComplexSpace(2)
>>> hs = c**n
>>> hs
C(2)**n
>>> hs.dimension
2**n
>>> c = ComplexSpace(2)
>>> c*c
C(2)**2
>>> f = FockSpace()
>>> c*f*f
C(2)*F**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
return Basic.__new__(cls, *r)
@classmethod
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp == 1:
return args[0]
#simplify hs**0 -> 1
if exp == 0:
return sympify(1)
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def dimension(self):
if self.base.dimension is oo:
return oo
else:
return self.base.dimension**self.exp
def _sympyrepr(self, printer, *args):
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
*args), printer._print(self.exp, *args))
def _sympystr(self, printer, *args):
return "%s**%s" % (printer._print(self.base, *args),
printer._print(self.exp, *args))
def _pretty(self, printer, *args):
pform_exp = printer._print(self.exp, *args)
if printer._use_unicode:
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
else:
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
pform_base = printer._print(self.base, *args)
return pform_base**pform_exp
def _latex(self, printer, *args):
base = printer._print(self.base, *args)
exp = printer._print(self.exp, *args)
return r'{%s}^{\otimes %s}' % (base, exp)
|
79586cf5c897a2e3836ff9c992c195861170cbdb5fc18858a29e5dd3897930da | """Bosonic quantum operators."""
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum import Operator
from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator
from sympy.functions.special.tensor_functions import KroneckerDelta
__all__ = [
'BosonOp',
'BosonFockKet',
'BosonFockBra',
'BosonCoherentKet',
'BosonCoherentBra'
]
class BosonOp(Operator):
"""A bosonic operator that satisfies [a, Dagger(a)] == 1.
Parameters
==========
name : str
A string that labels the bosonic mode.
annihilation : bool
A bool that indicates if the bosonic operator is an annihilation (True,
default value) or creation operator (False)
Examples
========
>>> from sympy.physics.quantum import Dagger, Commutator
>>> from sympy.physics.quantum.boson import BosonOp
>>> a = BosonOp("a")
>>> Commutator(a, Dagger(a)).doit()
1
"""
@property
def name(self):
return self.args[0]
@property
def is_annihilation(self):
return bool(self.args[1])
@classmethod
def default_args(self):
return ("a", True)
def __new__(cls, *args, **hints):
if not len(args) in [1, 2]:
raise ValueError('1 or 2 parameters expected, got %s' % args)
if len(args) == 1:
args = (args[0], S.One)
if len(args) == 2:
args = (args[0], Integer(args[1]))
return Operator.__new__(cls, *args)
def _eval_commutator_BosonOp(self, other, **hints):
if self.name == other.name:
# [a^\dagger, a] = -1
if not self.is_annihilation and other.is_annihilation:
return S.NegativeOne
elif 'independent' in hints and hints['independent']:
# [a, b] = 0
return S.Zero
return None
def _eval_commutator_FermionOp(self, other, **hints):
return S.Zero
def _eval_anticommutator_BosonOp(self, other, **hints):
if 'independent' in hints and hints['independent']:
# {a, b} = 2 * a * b, because [a, b] = 0
return 2 * self * other
return None
def _eval_adjoint(self):
return BosonOp(str(self.name), not self.is_annihilation)
def __mul__(self, other):
if other == IdentityOperator(2):
return self
if isinstance(other, Mul):
args1 = tuple(arg for arg in other.args if arg.is_commutative)
args2 = tuple(arg for arg in other.args if not arg.is_commutative)
x = self
for y in args2:
x = x * y
return Mul(*args1) * x
return Mul(self, other)
def _print_contents_latex(self, printer, *args):
if self.is_annihilation:
return r'{%s}' % str(self.name)
else:
return r'{{%s}^\dagger}' % str(self.name)
def _print_contents(self, printer, *args):
if self.is_annihilation:
return r'%s' % str(self.name)
else:
return r'Dagger(%s)' % str(self.name)
def _print_contents_pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
if self.is_annihilation:
return pform
else:
return pform**prettyForm('\N{DAGGER}')
class BosonFockKet(Ket):
"""Fock state ket for a bosonic mode.
Parameters
==========
n : Number
The Fock state number.
"""
def __new__(cls, n):
return Ket.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return BosonFockBra
@classmethod
def _eval_hilbert_space(cls, label):
return FockSpace()
def _eval_innerproduct_BosonFockBra(self, bra, **hints):
return KroneckerDelta(self.n, bra.n)
def _apply_operator_BosonOp(self, op, **options):
if op.is_annihilation:
return sqrt(self.n) * BosonFockKet(self.n - 1)
else:
return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
class BosonFockBra(Bra):
"""Fock state bra for a bosonic mode.
Parameters
==========
n : Number
The Fock state number.
"""
def __new__(cls, n):
return Bra.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return BosonFockKet
@classmethod
def _eval_hilbert_space(cls, label):
return FockSpace()
class BosonCoherentKet(Ket):
"""Coherent state ket for a bosonic mode.
Parameters
==========
alpha : Number, Symbol
The complex amplitude of the coherent state.
"""
def __new__(cls, alpha):
return Ket.__new__(cls, alpha)
@property
def alpha(self):
return self.label[0]
@classmethod
def dual_class(self):
return BosonCoherentBra
@classmethod
def _eval_hilbert_space(cls, label):
return HilbertSpace()
def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
if self.alpha == bra.alpha:
return S.One
else:
return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
def _apply_operator_BosonOp(self, op, **options):
if op.is_annihilation:
return self.alpha * self
else:
return None
class BosonCoherentBra(Bra):
"""Coherent state bra for a bosonic mode.
Parameters
==========
alpha : Number, Symbol
The complex amplitude of the coherent state.
"""
def __new__(cls, alpha):
return Bra.__new__(cls, alpha)
@property
def alpha(self):
return self.label[0]
@classmethod
def dual_class(self):
return BosonCoherentKet
def _apply_operator_BosonOp(self, op, **options):
if not op.is_annihilation:
return self.alpha * self
else:
return None
|
10b0a5d536f12e7367c41cc282f4c40840d8e0e107925f5b4f1a0ea488bf1ae5 | """Pauli operators and states"""
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import I
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp
from sympy.physics.quantum import Operator, Ket, Bra
from sympy.physics.quantum import ComplexSpace
from sympy.matrices import Matrix
from sympy.functions.special.tensor_functions import KroneckerDelta
__all__ = [
'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'SigmaPlus', 'SigmaZKet',
'SigmaZBra', 'qsimplify_pauli'
]
class SigmaOpBase(Operator):
"""Pauli sigma operator, base class"""
@property
def name(self):
return self.args[0]
@property
def use_name(self):
return bool(self.args[0]) is not False
@classmethod
def default_args(self):
return (False,)
def __new__(cls, *args, **hints):
return Operator.__new__(cls, *args, **hints)
def _eval_commutator_BosonOp(self, other, **hints):
return S.Zero
class SigmaX(SigmaOpBase):
"""Pauli sigma x operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent
>>> from sympy.physics.quantum.pauli import SigmaX
>>> sx = SigmaX()
>>> sx
SigmaX()
>>> represent(sx)
Matrix([
[0, 1],
[1, 0]])
"""
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args, **hints)
def _eval_commutator_SigmaY(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return 2 * I * SigmaZ(self.name)
def _eval_commutator_SigmaZ(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return - 2 * I * SigmaY(self.name)
def _eval_commutator_BosonOp(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaY(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaZ(self, other, **hints):
return S.Zero
def _eval_adjoint(self):
return self
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_x^{(%s)}}' % str(self.name)
else:
return r'{\sigma_x}'
def _print_contents(self, printer, *args):
return 'SigmaX()'
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return SigmaX(self.name).__pow__(int(e) % 2)
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[0, 1], [1, 0]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaY(SigmaOpBase):
"""Pauli sigma y operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent
>>> from sympy.physics.quantum.pauli import SigmaY
>>> sy = SigmaY()
>>> sy
SigmaY()
>>> represent(sy)
Matrix([
[0, -I],
[I, 0]])
"""
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args)
def _eval_commutator_SigmaZ(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return 2 * I * SigmaX(self.name)
def _eval_commutator_SigmaX(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return - 2 * I * SigmaZ(self.name)
def _eval_anticommutator_SigmaX(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaZ(self, other, **hints):
return S.Zero
def _eval_adjoint(self):
return self
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_y^{(%s)}}' % str(self.name)
else:
return r'{\sigma_y}'
def _print_contents(self, printer, *args):
return 'SigmaY()'
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return SigmaY(self.name).__pow__(int(e) % 2)
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[0, -I], [I, 0]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaZ(SigmaOpBase):
"""Pauli sigma z operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent
>>> from sympy.physics.quantum.pauli import SigmaZ
>>> sz = SigmaZ()
>>> sz ** 3
SigmaZ()
>>> represent(sz)
Matrix([
[1, 0],
[0, -1]])
"""
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args)
def _eval_commutator_SigmaX(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return 2 * I * SigmaY(self.name)
def _eval_commutator_SigmaY(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return - 2 * I * SigmaX(self.name)
def _eval_anticommutator_SigmaX(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaY(self, other, **hints):
return S.Zero
def _eval_adjoint(self):
return self
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_z^{(%s)}}' % str(self.name)
else:
return r'{\sigma_z}'
def _print_contents(self, printer, *args):
return 'SigmaZ()'
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return SigmaZ(self.name).__pow__(int(e) % 2)
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[1, 0], [0, -1]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaMinus(SigmaOpBase):
"""Pauli sigma minus operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent, Dagger
>>> from sympy.physics.quantum.pauli import SigmaMinus
>>> sm = SigmaMinus()
>>> sm
SigmaMinus()
>>> Dagger(sm)
SigmaPlus()
>>> represent(sm)
Matrix([
[0, 0],
[1, 0]])
"""
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args)
def _eval_commutator_SigmaX(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return -SigmaZ(self.name)
def _eval_commutator_SigmaY(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return I * SigmaZ(self.name)
def _eval_commutator_SigmaZ(self, other, **hints):
return 2 * self
def _eval_commutator_SigmaMinus(self, other, **hints):
return SigmaZ(self.name)
def _eval_anticommutator_SigmaZ(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaX(self, other, **hints):
return S.One
def _eval_anticommutator_SigmaY(self, other, **hints):
return I * S.NegativeOne
def _eval_anticommutator_SigmaPlus(self, other, **hints):
return S.One
def _eval_adjoint(self):
return SigmaPlus(self.name)
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return S.Zero
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_-^{(%s)}}' % str(self.name)
else:
return r'{\sigma_-}'
def _print_contents(self, printer, *args):
return 'SigmaMinus()'
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[0, 0], [1, 0]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaPlus(SigmaOpBase):
"""Pauli sigma plus operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent, Dagger
>>> from sympy.physics.quantum.pauli import SigmaPlus
>>> sp = SigmaPlus()
>>> sp
SigmaPlus()
>>> Dagger(sp)
SigmaMinus()
>>> represent(sp)
Matrix([
[0, 1],
[0, 0]])
"""
def __new__(cls, *args, **hints):
return SigmaOpBase.__new__(cls, *args)
def _eval_commutator_SigmaX(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return SigmaZ(self.name)
def _eval_commutator_SigmaY(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return I * SigmaZ(self.name)
def _eval_commutator_SigmaZ(self, other, **hints):
if self.name != other.name:
return S.Zero
else:
return -2 * self
def _eval_commutator_SigmaMinus(self, other, **hints):
return SigmaZ(self.name)
def _eval_anticommutator_SigmaZ(self, other, **hints):
return S.Zero
def _eval_anticommutator_SigmaX(self, other, **hints):
return S.One
def _eval_anticommutator_SigmaY(self, other, **hints):
return I
def _eval_anticommutator_SigmaMinus(self, other, **hints):
return S.One
def _eval_adjoint(self):
return SigmaMinus(self.name)
def _eval_mul(self, other):
return self * other
def _eval_power(self, e):
if e.is_Integer and e.is_positive:
return S.Zero
def _print_contents_latex(self, printer, *args):
if self.use_name:
return r'{\sigma_+^{(%s)}}' % str(self.name)
else:
return r'{\sigma_+}'
def _print_contents(self, printer, *args):
return 'SigmaPlus()'
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[0, 1], [0, 0]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaZKet(Ket):
"""Ket for a two-level system quantum system.
Parameters
==========
n : Number
The state number (0 or 1).
"""
def __new__(cls, n):
if n not in (0, 1):
raise ValueError("n must be 0 or 1")
return Ket.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return SigmaZBra
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(2)
def _eval_innerproduct_SigmaZBra(self, bra, **hints):
return KroneckerDelta(self.n, bra.n)
def _apply_operator_SigmaZ(self, op, **options):
if self.n == 0:
return self
else:
return S.NegativeOne * self
def _apply_operator_SigmaX(self, op, **options):
return SigmaZKet(1) if self.n == 0 else SigmaZKet(0)
def _apply_operator_SigmaY(self, op, **options):
return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0)
def _apply_operator_SigmaMinus(self, op, **options):
if self.n == 0:
return SigmaZKet(1)
else:
return S.Zero
def _apply_operator_SigmaPlus(self, op, **options):
if self.n == 0:
return S.Zero
else:
return SigmaZKet(0)
def _represent_default_basis(self, **options):
format = options.get('format', 'sympy')
if format == 'sympy':
return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]])
else:
raise NotImplementedError('Representation in format ' +
format + ' not implemented.')
class SigmaZBra(Bra):
"""Bra for a two-level quantum system.
Parameters
==========
n : Number
The state number (0 or 1).
"""
def __new__(cls, n):
if n not in (0, 1):
raise ValueError("n must be 0 or 1")
return Bra.__new__(cls, n)
@property
def n(self):
return self.label[0]
@classmethod
def dual_class(self):
return SigmaZKet
def _qsimplify_pauli_product(a, b):
"""
Internal helper function for simplifying products of Pauli operators.
"""
if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)):
return Mul(a, b)
if a.name != b.name:
# Pauli matrices with different labels commute; sort by name
if a.name < b.name:
return Mul(a, b)
else:
return Mul(b, a)
elif isinstance(a, SigmaX):
if isinstance(b, SigmaX):
return S.One
if isinstance(b, SigmaY):
return I * SigmaZ(a.name)
if isinstance(b, SigmaZ):
return - I * SigmaY(a.name)
if isinstance(b, SigmaMinus):
return (S.Half + SigmaZ(a.name)/2)
if isinstance(b, SigmaPlus):
return (S.Half - SigmaZ(a.name)/2)
elif isinstance(a, SigmaY):
if isinstance(b, SigmaX):
return - I * SigmaZ(a.name)
if isinstance(b, SigmaY):
return S.One
if isinstance(b, SigmaZ):
return I * SigmaX(a.name)
if isinstance(b, SigmaMinus):
return -I * (S.One + SigmaZ(a.name))/2
if isinstance(b, SigmaPlus):
return I * (S.One - SigmaZ(a.name))/2
elif isinstance(a, SigmaZ):
if isinstance(b, SigmaX):
return I * SigmaY(a.name)
if isinstance(b, SigmaY):
return - I * SigmaX(a.name)
if isinstance(b, SigmaZ):
return S.One
if isinstance(b, SigmaMinus):
return - SigmaMinus(a.name)
if isinstance(b, SigmaPlus):
return SigmaPlus(a.name)
elif isinstance(a, SigmaMinus):
if isinstance(b, SigmaX):
return (S.One - SigmaZ(a.name))/2
if isinstance(b, SigmaY):
return - I * (S.One - SigmaZ(a.name))/2
if isinstance(b, SigmaZ):
# (SigmaX(a.name) - I * SigmaY(a.name))/2
return SigmaMinus(b.name)
if isinstance(b, SigmaMinus):
return S.Zero
if isinstance(b, SigmaPlus):
return S.Half - SigmaZ(a.name)/2
elif isinstance(a, SigmaPlus):
if isinstance(b, SigmaX):
return (S.One + SigmaZ(a.name))/2
if isinstance(b, SigmaY):
return I * (S.One + SigmaZ(a.name))/2
if isinstance(b, SigmaZ):
#-(SigmaX(a.name) + I * SigmaY(a.name))/2
return -SigmaPlus(a.name)
if isinstance(b, SigmaMinus):
return (S.One + SigmaZ(a.name))/2
if isinstance(b, SigmaPlus):
return S.Zero
else:
return a * b
def qsimplify_pauli(e):
"""
Simplify an expression that includes products of pauli operators.
Parameters
==========
e : expression
An expression that contains products of Pauli operators that is
to be simplified.
Examples
========
>>> from sympy.physics.quantum.pauli import SigmaX, SigmaY
>>> from sympy.physics.quantum.pauli import qsimplify_pauli
>>> sx, sy = SigmaX(), SigmaY()
>>> sx * sy
SigmaX()*SigmaY()
>>> qsimplify_pauli(sx * sy)
I*SigmaZ()
"""
if isinstance(e, Operator):
return e
if isinstance(e, (Add, Pow, exp)):
t = type(e)
return t(*(qsimplify_pauli(arg) for arg in e.args))
if isinstance(e, Mul):
c, nc = e.args_cnc()
nc_s = []
while nc:
curr = nc.pop(0)
while (len(nc) and
isinstance(curr, SigmaOpBase) and
isinstance(nc[0], SigmaOpBase) and
curr.name == nc[0].name):
x = nc.pop(0)
y = _qsimplify_pauli_product(curr, x)
c1, nc1 = y.args_cnc()
curr = Mul(*nc1)
c = c + c1
nc_s.append(curr)
return Mul(*c) * Mul(*nc_s)
return e
|
5862ba0be3350d219db30ae11990c8c2afa2f15ef9e9c90da0e1ddd66cc9624e | """Simple Harmonic Oscillator 1-Dimension"""
from sympy.core.numbers import (I, Integer)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.state import Bra, Ket, State
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.cartesian import X, Px
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.matrixutils import matrix_zeros
#------------------------------------------------------------------------------
class SHOOp(Operator):
"""A base class for the SHO Operators.
We are limiting the number of arguments to be 1.
"""
@classmethod
def _eval_args(cls, args):
args = QExpr._eval_args(args)
if len(args) == 1:
return args
else:
raise ValueError("Too many arguments")
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(S.Infinity)
class RaisingOp(SHOOp):
"""The Raising Operator or a^dagger.
When a^dagger acts on a state it raises the state up by one. Taking
the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger
can be rewritten in terms of position and momentum. We can represent
a^dagger as a matrix, which will be its default basis.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator.
Examples
========
Create a Raising Operator and rewrite it in terms of position and
momentum, and show that taking its adjoint returns 'a':
>>> from sympy.physics.quantum.sho1d import RaisingOp
>>> from sympy.physics.quantum import Dagger
>>> ad = RaisingOp('a')
>>> ad.rewrite('xp').doit()
sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
>>> Dagger(ad)
a
Taking the commutator of a^dagger with other Operators:
>>> from sympy.physics.quantum import Commutator
>>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
>>> from sympy.physics.quantum.sho1d import NumberOp
>>> ad = RaisingOp('a')
>>> a = LoweringOp('a')
>>> N = NumberOp('N')
>>> Commutator(ad, a).doit()
-1
>>> Commutator(ad, N).doit()
-RaisingOp(a)
Apply a^dagger to a state:
>>> from sympy.physics.quantum import qapply
>>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet
>>> ad = RaisingOp('a')
>>> k = SHOKet('k')
>>> qapply(ad*k)
sqrt(k + 1)*|k + 1>
Matrix Representation
>>> from sympy.physics.quantum.sho1d import RaisingOp
>>> from sympy.physics.quantum.represent import represent
>>> ad = RaisingOp('a')
>>> represent(ad, basis=N, ndim=4, format='sympy')
Matrix([
[0, 0, 0, 0],
[1, 0, 0, 0],
[0, sqrt(2), 0, 0],
[0, 0, sqrt(3), 0]])
"""
def _eval_rewrite_as_xp(self, *args, **kwargs):
return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
S.NegativeOne*I*Px + m*omega*X)
def _eval_adjoint(self):
return LoweringOp(*self.args)
def _eval_commutator_LoweringOp(self, other):
return S.NegativeOne
def _eval_commutator_NumberOp(self, other):
return S.NegativeOne*self
def _apply_operator_SHOKet(self, ket):
temp = ket.n + S.One
return sqrt(temp)*SHOKet(temp)
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_XOp(self, basis, **options):
# This logic is good but the underlying position
# representation logic is broken.
# temp = self.rewrite('xp').doit()
# result = represent(temp, basis=X)
# return result
raise NotImplementedError('Position representation is not implemented')
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format','sympy')
matrix = matrix_zeros(ndim_info, ndim_info, **options)
for i in range(ndim_info - 1):
value = sqrt(i + 1)
if format == 'scipy.sparse':
value = float(value)
matrix[i + 1, i] = value
if format == 'scipy.sparse':
matrix = matrix.tocsr()
return matrix
#--------------------------------------------------------------------------
# Printing Methods
#--------------------------------------------------------------------------
def _print_contents(self, printer, *args):
arg0 = printer._print(self.args[0], *args)
return '%s(%s)' % (self.__class__.__name__, arg0)
def _print_contents_pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
pform = pform**prettyForm('\N{DAGGER}')
return pform
def _print_contents_latex(self, printer, *args):
arg = printer._print(self.args[0])
return '%s^{\\dagger}' % arg
class LoweringOp(SHOOp):
"""The Lowering Operator or 'a'.
When 'a' acts on a state it lowers the state up by one. Taking
the adjoint of 'a' returns a^dagger, the Raising Operator. 'a'
can be rewritten in terms of position and momentum. We can
represent 'a' as a matrix, which will be its default basis.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator.
Examples
========
Create a Lowering Operator and rewrite it in terms of position and
momentum, and show that taking its adjoint returns a^dagger:
>>> from sympy.physics.quantum.sho1d import LoweringOp
>>> from sympy.physics.quantum import Dagger
>>> a = LoweringOp('a')
>>> a.rewrite('xp').doit()
sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
>>> Dagger(a)
RaisingOp(a)
Taking the commutator of 'a' with other Operators:
>>> from sympy.physics.quantum import Commutator
>>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp
>>> from sympy.physics.quantum.sho1d import NumberOp
>>> a = LoweringOp('a')
>>> ad = RaisingOp('a')
>>> N = NumberOp('N')
>>> Commutator(a, ad).doit()
1
>>> Commutator(a, N).doit()
a
Apply 'a' to a state:
>>> from sympy.physics.quantum import qapply
>>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
>>> a = LoweringOp('a')
>>> k = SHOKet('k')
>>> qapply(a*k)
sqrt(k)*|k - 1>
Taking 'a' of the lowest state will return 0:
>>> from sympy.physics.quantum import qapply
>>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
>>> a = LoweringOp('a')
>>> k = SHOKet(0)
>>> qapply(a*k)
0
Matrix Representation
>>> from sympy.physics.quantum.sho1d import LoweringOp
>>> from sympy.physics.quantum.represent import represent
>>> a = LoweringOp('a')
>>> represent(a, basis=N, ndim=4, format='sympy')
Matrix([
[0, 1, 0, 0],
[0, 0, sqrt(2), 0],
[0, 0, 0, sqrt(3)],
[0, 0, 0, 0]])
"""
def _eval_rewrite_as_xp(self, *args, **kwargs):
return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
I*Px + m*omega*X)
def _eval_adjoint(self):
return RaisingOp(*self.args)
def _eval_commutator_RaisingOp(self, other):
return S.One
def _eval_commutator_NumberOp(self, other):
return self
def _apply_operator_SHOKet(self, ket):
temp = ket.n - Integer(1)
if ket.n is S.Zero:
return S.Zero
else:
return sqrt(ket.n)*SHOKet(temp)
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_XOp(self, basis, **options):
# This logic is good but the underlying position
# representation logic is broken.
# temp = self.rewrite('xp').doit()
# result = represent(temp, basis=X)
# return result
raise NotImplementedError('Position representation is not implemented')
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format', 'sympy')
matrix = matrix_zeros(ndim_info, ndim_info, **options)
for i in range(ndim_info - 1):
value = sqrt(i + 1)
if format == 'scipy.sparse':
value = float(value)
matrix[i,i + 1] = value
if format == 'scipy.sparse':
matrix = matrix.tocsr()
return matrix
class NumberOp(SHOOp):
"""The Number Operator is simply a^dagger*a
It is often useful to write a^dagger*a as simply the Number Operator
because the Number Operator commutes with the Hamiltonian. And can be
expressed using the Number Operator. Also the Number Operator can be
applied to states. We can represent the Number Operator as a matrix,
which will be its default basis.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator.
Examples
========
Create a Number Operator and rewrite it in terms of the ladder
operators, position and momentum operators, and Hamiltonian:
>>> from sympy.physics.quantum.sho1d import NumberOp
>>> N = NumberOp('N')
>>> N.rewrite('a').doit()
RaisingOp(a)*a
>>> N.rewrite('xp').doit()
-1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega)
>>> N.rewrite('H').doit()
-1/2 + H/(hbar*omega)
Take the Commutator of the Number Operator with other Operators:
>>> from sympy.physics.quantum import Commutator
>>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian
>>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
>>> N = NumberOp('N')
>>> H = Hamiltonian('H')
>>> ad = RaisingOp('a')
>>> a = LoweringOp('a')
>>> Commutator(N,H).doit()
0
>>> Commutator(N,ad).doit()
RaisingOp(a)
>>> Commutator(N,a).doit()
-a
Apply the Number Operator to a state:
>>> from sympy.physics.quantum import qapply
>>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet
>>> N = NumberOp('N')
>>> k = SHOKet('k')
>>> qapply(N*k)
k*|k>
Matrix Representation
>>> from sympy.physics.quantum.sho1d import NumberOp
>>> from sympy.physics.quantum.represent import represent
>>> N = NumberOp('N')
>>> represent(N, basis=N, ndim=4, format='sympy')
Matrix([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 2, 0],
[0, 0, 0, 3]])
"""
def _eval_rewrite_as_a(self, *args, **kwargs):
return ad*a
def _eval_rewrite_as_xp(self, *args, **kwargs):
return (S.One/(Integer(2)*m*hbar*omega))*(Px**2 + (
m*omega*X)**2) - S.Half
def _eval_rewrite_as_H(self, *args, **kwargs):
return H/(hbar*omega) - S.Half
def _apply_operator_SHOKet(self, ket):
return ket.n*ket
def _eval_commutator_Hamiltonian(self, other):
return S.Zero
def _eval_commutator_RaisingOp(self, other):
return other
def _eval_commutator_LoweringOp(self, other):
return S.NegativeOne*other
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_XOp(self, basis, **options):
# This logic is good but the underlying position
# representation logic is broken.
# temp = self.rewrite('xp').doit()
# result = represent(temp, basis=X)
# return result
raise NotImplementedError('Position representation is not implemented')
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format', 'sympy')
matrix = matrix_zeros(ndim_info, ndim_info, **options)
for i in range(ndim_info):
value = i
if format == 'scipy.sparse':
value = float(value)
matrix[i,i] = value
if format == 'scipy.sparse':
matrix = matrix.tocsr()
return matrix
class Hamiltonian(SHOOp):
"""The Hamiltonian Operator.
The Hamiltonian is used to solve the time-independent Schrodinger
equation. The Hamiltonian can be expressed using the ladder operators,
as well as by position and momentum. We can represent the Hamiltonian
Operator as a matrix, which will be its default basis.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
operator.
Examples
========
Create a Hamiltonian Operator and rewrite it in terms of the ladder
operators, position and momentum, and the Number Operator:
>>> from sympy.physics.quantum.sho1d import Hamiltonian
>>> H = Hamiltonian('H')
>>> H.rewrite('a').doit()
hbar*omega*(1/2 + RaisingOp(a)*a)
>>> H.rewrite('xp').doit()
(m**2*omega**2*X**2 + Px**2)/(2*m)
>>> H.rewrite('N').doit()
hbar*omega*(1/2 + N)
Take the Commutator of the Hamiltonian and the Number Operator:
>>> from sympy.physics.quantum import Commutator
>>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp
>>> H = Hamiltonian('H')
>>> N = NumberOp('N')
>>> Commutator(H,N).doit()
0
Apply the Hamiltonian Operator to a state:
>>> from sympy.physics.quantum import qapply
>>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet
>>> H = Hamiltonian('H')
>>> k = SHOKet('k')
>>> qapply(H*k)
hbar*k*omega*|k> + hbar*omega*|k>/2
Matrix Representation
>>> from sympy.physics.quantum.sho1d import Hamiltonian
>>> from sympy.physics.quantum.represent import represent
>>> H = Hamiltonian('H')
>>> represent(H, basis=N, ndim=4, format='sympy')
Matrix([
[hbar*omega/2, 0, 0, 0],
[ 0, 3*hbar*omega/2, 0, 0],
[ 0, 0, 5*hbar*omega/2, 0],
[ 0, 0, 0, 7*hbar*omega/2]])
"""
def _eval_rewrite_as_a(self, *args, **kwargs):
return hbar*omega*(ad*a + S.Half)
def _eval_rewrite_as_xp(self, *args, **kwargs):
return (S.One/(Integer(2)*m))*(Px**2 + (m*omega*X)**2)
def _eval_rewrite_as_N(self, *args, **kwargs):
return hbar*omega*(N + S.Half)
def _apply_operator_SHOKet(self, ket):
return (hbar*omega*(ket.n + S.Half))*ket
def _eval_commutator_NumberOp(self, other):
return S.Zero
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_XOp(self, basis, **options):
# This logic is good but the underlying position
# representation logic is broken.
# temp = self.rewrite('xp').doit()
# result = represent(temp, basis=X)
# return result
raise NotImplementedError('Position representation is not implemented')
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format', 'sympy')
matrix = matrix_zeros(ndim_info, ndim_info, **options)
for i in range(ndim_info):
value = i + S.Half
if format == 'scipy.sparse':
value = float(value)
matrix[i,i] = value
if format == 'scipy.sparse':
matrix = matrix.tocsr()
return hbar*omega*matrix
#------------------------------------------------------------------------------
class SHOState(State):
"""State class for SHO states"""
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(S.Infinity)
@property
def n(self):
return self.args[0]
class SHOKet(SHOState, Ket):
"""1D eigenket.
Inherits from SHOState and Ket.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket
This is usually its quantum numbers or its symbol.
Examples
========
Ket's know about their associated bra:
>>> from sympy.physics.quantum.sho1d import SHOKet
>>> k = SHOKet('k')
>>> k.dual
<k|
>>> k.dual_class()
<class 'sympy.physics.quantum.sho1d.SHOBra'>
Take the Inner Product with a bra:
>>> from sympy.physics.quantum import InnerProduct
>>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra
>>> k = SHOKet('k')
>>> b = SHOBra('b')
>>> InnerProduct(b,k).doit()
KroneckerDelta(b, k)
Vector representation of a numerical state ket:
>>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp
>>> from sympy.physics.quantum.represent import represent
>>> k = SHOKet(3)
>>> N = NumberOp('N')
>>> represent(k, basis=N, ndim=4)
Matrix([
[0],
[0],
[0],
[1]])
"""
@classmethod
def dual_class(self):
return SHOBra
def _eval_innerproduct_SHOBra(self, bra, **hints):
result = KroneckerDelta(self.n, bra.n)
return result
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format', 'sympy')
options['spmatrix'] = 'lil'
vector = matrix_zeros(ndim_info, 1, **options)
if isinstance(self.n, Integer):
if self.n >= ndim_info:
return ValueError("N-Dimension too small")
if format == 'scipy.sparse':
vector[int(self.n), 0] = 1.0
vector = vector.tocsr()
elif format == 'numpy':
vector[int(self.n), 0] = 1.0
else:
vector[self.n, 0] = S.One
return vector
else:
return ValueError("Not Numerical State")
class SHOBra(SHOState, Bra):
"""A time-independent Bra in SHO.
Inherits from SHOState and Bra.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket
This is usually its quantum numbers or its symbol.
Examples
========
Bra's know about their associated ket:
>>> from sympy.physics.quantum.sho1d import SHOBra
>>> b = SHOBra('b')
>>> b.dual
|b>
>>> b.dual_class()
<class 'sympy.physics.quantum.sho1d.SHOKet'>
Vector representation of a numerical state bra:
>>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp
>>> from sympy.physics.quantum.represent import represent
>>> b = SHOBra(3)
>>> N = NumberOp('N')
>>> represent(b, basis=N, ndim=4)
Matrix([[0, 0, 0, 1]])
"""
@classmethod
def dual_class(self):
return SHOKet
def _represent_default_basis(self, **options):
return self._represent_NumberOp(None, **options)
def _represent_NumberOp(self, basis, **options):
ndim_info = options.get('ndim', 4)
format = options.get('format', 'sympy')
options['spmatrix'] = 'lil'
vector = matrix_zeros(1, ndim_info, **options)
if isinstance(self.n, Integer):
if self.n >= ndim_info:
return ValueError("N-Dimension too small")
if format == 'scipy.sparse':
vector[0, int(self.n)] = 1.0
vector = vector.tocsr()
elif format == 'numpy':
vector[0, int(self.n)] = 1.0
else:
vector[0, self.n] = S.One
return vector
else:
return ValueError("Not Numerical State")
ad = RaisingOp('a')
a = LoweringOp('a')
H = Hamiltonian('H')
N = NumberOp('N')
omega = Symbol('omega')
m = Symbol('m')
|
e66ef33c1870ee00e39e3f3ad24b42dedeb96bdc2c85114efc7f1780bcac590a | """Logic for applying operators to states.
Todo:
* Sometimes the final result needs to be expanded, we should do this by hand.
"""
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.operator import OuterProduct, Operator
from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
from sympy.physics.quantum.tensorproduct import TensorProduct
__all__ = [
'qapply'
]
#-----------------------------------------------------------------------------
# Main code
#-----------------------------------------------------------------------------
def qapply(e, **options):
"""Apply operators to states in a quantum expression.
Parameters
==========
e : Expr
The expression containing operators and states. This expression tree
will be walked to find operators acting on states symbolically.
options : dict
A dict of key/value pairs that determine how the operator actions
are carried out.
The following options are valid:
* ``dagger``: try to apply Dagger operators to the left
(default: False).
* ``ip_doit``: call ``.doit()`` in inner products when they are
encountered (default: True).
Returns
=======
e : Expr
The original expression, but with the operators applied to states.
Examples
========
>>> from sympy.physics.quantum import qapply, Ket, Bra
>>> b = Bra('b')
>>> k = Ket('k')
>>> A = k * b
>>> A
|k><b|
>>> qapply(A * b.dual / (b * b.dual))
|k>
>>> qapply(k.dual * A / (k.dual * k), dagger=True)
<b|
>>> qapply(k.dual * A / (k.dual * k))
<k|*|k><b|/<k|k>
"""
from sympy.physics.quantum.density import Density
dagger = options.get('dagger', False)
if e == 0:
return S.Zero
# This may be a bit aggressive but ensures that everything gets expanded
# to its simplest form before trying to apply operators. This includes
# things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and
# TensorProducts. The only problem with this is that if we can't apply
# all the Operators, we have just expanded everything.
# TODO: don't expand the scalars in front of each Mul.
e = e.expand(commutator=True, tensorproduct=True)
# If we just have a raw ket, return it.
if isinstance(e, KetBase):
return e
# We have an Add(a, b, c, ...) and compute
# Add(qapply(a), qapply(b), ...)
elif isinstance(e, Add):
result = 0
for arg in e.args:
result += qapply(arg, **options)
return result.expand()
# For a Density operator call qapply on its state
elif isinstance(e, Density):
new_args = [(qapply(state, **options), prob) for (state,
prob) in e.args]
return Density(*new_args)
# For a raw TensorProduct, call qapply on its args.
elif isinstance(e, TensorProduct):
return TensorProduct(*[qapply(t, **options) for t in e.args])
# For a Pow, call qapply on its base.
elif isinstance(e, Pow):
return qapply(e.base, **options)**e.exp
# We have a Mul where there might be actual operators to apply to kets.
elif isinstance(e, Mul):
c_part, nc_part = e.args_cnc()
c_mul = Mul(*c_part)
nc_mul = Mul(*nc_part)
if isinstance(nc_mul, Mul):
result = c_mul*qapply_Mul(nc_mul, **options)
else:
result = c_mul*qapply(nc_mul, **options)
if result == e and dagger:
return Dagger(qapply_Mul(Dagger(e), **options))
else:
return result
# In all other cases (State, Operator, Pow, Commutator, InnerProduct,
# OuterProduct) we won't ever have operators to apply to kets.
else:
return e
def qapply_Mul(e, **options):
ip_doit = options.get('ip_doit', True)
args = list(e.args)
# If we only have 0 or 1 args, we have nothing to do and return.
if len(args) <= 1 or not isinstance(e, Mul):
return e
rhs = args.pop()
lhs = args.pop()
# Make sure we have two non-commutative objects before proceeding.
if (sympify(rhs).is_commutative and not isinstance(rhs, Wavefunction)) or \
(sympify(lhs).is_commutative and not isinstance(lhs, Wavefunction)):
return e
# For a Pow with an integer exponent, apply one of them and reduce the
# exponent by one.
if isinstance(lhs, Pow) and lhs.exp.is_Integer:
args.append(lhs.base**(lhs.exp - 1))
lhs = lhs.base
# Pull OuterProduct apart
if isinstance(lhs, OuterProduct):
args.append(lhs.ket)
lhs = lhs.bra
# Call .doit() on Commutator/AntiCommutator.
if isinstance(lhs, (Commutator, AntiCommutator)):
comm = lhs.doit()
if isinstance(comm, Add):
return qapply(
e.func(*(args + [comm.args[0], rhs])) +
e.func(*(args + [comm.args[1], rhs])),
**options
)
else:
return qapply(e.func(*args)*comm*rhs, **options)
# Apply tensor products of operators to states
if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
len(lhs.args) == len(rhs.args):
result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
return qapply_Mul(e.func(*args), **options)*result
# Now try to actually apply the operator and build an inner product.
try:
result = lhs._apply_operator(rhs, **options)
except (NotImplementedError, AttributeError):
try:
result = rhs._apply_operator(lhs, **options)
except (NotImplementedError, AttributeError):
if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
result = InnerProduct(lhs, rhs)
if ip_doit:
result = result.doit()
else:
result = None
# TODO: I may need to expand before returning the final result.
if result == 0:
return S.Zero
elif result is None:
if len(args) == 0:
# We had two args to begin with so args=[].
return e
else:
return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs
elif isinstance(result, InnerProduct):
return result*qapply_Mul(e.func(*args), **options)
else: # result is a scalar times a Mul, Add or TensorProduct
return qapply(e.func(*args)*result, **options)
|
527e9ea78eedca07f555da7ef06d964bab93f850aa381470ac351da2715dfef0 | from sympy.core.backend import eye, Matrix, zeros
from sympy.physics.mechanics import dynamicsymbols
from sympy.physics.mechanics.functions import find_dynamicsymbols
__all__ = ['SymbolicSystem']
class SymbolicSystem:
"""SymbolicSystem is a class that contains all the information about a
system in a symbolic format such as the equations of motions and the bodies
and loads in the system.
There are three ways that the equations of motion can be described for
Symbolic System:
[1] Explicit form where the kinematics and dynamics are combined
x' = F_1(x, t, r, p)
[2] Implicit form where the kinematics and dynamics are combined
M_2(x, p) x' = F_2(x, t, r, p)
[3] Implicit form where the kinematics and dynamics are separate
M_3(q, p) u' = F_3(q, u, t, r, p)
q' = G(q, u, t, r, p)
where
x : states, e.g. [q, u]
t : time
r : specified (exogenous) inputs
p : constants
q : generalized coordinates
u : generalized speeds
F_1 : right hand side of the combined equations in explicit form
F_2 : right hand side of the combined equations in implicit form
F_3 : right hand side of the dynamical equations in implicit form
M_2 : mass matrix of the combined equations in implicit form
M_3 : mass matrix of the dynamical equations in implicit form
G : right hand side of the kinematical differential equations
Parameters
==========
coord_states : ordered iterable of functions of time
This input will either be a collection of the coordinates or states
of the system depending on whether or not the speeds are also
given. If speeds are specified this input will be assumed to
be the coordinates otherwise this input will be assumed to
be the states.
right_hand_side : Matrix
This variable is the right hand side of the equations of motion in
any of the forms. The specific form will be assumed depending on
whether a mass matrix or coordinate derivatives are given.
speeds : ordered iterable of functions of time, optional
This is a collection of the generalized speeds of the system. If
given it will be assumed that the first argument (coord_states)
will represent the generalized coordinates of the system.
mass_matrix : Matrix, optional
The matrix of the implicit forms of the equations of motion (forms
[2] and [3]). The distinction between the forms is determined by
whether or not the coordinate derivatives are passed in. If
they are given form [3] will be assumed otherwise form [2] is
assumed.
coordinate_derivatives : Matrix, optional
The right hand side of the kinematical equations in explicit form.
If given it will be assumed that the equations of motion are being
entered in form [3].
alg_con : Iterable, optional
The indexes of the rows in the equations of motion that contain
algebraic constraints instead of differential equations. If the
equations are input in form [3], it will be assumed the indexes are
referencing the mass_matrix/right_hand_side combination and not the
coordinate_derivatives.
output_eqns : Dictionary, optional
Any output equations that are desired to be tracked are stored in a
dictionary where the key corresponds to the name given for the
specific equation and the value is the equation itself in symbolic
form
coord_idxs : Iterable, optional
If coord_states corresponds to the states rather than the
coordinates this variable will tell SymbolicSystem which indexes of
the states correspond to generalized coordinates.
speed_idxs : Iterable, optional
If coord_states corresponds to the states rather than the
coordinates this variable will tell SymbolicSystem which indexes of
the states correspond to generalized speeds.
bodies : iterable of Body/Rigidbody objects, optional
Iterable containing the bodies of the system
loads : iterable of load instances (described below), optional
Iterable containing the loads of the system where forces are given
by (point of application, force vector) and torques are given by
(reference frame acting upon, torque vector). Ex [(point, force),
(ref_frame, torque)]
Attributes
==========
coordinates : Matrix, shape(n, 1)
This is a matrix containing the generalized coordinates of the system
speeds : Matrix, shape(m, 1)
This is a matrix containing the generalized speeds of the system
states : Matrix, shape(o, 1)
This is a matrix containing the state variables of the system
alg_con : List
This list contains the indices of the algebraic constraints in the
combined equations of motion. The presence of these constraints
requires that a DAE solver be used instead of an ODE solver.
If the system is given in form [3] the alg_con variable will be
adjusted such that it is a representation of the combined kinematics
and dynamics thus make sure it always matches the mass matrix
entered.
dyn_implicit_mat : Matrix, shape(m, m)
This is the M matrix in form [3] of the equations of motion (the mass
matrix or generalized inertia matrix of the dynamical equations of
motion in implicit form).
dyn_implicit_rhs : Matrix, shape(m, 1)
This is the F vector in form [3] of the equations of motion (the right
hand side of the dynamical equations of motion in implicit form).
comb_implicit_mat : Matrix, shape(o, o)
This is the M matrix in form [2] of the equations of motion.
This matrix contains a block diagonal structure where the top
left block (the first rows) represent the matrix in the
implicit form of the kinematical equations and the bottom right
block (the last rows) represent the matrix in the implicit form
of the dynamical equations.
comb_implicit_rhs : Matrix, shape(o, 1)
This is the F vector in form [2] of the equations of motion. The top
part of the vector represents the right hand side of the implicit form
of the kinemaical equations and the bottom of the vector represents the
right hand side of the implicit form of the dynamical equations of
motion.
comb_explicit_rhs : Matrix, shape(o, 1)
This vector represents the right hand side of the combined equations of
motion in explicit form (form [1] from above).
kin_explicit_rhs : Matrix, shape(m, 1)
This is the right hand side of the explicit form of the kinematical
equations of motion as can be seen in form [3] (the G matrix).
output_eqns : Dictionary
If output equations were given they are stored in a dictionary where
the key corresponds to the name given for the specific equation and
the value is the equation itself in symbolic form
bodies : Tuple
If the bodies in the system were given they are stored in a tuple for
future access
loads : Tuple
If the loads in the system were given they are stored in a tuple for
future access. This includes forces and torques where forces are given
by (point of application, force vector) and torques are given by
(reference frame acted upon, torque vector).
Example
=======
As a simple example, the dynamics of a simple pendulum will be input into a
SymbolicSystem object manually. First some imports will be needed and then
symbols will be set up for the length of the pendulum (l), mass at the end
of the pendulum (m), and a constant for gravity (g). ::
>>> from sympy import Matrix, sin, symbols
>>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem
>>> l, m, g = symbols('l m g')
The system will be defined by an angle of theta from the vertical and a
generalized speed of omega will be used where omega = theta_dot. ::
>>> theta, omega = dynamicsymbols('theta omega')
Now the equations of motion are ready to be formed and passed to the
SymbolicSystem object. ::
>>> kin_explicit_rhs = Matrix([omega])
>>> dyn_implicit_mat = Matrix([l**2 * m])
>>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)])
>>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega],
... dyn_implicit_mat)
Notes
=====
m : number of generalized speeds
n : number of generalized coordinates
o : number of states
"""
def __init__(self, coord_states, right_hand_side, speeds=None,
mass_matrix=None, coordinate_derivatives=None, alg_con=None,
output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None,
loads=None):
"""Initializes a SymbolicSystem object"""
# Extract information on speeds, coordinates and states
if speeds is None:
self._states = Matrix(coord_states)
if coord_idxs is None:
self._coordinates = None
else:
coords = [coord_states[i] for i in coord_idxs]
self._coordinates = Matrix(coords)
if speed_idxs is None:
self._speeds = None
else:
speeds_inter = [coord_states[i] for i in speed_idxs]
self._speeds = Matrix(speeds_inter)
else:
self._coordinates = Matrix(coord_states)
self._speeds = Matrix(speeds)
self._states = self._coordinates.col_join(self._speeds)
# Extract equations of motion form
if coordinate_derivatives is not None:
self._kin_explicit_rhs = coordinate_derivatives
self._dyn_implicit_rhs = right_hand_side
self._dyn_implicit_mat = mass_matrix
self._comb_implicit_rhs = None
self._comb_implicit_mat = None
self._comb_explicit_rhs = None
elif mass_matrix is not None:
self._kin_explicit_rhs = None
self._dyn_implicit_rhs = None
self._dyn_implicit_mat = None
self._comb_implicit_rhs = right_hand_side
self._comb_implicit_mat = mass_matrix
self._comb_explicit_rhs = None
else:
self._kin_explicit_rhs = None
self._dyn_implicit_rhs = None
self._dyn_implicit_mat = None
self._comb_implicit_rhs = None
self._comb_implicit_mat = None
self._comb_explicit_rhs = right_hand_side
# Set the remainder of the inputs as instance attributes
if alg_con is not None and coordinate_derivatives is not None:
alg_con = [i + len(coordinate_derivatives) for i in alg_con]
self._alg_con = alg_con
self.output_eqns = output_eqns
# Change the body and loads iterables to tuples if they are not tuples
# already
if not isinstance(bodies, tuple) and bodies is not None:
bodies = tuple(bodies)
if not isinstance(loads, tuple) and loads is not None:
loads = tuple(loads)
self._bodies = bodies
self._loads = loads
@property
def coordinates(self):
"""Returns the column matrix of the generalized coordinates"""
if self._coordinates is None:
raise AttributeError("The coordinates were not specified.")
else:
return self._coordinates
@property
def speeds(self):
"""Returns the column matrix of generalized speeds"""
if self._speeds is None:
raise AttributeError("The speeds were not specified.")
else:
return self._speeds
@property
def states(self):
"""Returns the column matrix of the state variables"""
return self._states
@property
def alg_con(self):
"""Returns a list with the indices of the rows containing algebraic
constraints in the combined form of the equations of motion"""
return self._alg_con
@property
def dyn_implicit_mat(self):
"""Returns the matrix, M, corresponding to the dynamic equations in
implicit form, M x' = F, where the kinematical equations are not
included"""
if self._dyn_implicit_mat is None:
raise AttributeError("dyn_implicit_mat is not specified for "
"equations of motion form [1] or [2].")
else:
return self._dyn_implicit_mat
@property
def dyn_implicit_rhs(self):
"""Returns the column matrix, F, corresponding to the dynamic equations
in implicit form, M x' = F, where the kinematical equations are not
included"""
if self._dyn_implicit_rhs is None:
raise AttributeError("dyn_implicit_rhs is not specified for "
"equations of motion form [1] or [2].")
else:
return self._dyn_implicit_rhs
@property
def comb_implicit_mat(self):
"""Returns the matrix, M, corresponding to the equations of motion in
implicit form (form [2]), M x' = F, where the kinematical equations are
included"""
if self._comb_implicit_mat is None:
if self._dyn_implicit_mat is not None:
num_kin_eqns = len(self._kin_explicit_rhs)
num_dyn_eqns = len(self._dyn_implicit_rhs)
zeros1 = zeros(num_kin_eqns, num_dyn_eqns)
zeros2 = zeros(num_dyn_eqns, num_kin_eqns)
inter1 = eye(num_kin_eqns).row_join(zeros1)
inter2 = zeros2.row_join(self._dyn_implicit_mat)
self._comb_implicit_mat = inter1.col_join(inter2)
return self._comb_implicit_mat
else:
raise AttributeError("comb_implicit_mat is not specified for "
"equations of motion form [1].")
else:
return self._comb_implicit_mat
@property
def comb_implicit_rhs(self):
"""Returns the column matrix, F, corresponding to the equations of
motion in implicit form (form [2]), M x' = F, where the kinematical
equations are included"""
if self._comb_implicit_rhs is None:
if self._dyn_implicit_rhs is not None:
kin_inter = self._kin_explicit_rhs
dyn_inter = self._dyn_implicit_rhs
self._comb_implicit_rhs = kin_inter.col_join(dyn_inter)
return self._comb_implicit_rhs
else:
raise AttributeError("comb_implicit_mat is not specified for "
"equations of motion in form [1].")
else:
return self._comb_implicit_rhs
def compute_explicit_form(self):
"""If the explicit right hand side of the combined equations of motion
is to provided upon initialization, this method will calculate it. This
calculation can potentially take awhile to compute."""
if self._comb_explicit_rhs is not None:
raise AttributeError("comb_explicit_rhs is already formed.")
inter1 = getattr(self, 'kin_explicit_rhs', None)
if inter1 is not None:
inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs)
out = inter1.col_join(inter2)
else:
out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs)
self._comb_explicit_rhs = out
@property
def comb_explicit_rhs(self):
"""Returns the right hand side of the equations of motion in explicit
form, x' = F, where the kinematical equations are included"""
if self._comb_explicit_rhs is None:
raise AttributeError("Please run .combute_explicit_form before "
"attempting to access comb_explicit_rhs.")
else:
return self._comb_explicit_rhs
@property
def kin_explicit_rhs(self):
"""Returns the right hand side of the kinematical equations in explicit
form, q' = G"""
if self._kin_explicit_rhs is None:
raise AttributeError("kin_explicit_rhs is not specified for "
"equations of motion form [1] or [2].")
else:
return self._kin_explicit_rhs
def dynamic_symbols(self):
"""Returns a column matrix containing all of the symbols in the system
that depend on time"""
# Create a list of all of the expressions in the equations of motion
if self._comb_explicit_rhs is None:
eom_expressions = (self.comb_implicit_mat[:] +
self.comb_implicit_rhs[:])
else:
eom_expressions = (self._comb_explicit_rhs[:])
functions_of_time = set()
for expr in eom_expressions:
functions_of_time = functions_of_time.union(
find_dynamicsymbols(expr))
functions_of_time = functions_of_time.union(self._states)
return tuple(functions_of_time)
def constant_symbols(self):
"""Returns a column matrix containing all of the symbols in the system
that do not depend on time"""
# Create a list of all of the expressions in the equations of motion
if self._comb_explicit_rhs is None:
eom_expressions = (self.comb_implicit_mat[:] +
self.comb_implicit_rhs[:])
else:
eom_expressions = (self._comb_explicit_rhs[:])
constants = set()
for expr in eom_expressions:
constants = constants.union(expr.free_symbols)
constants.remove(dynamicsymbols._t)
return tuple(constants)
@property
def bodies(self):
"""Returns the bodies in the system"""
if self._bodies is None:
raise AttributeError("bodies were not specified for the system.")
else:
return self._bodies
@property
def loads(self):
"""Returns the loads in the system"""
if self._loads is None:
raise AttributeError("loads were not specified for the system.")
else:
return self._loads
|
c0925fd56913419e5bdb84b3260bbb396c816da7dbe22e33a897c2e9d846c324 | from sympy.core.backend import zeros, Matrix, diff, eye
from sympy.core.sorting import default_sort_key
from sympy.solvers.solvers import solve_linear_system_LU
from sympy.physics.vector import (ReferenceFrame, dynamicsymbols,
partial_velocity)
from sympy.physics.mechanics.method import _Methods
from sympy.physics.mechanics.particle import Particle
from sympy.physics.mechanics.rigidbody import RigidBody
from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols,
_f_list_parser)
from sympy.physics.mechanics.linearize import Linearizer
from sympy.utilities.iterables import iterable
__all__ = ['KanesMethod']
class KanesMethod(_Methods):
"""Kane's method object.
Explanation
===========
This object is used to do the "book-keeping" as you go through and form
equations of motion in the way Kane presents in:
Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
The attributes are for equations in the form [M] udot = forcing.
Attributes
==========
q, u : Matrix
Matrices of the generalized coordinates and speeds
bodies : iterable
Iterable of Point and RigidBody objects in the system.
loads : iterable
Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
describing the forces on the system.
auxiliary : Matrix
If applicable, the set of auxiliary Kane's
equations used to solve for non-contributing
forces.
mass_matrix : Matrix
The system's mass matrix
forcing : Matrix
The system's forcing vector
mass_matrix_full : Matrix
The "mass matrix" for the u's and q's
forcing_full : Matrix
The "forcing vector" for the u's and q's
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
In this example, we first need to do the kinematics.
This involves creating generalized speeds and coordinates and their
derivatives.
Then we create a point and set its velocity in a frame.
>>> from sympy import symbols
>>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame
>>> from sympy.physics.mechanics import Point, Particle, KanesMethod
>>> q, u = dynamicsymbols('q u')
>>> qd, ud = dynamicsymbols('q u', 1)
>>> m, c, k = symbols('m c k')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, u * N.x)
Next we need to arrange/store information in the way that KanesMethod
requires. The kinematic differential equations need to be stored in a
dict. A list of forces/torques must be constructed, where each entry in
the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the
Vectors represent the Force or Torque.
Next a particle needs to be created, and it needs to have a point and mass
assigned to it.
Finally, a list of all bodies and particles needs to be created.
>>> kd = [qd - u]
>>> FL = [(P, (-k * q - c * u) * N.x)]
>>> pa = Particle('pa', P, m)
>>> BL = [pa]
Finally we can generate the equations of motion.
First we create the KanesMethod object and supply an inertial frame,
coordinates, generalized speeds, and the kinematic differential equations.
Additional quantities such as configuration and motion constraints,
dependent coordinates and speeds, and auxiliary speeds are also supplied
here (see the online documentation).
Next we form FR* and FR to complete: Fr + Fr* = 0.
We have the equations of motion at this point.
It makes sense to rearrange them though, so we calculate the mass matrix and
the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is
the mass matrix, udot is a vector of the time derivatives of the
generalized speeds, and forcing is a vector representing "forcing" terms.
>>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd)
>>> (fr, frstar) = KM.kanes_equations(BL, FL)
>>> MM = KM.mass_matrix
>>> forcing = KM.forcing
>>> rhs = MM.inv() * forcing
>>> rhs
Matrix([[(-c*u(t) - k*q(t))/m]])
>>> KM.linearize(A_and_B=True)[0]
Matrix([
[ 0, 1],
[-k/m, -c/m]])
Please look at the documentation pages for more information on how to
perform linearization and how to deal with dependent coordinates & speeds,
and how do deal with bringing non-contributing forces into evidence.
"""
def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
configuration_constraints=None, u_dependent=None,
velocity_constraints=None, acceleration_constraints=None,
u_auxiliary=None, bodies=None, forcelist=None):
"""Please read the online documentation. """
if not q_ind:
q_ind = [dynamicsymbols('dummy_q')]
kd_eqs = [dynamicsymbols('dummy_kd')]
if not isinstance(frame, ReferenceFrame):
raise TypeError('An inertial ReferenceFrame must be supplied')
self._inertial = frame
self._fr = None
self._frstar = None
self._forcelist = forcelist
self._bodylist = bodies
self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
u_auxiliary)
self._initialize_kindiffeq_matrices(kd_eqs)
self._initialize_constraint_matrices(configuration_constraints,
velocity_constraints, acceleration_constraints)
def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
"""Initialize the coordinate and speed vectors."""
none_handler = lambda x: Matrix(x) if x else Matrix()
# Initialize generalized coordinates
q_dep = none_handler(q_dep)
if not iterable(q_ind):
raise TypeError('Generalized coordinates must be an iterable.')
if not iterable(q_dep):
raise TypeError('Dependent coordinates must be an iterable.')
q_ind = Matrix(q_ind)
self._qdep = q_dep
self._q = Matrix([q_ind, q_dep])
self._qdot = self.q.diff(dynamicsymbols._t)
# Initialize generalized speeds
u_dep = none_handler(u_dep)
if not iterable(u_ind):
raise TypeError('Generalized speeds must be an iterable.')
if not iterable(u_dep):
raise TypeError('Dependent speeds must be an iterable.')
u_ind = Matrix(u_ind)
self._udep = u_dep
self._u = Matrix([u_ind, u_dep])
self._udot = self.u.diff(dynamicsymbols._t)
self._uaux = none_handler(u_aux)
def _initialize_constraint_matrices(self, config, vel, acc):
"""Initializes constraint matrices."""
# Define vector dimensions
o = len(self.u)
m = len(self._udep)
p = o - m
none_handler = lambda x: Matrix(x) if x else Matrix()
# Initialize configuration constraints
config = none_handler(config)
if len(self._qdep) != len(config):
raise ValueError('There must be an equal number of dependent '
'coordinates and configuration constraints.')
self._f_h = none_handler(config)
# Initialize velocity and acceleration constraints
vel = none_handler(vel)
acc = none_handler(acc)
if len(vel) != m:
raise ValueError('There must be an equal number of dependent '
'speeds and velocity constraints.')
if acc and (len(acc) != m):
raise ValueError('There must be an equal number of dependent '
'speeds and acceleration constraints.')
if vel:
u_zero = {i: 0 for i in self.u}
udot_zero = {i: 0 for i in self._udot}
# When calling kanes_equations, another class instance will be
# created if auxiliary u's are present. In this case, the
# computation of kinetic differential equation matrices will be
# skipped as this was computed during the original KanesMethod
# object, and the qd_u_map will not be available.
if self._qdot_u_map is not None:
vel = msubs(vel, self._qdot_u_map)
self._f_nh = msubs(vel, u_zero)
self._k_nh = (vel - self._f_nh).jacobian(self.u)
# If no acceleration constraints given, calculate them.
if not acc:
_f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u +
self._f_nh.diff(dynamicsymbols._t))
if self._qdot_u_map is not None:
_f_dnh = msubs(_f_dnh, self._qdot_u_map)
self._f_dnh = _f_dnh
self._k_dnh = self._k_nh
else:
if self._qdot_u_map is not None:
acc = msubs(acc, self._qdot_u_map)
self._f_dnh = msubs(acc, udot_zero)
self._k_dnh = (acc - self._f_dnh).jacobian(self._udot)
# Form of non-holonomic constraints is B*u + C = 0.
# We partition B into independent and dependent columns:
# Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds
# to independent speeds as: udep = Ars*uind, neglecting the C term.
B_ind = self._k_nh[:, :p]
B_dep = self._k_nh[:, p:o]
self._Ars = -B_dep.LUsolve(B_ind)
else:
self._f_nh = Matrix()
self._k_nh = Matrix()
self._f_dnh = Matrix()
self._k_dnh = Matrix()
self._Ars = Matrix()
def _initialize_kindiffeq_matrices(self, kdeqs):
"""Initialize the kinematic differential equation matrices."""
if kdeqs:
if len(self.q) != len(kdeqs):
raise ValueError('There must be an equal number of kinematic '
'differential equations and coordinates.')
kdeqs = Matrix(kdeqs)
u = self.u
qdot = self._qdot
# Dictionaries setting things to zero
u_zero = {i: 0 for i in u}
uaux_zero = {i: 0 for i in self._uaux}
qdot_zero = {i: 0 for i in qdot}
f_k = msubs(kdeqs, u_zero, qdot_zero)
k_ku = (msubs(kdeqs, qdot_zero) - f_k).jacobian(u)
k_kqdot = (msubs(kdeqs, u_zero) - f_k).jacobian(qdot)
f_k = k_kqdot.LUsolve(f_k)
k_ku = k_kqdot.LUsolve(k_ku)
k_kqdot = eye(len(qdot))
self._qdot_u_map = solve_linear_system_LU(
Matrix([k_kqdot.T, -(k_ku * u + f_k).T]).T, qdot)
self._f_k = msubs(f_k, uaux_zero)
self._k_ku = msubs(k_ku, uaux_zero)
self._k_kqdot = k_kqdot
else:
self._qdot_u_map = None
self._f_k = Matrix()
self._k_ku = Matrix()
self._k_kqdot = Matrix()
def _form_fr(self, fl):
"""Form the generalized active force."""
if fl is not None and (len(fl) == 0 or not iterable(fl)):
raise ValueError('Force pairs must be supplied in an '
'non-empty iterable or None.')
N = self._inertial
# pull out relevant velocities for constructing partial velocities
vel_list, f_list = _f_list_parser(fl, N)
vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
f_list = [msubs(i, self._qdot_u_map) for i in f_list]
# Fill Fr with dot product of partial velocities and forces
o = len(self.u)
b = len(f_list)
FR = zeros(o, 1)
partials = partial_velocity(vel_list, self.u, N)
for i in range(o):
FR[i] = sum(partials[j][i] & f_list[j] for j in range(b))
# In case there are dependent speeds
if self._udep:
p = o - len(self._udep)
FRtilde = FR[:p, 0]
FRold = FR[p:o, 0]
FRtilde += self._Ars.T * FRold
FR = FRtilde
self._forcelist = fl
self._fr = FR
return FR
def _form_frstar(self, bl):
"""Form the generalized inertia force."""
if not iterable(bl):
raise TypeError('Bodies must be supplied in an iterable.')
t = dynamicsymbols._t
N = self._inertial
# Dicts setting things to zero
udot_zero = {i: 0 for i in self._udot}
uaux_zero = {i: 0 for i in self._uaux}
uauxdot = [diff(i, t) for i in self._uaux]
uauxdot_zero = {i: 0 for i in uauxdot}
# Dictionary of q' and q'' to u and u'
q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in
self._qdot_u_map.items()}
q_ddot_u_map.update(self._qdot_u_map)
# Fill up the list of partials: format is a list with num elements
# equal to number of entries in body list. Each of these elements is a
# list - either of length 1 for the translational components of
# particles or of length 2 for the translational and rotational
# components of rigid bodies. The inner most list is the list of
# partial velocities.
def get_partial_velocity(body):
if isinstance(body, RigidBody):
vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)]
elif isinstance(body, Particle):
vlist = [body.point.vel(N),]
else:
raise TypeError('The body list may only contain either '
'RigidBody or Particle as list elements.')
v = [msubs(vel, self._qdot_u_map) for vel in vlist]
return partial_velocity(v, self.u, N)
partials = [get_partial_velocity(body) for body in bl]
# Compute fr_star in two components:
# fr_star = -(MM*u' + nonMM)
o = len(self.u)
MM = zeros(o, o)
nonMM = zeros(o, 1)
zero_uaux = lambda expr: msubs(expr, uaux_zero)
zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero)
for i, body in enumerate(bl):
if isinstance(body, RigidBody):
M = zero_uaux(body.mass)
I = zero_uaux(body.central_inertia)
vel = zero_uaux(body.masscenter.vel(N))
omega = zero_uaux(body.frame.ang_vel_in(N))
acc = zero_udot_uaux(body.masscenter.acc(N))
inertial_force = (M.diff(t) * vel + M * acc)
inertial_torque = zero_uaux((I.dt(body.frame) & omega) +
msubs(I & body.frame.ang_acc_in(N), udot_zero) +
(omega ^ (I & omega)))
for j in range(o):
tmp_vel = zero_uaux(partials[i][0][j])
tmp_ang = zero_uaux(I & partials[i][1][j])
for k in range(o):
# translational
MM[j, k] += M * (tmp_vel & partials[i][0][k])
# rotational
MM[j, k] += (tmp_ang & partials[i][1][k])
nonMM[j] += inertial_force & partials[i][0][j]
nonMM[j] += inertial_torque & partials[i][1][j]
else:
M = zero_uaux(body.mass)
vel = zero_uaux(body.point.vel(N))
acc = zero_udot_uaux(body.point.acc(N))
inertial_force = (M.diff(t) * vel + M * acc)
for j in range(o):
temp = zero_uaux(partials[i][0][j])
for k in range(o):
MM[j, k] += M * (temp & partials[i][0][k])
nonMM[j] += inertial_force & partials[i][0][j]
# Compose fr_star out of MM and nonMM
MM = zero_uaux(msubs(MM, q_ddot_u_map))
nonMM = msubs(msubs(nonMM, q_ddot_u_map),
udot_zero, uauxdot_zero, uaux_zero)
fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM)
# If there are dependent speeds, we need to find fr_star_tilde
if self._udep:
p = o - len(self._udep)
fr_star_ind = fr_star[:p, 0]
fr_star_dep = fr_star[p:o, 0]
fr_star = fr_star_ind + (self._Ars.T * fr_star_dep)
# Apply the same to MM
MMi = MM[:p, :]
MMd = MM[p:o, :]
MM = MMi + (self._Ars.T * MMd)
self._bodylist = bl
self._frstar = fr_star
self._k_d = MM
self._f_d = -msubs(self._fr + self._frstar, udot_zero)
return fr_star
def to_linearizer(self):
"""Returns an instance of the Linearizer class, initiated from the
data in the KanesMethod class. This may be more desirable than using
the linearize class method, as the Linearizer object will allow more
efficient recalculation (i.e. about varying operating points)."""
if (self._fr is None) or (self._frstar is None):
raise ValueError('Need to compute Fr, Fr* first.')
# Get required equation components. The Kane's method class breaks
# these into pieces. Need to reassemble
f_c = self._f_h
if self._f_nh and self._k_nh:
f_v = self._f_nh + self._k_nh*Matrix(self.u)
else:
f_v = Matrix()
if self._f_dnh and self._k_dnh:
f_a = self._f_dnh + self._k_dnh*Matrix(self._udot)
else:
f_a = Matrix()
# Dicts to sub to zero, for splitting up expressions
u_zero = {i: 0 for i in self.u}
ud_zero = {i: 0 for i in self._udot}
qd_zero = {i: 0 for i in self._qdot}
qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])}
# Break the kinematic differential eqs apart into f_0 and f_1
f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot)
f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u)
# Break the dynamic differential eqs into f_2 and f_3
f_2 = msubs(self._frstar, qd_u_zero)
f_3 = msubs(self._frstar, ud_zero) + self._fr
f_4 = zeros(len(f_2), 1)
# Get the required vector components
q = self.q
u = self.u
if self._qdep:
q_i = q[:-len(self._qdep)]
else:
q_i = q
q_d = self._qdep
if self._udep:
u_i = u[:-len(self._udep)]
else:
u_i = u
u_d = self._udep
# Form dictionary to set auxiliary speeds & their derivatives to 0.
uaux = self._uaux
uauxdot = uaux.diff(dynamicsymbols._t)
uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])}
# Checking for dynamic symbols outside the dynamic differential
# equations; throws error if there is.
sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot]))
if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot,
self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]):
raise ValueError('Cannot have dynamicsymbols outside dynamic \
forcing vector.')
# Find all other dynamic symbols, forming the forcing vector r.
# Sort r to make it canonical.
r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list))
r.sort(key=default_sort_key)
# Check for any derivatives of variables in r that are also found in r.
for i in r:
if diff(i, dynamicsymbols._t) in r:
raise ValueError('Cannot have derivatives of specified \
quantities when linearizing forcing terms.')
return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
q_d, u_i, u_d, r)
# TODO : Remove `new_method` after 1.1 has been released.
def linearize(self, *, new_method=None, **kwargs):
""" Linearize the equations of motion about a symbolic operating point.
Explanation
===========
If kwarg A_and_B is False (default), returns M, A, B, r for the
linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
If kwarg A_and_B is True, returns A, B, r for the linearized form
dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
computationally intensive if there are many symbolic parameters. For
this reason, it may be more desirable to use the default A_and_B=False,
returning M, A, and B. Values may then be substituted in to these
matrices, and the state space form found as
A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
In both cases, r is found as all dynamicsymbols in the equations of
motion that are not part of q, u, q', or u'. They are sorted in
canonical form.
The operating points may be also entered using the ``op_point`` kwarg.
This takes a dictionary of {symbol: value}, or a an iterable of such
dictionaries. The values may be numeric or symbolic. The more values
you can specify beforehand, the faster this computation will run.
For more documentation, please see the ``Linearizer`` class."""
linearizer = self.to_linearizer()
result = linearizer.linearize(**kwargs)
return result + (linearizer.r,)
def kanes_equations(self, bodies=None, loads=None):
""" Method to form Kane's equations, Fr + Fr* = 0.
Explanation
===========
Returns (Fr, Fr*). In the case where auxiliary generalized speeds are
present (say, s auxiliary speeds, o generalized speeds, and m motion
constraints) the length of the returned vectors will be o - m + s in
length. The first o - m equations will be the constrained Kane's
equations, then the s auxiliary Kane's equations. These auxiliary
equations can be accessed with the auxiliary_eqs().
Parameters
==========
bodies : iterable
An iterable of all RigidBody's and Particle's in the system.
A system must have at least one body.
loads : iterable
Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector)
tuples which represent the force at a point or torque on a frame.
Must be either a non-empty iterable of tuples or None which corresponds
to a system with no constraints.
"""
if bodies is None:
bodies = self.bodies
if loads is None and self._forcelist is not None:
loads = self._forcelist
if loads == []:
loads = None
if not self._k_kqdot:
raise AttributeError('Create an instance of KanesMethod with '
'kinematic differential equations to use this method.')
fr = self._form_fr(loads)
frstar = self._form_frstar(bodies)
if self._uaux:
if not self._udep:
km = KanesMethod(self._inertial, self.q, self._uaux,
u_auxiliary=self._uaux)
else:
km = KanesMethod(self._inertial, self.q, self._uaux,
u_auxiliary=self._uaux, u_dependent=self._udep,
velocity_constraints=(self._k_nh * self.u +
self._f_nh))
km._qdot_u_map = self._qdot_u_map
self._km = km
fraux = km._form_fr(loads)
frstaraux = km._form_frstar(bodies)
self._aux_eq = fraux + frstaraux
self._fr = fr.col_join(fraux)
self._frstar = frstar.col_join(frstaraux)
return (self._fr, self._frstar)
def _form_eoms(self):
fr, frstar = self.kanes_equations(self.bodylist, self.forcelist)
return fr + frstar
def rhs(self, inv_method=None):
"""Returns the system's equations of motion in first order form. The
output is the right hand side of::
x' = |q'| =: f(q, u, r, p, t)
|u'|
The right hand side is what is needed by most numerical ODE
integrators.
Parameters
==========
inv_method : str
The specific sympy inverse matrix calculation method to use. For a
list of valid methods, see
:meth:`~sympy.matrices.matrices.MatrixBase.inv`
"""
rhs = zeros(len(self.q) + len(self.u), 1)
kdes = self.kindiffdict()
for i, q_i in enumerate(self.q):
rhs[i] = kdes[q_i.diff()]
if inv_method is None:
rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing)
else:
rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method,
try_block_diag=True) *
self.forcing)
return rhs
def kindiffdict(self):
"""Returns a dictionary mapping q' to u."""
if not self._qdot_u_map:
raise AttributeError('Create an instance of KanesMethod with '
'kinematic differential equations to use this method.')
return self._qdot_u_map
@property
def auxiliary_eqs(self):
"""A matrix containing the auxiliary equations."""
if not self._fr or not self._frstar:
raise ValueError('Need to compute Fr, Fr* first.')
if not self._uaux:
raise ValueError('No auxiliary speeds have been declared.')
return self._aux_eq
@property
def mass_matrix(self):
"""The mass matrix of the system."""
if not self._fr or not self._frstar:
raise ValueError('Need to compute Fr, Fr* first.')
return Matrix([self._k_d, self._k_dnh])
@property
def mass_matrix_full(self):
"""The mass matrix of the system, augmented by the kinematic
differential equations."""
if not self._fr or not self._frstar:
raise ValueError('Need to compute Fr, Fr* first.')
o = len(self.u)
n = len(self.q)
return ((self._k_kqdot).row_join(zeros(n, o))).col_join((zeros(o,
n)).row_join(self.mass_matrix))
@property
def forcing(self):
"""The forcing vector of the system."""
if not self._fr or not self._frstar:
raise ValueError('Need to compute Fr, Fr* first.')
return -Matrix([self._f_d, self._f_dnh])
@property
def forcing_full(self):
"""The forcing vector of the system, augmented by the kinematic
differential equations."""
if not self._fr or not self._frstar:
raise ValueError('Need to compute Fr, Fr* first.')
f1 = self._k_ku * Matrix(self.u) + self._f_k
return -Matrix([f1, self._f_d, self._f_dnh])
@property
def q(self):
return self._q
@property
def u(self):
return self._u
@property
def bodylist(self):
return self._bodylist
@property
def forcelist(self):
return self._forcelist
@property
def bodies(self):
return self._bodylist
@property
def loads(self):
return self._forcelist
|
9ceafc644b9ef74c5e3bc32974230b225b6f50494dc49bc14503290c1ef0eb45 | from sympy.utilities import dict_merge
from sympy.utilities.iterables import iterable
from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame,
Point, dynamicsymbols)
from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex,
init_vprinting)
from sympy.physics.mechanics.particle import Particle
from sympy.physics.mechanics.rigidbody import RigidBody
from sympy.simplify.simplify import simplify
from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos,
tan, AppliedUndef, S)
__all__ = ['inertia',
'inertia_of_point_mass',
'linear_momentum',
'angular_momentum',
'kinetic_energy',
'potential_energy',
'Lagrangian',
'mechanics_printing',
'mprint',
'msprint',
'mpprint',
'mlatex',
'msubs',
'find_dynamicsymbols']
# These are functions that we've moved and renamed during extracting the
# basic vector calculus code from the mechanics packages.
mprint = vprint
msprint = vsprint
mpprint = vpprint
mlatex = vlatex
def mechanics_printing(**kwargs):
"""
Initializes time derivative printing for all SymPy objects in
mechanics module.
"""
init_vprinting(**kwargs)
mechanics_printing.__doc__ = init_vprinting.__doc__
def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
"""Simple way to create inertia Dyadic object.
Explanation
===========
If you don't know what a Dyadic is, just treat this like the inertia
tensor. Then, do the easy thing and define it in a body-fixed frame.
Parameters
==========
frame : ReferenceFrame
The frame the inertia is defined in
ixx : Sympifyable
the xx element in the inertia dyadic
iyy : Sympifyable
the yy element in the inertia dyadic
izz : Sympifyable
the zz element in the inertia dyadic
ixy : Sympifyable
the xy element in the inertia dyadic
iyz : Sympifyable
the yz element in the inertia dyadic
izx : Sympifyable
the zx element in the inertia dyadic
Examples
========
>>> from sympy.physics.mechanics import ReferenceFrame, inertia
>>> N = ReferenceFrame('N')
>>> inertia(N, 1, 2, 3)
(N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Need to define the inertia in a frame')
ol = sympify(ixx) * (frame.x | frame.x)
ol += sympify(ixy) * (frame.x | frame.y)
ol += sympify(izx) * (frame.x | frame.z)
ol += sympify(ixy) * (frame.y | frame.x)
ol += sympify(iyy) * (frame.y | frame.y)
ol += sympify(iyz) * (frame.y | frame.z)
ol += sympify(izx) * (frame.z | frame.x)
ol += sympify(iyz) * (frame.z | frame.y)
ol += sympify(izz) * (frame.z | frame.z)
return ol
def inertia_of_point_mass(mass, pos_vec, frame):
"""Inertia dyadic of a point mass relative to point O.
Parameters
==========
mass : Sympifyable
Mass of the point mass
pos_vec : Vector
Position from point O to point mass
frame : ReferenceFrame
Reference frame to express the dyadic in
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
>>> N = ReferenceFrame('N')
>>> r, m = symbols('r m')
>>> px = r * N.x
>>> inertia_of_point_mass(m, px, N)
m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
"""
return mass * (((frame.x | frame.x) + (frame.y | frame.y) +
(frame.z | frame.z)) * (pos_vec & pos_vec) -
(pos_vec | pos_vec))
def linear_momentum(frame, *body):
"""Linear momentum of the system.
Explanation
===========
This function returns the linear momentum of a system of Particle's and/or
RigidBody's. The linear momentum of a system is equal to the vector sum of
the linear momentum of its constituents. Consider a system, S, comprised of
a rigid body, A, and a particle, P. The linear momentum of the system, L,
is equal to the vector sum of the linear momentum of the particle, L1, and
the linear momentum of the rigid body, L2, i.e.
L = L1 + L2
Parameters
==========
frame : ReferenceFrame
The frame in which linear momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose linear momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = Point('Ac')
>>> Ac.set_vel(N, 25 * N.y)
>>> I = outer(N.x, N.x)
>>> A = RigidBody('A', Ac, N, 20, (I, Ac))
>>> linear_momentum(N, A, Pa)
10*N.x + 500*N.y
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please specify a valid ReferenceFrame')
else:
linear_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
linear_momentum_sys += e.linear_momentum(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return linear_momentum_sys
def angular_momentum(point, frame, *body):
"""Angular momentum of a system.
Explanation
===========
This function returns the angular momentum of a system of Particle's and/or
RigidBody's. The angular momentum of such a system is equal to the vector
sum of the angular momentum of its constituents. Consider a system, S,
comprised of a rigid body, A, and a particle, P. The angular momentum of
the system, H, is equal to the vector sum of the angular momentum of the
particle, H1, and the angular momentum of the rigid body, H2, i.e.
H = H1 + H2
Parameters
==========
point : Point
The point about which angular momentum of the system is desired.
frame : ReferenceFrame
The frame in which angular momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose angular momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> angular_momentum(O, N, Pa, A)
10*N.z
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
if not isinstance(point, Point):
raise TypeError('Please specify a valid Point')
else:
angular_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
angular_momentum_sys += e.angular_momentum(point, frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return angular_momentum_sys
def kinetic_energy(frame, *body):
"""Kinetic energy of a multibody system.
Explanation
===========
This function returns the kinetic energy of a system of Particle's and/or
RigidBody's. The kinetic energy of such a system is equal to the sum of
the kinetic energies of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The kinetic energy of the system, T,
is equal to the vector sum of the kinetic energy of the particle, T1, and
the kinetic energy of the rigid body, T2, i.e.
T = T1 + T2
Kinetic energy is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose kinetic energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> kinetic_energy(N, Pa, A)
350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
ke_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
ke_sys += e.kinetic_energy(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return ke_sys
def potential_energy(*body):
"""Potential energy of a multibody system.
Explanation
===========
This function returns the potential energy of a system of Particle's and/or
RigidBody's. The potential energy of such a system is equal to the sum of
the potential energy of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The potential energy of the system, V,
is equal to the vector sum of the potential energy of the particle, V1, and
the potential energy of the rigid body, V2, i.e.
V = V1 + V2
Potential energy is a scalar.
Parameters
==========
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose potential energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> Pa = Particle('Pa', P, m)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> a = ReferenceFrame('a')
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, M, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> potential_energy(Pa, A)
M*g*h + g*h*m
"""
pe_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
pe_sys += e.potential_energy
else:
raise TypeError('*body must have only Particle or RigidBody')
return pe_sys
def gravity(acceleration, *bodies):
"""
Returns a list of gravity forces given the acceleration
due to gravity and any number of particles or rigidbodies.
Example
=======
>>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody
>>> from sympy.physics.mechanics.functions import gravity
>>> from sympy import symbols
>>> N = ReferenceFrame('N')
>>> m, M, g = symbols('m M g')
>>> F1, F2 = symbols('F1 F2')
>>> po = Point('po')
>>> pa = Particle('pa', po, m)
>>> A = ReferenceFrame('A')
>>> P = Point('P')
>>> I = outer(A.x, A.x)
>>> B = RigidBody('B', P, A, M, (I, P))
>>> forceList = [(po, F1), (P, F2)]
>>> forceList.extend(gravity(g*N.y, pa, B))
>>> forceList
[(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)]
"""
gravity_force = []
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
for e in bodies:
point = getattr(e, 'masscenter', None)
if point is None:
point = e.point
gravity_force.append((point, e.mass*acceleration))
return gravity_force
def center_of_mass(point, *bodies):
"""
Returns the position vector from the given point to the center of mass
of the given bodies(particles or rigidbodies).
Example
=======
>>> from sympy import symbols, S
>>> from sympy.physics.vector import Point
>>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
>>> from sympy.physics.mechanics.functions import center_of_mass
>>> a = ReferenceFrame('a')
>>> m = symbols('m', real=True)
>>> p1 = Particle('p1', Point('p1_pt'), S(1))
>>> p2 = Particle('p2', Point('p2_pt'), S(2))
>>> p3 = Particle('p3', Point('p3_pt'), S(3))
>>> p4 = Particle('p4', Point('p4_pt'), m)
>>> b_f = ReferenceFrame('b_f')
>>> b_cm = Point('b_cm')
>>> mb = symbols('mb')
>>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
>>> p2.point.set_pos(p1.point, a.x)
>>> p3.point.set_pos(p1.point, a.x + a.y)
>>> p4.point.set_pos(p1.point, a.y)
>>> b.masscenter.set_pos(p1.point, a.y + a.z)
>>> point_o=Point('o')
>>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
>>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
>>> point_o.pos_from(p1.point)
5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
"""
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
total_mass = 0
vec = Vector(0)
for i in bodies:
total_mass += i.mass
masscenter = getattr(i, 'masscenter', None)
if masscenter is None:
masscenter = i.point
vec += i.mass*masscenter.pos_from(point)
return vec/total_mass
def Lagrangian(frame, *body):
"""Lagrangian of a multibody system.
Explanation
===========
This function returns the Lagrangian of a system of Particle's and/or
RigidBody's. The Lagrangian of such a system is equal to the difference
between the kinetic energies and potential energies of its constituents. If
T and V are the kinetic and potential energies of a system then it's
Lagrangian, L, is defined as
L = T - V
The Lagrangian is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined to determine the kinetic energy.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose Lagrangian is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> Lagrangian(N, Pa, A)
-M*g*h - g*h*m + 350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please supply a valid ReferenceFrame')
for e in body:
if not isinstance(e, (RigidBody, Particle)):
raise TypeError('*body must have only Particle or RigidBody')
return kinetic_energy(frame, *body) - potential_energy(*body)
def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
"""Find all dynamicsymbols in expression.
Explanation
===========
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
If we intend to apply this function on a vector, the optional
``reference_frame`` is also used to inform about the corresponding frame
with respect to which the dynamic symbols of the given vector is to be
determined.
Parameters
==========
expression : SymPy expression
exclude : iterable of dynamicsymbols, optional
reference_frame : ReferenceFrame, optional
The frame with respect to which the dynamic symbols of the
given vector is to be determined.
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> from sympy.physics.mechanics import ReferenceFrame
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
{x(t), y(t), Derivative(x(t), t)}
>>> find_dynamicsymbols(expr, exclude=[x, y])
{Derivative(x(t), t)}
>>> a, b, c = dynamicsymbols('a, b, c')
>>> A = ReferenceFrame('A')
>>> v = a * A.x + b * A.y + c * A.z
>>> find_dynamicsymbols(v, reference_frame=A)
{a(t), b(t), c(t)}
"""
t_set = {dynamicsymbols._t}
if exclude:
if iterable(exclude):
exclude_set = set(exclude)
else:
raise TypeError("exclude kwarg must be iterable")
else:
exclude_set = set()
if isinstance(expression, Vector):
if reference_frame is None:
raise ValueError("You must provide reference_frame when passing a "
"vector expression, got %s." % reference_frame)
else:
expression = expression.to_matrix(reference_frame)
return {i for i in expression.atoms(AppliedUndef, Derivative) if
i.free_symbols == t_set} - exclude_set
def msubs(expr, *sub_dicts, smart=False, **kwargs):
"""A custom subs for use on expressions derived in physics.mechanics.
Traverses the expression tree once, performing the subs found in sub_dicts.
Terms inside ``Derivative`` expressions are ignored:
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, msubs
>>> x = dynamicsymbols('x')
>>> msubs(x.diff() + x, {x: 1})
Derivative(x(t), t) + 1
Note that sub_dicts can be a single dictionary, or several dictionaries:
>>> x, y, z = dynamicsymbols('x, y, z')
>>> sub1 = {x: 1, y: 2}
>>> sub2 = {z: 3, x.diff(): 4}
>>> msubs(x.diff() + x + y + z, sub1, sub2)
10
If smart=True (default False), also checks for conditions that may result
in ``nan``, but if simplified would yield a valid expression. For example:
>>> from sympy import sin, tan
>>> (sin(x)/tan(x)).subs(x, 0)
nan
>>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
1
It does this by first replacing all ``tan`` with ``sin/cos``. Then each
node is traversed. If the node is a fraction, subs is first evaluated on
the denominator. If this results in 0, simplification of the entire
fraction is attempted. Using this selective simplification, only
subexpressions that result in 1/0 are targeted, resulting in faster
performance.
"""
sub_dict = dict_merge(*sub_dicts)
if smart:
func = _smart_subs
elif hasattr(expr, 'msubs'):
return expr.msubs(sub_dict)
else:
func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
if isinstance(expr, (Matrix, Vector, Dyadic)):
return expr.applyfunc(lambda x: func(x, sub_dict))
else:
return func(expr, sub_dict)
def _crawl(expr, func, *args, **kwargs):
"""Crawl the expression tree, and apply func to every node."""
val = func(expr, *args, **kwargs)
if val is not None:
return val
new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
return expr.func(*new_args)
def _sub_func(expr, sub_dict):
"""Perform direct matching substitution, ignoring derivatives."""
if expr in sub_dict:
return sub_dict[expr]
elif not expr.args or expr.is_Derivative:
return expr
def _tan_repl_func(expr):
"""Replace tan with sin/cos."""
if isinstance(expr, tan):
return sin(*expr.args) / cos(*expr.args)
elif not expr.args or expr.is_Derivative:
return expr
def _smart_subs(expr, sub_dict):
"""Performs subs, checking for conditions that may result in `nan` or
`oo`, and attempts to simplify them out.
The expression tree is traversed twice, and the following steps are
performed on each expression node:
- First traverse:
Replace all `tan` with `sin/cos`.
- Second traverse:
If node is a fraction, check if the denominator evaluates to 0.
If so, attempt to simplify it out. Then if node is in sub_dict,
sub in the corresponding value."""
expr = _crawl(expr, _tan_repl_func)
def _recurser(expr, sub_dict):
# Decompose the expression into num, den
num, den = _fraction_decomp(expr)
if den != 1:
# If there is a non trivial denominator, we need to handle it
denom_subbed = _recurser(den, sub_dict)
if denom_subbed.evalf() == 0:
# If denom is 0 after this, attempt to simplify the bad expr
expr = simplify(expr)
else:
# Expression won't result in nan, find numerator
num_subbed = _recurser(num, sub_dict)
return num_subbed / denom_subbed
# We have to crawl the tree manually, because `expr` may have been
# modified in the simplify step. First, perform subs as normal:
val = _sub_func(expr, sub_dict)
if val is not None:
return val
new_args = (_recurser(arg, sub_dict) for arg in expr.args)
return expr.func(*new_args)
return _recurser(expr, sub_dict)
def _fraction_decomp(expr):
"""Return num, den such that expr = num/den"""
if not isinstance(expr, Mul):
return expr, 1
num = []
den = []
for a in expr.args:
if a.is_Pow and a.args[1] < 0:
den.append(1 / a)
else:
num.append(a)
if not den:
return expr, 1
num = Mul(*num)
den = Mul(*den)
return num, den
def _f_list_parser(fl, ref_frame):
"""Parses the provided forcelist composed of items
of the form (obj, force).
Returns a tuple containing:
vel_list: The velocity (ang_vel for Frames, vel for Points) in
the provided reference frame.
f_list: The forces.
Used internally in the KanesMethod and LagrangesMethod classes.
"""
def flist_iter():
for pair in fl:
obj, force = pair
if isinstance(obj, ReferenceFrame):
yield obj.ang_vel_in(ref_frame), force
elif isinstance(obj, Point):
yield obj.vel(ref_frame), force
else:
raise TypeError('First entry in each forcelist pair must '
'be a point or frame.')
if not fl:
vel_list, f_list = (), ()
else:
unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
vel_list, f_list = unzip(list(flist_iter()))
return vel_list, f_list
|
c6cf30ea9625cb8bbda4d95be0430bdd87bd05aa762d0968fa2bdf4546d68220 | # coding=utf-8
from abc import ABC, abstractmethod
from sympy.core.numbers import pi
from sympy.physics.mechanics.body import Body
from sympy.physics.vector import Vector, dynamicsymbols, cross
from sympy.physics.vector.frame import ReferenceFrame
import warnings
__all__ = ['Joint', 'PinJoint', 'PrismaticJoint']
class Joint(ABC):
"""Abstract base class for all specific joints.
Explanation
===========
A joint subtracts degrees of freedom from a body. This is the base class
for all specific joints and holds all common methods acting as an interface
for all joints. Custom joint can be created by inheriting Joint class and
defining all abstract functions.
The abstract methods are:
- ``_generate_coordinates``
- ``_generate_speeds``
- ``_orient_frames``
- ``_set_angular_velocity``
- ``_set_linar_velocity``
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: List of dynamicsymbols, optional
Generalized coordinates of the joint.
speeds : List of dynamicsymbols, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Notes
=====
The direction cosine matrix between the child and parent is formed using a
simple rotation about an axis that is normal to both ``child_axis`` and
``parent_axis``. In general, the normal axis is formed by crossing the
``child_axis`` into the ``parent_axis`` except if the child and parent axes
are in exactly opposite directions. In that case the rotation vector is chosen
using the rules in the following table where ``C`` is the child reference
frame and ``P`` is the parent reference frame:
.. list-table::
:header-rows: 1
* - ``child_axis``
- ``parent_axis``
- ``rotation_axis``
* - ``-C.x``
- ``P.x``
- ``P.z``
* - ``-C.y``
- ``P.y``
- ``P.x``
* - ``-C.z``
- ``P.z``
- ``P.y``
* - ``-C.x-C.y``
- ``P.x+P.y``
- ``P.z``
* - ``-C.y-C.z``
- ``P.y+P.z``
- ``P.x``
* - ``-C.x-C.z``
- ``P.x+P.z``
- ``P.y``
* - ``-C.x-C.y-C.z``
- ``P.x+P.y+P.z``
- ``(P.x+P.y+P.z) × P.x``
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_joint_pos=None, child_joint_pos=None, parent_axis=None,
child_axis=None):
if not isinstance(name, str):
raise TypeError('Supply a valid name.')
self._name = name
if not isinstance(parent, Body):
raise TypeError('Parent must be an instance of Body.')
self._parent = parent
if not isinstance(child, Body):
raise TypeError('Parent must be an instance of Body.')
self._child = child
self._coordinates = self._generate_coordinates(coordinates)
self._speeds = self._generate_speeds(speeds)
self._kdes = self._generate_kdes()
self._parent_axis = self._axis(parent, parent_axis)
self._child_axis = self._axis(child, child_axis)
self._parent_point = self._locate_joint_pos(parent, parent_joint_pos)
self._child_point = self._locate_joint_pos(child, child_joint_pos)
self._orient_frames()
self._set_angular_velocity()
self._set_linear_velocity()
def __str__(self):
return self.name
def __repr__(self):
return self.__str__()
@property
def name(self):
return self._name
@property
def parent(self):
"""Parent body of Joint."""
return self._parent
@property
def child(self):
"""Child body of Joint."""
return self._child
@property
def coordinates(self):
"""List generalized coordinates of the joint."""
return self._coordinates
@property
def speeds(self):
"""List generalized coordinates of the joint.."""
return self._speeds
@property
def kdes(self):
"""Kinematical differential equations of the joint."""
return self._kdes
@property
def parent_axis(self):
"""The axis of parent frame."""
return self._parent_axis
@property
def child_axis(self):
"""The axis of child frame."""
return self._child_axis
@property
def parent_point(self):
"""The joint's point where parent body is connected to the joint."""
return self._parent_point
@property
def child_point(self):
"""The joint's point where child body is connected to the joint."""
return self._child_point
@abstractmethod
def _generate_coordinates(self, coordinates):
"""Generate list generalized coordinates of the joint."""
pass
@abstractmethod
def _generate_speeds(self, speeds):
"""Generate list generalized speeds of the joint."""
pass
@abstractmethod
def _orient_frames(self):
"""Orient frames as per the joint."""
pass
@abstractmethod
def _set_angular_velocity(self):
pass
@abstractmethod
def _set_linear_velocity(self):
pass
def _generate_kdes(self):
kdes = []
t = dynamicsymbols._t
for i in range(len(self.coordinates)):
kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
return kdes
def _axis(self, body, ax):
if ax is None:
ax = body.frame.x
return ax
if not isinstance(ax, Vector):
raise TypeError("Axis must be of type Vector.")
if not ax.dt(body.frame) == 0:
msg = ('Axis cannot be time-varying when viewed from the '
'associated body.')
raise ValueError(msg)
return ax
def _locate_joint_pos(self, body, joint_pos):
if joint_pos is None:
joint_pos = Vector(0)
if not isinstance(joint_pos, Vector):
raise ValueError('Joint Position must be supplied as Vector.')
if not joint_pos.dt(body.frame) == 0:
msg = ('Position Vector cannot be time-varying when viewed from '
'the associated body.')
raise ValueError(msg)
point_name = self._name + '_' + body.name + '_joint'
return body.masscenter.locatenew(point_name, joint_pos)
def _alignment_rotation(self, parent, child):
# Returns the axis and angle between two axis(vectors).
angle = parent.angle_between(child)
axis = cross(child, parent).normalize()
return angle, axis
def _generate_vector(self):
parent_frame = self.parent.frame
components = self.parent_axis.to_matrix(parent_frame)
x, y, z = components[0], components[1], components[2]
if x != 0:
if y!=0:
if z!=0:
return cross(self.parent_axis,
parent_frame.x)
if z!=0:
return parent_frame.y
return parent_frame.z
if x == 0:
if y!=0:
if z!=0:
return parent_frame.x
return parent_frame.x
return parent_frame.y
def _set_orientation(self):
#Helper method for `orient_axis()`
self.child.frame.orient_axis(self.parent.frame, self.parent_axis, 0)
angle, axis = self._alignment_rotation(self.parent_axis,
self.child_axis)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
if axis != Vector(0) or angle == pi:
if angle == pi:
axis = self._generate_vector()
int_frame = ReferenceFrame('int_frame')
int_frame.orient_axis(self.child.frame, self.child_axis, 0)
int_frame.orient_axis(self.parent.frame, axis, angle)
return int_frame
return self.parent.frame
class PinJoint(Joint):
"""Pin (Revolute) Joint.
Explanation
===========
A pin joint is defined such that the joint rotation axis is fixed in both
the child and parent and the location of the joint is relative to the mass
center of each body. The child rotates an angle, θ, from the parent about
the rotation axis and has a simple angular speed, ω, relative to the
parent. The direction cosine matrix between the child and parent is formed
using a simple rotation about an axis that is normal to both ``child_axis``
and ``parent_axis``, see the Notes section for a detailed explanation of
this.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint.
speeds : dynamicsymbol, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Examples
=========
A single pin joint is created from two bodies and has the following basic
attributes:
>>> from sympy.physics.mechanics import Body, PinJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PinJoint('PC', parent, child)
>>> joint
PinJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
PC_P_joint
>>> joint.child_point
PC_C_joint
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
[theta_PC(t)]
>>> joint.speeds
[omega_PC(t)]
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
omega_PC(t)*P_frame.x
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, cos(theta_PC(t)), sin(theta_PC(t))],
[0, -sin(theta_PC(t)), cos(theta_PC(t))]])
>>> joint.child_point.pos_from(joint.parent_point)
0
To further demonstrate the use of the pin joint, the kinematics of simple
double pendulum that rotates about the Z axis of each connected body can be
created as follows.
>>> from sympy import symbols, trigsimp
>>> from sympy.physics.mechanics import Body, PinJoint
>>> l1, l2 = symbols('l1 l2')
First create bodies to represent the fixed ceiling and one to represent
each pendulum bob.
>>> ceiling = Body('C')
>>> upper_bob = Body('U')
>>> lower_bob = Body('L')
The first joint will connect the upper bob to the ceiling by a distance of
``l1`` and the joint axis will be about the Z axis for each body.
>>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
... child_joint_pos=-l1*upper_bob.frame.x,
... parent_axis=ceiling.frame.z,
... child_axis=upper_bob.frame.z)
The second joint will connect the lower bob to the upper bob by a distance
of ``l2`` and the joint axis will also be about the Z axis for each body.
>>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
... child_joint_pos=-l2*lower_bob.frame.x,
... parent_axis=upper_bob.frame.z,
... child_axis=lower_bob.frame.z)
Once the joints are established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of pendulum link relative
to the ceiling are found:
>>> upper_bob.frame.dcm(ceiling.frame)
Matrix([
[ cos(theta_P1(t)), sin(theta_P1(t)), 0],
[-sin(theta_P1(t)), cos(theta_P1(t)), 0],
[ 0, 0, 1]])
>>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
Matrix([
[ cos(theta_P1(t) + theta_P2(t)), sin(theta_P1(t) + theta_P2(t)), 0],
[-sin(theta_P1(t) + theta_P2(t)), cos(theta_P1(t) + theta_P2(t)), 0],
[ 0, 0, 1]])
The position of the lower bob's masscenter is found with:
>>> lower_bob.masscenter.pos_from(ceiling.masscenter)
l1*U_frame.x + l2*L_frame.x
The angular velocities of the two pendulum links can be computed with
respect to the ceiling.
>>> upper_bob.frame.ang_vel_in(ceiling.frame)
omega_P1(t)*C_frame.z
>>> lower_bob.frame.ang_vel_in(ceiling.frame)
omega_P1(t)*C_frame.z + omega_P2(t)*U_frame.z
And finally, the linear velocities of the two pendulum bobs can be computed
with respect to the ceiling.
>>> upper_bob.masscenter.vel(ceiling.frame)
l1*omega_P1(t)*U_frame.y
>>> lower_bob.masscenter.vel(ceiling.frame)
l1*omega_P1(t)*U_frame.y + l2*(omega_P1(t) + omega_P2(t))*L_frame.y
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_joint_pos=None, child_joint_pos=None, parent_axis=None,
child_axis=None):
super().__init__(name, parent, child, coordinates, speeds,
parent_joint_pos, child_joint_pos, parent_axis,
child_axis)
def __str__(self):
return (f'PinJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
def _generate_coordinates(self, coordinate):
coordinates = []
if coordinate is None:
theta = dynamicsymbols('theta' + '_' + self._name)
coordinate = theta
coordinates.append(coordinate)
return coordinates
def _generate_speeds(self, speed):
speeds = []
if speed is None:
omega = dynamicsymbols('omega' + '_' + self._name)
speed = omega
speeds.append(speed)
return speeds
def _orient_frames(self):
frame = self._set_orientation()
self.child.frame.orient_axis(frame, self.parent_axis,
self.coordinates[0])
def _set_angular_velocity(self):
self.child.frame.set_ang_vel(self.parent.frame, self.speeds[0] *
self.parent_axis.normalize())
def _set_linear_velocity(self):
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.parent.frame, 0)
self.child_point.set_pos(self.parent_point, 0)
self.child.masscenter.v2pt_theory(self.parent.masscenter,
self.parent.frame, self.child.frame)
class PrismaticJoint(Joint):
"""Prismatic (Sliding) Joint.
Explanation
===========
It is defined such that the child body translates with respect to the parent
body along the body fixed parent axis. The location of the joint is defined
by two points in each body which coincides when the generalized coordinate is zero. The direction cosine matrix between
the child and parent is formed using a simple rotation about an axis that is normal to
both ``child_axis`` and ``parent_axis``, see the Notes section for a detailed explanation of
this.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint.
speeds : dynamicsymbol, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Examples
=========
A single prismatic joint is created from two bodies and has the following basic
attributes:
>>> from sympy.physics.mechanics import Body, PrismaticJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PrismaticJoint('PC', parent, child)
>>> joint
PrismaticJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
PC_P_joint
>>> joint.child_point
PC_C_joint
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
[x_PC(t)]
>>> joint.speeds
[v_PC(t)]
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
0
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> joint.child_point.pos_from(joint.parent_point)
x_PC(t)*P_frame.x
To further demonstrate the use of the prismatic joint, the kinematics of
two masses sliding, one moving relative to a fixed body and the other relative to the
moving body. about the X axis of each connected body can be created as follows.
>>> from sympy.physics.mechanics import PrismaticJoint, Body
First create bodies to represent the fixed ceiling and one to represent
a particle.
>>> wall = Body('W')
>>> Part1 = Body('P1')
>>> Part2 = Body('P2')
The first joint will connect the particle to the ceiling and the
joint axis will be about the X axis for each body.
>>> J1 = PrismaticJoint('J1', wall, Part1)
The second joint will connect the second particle to the first particle
and the joint axis will also be about the X axis for each body.
>>> J2 = PrismaticJoint('J2', Part1, Part2)
Once the joint is established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of Part relative
to the ceiling are found:
>>> Part1.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> Part2.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
The position of the particles' masscenter is found with:
>>> Part1.masscenter.pos_from(wall.masscenter)
x_J1(t)*W_frame.x
>>> Part2.masscenter.pos_from(wall.masscenter)
x_J1(t)*W_frame.x + x_J2(t)*P1_frame.x
The angular velocities of the two particle links can be computed with
respect to the ceiling.
>>> Part1.ang_vel_in(wall)
0
>>> Part2.ang_vel_in(wall)
0
And finally, the linear velocities of the two particles can be computed
with respect to the ceiling.
>>> Part1.masscenter_vel(wall)
v_J1(t)*W_frame.x
>>> Part2.masscenter.vel(wall.frame)
v_J1(t)*W_frame.x + v_J2(t)*P1_frame.x
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_joint_pos=None,
child_joint_pos=None, parent_axis=None, child_axis=None):
super().__init__(name, parent, child, coordinates, speeds, parent_joint_pos,
child_joint_pos, parent_axis, child_axis)
def __str__(self):
return (f'PrismaticJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
def _generate_coordinates(self, coordinate):
coordinates = []
if coordinate is None:
x = dynamicsymbols('x' + '_' + self._name)
coordinate = x
coordinates.append(coordinate)
return coordinates
def _generate_speeds(self, speed):
speeds = []
if speed is None:
y = dynamicsymbols('v' + '_' + self._name)
speed = y
speeds.append(speed)
return speeds
def _orient_frames(self):
frame = self._set_orientation()
self.child.frame.orient_axis(frame, self.parent_axis, 0)
def _set_angular_velocity(self):
self.child.frame.set_ang_vel(self.parent.frame, 0)
def _set_linear_velocity(self):
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child_point.set_pos(self.parent_point, self.coordinates[0] * self.parent_axis.normalize())
self.child_point.set_vel(self.parent.frame, self.speeds[0] * self.parent_axis.normalize())
self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * self.parent_axis.normalize())
|
cae60972d5efc4a73731b9f7d66d1f7433f005daf14ab61c05fb0e05d239bbef | __all__ = ['Linearizer']
from sympy.core.backend import Matrix, eye, zeros
from sympy.core.symbol import Dummy
from sympy.utilities.iterables import flatten
from sympy.physics.vector import dynamicsymbols
from sympy.physics.mechanics.functions import msubs
from collections import namedtuple
from collections.abc import Iterable
class Linearizer:
"""This object holds the general model form for a dynamic system.
This model is used for computing the linearized form of the system,
while properly dealing with constraints leading to dependent
coordinates and speeds.
Attributes
==========
f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
Matrices holding the general system form.
q, u, r : Matrix
Matrices holding the generalized coordinates, speeds, and
input vectors.
q_i, u_i : Matrix
Matrices of the independent generalized coordinates and speeds.
q_d, u_d : Matrix
Matrices of the dependent generalized coordinates and speeds.
perm_mat : Matrix
Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
"""
def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u,
q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None):
"""
Parameters
==========
f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
System of equations holding the general system form.
Supply empty array or Matrix if the parameter
doesn't exist.
q : array_like
The generalized coordinates.
u : array_like
The generalized speeds
q_i, u_i : array_like, optional
The independent generalized coordinates and speeds.
q_d, u_d : array_like, optional
The dependent generalized coordinates and speeds.
r : array_like, optional
The input variables.
lams : array_like, optional
The lagrange multipliers
"""
# Generalized equation form
self.f_0 = Matrix(f_0)
self.f_1 = Matrix(f_1)
self.f_2 = Matrix(f_2)
self.f_3 = Matrix(f_3)
self.f_4 = Matrix(f_4)
self.f_c = Matrix(f_c)
self.f_v = Matrix(f_v)
self.f_a = Matrix(f_a)
# Generalized equation variables
self.q = Matrix(q)
self.u = Matrix(u)
none_handler = lambda x: Matrix(x) if x else Matrix()
self.q_i = none_handler(q_i)
self.q_d = none_handler(q_d)
self.u_i = none_handler(u_i)
self.u_d = none_handler(u_d)
self.r = none_handler(r)
self.lams = none_handler(lams)
# Derivatives of generalized equation variables
self._qd = self.q.diff(dynamicsymbols._t)
self._ud = self.u.diff(dynamicsymbols._t)
# If the user doesn't actually use generalized variables, and the
# qd and u vectors have any intersecting variables, this can cause
# problems. We'll fix this with some hackery, and Dummy variables
dup_vars = set(self._qd).intersection(self.u)
self._qd_dup = Matrix([var if var not in dup_vars else Dummy()
for var in self._qd])
# Derive dimesion terms
l = len(self.f_c)
m = len(self.f_v)
n = len(self.q)
o = len(self.u)
s = len(self.r)
k = len(self.lams)
dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
self._dims = dims(l, m, n, o, s, k)
self._Pq = None
self._Pqi = None
self._Pqd = None
self._Pu = None
self._Pui = None
self._Pud = None
self._C_0 = None
self._C_1 = None
self._C_2 = None
self.perm_mat = None
self._setup_done = False
def _setup(self):
# Calculations here only need to be run once. They are moved out of
# the __init__ method to increase the speed of Linearizer creation.
self._form_permutation_matrices()
self._form_block_matrices()
self._form_coefficient_matrices()
self._setup_done = True
def _form_permutation_matrices(self):
"""Form the permutation matrices Pq and Pu."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Compute permutation matrices
if n != 0:
self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
if l > 0:
self._Pqi = self._Pq[:, :-l]
self._Pqd = self._Pq[:, -l:]
else:
self._Pqi = self._Pq
self._Pqd = Matrix()
if o != 0:
self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
if m > 0:
self._Pui = self._Pu[:, :-m]
self._Pud = self._Pu[:, -m:]
else:
self._Pui = self._Pu
self._Pud = Matrix()
# Compute combination permutation matrix for computing A and B
P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
if P_col1:
if P_col2:
self.perm_mat = P_col1.row_join(P_col2)
else:
self.perm_mat = P_col1
else:
self.perm_mat = P_col2
def _form_coefficient_matrices(self):
"""Form the coefficient matrices C_0, C_1, and C_2."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Build up the coefficient matrices C_0, C_1, and C_2
# If there are configuration constraints (l > 0), form C_0 as normal.
# If not, C_0 is I_(nxn). Note that this works even if n=0
if l > 0:
f_c_jac_q = self.f_c.jacobian(self.q)
self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q *
self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi
else:
self._C_0 = eye(n)
# If there are motion constraints (m > 0), form C_1 and C_2 as normal.
# If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
# o = 0.
if m > 0:
f_v_jac_u = self.f_v.jacobian(self.u)
temp = f_v_jac_u * self._Pud
if n != 0:
f_v_jac_q = self.f_v.jacobian(self.q)
self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q)
else:
self._C_1 = zeros(o, n)
self._C_2 = (eye(o) - self._Pud *
temp.LUsolve(f_v_jac_u)) * self._Pui
else:
self._C_1 = zeros(o, n)
self._C_2 = eye(o)
def _form_block_matrices(self):
"""Form the block matrices for composing M, A, and B."""
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Block Matrix Definitions. These are only defined if under certain
# conditions. If undefined, an empty matrix is used instead
if n != 0:
self._M_qq = self.f_0.jacobian(self._qd)
self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
else:
self._M_qq = Matrix()
self._A_qq = Matrix()
if n != 0 and m != 0:
self._M_uqc = self.f_a.jacobian(self._qd_dup)
self._A_uqc = -self.f_a.jacobian(self.q)
else:
self._M_uqc = Matrix()
self._A_uqc = Matrix()
if n != 0 and o - m + k != 0:
self._M_uqd = self.f_3.jacobian(self._qd_dup)
self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
else:
self._M_uqd = Matrix()
self._A_uqd = Matrix()
if o != 0 and m != 0:
self._M_uuc = self.f_a.jacobian(self._ud)
self._A_uuc = -self.f_a.jacobian(self.u)
else:
self._M_uuc = Matrix()
self._A_uuc = Matrix()
if o != 0 and o - m + k != 0:
self._M_uud = self.f_2.jacobian(self._ud)
self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
else:
self._M_uud = Matrix()
self._A_uud = Matrix()
if o != 0 and n != 0:
self._A_qu = -self.f_1.jacobian(self.u)
else:
self._A_qu = Matrix()
if k != 0 and o - m + k != 0:
self._M_uld = self.f_4.jacobian(self.lams)
else:
self._M_uld = Matrix()
if s != 0 and o - m + k != 0:
self._B_u = -self.f_3.jacobian(self.r)
else:
self._B_u = Matrix()
def linearize(self, op_point=None, A_and_B=False, simplify=False):
"""Linearize the system about the operating point. Note that
q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
These may be either symbolic or numeric.
Parameters
==========
op_point : dict or iterable of dicts, optional
Dictionary or iterable of dictionaries containing the operating
point conditions. These will be substituted in to the linearized
system before the linearization is complete. Leave blank if you
want a completely symbolic form. Note that any reduction in
symbols (whether substituted for numbers or expressions with a
common parameter) will result in faster runtime.
A_and_B : bool, optional
If A_and_B=False (default), (M, A, B) is returned for forming
[M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True,
(A, B) is returned for forming dx = [A]x + [B]r, where
x = [q_ind, u_ind]^T.
simplify : bool, optional
Determines if returned values are simplified before return.
For large expressions this may be time consuming. Default is False.
Potential Issues
================
Note that the process of solving with A_and_B=True is
computationally intensive if there are many symbolic parameters.
For this reason, it may be more desirable to use the default
A_and_B=False, returning M, A, and B. More values may then be
substituted in to these matrices later on. The state space form can
then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where
P = Linearizer.perm_mat.
"""
# Run the setup if needed:
if not self._setup_done:
self._setup()
# Compose dict of operating conditions
if isinstance(op_point, dict):
op_point_dict = op_point
elif isinstance(op_point, Iterable):
op_point_dict = {}
for op in op_point:
op_point_dict.update(op)
else:
op_point_dict = {}
# Extract dimension variables
l, m, n, o, s, k = self._dims
# Rename terms to shorten expressions
M_qq = self._M_qq
M_uqc = self._M_uqc
M_uqd = self._M_uqd
M_uuc = self._M_uuc
M_uud = self._M_uud
M_uld = self._M_uld
A_qq = self._A_qq
A_uqc = self._A_uqc
A_uqd = self._A_uqd
A_qu = self._A_qu
A_uuc = self._A_uuc
A_uud = self._A_uud
B_u = self._B_u
C_0 = self._C_0
C_1 = self._C_1
C_2 = self._C_2
# Build up Mass Matrix
# |M_qq 0_nxo 0_nxk|
# M = |M_uqc M_uuc 0_mxk|
# |M_uqd M_uud M_uld|
if o != 0:
col2 = Matrix([zeros(n, o), M_uuc, M_uud])
if k != 0:
col3 = Matrix([zeros(n + m, k), M_uld])
if n != 0:
col1 = Matrix([M_qq, M_uqc, M_uqd])
if o != 0 and k != 0:
M = col1.row_join(col2).row_join(col3)
elif o != 0:
M = col1.row_join(col2)
else:
M = col1
elif k != 0:
M = col2.row_join(col3)
else:
M = col2
M_eq = msubs(M, op_point_dict)
# Build up state coefficient matrix A
# |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
# A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
# |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
# Col 1 is only defined if n != 0
if n != 0:
r1c1 = A_qq
if o != 0:
r1c1 += (A_qu * C_1)
r1c1 = r1c1 * C_0
if m != 0:
r2c1 = A_uqc
if o != 0:
r2c1 += (A_uuc * C_1)
r2c1 = r2c1 * C_0
else:
r2c1 = Matrix()
if o - m + k != 0:
r3c1 = A_uqd
if o != 0:
r3c1 += (A_uud * C_1)
r3c1 = r3c1 * C_0
else:
r3c1 = Matrix()
col1 = Matrix([r1c1, r2c1, r3c1])
else:
col1 = Matrix()
# Col 2 is only defined if o != 0
if o != 0:
if n != 0:
r1c2 = A_qu * C_2
else:
r1c2 = Matrix()
if m != 0:
r2c2 = A_uuc * C_2
else:
r2c2 = Matrix()
if o - m + k != 0:
r3c2 = A_uud * C_2
else:
r3c2 = Matrix()
col2 = Matrix([r1c2, r2c2, r3c2])
else:
col2 = Matrix()
if col1:
if col2:
Amat = col1.row_join(col2)
else:
Amat = col1
else:
Amat = col2
Amat_eq = msubs(Amat, op_point_dict)
# Build up the B matrix if there are forcing variables
# |0_(n + m)xs|
# B = |B_u |
if s != 0 and o - m + k != 0:
Bmat = zeros(n + m, s).col_join(B_u)
Bmat_eq = msubs(Bmat, op_point_dict)
else:
Bmat_eq = Matrix()
# kwarg A_and_B indicates to return A, B for forming the equation
# dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
if A_and_B:
A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq)
if Bmat_eq:
B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq)
else:
# Bmat = Matrix([]), so no need to sub
B_cont = Bmat_eq
if simplify:
A_cont.simplify()
B_cont.simplify()
return A_cont, B_cont
# Otherwise return M, A, B for forming the equation
# [M]dx = [A]x + [B]r, where x = [q, u]^T
else:
if simplify:
M_eq.simplify()
Amat_eq.simplify()
Bmat_eq.simplify()
return M_eq, Amat_eq, Bmat_eq
def permutation_matrix(orig_vec, per_vec):
"""Compute the permutation matrix to change order of
orig_vec into order of per_vec.
Parameters
==========
orig_vec : array_like
Symbols in original ordering.
per_vec : array_like
Symbols in new ordering.
Returns
=======
p_matrix : Matrix
Permutation matrix such that orig_vec == (p_matrix * per_vec).
"""
if not isinstance(orig_vec, (list, tuple)):
orig_vec = flatten(orig_vec)
if not isinstance(per_vec, (list, tuple)):
per_vec = flatten(per_vec)
if set(orig_vec) != set(per_vec):
raise ValueError("orig_vec and per_vec must be the same length, " +
"and contain the same symbols.")
ind_list = [orig_vec.index(i) for i in per_vec]
p_matrix = zeros(len(orig_vec))
for i, j in enumerate(ind_list):
p_matrix[i, j] = 1
return p_matrix
|
458ac31d161caad5a1a4fb1987967f326b203355fffe3892bfef0fa2ee94ecac | from sympy.core.backend import diff, zeros, Matrix, eye, sympify
from sympy.core.sorting import default_sort_key
from sympy.physics.vector import dynamicsymbols, ReferenceFrame
from sympy.physics.mechanics.method import _Methods
from sympy.physics.mechanics.functions import (find_dynamicsymbols, msubs,
_f_list_parser)
from sympy.physics.mechanics.linearize import Linearizer
from sympy.utilities.iterables import iterable
__all__ = ['LagrangesMethod']
class LagrangesMethod(_Methods):
"""Lagrange's method object.
Explanation
===========
This object generates the equations of motion in a two step procedure. The
first step involves the initialization of LagrangesMethod by supplying the
Lagrangian and the generalized coordinates, at the bare minimum. If there
are any constraint equations, they can be supplied as keyword arguments.
The Lagrange multipliers are automatically generated and are equal in
number to the constraint equations. Similarly any non-conservative forces
can be supplied in an iterable (as described below and also shown in the
example) along with a ReferenceFrame. This is also discussed further in the
__init__ method.
Attributes
==========
q, u : Matrix
Matrices of the generalized coordinates and speeds
loads : iterable
Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
describing the forces on the system.
bodies : iterable
Iterable containing the rigid bodies and particles of the system.
mass_matrix : Matrix
The system's mass matrix
forcing : Matrix
The system's forcing vector
mass_matrix_full : Matrix
The "mass matrix" for the qdot's, qdoubledot's, and the
lagrange multipliers (lam)
forcing_full : Matrix
The forcing vector for the qdot's, qdoubledot's and
lagrange multipliers (lam)
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
In this example, we first need to do the kinematics.
This involves creating generalized coordinates and their derivatives.
Then we create a point and set its velocity in a frame.
>>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian
>>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point
>>> from sympy.physics.mechanics import dynamicsymbols
>>> from sympy import symbols
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> m, k, b = symbols('m k b')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, qd * N.x)
We need to then prepare the information as required by LagrangesMethod to
generate equations of motion.
First we create the Particle, which has a point attached to it.
Following this the lagrangian is created from the kinetic and potential
energies.
Then, an iterable of nonconservative forces/torques must be constructed,
where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple,
with the Vectors representing the nonconservative forces or torques.
>>> Pa = Particle('Pa', P, m)
>>> Pa.potential_energy = k * q**2 / 2.0
>>> L = Lagrangian(N, Pa)
>>> fl = [(P, -b * qd * N.x)]
Finally we can generate the equations of motion.
First we create the LagrangesMethod object. To do this one must supply
the Lagrangian, and the generalized coordinates. The constraint equations,
the forcelist, and the inertial frame may also be provided, if relevant.
Next we generate Lagrange's equations of motion, such that:
Lagrange's equations of motion = 0.
We have the equations of motion at this point.
>>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N)
>>> print(l.form_lagranges_equations())
Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]])
We can also solve for the states using the 'rhs' method.
>>> print(l.rhs())
Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]])
Please refer to the docstrings on each method for more details.
"""
def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None,
hol_coneqs=None, nonhol_coneqs=None):
"""Supply the following for the initialization of LagrangesMethod.
Lagrangian : Sympifyable
qs : array_like
The generalized coordinates
hol_coneqs : array_like, optional
The holonomic constraint equations
nonhol_coneqs : array_like, optional
The nonholonomic constraint equations
forcelist : iterable, optional
Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector)
tuples which represent the force at a point or torque on a frame.
This feature is primarily to account for the nonconservative forces
and/or moments.
bodies : iterable, optional
Takes an iterable containing the rigid bodies and particles of the
system.
frame : ReferenceFrame, optional
Supply the inertial frame. This is used to determine the
generalized forces due to non-conservative forces.
"""
self._L = Matrix([sympify(Lagrangian)])
self.eom = None
self._m_cd = Matrix() # Mass Matrix of differentiated coneqs
self._m_d = Matrix() # Mass Matrix of dynamic equations
self._f_cd = Matrix() # Forcing part of the diff coneqs
self._f_d = Matrix() # Forcing part of the dynamic equations
self.lam_coeffs = Matrix() # The coeffecients of the multipliers
forcelist = forcelist if forcelist else []
if not iterable(forcelist):
raise TypeError('Force pairs must be supplied in an iterable.')
self._forcelist = forcelist
if frame and not isinstance(frame, ReferenceFrame):
raise TypeError('frame must be a valid ReferenceFrame')
self._bodies = bodies
self.inertial = frame
self.lam_vec = Matrix()
self._term1 = Matrix()
self._term2 = Matrix()
self._term3 = Matrix()
self._term4 = Matrix()
# Creating the qs, qdots and qdoubledots
if not iterable(qs):
raise TypeError('Generalized coordinates must be an iterable')
self._q = Matrix(qs)
self._qdots = self.q.diff(dynamicsymbols._t)
self._qdoubledots = self._qdots.diff(dynamicsymbols._t)
mat_build = lambda x: Matrix(x) if x else Matrix()
hol_coneqs = mat_build(hol_coneqs)
nonhol_coneqs = mat_build(nonhol_coneqs)
self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t),
nonhol_coneqs])
self._hol_coneqs = hol_coneqs
def form_lagranges_equations(self):
"""Method to form Lagrange's equations of motion.
Returns a vector of equations of motion using Lagrange's equations of
the second kind.
"""
qds = self._qdots
qdd_zero = {i: 0 for i in self._qdoubledots}
n = len(self.q)
# Internally we represent the EOM as four terms:
# EOM = term1 - term2 - term3 - term4 = 0
# First term
self._term1 = self._L.jacobian(qds)
self._term1 = self._term1.diff(dynamicsymbols._t).T
# Second term
self._term2 = self._L.jacobian(self.q).T
# Third term
if self.coneqs:
coneqs = self.coneqs
m = len(coneqs)
# Creating the multipliers
self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1)))
self.lam_coeffs = -coneqs.jacobian(qds)
self._term3 = self.lam_coeffs.T * self.lam_vec
# Extracting the coeffecients of the qdds from the diff coneqs
diffconeqs = coneqs.diff(dynamicsymbols._t)
self._m_cd = diffconeqs.jacobian(self._qdoubledots)
# The remaining terms i.e. the 'forcing' terms in diff coneqs
self._f_cd = -diffconeqs.subs(qdd_zero)
else:
self._term3 = zeros(n, 1)
# Fourth term
if self.forcelist:
N = self.inertial
self._term4 = zeros(n, 1)
for i, qd in enumerate(qds):
flist = zip(*_f_list_parser(self.forcelist, N))
self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist)
else:
self._term4 = zeros(n, 1)
# Form the dynamic mass and forcing matrices
without_lam = self._term1 - self._term2 - self._term4
self._m_d = without_lam.jacobian(self._qdoubledots)
self._f_d = -without_lam.subs(qdd_zero)
# Form the EOM
self.eom = without_lam - self._term3
return self.eom
def _form_eoms(self):
return self.form_lagranges_equations()
@property
def mass_matrix(self):
"""Returns the mass matrix, which is augmented by the Lagrange
multipliers, if necessary.
Explanation
===========
If the system is described by 'n' generalized coordinates and there are
no constraint equations then an n X n matrix is returned.
If there are 'n' generalized coordinates and 'm' constraint equations
have been supplied during initialization then an n X (n+m) matrix is
returned. The (n + m - 1)th and (n + m)th columns contain the
coefficients of the Lagrange multipliers.
"""
if self.eom is None:
raise ValueError('Need to compute the equations of motion first')
if self.coneqs:
return (self._m_d).row_join(self.lam_coeffs.T)
else:
return self._m_d
@property
def mass_matrix_full(self):
"""Augments the coefficients of qdots to the mass_matrix."""
if self.eom is None:
raise ValueError('Need to compute the equations of motion first')
n = len(self.q)
m = len(self.coneqs)
row1 = eye(n).row_join(zeros(n, n + m))
row2 = zeros(n, n).row_join(self.mass_matrix)
if self.coneqs:
row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m))
return row1.col_join(row2).col_join(row3)
else:
return row1.col_join(row2)
@property
def forcing(self):
"""Returns the forcing vector from 'lagranges_equations' method."""
if self.eom is None:
raise ValueError('Need to compute the equations of motion first')
return self._f_d
@property
def forcing_full(self):
"""Augments qdots to the forcing vector above."""
if self.eom is None:
raise ValueError('Need to compute the equations of motion first')
if self.coneqs:
return self._qdots.col_join(self.forcing).col_join(self._f_cd)
else:
return self._qdots.col_join(self.forcing)
def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None):
"""Returns an instance of the Linearizer class, initiated from the
data in the LagrangesMethod class. This may be more desirable than using
the linearize class method, as the Linearizer object will allow more
efficient recalculation (i.e. about varying operating points).
Parameters
==========
q_ind, qd_ind : array_like, optional
The independent generalized coordinates and speeds.
q_dep, qd_dep : array_like, optional
The dependent generalized coordinates and speeds.
"""
# Compose vectors
t = dynamicsymbols._t
q = self.q
u = self._qdots
ud = u.diff(t)
# Get vector of lagrange multipliers
lams = self.lam_vec
mat_build = lambda x: Matrix(x) if x else Matrix()
q_i = mat_build(q_ind)
q_d = mat_build(q_dep)
u_i = mat_build(qd_ind)
u_d = mat_build(qd_dep)
# Compose general form equations
f_c = self._hol_coneqs
f_v = self.coneqs
f_a = f_v.diff(t)
f_0 = u
f_1 = -u
f_2 = self._term1
f_3 = -(self._term2 + self._term4)
f_4 = -self._term3
# Check that there are an appropriate number of independent and
# dependent coordinates
if len(q_d) != len(f_c) or len(u_d) != len(f_v):
raise ValueError(("Must supply {:} dependent coordinates, and " +
"{:} dependent speeds").format(len(f_c), len(f_v)))
if set(Matrix([q_i, q_d])) != set(q):
raise ValueError("Must partition q into q_ind and q_dep, with " +
"no extra or missing symbols.")
if set(Matrix([u_i, u_d])) != set(u):
raise ValueError("Must partition qd into qd_ind and qd_dep, " +
"with no extra or missing symbols.")
# Find all other dynamic symbols, forming the forcing vector r.
# Sort r to make it canonical.
insyms = set(Matrix([q, u, ud, lams]))
r = list(find_dynamicsymbols(f_3, insyms))
r.sort(key=default_sort_key)
# Check for any derivatives of variables in r that are also found in r.
for i in r:
if diff(i, dynamicsymbols._t) in r:
raise ValueError('Cannot have derivatives of specified \
quantities when linearizing forcing terms.')
return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
q_d, u_i, u_d, r, lams)
def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None,
**kwargs):
"""Linearize the equations of motion about a symbolic operating point.
Explanation
===========
If kwarg A_and_B is False (default), returns M, A, B, r for the
linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
If kwarg A_and_B is True, returns A, B, r for the linearized form
dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
computationally intensive if there are many symbolic parameters. For
this reason, it may be more desirable to use the default A_and_B=False,
returning M, A, and B. Values may then be substituted in to these
matrices, and the state space form found as
A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
In both cases, r is found as all dynamicsymbols in the equations of
motion that are not part of q, u, q', or u'. They are sorted in
canonical form.
The operating points may be also entered using the ``op_point`` kwarg.
This takes a dictionary of {symbol: value}, or a an iterable of such
dictionaries. The values may be numeric or symbolic. The more values
you can specify beforehand, the faster this computation will run.
For more documentation, please see the ``Linearizer`` class."""
linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep)
result = linearizer.linearize(**kwargs)
return result + (linearizer.r,)
def solve_multipliers(self, op_point=None, sol_type='dict'):
"""Solves for the values of the lagrange multipliers symbolically at
the specified operating point.
Parameters
==========
op_point : dict or iterable of dicts, optional
Point at which to solve at. The operating point is specified as
a dictionary or iterable of dictionaries of {symbol: value}. The
value may be numeric or symbolic itself.
sol_type : str, optional
Solution return type. Valid options are:
- 'dict': A dict of {symbol : value} (default)
- 'Matrix': An ordered column matrix of the solution
"""
# Determine number of multipliers
k = len(self.lam_vec)
if k == 0:
raise ValueError("System has no lagrange multipliers to solve for.")
# Compose dict of operating conditions
if isinstance(op_point, dict):
op_point_dict = op_point
elif iterable(op_point):
op_point_dict = {}
for op in op_point:
op_point_dict.update(op)
elif op_point is None:
op_point_dict = {}
else:
raise TypeError("op_point must be either a dictionary or an "
"iterable of dictionaries.")
# Compose the system to be solved
mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join(
zeros(k, k)))
force_matrix = self.forcing.col_join(self._f_cd)
# Sub in the operating point
mass_matrix = msubs(mass_matrix, op_point_dict)
force_matrix = msubs(force_matrix, op_point_dict)
# Solve for the multipliers
sol_list = mass_matrix.LUsolve(-force_matrix)[-k:]
if sol_type == 'dict':
return dict(zip(self.lam_vec, sol_list))
elif sol_type == 'Matrix':
return Matrix(sol_list)
else:
raise ValueError("Unknown sol_type {:}.".format(sol_type))
def rhs(self, inv_method=None, **kwargs):
"""Returns equations that can be solved numerically.
Parameters
==========
inv_method : str
The specific sympy inverse matrix calculation method to use. For a
list of valid methods, see
:meth:`~sympy.matrices.matrices.MatrixBase.inv`
"""
if inv_method is None:
self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full)
else:
self._rhs = (self.mass_matrix_full.inv(inv_method,
try_block_diag=True) * self.forcing_full)
return self._rhs
@property
def q(self):
return self._q
@property
def u(self):
return self._qdots
@property
def bodies(self):
return self._bodies
@property
def forcelist(self):
return self._forcelist
@property
def loads(self):
return self._forcelist
|
230b0a6986512880df95338a084e9f8df27abadf8cccf7e3b5c191710a8a027e | # isort:skip_file
"""
Dimensional analysis and unit systems.
This module defines dimension/unit systems and physical quantities. It is
based on a group-theoretical construction where dimensions are represented as
vectors (coefficients being the exponents), and units are defined as a dimension
to which we added a scale.
Quantities are built from a factor and a unit, and are the basic objects that
one will use when doing computations.
All objects except systems and prefixes can be used in SymPy expressions.
Note that as part of a CAS, various objects do not combine automatically
under operations.
Details about the implementation can be found in the documentation, and we
will not repeat all the explanations we gave there concerning our approach.
Ideas about future developments can be found on the `Github wiki
<https://github.com/sympy/sympy/wiki/Unit-systems>`_, and you should consult
this page if you are willing to help.
Useful functions:
- ``find_unit``: easily lookup pre-defined units.
- ``convert_to(expr, newunit)``: converts an expression into the same
expression expressed in another unit.
"""
from .dimensions import Dimension, DimensionSystem
from .unitsystem import UnitSystem
from .util import convert_to
from .quantities import Quantity
from .definitions.dimension_definitions import (
amount_of_substance, acceleration, action,
capacitance, charge, conductance, current, energy,
force, frequency, impedance, inductance, length,
luminous_intensity, magnetic_density,
magnetic_flux, mass, momentum, power, pressure, temperature, time,
velocity, voltage, volume
)
Unit = Quantity
speed = velocity
luminosity = luminous_intensity
magnetic_flux_density = magnetic_density
amount = amount_of_substance
from .prefixes import (
# 10-power based:
yotta,
zetta,
exa,
peta,
tera,
giga,
mega,
kilo,
hecto,
deca,
deci,
centi,
milli,
micro,
nano,
pico,
femto,
atto,
zepto,
yocto,
# 2-power based:
kibi,
mebi,
gibi,
tebi,
pebi,
exbi,
)
from .definitions import (
percent, percents,
permille,
rad, radian, radians,
deg, degree, degrees,
sr, steradian, steradians,
mil, angular_mil, angular_mils,
m, meter, meters,
kg, kilogram, kilograms,
s, second, seconds,
A, ampere, amperes,
K, kelvin, kelvins,
mol, mole, moles,
cd, candela, candelas,
g, gram, grams,
mg, milligram, milligrams,
ug, microgram, micrograms,
newton, newtons, N,
joule, joules, J,
watt, watts, W,
pascal, pascals, Pa, pa,
hertz, hz, Hz,
coulomb, coulombs, C,
volt, volts, v, V,
ohm, ohms,
siemens, S, mho, mhos,
farad, farads, F,
henry, henrys, H,
tesla, teslas, T,
weber, webers, Wb, wb,
optical_power, dioptre, D,
lux, lx,
katal, kat,
gray, Gy,
becquerel, Bq,
km, kilometer, kilometers,
dm, decimeter, decimeters,
cm, centimeter, centimeters,
mm, millimeter, millimeters,
um, micrometer, micrometers, micron, microns,
nm, nanometer, nanometers,
pm, picometer, picometers,
ft, foot, feet,
inch, inches,
yd, yard, yards,
mi, mile, miles,
nmi, nautical_mile, nautical_miles,
l, liter, liters,
dl, deciliter, deciliters,
cl, centiliter, centiliters,
ml, milliliter, milliliters,
ms, millisecond, milliseconds,
us, microsecond, microseconds,
ns, nanosecond, nanoseconds,
ps, picosecond, picoseconds,
minute, minutes,
h, hour, hours,
day, days,
anomalistic_year, anomalistic_years,
sidereal_year, sidereal_years,
tropical_year, tropical_years,
common_year, common_years,
julian_year, julian_years,
draconic_year, draconic_years,
gaussian_year, gaussian_years,
full_moon_cycle, full_moon_cycles,
year, years,
G, gravitational_constant,
c, speed_of_light,
elementary_charge,
hbar,
planck,
eV, electronvolt, electronvolts,
avogadro_number,
avogadro, avogadro_constant,
boltzmann, boltzmann_constant,
stefan, stefan_boltzmann_constant,
R, molar_gas_constant,
faraday_constant,
josephson_constant,
von_klitzing_constant,
amu, amus, atomic_mass_unit, atomic_mass_constant,
gee, gees, acceleration_due_to_gravity,
u0, magnetic_constant, vacuum_permeability,
e0, electric_constant, vacuum_permittivity,
Z0, vacuum_impedance,
coulomb_constant, electric_force_constant,
atmosphere, atmospheres, atm,
kPa,
bar, bars,
pound, pounds,
psi,
dHg0,
mmHg, torr,
mmu, mmus, milli_mass_unit,
quart, quarts,
ly, lightyear, lightyears,
au, astronomical_unit, astronomical_units,
planck_mass,
planck_time,
planck_temperature,
planck_length,
planck_charge,
planck_area,
planck_volume,
planck_momentum,
planck_energy,
planck_force,
planck_power,
planck_density,
planck_energy_density,
planck_intensity,
planck_angular_frequency,
planck_pressure,
planck_current,
planck_voltage,
planck_impedance,
planck_acceleration,
bit, bits,
byte,
kibibyte, kibibytes,
mebibyte, mebibytes,
gibibyte, gibibytes,
tebibyte, tebibytes,
pebibyte, pebibytes,
exbibyte, exbibytes,
)
from .systems import (
mks, mksa, si
)
def find_unit(quantity, unit_system="SI"):
"""
Return a list of matching units or dimension names.
- If ``quantity`` is a string -- units/dimensions containing the string
`quantity`.
- If ``quantity`` is a unit or dimension -- units having matching base
units or dimensions.
Examples
========
>>> from sympy.physics import units as u
>>> u.find_unit('charge')
['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
>>> u.find_unit(u.charge)
['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
>>> u.find_unit("ampere")
['ampere', 'amperes']
>>> u.find_unit('volt')
['volt', 'volts', 'electronvolt', 'electronvolts', 'planck_voltage']
>>> u.find_unit(u.inch**3)[:5]
['l', 'cl', 'dl', 'ml', 'liter']
"""
unit_system = UnitSystem.get_unit_system(unit_system)
import sympy.physics.units as u
rv = []
if isinstance(quantity, str):
rv = [i for i in dir(u) if quantity in i and isinstance(getattr(u, i), Quantity)]
dim = getattr(u, quantity)
if isinstance(dim, Dimension):
rv.extend(find_unit(dim))
else:
for i in sorted(dir(u)):
other = getattr(u, i)
if not isinstance(other, Quantity):
continue
if isinstance(quantity, Quantity):
if quantity.dimension == other.dimension:
rv.append(str(i))
elif isinstance(quantity, Dimension):
if other.dimension == quantity:
rv.append(str(i))
elif other.dimension == Dimension(unit_system.get_dimensional_expr(quantity)):
rv.append(str(i))
return sorted(set(rv), key=lambda x: (len(x), x))
# NOTE: the old units module had additional variables:
# 'density', 'illuminance', 'resistance'.
# They were not dimensions, but units (old Unit class).
__all__ = [
'Dimension', 'DimensionSystem',
'UnitSystem',
'convert_to',
'Quantity',
'amount_of_substance', 'acceleration', 'action',
'capacitance', 'charge', 'conductance', 'current', 'energy',
'force', 'frequency', 'impedance', 'inductance', 'length',
'luminous_intensity', 'magnetic_density',
'magnetic_flux', 'mass', 'momentum', 'power', 'pressure', 'temperature', 'time',
'velocity', 'voltage', 'volume',
'Unit',
'speed',
'luminosity',
'magnetic_flux_density',
'amount',
'yotta',
'zetta',
'exa',
'peta',
'tera',
'giga',
'mega',
'kilo',
'hecto',
'deca',
'deci',
'centi',
'milli',
'micro',
'nano',
'pico',
'femto',
'atto',
'zepto',
'yocto',
'kibi',
'mebi',
'gibi',
'tebi',
'pebi',
'exbi',
'percent', 'percents',
'permille',
'rad', 'radian', 'radians',
'deg', 'degree', 'degrees',
'sr', 'steradian', 'steradians',
'mil', 'angular_mil', 'angular_mils',
'm', 'meter', 'meters',
'kg', 'kilogram', 'kilograms',
's', 'second', 'seconds',
'A', 'ampere', 'amperes',
'K', 'kelvin', 'kelvins',
'mol', 'mole', 'moles',
'cd', 'candela', 'candelas',
'g', 'gram', 'grams',
'mg', 'milligram', 'milligrams',
'ug', 'microgram', 'micrograms',
'newton', 'newtons', 'N',
'joule', 'joules', 'J',
'watt', 'watts', 'W',
'pascal', 'pascals', 'Pa', 'pa',
'hertz', 'hz', 'Hz',
'coulomb', 'coulombs', 'C',
'volt', 'volts', 'v', 'V',
'ohm', 'ohms',
'siemens', 'S', 'mho', 'mhos',
'farad', 'farads', 'F',
'henry', 'henrys', 'H',
'tesla', 'teslas', 'T',
'weber', 'webers', 'Wb', 'wb',
'optical_power', 'dioptre', 'D',
'lux', 'lx',
'katal', 'kat',
'gray', 'Gy',
'becquerel', 'Bq',
'km', 'kilometer', 'kilometers',
'dm', 'decimeter', 'decimeters',
'cm', 'centimeter', 'centimeters',
'mm', 'millimeter', 'millimeters',
'um', 'micrometer', 'micrometers', 'micron', 'microns',
'nm', 'nanometer', 'nanometers',
'pm', 'picometer', 'picometers',
'ft', 'foot', 'feet',
'inch', 'inches',
'yd', 'yard', 'yards',
'mi', 'mile', 'miles',
'nmi', 'nautical_mile', 'nautical_miles',
'l', 'liter', 'liters',
'dl', 'deciliter', 'deciliters',
'cl', 'centiliter', 'centiliters',
'ml', 'milliliter', 'milliliters',
'ms', 'millisecond', 'milliseconds',
'us', 'microsecond', 'microseconds',
'ns', 'nanosecond', 'nanoseconds',
'ps', 'picosecond', 'picoseconds',
'minute', 'minutes',
'h', 'hour', 'hours',
'day', 'days',
'anomalistic_year', 'anomalistic_years',
'sidereal_year', 'sidereal_years',
'tropical_year', 'tropical_years',
'common_year', 'common_years',
'julian_year', 'julian_years',
'draconic_year', 'draconic_years',
'gaussian_year', 'gaussian_years',
'full_moon_cycle', 'full_moon_cycles',
'year', 'years',
'G', 'gravitational_constant',
'c', 'speed_of_light',
'elementary_charge',
'hbar',
'planck',
'eV', 'electronvolt', 'electronvolts',
'avogadro_number',
'avogadro', 'avogadro_constant',
'boltzmann', 'boltzmann_constant',
'stefan', 'stefan_boltzmann_constant',
'R', 'molar_gas_constant',
'faraday_constant',
'josephson_constant',
'von_klitzing_constant',
'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant',
'gee', 'gees', 'acceleration_due_to_gravity',
'u0', 'magnetic_constant', 'vacuum_permeability',
'e0', 'electric_constant', 'vacuum_permittivity',
'Z0', 'vacuum_impedance',
'coulomb_constant', 'electric_force_constant',
'atmosphere', 'atmospheres', 'atm',
'kPa',
'bar', 'bars',
'pound', 'pounds',
'psi',
'dHg0',
'mmHg', 'torr',
'mmu', 'mmus', 'milli_mass_unit',
'quart', 'quarts',
'ly', 'lightyear', 'lightyears',
'au', 'astronomical_unit', 'astronomical_units',
'planck_mass',
'planck_time',
'planck_temperature',
'planck_length',
'planck_charge',
'planck_area',
'planck_volume',
'planck_momentum',
'planck_energy',
'planck_force',
'planck_power',
'planck_density',
'planck_energy_density',
'planck_intensity',
'planck_angular_frequency',
'planck_pressure',
'planck_current',
'planck_voltage',
'planck_impedance',
'planck_acceleration',
'bit', 'bits',
'byte',
'kibibyte', 'kibibytes',
'mebibyte', 'mebibytes',
'gibibyte', 'gibibytes',
'tebibyte', 'tebibytes',
'pebibyte', 'pebibytes',
'exbibyte', 'exbibytes',
'mks', 'mksa', 'si',
]
|
9dd4800a5d6255d8af5d4bfec5166467bf3099fedf1be2fd4188892410343cc4 | """
Unit system for physical quantities; include definition of constants.
"""
from typing import Dict as tDict
from sympy.core.add import Add
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.physics.units.dimensions import _QuantityMapper
from sympy.utilities.exceptions import SymPyDeprecationWarning
from .dimensions import Dimension
class UnitSystem(_QuantityMapper):
"""
UnitSystem represents a coherent set of units.
A unit system is basically a dimension system with notions of scales. Many
of the methods are defined in the same way.
It is much better if all base units have a symbol.
"""
_unit_systems = {} # type: tDict[str, UnitSystem]
def __init__(self, base_units, units=(), name="", descr="", dimension_system=None):
UnitSystem._unit_systems[name] = self
self.name = name
self.descr = descr
self._base_units = base_units
self._dimension_system = dimension_system
self._units = tuple(set(base_units) | set(units))
self._base_units = tuple(base_units)
super().__init__()
def __str__(self):
"""
Return the name of the system.
If it does not exist, then it makes a list of symbols (or names) of
the base dimensions.
"""
if self.name != "":
return self.name
else:
return "UnitSystem((%s))" % ", ".join(
str(d) for d in self._base_units)
def __repr__(self):
return '<UnitSystem: %s>' % repr(self._base_units)
def extend(self, base, units=(), name="", description="", dimension_system=None):
"""Extend the current system into a new one.
Take the base and normal units of the current system to merge
them to the base and normal units given in argument.
If not provided, name and description are overridden by empty strings.
"""
base = self._base_units + tuple(base)
units = self._units + tuple(units)
return UnitSystem(base, units, name, description, dimension_system)
def print_unit_base(self, unit):
"""
Useless method.
DO NOT USE, use instead ``convert_to``.
Give the string expression of a unit in term of the basis.
Units are displayed by decreasing power.
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="print_unit_base",
useinstead="convert_to",
).warn()
from sympy.physics.units import convert_to
return convert_to(unit, self._base_units)
def get_dimension_system(self):
return self._dimension_system
def get_quantity_dimension(self, unit):
qdm = self.get_dimension_system()._quantity_dimension_map
if unit in qdm:
return qdm[unit]
return super().get_quantity_dimension(unit)
def get_quantity_scale_factor(self, unit):
qsfm = self.get_dimension_system()._quantity_scale_factors
if unit in qsfm:
return qsfm[unit]
return super().get_quantity_scale_factor(unit)
@staticmethod
def get_unit_system(unit_system):
if isinstance(unit_system, UnitSystem):
return unit_system
if unit_system not in UnitSystem._unit_systems:
raise ValueError(
"Unit system is not supported. Currently"
"supported unit systems are {}".format(
", ".join(sorted(UnitSystem._unit_systems))
)
)
return UnitSystem._unit_systems[unit_system]
@staticmethod
def get_default_unit_system():
return UnitSystem._unit_systems["SI"]
@property
def dim(self):
"""
Give the dimension of the system.
That is return the number of units forming the basis.
"""
return len(self._base_units)
@property
def is_consistent(self):
"""
Check if the underlying dimension system is consistent.
"""
# test is performed in DimensionSystem
return self.get_dimension_system().is_consistent
def get_dimensional_expr(self, expr):
from sympy.physics.units import Quantity
if isinstance(expr, Mul):
return Mul(*[self.get_dimensional_expr(i) for i in expr.args])
elif isinstance(expr, Pow):
return self.get_dimensional_expr(expr.base) ** expr.exp
elif isinstance(expr, Add):
return self.get_dimensional_expr(expr.args[0])
elif isinstance(expr, Derivative):
dim = self.get_dimensional_expr(expr.expr)
for independent, count in expr.variable_count:
dim /= self.get_dimensional_expr(independent)**count
return dim
elif isinstance(expr, Function):
args = [self.get_dimensional_expr(arg) for arg in expr.args]
if all(i == 1 for i in args):
return S.One
return expr.func(*args)
elif isinstance(expr, Quantity):
return self.get_quantity_dimension(expr).name
return S.One
def _collect_factor_and_dimension(self, expr):
"""
Return tuple with scale factor expression and dimension expression.
"""
from sympy.physics.units import Quantity
if isinstance(expr, Quantity):
return expr.scale_factor, expr.dimension
elif isinstance(expr, Mul):
factor = 1
dimension = Dimension(1)
for arg in expr.args:
arg_factor, arg_dim = self._collect_factor_and_dimension(arg)
factor *= arg_factor
dimension *= arg_dim
return factor, dimension
elif isinstance(expr, Pow):
factor, dim = self._collect_factor_and_dimension(expr.base)
exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp)
if self.get_dimension_system().is_dimensionless(exp_dim):
exp_dim = 1
return factor ** exp_factor, dim ** (exp_factor * exp_dim)
elif isinstance(expr, Add):
factor, dim = self._collect_factor_and_dimension(expr.args[0])
for addend in expr.args[1:]:
addend_factor, addend_dim = \
self._collect_factor_and_dimension(addend)
if dim != addend_dim:
raise ValueError(
'Dimension of "{}" is {}, '
'but it should be {}'.format(
addend, addend_dim, dim))
factor += addend_factor
return factor, dim
elif isinstance(expr, Derivative):
factor, dim = self._collect_factor_and_dimension(expr.args[0])
for independent, count in expr.variable_count:
ifactor, idim = self._collect_factor_and_dimension(independent)
factor /= ifactor**count
dim /= idim**count
return factor, dim
elif isinstance(expr, Function):
fds = [self._collect_factor_and_dimension(
arg) for arg in expr.args]
return (expr.func(*(f[0] for f in fds)),
expr.func(*(d[1] for d in fds)))
elif isinstance(expr, Dimension):
return S.One, expr
else:
return expr, Dimension(1)
|
846310907a07cdcf50d7f22a176b7b7d850952b85c03b8b9a8a7d1152009db2c | """
Definition of physical dimensions.
Unit systems will be constructed on top of these dimensions.
Most of the examples in the doc use MKS system and are presented from the
computer point of view: from a human point, adding length to time is not legal
in MKS but it is in natural system; for a computer in natural system there is
no time dimension (but a velocity dimension instead) - in the basis - so the
question of adding time to length has no meaning.
"""
from typing import Dict as tDict
import collections
from functools import reduce
from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices.dense import Matrix
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.core.expr import Expr
from sympy.core.power import Pow
from sympy.utilities.exceptions import SymPyDeprecationWarning
class _QuantityMapper:
_quantity_scale_factors_global = {} # type: tDict[Expr, Expr]
_quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr]
_quantity_dimension_global = {} # type: tDict[Expr, Expr]
def __init__(self, *args, **kwargs):
self._quantity_dimension_map = {}
self._quantity_scale_factors = {}
def set_quantity_dimension(self, unit, dimension):
from sympy.physics.units import Quantity
dimension = sympify(dimension)
if not isinstance(dimension, Dimension):
if dimension == 1:
dimension = Dimension(1)
else:
raise ValueError("expected dimension or 1")
elif isinstance(dimension, Quantity):
dimension = self.get_quantity_dimension(dimension)
self._quantity_dimension_map[unit] = dimension
def set_quantity_scale_factor(self, unit, scale_factor):
from sympy.physics.units import Quantity
from sympy.physics.units.prefixes import Prefix
scale_factor = sympify(scale_factor)
# replace all prefixes by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Prefix),
lambda x: x.scale_factor
)
# replace all quantities by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Quantity),
lambda x: self.get_quantity_scale_factor(x)
)
self._quantity_scale_factors[unit] = scale_factor
def get_quantity_dimension(self, unit):
from sympy.physics.units import Quantity
# First look-up the local dimension map, then the global one:
if unit in self._quantity_dimension_map:
return self._quantity_dimension_map[unit]
if unit in self._quantity_dimension_global:
return self._quantity_dimension_global[unit]
if unit in self._quantity_dimensional_equivalence_map_global:
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
if isinstance(dep_unit, Quantity):
return self.get_quantity_dimension(dep_unit)
else:
return Dimension(self.get_dimensional_expr(dep_unit))
if isinstance(unit, Quantity):
return Dimension(unit.name)
else:
return Dimension(1)
def get_quantity_scale_factor(self, unit):
if unit in self._quantity_scale_factors:
return self._quantity_scale_factors[unit]
if unit in self._quantity_scale_factors_global:
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
return mul_factor*self.get_quantity_scale_factor(other_unit)
return S.One
class Dimension(Expr):
"""
This class represent the dimension of a physical quantities.
The ``Dimension`` constructor takes as parameters a name and an optional
symbol.
For example, in classical mechanics we know that time is different from
temperature and dimensions make this difference (but they do not provide
any measure of these quantites.
>>> from sympy.physics.units import Dimension
>>> length = Dimension('length')
>>> length
Dimension(length)
>>> time = Dimension('time')
>>> time
Dimension(time)
Dimensions can be composed using multiplication, division and
exponentiation (by a number) to give new dimensions. Addition and
subtraction is defined only when the two objects are the same dimension.
>>> velocity = length / time
>>> velocity
Dimension(length/time)
It is possible to use a dimension system object to get the dimensionsal
dependencies of a dimension, for example the dimension system used by the
SI units convention can be used:
>>> from sympy.physics.units.systems.si import dimsys_SI
>>> dimsys_SI.get_dimensional_dependencies(velocity)
{'length': 1, 'time': -1}
>>> length + length
Dimension(length)
>>> l2 = length**2
>>> l2
Dimension(length**2)
>>> dimsys_SI.get_dimensional_dependencies(l2)
{'length': 2}
"""
_op_priority = 13.0
# XXX: This doesn't seem to be used anywhere...
_dimensional_dependencies = dict() # type: ignore
is_commutative = True
is_number = False
# make sqrt(M**2) --> M
is_positive = True
is_real = True
def __new__(cls, name, symbol=None):
if isinstance(name, str):
name = Symbol(name)
else:
name = sympify(name)
if not isinstance(name, Expr):
raise TypeError("Dimension name needs to be a valid math expression")
if isinstance(symbol, str):
symbol = Symbol(symbol)
elif symbol is not None:
assert isinstance(symbol, Symbol)
if symbol is not None:
obj = Expr.__new__(cls, name, symbol)
else:
obj = Expr.__new__(cls, name)
obj._name = name
obj._symbol = symbol
return obj
@property
def name(self):
return self._name
@property
def symbol(self):
return self._symbol
def __hash__(self):
return Expr.__hash__(self)
def __eq__(self, other):
if isinstance(other, Dimension):
return self.name == other.name
return False
def __str__(self):
"""
Display the string representation of the dimension.
"""
if self.symbol is None:
return "Dimension(%s)" % (self.name)
else:
return "Dimension(%s, %s)" % (self.name, self.symbol)
def __repr__(self):
return self.__str__()
def __neg__(self):
return self
def __add__(self, other):
from sympy.physics.units.quantities import Quantity
other = sympify(other)
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension) and self == other:
return self
return super().__add__(other)
return self
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __rsub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __pow__(self, other):
return self._eval_power(other)
def _eval_power(self, other):
other = sympify(other)
return Dimension(self.name**other)
def __mul__(self, other):
from sympy.physics.units.quantities import Quantity
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension):
return Dimension(self.name*other.name)
if not other.free_symbols: # other.is_number cannot be used
return self
return super().__mul__(other)
return self
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return self*Pow(other, -1)
def __rtruediv__(self, other):
return other * pow(self, -1)
@classmethod
def _from_dimensional_dependencies(cls, dependencies):
return reduce(lambda x, y: x * y, (
Dimension(d)**e for d, e in dependencies.items()
), 1)
@classmethod
def _get_dimensional_dependencies_for_name(cls, name):
from sympy.physics.units.systems.si import dimsys_default
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="do not call from `Dimension` objects.",
useinstead="DimensionSystem"
).warn()
return dimsys_default.get_dimensional_dependencies(name)
@property
def is_dimensionless(self):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if self.name == 1:
return True
from sympy.physics.units.systems.si import dimsys_default
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="wrong class",
).warn()
dimensional_dependencies=dimsys_default
return dimensional_dependencies.get_dimensional_dependencies(self) == {}
def has_integer_powers(self, dim_sys):
"""
Check if the dimension object has only integer powers.
All the dimension powers should be integers, but rational powers may
appear in intermediate steps. This method may be used to check that the
final result is well-defined.
"""
return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
# Create dimensions according to the base units in MKSA.
# For other unit systems, they can be derived by transforming the base
# dimensional dependency dictionary.
class DimensionSystem(Basic, _QuantityMapper):
r"""
DimensionSystem represents a coherent set of dimensions.
The constructor takes three parameters:
- base dimensions;
- derived dimensions: these are defined in terms of the base dimensions
(for example velocity is defined from the division of length by time);
- dependency of dimensions: how the derived dimensions depend
on the base dimensions.
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
may be omitted.
"""
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}, name=None, descr=None):
dimensional_dependencies = dict(dimensional_dependencies)
if (name is not None) or (descr is not None):
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
useinstead="do not define a `name` or `descr`",
).warn()
def parse_dim(dim):
if isinstance(dim, str):
dim = Dimension(Symbol(dim))
elif isinstance(dim, Dimension):
pass
elif isinstance(dim, Symbol):
dim = Dimension(dim)
else:
raise TypeError("%s wrong type" % dim)
return dim
base_dims = [parse_dim(i) for i in base_dims]
derived_dims = [parse_dim(i) for i in derived_dims]
for dim in base_dims:
dim = dim.name
if (dim in dimensional_dependencies
and (len(dimensional_dependencies[dim]) != 1 or
dimensional_dependencies[dim].get(dim, None) != 1)):
raise IndexError("Repeated value in base dimensions")
dimensional_dependencies[dim] = Dict({dim: 1})
def parse_dim_name(dim):
if isinstance(dim, Dimension):
return dim.name
elif isinstance(dim, str):
return Symbol(dim)
elif isinstance(dim, Symbol):
return dim
else:
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
for dim in dimensional_dependencies.keys():
dim = parse_dim(dim)
if (dim not in derived_dims) and (dim not in base_dims):
derived_dims.append(dim)
def parse_dict(d):
return Dict({parse_dim_name(i): j for i, j in d.items()})
# Make sure everything is a SymPy type:
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
dimensional_dependencies.items()}
for dim in derived_dims:
if dim in base_dims:
raise ValueError("Dimension %s both in base and derived" % dim)
if dim.name not in dimensional_dependencies:
# TODO: should this raise a warning?
dimensional_dependencies[dim.name] = Dict({dim.name: 1})
base_dims.sort(key=default_sort_key)
derived_dims.sort(key=default_sort_key)
base_dims = Tuple(*base_dims)
derived_dims = Tuple(*derived_dims)
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
return obj
@property
def base_dims(self):
return self.args[0]
@property
def derived_dims(self):
return self.args[1]
@property
def dimensional_dependencies(self):
return self.args[2]
def _get_dimensional_dependencies_for_name(self, name):
if isinstance(name, Dimension):
name = name.name
if isinstance(name, str):
name = Symbol(name)
if name.is_Symbol:
# Dimensions not included in the dependencies are considered
# as base dimensions:
return dict(self.dimensional_dependencies.get(name, {name: 1}))
if name.is_number or name.is_NumberSymbol:
return {}
get_for_name = self._get_dimensional_dependencies_for_name
if name.is_Mul:
ret = collections.defaultdict(int)
dicts = [get_for_name(i) for i in name.args]
for d in dicts:
for k, v in d.items():
ret[k] += v
return {k: v for (k, v) in ret.items() if v != 0}
if name.is_Add:
dicts = [get_for_name(i) for i in name.args]
if all(d == dicts[0] for d in dicts[1:]):
return dicts[0]
raise TypeError("Only equivalent dimensions can be added or subtracted.")
if name.is_Pow:
dim_base = get_for_name(name.base)
dim_exp = get_for_name(name.exp)
if dim_exp == {} or name.exp.is_Symbol:
return {k: v*name.exp for (k, v) in dim_base.items()}
else:
raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
if name.is_Function:
args = (Dimension._from_dimensional_dependencies(
get_for_name(arg)) for arg in name.args)
result = name.func(*args)
dicts = [get_for_name(i) for i in name.args]
if isinstance(result, Dimension):
return self.get_dimensional_dependencies(result)
elif result.func == name.func:
if isinstance(name, TrigonometricFunction):
if dicts[0] in ({}, {Symbol('angle'): 1}):
return {}
else:
raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(name.func))
else:
if all( (item == {} for item in dicts) ):
return {}
else:
raise TypeError("The input arguments for the function {} must be dimensionless.".format(name.func))
else:
return get_for_name(result)
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(name)))
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
dimdep = self._get_dimensional_dependencies_for_name(name)
if mark_dimensionless and dimdep == {}:
return {'dimensionless': 1}
return {str(i): j for i, j in dimdep.items()}
def equivalent_dims(self, dim1, dim2):
deps1 = self.get_dimensional_dependencies(dim1)
deps2 = self.get_dimensional_dependencies(dim2)
return deps1 == deps2
def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None, name=None, description=None):
if (name is not None) or (description is not None):
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="name and descriptions of DimensionSystem",
useinstead="do not specify `name` or `description`",
).warn()
deps = dict(self.dimensional_dependencies)
if new_dim_deps:
deps.update(new_dim_deps)
new_dim_sys = DimensionSystem(
tuple(self.base_dims) + tuple(new_base_dims),
tuple(self.derived_dims) + tuple(new_derived_dims),
deps
)
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
return new_dim_sys
@staticmethod
def sort_dims(dims):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Sort dimensions given in argument using their str function.
This function will ensure that we get always the same tuple for a given
set of dimensions.
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="sort_dims",
useinstead="sorted(..., key=default_sort_key)",
).warn()
return tuple(sorted(dims, key=str))
def __getitem__(self, key):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Shortcut to the get_dim method, using key access.
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="the get [ ] operator",
useinstead="the dimension definition",
).warn()
d = self.get_dim(key)
#TODO: really want to raise an error?
if d is None:
raise KeyError(key)
return d
def __call__(self, unit):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Wrapper to the method print_dim_base
"""
SymPyDeprecationWarning(
deprecated_since_version="1.2",
issue=13336,
feature="call DimensionSystem",
useinstead="the dimension definition",
).warn()
return self.print_dim_base(unit)
def is_dimensionless(self, dimension):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if dimension.name == 1:
return True
return self.get_dimensional_dependencies(dimension) == {}
@property
def list_can_dims(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
List all canonical dimension names.
"""
dimset = set()
for i in self.base_dims:
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
return tuple(sorted(dimset, key=str))
@property
def inv_can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Compute the inverse transformation matrix from the base to the
canonical dimension basis.
It corresponds to the matrix where columns are the vector of base
dimensions in canonical basis.
This matrix will almost never be used because dimensions are always
defined with respect to the canonical basis, so no work has to be done
to get them in this basis. Nonetheless if this matrix is not square
(or not invertible) it means that we have chosen a bad basis.
"""
matrix = reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in self.base_dims])
return matrix
@property
def can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Return the canonical transformation matrix from the canonical to the
base dimension basis.
It is the inverse of the matrix computed with inv_can_transf_matrix().
"""
#TODO: the inversion will fail if the system is inconsistent, for
# example if the matrix is not a square
return reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
).inv()
def dim_can_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Dimensional representation in terms of the canonical base dimensions.
"""
vec = []
for d in self.list_can_dims:
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
return Matrix(vec)
def dim_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Vector representation in terms of the base dimensions.
"""
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
def print_dim_base(self, dim):
"""
Give the string expression of a dimension in term of the basis symbols.
"""
dims = self.dim_vector(dim)
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
res = S.One
for (s, p) in zip(symbols, dims):
res *= s**p
return res
@property
def dim(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Give the dimension of the system.
That is return the number of dimensions forming the basis.
"""
return len(self.base_dims)
@property
def is_consistent(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Check if the system is well defined.
"""
# not enough or too many base dimensions compared to independent
# dimensions
# in vector language: the set of vectors do not form a basis
return self.inv_can_transf_matrix.is_square
|
9b77514c8984bc46c5fac99e0ec47cea479e7887c2acb56ee7809f738336fee8 | """
Module defining unit prefixe class and some constants.
Constant dict for SI and binary prefixes are defined as PREFIXES and
BIN_PREFIXES.
"""
from sympy.core.expr import Expr
from sympy.core.sympify import sympify
class Prefix(Expr):
"""
This class represent prefixes, with their name, symbol and factor.
Prefixes are used to create derived units from a given unit. They should
always be encapsulated into units.
The factor is constructed from a base (default is 10) to some power, and
it gives the total multiple or fraction. For example the kilometer km
is constructed from the meter (factor 1) and the kilo (10 to the power 3,
i.e. 1000). The base can be changed to allow e.g. binary prefixes.
A prefix multiplied by something will always return the product of this
other object times the factor, except if the other object:
- is a prefix and they can be combined into a new prefix;
- defines multiplication with prefixes (which is the case for the Unit
class).
"""
_op_priority = 13.0
is_commutative = True
def __new__(cls, name, abbrev, exponent, base=sympify(10)):
name = sympify(name)
abbrev = sympify(abbrev)
exponent = sympify(exponent)
base = sympify(base)
obj = Expr.__new__(cls, name, abbrev, exponent, base)
obj._name = name
obj._abbrev = abbrev
obj._scale_factor = base**exponent
obj._exponent = exponent
obj._base = base
return obj
@property
def name(self):
return self._name
@property
def abbrev(self):
return self._abbrev
@property
def scale_factor(self):
return self._scale_factor
@property
def base(self):
return self._base
def __str__(self):
# TODO: add proper printers and tests:
if self.base == 10:
return "Prefix(%r, %r, %r)" % (
str(self.name), str(self.abbrev), self._exponent)
else:
return "Prefix(%r, %r, %r, %r)" % (
str(self.name), str(self.abbrev), self._exponent, self.base)
__repr__ = __str__
def __mul__(self, other):
from sympy.physics.units import Quantity
if not isinstance(other, (Quantity, Prefix)):
return super().__mul__(other)
fact = self.scale_factor * other.scale_factor
if fact == 1:
return 1
elif isinstance(other, Prefix):
# simplify prefix
for p in PREFIXES:
if PREFIXES[p].scale_factor == fact:
return PREFIXES[p]
return fact
return self.scale_factor * other
def __truediv__(self, other):
if not hasattr(other, "scale_factor"):
return super().__truediv__(other)
fact = self.scale_factor / other.scale_factor
if fact == 1:
return 1
elif isinstance(other, Prefix):
for p in PREFIXES:
if PREFIXES[p].scale_factor == fact:
return PREFIXES[p]
return fact
return self.scale_factor / other
def __rtruediv__(self, other):
if other == 1:
for p in PREFIXES:
if PREFIXES[p].scale_factor == 1 / self.scale_factor:
return PREFIXES[p]
return other / self.scale_factor
def prefix_unit(unit, prefixes):
"""
Return a list of all units formed by unit and the given prefixes.
You can use the predefined PREFIXES or BIN_PREFIXES, but you can also
pass as argument a subdict of them if you don't want all prefixed units.
>>> from sympy.physics.units.prefixes import (PREFIXES,
... prefix_unit)
>>> from sympy.physics.units import m
>>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
>>> prefix_unit(m, pref) # doctest: +SKIP
[millimeter, centimeter, decimeter]
"""
from sympy.physics.units.quantities import Quantity
from sympy.physics.units import UnitSystem
prefixed_units = []
for prefix_abbr, prefix in prefixes.items():
quantity = Quantity(
"%s%s" % (prefix.name, unit.name),
abbrev=("%s%s" % (prefix.abbrev, unit.abbrev))
)
UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit
UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit)
prefixed_units.append(quantity)
return prefixed_units
yotta = Prefix('yotta', 'Y', 24)
zetta = Prefix('zetta', 'Z', 21)
exa = Prefix('exa', 'E', 18)
peta = Prefix('peta', 'P', 15)
tera = Prefix('tera', 'T', 12)
giga = Prefix('giga', 'G', 9)
mega = Prefix('mega', 'M', 6)
kilo = Prefix('kilo', 'k', 3)
hecto = Prefix('hecto', 'h', 2)
deca = Prefix('deca', 'da', 1)
deci = Prefix('deci', 'd', -1)
centi = Prefix('centi', 'c', -2)
milli = Prefix('milli', 'm', -3)
micro = Prefix('micro', 'mu', -6)
nano = Prefix('nano', 'n', -9)
pico = Prefix('pico', 'p', -12)
femto = Prefix('femto', 'f', -15)
atto = Prefix('atto', 'a', -18)
zepto = Prefix('zepto', 'z', -21)
yocto = Prefix('yocto', 'y', -24)
# http://physics.nist.gov/cuu/Units/prefixes.html
PREFIXES = {
'Y': yotta,
'Z': zetta,
'E': exa,
'P': peta,
'T': tera,
'G': giga,
'M': mega,
'k': kilo,
'h': hecto,
'da': deca,
'd': deci,
'c': centi,
'm': milli,
'mu': micro,
'n': nano,
'p': pico,
'f': femto,
'a': atto,
'z': zepto,
'y': yocto,
}
kibi = Prefix('kibi', 'Y', 10, 2)
mebi = Prefix('mebi', 'Y', 20, 2)
gibi = Prefix('gibi', 'Y', 30, 2)
tebi = Prefix('tebi', 'Y', 40, 2)
pebi = Prefix('pebi', 'Y', 50, 2)
exbi = Prefix('exbi', 'Y', 60, 2)
# http://physics.nist.gov/cuu/Units/binary.html
BIN_PREFIXES = {
'Ki': kibi,
'Mi': mebi,
'Gi': gibi,
'Ti': tebi,
'Pi': pebi,
'Ei': exbi,
}
|
0d978e0cc246d686efaca1a5eea85b772c24510bca3fe23364f953c1996790fd | """
Several methods to simplify expressions involving unit objects.
"""
from functools import reduce
from collections.abc import Iterable
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.sorting import ordered
from sympy.core.sympify import sympify
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.physics.units.dimensions import Dimension
from sympy.physics.units.prefixes import Prefix
from sympy.physics.units.quantities import Quantity
from sympy.utilities.iterables import sift
def _get_conversion_matrix_for_expr(expr, target_units, unit_system):
from sympy.matrices.dense import Matrix
dimension_system = unit_system.get_dimension_system()
expr_dim = Dimension(unit_system.get_dimensional_expr(expr))
dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True)
target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units]
canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)]
canon_expr_units = {i for i in dim_dependencies}
if not canon_expr_units.issubset(set(canon_dim_units)):
return None
seen = set()
canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))]
camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])
exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])
try:
res_exponents = camat.solve(exprmat)
except NonInvertibleMatrixError:
return None
return res_exponents
def convert_to(expr, target_units, unit_system="SI"):
"""
Convert ``expr`` to the same expression with all of its units and quantities
represented as factors of ``target_units``, whenever the dimension is compatible.
``target_units`` may be a single unit/quantity, or a collection of
units/quantities.
Examples
========
>>> from sympy.physics.units import speed_of_light, meter, gram, second, day
>>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant
>>> from sympy.physics.units import kilometer, centimeter
>>> from sympy.physics.units import gravitational_constant, hbar
>>> from sympy.physics.units import convert_to
>>> convert_to(mile, kilometer)
25146*kilometer/15625
>>> convert_to(mile, kilometer).n()
1.609344*kilometer
>>> convert_to(speed_of_light, meter/second)
299792458*meter/second
>>> convert_to(day, second)
86400*second
>>> 3*newton
3*newton
>>> convert_to(3*newton, kilogram*meter/second**2)
3*kilogram*meter/second**2
>>> convert_to(atomic_mass_constant, gram)
1.660539060e-24*gram
Conversion to multiple units:
>>> convert_to(speed_of_light, [meter, second])
299792458*meter/second
>>> convert_to(3*newton, [centimeter, gram, second])
300000*centimeter*gram/second**2
Conversion to Planck units:
>>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()
7.62963087839509e-20*hbar**0.5*speed_of_light**0.5/gravitational_constant**0.5
"""
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
if not isinstance(target_units, (Iterable, Tuple)):
target_units = [target_units]
if isinstance(expr, Add):
return Add.fromiter(convert_to(i, target_units, unit_system) for i in expr.args)
expr = sympify(expr)
if not isinstance(expr, Quantity) and expr.has(Quantity):
expr = expr.replace(lambda x: isinstance(x, Quantity), lambda x: x.convert_to(target_units, unit_system))
def get_total_scale_factor(expr):
if isinstance(expr, Mul):
return reduce(lambda x, y: x * y, [get_total_scale_factor(i) for i in expr.args])
elif isinstance(expr, Pow):
return get_total_scale_factor(expr.base) ** expr.exp
elif isinstance(expr, Quantity):
return unit_system.get_quantity_scale_factor(expr)
return expr
depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system)
if depmat is None:
return expr
expr_scale_factor = get_total_scale_factor(expr)
return expr_scale_factor * Mul.fromiter((1/get_total_scale_factor(u) * u) ** p for u, p in zip(target_units, depmat))
def quantity_simplify(expr):
"""Return an equivalent expression in which prefixes are replaced
with numerical values and all units of a given dimension are the
unified in a canonical manner.
Examples
========
>>> from sympy.physics.units.util import quantity_simplify
>>> from sympy.physics.units.prefixes import kilo
>>> from sympy.physics.units import foot, inch
>>> quantity_simplify(kilo*foot*inch)
250*foot**2/3
>>> quantity_simplify(foot - 6*inch)
foot/2
"""
if expr.is_Atom or not expr.has(Prefix, Quantity):
return expr
# replace all prefixes with numerical values
p = expr.atoms(Prefix)
expr = expr.xreplace({p: p.scale_factor for p in p})
# replace all quantities of given dimension with a canonical
# quantity, chosen from those in the expression
d = sift(expr.atoms(Quantity), lambda i: i.dimension)
for k in d:
if len(d[k]) == 1:
continue
v = list(ordered(d[k]))
ref = v[0]/v[0].scale_factor
expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]})
return expr
def check_dimensions(expr, unit_system="SI"):
"""Return expr if units in addends have the same
base dimensions, else raise a ValueError."""
# the case of adding a number to a dimensional quantity
# is ignored for the sake of SymPy core routines, so this
# function will raise an error now if such an addend is
# found.
# Also, when doing substitutions, multiplicative constants
# might be introduced, so remove those now
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
def addDict(dict1, dict2):
"""Merge dictionaries by adding values of common keys and
removing keys with value of 0."""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = value + dict1[key]
return {key:val for key, val in dict3.items() if val != 0}
adds = expr.atoms(Add)
DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies
for a in adds:
deset = set()
for ai in a.args:
if ai.is_number:
deset.add(())
continue
dims = []
skip = False
dimdict = {}
for i in Mul.make_args(ai):
if i.has(Quantity):
i = Dimension(unit_system.get_dimensional_expr(i))
if i.has(Dimension):
dimdict = addDict(dimdict, DIM_OF(i))
elif i.free_symbols:
skip = True
break
dims.extend(dimdict.items())
if not skip:
deset.add(tuple(sorted(dims)))
if len(deset) > 1:
raise ValueError(
"addends have incompatible dimensions: {}".format(deset))
# clear multiplicative constants on Dimensions which may be
# left after substitution
reps = {}
for m in expr.atoms(Mul):
if any(isinstance(i, Dimension) for i in m.args):
reps[m] = m.func(*[
i for i in m.args if not i.is_number])
return expr.xreplace(reps)
|
bcc09e3e0e093fbe42485056a127846852df06f041efe9e4b54be1deec1a42fb | """
Physical quantities.
"""
from sympy.core.expr import AtomicExpr
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.physics.units.dimensions import _QuantityMapper
from sympy.physics.units.prefixes import Prefix
from sympy.utilities.exceptions import SymPyDeprecationWarning
class Quantity(AtomicExpr):
"""
Physical quantity: can be a unit of measure, a constant or a generic quantity.
"""
is_commutative = True
is_real = True
is_number = False
is_nonzero = True
_diff_wrt = True
def __new__(cls, name, abbrev=None, dimension=None, scale_factor=None,
latex_repr=None, pretty_unicode_repr=None,
pretty_ascii_repr=None, mathml_presentation_repr=None,
**assumptions):
if not isinstance(name, Symbol):
name = Symbol(name)
# For Quantity(name, dim, scale, abbrev) to work like in the
# old version of SymPy:
if not isinstance(abbrev, str) and not \
isinstance(abbrev, Symbol):
dimension, scale_factor, abbrev = abbrev, dimension, scale_factor
if dimension is not None:
SymPyDeprecationWarning(
deprecated_since_version="1.3",
issue=14319,
feature="Quantity arguments",
useinstead="unit_system.set_quantity_dimension_map",
).warn()
if scale_factor is not None:
SymPyDeprecationWarning(
deprecated_since_version="1.3",
issue=14319,
feature="Quantity arguments",
useinstead="SI_quantity_scale_factors",
).warn()
if abbrev is None:
abbrev = name
elif isinstance(abbrev, str):
abbrev = Symbol(abbrev)
obj = AtomicExpr.__new__(cls, name, abbrev)
obj._name = name
obj._abbrev = abbrev
obj._latex_repr = latex_repr
obj._unicode_repr = pretty_unicode_repr
obj._ascii_repr = pretty_ascii_repr
obj._mathml_repr = mathml_presentation_repr
if dimension is not None:
# TODO: remove after deprecation:
obj.set_dimension(dimension)
if scale_factor is not None:
# TODO: remove after deprecation:
obj.set_scale_factor(scale_factor)
return obj
def set_dimension(self, dimension, unit_system="SI"):
SymPyDeprecationWarning(
deprecated_since_version="1.5",
issue=17765,
feature="Moving method to UnitSystem class",
useinstead="unit_system.set_quantity_dimension or {}.set_global_relative_scale_factor".format(self),
).warn()
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
unit_system.set_quantity_dimension(self, dimension)
def set_scale_factor(self, scale_factor, unit_system="SI"):
SymPyDeprecationWarning(
deprecated_since_version="1.5",
issue=17765,
feature="Moving method to UnitSystem class",
useinstead="unit_system.set_quantity_scale_factor or {}.set_global_relative_scale_factor".format(self),
).warn()
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
unit_system.set_quantity_scale_factor(self, scale_factor)
def set_global_dimension(self, dimension):
_QuantityMapper._quantity_dimension_global[self] = dimension
def set_global_relative_scale_factor(self, scale_factor, reference_quantity):
"""
Setting a scale factor that is valid across all unit system.
"""
from sympy.physics.units import UnitSystem
scale_factor = sympify(scale_factor)
# replace all prefixes by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Prefix),
lambda x: x.scale_factor
)
scale_factor = sympify(scale_factor)
UnitSystem._quantity_scale_factors_global[self] = (scale_factor, reference_quantity)
UnitSystem._quantity_dimensional_equivalence_map_global[self] = reference_quantity
@property
def name(self):
return self._name
@property
def dimension(self):
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_default_unit_system()
return unit_system.get_quantity_dimension(self)
@property
def abbrev(self):
"""
Symbol representing the unit name.
Prepend the abbreviation with the prefix symbol if it is defines.
"""
return self._abbrev
@property
def scale_factor(self):
"""
Overall magnitude of the quantity as compared to the canonical units.
"""
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_default_unit_system()
return unit_system.get_quantity_scale_factor(self)
def _eval_is_positive(self):
return True
def _eval_is_constant(self):
return True
def _eval_Abs(self):
return self
def _eval_subs(self, old, new):
if isinstance(new, Quantity) and self != old:
return self
@staticmethod
def get_dimensional_expr(expr, unit_system="SI"):
SymPyDeprecationWarning(
deprecated_since_version="1.5",
issue=17765,
feature="get_dimensional_expr() is now associated with UnitSystem objects. " \
"The dimensional relations depend on the unit system used.",
useinstead="unit_system.get_dimensional_expr"
).warn()
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
return unit_system.get_dimensional_expr(expr)
@staticmethod
def _collect_factor_and_dimension(expr, unit_system="SI"):
"""Return tuple with scale factor expression and dimension expression."""
SymPyDeprecationWarning(
deprecated_since_version="1.5",
issue=17765,
feature="This method has been moved to the UnitSystem class.",
useinstead="unit_system._collect_factor_and_dimension",
).warn()
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
return unit_system._collect_factor_and_dimension(expr)
def _latex(self, printer):
if self._latex_repr:
return self._latex_repr
else:
return r'\text{{{}}}'.format(self.args[1] \
if len(self.args) >= 2 else self.args[0])
def convert_to(self, other, unit_system="SI"):
"""
Convert the quantity to another quantity of same dimensions.
Examples
========
>>> from sympy.physics.units import speed_of_light, meter, second
>>> speed_of_light
speed_of_light
>>> speed_of_light.convert_to(meter/second)
299792458*meter/second
>>> from sympy.physics.units import liter
>>> liter.convert_to(meter**3)
meter**3/1000
"""
from .util import convert_to
return convert_to(self, other, unit_system)
@property
def free_symbols(self):
"""Return free symbols from quantity."""
return set()
|
38fa1599c8c170bef61cfd37984caadd5a2295c7a0b4fd4fe51006e93b77665a | """
Module to handle gamma matrices expressed as tensor objects.
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
>>> from sympy.tensor.tensor import tensor_indices
>>> i = tensor_indices('i', LorentzIndex)
>>> G(i)
GammaMatrix(i)
Note that there is already an instance of GammaMatrixHead in four dimensions:
GammaMatrix, which is simply declare as
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix
>>> from sympy.tensor.tensor import tensor_indices
>>> i = tensor_indices('i', LorentzIndex)
>>> GammaMatrix(i)
GammaMatrix(i)
To access the metric tensor
>>> LorentzIndex.metric
metric(LorentzIndex,LorentzIndex)
"""
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.matrices.dense import eye
from sympy.matrices.expressions.trace import trace
from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
# DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
TensorSymmetry.no_symmetry(1), comm=None)
def extract_type_tens(expression, component):
"""
Extract from a ``TensExpr`` all tensors with `component`.
Returns two tensor expressions:
* the first contains all ``Tensor`` of having `component`.
* the second contains all remaining.
"""
if isinstance(expression, Tensor):
sp = [expression]
elif isinstance(expression, TensMul):
sp = expression.args
else:
raise ValueError('wrong type')
# Collect all gamma matrices of the same dimension
new_expr = S.One
residual_expr = S.One
for i in sp:
if isinstance(i, Tensor) and i.component == component:
new_expr *= i
else:
residual_expr *= i
return new_expr, residual_expr
def simplify_gamma_expression(expression):
extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
res_expr = _simplify_single_line(extracted_expr)
return res_expr * residual_expr
def simplify_gpgp(ex, sort=True):
"""
simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, simplify_gpgp
>>> from sympy.tensor.tensor import tensor_indices, tensor_heads
>>> p, q = tensor_heads('p, q', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> ps = p(i0)*G(-i0)
>>> qs = q(i0)*G(-i0)
>>> simplify_gpgp(ps*qs*qs)
GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
"""
def _simplify_gpgp(ex):
components = ex.components
a = []
comp_map = []
for i, comp in enumerate(components):
comp_map.extend([i]*comp.rank)
dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
for i in range(len(components)):
if components[i] != GammaMatrix:
continue
for dx in dum:
if dx[2] == i:
p_pos1 = dx[3]
elif dx[3] == i:
p_pos1 = dx[2]
else:
continue
comp1 = components[p_pos1]
if comp1.comm == 0 and comp1.rank == 1:
a.append((i, p_pos1))
if not a:
return ex
elim = set()
tv = []
hit = True
coeff = S.One
ta = None
while hit:
hit = False
for i, ai in enumerate(a[:-1]):
if ai[0] in elim:
continue
if ai[0] != a[i + 1][0] - 1:
continue
if components[ai[1]] != components[a[i + 1][1]]:
continue
elim.add(ai[0])
elim.add(ai[1])
elim.add(a[i + 1][0])
elim.add(a[i + 1][1])
if not ta:
ta = ex.split()
mu = TensorIndex('mu', LorentzIndex)
hit = True
if i == 0:
coeff = ex.coeff
tx = components[ai[1]](mu)*components[ai[1]](-mu)
if len(a) == 2:
tx *= 4 # eye(4)
tv.append(tx)
break
if tv:
a = [x for j, x in enumerate(ta) if j not in elim]
a.extend(tv)
t = tensor_mul(*a)*coeff
# t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
return t
else:
return ex
if sort:
ex = ex.sorted_components()
# this would be better off with pattern matching
while 1:
t = _simplify_gpgp(ex)
if t != ex:
ex = t
else:
return t
def gamma_trace(t):
"""
trace of a single line of gamma matrices
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
gamma_trace, LorentzIndex
>>> from sympy.tensor.tensor import tensor_indices, tensor_heads
>>> p, q = tensor_heads('p, q', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> ps = p(i0)*G(-i0)
>>> qs = q(i0)*G(-i0)
>>> gamma_trace(G(i0)*G(i1))
4*metric(i0, i1)
>>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
0
>>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
0
"""
if isinstance(t, TensAdd):
res = TensAdd(*[_trace_single_line(x) for x in t.args])
return res
t = _simplify_single_line(t)
res = _trace_single_line(t)
return res
def _simplify_single_line(expression):
"""
Simplify single-line product of gamma matrices.
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, _simplify_single_line
>>> from sympy.tensor.tensor import tensor_indices, TensorHead
>>> p = TensorHead('p', [LorentzIndex])
>>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
>>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
0
"""
t1, t2 = extract_type_tens(expression, GammaMatrix)
if t1 != 1:
t1 = kahane_simplify(t1)
res = t1*t2
return res
def _trace_single_line(t):
"""
Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
Notes
=====
If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
indices trace over them; otherwise traces are not implied (explain)
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, _trace_single_line
>>> from sympy.tensor.tensor import tensor_indices, TensorHead
>>> p = TensorHead('p', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> _trace_single_line(G(i0)*G(i1))
4*metric(i0, i1)
>>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
0
"""
def _trace_single_line1(t):
t = t.sorted_components()
components = t.components
ncomps = len(components)
g = LorentzIndex.metric
# gamma matirices are in a[i:j]
hit = 0
for i in range(ncomps):
if components[i] == GammaMatrix:
hit = 1
break
for j in range(i + hit, ncomps):
if components[j] != GammaMatrix:
break
else:
j = ncomps
numG = j - i
if numG == 0:
tcoeff = t.coeff
return t.nocoeff if tcoeff else t
if numG % 2 == 1:
return TensMul.from_data(S.Zero, [], [], [])
elif numG > 4:
# find the open matrix indices and connect them:
a = t.split()
ind1 = a[i].get_indices()[0]
ind2 = a[i + 1].get_indices()[0]
aa = a[:i] + a[i + 2:]
t1 = tensor_mul(*aa)*g(ind1, ind2)
t1 = t1.contract_metric(g)
args = [t1]
sign = 1
for k in range(i + 2, j):
sign = -sign
ind2 = a[k].get_indices()[0]
aa = a[:i] + a[i + 1:k] + a[k + 1:]
t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
t2 = t2.contract_metric(g)
t2 = simplify_gpgp(t2, False)
args.append(t2)
t3 = TensAdd(*args)
t3 = _trace_single_line(t3)
return t3
else:
a = t.split()
t1 = _gamma_trace1(*a[i:j])
a2 = a[:i] + a[j:]
t2 = tensor_mul(*a2)
t3 = t1*t2
if not t3:
return t3
t3 = t3.contract_metric(g)
return t3
t = t.expand()
if isinstance(t, TensAdd):
a = [_trace_single_line1(x)*x.coeff for x in t.args]
return TensAdd(*a)
elif isinstance(t, (Tensor, TensMul)):
r = t.coeff*_trace_single_line1(t)
return r
else:
return trace(t)
def _gamma_trace1(*a):
gctr = 4 # FIXME specific for d=4
g = LorentzIndex.metric
if not a:
return gctr
n = len(a)
if n%2 == 1:
#return TensMul.from_data(S.Zero, [], [], [])
return S.Zero
if n == 2:
ind0 = a[0].get_indices()[0]
ind1 = a[1].get_indices()[0]
return gctr*g(ind0, ind1)
if n == 4:
ind0 = a[0].get_indices()[0]
ind1 = a[1].get_indices()[0]
ind2 = a[2].get_indices()[0]
ind3 = a[3].get_indices()[0]
return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
def kahane_simplify(expression):
r"""
This function cancels contracted elements in a product of four
dimensional gamma matrices, resulting in an expression equal to the given
one, without the contracted gamma matrices.
Parameters
==========
`expression` the tensor expression containing the gamma matrices to simplify.
Notes
=====
If spinor indices are given, the matrices must be given in
the order given in the product.
Algorithm
=========
The idea behind the algorithm is to use some well-known identities,
i.e., for contractions enclosing an even number of `\gamma` matrices
`\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
for an odd number of `\gamma` matrices
`\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
Instead of repeatedly applying these identities to cancel out all contracted indices,
it is possible to recognize the links that would result from such an operation,
the problem is thus reduced to a simple rearrangement of free gamma matrices.
Examples
========
When using, always remember that the original expression coefficient
has to be handled separately
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
>>> from sympy.physics.hep.gamma_matrices import kahane_simplify
>>> from sympy.tensor.tensor import tensor_indices
>>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
>>> ta = G(i0)*G(-i0)
>>> kahane_simplify(ta)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
>>> tb = G(i0)*G(i1)*G(-i0)
>>> kahane_simplify(tb)
-2*GammaMatrix(i1)
>>> t = G(i0)*G(-i0)
>>> kahane_simplify(t)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
>>> t = G(i0)*G(-i0)
>>> kahane_simplify(t)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
If there are no contractions, the same expression is returned
>>> tc = G(i0)*G(i1)
>>> kahane_simplify(tc)
GammaMatrix(i0)*GammaMatrix(i1)
References
==========
[1] Algorithm for Reducing Contracted Products of gamma Matrices,
Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
"""
if isinstance(expression, Mul):
return expression
if isinstance(expression, TensAdd):
return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
if isinstance(expression, Tensor):
return expression
assert isinstance(expression, TensMul)
gammas = expression.args
for gamma in gammas:
assert gamma.component == GammaMatrix
free = expression.free
# spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
# if len(spinor_free) == 2:
# spinor_free.sort(key=lambda x: x[2])
# assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
# assert spinor_free[0][2] == 0
# elif spinor_free:
# raise ValueError('spinor indices do not match')
dum = []
for dum_pair in expression.dum:
if expression.index_types[dum_pair[0]] == LorentzIndex:
dum.append((dum_pair[0], dum_pair[1]))
dum = sorted(dum)
if len(dum) == 0: # or GammaMatrixHead:
# no contractions in `expression`, just return it.
return expression
# find the `first_dum_pos`, i.e. the position of the first contracted
# gamma matrix, Kahane's algorithm as described in his paper requires the
# gamma matrix expression to start with a contracted gamma matrix, this is
# a workaround which ignores possible initial free indices, and re-adds
# them later.
first_dum_pos = min(map(min, dum))
# for p1, p2, a1, a2 in expression.dum_in_args:
# if p1 != 0 or p2 != 0:
# # only Lorentz indices, skip Dirac indices:
# continue
# first_dum_pos = min(p1, p2)
# break
total_number = len(free) + len(dum)*2
number_of_contractions = len(dum)
free_pos = [None]*total_number
for i in free:
free_pos[i[1]] = i[0]
# `index_is_free` is a list of booleans, to identify index position
# and whether that index is free or dummy.
index_is_free = [False]*total_number
for i, indx in enumerate(free):
index_is_free[indx[1]] = True
# `links` is a dictionary containing the graph described in Kahane's paper,
# to every key correspond one or two values, representing the linked indices.
# All values in `links` are integers, negative numbers are used in the case
# where it is necessary to insert gamma matrices between free indices, in
# order to make Kahane's algorithm work (see paper).
links = dict()
for i in range(first_dum_pos, total_number):
links[i] = []
# `cum_sign` is a step variable to mark the sign of every index, see paper.
cum_sign = -1
# `cum_sign_list` keeps storage for all `cum_sign` (every index).
cum_sign_list = [None]*total_number
block_free_count = 0
# multiply `resulting_coeff` by the coefficient parameter, the rest
# of the algorithm ignores a scalar coefficient.
resulting_coeff = S.One
# initialize a list of lists of indices. The outer list will contain all
# additive tensor expressions, while the inner list will contain the
# free indices (rearranged according to the algorithm).
resulting_indices = [[]]
# start to count the `connected_components`, which together with the number
# of contractions, determines a -1 or +1 factor to be multiplied.
connected_components = 1
# First loop: here we fill `cum_sign_list`, and draw the links
# among consecutive indices (they are stored in `links`). Links among
# non-consecutive indices will be drawn later.
for i, is_free in enumerate(index_is_free):
# if `expression` starts with free indices, they are ignored here;
# they are later added as they are to the beginning of all
# `resulting_indices` list of lists of indices.
if i < first_dum_pos:
continue
if is_free:
block_free_count += 1
# if previous index was free as well, draw an arch in `links`.
if block_free_count > 1:
links[i - 1].append(i)
links[i].append(i - 1)
else:
# Change the sign of the index (`cum_sign`) if the number of free
# indices preceding it is even.
cum_sign *= 1 if (block_free_count % 2) else -1
if block_free_count == 0 and i != first_dum_pos:
# check if there are two consecutive dummy indices:
# in this case create virtual indices with negative position,
# these "virtual" indices represent the insertion of two
# gamma^0 matrices to separate consecutive dummy indices, as
# Kahane's algorithm requires dummy indices to be separated by
# free indices. The product of two gamma^0 matrices is unity,
# so the new expression being examined is the same as the
# original one.
if cum_sign == -1:
links[-1-i] = [-1-i+1]
links[-1-i+1] = [-1-i]
if (i - cum_sign) in links:
if i != first_dum_pos:
links[i].append(i - cum_sign)
if block_free_count != 0:
if i - cum_sign < len(index_is_free):
if index_is_free[i - cum_sign]:
links[i - cum_sign].append(i)
block_free_count = 0
cum_sign_list[i] = cum_sign
# The previous loop has only created links between consecutive free indices,
# it is necessary to properly create links among dummy (contracted) indices,
# according to the rules described in Kahane's paper. There is only one exception
# to Kahane's rules: the negative indices, which handle the case of some
# consecutive free indices (Kahane's paper just describes dummy indices
# separated by free indices, hinting that free indices can be added without
# altering the expression result).
for i in dum:
# get the positions of the two contracted indices:
pos1 = i[0]
pos2 = i[1]
# create Kahane's upper links, i.e. the upper arcs between dummy
# (i.e. contracted) indices:
links[pos1].append(pos2)
links[pos2].append(pos1)
# create Kahane's lower links, this corresponds to the arcs below
# the line described in the paper:
# first we move `pos1` and `pos2` according to the sign of the indices:
linkpos1 = pos1 + cum_sign_list[pos1]
linkpos2 = pos2 + cum_sign_list[pos2]
# otherwise, perform some checks before creating the lower arcs:
# make sure we are not exceeding the total number of indices:
if linkpos1 >= total_number:
continue
if linkpos2 >= total_number:
continue
# make sure we are not below the first dummy index in `expression`:
if linkpos1 < first_dum_pos:
continue
if linkpos2 < first_dum_pos:
continue
# check if the previous loop created "virtual" indices between dummy
# indices, in such a case relink `linkpos1` and `linkpos2`:
if (-1-linkpos1) in links:
linkpos1 = -1-linkpos1
if (-1-linkpos2) in links:
linkpos2 = -1-linkpos2
# move only if not next to free index:
if linkpos1 >= 0 and not index_is_free[linkpos1]:
linkpos1 = pos1
if linkpos2 >=0 and not index_is_free[linkpos2]:
linkpos2 = pos2
# create the lower arcs:
if linkpos2 not in links[linkpos1]:
links[linkpos1].append(linkpos2)
if linkpos1 not in links[linkpos2]:
links[linkpos2].append(linkpos1)
# This loop starts from the `first_dum_pos` index (first dummy index)
# walks through the graph deleting the visited indices from `links`,
# it adds a gamma matrix for every free index in encounters, while it
# completely ignores dummy indices and virtual indices.
pointer = first_dum_pos
previous_pointer = 0
while True:
if pointer in links:
next_ones = links.pop(pointer)
else:
break
if previous_pointer in next_ones:
next_ones.remove(previous_pointer)
previous_pointer = pointer
if next_ones:
pointer = next_ones[0]
else:
break
if pointer == previous_pointer:
break
if pointer >=0 and free_pos[pointer] is not None:
for ri in resulting_indices:
ri.append(free_pos[pointer])
# The following loop removes the remaining connected components in `links`.
# If there are free indices inside a connected component, it gives a
# contribution to the resulting expression given by the factor
# `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
# paper represented as {gamma_a, gamma_b, ... , gamma_z},
# virtual indices are ignored. The variable `connected_components` is
# increased by one for every connected component this loop encounters.
# If the connected component has virtual and dummy indices only
# (no free indices), it contributes to `resulting_indices` by a factor of two.
# The multiplication by two is a result of the
# factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
# Note: curly brackets are meant as in the paper, as a generalized
# multi-element anticommutator!
while links:
connected_components += 1
pointer = min(links.keys())
previous_pointer = pointer
# the inner loop erases the visited indices from `links`, and it adds
# all free indices to `prepend_indices` list, virtual indices are
# ignored.
prepend_indices = []
while True:
if pointer in links:
next_ones = links.pop(pointer)
else:
break
if previous_pointer in next_ones:
if len(next_ones) > 1:
next_ones.remove(previous_pointer)
previous_pointer = pointer
if next_ones:
pointer = next_ones[0]
if pointer >= first_dum_pos and free_pos[pointer] is not None:
prepend_indices.insert(0, free_pos[pointer])
# if `prepend_indices` is void, it means there are no free indices
# in the loop (and it can be shown that there must be a virtual index),
# loops of virtual indices only contribute by a factor of two:
if len(prepend_indices) == 0:
resulting_coeff *= 2
# otherwise, add the free indices in `prepend_indices` to
# the `resulting_indices`:
else:
expr1 = prepend_indices
expr2 = list(reversed(prepend_indices))
resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
# sign correction, as described in Kahane's paper:
resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
# power of two factor, as described in Kahane's paper:
resulting_coeff *= 2**(number_of_contractions)
# If `first_dum_pos` is not zero, it means that there are trailing free gamma
# matrices in front of `expression`, so multiply by them:
for i in range(0, first_dum_pos):
[ri.insert(0, free_pos[i]) for ri in resulting_indices]
resulting_expr = S.Zero
for i in resulting_indices:
temp_expr = S.One
for j in i:
temp_expr *= GammaMatrix(j)
resulting_expr += temp_expr
t = resulting_coeff * resulting_expr
t1 = None
if isinstance(t, TensAdd):
t1 = t.args[0]
elif isinstance(t, TensMul):
t1 = t
if t1:
pass
else:
t = eye(4)*t
return t
|
004a4c1bcd17b2bce0c6c5741f8d4d650d0daccebb34e6e646eca911edcc5741 | from sympy.core.function import Derivative
from sympy.core.function import UndefinedFunction, AppliedUndef
from sympy.core.symbol import Symbol
from sympy.interactive.printing import init_printing
from sympy.printing.latex import LatexPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.pretty_symbology import center_accent
from sympy.printing.str import StrPrinter
from sympy.printing.precedence import PRECEDENCE
__all__ = ['vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex',
'init_vprinting']
class VectorStrPrinter(StrPrinter):
"""String Printer for vector expressions. """
def _print_Derivative(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
if (bool(sum([i == t for i in e.variables])) &
isinstance(type(e.args[0]), UndefinedFunction)):
ol = str(e.args[0].func)
for i, v in enumerate(e.variables):
ol += dynamicsymbols._str
return ol
else:
return StrPrinter().doprint(e)
def _print_Function(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
if isinstance(type(e), UndefinedFunction):
return StrPrinter().doprint(e).replace("(%s)" % t, '')
return e.func.__name__ + "(%s)" % self.stringify(e.args, ", ")
class VectorStrReprPrinter(VectorStrPrinter):
"""String repr printer for vector expressions."""
def _print_str(self, s):
return repr(s)
class VectorLatexPrinter(LatexPrinter):
"""Latex Printer for vector expressions. """
def _print_Function(self, expr, exp=None):
from sympy.physics.vector.functions import dynamicsymbols
func = expr.func.__name__
t = dynamicsymbols._t
if hasattr(self, '_print_' + func) and \
not isinstance(type(expr), UndefinedFunction):
return getattr(self, '_print_' + func)(expr, exp)
elif isinstance(type(expr), UndefinedFunction) and (expr.args == (t,)):
# treat this function like a symbol
expr = Symbol(func)
if exp is not None:
# copied from LatexPrinter._helper_print_standard_power, which
# we can't call because we only have exp as a string.
base = self.parenthesize(expr, PRECEDENCE['Pow'])
base = self.parenthesize_super(base)
return r"%s^{%s}" % (base, exp)
else:
return super()._print(expr)
else:
return super()._print_Function(expr, exp)
def _print_Derivative(self, der_expr):
from sympy.physics.vector.functions import dynamicsymbols
# make sure it is in the right form
der_expr = der_expr.doit()
if not isinstance(der_expr, Derivative):
return r"\left(%s\right)" % self.doprint(der_expr)
# check if expr is a dynamicsymbol
t = dynamicsymbols._t
expr = der_expr.expr
red = expr.atoms(AppliedUndef)
syms = der_expr.variables
test1 = not all(True for i in red if i.free_symbols == {t})
test2 = not all(t == i for i in syms)
if test1 or test2:
return super()._print_Derivative(der_expr)
# done checking
dots = len(syms)
base = self._print_Function(expr)
base_split = base.split('_', 1)
base = base_split[0]
if dots == 1:
base = r"\dot{%s}" % base
elif dots == 2:
base = r"\ddot{%s}" % base
elif dots == 3:
base = r"\dddot{%s}" % base
elif dots == 4:
base = r"\ddddot{%s}" % base
else: # Fallback to standard printing
return super()._print_Derivative(der_expr)
if len(base_split) != 1:
base += '_' + base_split[1]
return base
class VectorPrettyPrinter(PrettyPrinter):
"""Pretty Printer for vectorialexpressions. """
def _print_Derivative(self, deriv):
from sympy.physics.vector.functions import dynamicsymbols
# XXX use U('PARTIAL DIFFERENTIAL') here ?
t = dynamicsymbols._t
dot_i = 0
syms = list(reversed(deriv.variables))
while len(syms) > 0:
if syms[-1] == t:
syms.pop()
dot_i += 1
else:
return super()._print_Derivative(deriv)
if not (isinstance(type(deriv.expr), UndefinedFunction)
and (deriv.expr.args == (t,))):
return super()._print_Derivative(deriv)
else:
pform = self._print_Function(deriv.expr)
# the following condition would happen with some sort of non-standard
# dynamic symbol I guess, so we'll just print the SymPy way
if len(pform.picture) > 1:
return super()._print_Derivative(deriv)
# There are only special symbols up to fourth-order derivatives
if dot_i >= 5:
return super()._print_Derivative(deriv)
# Deal with special symbols
dots = {0 : "",
1 : "\N{COMBINING DOT ABOVE}",
2 : "\N{COMBINING DIAERESIS}",
3 : "\N{COMBINING THREE DOTS ABOVE}",
4 : "\N{COMBINING FOUR DOTS ABOVE}"}
d = pform.__dict__
#if unicode is false then calculate number of apostrophes needed and add to output
if not self._use_unicode:
apostrophes = ""
for i in range(0, dot_i):
apostrophes += "'"
d['picture'][0] += apostrophes + "(t)"
else:
d['picture'] = [center_accent(d['picture'][0], dots[dot_i])]
return pform
def _print_Function(self, e):
from sympy.physics.vector.functions import dynamicsymbols
t = dynamicsymbols._t
# XXX works only for applied functions
func = e.func
args = e.args
func_name = func.__name__
pform = self._print_Symbol(Symbol(func_name))
# If this function is an Undefined function of t, it is probably a
# dynamic symbol, so we'll skip the (t). The rest of the code is
# identical to the normal PrettyPrinter code
if not (isinstance(func, UndefinedFunction) and (args == (t,))):
return super()._print_Function(e)
return pform
def vprint(expr, **settings):
r"""Function for printing of expressions generated in the
sympy.physics vector package.
Extends SymPy's StrPrinter, takes the same setting accepted by SymPy's
:func:`~.sstr`, and is equivalent to ``print(sstr(foo))``.
Parameters
==========
expr : valid SymPy object
SymPy expression to print.
settings : args
Same as the settings accepted by SymPy's sstr().
Examples
========
>>> from sympy.physics.vector import vprint, dynamicsymbols
>>> u1 = dynamicsymbols('u1')
>>> print(u1)
u1(t)
>>> vprint(u1)
u1
"""
outstr = vsprint(expr, **settings)
import builtins
if (outstr != 'None'):
builtins._ = outstr
print(outstr)
def vsstrrepr(expr, **settings):
"""Function for displaying expression representation's with vector
printing enabled.
Parameters
==========
expr : valid SymPy object
SymPy expression to print.
settings : args
Same as the settings accepted by SymPy's sstrrepr().
"""
p = VectorStrReprPrinter(settings)
return p.doprint(expr)
def vsprint(expr, **settings):
r"""Function for displaying expressions generated in the
sympy.physics vector package.
Returns the output of vprint() as a string.
Parameters
==========
expr : valid SymPy object
SymPy expression to print
settings : args
Same as the settings accepted by SymPy's sstr().
Examples
========
>>> from sympy.physics.vector import vsprint, dynamicsymbols
>>> u1, u2 = dynamicsymbols('u1 u2')
>>> u2d = dynamicsymbols('u2', level=1)
>>> print("%s = %s" % (u1, u2 + u2d))
u1(t) = u2(t) + Derivative(u2(t), t)
>>> print("%s = %s" % (vsprint(u1), vsprint(u2 + u2d)))
u1 = u2 + u2'
"""
string_printer = VectorStrPrinter(settings)
return string_printer.doprint(expr)
def vpprint(expr, **settings):
r"""Function for pretty printing of expressions generated in the
sympy.physics vector package.
Mainly used for expressions not inside a vector; the output of running
scripts and generating equations of motion. Takes the same options as
SymPy's :func:`~.pretty_print`; see that function for more information.
Parameters
==========
expr : valid SymPy object
SymPy expression to pretty print
settings : args
Same as those accepted by SymPy's pretty_print.
"""
pp = VectorPrettyPrinter(settings)
# Note that this is copied from sympy.printing.pretty.pretty_print:
# XXX: this is an ugly hack, but at least it works
use_unicode = pp._settings['use_unicode']
from sympy.printing.pretty.pretty_symbology import pretty_use_unicode
uflag = pretty_use_unicode(use_unicode)
try:
return pp.doprint(expr)
finally:
pretty_use_unicode(uflag)
def vlatex(expr, **settings):
r"""Function for printing latex representation of sympy.physics.vector
objects.
For latex representation of Vectors, Dyadics, and dynamicsymbols. Takes the
same options as SymPy's :func:`~.latex`; see that function for more information;
Parameters
==========
expr : valid SymPy object
SymPy expression to represent in LaTeX form
settings : args
Same as latex()
Examples
========
>>> from sympy.physics.vector import vlatex, ReferenceFrame, dynamicsymbols
>>> N = ReferenceFrame('N')
>>> q1, q2 = dynamicsymbols('q1 q2')
>>> q1d, q2d = dynamicsymbols('q1 q2', 1)
>>> q1dd, q2dd = dynamicsymbols('q1 q2', 2)
>>> vlatex(N.x + N.y)
'\\mathbf{\\hat{n}_x} + \\mathbf{\\hat{n}_y}'
>>> vlatex(q1 + q2)
'q_{1} + q_{2}'
>>> vlatex(q1d)
'\\dot{q}_{1}'
>>> vlatex(q1 * q2d)
'q_{1} \\dot{q}_{2}'
>>> vlatex(q1dd * q1 / q1d)
'\\frac{q_{1} \\ddot{q}_{1}}{\\dot{q}_{1}}'
"""
latex_printer = VectorLatexPrinter(settings)
return latex_printer.doprint(expr)
def init_vprinting(**kwargs):
"""Initializes time derivative printing for all SymPy objects, i.e. any
functions of time will be displayed in a more compact notation. The main
benefit of this is for printing of time derivatives; instead of
displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is
only actually needed for when derivatives are present and are not in a
physics.vector.Vector or physics.vector.Dyadic object. This function is a
light wrapper to :func:`~.init_printing`. Any keyword
arguments for it are valid here.
{0}
Examples
========
>>> from sympy import Function, symbols
>>> t, x = symbols('t, x')
>>> omega = Function('omega')
>>> omega(x).diff()
Derivative(omega(x), x)
>>> omega(t).diff()
Derivative(omega(t), t)
Now use the string printer:
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> omega(x).diff()
Derivative(omega(x), x)
>>> omega(t).diff()
omega'
"""
kwargs['str_printer'] = vsstrrepr
kwargs['pretty_printer'] = vpprint
kwargs['latex_printer'] = vlatex
init_printing(**kwargs)
params = init_printing.__doc__.split('Examples\n ========')[0] # type: ignore
init_vprinting.__doc__ = init_vprinting.__doc__.format(params) # type: ignore
|
65ad5ee5f0ccef10a4cf4074319f71f97dcd6eabe4ce4c268a50dff856b22bb3 | from sympy.core.backend import (S, sympify, expand, sqrt, Add, zeros, acos,
ImmutableMatrix as Matrix, _simplify_matrix)
from sympy.simplify.trigsimp import trigsimp
from sympy.printing.defaults import Printable
from sympy.utilities.misc import filldedent
from sympy.core.evalf import EvalfMixin
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['Vector']
class Vector(Printable, EvalfMixin):
"""The class used to define vectors.
It along with ReferenceFrame are the building blocks of describing a
classical mechanics system in PyDy and sympy.physics.vector.
Attributes
==========
simp : Boolean
Let certain methods use trigsimp on their outputs
"""
simp = False
is_number = False
def __init__(self, inlist):
"""This is the constructor for the Vector class. You shouldn't be
calling this, it should only be used by other functions. You should be
treating Vectors like you would with if you were doing the math by
hand, and getting the first 3 from the standard basis vectors from a
ReferenceFrame.
The only exception is to create a zero vector:
zv = Vector(0)
"""
self.args = []
if inlist == 0:
inlist = []
if isinstance(inlist, dict):
d = inlist
else:
d = {}
for inp in inlist:
if inp[1] in d:
d[inp[1]] += inp[0]
else:
d[inp[1]] = inp[0]
for k, v in d.items():
if v != Matrix([0, 0, 0]):
self.args.append((v, k))
@property
def func(self):
"""Returns the class Vector. """
return Vector
def __hash__(self):
return hash(tuple(self.args))
def __add__(self, other):
"""The add operator for Vector. """
if other == 0:
return self
other = _check_vector(other)
return Vector(self.args + other.args)
def __and__(self, other):
"""Dot product of two vectors.
Returns a scalar, the dot product of the two Vectors
Parameters
==========
other : Vector
The Vector which we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot
>>> from sympy import symbols
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> dot(N.x, N.x)
1
>>> dot(N.x, N.y)
0
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> dot(N.y, A.y)
cos(q1)
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
out = S.Zero
for i, v1 in enumerate(self.args):
for j, v2 in enumerate(other.args):
out += ((v2[0].T)
* (v2[1].dcm(v1[1]))
* (v1[0]))[0]
if Vector.simp:
return trigsimp(sympify(out), recursive=True)
else:
return sympify(out)
def __truediv__(self, other):
"""This uses mul and inputs self and 1 divided by other. """
return self.__mul__(sympify(1) / other)
def __eq__(self, other):
"""Tests for equality.
It is very import to note that this is only as good as the SymPy
equality test; False does not always mean they are not equivalent
Vectors.
If other is 0, and self is empty, returns True.
If other is 0 and self is not empty, returns False.
If none of the above, only accepts other as a Vector.
"""
if other == 0:
other = Vector(0)
try:
other = _check_vector(other)
except TypeError:
return False
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
frame = self.args[0][1]
for v in frame:
if expand((self - other) & v) != 0:
return False
return True
def __mul__(self, other):
"""Multiplies the Vector by a sympifyable expression.
Parameters
==========
other : Sympifyable
The scalar to multiply this Vector with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> b = Symbol('b')
>>> V = 10 * b * N.x
>>> print(V)
10*b*N.x
"""
newlist = [v for v in self.args]
for i, v in enumerate(newlist):
newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1])
return Vector(newlist)
def __ne__(self, other):
return not self == other
def __neg__(self):
return self * -1
def __or__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def _latex(self, printer):
"""Latex Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].latex_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].latex_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + ar[i][1].latex_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
"""Pretty Printing method. """
from sympy.printing.pretty.stringpict import prettyForm
e = self
class Fake:
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
if len(ar) == 0:
return str(0)
pforms = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
pform = printer._print(ar[i][1].pretty_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
pform = printer._print(ar[i][1].pretty_vecs[j])
pform = prettyForm(*pform.left(" - "))
bin = prettyForm.NEG
pform = prettyForm(binding=bin, *pform)
elif ar[i][0][j] != 0:
# If the basis vector coeff is not 1 or -1,
# we might wrap it in parentheses, for readability.
pform = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
tmp = pform.parens()
pform = prettyForm(tmp[0], tmp[1])
pform = prettyForm(*pform.right(" ",
ar[i][1].pretty_vecs[j]))
else:
continue
pforms.append(pform)
pform = prettyForm.__add__(*pforms)
kwargs["wrap_line"] = kwargs.get("wrap_line")
kwargs["num_columns"] = kwargs.get("num_columns")
out_str = pform.render(*args, **kwargs)
mlines = [line.rstrip() for line in out_str.split("\n")]
return "\n".join(mlines)
return Fake()
def __ror__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(other.args):
for i2, v2 in enumerate(self.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def __rsub__(self, other):
return (-1 * self) + other
def _sympystr(self, printer, order=True):
"""Printing method. """
if not order or len(self.args) == 1:
ar = list(self.args)
elif len(self.args) == 0:
return printer._print(0)
else:
d = {v[1]: v[0] for v in self.args}
keys = sorted(d.keys(), key=lambda x: x.index)
ar = []
for key in keys:
ar.append((d[key], key))
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].str_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].str_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*' + ar[i][1].str_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""The cross product operator for two Vectors.
Returns a Vector, expressed in the same ReferenceFrames as self.
Parameters
==========
other : Vector
The Vector which we are crossing with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import symbols
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> N.x ^ N.y
N.z
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> A.x ^ N.y
N.z
>>> N.y ^ A.x
- sin(q1)*A.y - cos(q1)*A.z
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
if other.args == []:
return Vector(0)
def _det(mat):
"""This is needed as a little method for to find the determinant
of a list in python; needs to work for a 3x3 list.
SymPy's Matrix will not take in Vector, so need a custom function.
You shouldn't be calling this.
"""
return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1])
+ mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] *
mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] -
mat[1][1] * mat[2][0]))
outlist = []
ar = other.args # For brevity
for i, v in enumerate(ar):
tempx = v[1].x
tempy = v[1].y
tempz = v[1].z
tempm = ([[tempx, tempy, tempz], [self & tempx, self & tempy,
self & tempz], [Vector([ar[i]]) & tempx,
Vector([ar[i]]) & tempy, Vector([ar[i]]) & tempz]])
outlist += _det(tempm).args
return Vector(outlist)
__radd__ = __add__
__rand__ = __and__
__rmul__ = __mul__
def separate(self):
"""
The constituents of this vector in different reference frames,
as per its definition.
Returns a dict mapping each ReferenceFrame to the corresponding
constituent Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> R1 = ReferenceFrame('R1')
>>> R2 = ReferenceFrame('R2')
>>> v = R1.x + R2.x
>>> v.separate() == {R1: R1.x, R2: R2.x}
True
"""
components = {}
for x in self.args:
components[x[1]] = Vector([x])
return components
def dot(self, other):
return self & other
dot.__doc__ = __and__.__doc__
def cross(self, other):
return self ^ other
cross.__doc__ = __xor__.__doc__
def outer(self, other):
return self | other
outer.__doc__ = __or__.__doc__
def diff(self, var, frame, var_in_dcm=True):
"""Returns the partial derivative of the vector with respect to a
variable in the provided reference frame.
Parameters
==========
var : Symbol
What the partial derivative is taken with respect to.
frame : ReferenceFrame
The reference frame that the partial derivative is taken in.
var_in_dcm : boolean
If true, the differentiation algorithm assumes that the variable
may be present in any of the direction cosine matrices that relate
the frame to the frames of any component of the vector. But if it
is known that the variable is not present in the direction cosine
matrices, false can be set to skip full reexpression in the desired
frame.
Examples
========
>>> from sympy import Symbol
>>> from sympy.physics.vector import dynamicsymbols, ReferenceFrame
>>> from sympy.physics.vector import Vector
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> Vector.simp = True
>>> t = Symbol('t')
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.diff(t, N)
- q1'*A.z
>>> B = ReferenceFrame('B')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> v = u1 * A.x + u2 * B.y
>>> v.diff(u2, N, var_in_dcm=False)
B.y
"""
from sympy.physics.vector.frame import _check_frame
var = sympify(var)
_check_frame(frame)
inlist = []
for vector_component in self.args:
measure_number = vector_component[0]
component_frame = vector_component[1]
if component_frame == frame:
inlist += [(measure_number.diff(var), frame)]
else:
# If the direction cosine matrix relating the component frame
# with the derivative frame does not contain the variable.
if not var_in_dcm or (frame.dcm(component_frame).diff(var) ==
zeros(3, 3)):
inlist += [(measure_number.diff(var),
component_frame)]
else: # else express in the frame
reexp_vec_comp = Vector([vector_component]).express(frame)
deriv = reexp_vec_comp.args[0][0].diff(var)
inlist += Vector([(deriv, frame)]).express(component_frame).args
return Vector(inlist)
def express(self, otherframe, variables=False):
"""
Returns a Vector equivalent to this one, expressed in otherframe.
Uses the global express method.
Parameters
==========
otherframe : ReferenceFrame
The frame for this Vector to be described in
variables : boolean
If True, the coordinate symbols(if present) in this Vector
are re-expressed in terms otherframe
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.express(N)
cos(q1)*N.x - sin(q1)*N.z
"""
from sympy.physics.vector import express
return express(self, otherframe, variables=variables)
def to_matrix(self, reference_frame):
"""Returns the matrix form of the vector with respect to the given
frame.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows of the matrix correspond to.
Returns
-------
matrix : ImmutableMatrix, shape(3,1)
The matrix that gives the 1D vector.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> a, b, c = symbols('a, b, c')
>>> N = ReferenceFrame('N')
>>> vector = a * N.x + b * N.y + c * N.z
>>> vector.to_matrix(N)
Matrix([
[a],
[b],
[c]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> vector.to_matrix(A)
Matrix([
[ a],
[ b*cos(beta) + c*sin(beta)],
[-b*sin(beta) + c*cos(beta)]])
"""
return Matrix([self.dot(unit_vec) for unit_vec in
reference_frame]).reshape(3, 1)
def doit(self, **hints):
"""Calls .doit() on each term in the Vector"""
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(lambda x: x.doit(**hints))
return Vector(d)
def dt(self, otherframe):
"""
Returns a Vector which is the time derivative of
the self Vector, taken in frame otherframe.
Calls the global time_derivative method
Parameters
==========
otherframe : ReferenceFrame
The frame to calculate the time derivative in
"""
from sympy.physics.vector import time_derivative
return time_derivative(self, otherframe)
def simplify(self):
"""Returns a simplified Vector."""
d = {}
for v in self.args:
d[v[1]] = _simplify_matrix(v[0])
return Vector(d)
def subs(self, *args, **kwargs):
"""Substitution on the Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = N.x * s
>>> a.subs({s: 2})
2*N.x
"""
d = {}
for v in self.args:
d[v[1]] = v[0].subs(*args, **kwargs)
return Vector(d)
def magnitude(self):
"""Returns the magnitude (Euclidean norm) of self.
Warnings
========
Python ignores the leading negative sign so that might
give wrong results.
``-A.x.magnitude()`` would be treated as ``-(A.x.magnitude())``,
instead of ``(-A.x).magnitude()``.
"""
return sqrt(self & self)
def normalize(self):
"""Returns a Vector of magnitude 1, codirectional with self."""
return Vector(self.args + []) / self.magnitude()
def applyfunc(self, f):
"""Apply a function to each component of a vector."""
if not callable(f):
raise TypeError("`f` must be callable.")
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(f)
return Vector(d)
def angle_between(self, vec):
"""
Returns the smallest angle between Vector 'vec' and self.
Parameter
=========
vec : Vector
The Vector between which angle is needed.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame("A")
>>> v1 = A.x
>>> v2 = A.y
>>> v1.angle_between(v2)
pi/2
>>> v3 = A.x + A.y + A.z
>>> v1.angle_between(v3)
acos(sqrt(3)/3)
Warnings
========
Python ignores the leading negative sign so that might
give wrong results.
``-A.x.angle_between()`` would be treated as ``-(A.x.angle_between())``,
instead of ``(-A.x).angle_between()``.
"""
vec1 = self.normalize()
vec2 = vec.normalize()
angle = acos(vec1.dot(vec2))
return angle
def free_symbols(self, reference_frame):
"""
Returns the free symbols in the measure numbers of the vector
expressed in the given reference frame.
Parameter
=========
reference_frame : ReferenceFrame
The frame with respect to which the free symbols of the
given vector is to be determined.
"""
return self.to_matrix(reference_frame).free_symbols
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
dps = prec_to_dps(prec)
for mat, frame in self.args:
new_args.append([mat.evalf(n=dps), frame])
return Vector(new_args)
def xreplace(self, rule):
"""
Replace occurrences of objects within the measure numbers of the vector.
Parameters
==========
rule : dict-like
Expresses a replacement rule.
Returns
=======
Vector
Result of the replacement.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame('A')
>>> x, y, z = symbols('x y z')
>>> ((1 + x*y) * A.x).xreplace({x: pi})
(pi*y + 1)*A.x
>>> ((1 + x*y) * A.x).xreplace({x: pi, y: 2})
(1 + 2*pi)*A.x
Replacements occur only if an entire node in the expression tree is
matched:
>>> ((x*y + z) * A.x).xreplace({x*y: pi})
(z + pi)*A.x
>>> ((x*y*z) * A.x).xreplace({x*y: pi})
x*y*z*A.x
"""
new_args = []
for mat, frame in self.args:
mat = mat.xreplace(rule)
new_args.append([mat, frame])
return Vector(new_args)
class VectorTypeError(TypeError):
def __init__(self, other, want):
msg = filldedent("Expected an instance of %s, but received object "
"'%s' of %s." % (type(want), other, type(other)))
super().__init__(msg)
def _check_vector(other):
if not isinstance(other, Vector):
raise TypeError('A Vector must be supplied')
return other
|
e6a4b29b171da25186f068b70f57b3fd1551874cf308a011f18949b1ccdf9b0c | from functools import reduce
from sympy.core.backend import (sympify, diff, sin, cos, Matrix, symbols,
Function, S, Symbol)
from sympy.integrals.integrals import integrate
from sympy.simplify.trigsimp import trigsimp
from .vector import Vector, _check_vector
from .frame import CoordinateSym, _check_frame
from .dyadic import Dyadic
from .printing import vprint, vsprint, vpprint, vlatex, init_vprinting
from sympy.utilities.iterables import iterable
from sympy.utilities.misc import translate
__all__ = ['cross', 'dot', 'express', 'time_derivative', 'outer',
'kinematic_equations', 'get_motion_params', 'partial_velocity',
'dynamicsymbols', 'vprint', 'vsprint', 'vpprint', 'vlatex',
'init_vprinting']
def cross(vec1, vec2):
"""Cross product convenience wrapper for Vector.cross(): \n"""
if not isinstance(vec1, (Vector, Dyadic)):
raise TypeError('Cross product is between two vectors')
return vec1 ^ vec2
cross.__doc__ += Vector.cross.__doc__ # type: ignore
def dot(vec1, vec2):
"""Dot product convenience wrapper for Vector.dot(): \n"""
if not isinstance(vec1, (Vector, Dyadic)):
raise TypeError('Dot product is between two vectors')
return vec1 & vec2
dot.__doc__ += Vector.dot.__doc__ # type: ignore
def express(expr, frame, frame2=None, variables=False):
"""
Global function for 'express' functionality.
Re-expresses a Vector, scalar(sympyfiable) or Dyadic in given frame.
Refer to the local methods of Vector and Dyadic for details.
If 'variables' is True, then the coordinate variables (CoordinateSym
instances) of other frames present in the vector/scalar field or
dyadic expression are also substituted in terms of the base scalars of
this frame.
Parameters
==========
expr : Vector/Dyadic/scalar(sympyfiable)
The expression to re-express in ReferenceFrame 'frame'
frame: ReferenceFrame
The reference frame to express expr in
frame2 : ReferenceFrame
The other frame required for re-expression(only for Dyadic expr)
variables : boolean
Specifies whether to substitute the coordinate variables present
in expr, in terms of those of frame
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> from sympy.physics.vector import express
>>> express(d, B, N)
cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x)
>>> express(B.x, N)
cos(q)*N.x + sin(q)*N.y
>>> express(N[0], B, variables=True)
B_x*cos(q) - B_y*sin(q)
"""
_check_frame(frame)
if expr == 0:
return expr
if isinstance(expr, Vector):
#Given expr is a Vector
if variables:
#If variables attribute is True, substitute
#the coordinate variables in the Vector
frame_list = [x[-1] for x in expr.args]
subs_dict = {}
for f in frame_list:
subs_dict.update(f.variable_map(frame))
expr = expr.subs(subs_dict)
#Re-express in this frame
outvec = Vector([])
for i, v in enumerate(expr.args):
if v[1] != frame:
temp = frame.dcm(v[1]) * v[0]
if Vector.simp:
temp = temp.applyfunc(lambda x:
trigsimp(x, method='fu'))
outvec += Vector([(temp, frame)])
else:
outvec += Vector([v])
return outvec
if isinstance(expr, Dyadic):
if frame2 is None:
frame2 = frame
_check_frame(frame2)
ol = Dyadic(0)
for i, v in enumerate(expr.args):
ol += express(v[0], frame, variables=variables) * \
(express(v[1], frame, variables=variables) |
express(v[2], frame2, variables=variables))
return ol
else:
if variables:
#Given expr is a scalar field
frame_set = set()
expr = sympify(expr)
#Substitute all the coordinate variables
for x in expr.free_symbols:
if isinstance(x, CoordinateSym)and x.frame != frame:
frame_set.add(x.frame)
subs_dict = {}
for f in frame_set:
subs_dict.update(f.variable_map(frame))
return expr.subs(subs_dict)
return expr
def time_derivative(expr, frame, order=1):
"""
Calculate the time derivative of a vector/scalar field function
or dyadic expression in given frame.
References
==========
https://en.wikipedia.org/wiki/Rotating_reference_frame#Time_derivatives_in_the_two_frames
Parameters
==========
expr : Vector/Dyadic/sympifyable
The expression whose time derivative is to be calculated
frame : ReferenceFrame
The reference frame to calculate the time derivative in
order : integer
The order of the derivative to be calculated
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> from sympy import Symbol
>>> q1 = Symbol('q1')
>>> u1 = dynamicsymbols('u1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> v = u1 * N.x
>>> A.set_ang_vel(N, 10*A.x)
>>> from sympy.physics.vector import time_derivative
>>> time_derivative(v, N)
u1'*N.x
>>> time_derivative(u1*A[0], N)
N_x*u1'
>>> B = N.orientnew('B', 'Axis', [u1, N.z])
>>> from sympy.physics.vector import outer
>>> d = outer(N.x, N.x)
>>> time_derivative(d, B)
- u1'*(N.y|N.x) - u1'*(N.x|N.y)
"""
t = dynamicsymbols._t
_check_frame(frame)
if order == 0:
return expr
if order % 1 != 0 or order < 0:
raise ValueError("Unsupported value of order entered")
if isinstance(expr, Vector):
outlist = []
for i, v in enumerate(expr.args):
if v[1] == frame:
outlist += [(express(v[0], frame,
variables=True).diff(t), frame)]
else:
outlist += (time_derivative(Vector([v]), v[1]) + \
(v[1].ang_vel_in(frame) ^ Vector([v]))).args
outvec = Vector(outlist)
return time_derivative(outvec, frame, order - 1)
if isinstance(expr, Dyadic):
ol = Dyadic(0)
for i, v in enumerate(expr.args):
ol += (v[0].diff(t) * (v[1] | v[2]))
ol += (v[0] * (time_derivative(v[1], frame) | v[2]))
ol += (v[0] * (v[1] | time_derivative(v[2], frame)))
return time_derivative(ol, frame, order - 1)
else:
return diff(express(expr, frame, variables=True), t, order)
def outer(vec1, vec2):
"""Outer product convenience wrapper for Vector.outer():\n"""
if not isinstance(vec1, Vector):
raise TypeError('Outer product is between two Vectors')
return vec1 | vec2
outer.__doc__ += Vector.outer.__doc__ # type: ignore
def kinematic_equations(speeds, coords, rot_type, rot_order=''):
"""Gives equations relating the qdot's to u's for a rotation type.
Supply rotation type and order as in orient. Speeds are assumed to be
body-fixed; if we are defining the orientation of B in A using by rot_type,
the angular velocity of B in A is assumed to be in the form: speed[0]*B.x +
speed[1]*B.y + speed[2]*B.z
Parameters
==========
speeds : list of length 3
The body fixed angular velocity measure numbers.
coords : list of length 3 or 4
The coordinates used to define the orientation of the two frames.
rot_type : str
The type of rotation used to create the equations. Body, Space, or
Quaternion only
rot_order : str or int
If applicable, the order of a series of rotations.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import kinematic_equations, vprint
>>> u1, u2, u3 = dynamicsymbols('u1 u2 u3')
>>> q1, q2, q3 = dynamicsymbols('q1 q2 q3')
>>> vprint(kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313'),
... order=None)
[-(u1*sin(q3) + u2*cos(q3))/sin(q2) + q1', -u1*cos(q3) + u2*sin(q3) + q2', (u1*sin(q3) + u2*cos(q3))*cos(q2)/sin(q2) - u3 + q3']
"""
# Code below is checking and sanitizing input
approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131',
'212', '232', '313', '323', '1', '2', '3', '')
# make sure XYZ => 123 and rot_type is in lower case
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.lower()
if not isinstance(speeds, (list, tuple)):
raise TypeError('Need to supply speeds in a list')
if len(speeds) != 3:
raise TypeError('Need to supply 3 body-fixed speeds')
if not isinstance(coords, (list, tuple)):
raise TypeError('Need to supply coordinates in a list')
if rot_type in ['body', 'space']:
if rot_order not in approved_orders:
raise ValueError('Not an acceptable rotation order')
if len(coords) != 3:
raise ValueError('Need 3 coordinates for body or space')
# Actual hard-coded kinematic differential equations
w1, w2, w3 = speeds
if w1 == w2 == w3 == 0:
return [S.Zero]*3
q1, q2, q3 = coords
q1d, q2d, q3d = [diff(i, dynamicsymbols._t) for i in coords]
s1, s2, s3 = [sin(q1), sin(q2), sin(q3)]
c1, c2, c3 = [cos(q1), cos(q2), cos(q3)]
if rot_type == 'body':
if rot_order == '123':
return [q1d - (w1 * c3 - w2 * s3) / c2, q2d - w1 * s3 - w2 *
c3, q3d - (-w1 * c3 + w2 * s3) * s2 / c2 - w3]
if rot_order == '231':
return [q1d - (w2 * c3 - w3 * s3) / c2, q2d - w2 * s3 - w3 *
c3, q3d - w1 - (- w2 * c3 + w3 * s3) * s2 / c2]
if rot_order == '312':
return [q1d - (-w1 * s3 + w3 * c3) / c2, q2d - w1 * c3 - w3 *
s3, q3d - (w1 * s3 - w3 * c3) * s2 / c2 - w2]
if rot_order == '132':
return [q1d - (w1 * c3 + w3 * s3) / c2, q2d + w1 * s3 - w3 *
c3, q3d - (w1 * c3 + w3 * s3) * s2 / c2 - w2]
if rot_order == '213':
return [q1d - (w1 * s3 + w2 * c3) / c2, q2d - w1 * c3 + w2 *
s3, q3d - (w1 * s3 + w2 * c3) * s2 / c2 - w3]
if rot_order == '321':
return [q1d - (w2 * s3 + w3 * c3) / c2, q2d - w2 * c3 + w3 *
s3, q3d - w1 - (w2 * s3 + w3 * c3) * s2 / c2]
if rot_order == '121':
return [q1d - (w2 * s3 + w3 * c3) / s2, q2d - w2 * c3 + w3 *
s3, q3d - w1 + (w2 * s3 + w3 * c3) * c2 / s2]
if rot_order == '131':
return [q1d - (-w2 * c3 + w3 * s3) / s2, q2d - w2 * s3 - w3 *
c3, q3d - w1 - (w2 * c3 - w3 * s3) * c2 / s2]
if rot_order == '212':
return [q1d - (w1 * s3 - w3 * c3) / s2, q2d - w1 * c3 - w3 *
s3, q3d - (-w1 * s3 + w3 * c3) * c2 / s2 - w2]
if rot_order == '232':
return [q1d - (w1 * c3 + w3 * s3) / s2, q2d + w1 * s3 - w3 *
c3, q3d + (w1 * c3 + w3 * s3) * c2 / s2 - w2]
if rot_order == '313':
return [q1d - (w1 * s3 + w2 * c3) / s2, q2d - w1 * c3 + w2 *
s3, q3d + (w1 * s3 + w2 * c3) * c2 / s2 - w3]
if rot_order == '323':
return [q1d - (-w1 * c3 + w2 * s3) / s2, q2d - w1 * s3 - w2 *
c3, q3d - (w1 * c3 - w2 * s3) * c2 / s2 - w3]
if rot_type == 'space':
if rot_order == '123':
return [q1d - w1 - (w2 * s1 + w3 * c1) * s2 / c2, q2d - w2 *
c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / c2]
if rot_order == '231':
return [q1d - (w1 * c1 + w3 * s1) * s2 / c2 - w2, q2d + w1 *
s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / c2]
if rot_order == '312':
return [q1d - (w1 * s1 + w2 * c1) * s2 / c2 - w3, q2d - w1 *
c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / c2]
if rot_order == '132':
return [q1d - w1 - (-w2 * c1 + w3 * s1) * s2 / c2, q2d - w2 *
s1 - w3 * c1, q3d - (w2 * c1 - w3 * s1) / c2]
if rot_order == '213':
return [q1d - (w1 * s1 - w3 * c1) * s2 / c2 - w2, q2d - w1 *
c1 - w3 * s1, q3d - (-w1 * s1 + w3 * c1) / c2]
if rot_order == '321':
return [q1d - (-w1 * c1 + w2 * s1) * s2 / c2 - w3, q2d - w1 *
s1 - w2 * c1, q3d - (w1 * c1 - w2 * s1) / c2]
if rot_order == '121':
return [q1d - w1 + (w2 * s1 + w3 * c1) * c2 / s2, q2d - w2 *
c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / s2]
if rot_order == '131':
return [q1d - w1 - (w2 * c1 - w3 * s1) * c2 / s2, q2d - w2 *
s1 - w3 * c1, q3d - (-w2 * c1 + w3 * s1) / s2]
if rot_order == '212':
return [q1d - (-w1 * s1 + w3 * c1) * c2 / s2 - w2, q2d - w1 *
c1 - w3 * s1, q3d - (w1 * s1 - w3 * c1) / s2]
if rot_order == '232':
return [q1d + (w1 * c1 + w3 * s1) * c2 / s2 - w2, q2d + w1 *
s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / s2]
if rot_order == '313':
return [q1d + (w1 * s1 + w2 * c1) * c2 / s2 - w3, q2d - w1 *
c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / s2]
if rot_order == '323':
return [q1d - (w1 * c1 - w2 * s1) * c2 / s2 - w3, q2d - w1 *
s1 - w2 * c1, q3d - (-w1 * c1 + w2 * s1) / s2]
elif rot_type == 'quaternion':
if rot_order != '':
raise ValueError('Cannot have rotation order for quaternion')
if len(coords) != 4:
raise ValueError('Need 4 coordinates for quaternion')
# Actual hard-coded kinematic differential equations
e0, e1, e2, e3 = coords
w = Matrix(speeds + [0])
E = Matrix([[e0, -e3, e2, e1], [e3, e0, -e1, e2], [-e2, e1, e0, e3],
[-e1, -e2, -e3, e0]])
edots = Matrix([diff(i, dynamicsymbols._t) for i in [e1, e2, e3, e0]])
return list(edots.T - 0.5 * w.T * E.T)
else:
raise ValueError('Not an approved rotation type for this function')
def get_motion_params(frame, **kwargs):
"""
Returns the three motion parameters - (acceleration, velocity, and
position) as vectorial functions of time in the given frame.
If a higher order differential function is provided, the lower order
functions are used as boundary conditions. For example, given the
acceleration, the velocity and position parameters are taken as
boundary conditions.
The values of time at which the boundary conditions are specified
are taken from timevalue1(for position boundary condition) and
timevalue2(for velocity boundary condition).
If any of the boundary conditions are not provided, they are taken
to be zero by default (zero vectors, in case of vectorial inputs). If
the boundary conditions are also functions of time, they are converted
to constants by substituting the time values in the dynamicsymbols._t
time Symbol.
This function can also be used for calculating rotational motion
parameters. Have a look at the Parameters and Examples for more clarity.
Parameters
==========
frame : ReferenceFrame
The frame to express the motion parameters in
acceleration : Vector
Acceleration of the object/frame as a function of time
velocity : Vector
Velocity as function of time or as boundary condition
of velocity at time = timevalue1
position : Vector
Velocity as function of time or as boundary condition
of velocity at time = timevalue1
timevalue1 : sympyfiable
Value of time for position boundary condition
timevalue2 : sympyfiable
Value of time for velocity boundary condition
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, get_motion_params, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> from sympy import symbols
>>> R = ReferenceFrame('R')
>>> v1, v2, v3 = dynamicsymbols('v1 v2 v3')
>>> v = v1*R.x + v2*R.y + v3*R.z
>>> get_motion_params(R, position = v)
(v1''*R.x + v2''*R.y + v3''*R.z, v1'*R.x + v2'*R.y + v3'*R.z, v1*R.x + v2*R.y + v3*R.z)
>>> a, b, c = symbols('a b c')
>>> v = a*R.x + b*R.y + c*R.z
>>> get_motion_params(R, velocity = v)
(0, a*R.x + b*R.y + c*R.z, a*t*R.x + b*t*R.y + c*t*R.z)
>>> parameters = get_motion_params(R, acceleration = v)
>>> parameters[1]
a*t*R.x + b*t*R.y + c*t*R.z
>>> parameters[2]
a*t**2/2*R.x + b*t**2/2*R.y + c*t**2/2*R.z
"""
##Helper functions
def _process_vector_differential(vectdiff, condition, \
variable, ordinate, frame):
"""
Helper function for get_motion methods. Finds derivative of vectdiff wrt
variable, and its integral using the specified boundary condition at
value of variable = ordinate.
Returns a tuple of - (derivative, function and integral) wrt vectdiff
"""
#Make sure boundary condition is independent of 'variable'
if condition != 0:
condition = express(condition, frame, variables=True)
#Special case of vectdiff == 0
if vectdiff == Vector(0):
return (0, 0, condition)
#Express vectdiff completely in condition's frame to give vectdiff1
vectdiff1 = express(vectdiff, frame)
#Find derivative of vectdiff
vectdiff2 = time_derivative(vectdiff, frame)
#Integrate and use boundary condition
vectdiff0 = Vector(0)
lims = (variable, ordinate, variable)
for dim in frame:
function1 = vectdiff1.dot(dim)
abscissa = dim.dot(condition).subs({variable : ordinate})
# Indefinite integral of 'function1' wrt 'variable', using
# the given initial condition (ordinate, abscissa).
vectdiff0 += (integrate(function1, lims) + abscissa) * dim
#Return tuple
return (vectdiff2, vectdiff, vectdiff0)
##Function body
_check_frame(frame)
#Decide mode of operation based on user's input
if 'acceleration' in kwargs:
mode = 2
elif 'velocity' in kwargs:
mode = 1
else:
mode = 0
#All the possible parameters in kwargs
#Not all are required for every case
#If not specified, set to default values(may or may not be used in
#calculations)
conditions = ['acceleration', 'velocity', 'position',
'timevalue', 'timevalue1', 'timevalue2']
for i, x in enumerate(conditions):
if x not in kwargs:
if i < 3:
kwargs[x] = Vector(0)
else:
kwargs[x] = S.Zero
elif i < 3:
_check_vector(kwargs[x])
else:
kwargs[x] = sympify(kwargs[x])
if mode == 2:
vel = _process_vector_differential(kwargs['acceleration'],
kwargs['velocity'],
dynamicsymbols._t,
kwargs['timevalue2'], frame)[2]
pos = _process_vector_differential(vel, kwargs['position'],
dynamicsymbols._t,
kwargs['timevalue1'], frame)[2]
return (kwargs['acceleration'], vel, pos)
elif mode == 1:
return _process_vector_differential(kwargs['velocity'],
kwargs['position'],
dynamicsymbols._t,
kwargs['timevalue1'], frame)
else:
vel = time_derivative(kwargs['position'], frame)
acc = time_derivative(vel, frame)
return (acc, vel, kwargs['position'])
def partial_velocity(vel_vecs, gen_speeds, frame):
"""Returns a list of partial velocities with respect to the provided
generalized speeds in the given reference frame for each of the supplied
velocity vectors.
The output is a list of lists. The outer list has a number of elements
equal to the number of supplied velocity vectors. The inner lists are, for
each velocity vector, the partial derivatives of that velocity vector with
respect to the generalized speeds supplied.
Parameters
==========
vel_vecs : iterable
An iterable of velocity vectors (angular or linear).
gen_speeds : iterable
An iterable of generalized speeds.
frame : ReferenceFrame
The reference frame that the partial derivatives are going to be taken
in.
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import partial_velocity
>>> u = dynamicsymbols('u')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, u * N.x)
>>> vel_vecs = [P.vel(N)]
>>> gen_speeds = [u]
>>> partial_velocity(vel_vecs, gen_speeds, N)
[[N.x]]
"""
if not iterable(vel_vecs):
raise TypeError('Velocity vectors must be contained in an iterable.')
if not iterable(gen_speeds):
raise TypeError('Generalized speeds must be contained in an iterable')
vec_partials = []
for vec in vel_vecs:
partials = []
for speed in gen_speeds:
partials.append(vec.diff(speed, frame, var_in_dcm=False))
vec_partials.append(partials)
return vec_partials
def dynamicsymbols(names, level=0,**assumptions):
"""Uses symbols and Function for functions of time.
Creates a SymPy UndefinedFunction, which is then initialized as a function
of a variable, the default being Symbol('t').
Parameters
==========
names : str
Names of the dynamic symbols you want to create; works the same way as
inputs to symbols
level : int
Level of differentiation of the returned function; d/dt once of t,
twice of t, etc.
assumptions :
- real(bool) : This is used to set the dynamicsymbol as real,
by default is False.
- positive(bool) : This is used to set the dynamicsymbol as positive,
by default is False.
- commutative(bool) : This is used to set the commutative property of
a dynamicsymbol, by default is True.
- integer(bool) : This is used to set the dynamicsymbol as integer,
by default is False.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy import diff, Symbol
>>> q1 = dynamicsymbols('q1')
>>> q1
q1(t)
>>> q2 = dynamicsymbols('q2', real=True)
>>> q2.is_real
True
>>> q3 = dynamicsymbols('q3', positive=True)
>>> q3.is_positive
True
>>> q4, q5 = dynamicsymbols('q4,q5', commutative=False)
>>> bool(q4*q5 != q5*q4)
True
>>> q6 = dynamicsymbols('q6', integer=True)
>>> q6.is_integer
True
>>> diff(q1, Symbol('t'))
Derivative(q1(t), t)
"""
esses = symbols(names, cls=Function,**assumptions)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, [t] * level, e(t)) for e in esses]
return esses
else:
return reduce(diff, [t] * level, esses(t))
dynamicsymbols._t = Symbol('t') # type: ignore
dynamicsymbols._str = '\'' # type: ignore
|
0d5cff0af28b67b874b53a268487ec5db26ccd66518c3582cc3077c8516888e9 | from sympy.core.function import diff
from sympy.core.singleton import S
from sympy.integrals.integrals import integrate
from sympy.physics.vector import Vector, express
from sympy.physics.vector.frame import _check_frame
from sympy.physics.vector.vector import _check_vector
__all__ = ['curl', 'divergence', 'gradient', 'is_conservative',
'is_solenoidal', 'scalar_potential',
'scalar_potential_difference']
def curl(vect, frame):
"""
Returns the curl of a vector field computed wrt the coordinate
symbols of the given frame.
Parameters
==========
vect : Vector
The vector operand
frame : ReferenceFrame
The reference frame to calculate the curl in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import curl
>>> R = ReferenceFrame('R')
>>> v1 = R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z
>>> curl(v1, R)
0
>>> v2 = R[0]*R[1]*R[2]*R.x
>>> curl(v2, R)
R_x*R_y*R.y - R_x*R_z*R.z
"""
_check_vector(vect)
if vect == 0:
return Vector(0)
vect = express(vect, frame, variables=True)
#A mechanical approach to avoid looping overheads
vectx = vect.dot(frame.x)
vecty = vect.dot(frame.y)
vectz = vect.dot(frame.z)
outvec = Vector(0)
outvec += (diff(vectz, frame[1]) - diff(vecty, frame[2])) * frame.x
outvec += (diff(vectx, frame[2]) - diff(vectz, frame[0])) * frame.y
outvec += (diff(vecty, frame[0]) - diff(vectx, frame[1])) * frame.z
return outvec
def divergence(vect, frame):
"""
Returns the divergence of a vector field computed wrt the coordinate
symbols of the given frame.
Parameters
==========
vect : Vector
The vector operand
frame : ReferenceFrame
The reference frame to calculate the divergence in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import divergence
>>> R = ReferenceFrame('R')
>>> v1 = R[0]*R[1]*R[2] * (R.x+R.y+R.z)
>>> divergence(v1, R)
R_x*R_y + R_x*R_z + R_y*R_z
>>> v2 = 2*R[1]*R[2]*R.y
>>> divergence(v2, R)
2*R_z
"""
_check_vector(vect)
if vect == 0:
return S.Zero
vect = express(vect, frame, variables=True)
vectx = vect.dot(frame.x)
vecty = vect.dot(frame.y)
vectz = vect.dot(frame.z)
out = S.Zero
out += diff(vectx, frame[0])
out += diff(vecty, frame[1])
out += diff(vectz, frame[2])
return out
def gradient(scalar, frame):
"""
Returns the vector gradient of a scalar field computed wrt the
coordinate symbols of the given frame.
Parameters
==========
scalar : sympifiable
The scalar field to take the gradient of
frame : ReferenceFrame
The frame to calculate the gradient in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import gradient
>>> R = ReferenceFrame('R')
>>> s1 = R[0]*R[1]*R[2]
>>> gradient(s1, R)
R_y*R_z*R.x + R_x*R_z*R.y + R_x*R_y*R.z
>>> s2 = 5*R[0]**2*R[2]
>>> gradient(s2, R)
10*R_x*R_z*R.x + 5*R_x**2*R.z
"""
_check_frame(frame)
outvec = Vector(0)
scalar = express(scalar, frame, variables=True)
for i, x in enumerate(frame):
outvec += diff(scalar, frame[i]) * x
return outvec
def is_conservative(field):
"""
Checks if a field is conservative.
Parameters
==========
field : Vector
The field to check for conservative property
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import is_conservative
>>> R = ReferenceFrame('R')
>>> is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z)
True
>>> is_conservative(R[2] * R.y)
False
"""
#Field is conservative irrespective of frame
#Take the first frame in the result of the
#separate method of Vector
if field == Vector(0):
return True
frame = list(field.separate())[0]
return curl(field, frame).simplify() == Vector(0)
def is_solenoidal(field):
"""
Checks if a field is solenoidal.
Parameters
==========
field : Vector
The field to check for solenoidal property
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import is_solenoidal
>>> R = ReferenceFrame('R')
>>> is_solenoidal(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z)
True
>>> is_solenoidal(R[1] * R.y)
False
"""
#Field is solenoidal irrespective of frame
#Take the first frame in the result of the
#separate method in Vector
if field == Vector(0):
return True
frame = list(field.separate())[0]
return divergence(field, frame).simplify() is S.Zero
def scalar_potential(field, frame):
"""
Returns the scalar potential function of a field in a given frame
(without the added integration constant).
Parameters
==========
field : Vector
The vector field whose scalar potential function is to be
calculated
frame : ReferenceFrame
The frame to do the calculation in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy.physics.vector import scalar_potential, gradient
>>> R = ReferenceFrame('R')
>>> scalar_potential(R.z, R) == R[2]
True
>>> scalar_field = 2*R[0]**2*R[1]*R[2]
>>> grad_field = gradient(scalar_field, R)
>>> scalar_potential(grad_field, R)
2*R_x**2*R_y*R_z
"""
#Check whether field is conservative
if not is_conservative(field):
raise ValueError("Field is not conservative")
if field == Vector(0):
return S.Zero
#Express the field exntirely in frame
#Substitute coordinate variables also
_check_frame(frame)
field = express(field, frame, variables=True)
#Make a list of dimensions of the frame
dimensions = [x for x in frame]
#Calculate scalar potential function
temp_function = integrate(field.dot(dimensions[0]), frame[0])
for i, dim in enumerate(dimensions[1:]):
partial_diff = diff(temp_function, frame[i + 1])
partial_diff = field.dot(dim) - partial_diff
temp_function += integrate(partial_diff, frame[i + 1])
return temp_function
def scalar_potential_difference(field, frame, point1, point2, origin):
"""
Returns the scalar potential difference between two points in a
certain frame, wrt a given field.
If a scalar field is provided, its values at the two points are
considered. If a conservative vector field is provided, the values
of its scalar potential function at the two points are used.
Returns (potential at position 2) - (potential at position 1)
Parameters
==========
field : Vector/sympyfiable
The field to calculate wrt
frame : ReferenceFrame
The frame to do the calculations in
point1 : Point
The initial Point in given frame
position2 : Point
The second Point in the given frame
origin : Point
The Point to use as reference point for position vector
calculation
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, Point
>>> from sympy.physics.vector import scalar_potential_difference
>>> R = ReferenceFrame('R')
>>> O = Point('O')
>>> P = O.locatenew('P', R[0]*R.x + R[1]*R.y + R[2]*R.z)
>>> vectfield = 4*R[0]*R[1]*R.x + 2*R[0]**2*R.y
>>> scalar_potential_difference(vectfield, R, O, P, O)
2*R_x**2*R_y
>>> Q = O.locatenew('O', 3*R.x + R.y + 2*R.z)
>>> scalar_potential_difference(vectfield, R, P, Q, O)
-2*R_x**2*R_y + 18
"""
_check_frame(frame)
if isinstance(field, Vector):
#Get the scalar potential function
scalar_fn = scalar_potential(field, frame)
else:
#Field is a scalar
scalar_fn = field
#Express positions in required frame
position1 = express(point1.pos_from(origin), frame, variables=True)
position2 = express(point2.pos_from(origin), frame, variables=True)
#Get the two positions as substitution dicts for coordinate variables
subs_dict1 = {}
subs_dict2 = {}
for i, x in enumerate(frame):
subs_dict1[frame[i]] = x.dot(position1)
subs_dict2[frame[i]] = x.dot(position2)
return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1)
|
b31580572899eebf8081195f89dbc721f0d6e3bbfc066cd8bab301f8f011528f | from sympy.core.backend import (diff, expand, sin, cos, sympify, eye, symbols,
ImmutableMatrix as Matrix, MatrixBase)
from sympy.core.symbol import (Dummy, Symbol)
from sympy.simplify.trigsimp import trigsimp
from sympy.solvers.solvers import solve
from sympy.physics.vector.vector import Vector, _check_vector
from sympy.utilities.misc import translate
from warnings import warn
__all__ = ['CoordinateSym', 'ReferenceFrame']
class CoordinateSym(Symbol):
"""
A coordinate symbol/base scalar associated wrt a Reference Frame.
Ideally, users should not instantiate this class. Instances of
this class must only be accessed through the corresponding frame
as 'frame[index]'.
CoordinateSyms having the same frame and index parameters are equal
(even though they may be instantiated separately).
Parameters
==========
name : string
The display name of the CoordinateSym
frame : ReferenceFrame
The reference frame this base scalar belongs to
index : 0, 1 or 2
The index of the dimension denoted by this coordinate variable
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, CoordinateSym
>>> A = ReferenceFrame('A')
>>> A[1]
A_y
>>> type(A[0])
<class 'sympy.physics.vector.frame.CoordinateSym'>
>>> a_y = CoordinateSym('a_y', A, 1)
>>> a_y == A[1]
True
"""
def __new__(cls, name, frame, index):
# We can't use the cached Symbol.__new__ because this class depends on
# frame and index, which are not passed to Symbol.__xnew__.
assumptions = {}
super()._sanitize(assumptions, cls)
obj = super().__xnew__(cls, name, **assumptions)
_check_frame(frame)
if index not in range(0, 3):
raise ValueError("Invalid index specified")
obj._id = (frame, index)
return obj
@property
def frame(self):
return self._id[0]
def __eq__(self, other):
#Check if the other object is a CoordinateSym of the same frame
#and same index
if isinstance(other, CoordinateSym):
if other._id == self._id:
return True
return False
def __ne__(self, other):
return not self == other
def __hash__(self):
return tuple((self._id[0].__hash__(), self._id[1])).__hash__()
class ReferenceFrame:
"""A reference frame in classical mechanics.
ReferenceFrame is a class used to represent a reference frame in classical
mechanics. It has a standard basis of three unit vectors in the frame's
x, y, and z directions.
It also can have a rotation relative to a parent frame; this rotation is
defined by a direction cosine matrix relating this frame's basis vectors to
the parent frame's basis vectors. It can also have an angular velocity
vector, defined in another frame.
"""
_count = 0
def __init__(self, name, indices=None, latexs=None, variables=None):
"""ReferenceFrame initialization method.
A ReferenceFrame has a set of orthonormal basis vectors, along with
orientations relative to other ReferenceFrames and angular velocities
relative to other ReferenceFrames.
Parameters
==========
indices : tuple of str
Enables the reference frame's basis unit vectors to be accessed by
Python's square bracket indexing notation using the provided three
indice strings and alters the printing of the unit vectors to
reflect this choice.
latexs : tuple of str
Alters the LaTeX printing of the reference frame's basis unit
vectors to the provided three valid LaTeX strings.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, vlatex
>>> N = ReferenceFrame('N')
>>> N.x
N.x
>>> O = ReferenceFrame('O', indices=('1', '2', '3'))
>>> O.x
O['1']
>>> O['1']
O['1']
>>> P = ReferenceFrame('P', latexs=('A1', 'A2', 'A3'))
>>> vlatex(P.x)
'A1'
symbols() can be used to create multiple Reference Frames in one step, for example:
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import symbols
>>> A, B, C = symbols('A B C', cls=ReferenceFrame)
>>> D, E = symbols('D E', cls=ReferenceFrame, indices=('1', '2', '3'))
>>> A[0]
A_x
>>> D.x
D['1']
>>> E.y
E['2']
>>> type(A) == type(D)
True
"""
if not isinstance(name, str):
raise TypeError('Need to supply a valid name')
# The if statements below are for custom printing of basis-vectors for
# each frame.
# First case, when custom indices are supplied
if indices is not None:
if not isinstance(indices, (tuple, list)):
raise TypeError('Supply the indices as a list')
if len(indices) != 3:
raise ValueError('Supply 3 indices')
for i in indices:
if not isinstance(i, str):
raise TypeError('Indices must be strings')
self.str_vecs = [(name + '[\'' + indices[0] + '\']'),
(name + '[\'' + indices[1] + '\']'),
(name + '[\'' + indices[2] + '\']')]
self.pretty_vecs = [(name.lower() + "_" + indices[0]),
(name.lower() + "_" + indices[1]),
(name.lower() + "_" + indices[2])]
self.latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[0])), (r"\mathbf{\hat{%s}_{%s}}" %
(name.lower(), indices[1])),
(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[2]))]
self.indices = indices
# Second case, when no custom indices are supplied
else:
self.str_vecs = [(name + '.x'), (name + '.y'), (name + '.z')]
self.pretty_vecs = [name.lower() + "_x",
name.lower() + "_y",
name.lower() + "_z"]
self.latex_vecs = [(r"\mathbf{\hat{%s}_x}" % name.lower()),
(r"\mathbf{\hat{%s}_y}" % name.lower()),
(r"\mathbf{\hat{%s}_z}" % name.lower())]
self.indices = ['x', 'y', 'z']
# Different step, for custom latex basis vectors
if latexs is not None:
if not isinstance(latexs, (tuple, list)):
raise TypeError('Supply the indices as a list')
if len(latexs) != 3:
raise ValueError('Supply 3 indices')
for i in latexs:
if not isinstance(i, str):
raise TypeError('Latex entries must be strings')
self.latex_vecs = latexs
self.name = name
self._var_dict = {}
#The _dcm_dict dictionary will only store the dcms of adjacent parent-child
#relationships. The _dcm_cache dictionary will store calculated dcm along with
#all content of _dcm_dict for faster retrieval of dcms.
self._dcm_dict = {}
self._dcm_cache = {}
self._ang_vel_dict = {}
self._ang_acc_dict = {}
self._dlist = [self._dcm_dict, self._ang_vel_dict, self._ang_acc_dict]
self._cur = 0
self._x = Vector([(Matrix([1, 0, 0]), self)])
self._y = Vector([(Matrix([0, 1, 0]), self)])
self._z = Vector([(Matrix([0, 0, 1]), self)])
#Associate coordinate symbols wrt this frame
if variables is not None:
if not isinstance(variables, (tuple, list)):
raise TypeError('Supply the variable names as a list/tuple')
if len(variables) != 3:
raise ValueError('Supply 3 variable names')
for i in variables:
if not isinstance(i, str):
raise TypeError('Variable names must be strings')
else:
variables = [name + '_x', name + '_y', name + '_z']
self.varlist = (CoordinateSym(variables[0], self, 0), \
CoordinateSym(variables[1], self, 1), \
CoordinateSym(variables[2], self, 2))
ReferenceFrame._count += 1
self.index = ReferenceFrame._count
def __getitem__(self, ind):
"""
Returns basis vector for the provided index, if the index is a string.
If the index is a number, returns the coordinate variable correspon-
-ding to that index.
"""
if not isinstance(ind, str):
if ind < 3:
return self.varlist[ind]
else:
raise ValueError("Invalid index provided")
if self.indices[0] == ind:
return self.x
if self.indices[1] == ind:
return self.y
if self.indices[2] == ind:
return self.z
else:
raise ValueError('Not a defined index')
def __iter__(self):
return iter([self.x, self.y, self.z])
def __str__(self):
"""Returns the name of the frame. """
return self.name
__repr__ = __str__
def _dict_list(self, other, num):
"""Returns an inclusive list of reference frames that connect this
reference frame to the provided reference frame.
Parameters
==========
other : ReferenceFrame
The other reference frame to look for a connecting relationship to.
num : integer
``0``, ``1``, and ``2`` will look for orientation, angular
velocity, and angular acceleration relationships between the two
frames, respectively.
Returns
=======
list
Inclusive list of reference frames that connect this reference
frame to the other reference frame.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame('A')
>>> B = ReferenceFrame('B')
>>> C = ReferenceFrame('C')
>>> D = ReferenceFrame('D')
>>> B.orient_axis(A, A.x, 1.0)
>>> C.orient_axis(B, B.x, 1.0)
>>> D.orient_axis(C, C.x, 1.0)
>>> D._dict_list(A, 0)
[D, C, B, A]
Raises
======
ValueError
When no path is found between the two reference frames or ``num``
is an incorrect value.
"""
connect_type = {0: 'orientation',
1: 'angular velocity',
2: 'angular acceleration'}
if num not in connect_type.keys():
raise ValueError('Valid values for num are 0, 1, or 2.')
possible_connecting_paths = [[self]]
oldlist = [[]]
while possible_connecting_paths != oldlist:
oldlist = possible_connecting_paths[:] # make a copy
for frame_list in possible_connecting_paths:
frames_adjacent_to_last = frame_list[-1]._dlist[num].keys()
for adjacent_frame in frames_adjacent_to_last:
if adjacent_frame not in frame_list:
connecting_path = frame_list + [adjacent_frame]
if connecting_path not in possible_connecting_paths:
possible_connecting_paths.append(connecting_path)
for connecting_path in oldlist:
if connecting_path[-1] != other:
possible_connecting_paths.remove(connecting_path)
possible_connecting_paths.sort(key=len)
if len(possible_connecting_paths) != 0:
return possible_connecting_paths[0] # selects the shortest path
msg = 'No connecting {} path found between {} and {}.'
raise ValueError(msg.format(connect_type[num], self.name, other.name))
def _w_diff_dcm(self, otherframe):
"""Angular velocity from time differentiating the DCM. """
from sympy.physics.vector.functions import dynamicsymbols
dcm2diff = otherframe.dcm(self)
diffed = dcm2diff.diff(dynamicsymbols._t)
angvelmat = diffed * dcm2diff.T
w1 = trigsimp(expand(angvelmat[7]), recursive=True)
w2 = trigsimp(expand(angvelmat[2]), recursive=True)
w3 = trigsimp(expand(angvelmat[3]), recursive=True)
return Vector([(Matrix([w1, w2, w3]), otherframe)])
def variable_map(self, otherframe):
"""
Returns a dictionary which expresses the coordinate variables
of this frame in terms of the variables of otherframe.
If Vector.simp is True, returns a simplified version of the mapped
values. Else, returns them without simplification.
Simplification of the expressions may take time.
Parameters
==========
otherframe : ReferenceFrame
The other frame to map the variables to
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> A = ReferenceFrame('A')
>>> q = dynamicsymbols('q')
>>> B = A.orientnew('B', 'Axis', [q, A.z])
>>> A.variable_map(B)
{A_x: B_x*cos(q(t)) - B_y*sin(q(t)), A_y: B_x*sin(q(t)) + B_y*cos(q(t)), A_z: B_z}
"""
_check_frame(otherframe)
if (otherframe, Vector.simp) in self._var_dict:
return self._var_dict[(otherframe, Vector.simp)]
else:
vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist)
mapping = {}
for i, x in enumerate(self):
if Vector.simp:
mapping[self.varlist[i]] = trigsimp(vars_matrix[i], method='fu')
else:
mapping[self.varlist[i]] = vars_matrix[i]
self._var_dict[(otherframe, Vector.simp)] = mapping
return mapping
def ang_acc_in(self, otherframe):
"""Returns the angular acceleration Vector of the ReferenceFrame.
Effectively returns the Vector:
^N alpha ^B
which represent the angular acceleration of B in N, where B is self, and
N is otherframe.
Parameters
==========
otherframe : ReferenceFrame
The ReferenceFrame which the angular acceleration is returned in.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_acc(N, V)
>>> A.ang_acc_in(N)
10*N.x
"""
_check_frame(otherframe)
if otherframe in self._ang_acc_dict:
return self._ang_acc_dict[otherframe]
else:
return self.ang_vel_in(otherframe).dt(otherframe)
def ang_vel_in(self, otherframe):
"""Returns the angular velocity Vector of the ReferenceFrame.
Effectively returns the Vector:
^N omega ^B
which represent the angular velocity of B in N, where B is self, and
N is otherframe.
Parameters
==========
otherframe : ReferenceFrame
The ReferenceFrame which the angular velocity is returned in.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_vel(N, V)
>>> A.ang_vel_in(N)
10*N.x
"""
_check_frame(otherframe)
flist = self._dict_list(otherframe, 1)
outvec = Vector(0)
for i in range(len(flist) - 1):
outvec += flist[i]._ang_vel_dict[flist[i + 1]]
return outvec
def dcm(self, otherframe):
r"""Returns the direction cosine matrix relative to the provided
reference frame.
The returned matrix can be used to express the orthogonal unit vectors
of this frame in terms of the orthogonal unit vectors of
``otherframe``.
Parameters
==========
otherframe : ReferenceFrame
The reference frame which the direction cosine matrix of this frame
is formed relative to.
Examples
========
The following example rotates the reference frame A relative to N by a
simple rotation and then calculates the direction cosine matrix of N
relative to A.
>>> from sympy import symbols, sin, cos
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', (q1, N.x))
>>> N.dcm(A)
Matrix([
[1, 0, 0],
[0, cos(q1), -sin(q1)],
[0, sin(q1), cos(q1)]])
The second row of the above direction cosine matrix represents the
``N.y`` unit vector in N expressed in A. Like so:
>>> Ny = 0*A.x + cos(q1)*A.y - sin(q1)*A.z
Thus, expressing ``N.y`` in A should return the same result:
>>> N.y.express(A)
cos(q1)*A.y - sin(q1)*A.z
Notes
=====
It is import to know what form of the direction cosine matrix is
returned. If ``B.dcm(A)`` is called, it means the "direction cosine
matrix of B relative to A". This is the matrix :math:`^{\mathbf{A}} \mathbf{R} ^{\mathbf{B}}`
shown in the following relationship:
.. math::
\begin{bmatrix}
\hat{\mathbf{b}}_1 \\
\hat{\mathbf{b}}_2 \\
\hat{\mathbf{b}}_3
\end{bmatrix}
=
{}^A\mathbf{R}^B
\begin{bmatrix}
\hat{\mathbf{a}}_1 \\
\hat{\mathbf{a}}_2 \\
\hat{\mathbf{a}}_3
\end{bmatrix}.
:math:`{}^A\mathbf{R}^B` is the matrix that expresses the B unit
vectors in terms of the A unit vectors.
"""
_check_frame(otherframe)
# Check if the dcm wrt that frame has already been calculated
if otherframe in self._dcm_cache:
return self._dcm_cache[otherframe]
flist = self._dict_list(otherframe, 0)
outdcm = eye(3)
for i in range(len(flist) - 1):
outdcm = outdcm * flist[i]._dcm_dict[flist[i + 1]]
# After calculation, store the dcm in dcm cache for faster future
# retrieval
self._dcm_cache[otherframe] = outdcm
otherframe._dcm_cache[self] = outdcm.T
return outdcm
def _dcm(self, parent, parent_orient):
# If parent.oreint(self) is already defined,then
# update the _dcm_dict of parent while over write
# all content of self._dcm_dict and self._dcm_cache
# with new dcm relation.
# Else update _dcm_cache and _dcm_dict of both
# self and parent.
frames = self._dcm_cache.keys()
dcm_dict_del = []
dcm_cache_del = []
if parent in frames:
for frame in frames:
if frame in self._dcm_dict:
dcm_dict_del += [frame]
dcm_cache_del += [frame]
# Reset the _dcm_cache of this frame, and remove it from the
# _dcm_caches of the frames it is linked to. Also remove it from the
# _dcm_dict of its parent
for frame in dcm_dict_del:
del frame._dcm_dict[self]
for frame in dcm_cache_del:
del frame._dcm_cache[self]
# Reset the _dcm_dict
self._dcm_dict = self._dlist[0] = {}
# Reset the _dcm_cache
self._dcm_cache = {}
else:
#Check for loops and raise warning accordingly.
visited = []
queue = list(frames)
cont = True #Flag to control queue loop.
while queue and cont:
node = queue.pop(0)
if node not in visited:
visited.append(node)
neighbors = node._dcm_dict.keys()
for neighbor in neighbors:
if neighbor == parent:
warn('Loops are defined among the orientation of frames.' + \
' This is likely not desired and may cause errors in your calculations.')
cont = False
break
queue.append(neighbor)
# Add the dcm relationship to _dcm_dict
self._dcm_dict.update({parent: parent_orient.T})
parent._dcm_dict.update({self: parent_orient})
# Update the dcm cache
self._dcm_cache.update({parent: parent_orient.T})
parent._dcm_cache.update({self: parent_orient})
def orient_axis(self, parent, axis, angle):
"""Sets the orientation of this reference frame with respect to a
parent reference frame by rotating through an angle about an axis fixed
in the parent reference frame.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
axis : Vector
Vector fixed in the parent frame about about which this frame is
rotated. It need not be a unit vector and the rotation follows the
right hand rule.
angle : sympifiable
Angle in radians by which it the frame is to be rotated.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B.orient_axis(N, N.x, q1)
The ``orient_axis()`` method generates a direction cosine matrix and
its transpose which defines the orientation of B relative to N and vice
versa. Once orient is called, ``dcm()`` outputs the appropriate
direction cosine matrix:
>>> B.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
>>> N.dcm(B)
Matrix([
[1, 0, 0],
[0, cos(q1), -sin(q1)],
[0, sin(q1), cos(q1)]])
The following two lines show that the sense of the rotation can be
defined by negating the vector direction or the angle. Both lines
produce the same result.
>>> B.orient_axis(N, -N.x, q1)
>>> B.orient_axis(N, N.x, -q1)
"""
from sympy.physics.vector.functions import dynamicsymbols
_check_frame(parent)
if not isinstance(axis, Vector) and isinstance(angle, Vector):
axis, angle = angle, axis
axis = _check_vector(axis)
amount = sympify(angle)
theta = amount
parent_orient_axis = []
if not axis.dt(parent) == 0:
raise ValueError('Axis cannot be time-varying.')
unit_axis = axis.express(parent).normalize()
unit_col = unit_axis.args[0][0]
parent_orient_axis = (
(eye(3) - unit_col * unit_col.T) * cos(theta) +
Matrix([[0, -unit_col[2], unit_col[1]],
[unit_col[2], 0, -unit_col[0]],
[-unit_col[1], unit_col[0], 0]]) *
sin(theta) + unit_col * unit_col.T)
self._dcm(parent, parent_orient_axis)
thetad = (amount).diff(dynamicsymbols._t)
wvec = thetad*axis.express(parent).normalize()
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_explicit(self, parent, dcm):
"""Sets the orientation of this reference frame relative to a parent
reference frame by explicitly setting the direction cosine matrix.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
dcm : Matrix, shape(3, 3)
Direction cosine matrix that specifies the relative rotation
between the two reference frames.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols, Matrix, sin, cos
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> A = ReferenceFrame('A')
>>> B = ReferenceFrame('B')
>>> N = ReferenceFrame('N')
A simple rotation of ``A`` relative to ``N`` about ``N.x`` is defined
by the following direction cosine matrix:
>>> dcm = Matrix([[1, 0, 0],
... [0, cos(q1), -sin(q1)],
... [0, sin(q1), cos(q1)]])
>>> A.orient_explicit(N, dcm)
>>> A.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
This is equivalent to using ``orient_axis()``:
>>> B.orient_axis(N, N.x, q1)
>>> B.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
**Note carefully that** ``N.dcm(B)`` **(the transpose) would be passed
into** ``orient_explicit()`` **for** ``A.dcm(N)`` **to match**
``B.dcm(N)``:
>>> A.orient_explicit(N, N.dcm(B))
>>> A.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
"""
_check_frame(parent)
# amounts must be a Matrix type object
# (e.g. sympy.matrices.dense.MutableDenseMatrix).
if not isinstance(dcm, MatrixBase):
raise TypeError("Amounts must be a SymPy Matrix type object.")
parent_orient_dcm = []
parent_orient_dcm = dcm
self._dcm(parent, parent_orient_dcm)
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def _rot(self, axis, angle):
"""DCM for simple axis 1,2,or 3 rotations."""
if axis == 1:
return Matrix([[1, 0, 0],
[0, cos(angle), -sin(angle)],
[0, sin(angle), cos(angle)]])
elif axis == 2:
return Matrix([[cos(angle), 0, sin(angle)],
[0, 1, 0],
[-sin(angle), 0, cos(angle)]])
elif axis == 3:
return Matrix([[cos(angle), -sin(angle), 0],
[sin(angle), cos(angle), 0],
[0, 0, 1]])
def orient_body_fixed(self, parent, angles, rotation_order):
"""Rotates this reference frame relative to the parent reference frame
by right hand rotating through three successive body fixed simple axis
rotations. Each subsequent axis of rotation is about the "body fixed"
unit vectors of a new intermediate reference frame. This type of
rotation is also referred to rotating through the `Euler and Tait-Bryan
Angles`_.
.. _Euler and Tait-Bryan Angles: https://en.wikipedia.org/wiki/Euler_angles
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
angles : 3-tuple of sympifiable
Three angles in radians used for the successive rotations.
rotation_order : 3 character string or 3 digit integer
Order of the rotations about each intermediate reference frames'
unit vectors. The Euler rotation about the X, Z', X'' axes can be
specified by the strings ``'XZX'``, ``'131'``, or the integer
``131``. There are 12 unique valid rotation orders (6 Euler and 6
Tait-Bryan): zxz, xyx, yzy, zyz, xzx, yxy, xyz, yzx, zxy, xzy, zyx,
and yxz.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1, q2, q3 = symbols('q1, q2, q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B1 = ReferenceFrame('B1')
>>> B2 = ReferenceFrame('B2')
>>> B3 = ReferenceFrame('B3')
For example, a classic Euler Angle rotation can be done by:
>>> B.orient_body_fixed(N, (q1, q2, q3), 'XYX')
>>> B.dcm(N)
Matrix([
[ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)],
[sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)],
[sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]])
This rotates reference frame B relative to reference frame N through
``q1`` about ``N.x``, then rotates B again through ``q2`` about
``B.y``, and finally through ``q3`` about ``B.x``. It is equivalent to
three successive ``orient_axis()`` calls:
>>> B1.orient_axis(N, N.x, q1)
>>> B2.orient_axis(B1, B1.y, q2)
>>> B3.orient_axis(B2, B2.x, q3)
>>> B3.dcm(N)
Matrix([
[ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)],
[sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)],
[sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]])
Acceptable rotation orders are of length 3, expressed in as a string
``'XYZ'`` or ``'123'`` or integer ``123``. Rotations about an axis
twice in a row are prohibited.
>>> B.orient_body_fixed(N, (q1, q2, 0), 'ZXZ')
>>> B.orient_body_fixed(N, (q1, q2, 0), '121')
>>> B.orient_body_fixed(N, (q1, q2, q3), 123)
"""
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not isinstance(v, Vector):
amounts[i] = sympify(v)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
# make sure XYZ => 123
rot_order = translate(str(rotation_order), 'XYZxyz', '123123')
if rot_order not in approved_orders:
raise TypeError('The rotation order is not a valid order.')
parent_orient_body = []
if not (len(amounts) == 3 & len(rot_order) == 3):
raise TypeError('Body orientation takes 3 values & 3 orders')
a1 = int(rot_order[0])
a2 = int(rot_order[1])
a3 = int(rot_order[2])
parent_orient_body = (self._rot(a1, amounts[0]) *
self._rot(a2, amounts[1]) *
self._rot(a3, amounts[2]))
self._dcm(parent, parent_orient_body)
try:
from sympy.polys.polyerrors import CoercionFailed
from sympy.physics.vector.functions import kinematic_equations
q1, q2, q3 = amounts
u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy)
templist = kinematic_equations([u1, u2, u3], [q1, q2, q3],
'body', rot_order)
templist = [expand(i) for i in templist]
td = solve(templist, [u1, u2, u3])
u1 = expand(td[u1])
u2 = expand(td[u2])
u3 = expand(td[u3])
wvec = u1 * self.x + u2 * self.y + u3 * self.z
except (CoercionFailed, AssertionError):
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_space_fixed(self, parent, angles, rotation_order):
"""Rotates this reference frame relative to the parent reference frame
by right hand rotating through three successive space fixed simple axis
rotations. Each subsequent axis of rotation is about the "space fixed"
unit vectors of the parent reference frame.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
angles : 3-tuple of sympifiable
Three angles in radians used for the successive rotations.
rotation_order : 3 character string or 3 digit integer
Order of the rotations about the parent reference frame's unit
vectors. The order can be specified by the strings ``'XZX'``,
``'131'``, or the integer ``131``. There are 12 unique valid
rotation orders.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1, q2, q3 = symbols('q1, q2, q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B1 = ReferenceFrame('B1')
>>> B2 = ReferenceFrame('B2')
>>> B3 = ReferenceFrame('B3')
>>> B.orient_space_fixed(N, (q1, q2, q3), '312')
>>> B.dcm(N)
Matrix([
[ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)],
[-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)],
[ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]])
is equivalent to:
>>> B1.orient_axis(N, N.z, q1)
>>> B2.orient_axis(B1, N.x, q2)
>>> B3.orient_axis(B2, N.y, q3)
>>> B3.dcm(N).simplify()
Matrix([
[ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)],
[-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)],
[ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]])
It is worth noting that space-fixed and body-fixed rotations are
related by the order of the rotations, i.e. the reverse order of body
fixed will give space fixed and vice versa.
>>> B.orient_space_fixed(N, (q1, q2, q3), '231')
>>> B.dcm(N)
Matrix([
[cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],
[ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)],
[sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]])
>>> B.orient_body_fixed(N, (q3, q2, q1), '132')
>>> B.dcm(N)
Matrix([
[cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],
[ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)],
[sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]])
"""
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not isinstance(v, Vector):
amounts[i] = sympify(v)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
# make sure XYZ => 123
rot_order = translate(str(rotation_order), 'XYZxyz', '123123')
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
parent_orient_space = []
if not (len(amounts) == 3 & len(rot_order) == 3):
raise TypeError('Space orientation takes 3 values & 3 orders')
a1 = int(rot_order[0])
a2 = int(rot_order[1])
a3 = int(rot_order[2])
parent_orient_space = (self._rot(a3, amounts[2]) *
self._rot(a2, amounts[1]) *
self._rot(a1, amounts[0]))
self._dcm(parent, parent_orient_space)
try:
from sympy.polys.polyerrors import CoercionFailed
from sympy.physics.vector.functions import kinematic_equations
q1, q2, q3 = amounts
u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy)
templist = kinematic_equations([u1, u2, u3], [q1, q2, q3],
'space', rot_order)
templist = [expand(i) for i in templist]
td = solve(templist, [u1, u2, u3])
u1 = expand(td[u1])
u2 = expand(td[u2])
u3 = expand(td[u3])
wvec = u1 * self.x + u2 * self.y + u3 * self.z
except (CoercionFailed, AssertionError):
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_quaternion(self, parent, numbers):
"""Sets the orientation of this reference frame relative to a parent
reference frame via an orientation quaternion. An orientation
quaternion is defined as a finite rotation a unit vector, ``(lambda_x,
lambda_y, lambda_z)``, by an angle ``theta``. The orientation
quaternion is described by four parameters:
- ``q0 = cos(theta/2)``
- ``q1 = lambda_x*sin(theta/2)``
- ``q2 = lambda_y*sin(theta/2)``
- ``q3 = lambda_z*sin(theta/2)``
See `Quaternions and Spatial Rotation
<https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ on
Wikipedia for more information.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
numbers : 4-tuple of sympifiable
The four quaternion scalar numbers as defined above: ``q0``,
``q1``, ``q2``, ``q3``.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
Set the orientation:
>>> B.orient_quaternion(N, (q0, q1, q2, q3))
>>> B.dcm(N)
Matrix([
[q0**2 + q1**2 - q2**2 - q3**2, 2*q0*q3 + 2*q1*q2, -2*q0*q2 + 2*q1*q3],
[ -2*q0*q3 + 2*q1*q2, q0**2 - q1**2 + q2**2 - q3**2, 2*q0*q1 + 2*q2*q3],
[ 2*q0*q2 + 2*q1*q3, -2*q0*q1 + 2*q2*q3, q0**2 - q1**2 - q2**2 + q3**2]])
"""
from sympy.physics.vector.functions import dynamicsymbols
_check_frame(parent)
numbers = list(numbers)
for i, v in enumerate(numbers):
if not isinstance(v, Vector):
numbers[i] = sympify(v)
parent_orient_quaternion = []
if not (isinstance(numbers, (list, tuple)) & (len(numbers) == 4)):
raise TypeError('Amounts are a list or tuple of length 4')
q0, q1, q2, q3 = numbers
parent_orient_quaternion = (
Matrix([[q0**2 + q1**2 - q2**2 - q3**2,
2 * (q1 * q2 - q0 * q3),
2 * (q0 * q2 + q1 * q3)],
[2 * (q1 * q2 + q0 * q3),
q0**2 - q1**2 + q2**2 - q3**2,
2 * (q2 * q3 - q0 * q1)],
[2 * (q1 * q3 - q0 * q2),
2 * (q0 * q1 + q2 * q3),
q0**2 - q1**2 - q2**2 + q3**2]]))
self._dcm(parent, parent_orient_quaternion)
t = dynamicsymbols._t
q0, q1, q2, q3 = numbers
q0d = diff(q0, t)
q1d = diff(q1, t)
q2d = diff(q2, t)
q3d = diff(q3, t)
w1 = 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1)
w2 = 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2)
w3 = 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3)
wvec = Vector([(Matrix([w1, w2, w3]), self)])
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient(self, parent, rot_type, amounts, rot_order=''):
"""Sets the orientation of this reference frame relative to another
(parent) reference frame.
.. note:: It is now recommended to use the ``.orient_axis,
.orient_body_fixed, .orient_space_fixed, .orient_quaternion``
methods for the different rotation types.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
rot_type : str
The method used to generate the direction cosine matrix. Supported
methods are:
- ``'Axis'``: simple rotations about a single common axis
- ``'DCM'``: for setting the direction cosine matrix directly
- ``'Body'``: three successive rotations about new intermediate
axes, also called "Euler and Tait-Bryan angles"
- ``'Space'``: three successive rotations about the parent
frames' unit vectors
- ``'Quaternion'``: rotations defined by four parameters which
result in a singularity free direction cosine matrix
amounts :
Expressions defining the rotation angles or direction cosine
matrix. These must match the ``rot_type``. See examples below for
details. The input types are:
- ``'Axis'``: 2-tuple (expr/sym/func, Vector)
- ``'DCM'``: Matrix, shape(3,3)
- ``'Body'``: 3-tuple of expressions, symbols, or functions
- ``'Space'``: 3-tuple of expressions, symbols, or functions
- ``'Quaternion'``: 4-tuple of expressions, symbols, or
functions
rot_order : str or int, optional
If applicable, the order of the successive of rotations. The string
``'123'`` and integer ``123`` are equivalent, for example. Required
for ``'Body'`` and ``'Space'``.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
"""
_check_frame(parent)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.upper()
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
if rot_type == 'AXIS':
self.orient_axis(parent, amounts[1], amounts[0])
elif rot_type == 'DCM':
self.orient_explicit(parent, amounts)
elif rot_type == 'BODY':
self.orient_body_fixed(parent, amounts, rot_order)
elif rot_type == 'SPACE':
self.orient_space_fixed(parent, amounts, rot_order)
elif rot_type == 'QUATERNION':
self.orient_quaternion(parent, amounts)
else:
raise NotImplementedError('That is not an implemented rotation')
def orientnew(self, newname, rot_type, amounts, rot_order='',
variables=None, indices=None, latexs=None):
r"""Returns a new reference frame oriented with respect to this
reference frame.
See ``ReferenceFrame.orient()`` for detailed examples of how to orient
reference frames.
Parameters
==========
newname : str
Name for the new reference frame.
rot_type : str
The method used to generate the direction cosine matrix. Supported
methods are:
- ``'Axis'``: simple rotations about a single common axis
- ``'DCM'``: for setting the direction cosine matrix directly
- ``'Body'``: three successive rotations about new intermediate
axes, also called "Euler and Tait-Bryan angles"
- ``'Space'``: three successive rotations about the parent
frames' unit vectors
- ``'Quaternion'``: rotations defined by four parameters which
result in a singularity free direction cosine matrix
amounts :
Expressions defining the rotation angles or direction cosine
matrix. These must match the ``rot_type``. See examples below for
details. The input types are:
- ``'Axis'``: 2-tuple (expr/sym/func, Vector)
- ``'DCM'``: Matrix, shape(3,3)
- ``'Body'``: 3-tuple of expressions, symbols, or functions
- ``'Space'``: 3-tuple of expressions, symbols, or functions
- ``'Quaternion'``: 4-tuple of expressions, symbols, or
functions
rot_order : str or int, optional
If applicable, the order of the successive of rotations. The string
``'123'`` and integer ``123`` are equivalent, for example. Required
for ``'Body'`` and ``'Space'``.
indices : tuple of str
Enables the reference frame's basis unit vectors to be accessed by
Python's square bracket indexing notation using the provided three
indice strings and alters the printing of the unit vectors to
reflect this choice.
latexs : tuple of str
Alters the LaTeX printing of the reference frame's basis unit
vectors to the provided three valid LaTeX strings.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, vlatex
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
>>> N = ReferenceFrame('N')
Create a new reference frame A rotated relative to N through a simple
rotation.
>>> A = N.orientnew('A', 'Axis', (q0, N.x))
Create a new reference frame B rotated relative to N through body-fixed
rotations.
>>> B = N.orientnew('B', 'Body', (q1, q2, q3), '123')
Create a new reference frame C rotated relative to N through a simple
rotation with unique indices and LaTeX printing.
>>> C = N.orientnew('C', 'Axis', (q0, N.x), indices=('1', '2', '3'),
... latexs=(r'\hat{\mathbf{c}}_1',r'\hat{\mathbf{c}}_2',
... r'\hat{\mathbf{c}}_3'))
>>> C['1']
C['1']
>>> print(vlatex(C['1']))
\hat{\mathbf{c}}_1
"""
newframe = self.__class__(newname, variables=variables,
indices=indices, latexs=latexs)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.upper()
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
if rot_type == 'AXIS':
newframe.orient_axis(self, amounts[1], amounts[0])
elif rot_type == 'DCM':
newframe.orient_explicit(self, amounts)
elif rot_type == 'BODY':
newframe.orient_body_fixed(self, amounts, rot_order)
elif rot_type == 'SPACE':
newframe.orient_space_fixed(self, amounts, rot_order)
elif rot_type == 'QUATERNION':
newframe.orient_quaternion(self, amounts)
else:
raise NotImplementedError('That is not an implemented rotation')
return newframe
def set_ang_acc(self, otherframe, value):
"""Define the angular acceleration Vector in a ReferenceFrame.
Defines the angular acceleration of this ReferenceFrame, in another.
Angular acceleration can be defined with respect to multiple different
ReferenceFrames. Care must be taken to not create loops which are
inconsistent.
Parameters
==========
otherframe : ReferenceFrame
A ReferenceFrame to define the angular acceleration in
value : Vector
The Vector representing angular acceleration
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_acc(N, V)
>>> A.ang_acc_in(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(otherframe)
self._ang_acc_dict.update({otherframe: value})
otherframe._ang_acc_dict.update({self: -value})
def set_ang_vel(self, otherframe, value):
"""Define the angular velocity vector in a ReferenceFrame.
Defines the angular velocity of this ReferenceFrame, in another.
Angular velocity can be defined with respect to multiple different
ReferenceFrames. Care must be taken to not create loops which are
inconsistent.
Parameters
==========
otherframe : ReferenceFrame
A ReferenceFrame to define the angular velocity in
value : Vector
The Vector representing angular velocity
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_vel(N, V)
>>> A.ang_vel_in(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(otherframe)
self._ang_vel_dict.update({otherframe: value})
otherframe._ang_vel_dict.update({self: -value})
@property
def x(self):
"""The basis Vector for the ReferenceFrame, in the x direction. """
return self._x
@property
def y(self):
"""The basis Vector for the ReferenceFrame, in the y direction. """
return self._y
@property
def z(self):
"""The basis Vector for the ReferenceFrame, in the z direction. """
return self._z
def partial_velocity(self, frame, *gen_speeds):
"""Returns the partial angular velocities of this frame in the given
frame with respect to one or more provided generalized speeds.
Parameters
==========
frame : ReferenceFrame
The frame with which the angular velocity is defined in.
gen_speeds : functions of time
The generalized speeds.
Returns
=======
partial_velocities : tuple of Vector
The partial angular velocity vectors corresponding to the provided
generalized speeds.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> A.set_ang_vel(N, u1 * A.x + u2 * N.y)
>>> A.partial_velocity(N, u1)
A.x
>>> A.partial_velocity(N, u1, u2)
(A.x, N.y)
"""
partials = [self.ang_vel_in(frame).diff(speed, frame, var_in_dcm=False)
for speed in gen_speeds]
if len(partials) == 1:
return partials[0]
else:
return tuple(partials)
def _check_frame(other):
from .vector import VectorTypeError
if not isinstance(other, ReferenceFrame):
raise VectorTypeError(other, ReferenceFrame('A'))
|
2ee2c6ee8c8f64e5b2e1445c96a9da59bd3cdf8506c2da03c54adc77f427f891 | from sympy.core.backend import sympify, Add, ImmutableMatrix as Matrix
from sympy.core.evalf import EvalfMixin
from sympy.printing.defaults import Printable
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['Dyadic']
class Dyadic(Printable, EvalfMixin):
"""A Dyadic object.
See:
https://en.wikipedia.org/wiki/Dyadic_tensor
Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
A more powerful way to represent a rigid body's inertia. While it is more
complex, by choosing Dyadic components to be in body fixed basis vectors,
the resulting matrix is equivalent to the inertia tensor.
"""
is_number = False
def __init__(self, inlist):
"""
Just like Vector's init, you shouldn't call this unless creating a
zero dyadic.
zd = Dyadic(0)
Stores a Dyadic as a list of lists; the inner list has the measure
number and the two unit vectors; the outerlist holds each unique
unit vector pair.
"""
self.args = []
if inlist == 0:
inlist = []
while len(inlist) != 0:
added = 0
for i, v in enumerate(self.args):
if ((str(inlist[0][1]) == str(self.args[i][1])) and
(str(inlist[0][2]) == str(self.args[i][2]))):
self.args[i] = (self.args[i][0] + inlist[0][0],
inlist[0][1], inlist[0][2])
inlist.remove(inlist[0])
added = 1
break
if added != 1:
self.args.append(inlist[0])
inlist.remove(inlist[0])
i = 0
# This code is to remove empty parts from the list
while i < len(self.args):
if ((self.args[i][0] == 0) | (self.args[i][1] == 0) |
(self.args[i][2] == 0)):
self.args.remove(self.args[i])
i -= 1
i += 1
@property
def func(self):
"""Returns the class Dyadic. """
return Dyadic
def __add__(self, other):
"""The add operator for Dyadic. """
other = _check_dyadic(other)
return Dyadic(self.args + other.args)
def __and__(self, other):
"""The inner product operator for a Dyadic and a Dyadic or Vector.
Parameters
==========
other : Dyadic or Vector
The other Dyadic or Vector to take the inner product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> D1 = outer(N.x, N.y)
>>> D2 = outer(N.y, N.y)
>>> D1.dot(D2)
(N.x|N.y)
>>> D1.dot(N.y)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
if isinstance(other, Dyadic):
other = _check_dyadic(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
ol += v[0] * v2[0] * (v[2] & v2[1]) * (v[1] | v2[2])
else:
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[1] * (v[2] & other)
return ol
def __truediv__(self, other):
"""Divides the Dyadic by a sympifyable expression. """
return self.__mul__(1 / other)
def __eq__(self, other):
"""Tests for equality.
Is currently weak; needs stronger comparison testing
"""
if other == 0:
other = Dyadic(0)
other = _check_dyadic(other)
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
return set(self.args) == set(other.args)
def __mul__(self, other):
"""Multiplies the Dyadic by a sympifyable expression.
Parameters
==========
other : Sympafiable
The scalar to multiply this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> 5 * d
5*(N.x|N.x)
"""
newlist = [v for v in self.args]
for i, v in enumerate(newlist):
newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1],
newlist[i][2])
return Dyadic(newlist)
def __ne__(self, other):
return not self == other
def __neg__(self):
return self * -1
def _latex(self, printer):
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + ' + printer._print(ar[i][1]) + r"\otimes " +
printer._print(ar[i][2]))
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - ' +
printer._print(ar[i][1]) +
r"\otimes " +
printer._print(ar[i][2]))
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = '(%s)' % arg_str
if arg_str.startswith('-'):
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + printer._print(ar[i][1]) +
r"\otimes " + printer._print(ar[i][2]))
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
e = self
class Fake:
baseline = 0
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
mpp = printer
if len(ar) == 0:
return str(0)
bar = "\N{CIRCLED TIMES}" if printer._use_unicode else "|"
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.extend([" + ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.extend([" - ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
if isinstance(ar[i][0], Add):
arg_str = mpp._print(
ar[i][0]).parens()[0]
else:
arg_str = mpp.doprint(ar[i][0])
if arg_str.startswith("-"):
arg_str = arg_str[1:]
str_start = " - "
else:
str_start = " + "
ol.extend([str_start, arg_str, " ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
outstr = "".join(ol)
if outstr.startswith(" + "):
outstr = outstr[3:]
elif outstr.startswith(" "):
outstr = outstr[1:]
return outstr
return Fake()
def __rand__(self, other):
"""The inner product operator for a Vector or Dyadic, and a Dyadic
This is for: Vector dot Dyadic
Parameters
==========
other : Vector
The vector we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> dot(N.x, d)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[2] * (v[1] & other)
return ol
def __rsub__(self, other):
return (-1 * self) + other
def __rxor__(self, other):
"""For a cross product in the form: Vector x Dyadic
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(N.y, d)
- (N.z|N.x)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * ((other ^ v[1]) | v[2])
return ol
def _sympystr(self, printer):
"""Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return printer._print(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')')
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - (' + printer._print(ar[i][1]) + '|' + printer._print(ar[i][2]) + ')')
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*(' + printer._print(ar[i][1]) +
'|' + printer._print(ar[i][2]) + ')')
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""For a cross product in the form: Dyadic x Vector.
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(d, N.y)
(N.x|N.z)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * (v[1] | (v[2] ^ other))
return ol
__radd__ = __add__
__rmul__ = __mul__
def express(self, frame1, frame2=None):
"""Expresses this Dyadic in alternate frame(s)
The first frame is the list side expression, the second frame is the
right side; if Dyadic is in form A.x|B.y, you can express it in two
different frames. If no second frame is given, the Dyadic is
expressed in only one frame.
Calls the global express function
Parameters
==========
frame1 : ReferenceFrame
The frame to express the left side of the Dyadic in
frame2 : ReferenceFrame
If provided, the frame to express the right side of the Dyadic in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.express(B, N)
cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x)
"""
from sympy.physics.vector.functions import express
return express(self, frame1, frame2)
def to_matrix(self, reference_frame, second_reference_frame=None):
"""Returns the matrix form of the dyadic with respect to one or two
reference frames.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows and columns of the matrix
correspond to. If a second reference frame is provided, this
only corresponds to the rows of the matrix.
second_reference_frame : ReferenceFrame, optional, default=None
The reference frame that the columns of the matrix correspond
to.
Returns
-------
matrix : ImmutableMatrix, shape(3,3)
The matrix that gives the 2D tensor form.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, Vector
>>> Vector.simp = True
>>> from sympy.physics.mechanics import inertia
>>> Ixx, Iyy, Izz, Ixy, Iyz, Ixz = symbols('Ixx, Iyy, Izz, Ixy, Iyz, Ixz')
>>> N = ReferenceFrame('N')
>>> inertia_dyadic = inertia(N, Ixx, Iyy, Izz, Ixy, Iyz, Ixz)
>>> inertia_dyadic.to_matrix(N)
Matrix([
[Ixx, Ixy, Ixz],
[Ixy, Iyy, Iyz],
[Ixz, Iyz, Izz]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> inertia_dyadic.to_matrix(A)
Matrix([
[ Ixx, Ixy*cos(beta) + Ixz*sin(beta), -Ixy*sin(beta) + Ixz*cos(beta)],
[ Ixy*cos(beta) + Ixz*sin(beta), Iyy*cos(2*beta)/2 + Iyy/2 + Iyz*sin(2*beta) - Izz*cos(2*beta)/2 + Izz/2, -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2],
[-Ixy*sin(beta) + Ixz*cos(beta), -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2, -Iyy*cos(2*beta)/2 + Iyy/2 - Iyz*sin(2*beta) + Izz*cos(2*beta)/2 + Izz/2]])
"""
if second_reference_frame is None:
second_reference_frame = reference_frame
return Matrix([i.dot(self).dot(j) for i in reference_frame for j in
second_reference_frame]).reshape(3, 3)
def doit(self, **hints):
"""Calls .doit() on each term in the Dyadic"""
return sum([Dyadic([(v[0].doit(**hints), v[1], v[2])])
for v in self.args], Dyadic(0))
def dt(self, frame):
"""Take the time derivative of this Dyadic in a frame.
This function calls the global time_derivative method
Parameters
==========
frame : ReferenceFrame
The frame to take the time derivative in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.dt(B)
- q'*(N.y|N.x) - q'*(N.x|N.y)
"""
from sympy.physics.vector.functions import time_derivative
return time_derivative(self, frame)
def simplify(self):
"""Returns a simplified Dyadic."""
out = Dyadic(0)
for v in self.args:
out += Dyadic([(v[0].simplify(), v[1], v[2])])
return out
def subs(self, *args, **kwargs):
"""Substitution on the Dyadic.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = s*(N.x|N.x)
>>> a.subs({s: 2})
2*(N.x|N.x)
"""
return sum([Dyadic([(v[0].subs(*args, **kwargs), v[1], v[2])])
for v in self.args], Dyadic(0))
def applyfunc(self, f):
"""Apply a function to each component of a Dyadic."""
if not callable(f):
raise TypeError("`f` must be callable.")
out = Dyadic(0)
for a, b, c in self.args:
out += f(a) * (b|c)
return out
dot = __and__
cross = __xor__
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
dps = prec_to_dps(prec)
for inlist in self.args:
new_inlist = list(inlist)
new_inlist[0] = inlist[0].evalf(n=dps)
new_args.append(tuple(new_inlist))
return Dyadic(new_args)
def xreplace(self, rule):
"""
Replace occurrences of objects within the measure numbers of the Dyadic.
Parameters
==========
rule : dict-like
Expresses a replacement rule.
Returns
=======
Dyadic
Result of the replacement.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> D = outer(N.x, N.x)
>>> x, y, z = symbols('x y z')
>>> ((1 + x*y) * D).xreplace({x: pi})
(pi*y + 1)*(N.x|N.x)
>>> ((1 + x*y) * D).xreplace({x: pi, y: 2})
(1 + 2*pi)*(N.x|N.x)
Replacements occur only if an entire node in the expression tree is
matched:
>>> ((x*y + z) * D).xreplace({x*y: pi})
(z + pi)*(N.x|N.x)
>>> ((x*y*z) * D).xreplace({x*y: pi})
x*y*z*(N.x|N.x)
"""
new_args = []
for inlist in self.args:
new_inlist = list(inlist)
new_inlist[0] = new_inlist[0].xreplace(rule)
new_args.append(tuple(new_inlist))
return Dyadic(new_args)
def _check_dyadic(other):
if not isinstance(other, Dyadic):
raise TypeError('A Dyadic must be supplied')
return other
|
b72b2110cb0b34f478898ce801b3c665167e7bff2dec60cfff1ca347285ea5e4 | from sympy.core.numbers import I
from sympy.core.symbol import symbols
from sympy.physics.paulialgebra import Pauli
from sympy.testing.pytest import XFAIL
from sympy.physics.quantum import TensorProduct
sigma1 = Pauli(1)
sigma2 = Pauli(2)
sigma3 = Pauli(3)
tau1 = symbols("tau1", commutative = False)
def test_Pauli():
assert sigma1 == sigma1
assert sigma1 != sigma2
assert sigma1*sigma2 == I*sigma3
assert sigma3*sigma1 == I*sigma2
assert sigma2*sigma3 == I*sigma1
assert sigma1*sigma1 == 1
assert sigma2*sigma2 == 1
assert sigma3*sigma3 == 1
assert sigma1**0 == 1
assert sigma1**1 == sigma1
assert sigma1**2 == 1
assert sigma1**3 == sigma1
assert sigma1**4 == 1
assert sigma3**2 == 1
assert sigma1*2*sigma1 == 2
def test_evaluate_pauli_product():
from sympy.physics.paulialgebra import evaluate_pauli_product
assert evaluate_pauli_product(I*sigma2*sigma3) == -sigma1
# Check issue 6471
assert evaluate_pauli_product(-I*4*sigma1*sigma2) == 4*sigma3
assert evaluate_pauli_product(
1 + I*sigma1*sigma2*sigma1*sigma2 + \
I*sigma1*sigma2*tau1*sigma1*sigma3 + \
((tau1**2).subs(tau1, I*sigma1)) + \
sigma3*((tau1**2).subs(tau1, I*sigma1)) + \
TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1)
) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1)
@XFAIL
def test_Pauli_should_work():
assert sigma1*sigma3*sigma1 == -sigma3
|
2c3f5653e639956edb54ceccc82912196f4c5361598558cc079664f38f3fab53 | from sympy.core.numbers import (Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.simplify.simplify import simplify
from sympy.abc import omega, m, x
from sympy.physics.qho_1d import psi_n, E_n, coherent_state
from sympy.physics.quantum.constants import hbar
nu = m * omega / hbar
def test_wavefunction():
Psi = {
0: (nu/pi)**Rational(1, 4) * exp(-nu * x**2 /2),
1: (nu/pi)**Rational(1, 4) * sqrt(2*nu) * x * exp(-nu * x**2 /2),
2: (nu/pi)**Rational(1, 4) * (2 * nu * x**2 - 1)/sqrt(2) * exp(-nu * x**2 /2),
3: (nu/pi)**Rational(1, 4) * sqrt(nu/3) * (2 * nu * x**3 - 3 * x) * exp(-nu * x**2 /2)
}
for n in Psi:
assert simplify(psi_n(n, x, m, omega) - Psi[n]) == 0
def test_norm(n=1):
# Maximum "n" which is tested:
for i in range(n + 1):
assert integrate(psi_n(i, x, 1, 1)**2, (x, -oo, oo)) == 1
def test_orthogonality(n=1):
# Maximum "n" which is tested:
for i in range(n + 1):
for j in range(i + 1, n + 1):
assert integrate(
psi_n(i, x, 1, 1)*psi_n(j, x, 1, 1), (x, -oo, oo)) == 0
def test_energies(n=1):
# Maximum "n" which is tested:
for i in range(n + 1):
assert E_n(i, omega) == hbar * omega * (i + S.Half)
def test_coherent_state(n=10):
# Maximum "n" which is tested:
# test whether coherent state is the eigenstate of annihilation operator
alpha = Symbol("alpha")
for i in range(n + 1):
assert simplify(sqrt(n + 1) * coherent_state(n + 1, alpha)) == simplify(alpha * coherent_state(n, alpha))
|
8ac4b6627227208357ce4f1bcb7a5888bdf0563e7a168a50bfc74ac2682ae947 | from sympy.core.numbers import (I, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.spherical_harmonics import Ynm
from sympy.matrices.dense import Matrix
from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt,
racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d)
from sympy.core.numbers import Rational
# for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients
def test_clebsch_gordan_docs():
assert clebsch_gordan(Rational(3, 2), S.Half, 2, Rational(3, 2), S.Half, 2) == 1
assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(3, 2), Rational(-1, 2), 1) == sqrt(3)/2
assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2
def test_clebsch_gordan1():
j_1 = S.Half
j_2 = S.Half
m = 1
j = 1
m_1 = S.Half
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = S.Half
j_2 = S.Half
m = -1
j = 1
m_1 = Rational(-1, 2)
m_2 = Rational(-1, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = S.Half
j_2 = S.Half
m = 0
j = 1
m_1 = S.Half
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 0
j_1 = S.Half
j_2 = S.Half
m = 0
j = 1
m_1 = S.Half
m_2 = Rational(-1, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2
j_1 = S.Half
j_2 = S.Half
m = 0
j = 0
m_1 = S.Half
m_2 = Rational(-1, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2
j_1 = S.Half
j_2 = S.Half
m = 0
j = 1
m_1 = Rational(-1, 2)
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/2
j_1 = S.Half
j_2 = S.Half
m = 0
j = 0
m_1 = Rational(-1, 2)
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -sqrt(2)/2
def test_clebsch_gordan2():
j_1 = S.One
j_2 = S.Half
m = Rational(3, 2)
j = Rational(3, 2)
m_1 = 1
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = S.One
j_2 = S.Half
m = S.Half
j = Rational(3, 2)
m_1 = 1
m_2 = Rational(-1, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(3)
j_1 = S.One
j_2 = S.Half
m = S.Half
j = S.Half
m_1 = 1
m_2 = Rational(-1, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/sqrt(3)
j_1 = S.One
j_2 = S.Half
m = S.Half
j = S.Half
m_1 = 0
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -1/sqrt(3)
j_1 = S.One
j_2 = S.Half
m = S.Half
j = Rational(3, 2)
m_1 = 0
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(2)/sqrt(3)
j_1 = S.One
j_2 = S.One
m = S(2)
j = S(2)
m_1 = 1
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = S.One
j_2 = S.One
m = 1
j = S(2)
m_1 = 1
m_2 = 0
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
j_1 = S.One
j_2 = S.One
m = 1
j = S(2)
m_1 = 0
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
j_1 = S.One
j_2 = S.One
m = 1
j = 1
m_1 = 1
m_2 = 0
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
j_1 = S.One
j_2 = S.One
m = 1
j = 1
m_1 = 0
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == -1/sqrt(2)
def test_clebsch_gordan3():
j_1 = Rational(3, 2)
j_2 = Rational(3, 2)
m = S(3)
j = S(3)
m_1 = Rational(3, 2)
m_2 = Rational(3, 2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = Rational(3, 2)
j_2 = Rational(3, 2)
m = S(2)
j = S(2)
m_1 = Rational(3, 2)
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
j_1 = Rational(3, 2)
j_2 = Rational(3, 2)
m = S(2)
j = S(3)
m_1 = Rational(3, 2)
m_2 = S.Half
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
def test_clebsch_gordan4():
j_1 = S(2)
j_2 = S(2)
m = S(4)
j = S(4)
m_1 = S(2)
m_2 = S(2)
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = S(2)
j_2 = S(2)
m = S(3)
j = S(3)
m_1 = S(2)
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(2)
j_1 = S(2)
j_2 = S(2)
m = S(2)
j = S(3)
m_1 = 1
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 0
def test_clebsch_gordan5():
j_1 = Rational(5, 2)
j_2 = S.One
m = Rational(7, 2)
j = Rational(7, 2)
m_1 = Rational(5, 2)
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1
j_1 = Rational(5, 2)
j_2 = S.One
m = Rational(5, 2)
j = Rational(5, 2)
m_1 = Rational(5, 2)
m_2 = 0
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == sqrt(5)/sqrt(7)
j_1 = Rational(5, 2)
j_2 = S.One
m = Rational(3, 2)
j = Rational(3, 2)
m_1 = S.Half
m_2 = 1
assert clebsch_gordan(j_1, j_2, j, m_1, m_2, m) == 1/sqrt(15)
def test_wigner():
def tn(a, b):
return (a - b).n(64) < S('1e-64')
assert tn(wigner_9j(1, 1, 1, 1, 1, 1, 1, 1, 0, prec=64), Rational(1, 18))
assert wigner_9j(3, 3, 2, 3, 3, 2, 3, 3, 2) == 3221*sqrt(
70)/(246960*sqrt(105)) - 365/(3528*sqrt(70)*sqrt(105))
assert wigner_6j(5, 5, 5, 5, 5, 5) == Rational(1, 52)
assert tn(wigner_6j(8, 8, 8, 8, 8, 8, prec=64), Rational(-12219, 965770))
# regression test for #8747
half = S.Half
assert wigner_9j(0, 0, 0, 0, half, half, 0, half, half) == half
assert (wigner_9j(3, 5, 4,
7 * half, 5 * half, 4,
9 * half, 9 * half, 0)
== -sqrt(Rational(361, 205821000)))
assert (wigner_9j(1, 4, 3,
5 * half, 4, 5 * half,
5 * half, 2, 7 * half)
== -sqrt(Rational(3971, 373403520)))
assert (wigner_9j(4, 9 * half, 5 * half,
2, 4, 4,
5, 7 * half, 7 * half)
== -sqrt(Rational(3481, 5042614500)))
def test_gaunt():
def tn(a, b):
return (a - b).n(64) < S('1e-64')
assert gaunt(1, 0, 1, 1, 0, -1) == -1/(2*sqrt(pi))
assert isinstance(gaunt(1, 1, 0, -1, 1, 0).args[0], Rational)
assert isinstance(gaunt(0, 1, 1, 0, -1, 1).args[0], Rational)
assert tn(gaunt(
10, 10, 12, 9, 3, -12, prec=64), (Rational(-98, 62031)) * sqrt(6279)/sqrt(pi))
def gaunt_ref(l1, l2, l3, m1, m2, m3):
return (
sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) / (4 * pi)) *
wigner_3j(l1, l2, l3, 0, 0, 0) *
wigner_3j(l1, l2, l3, m1, m2, m3)
)
threshold = 1e-10
l_max = 3
l3_max = 24
for l1 in range(l_max + 1):
for l2 in range(l_max + 1):
for l3 in range(l3_max + 1):
for m1 in range(-l1, l1 + 1):
for m2 in range(-l2, l2 + 1):
for m3 in range(-l3, l3 + 1):
args = l1, l2, l3, m1, m2, m3
g = gaunt(*args)
g0 = gaunt_ref(*args)
assert abs(g - g0) < threshold
if m1 + m2 + m3 != 0:
assert abs(g) < threshold
if (l1 + l2 + l3) % 2:
assert abs(g) < threshold
def test_racah():
assert racah(3,3,3,3,3,3) == Rational(-1,14)
assert racah(2,2,2,2,2,2) == Rational(-3,70)
assert racah(7,8,7,1,7,7, prec=4).is_Float
assert racah(5.5,7.5,9.5,6.5,8,9) == -719*sqrt(598)/1158924
assert abs(racah(5.5,7.5,9.5,6.5,8,9, prec=4) - (-0.01517)) < S('1e-4')
def test_dot_rota_grad_SH():
theta, phi = symbols("theta phi")
assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0) != \
sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0).doit() == \
sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2) != \
0
assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2).doit() == \
0
assert dot_rot_grad_Ynm(3, 3, 3, 3, theta, phi).doit() == \
15*sqrt(3003)*Ynm(6, 6, theta, phi)/(143*sqrt(pi))
assert dot_rot_grad_Ynm(3, 3, 1, 1, theta, phi).doit() == \
sqrt(3)*Ynm(4, 4, theta, phi)/sqrt(pi)
assert dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() == \
3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
assert dot_rot_grad_Ynm(3, 2, 3, 2, theta, phi).doit().expand() == \
-sqrt(70)*Ynm(4, 4, theta, phi)/(11*sqrt(pi)) + \
45*sqrt(182)*Ynm(6, 4, theta, phi)/(143*sqrt(pi))
def test_wigner_d():
half = S(1)/2
alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
d = wigner_d_small(half, beta).subs({beta: pi/2})
d_ = Matrix([[1, 1], [-1, 1]])/sqrt(2)
assert d == d_
D = wigner_d(half, alpha, beta, gamma)
assert D[0, 0] == exp(I*alpha/2)*exp(I*gamma/2)*cos(beta/2)
assert D[0, 1] == exp(I*alpha/2)*exp(-I*gamma/2)*sin(beta/2)
assert D[1, 0] == -exp(-I*alpha/2)*exp(I*gamma/2)*sin(beta/2)
assert D[1, 1] == exp(-I*alpha/2)*exp(-I*gamma/2)*cos(beta/2)
|
928851211e89a2313f1966279732ec30c81d86829df3085acecd26abb7024d07 | from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.integrals.integrals import integrate
from sympy.simplify.simplify import simplify
from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac, Psi_nlm
from sympy.testing.pytest import raises
n, r, Z = symbols('n r Z')
def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
a = float(a)
b = float(b)
# if the numbers are close enough (absolutely), then they are equal
if abs(a - b) < max_absolute_error:
return True
# if not, they can still be equal if their relative error is small
if abs(b) > abs(a):
relative_error = abs((a - b)/b)
else:
relative_error = abs((a - b)/a)
return relative_error <= max_relative_error
def test_wavefunction():
a = 1/Z
R = {
(1, 0): 2*sqrt(1/a**3) * exp(-r/a),
(2, 0): sqrt(1/(2*a**3)) * exp(-r/(2*a)) * (1 - r/(2*a)),
(2, 1): S.Half * sqrt(1/(6*a**3)) * exp(-r/(2*a)) * r/a,
(3, 0): Rational(2, 3) * sqrt(1/(3*a**3)) * exp(-r/(3*a)) *
(1 - 2*r/(3*a) + Rational(2, 27) * (r/a)**2),
(3, 1): Rational(4, 27) * sqrt(2/(3*a**3)) * exp(-r/(3*a)) *
(1 - r/(6*a)) * r/a,
(3, 2): Rational(2, 81) * sqrt(2/(15*a**3)) * exp(-r/(3*a)) * (r/a)**2,
(4, 0): Rational(1, 4) * sqrt(1/a**3) * exp(-r/(4*a)) *
(1 - 3*r/(4*a) + Rational(1, 8) * (r/a)**2 - Rational(1, 192) * (r/a)**3),
(4, 1): Rational(1, 16) * sqrt(5/(3*a**3)) * exp(-r/(4*a)) *
(1 - r/(4*a) + Rational(1, 80) * (r/a)**2) * (r/a),
(4, 2): Rational(1, 64) * sqrt(1/(5*a**3)) * exp(-r/(4*a)) *
(1 - r/(12*a)) * (r/a)**2,
(4, 3): Rational(1, 768) * sqrt(1/(35*a**3)) * exp(-r/(4*a)) * (r/a)**3,
}
for n, l in R:
assert simplify(R_nl(n, l, r, Z) - R[(n, l)]) == 0
def test_norm():
# Maximum "n" which is tested:
n_max = 2 # it works, but is slow, for n_max > 2
for n in range(n_max + 1):
for l in range(n):
assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1
def test_psi_nlm():
r=S('r')
phi=S('phi')
theta=S('theta')
assert (Psi_nlm(1, 0, 0, r, phi, theta) == exp(-r) / sqrt(pi))
assert (Psi_nlm(2, 1, -1, r, phi, theta)) == S.Half * exp(-r / (2)) * r \
* (sin(theta) * exp(-I * phi) / (4 * sqrt(pi)))
assert (Psi_nlm(3, 2, 1, r, phi, theta, 2) == -sqrt(2) * sin(theta) \
* exp(I * phi) * cos(theta) / (4 * sqrt(pi)) * S(2) / 81 \
* sqrt(2 * 2 ** 3) * exp(-2 * r / (3)) * (r * 2) ** 2)
def test_hydrogen_energies():
assert E_nl(n, Z) == -Z**2/(2*n**2)
assert E_nl(n) == -1/(2*n**2)
assert E_nl(1, 47) == -S(47)**2/(2*1**2)
assert E_nl(2, 47) == -S(47)**2/(2*2**2)
assert E_nl(1) == -S.One/(2*1**2)
assert E_nl(2) == -S.One/(2*2**2)
assert E_nl(3) == -S.One/(2*3**2)
assert E_nl(4) == -S.One/(2*4**2)
assert E_nl(100) == -S.One/(2*100**2)
raises(ValueError, lambda: E_nl(0))
def test_hydrogen_energies_relat():
# First test exact formulas for small "c" so that we get nice expressions:
assert E_nl_dirac(2, 0, Z=1, c=1) == 1/sqrt(2) - 1
assert simplify(E_nl_dirac(2, 0, Z=1, c=2) - ( (8*sqrt(3) + 16)
/ sqrt(16*sqrt(3) + 32) - 4)) == 0
assert simplify(E_nl_dirac(2, 0, Z=1, c=3) - ( (54*sqrt(2) + 81)
/ sqrt(108*sqrt(2) + 162) - 9)) == 0
# Now test for almost the correct speed of light, without floating point
# numbers:
assert simplify(E_nl_dirac(2, 0, Z=1, c=137) - ( (352275361 + 10285412 *
sqrt(1173)) / sqrt(704550722 + 20570824 * sqrt(1173)) - 18769)) == 0
assert simplify(E_nl_dirac(2, 0, Z=82, c=137) - ( (352275361 + 2571353 *
sqrt(12045)) / sqrt(704550722 + 5142706*sqrt(12045)) - 18769)) == 0
# Test using exact speed of light, and compare against the nonrelativistic
# energies:
for n in range(1, 5):
for l in range(n):
assert feq(E_nl_dirac(n, l), E_nl(n), 1e-5, 1e-5)
if l > 0:
assert feq(E_nl_dirac(n, l, False), E_nl(n), 1e-5, 1e-5)
Z = 2
for n in range(1, 5):
for l in range(n):
assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-4, 1e-4)
if l > 0:
assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-4, 1e-4)
Z = 3
for n in range(1, 5):
for l in range(n):
assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-3, 1e-3)
if l > 0:
assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-3, 1e-3)
# Test the exceptions:
raises(ValueError, lambda: E_nl_dirac(0, 0))
raises(ValueError, lambda: E_nl_dirac(1, -1))
raises(ValueError, lambda: E_nl_dirac(1, 0, False))
|
0e16bc890461cf12dc97b4ca480e903f4a6711c068aad8ff39beadc74d523302 | from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import (Matrix, eye, zeros)
from sympy.testing.pytest import warns_deprecated_sympy
def test_parallel_axis_theorem():
# This tests the parallel axis theorem matrix by comparing to test
# matrices.
# First case, 1 in all directions.
mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2)))
assert pat_matrix(1, 1, 1, 1) == mat1
assert pat_matrix(2, 1, 1, 1) == 2*mat1
# Second case, 1 in x, 0 in all others
mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1)))
assert pat_matrix(1, 1, 0, 0) == mat2
assert pat_matrix(2, 1, 0, 0) == 2*mat2
# Third case, 1 in y, 0 in all others
mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1)))
assert pat_matrix(1, 0, 1, 0) == mat3
assert pat_matrix(2, 0, 1, 0) == 2*mat3
# Fourth case, 1 in z, 0 in all others
mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0)))
assert pat_matrix(1, 0, 0, 1) == mat4
assert pat_matrix(2, 0, 0, 1) == 2*mat4
def test_Pauli():
#this and the following test are testing both Pauli and Dirac matrices
#and also that the general Matrix class works correctly in a real world
#situation
sigma1 = msigma(1)
sigma2 = msigma(2)
sigma3 = msigma(3)
assert sigma1 == sigma1
assert sigma1 != sigma2
# sigma*I -> I*sigma (see #354)
assert sigma1*sigma2 == sigma3*I
assert sigma3*sigma1 == sigma2*I
assert sigma2*sigma3 == sigma1*I
assert sigma1*sigma1 == eye(2)
assert sigma2*sigma2 == eye(2)
assert sigma3*sigma3 == eye(2)
assert sigma1*2*sigma1 == 2*eye(2)
assert sigma1*sigma3*sigma1 == -sigma3
def test_Dirac():
gamma0 = mgamma(0)
gamma1 = mgamma(1)
gamma2 = mgamma(2)
gamma3 = mgamma(3)
gamma5 = mgamma(5)
# gamma*I -> I*gamma (see #354)
assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I
assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4)
assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0]
assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0]
assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2]
assert mgamma(5, True) == \
mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
def test_mdft():
with warns_deprecated_sympy():
assert mdft(1) == Matrix([[1]])
with warns_deprecated_sympy():
assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
with warns_deprecated_sympy():
assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half],
[S.Half, -I/2, Rational(-1,2), I/2],
[S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
[S.Half, I/2, Rational(-1,2), -I/2]])
|
688b357f77a8ea16f812b454f31aebfe1ff2853991c7e7d082ff67dbb49fb0b3 | from sympy.core import symbols, Rational, Function, diff
from sympy.physics.sho import R_nl, E_nl
from sympy.simplify.simplify import simplify
def test_sho_R_nl():
omega, r = symbols('omega r')
l = symbols('l', integer=True)
u = Function('u')
# check that it obeys the Schrodinger equation
for n in range(5):
schreq = ( -diff(u(r), r, 2)/2 + ((l*(l + 1))/(2*r**2)
+ omega**2*r**2/2 - E_nl(n, l, omega))*u(r) )
result = schreq.subs(u(r), r*R_nl(n, l, omega/2, r))
assert simplify(result.doit()) == 0
def test_energy():
n, l, hw = symbols('n l hw')
assert simplify(E_nl(n, l, hw) - (2*n + l + Rational(3, 2))*hw) == 0
|
2374f2284ef811c71872edada237370d41f2b759f90fccfb46d947f58261d3fa | from sympy.physics.secondquant import (
Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis,
matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta,
AnnihilateBoson, CreateBoson, BosonicOperator,
F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion,
evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks,
PermutationOperator, simplify_index_permutations,
_sort_anticommuting_fermions, _get_ordered_dummies,
substitute_dummies, FockStateBosonKet,
ContractionAppliesOnlyToFermions
)
from sympy.concrete.summations import Sum
from sympy.core.function import (Function, expand)
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.printing.repr import srepr
from sympy.simplify.simplify import simplify
from sympy.testing.pytest import slow, raises
from sympy.printing.latex import latex
def test_PermutationOperator():
p, q, r, s = symbols('p,q,r,s')
f, g, h, i = map(Function, 'fghi')
P = PermutationOperator
assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p)
assert P(p, q).get_permuted(f(p, q)) == -f(q, p)
assert P(p, q).get_permuted(f(p)) == f(p)
expr = (f(p)*g(q)*h(r)*i(s)
- f(q)*g(p)*h(r)*i(s)
- f(p)*g(q)*h(s)*i(r)
+ f(q)*g(p)*h(s)*i(r))
perms = [P(p, q), P(r, s)]
assert (simplify_index_permutations(expr, perms) ==
P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s))
assert latex(P(p, q)) == 'P(pq)'
def test_index_permutations_with_dummies():
a, b, c, d = symbols('a b c d')
p, q, r, s = symbols('p q r s', cls=Dummy)
f, g = map(Function, 'fg')
P = PermutationOperator
# No dummy substitution necessary
expr = f(a, b, p, q) - f(b, a, p, q)
assert simplify_index_permutations(
expr, [P(a, b)]) == P(a, b)*f(a, b, p, q)
# Cases where dummy substitution is needed
expected = P(a, b)*substitute_dummies(f(a, b, p, q))
expr = f(a, b, p, q) - f(b, a, q, p)
result = simplify_index_permutations(expr, [P(a, b)])
assert expected == substitute_dummies(result)
expr = f(a, b, q, p) - f(b, a, p, q)
result = simplify_index_permutations(expr, [P(a, b)])
assert expected == substitute_dummies(result)
# A case where nothing can be done
expr = f(a, b, q, p) - g(b, a, p, q)
result = simplify_index_permutations(expr, [P(a, b)])
assert expr == result
def test_dagger():
i, j, n, m = symbols('i,j,n,m')
assert Dagger(1) == 1
assert Dagger(1.0) == 1.0
assert Dagger(2*I) == -2*I
assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0
assert Dagger(BKet([n])) == BBra([n])
assert Dagger(B(0)) == Bd(0)
assert Dagger(Bd(0)) == B(0)
assert Dagger(B(n)) == Bd(n)
assert Dagger(Bd(n)) == B(n)
assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1)
assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute
assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n)
assert Dagger(B(n)**10) == Dagger(B(n))**10
assert Dagger('a') == Dagger(Symbol('a'))
assert Dagger(Dagger('a')) == Symbol('a')
def test_operator():
i, j = symbols('i,j')
o = BosonicOperator(i)
assert o.state == i
assert o.is_symbolic
o = BosonicOperator(1)
assert o.state == 1
assert not o.is_symbolic
def test_create():
i, j, n, m = symbols('i,j,n,m')
o = Bd(i)
assert latex(o) == "{b^\\dagger_{i}}"
assert isinstance(o, CreateBoson)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = Bd(0)
assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
o = Bd(n)
assert o.apply_operator(BKet([n])) == o*BKet([n])
def test_annihilate():
i, j, n, m = symbols('i,j,n,m')
o = B(i)
assert latex(o) == "b_{i}"
assert isinstance(o, AnnihilateBoson)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = B(0)
assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1])
o = B(n)
assert o.apply_operator(BKet([n])) == o*BKet([n])
def test_basic_state():
i, j, n, m = symbols('i,j,n,m')
s = BosonState([0, 1, 2, 3, 4])
assert len(s) == 5
assert s.args[0] == tuple(range(5))
assert s.up(0) == BosonState([1, 1, 2, 3, 4])
assert s.down(4) == BosonState([0, 1, 2, 3, 3])
for i in range(5):
assert s.up(i).down(i) == s
assert s.down(0) == 0
for i in range(5):
assert s[i] == i
s = BosonState([n, m])
assert s.down(0) == BosonState([n - 1, m])
assert s.up(0) == BosonState([n + 1, m])
def test_basic_apply():
n = symbols("n")
e = B(0)*BKet([n])
assert apply_operators(e) == sqrt(n)*BKet([n - 1])
e = Bd(0)*BKet([n])
assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1])
def test_complex_apply():
n, m = symbols("n,m")
o = Bd(0)*B(0)*Bd(1)*B(0)
e = apply_operators(o*BKet([n, m]))
answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m])
assert expand(e) == expand(answer)
def test_number_operator():
n = symbols("n")
o = Bd(0)*B(0)
e = apply_operators(o*BKet([n]))
assert e == n*BKet([n])
def test_inner_product():
i, j, k, l = symbols('i,j,k,l')
s1 = BBra([0])
s2 = BKet([1])
assert InnerProduct(s1, Dagger(s1)) == 1
assert InnerProduct(s1, s2) == 0
s1 = BBra([i, j])
s2 = BKet([k, l])
r = InnerProduct(s1, s2)
assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l)
def test_symbolic_matrix_elements():
n, m = symbols('n,m')
s1 = BBra([n])
s2 = BKet([m])
o = B(0)
e = apply_operators(s1*o*s2)
assert e == sqrt(m)*KroneckerDelta(n, m - 1)
def test_matrix_elements():
b = VarBosonicBasis(5)
o = B(0)
m = matrix_rep(o, b)
for i in range(4):
assert m[i, i + 1] == sqrt(i + 1)
o = Bd(0)
m = matrix_rep(o, b)
for i in range(4):
assert m[i + 1, i] == sqrt(i + 1)
def test_fixed_bosonic_basis():
b = FixedBosonicBasis(2, 2)
# assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
state = b.state(1)
assert state == FockStateBosonKet((1, 1))
assert b.index(state) == 1
assert b.state(1) == b[1]
assert len(b) == 3
assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
@slow
def test_sho():
n, m = symbols('n,m')
h_n = Bd(n)*B(n)*(n + S.Half)
H = Sum(h_n, (n, 0, 5))
o = H.doit(deep=False)
b = FixedBosonicBasis(2, 6)
m = matrix_rep(o, b)
# We need to double check these energy values to make sure that they
# are correct and have the proper degeneracies!
diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11]
for i in range(len(diag)):
assert diag[i] == m[i, i]
def test_commutation():
n, m = symbols("n,m", above_fermi=True)
c = Commutator(B(0), Bd(0))
assert c == 1
c = Commutator(Bd(0), B(0))
assert c == -1
c = Commutator(B(n), Bd(0))
assert c == KroneckerDelta(n, 0)
c = Commutator(B(0), B(0))
assert c == 0
c = Commutator(B(0), Bd(0))
e = simplify(apply_operators(c*BKet([n])))
assert e == BKet([n])
c = Commutator(B(0), B(1))
e = simplify(apply_operators(c*BKet([n, m])))
assert e == 0
c = Commutator(F(m), Fd(m))
assert c == +1 - 2*NO(Fd(m)*F(m))
c = Commutator(Fd(m), F(m))
assert c.expand() == -1 + 2*NO(Fd(m)*F(m))
C = Commutator
X, Y, Z = symbols('X,Y,Z', commutative=False)
assert C(C(X, Y), Z) != 0
assert C(C(X, Z), Y) != 0
assert C(Y, C(X, Z)) != 0
i, j, k, l = symbols('i,j,k,l', below_fermi=True)
a, b, c, d = symbols('a,b,c,d', above_fermi=True)
p, q, r, s = symbols('p,q,r,s')
D = KroneckerDelta
assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a))
assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a)
assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0
c1 = Commutator(F(a), Fd(a))
assert Commutator.eval(c1, c1) == 0
c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]'
assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))'
assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]'
def test_create_f():
i, j, n, m = symbols('i,j,n,m')
o = Fd(i)
assert isinstance(o, CreateFermion)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = Fd(1)
assert o.apply_operator(FKet([n])) == FKet([1, n])
assert o.apply_operator(FKet([n])) == -FKet([n, 1])
o = Fd(n)
assert o.apply_operator(FKet([])) == FKet([n])
vacuum = FKet([], fermi_level=4)
assert vacuum == FKet([], fermi_level=4)
i, j, k, l = symbols('i,j,k,l', below_fermi=True)
a, b, c, d = symbols('a,b,c,d', above_fermi=True)
p, q, r, s = symbols('p,q,r,s')
assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4)
assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4)
assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p)
assert repr(Fd(p)) == 'CreateFermion(p)'
assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))"
assert latex(Fd(p)) == r'{a^\dagger_{p}}'
def test_annihilate_f():
i, j, n, m = symbols('i,j,n,m')
o = F(i)
assert isinstance(o, AnnihilateFermion)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = F(1)
assert o.apply_operator(FKet([1, n])) == FKet([n])
assert o.apply_operator(FKet([n, 1])) == -FKet([n])
o = F(n)
assert o.apply_operator(FKet([n])) == FKet([])
i, j, k, l = symbols('i,j,k,l', below_fermi=True)
a, b, c, d = symbols('a,b,c,d', above_fermi=True)
p, q, r, s = symbols('p,q,r,s')
assert F(i).apply_operator(FKet([i, j, k], 4)) == 0
assert F(a).apply_operator(FKet([i, b, k], 4)) == 0
assert F(l).apply_operator(FKet([i, j, k], 3)) == 0
assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4)
assert str(F(p)) == 'f(p)'
assert repr(F(p)) == 'AnnihilateFermion(p)'
assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))"
assert latex(F(p)) == 'a_{p}'
def test_create_b():
i, j, n, m = symbols('i,j,n,m')
o = Bd(i)
assert isinstance(o, CreateBoson)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = Bd(0)
assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
o = Bd(n)
assert o.apply_operator(BKet([n])) == o*BKet([n])
def test_annihilate_b():
i, j, n, m = symbols('i,j,n,m')
o = B(i)
assert isinstance(o, AnnihilateBoson)
o = o.subs(i, j)
assert o.atoms(Symbol) == {j}
o = B(0)
def test_wicks():
p, q, r, s = symbols('p,q,r,s', above_fermi=True)
# Testing for particles only
str = F(p)*Fd(q)
assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q)
str = Fd(p)*F(q)
assert wicks(str) == NO(Fd(p)*F(q))
str = F(p)*Fd(q)*F(r)*Fd(s)
nstr = wicks(str)
fasit = NO(
KroneckerDelta(p, q)*KroneckerDelta(r, s)
+ KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s)
+ KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q)
- KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q)
- AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s))
assert nstr == fasit
assert (p*q*nstr).expand() == wicks(p*q*str)
assert (nstr*p*q*2).expand() == wicks(str*p*q*2)
# Testing CC equations particles and holes
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
p, q, r, s = symbols('p q r s', cls=Dummy)
assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) ==
NO(F(a)*F(i)*F(j)*Fd(b)) +
KroneckerDelta(a, b)*NO(F(i)*F(j)))
assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) ==
NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) -
KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k)))
expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l))
assert (expr ==
-KroneckerDelta(i, k)*NO(Fd(j)*F(l)) -
KroneckerDelta(j, l)*NO(Fd(i)*F(k)) -
KroneckerDelta(i, k)*KroneckerDelta(j, l) +
KroneckerDelta(i, l)*NO(Fd(j)*F(k)) +
NO(Fd(i)*Fd(j)*F(k)*F(l)))
expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d))
assert (expr ==
-KroneckerDelta(a, c)*NO(F(b)*Fd(d)) -
KroneckerDelta(b, d)*NO(F(a)*Fd(c)) -
KroneckerDelta(a, c)*KroneckerDelta(b, d) +
KroneckerDelta(a, d)*NO(F(b)*Fd(c)) +
NO(F(a)*F(b)*Fd(c)*Fd(d)))
def test_NO():
i, j, k, l = symbols('i j k l', below_fermi=True)
a, b, c, d = symbols('a b c d', above_fermi=True)
p, q, r, s = symbols('p q r s', cls=Dummy)
assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) ==
NO(Fd(p)*F(q)) + NO(Fd(a)*F(b)))
assert (NO(Fd(i)*NO(F(j)*Fd(a))) ==
NO(Fd(i)*F(j)*Fd(a)))
assert NO(1) == 1
assert NO(i) == i
assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) ==
NO(Fd(a)*Fd(b)*F(c)) +
NO(Fd(a)*Fd(b)*F(d)))
assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b)
assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i)
assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) ==
NO(Fd(a)*F(q)) + NO(Fd(i)*F(q)))
assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) ==
NO(Fd(p)*F(a)) + NO(Fd(p)*F(i)))
expr = NO(Fd(p)*F(q))._remove_brackets()
assert wicks(expr) == NO(expr)
assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a))
no = NO(Fd(a)*F(i)*F(b)*Fd(j))
l1 = [ ind for ind in no.iter_q_creators() ]
assert l1 == [0, 1]
l2 = [ ind for ind in no.iter_q_annihilators() ]
assert l2 == [3, 2]
no = NO(Fd(a)*Fd(i))
assert no.has_q_creators == 1
assert no.has_q_annihilators == -1
assert str(no) == ':CreateFermion(a)*CreateFermion(i):'
assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))'
assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}'
raises(NotImplementedError, lambda: NO(Bd(p)*F(q)))
def test_sorting():
i, j = symbols('i,j', below_fermi=True)
a, b = symbols('a,b', above_fermi=True)
p, q = symbols('p,q')
# p, q
assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0)
assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1)
# i, p
assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0)
assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1)
assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0)
assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1)
assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1)
assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0)
assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1)
assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0)
# a, p
assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1)
assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0)
assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1)
assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0)
assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0)
assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1)
assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0)
assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1)
# i, a
assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0)
assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1)
assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0)
assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1)
assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1)
assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0)
def test_contraction():
i, j, k, l = symbols('i,j,k,l', below_fermi=True)
a, b, c, d = symbols('a,b,c,d', above_fermi=True)
p, q, r, s = symbols('p,q,r,s')
assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j)
assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b)
assert contraction(F(a), Fd(i)) == 0
assert contraction(Fd(a), F(i)) == 0
assert contraction(F(i), Fd(a)) == 0
assert contraction(Fd(i), F(a)) == 0
assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p)
restr = evaluate_deltas(contraction(Fd(p), F(q)))
assert restr.is_only_below_fermi
restr = evaluate_deltas(contraction(F(p), Fd(q)))
assert restr.is_only_above_fermi
raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b)))
def test_evaluate_deltas():
i, j, k = symbols('i,j,k')
r = KroneckerDelta(i, j) * KroneckerDelta(j, k)
assert evaluate_deltas(r) == KroneckerDelta(i, k)
r = KroneckerDelta(i, 0) * KroneckerDelta(j, k)
assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k)
r = KroneckerDelta(1, j) * KroneckerDelta(j, k)
assert evaluate_deltas(r) == KroneckerDelta(1, k)
r = KroneckerDelta(j, 2) * KroneckerDelta(k, j)
assert evaluate_deltas(r) == KroneckerDelta(2, k)
r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1)
assert evaluate_deltas(r) == 0
r = (KroneckerDelta(0, i) * KroneckerDelta(0, j)
* KroneckerDelta(1, j) * KroneckerDelta(1, j))
assert evaluate_deltas(r) == 0
def test_Tensors():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
p, q, r, s = symbols('p q r s')
AT = AntiSymmetricTensor
assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j))
assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i))
assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i))
assert AT('t', (a, a), (i, j)) == 0
assert AT('t', (a, b), (i, i)) == 0
assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j))
assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j))
tabij = AT('t', (a, b), (i, j))
assert tabij.has(a)
assert tabij.has(b)
assert tabij.has(i)
assert tabij.has(j)
assert tabij.subs(b, c) == AT('t', (a, c), (i, j))
assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j))
assert tabij.symbol == Symbol('t')
assert latex(tabij) == '{t^{ab}_{ij}}'
assert str(tabij) == 't((_a, _b),(_i, _j))'
assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j))
assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j))
def test_fully_contracted():
i, j, k, l = symbols('i j k l', below_fermi=True)
a, b, c, d = symbols('a b c d', above_fermi=True)
p, q, r, s = symbols('p q r s', cls=Dummy)
Fock = (AntiSymmetricTensor('f', (p,), (q,))*
NO(Fd(p)*F(q)))
V = (AntiSymmetricTensor('v', (p, q), (r, s))*
NO(Fd(p)*Fd(q)*F(s)*F(r)))/4
Fai = wicks(NO(Fd(i)*F(a))*Fock,
keep_only_fully_contracted=True,
simplify_kronecker_deltas=True)
assert Fai == AntiSymmetricTensor('f', (a,), (i,))
Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V,
keep_only_fully_contracted=True,
simplify_kronecker_deltas=True)
assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j))
def test_substitute_dummies_without_dummies():
i, j = symbols('i,j')
assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2
assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1
def test_substitute_dummies_NO_operator():
i, j = symbols('i j', cls=Dummy)
assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j))
- att(j, i)*NO(Fd(j)*F(i))) == 0
def test_substitute_dummies_SQ_operator():
i, j = symbols('i j', cls=Dummy)
assert substitute_dummies(att(i, j)*Fd(i)*F(j)
- att(j, i)*Fd(j)*F(i)) == 0
def test_substitute_dummies_new_indices():
i, j = symbols('i j', below_fermi=True, cls=Dummy)
a, b = symbols('a b', above_fermi=True, cls=Dummy)
p, q = symbols('p q', cls=Dummy)
f = Function('f')
assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0
def test_substitute_dummies_substitution_order():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
f = Function('f')
from sympy.utilities.iterables import variations
for permut in variations([i, j, k, l], 4):
assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0
def test_dummy_order_inner_outer_lines_VT1T1T1():
ii = symbols('i', below_fermi=True)
aa = symbols('a', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
# Coupled-Cluster T1 terms with V*T1*T1*T1
# t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
exprs = [
# permut v and t <=> swapping internal lines, equivalent
# irrespective of symmetries in v
v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k),
v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l),
v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k),
v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_dummy_order_inner_outer_lines_VT1T1T1T1():
ii, jj = symbols('i j', below_fermi=True)
aa, bb = symbols('a b', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
# Coupled-Cluster T2 terms with V*T1*T1*T1*T1
exprs = [
# permut t <=> swapping external lines, not equivalent
# except if v has certain symmetries.
v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [
# permut v <=> swapping external lines, not equivalent
# except if v has certain symmetries.
#
# Note that in contrast to above, these permutations have identical
# dummy order. That is because the proximity to external indices
# has higher influence on the canonical dummy ordering than the
# position of a dummy on the factors. In fact, the terms here are
# similar in structure as the result of the dummy substitutions above.
v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
]
for permut in exprs[1:]:
assert dums(exprs[0]) == dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [
# permut t and v <=> swapping internal lines, equivalent.
# Canonical dummy order is different, and a consistent
# substitution reveals the equivalence.
v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_get_subNO():
p, q, r = symbols('p,q,r')
assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r))
assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r))
assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q))
def test_equivalent_internal_lines_VT1T1():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
exprs = [ # permute v. Different dummy order. Not equivalent.
v(i, j, a, b)*t(a, i)*t(b, j),
v(j, i, a, b)*t(a, i)*t(b, j),
v(i, j, b, a)*t(a, i)*t(b, j),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v. Different dummy order. Equivalent
v(i, j, a, b)*t(a, i)*t(b, j),
v(j, i, b, a)*t(a, i)*t(b, j),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [ # permute t. Same dummy order, not equivalent.
v(i, j, a, b)*t(a, i)*t(b, j),
v(i, j, a, b)*t(b, i)*t(a, j),
]
for permut in exprs[1:]:
assert dums(exprs[0]) == dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v and t. Different dummy order, equivalent
v(i, j, a, b)*t(a, i)*t(b, j),
v(j, i, a, b)*t(a, j)*t(b, i),
v(i, j, b, a)*t(b, i)*t(a, j),
v(j, i, b, a)*t(b, j)*t(a, i),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_equivalent_internal_lines_VT2conjT2():
# this diagram requires special handling in TCE
i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
from sympy.utilities.iterables import variations
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
# v(abcd)t(abij)t(ijcd)
template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
# v(abcd)t(abij)t(jicd)
template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
def test_equivalent_internal_lines_VT2conjT2_ambiguous_order():
# These diagrams invokes _determine_ambiguous() because the
# dummies can not be ordered unambiguously by the key alone
i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
from sympy.utilities.iterables import variations
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
# v(abcd)t(abij)t(cdij)
template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert dums(base) != dums(expr)
assert substitute_dummies(expr) == substitute_dummies(base)
def test_equivalent_internal_lines_VT2():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
exprs = [
# permute v. Same dummy order, not equivalent.
#
# This test show that the dummy order may not be sensitive to all
# index permutations. The following expressions have identical
# structure as the resulting terms from of the dummy substitutions
# in the test above. Here, all expressions have the same dummy
# order, so they cannot be simplified by means of dummy
# substitution. In order to simplify further, it is necessary to
# exploit symmetries in the objects, for instance if t or v is
# antisymmetric.
v(i, j, a, b)*t(a, b, i, j),
v(j, i, a, b)*t(a, b, i, j),
v(i, j, b, a)*t(a, b, i, j),
v(j, i, b, a)*t(a, b, i, j),
]
for permut in exprs[1:]:
assert dums(exprs[0]) == dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [
# permute t.
v(i, j, a, b)*t(a, b, i, j),
v(i, j, a, b)*t(b, a, i, j),
v(i, j, a, b)*t(a, b, j, i),
v(i, j, a, b)*t(b, a, j, i),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
v(i, j, a, b)*t(a, b, i, j),
v(j, i, a, b)*t(a, b, j, i),
v(i, j, b, a)*t(b, a, i, j),
v(j, i, b, a)*t(b, a, j, i),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_internal_external_VT2T2():
ii, jj = symbols('i j', below_fermi=True)
aa, bb = symbols('a b', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
exprs = [
v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [
v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l),
v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k),
v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l),
v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [
v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l),
v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k),
v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l),
v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_internal_external_pqrs():
ii, jj = symbols('i j')
aa, bb = symbols('a b')
k, l = symbols('k l', cls=Dummy)
c, d = symbols('c d', cls=Dummy)
v = Function('v')
t = Function('t')
dums = _get_ordered_dummies
exprs = [
v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
]
for permut in exprs[1:]:
assert dums(exprs[0]) != dums(permut)
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_dummy_order_well_defined():
aa, bb = symbols('a b', above_fermi=True)
k, l, m = symbols('k l m', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
p, q = symbols('p q', cls=Dummy)
A = Function('A')
B = Function('B')
C = Function('C')
dums = _get_ordered_dummies
# We go through all key components in the order of increasing priority,
# and consider only fully orderable expressions. Non-orderable expressions
# are tested elsewhere.
# pos in first factor determines sort order
assert dums(A(k, l)*B(l, k)) == [k, l]
assert dums(A(l, k)*B(l, k)) == [l, k]
assert dums(A(k, l)*B(k, l)) == [k, l]
assert dums(A(l, k)*B(k, l)) == [l, k]
# factors involving the index
assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m]
assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m]
assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m]
assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m]
assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m]
assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m]
assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m]
assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m]
# same, but with factor order determined by non-dummies
assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
# index range
assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p]
assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p]
assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p]
assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p]
assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p]
assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p]
assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p]
assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p]
assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p]
assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p]
assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p]
assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p]
def test_dummy_order_ambiguous():
aa, bb = symbols('a b', above_fermi=True)
i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy)
a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy)
p, q = symbols('p q', cls=Dummy)
p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy)
h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy)
A = Function('A')
B = Function('B')
from sympy.utilities.iterables import variations
# A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest
template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4)
permutator = variations([a, b, c, d, e], 5)
base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4, p5], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
# A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out
template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4)
permutator = variations([a, b, c, d, e], 5)
base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4, p5], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
# A*A*A -- ordering of p5 and p4 is used to figure out the rest
template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4)
permutator = variations([a, b, c, d, e], 5)
base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4, p5], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
def atv(*args):
return AntiSymmetricTensor('v', args[:2], args[2:] )
def att(*args):
if len(args) == 4:
return AntiSymmetricTensor('t', args[:2], args[2:] )
elif len(args) == 2:
return AntiSymmetricTensor('t', (args[0],), (args[1],))
def test_dummy_order_inner_outer_lines_VT1T1T1_AT():
ii = symbols('i', below_fermi=True)
aa = symbols('a', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
# Coupled-Cluster T1 terms with V*T1*T1*T1
# t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
exprs = [
# permut v and t <=> swapping internal lines, equivalent
# irrespective of symmetries in v
atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k),
atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l),
atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k),
atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT():
ii, jj = symbols('i j', below_fermi=True)
aa, bb = symbols('a b', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
# Coupled-Cluster T2 terms with V*T1*T1*T1*T1
# non-equivalent substitutions (change of sign)
exprs = [
# permut t <=> swapping external lines
atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l),
atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == -substitute_dummies(permut)
# equivalent substitutions
exprs = [
atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
# permut t <=> swapping external lines
atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_equivalent_internal_lines_VT1T1_AT():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
exprs = [ # permute v. Different dummy order. Not equivalent.
atv(i, j, a, b)*att(a, i)*att(b, j),
atv(j, i, a, b)*att(a, i)*att(b, j),
atv(i, j, b, a)*att(a, i)*att(b, j),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v. Different dummy order. Equivalent
atv(i, j, a, b)*att(a, i)*att(b, j),
atv(j, i, b, a)*att(a, i)*att(b, j),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [ # permute t. Same dummy order, not equivalent.
atv(i, j, a, b)*att(a, i)*att(b, j),
atv(i, j, a, b)*att(b, i)*att(a, j),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v and t. Different dummy order, equivalent
atv(i, j, a, b)*att(a, i)*att(b, j),
atv(j, i, a, b)*att(a, j)*att(b, i),
atv(i, j, b, a)*att(b, i)*att(a, j),
atv(j, i, b, a)*att(b, j)*att(a, i),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_equivalent_internal_lines_VT2conjT2_AT():
# this diagram requires special handling in TCE
i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
from sympy.utilities.iterables import variations
# atv(abcd)att(abij)att(ijcd)
template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
# atv(abcd)att(abij)att(jicd)
template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT():
# These diagrams invokes _determine_ambiguous() because the
# dummies can not be ordered unambiguously by the key alone
i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
from sympy.utilities.iterables import variations
# atv(abcd)att(abij)att(cdij)
template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j)
permutator = variations([a, b, c, d], 4)
base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
for permut in permutator:
subslist = zip([p1, p2, p3, p4], permut)
expr = template.subs(subslist)
assert substitute_dummies(expr) == substitute_dummies(base)
def test_equivalent_internal_lines_VT2_AT():
i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
exprs = [
# permute v. Same dummy order, not equivalent.
atv(i, j, a, b)*att(a, b, i, j),
atv(j, i, a, b)*att(a, b, i, j),
atv(i, j, b, a)*att(a, b, i, j),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [
# permute t.
atv(i, j, a, b)*att(a, b, i, j),
atv(i, j, a, b)*att(b, a, i, j),
atv(i, j, a, b)*att(a, b, j, i),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
atv(i, j, a, b)*att(a, b, i, j),
atv(j, i, a, b)*att(a, b, j, i),
atv(i, j, b, a)*att(b, a, i, j),
atv(j, i, b, a)*att(b, a, j, i),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_internal_external_VT2T2_AT():
ii, jj = symbols('i j', below_fermi=True)
aa, bb = symbols('a b', above_fermi=True)
k, l = symbols('k l', below_fermi=True, cls=Dummy)
c, d = symbols('c d', above_fermi=True, cls=Dummy)
exprs = [
atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [
atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l),
atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k),
atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l),
atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
exprs = [
atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l),
atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k),
atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l),
atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_internal_external_pqrs_AT():
ii, jj = symbols('i j')
aa, bb = symbols('a b')
k, l = symbols('k l', cls=Dummy)
c, d = symbols('c d', cls=Dummy)
exprs = [
atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
]
for permut in exprs[1:]:
assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
def test_issue_19661():
a = Symbol('0')
assert latex(Commutator(Bd(a)**2, B(a))
) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]'
def test_canonical_ordering_AntiSymmetricTensor():
v = symbols("v")
c, d = symbols(('c','d'), above_fermi=True,
cls=Dummy)
k, l = symbols(('k','l'), below_fermi=True,
cls=Dummy)
# formerly, the left gave either the left or the right
assert AntiSymmetricTensor(v, (k, l), (d, c)
) == -AntiSymmetricTensor(v, (l, k), (d, c))
|
5d271040ef51851ae5a92208fd9cb2394a44fb3b3eef0a61485099ab63ae1671 | from sympy.physics.pring import wavefunction, energy
from sympy.core.numbers import (I, pi)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.simplify.simplify import simplify
from sympy.abc import m, x, r
from sympy.physics.quantum.constants import hbar
def test_wavefunction():
Psi = {
0: (1/sqrt(2 * pi)),
1: (1/sqrt(2 * pi)) * exp(I * x),
2: (1/sqrt(2 * pi)) * exp(2 * I * x),
3: (1/sqrt(2 * pi)) * exp(3 * I * x)
}
for n in Psi:
assert simplify(wavefunction(n, x) - Psi[n]) == 0
def test_norm(n=1):
# Maximum "n" which is tested:
for i in range(n + 1):
assert integrate(
wavefunction(i, x) * wavefunction(-i, x), (x, 0, 2 * pi)) == 1
def test_orthogonality(n=1):
# Maximum "n" which is tested:
for i in range(n + 1):
for j in range(i+1, n+1):
assert integrate(
wavefunction(i, x) * wavefunction(j, x), (x, 0, 2 * pi)) == 0
def test_energy(n=1):
# Maximum "n" which is tested:
for i in range(n+1):
assert simplify(
energy(i, m, r) - ((i**2 * hbar**2) / (2 * m * r**2))) == 0
|
db62d48b85679fe170e8815e7f15b4ef93390809782c03b91fbec5db961f4dae | """
This module can be used to solve 2D beam bending problems with
singularity functions in mechanics.
"""
from sympy.core import S, Symbol, diff, symbols
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.relational import Eq
from sympy.core.sympify import sympify
from sympy.solvers import linsolve
from sympy.solvers.ode.ode import dsolve
from sympy.solvers.solvers import solve
from sympy.printing import sstr
from sympy.functions import SingularityFunction, Piecewise, factorial
from sympy.integrals import integrate
from sympy.series import limit
from sympy.plotting import plot, PlotGrid
from sympy.geometry.entity import GeometryEntity
from sympy.external import import_module
from sympy.sets.sets import Interval
from sympy.utilities.lambdify import lambdify
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import iterable
numpy = import_module('numpy', import_kwargs={'fromlist':['arange']})
class Beam:
"""
A Beam is a structural element that is capable of withstanding load
primarily by resisting against bending. Beams are characterized by
their cross sectional profile(Second moment of area), their length
and their material.
.. note::
A consistent sign convention must be used while solving a beam
bending problem; the results will
automatically follow the chosen sign convention. However, the
chosen sign convention must respect the rule that, on the positive
side of beam's axis (in respect to current section), a loading force
giving positive shear yields a negative moment, as below (the
curved arrow shows the positive moment and rotation):
.. image:: allowed-sign-conventions.png
Examples
========
There is a beam of length 4 meters. A constant distributed load of 6 N/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. The deflection of the beam at the end is restricted.
Using the sign convention of downwards forces being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols, Piecewise
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(4, E, I)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(6, 2, 0)
>>> b.apply_load(R2, 4, -1)
>>> b.bc_deflection = [(0, 0), (4, 0)]
>>> b.boundary_conditions
{'deflection': [(0, 0), (4, 0)], 'slope': []}
>>> b.load
R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0)
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.load
-3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1)
>>> b.shear_force()
3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0)
>>> b.bending_moment()
3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1)
>>> b.slope()
(-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I)
>>> b.deflection()
(7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I)
>>> b.deflection().rewrite(Piecewise)
(7*x - Piecewise((x**3, x > 0), (0, True))/2
- 3*Piecewise(((x - 4)**3, x > 4), (0, True))/2
+ Piecewise(((x - 2)**4, x > 2), (0, True))/4)/(E*I)
"""
def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C'):
"""Initializes the class.
Parameters
==========
length : Sympifyable
A Symbol or value representing the Beam's length.
elastic_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of Elasticity.
It is a measure of the stiffness of the Beam material. It can
also be a continuous function of position along the beam.
second_moment : Sympifyable or Geometry object
Describes the cross-section of the beam via a SymPy expression
representing the Beam's second moment of area. It is a geometrical
property of an area which reflects how its points are distributed
with respect to its neutral axis. It can also be a continuous
function of position along the beam. Alternatively ``second_moment``
can be a shape object such as a ``Polygon`` from the geometry module
representing the shape of the cross-section of the beam. In such cases,
it is assumed that the x-axis of the shape object is aligned with the
bending axis of the beam. The second moment of area will be computed
from the shape object internally.
area : Symbol/float
Represents the cross-section area of beam
variable : Symbol, optional
A Symbol object that will be used as the variable along the beam
while representing the load, shear, moment, slope and deflection
curve. By default, it is set to ``Symbol('x')``.
base_char : String, optional
A String that will be used as base character to generate sequential
symbols for integration constants in cases where boundary conditions
are not sufficient to solve them.
"""
self.length = length
self.elastic_modulus = elastic_modulus
if isinstance(second_moment, GeometryEntity):
self.cross_section = second_moment
else:
self.cross_section = None
self.second_moment = second_moment
self.variable = variable
self._base_char = base_char
self._boundary_conditions = {'deflection': [], 'slope': []}
self._load = 0
self._area = area
self._applied_supports = []
self._support_as_loads = []
self._applied_loads = []
self._reaction_loads = {}
self._ild_reactions = {}
self._ild_shear = 0
self._ild_moment = 0
# _original_load is a copy of _load equations with unsubstituted reaction
# forces. It is used for calculating reaction forces in case of I.L.D.
self._original_load = 0
self._composite_type = None
self._hinge_position = None
def __str__(self):
shape_description = self._cross_section if self._cross_section else self._second_moment
str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description))
return str_sol
@property
def reaction_loads(self):
""" Returns the reaction forces in a dictionary."""
return self._reaction_loads
@property
def ild_shear(self):
""" Returns the I.L.D. shear equation."""
return self._ild_shear
@property
def ild_reactions(self):
""" Returns the I.L.D. reaction forces in a dictionary."""
return self._ild_reactions
@property
def ild_moment(self):
""" Returns the I.L.D. moment equation."""
return self._ild_moment
@property
def length(self):
"""Length of the Beam."""
return self._length
@length.setter
def length(self, l):
self._length = sympify(l)
@property
def area(self):
"""Cross-sectional area of the Beam. """
return self._area
@area.setter
def area(self, a):
self._area = sympify(a)
@property
def variable(self):
"""
A symbol that can be used as a variable along the length of the beam
while representing load distribution, shear force curve, bending
moment, slope curve and the deflection curve. By default, it is set
to ``Symbol('x')``, but this property is mutable.
Examples
========
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I, A = symbols('E, I, A')
>>> x, y, z = symbols('x, y, z')
>>> b = Beam(4, E, I)
>>> b.variable
x
>>> b.variable = y
>>> b.variable
y
>>> b = Beam(4, E, I, A, z)
>>> b.variable
z
"""
return self._variable
@variable.setter
def variable(self, v):
if isinstance(v, Symbol):
self._variable = v
else:
raise TypeError("""The variable should be a Symbol object.""")
@property
def elastic_modulus(self):
"""Young's Modulus of the Beam. """
return self._elastic_modulus
@elastic_modulus.setter
def elastic_modulus(self, e):
self._elastic_modulus = sympify(e)
@property
def second_moment(self):
"""Second moment of area of the Beam. """
return self._second_moment
@second_moment.setter
def second_moment(self, i):
self._cross_section = None
if isinstance(i, GeometryEntity):
raise ValueError("To update cross-section geometry use `cross_section` attribute")
else:
self._second_moment = sympify(i)
@property
def cross_section(self):
"""Cross-section of the beam"""
return self._cross_section
@cross_section.setter
def cross_section(self, s):
if s:
self._second_moment = s.second_moment_of_area()[0]
self._cross_section = s
@property
def boundary_conditions(self):
"""
Returns a dictionary of boundary conditions applied on the beam.
The dictionary has three keywords namely moment, slope and deflection.
The value of each keyword is a list of tuple, where each tuple
contains location and value of a boundary condition in the format
(location, value).
Examples
========
There is a beam of length 4 meters. The bending moment at 0 should be 4
and at 4 it should be 0. The slope of the beam should be 1 at 0. The
deflection should be 2 at 0.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.bc_deflection = [(0, 2)]
>>> b.bc_slope = [(0, 1)]
>>> b.boundary_conditions
{'deflection': [(0, 2)], 'slope': [(0, 1)]}
Here the deflection of the beam should be ``2`` at ``0``.
Similarly, the slope of the beam should be ``1`` at ``0``.
"""
return self._boundary_conditions
@property
def bc_slope(self):
return self._boundary_conditions['slope']
@bc_slope.setter
def bc_slope(self, s_bcs):
self._boundary_conditions['slope'] = s_bcs
@property
def bc_deflection(self):
return self._boundary_conditions['deflection']
@bc_deflection.setter
def bc_deflection(self, d_bcs):
self._boundary_conditions['deflection'] = d_bcs
def join(self, beam, via="fixed"):
"""
This method joins two beams to make a new composite beam system.
Passed Beam class instance is attached to the right end of calling
object. This method can be used to form beams having Discontinuous
values of Elastic modulus or Second moment.
Parameters
==========
beam : Beam class object
The Beam object which would be connected to the right of calling
object.
via : String
States the way two Beam object would get connected
- For axially fixed Beams, via="fixed"
- For Beams connected via hinge, via="hinge"
Examples
========
There is a cantilever beam of length 4 meters. For first 2 meters
its moment of inertia is `1.5*I` and `I` for the other end.
A pointload of magnitude 4 N is applied from the top at its free end.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b1 = Beam(2, E, 1.5*I)
>>> b2 = Beam(2, E, I)
>>> b = b1.join(b2, "fixed")
>>> b.apply_load(20, 4, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 0, -2)
>>> b.bc_slope = [(0, 0)]
>>> b.bc_deflection = [(0, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.load
80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1)
>>> b.slope()
(-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0)
- 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I)
+ 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
new_length = self.length + beam.length
if self.second_moment != beam.second_moment:
new_second_moment = Piecewise((self.second_moment, x<=self.length),
(beam.second_moment, x<=new_length))
else:
new_second_moment = self.second_moment
if via == "fixed":
new_beam = Beam(new_length, E, new_second_moment, x)
new_beam._composite_type = "fixed"
return new_beam
if via == "hinge":
new_beam = Beam(new_length, E, new_second_moment, x)
new_beam._composite_type = "hinge"
new_beam._hinge_position = self.length
return new_beam
def apply_support(self, loc, type="fixed"):
"""
This method applies support to a particular beam object.
Parameters
==========
loc : Sympifyable
Location of point at which support is applied.
type : String
Determines type of Beam support applied. To apply support structure
with
- zero degree of freedom, type = "fixed"
- one degree of freedom, type = "pin"
- two degrees of freedom, type = "roller"
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(30, E, I)
>>> b.apply_support(10, 'roller')
>>> b.apply_support(30, 'roller')
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(120, 30, -2)
>>> R_10, R_30 = symbols('R_10, R_30')
>>> b.solve_for_reaction_loads(R_10, R_30)
>>> b.load
-8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1)
+ 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
>>> b.slope()
(-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I)
"""
loc = sympify(loc)
self._applied_supports.append((loc, type))
if type in ("pin", "roller"):
reaction_load = Symbol('R_'+str(loc))
self.apply_load(reaction_load, loc, -1)
self.bc_deflection.append((loc, 0))
else:
reaction_load = Symbol('R_'+str(loc))
reaction_moment = Symbol('M_'+str(loc))
self.apply_load(reaction_load, loc, -1)
self.apply_load(reaction_moment, loc, -2)
self.bc_deflection.append((loc, 0))
self.bc_slope.append((loc, 0))
self._support_as_loads.append((reaction_moment, loc, -2, None))
self._support_as_loads.append((reaction_load, loc, -1, None))
def apply_load(self, value, start, order, end=None):
"""
This method adds up the loads given to a particular beam object.
Parameters
==========
value : Sympifyable
The value inserted should have the units [Force/(Distance**(n+1)]
where n is the order of applied load.
Units for applied loads:
- For moments, unit = kN*m
- For point loads, unit = kN
- For constant distributed load, unit = kN/m
- For ramp loads, unit = kN/m/m
- For parabolic ramp loads, unit = kN/m/m/m
- ... so on.
start : Sympifyable
The starting point of the applied load. For point moments and
point forces this is the location of application.
order : Integer
The order of the applied load.
- For moments, order = -2
- For point loads, order =-1
- For constant distributed load, order = 0
- For ramp loads, order = 1
- For parabolic ramp loads, order = 2
- ... so on.
end : Sympifyable, optional
An optional argument that can be used if the load has an end point
within the length of the beam.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A point load of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 2 meters to 3 meters
away from the starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 2, 2, end=3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
self._applied_loads.append((value, start, order, end))
self._load += value*SingularityFunction(x, start, order)
self._original_load += value*SingularityFunction(x, start, order)
if end:
# load has an end point within the length of the beam.
self._handle_end(x, value, start, order, end, type="apply")
def remove_load(self, value, start, order, end=None):
"""
This method removes a particular load present on the beam object.
Returns a ValueError if the load passed as an argument is not
present on the beam.
Parameters
==========
value : Sympifyable
The magnitude of an applied load.
start : Sympifyable
The starting point of the applied load. For point moments and
point forces this is the location of application.
order : Integer
The order of the applied load.
- For moments, order= -2
- For point loads, order=-1
- For constant distributed load, order=0
- For ramp loads, order=1
- For parabolic ramp loads, order=2
- ... so on.
end : Sympifyable, optional
An optional argument that can be used if the load has an end point
within the length of the beam.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A pointload of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 2 meters to 3 meters
away from the starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 2, 2, end=3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
>>> b.remove_load(-2, 2, 2, end = 3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if (value, start, order, end) in self._applied_loads:
self._load -= value*SingularityFunction(x, start, order)
self._original_load -= value*SingularityFunction(x, start, order)
self._applied_loads.remove((value, start, order, end))
else:
msg = "No such load distribution exists on the beam object."
raise ValueError(msg)
if end:
# load has an end point within the length of the beam.
self._handle_end(x, value, start, order, end, type="remove")
def _handle_end(self, x, value, start, order, end, type):
"""
This functions handles the optional `end` value in the
`apply_load` and `remove_load` functions. When the value
of end is not NULL, this function will be executed.
"""
if order.is_negative:
msg = ("If 'end' is provided the 'order' of the load cannot "
"be negative, i.e. 'end' is only valid for distributed "
"loads.")
raise ValueError(msg)
# NOTE : A Taylor series can be used to define the summation of
# singularity functions that subtract from the load past the end
# point such that it evaluates to zero past 'end'.
f = value*x**order
if type == "apply":
# iterating for "apply_load" method
for i in range(0, order + 1):
self._load -= (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
self._original_load -= (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
elif type == "remove":
# iterating for "remove_load" method
for i in range(0, order + 1):
self._load += (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
self._original_load += (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
@property
def load(self):
"""
Returns a Singularity Function expression which represents
the load distribution curve of the Beam object.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A point load of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 3 meters away from the
starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 3, 2)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2)
"""
return self._load
@property
def applied_loads(self):
"""
Returns a list of all loads applied on the beam object.
Each load in the list is a tuple of form (value, start, order, end).
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A pointload of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point. Another pointload of magnitude 5 N
is applied at same position.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(5, 2, -1)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1)
>>> b.applied_loads
[(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)]
"""
return self._applied_loads
def _solve_hinge_beams(self, *reactions):
"""Method to find integration constants and reactional variables in a
composite beam connected via hinge.
This method resolves the composite Beam into its sub-beams and then
equations of shear force, bending moment, slope and deflection are
evaluated for both of them separately. These equations are then solved
for unknown reactions and integration constants using the boundary
conditions applied on the Beam. Equal deflection of both sub-beams
at the hinge joint gives us another equation to solve the system.
Examples
========
A combined beam, with constant fkexural rigidity E*I, is formed by joining
a Beam of length 2*l to the right of another Beam of length l. The whole beam
is fixed at both of its both end. A point load of magnitude P is also applied
from the top at a distance of 2*l from starting point.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> l=symbols('l', positive=True)
>>> b1=Beam(l, E, I)
>>> b2=Beam(2*l, E, I)
>>> b=b1.join(b2,"hinge")
>>> M1, A1, M2, A2, P = symbols('M1 A1 M2 A2 P')
>>> b.apply_load(A1,0,-1)
>>> b.apply_load(M1,0,-2)
>>> b.apply_load(P,2*l,-1)
>>> b.apply_load(A2,3*l,-1)
>>> b.apply_load(M2,3*l,-2)
>>> b.bc_slope=[(0,0), (3*l, 0)]
>>> b.bc_deflection=[(0,0), (3*l, 0)]
>>> b.solve_for_reaction_loads(M1, A1, M2, A2)
>>> b.reaction_loads
{A1: -5*P/18, A2: -13*P/18, M1: 5*P*l/18, M2: -4*P*l/9}
>>> b.slope()
(5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, 0, 0)/(E*I)
- (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, l, 0)/(E*I)
+ (P*l**2/18 - 4*P*l*SingularityFunction(-l + x, 2*l, 1)/9 - 5*P*SingularityFunction(-l + x, 0, 2)/36 + P*SingularityFunction(-l + x, l, 2)/2
- 13*P*SingularityFunction(-l + x, 2*l, 2)/36)*SingularityFunction(x, l, 0)/(E*I)
>>> b.deflection()
(5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, 0, 0)/(E*I)
- (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, l, 0)/(E*I)
+ (5*P*l**3/54 + P*l**2*(-l + x)/18 - 2*P*l*SingularityFunction(-l + x, 2*l, 2)/9 - 5*P*SingularityFunction(-l + x, 0, 3)/108 + P*SingularityFunction(-l + x, l, 3)/6
- 13*P*SingularityFunction(-l + x, 2*l, 3)/108)*SingularityFunction(x, l, 0)/(E*I)
"""
x = self.variable
l = self._hinge_position
E = self._elastic_modulus
I = self._second_moment
if isinstance(I, Piecewise):
I1 = I.args[0][0]
I2 = I.args[1][0]
else:
I1 = I2 = I
load_1 = 0 # Load equation on first segment of composite beam
load_2 = 0 # Load equation on second segment of composite beam
# Distributing load on both segments
for load in self.applied_loads:
if load[1] < l:
load_1 += load[0]*SingularityFunction(x, load[1], load[2])
if load[2] == 0:
load_1 -= load[0]*SingularityFunction(x, load[3], load[2])
elif load[2] > 0:
load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) + load[0]*SingularityFunction(x, load[3], 0)
elif load[1] == l:
load_1 += load[0]*SingularityFunction(x, load[1], load[2])
load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2])
elif load[1] > l:
load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2])
if load[2] == 0:
load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2])
elif load[2] > 0:
load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) + load[0]*SingularityFunction(x, load[3] - l, 0)
h = Symbol('h') # Force due to hinge
load_1 += h*SingularityFunction(x, l, -1)
load_2 -= h*SingularityFunction(x, 0, -1)
eq = []
shear_1 = integrate(load_1, x)
shear_curve_1 = limit(shear_1, x, l)
eq.append(shear_curve_1)
bending_1 = integrate(shear_1, x)
moment_curve_1 = limit(bending_1, x, l)
eq.append(moment_curve_1)
shear_2 = integrate(load_2, x)
shear_curve_2 = limit(shear_2, x, self.length - l)
eq.append(shear_curve_2)
bending_2 = integrate(shear_2, x)
moment_curve_2 = limit(bending_2, x, self.length - l)
eq.append(moment_curve_2)
C1 = Symbol('C1')
C2 = Symbol('C2')
C3 = Symbol('C3')
C4 = Symbol('C4')
slope_1 = S.One/(E*I1)*(integrate(bending_1, x) + C1)
def_1 = S.One/(E*I1)*(integrate((E*I)*slope_1, x) + C1*x + C2)
slope_2 = S.One/(E*I2)*(integrate(integrate(integrate(load_2, x), x), x) + C3)
def_2 = S.One/(E*I2)*(integrate((E*I)*slope_2, x) + C4)
for position, value in self.bc_slope:
if position<l:
eq.append(slope_1.subs(x, position) - value)
else:
eq.append(slope_2.subs(x, position - l) - value)
for position, value in self.bc_deflection:
if position<l:
eq.append(def_1.subs(x, position) - value)
else:
eq.append(def_2.subs(x, position - l) - value)
eq.append(def_1.subs(x, l) - def_2.subs(x, 0)) # Deflection of both the segments at hinge would be equal
constants = list(linsolve(eq, C1, C2, C3, C4, h, *reactions))
reaction_values = list(constants[0])[5:]
self._reaction_loads = dict(zip(reactions, reaction_values))
self._load = self._load.subs(self._reaction_loads)
# Substituting constants and reactional load and moments with their corresponding values
slope_1 = slope_1.subs({C1: constants[0][0], h:constants[0][4]}).subs(self._reaction_loads)
def_1 = def_1.subs({C1: constants[0][0], C2: constants[0][1], h:constants[0][4]}).subs(self._reaction_loads)
slope_2 = slope_2.subs({x: x-l, C3: constants[0][2], h:constants[0][4]}).subs(self._reaction_loads)
def_2 = def_2.subs({x: x-l,C3: constants[0][2], C4: constants[0][3], h:constants[0][4]}).subs(self._reaction_loads)
self._hinge_beam_slope = slope_1*SingularityFunction(x, 0, 0) - slope_1*SingularityFunction(x, l, 0) + slope_2*SingularityFunction(x, l, 0)
self._hinge_beam_deflection = def_1*SingularityFunction(x, 0, 0) - def_1*SingularityFunction(x, l, 0) + def_2*SingularityFunction(x, l, 0)
def solve_for_reaction_loads(self, *reactions):
"""
Solves for the reaction forces.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1) # Reaction force at x = 10
>>> b.apply_load(R2, 30, -1) # Reaction force at x = 30
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.load
R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1)
- 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2)
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.reaction_loads
{R1: 6, R2: 2}
>>> b.load
-8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1)
+ 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
"""
if self._composite_type == "hinge":
return self._solve_hinge_beams(*reactions)
x = self.variable
l = self.length
C3 = Symbol('C3')
C4 = Symbol('C4')
shear_curve = limit(self.shear_force(), x, l)
moment_curve = limit(self.bending_moment(), x, l)
slope_eqs = []
deflection_eqs = []
slope_curve = integrate(self.bending_moment(), x) + C3
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
slope_eqs.append(eqs)
deflection_curve = integrate(slope_curve, x) + C4
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
deflection_eqs.append(eqs)
solution = list((linsolve([shear_curve, moment_curve] + slope_eqs
+ deflection_eqs, (C3, C4) + reactions).args)[0])
solution = solution[2:]
self._reaction_loads = dict(zip(reactions, solution))
self._load = self._load.subs(self._reaction_loads)
def shear_force(self):
"""
Returns a Singularity Function expression which represents
the shear force curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.shear_force()
8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
"""
x = self.variable
return -integrate(self.load, x)
def max_shear_force(self):
"""Returns maximum Shear force and its coordinate
in the Beam object."""
shear_curve = self.shear_force()
x = self.variable
terms = shear_curve.args
singularity = [] # Points at which shear function changes
for term in terms:
if isinstance(term, Mul):
term = term.args[-1] # SingularityFunction in the term
singularity.append(term.args[1])
singularity.sort()
singularity = list(set(singularity))
intervals = [] # List of Intervals with discrete value of shear force
shear_values = [] # List of values of shear force in each interval
for i, s in enumerate(singularity):
if s == 0:
continue
try:
shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x<s), (float("nan"), True))
points = solve(shear_slope, x)
val = []
for point in points:
val.append(abs(shear_curve.subs(x, point)))
points.extend([singularity[i-1], s])
val += [abs(limit(shear_curve, x, singularity[i-1], '+')), abs(limit(shear_curve, x, s, '-'))]
max_shear = max(val)
shear_values.append(max_shear)
intervals.append(points[val.index(max_shear)])
# If shear force in a particular Interval has zero or constant
# slope, then above block gives NotImplementedError as
# solve can't represent Interval solutions.
except NotImplementedError:
initial_shear = limit(shear_curve, x, singularity[i-1], '+')
final_shear = limit(shear_curve, x, s, '-')
# If shear_curve has a constant slope(it is a line).
if shear_curve.subs(x, (singularity[i-1] + s)/2) == (initial_shear + final_shear)/2 and initial_shear != final_shear:
shear_values.extend([initial_shear, final_shear])
intervals.extend([singularity[i-1], s])
else: # shear_curve has same value in whole Interval
shear_values.append(final_shear)
intervals.append(Interval(singularity[i-1], s))
shear_values = list(map(abs, shear_values))
maximum_shear = max(shear_values)
point = intervals[shear_values.index(maximum_shear)]
return (point, maximum_shear)
def bending_moment(self):
"""
Returns a Singularity Function expression which represents
the bending moment curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.bending_moment()
8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
"""
x = self.variable
return integrate(self.shear_force(), x)
def max_bmoment(self):
"""Returns maximum Shear force and its coordinate
in the Beam object."""
bending_curve = self.bending_moment()
x = self.variable
terms = bending_curve.args
singularity = [] # Points at which bending moment changes
for term in terms:
if isinstance(term, Mul):
term = term.args[-1] # SingularityFunction in the term
singularity.append(term.args[1])
singularity.sort()
singularity = list(set(singularity))
intervals = [] # List of Intervals with discrete value of bending moment
moment_values = [] # List of values of bending moment in each interval
for i, s in enumerate(singularity):
if s == 0:
continue
try:
moment_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self.shear_force().rewrite(Piecewise), x<s), (float("nan"), True))
points = solve(moment_slope, x)
val = []
for point in points:
val.append(abs(bending_curve.subs(x, point)))
points.extend([singularity[i-1], s])
val += [abs(limit(bending_curve, x, singularity[i-1], '+')), abs(limit(bending_curve, x, s, '-'))]
max_moment = max(val)
moment_values.append(max_moment)
intervals.append(points[val.index(max_moment)])
# If bending moment in a particular Interval has zero or constant
# slope, then above block gives NotImplementedError as solve
# can't represent Interval solutions.
except NotImplementedError:
initial_moment = limit(bending_curve, x, singularity[i-1], '+')
final_moment = limit(bending_curve, x, s, '-')
# If bending_curve has a constant slope(it is a line).
if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment:
moment_values.extend([initial_moment, final_moment])
intervals.extend([singularity[i-1], s])
else: # bending_curve has same value in whole Interval
moment_values.append(final_moment)
intervals.append(Interval(singularity[i-1], s))
moment_values = list(map(abs, moment_values))
maximum_moment = max(moment_values)
point = intervals[moment_values.index(maximum_moment)]
return (point, maximum_moment)
def point_cflexure(self):
"""
Returns a Set of point(s) with zero bending moment and
where bending moment curve of the beam object changes
its sign from negative to positive or vice versa.
Examples
========
There is is 10 meter long overhanging beam. There are
two simple supports below the beam. One at the start
and another one at a distance of 6 meters from the start.
Point loads of magnitude 10KN and 20KN are applied at
2 meters and 4 meters from start respectively. A Uniformly
distribute load of magnitude of magnitude 3KN/m is also
applied on top starting from 6 meters away from starting
point till end.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(10, E, I)
>>> b.apply_load(-4, 0, -1)
>>> b.apply_load(-46, 6, -1)
>>> b.apply_load(10, 2, -1)
>>> b.apply_load(20, 4, -1)
>>> b.apply_load(3, 6, 0)
>>> b.point_cflexure()
[10/3]
"""
# To restrict the range within length of the Beam
moment_curve = Piecewise((float("nan"), self.variable<=0),
(self.bending_moment(), self.variable<self.length),
(float("nan"), True))
points = solve(moment_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
return points
def slope(self):
"""
Returns a Singularity Function expression which represents
the slope the elastic curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.slope()
(-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
I = self.second_moment
if self._composite_type == "hinge":
return self._hinge_beam_slope
if not self._boundary_conditions['slope']:
return diff(self.deflection(), x)
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
slope = 0
prev_slope = 0
prev_end = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
if i != len(args) - 1:
slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \
(prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
return slope
C3 = Symbol('C3')
slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3
bc_eqs = []
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, C3))
slope_curve = slope_curve.subs({C3: constants[0][0]})
return slope_curve
def deflection(self):
"""
Returns a Singularity Function expression which represents
the elastic curve or deflection of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.deflection()
(4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
+ 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
I = self.second_moment
if self._composite_type == "hinge":
return self._hinge_beam_deflection
if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']:
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
base_char = self._base_char
constants = symbols(base_char + '3:5')
return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1]
elif not self._boundary_conditions['deflection']:
base_char = self._base_char
constant = symbols(base_char + '4')
return integrate(self.slope(), x) + constant
elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']:
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
base_char = self._base_char
C3, C4 = symbols(base_char + '3:5') # Integration constants
slope_curve = -integrate(self.bending_moment(), x) + C3
deflection_curve = integrate(slope_curve, x) + C4
bc_eqs = []
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, (C3, C4)))
deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]})
return S.One/(E*I)*deflection_curve
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
C4 = Symbol('C4')
deflection_curve = integrate(self.slope(), x) + C4
bc_eqs = []
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, C4))
deflection_curve = deflection_curve.subs({C4: constants[0][0]})
return deflection_curve
def max_deflection(self):
"""
Returns point of max deflection and its corresponding deflection value
in a Beam object.
"""
# To restrict the range within length of the Beam
slope_curve = Piecewise((float("nan"), self.variable<=0),
(self.slope(), self.variable<self.length),
(float("nan"), True))
points = solve(slope_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
deflection_curve = self.deflection()
deflections = [deflection_curve.subs(self.variable, x) for x in points]
deflections = list(map(abs, deflections))
if len(deflections) != 0:
max_def = max(deflections)
return (points[deflections.index(max_def)], max_def)
else:
return None
def shear_stress(self):
"""
Returns an expression representing the Shear Stress
curve of the Beam object.
"""
return self.shear_force()/self._area
def plot_shear_stress(self, subs=None):
"""
Returns a plot of shear stress present in the beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters and area of cross section 2 square
meters. A constant distributed load of 10 KN/m is applied from half of
the beam till the end. There are two simple supports below the beam,
one at the starting point and another at the ending point of the beam.
A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6), 2)
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_shear_stress()
Plot object containing:
[0]: cartesian line: 6875*SingularityFunction(x, 0, 0) - 2500*SingularityFunction(x, 2, 0)
- 5000*SingularityFunction(x, 4, 1) + 15625*SingularityFunction(x, 8, 0)
+ 5000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
"""
shear_stress = self.shear_stress()
x = self.variable
length = self.length
if subs is None:
subs = {}
for sym in shear_stress.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('value of %s was not passed.' %sym)
if length in subs:
length = subs[length]
# Returns Plot of Shear Stress
return plot (shear_stress.subs(subs), (x, 0, length),
title='Shear Stress', xlabel=r'$\mathrm{x}$', ylabel=r'$\tau$',
line_color='r')
def plot_shear_force(self, subs=None):
"""
Returns a plot for Shear force present in the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_shear_force()
Plot object containing:
[0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0)
- 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0)
+ 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
"""
shear_force = self.shear_force()
if subs is None:
subs = {}
for sym in shear_force.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force',
xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g')
def plot_bending_moment(self, subs=None):
"""
Returns a plot for Bending moment present in the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_bending_moment()
Plot object containing:
[0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1)
- 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1)
+ 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0)
"""
bending_moment = self.bending_moment()
if subs is None:
subs = {}
for sym in bending_moment.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment',
xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b')
def plot_slope(self, subs=None):
"""
Returns a plot for slope of deflection curve of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_slope()
Plot object containing:
[0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2)
+ 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2)
- 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0)
"""
slope = self.slope()
if subs is None:
subs = {}
for sym in slope.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(slope.subs(subs), (self.variable, 0, length), title='Slope',
xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m')
def plot_deflection(self, subs=None):
"""
Returns a plot for deflection curve of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_deflection()
Plot object containing:
[0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3)
+ 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4)
- 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4)
for x over (0.0, 8.0)
"""
deflection = self.deflection()
if subs is None:
subs = {}
for sym in deflection.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(deflection.subs(subs), (self.variable, 0, length),
title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
line_color='r')
def plot_loading_results(self, subs=None):
"""
Returns a subplot of Shear Force, Bending Moment,
Slope and Deflection of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> axes = b.plot_loading_results()
"""
length = self.length
variable = self.variable
if subs is None:
subs = {}
for sym in self.deflection().atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if length in subs:
length = subs[length]
ax1 = plot(self.shear_force().subs(subs), (variable, 0, length),
title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$',
line_color='g', show=False)
ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length),
title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$',
line_color='b', show=False)
ax3 = plot(self.slope().subs(subs), (variable, 0, length),
title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$',
line_color='m', show=False)
ax4 = plot(self.deflection().subs(subs), (variable, 0, length),
title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
line_color='r', show=False)
return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
def _solve_for_ild_equations(self):
"""
Helper function for I.L.D. It takes the unsubstituted
copy of the load equation and uses it to calculate shear force and bending
moment equations.
"""
x = self.variable
shear_force = -integrate(self._original_load, x)
bending_moment = integrate(shear_force, x)
return shear_force, bending_moment
def solve_for_ild_reactions(self, value, *reactions):
"""
Determines the Influence Line Diagram equations for reaction
forces under the effect of a moving load.
Parameters
==========
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 10 meters. There are two simple supports
below the beam, one at the starting point and another at the ending
point of the beam. Calculate the I.L.D. equations for reaction forces
under the effect of a moving load of magnitude 1kN.
.. image:: ildreaction.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_10 = symbols('R_0, R_10')
>>> b = Beam(10, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(10, 'roller')
>>> b.solve_for_ild_reactions(1,R_0,R_10)
>>> b.ild_reactions
{R_0: x/10 - 1, R_10: -x/10}
"""
shear_force, bending_moment = self._solve_for_ild_equations()
x = self.variable
l = self.length
C3 = Symbol('C3')
C4 = Symbol('C4')
shear_curve = limit(shear_force, x, l) - value
moment_curve = limit(bending_moment, x, l) - value*(l-x)
slope_eqs = []
deflection_eqs = []
slope_curve = integrate(bending_moment, x) + C3
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
slope_eqs.append(eqs)
deflection_curve = integrate(slope_curve, x) + C4
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
deflection_eqs.append(eqs)
solution = list((linsolve([shear_curve, moment_curve] + slope_eqs
+ deflection_eqs, (C3, C4) + reactions).args)[0])
solution = solution[2:]
# Determining the equations and solving them.
self._ild_reactions = dict(zip(reactions, solution))
def plot_ild_reactions(self, subs=None):
"""
Plots the Influence Line Diagram of Reaction Forces
under the effect of a moving load. This function
should be called after calling solve_for_ild_reactions().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 10 meters. A point load of magnitude 5KN
is also applied from top of the beam, at a distance of 4 meters
from the starting point. There are two simple supports below the
beam, located at the starting point and at a distance of 7 meters
from the starting point. Plot the I.L.D. equations for reactions
at both support points under the effect of a moving load
of magnitude 1kN.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_7 = symbols('R_0, R_7')
>>> b = Beam(10, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(7, 'roller')
>>> b.apply_load(5,4,-1)
>>> b.solve_for_ild_reactions(1,R_0,R_7)
>>> b.ild_reactions
{R_0: x/7 - 22/7, R_7: -x/7 - 20/7}
>>> b.plot_ild_reactions()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: x/7 - 22/7 for x over (0.0, 10.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -x/7 - 20/7 for x over (0.0, 10.0)
"""
if not self._ild_reactions:
raise ValueError("I.L.D. reaction equations not found. Please use solve_for_ild_reactions() to generate the I.L.D. reaction equations.")
x = self.variable
ildplots = []
if subs is None:
subs = {}
for reaction in self._ild_reactions:
for sym in self._ild_reactions[reaction].atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for reaction in self._ild_reactions:
ildplots.append(plot(self._ild_reactions[reaction].subs(subs),
(x, 0, self._length.subs(subs)), title='I.L.D. for Reactions',
xlabel=x, ylabel=reaction, line_color='blue', show=False))
return PlotGrid(len(ildplots), 1, *ildplots)
def solve_for_ild_shear(self, distance, value, *reactions):
"""
Determines the Influence Line Diagram equations for shear at a
specified point under the effect of a moving load.
Parameters
==========
distance : Integer
Distance of the point from the start of the beam
for which equations are to be determined
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Calculate the I.L.D. equations for Shear at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_shear(4, 1, R_0, R_8)
>>> b.ild_shear
Piecewise((x/8, x < 4), (x/8 - 1, x > 4))
"""
x = self.variable
l = self.length
shear_force, _ = self._solve_for_ild_equations()
shear_curve1 = value - limit(shear_force, x, distance)
shear_curve2 = (limit(shear_force, x, l) - limit(shear_force, x, distance)) - value
for reaction in reactions:
shear_curve1 = shear_curve1.subs(reaction,self._ild_reactions[reaction])
shear_curve2 = shear_curve2.subs(reaction,self._ild_reactions[reaction])
shear_eq = Piecewise((shear_curve1, x < distance), (shear_curve2, x > distance))
self._ild_shear = shear_eq
def plot_ild_shear(self,subs=None):
"""
Plots the Influence Line Diagram for Shear under the effect
of a moving load. This function should be called after
calling solve_for_ild_shear().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Plot the I.L.D. for Shear at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_shear(4, 1, R_0, R_8)
>>> b.ild_shear
Piecewise((x/8, x < 4), (x/8 - 1, x > 4))
>>> b.plot_ild_shear()
Plot object containing:
[0]: cartesian line: Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) for x over (0.0, 12.0)
"""
if not self._ild_shear:
raise ValueError("I.L.D. shear equation not found. Please use solve_for_ild_shear() to generate the I.L.D. shear equations.")
x = self.variable
l = self._length
if subs is None:
subs = {}
for sym in self._ild_shear.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
return plot(self._ild_shear.subs(subs), (x, 0, l), title='I.L.D. for Shear',
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V}$', line_color='blue',show=True)
def solve_for_ild_moment(self, distance, value, *reactions):
"""
Determines the Influence Line Diagram equations for moment at a
specified point under the effect of a moving load.
Parameters
==========
distance : Integer
Distance of the point from the start of the beam
for which equations are to be determined
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Calculate the I.L.D. equations for Moment at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_moment(4, 1, R_0, R_8)
>>> b.ild_moment
Piecewise((-x/2, x < 4), (x/2 - 4, x > 4))
"""
x = self.variable
l = self.length
_, moment = self._solve_for_ild_equations()
moment_curve1 = value*(distance-x) - limit(moment, x, distance)
moment_curve2= (limit(moment, x, l)-limit(moment, x, distance))-value*(l-x)
for reaction in reactions:
moment_curve1 = moment_curve1.subs(reaction, self._ild_reactions[reaction])
moment_curve2 = moment_curve2.subs(reaction, self._ild_reactions[reaction])
moment_eq = Piecewise((moment_curve1, x < distance), (moment_curve2, x > distance))
self._ild_moment = moment_eq
def plot_ild_moment(self,subs=None):
"""
Plots the Influence Line Diagram for Moment under the effect
of a moving load. This function should be called after
calling solve_for_ild_moment().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Plot the I.L.D. for Moment at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_moment(4, 1, R_0, R_8)
>>> b.ild_moment
Piecewise((-x/2, x < 4), (x/2 - 4, x > 4))
>>> b.plot_ild_moment()
Plot object containing:
[0]: cartesian line: Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) for x over (0.0, 12.0)
"""
if not self._ild_moment:
raise ValueError("I.L.D. moment equation not found. Please use solve_for_ild_moment() to generate the I.L.D. moment equations.")
x = self.variable
if subs is None:
subs = {}
for sym in self._ild_moment.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
return plot(self._ild_moment.subs(subs), (x, 0, self._length), title='I.L.D. for Moment',
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M}$', line_color='blue', show=True)
@doctest_depends_on(modules=('numpy',))
def draw(self, pictorial=True):
"""
Returns a plot object representing the beam diagram of the beam.
.. note::
The user must be careful while entering load values.
The draw function assumes a sign convention which is used
for plotting loads.
Given a right handed coordinate system with XYZ coordinates,
the beam's length is assumed to be along the positive X axis.
The draw function recognizes positve loads(with n>-2) as loads
acting along negative Y direction and positve moments acting
along positive Z direction.
Parameters
==========
pictorial: Boolean (default=True)
Setting ``pictorial=True`` would simply create a pictorial (scaled) view
of the beam diagram not with the exact dimensions.
Although setting ``pictorial=False`` would create a beam diagram with
the exact dimensions on the plot
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> E, I = symbols('E, I')
>>> b = Beam(50, 20, 30)
>>> b.apply_load(10, 2, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(90, 5, 0, 23)
>>> b.apply_load(10, 30, 1, 50)
>>> b.apply_support(50, "pin")
>>> b.apply_support(0, "fixed")
>>> b.apply_support(20, "roller")
>>> p = b.draw()
>>> p
Plot object containing:
[0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0)
+ SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0)
- SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0)
[1]: cartesian line: 5 for x over (0.0, 50.0)
>>> p.show()
"""
if not numpy:
raise ImportError("To use this function numpy module is required")
x = self.variable
# checking whether length is an expression in terms of any Symbol.
if isinstance(self.length, Expr):
l = list(self.length.atoms(Symbol))
# assigning every Symbol a default value of 10
l = {i:10 for i in l}
length = self.length.subs(l)
else:
l = {}
length = self.length
height = length/10
rectangles = []
rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"})
annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l)
support_markers, support_rectangles = self._draw_supports(length, l)
rectangles += support_rectangles
markers += support_markers
sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length),
xlim=(-height, length + height), ylim=(-length, 1.25*length), annotations=annotations,
markers=markers, rectangles=rectangles, line_color='brown', fill=fill, axis=False, show=False)
return sing_plot
def _draw_load(self, pictorial, length, l):
loads = list(set(self.applied_loads) - set(self._support_as_loads))
height = length/10
x = self.variable
annotations = []
markers = []
load_args = []
scaled_load = 0
load_args1 = []
scaled_load1 = 0
load_eq = 0 # For positive valued higher order loads
load_eq1 = 0 # For negative valued higher order loads
fill = None
plus = 0 # For positive valued higher order loads
minus = 0 # For negative valued higher order loads
for load in loads:
# check if the position of load is in terms of the beam length.
if l:
pos = load[1].subs(l)
else:
pos = load[1]
# point loads
if load[2] == -1:
if isinstance(load[0], Symbol) or load[0].is_negative:
annotations.append({'text':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':dict(width= 1.5, headlength=5, headwidth=5, facecolor='black')})
else:
annotations.append({'text':'', 'xy':(pos, height), 'xytext':(pos, height*4), 'arrowprops':dict(width= 1.5, headlength=4, headwidth=4, facecolor='black')})
# moment loads
elif load[2] == -2:
if load[0].is_negative:
markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15})
else:
markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15})
# higher order loads
elif load[2] >= 0:
# `fill` will be assigned only when higher order loads are present
value, start, order, end = load
# Positive loads have their seperate equations
if(value>0):
plus = 1
# if pictorial is True we remake the load equation again with
# some constant magnitude values.
if pictorial:
value = 10**(1-order) if order > 0 else length/2
scaled_load += value*SingularityFunction(x, start, order)
if end:
f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order
for i in range(0, order + 1):
scaled_load -= (f2.diff(x, i).subs(x, end - start)*
SingularityFunction(x, end, i)/factorial(i))
if pictorial:
if isinstance(scaled_load, Add):
load_args = scaled_load.args
else:
# when the load equation consists of only a single term
load_args = (scaled_load,)
load_eq = [i.subs(l) for i in load_args]
else:
if isinstance(self.load, Add):
load_args = self.load.args
else:
load_args = (self.load,)
load_eq = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0]
load_eq = Add(*load_eq)
# filling higher order loads with colour
expr = height + load_eq.rewrite(Piecewise)
y1 = lambdify(x, expr, 'numpy')
# For loads with negative value
else:
minus = 1
# if pictorial is True we remake the load equation again with
# some constant magnitude values.
if pictorial:
value = 10**(1-order) if order > 0 else length/2
scaled_load1 += value*SingularityFunction(x, start, order)
if end:
f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order
for i in range(0, order + 1):
scaled_load1 -= (f2.diff(x, i).subs(x, end - start)*
SingularityFunction(x, end, i)/factorial(i))
if pictorial:
if isinstance(scaled_load1, Add):
load_args1 = scaled_load1.args
else:
# when the load equation consists of only a single term
load_args1 = (scaled_load1,)
load_eq1 = [i.subs(l) for i in load_args1]
else:
if isinstance(self.load, Add):
load_args1 = self.load.args1
else:
load_args1 = (self.load,)
load_eq1 = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0]
load_eq1 = -Add(*load_eq1)-height
# filling higher order loads with colour
expr = height + load_eq1.rewrite(Piecewise)
y1_ = lambdify(x, expr, 'numpy')
y = numpy.arange(0, float(length), 0.001)
y2 = float(height)
if(plus == 1 and minus == 1):
fill = {'x': y, 'y1': y1(y), 'y2': y1_(y), 'color':'darkkhaki'}
elif(plus == 1):
fill = {'x': y, 'y1': y1(y), 'y2': y2, 'color':'darkkhaki'}
else:
fill = {'x': y, 'y1': y1_(y), 'y2': y2, 'color':'darkkhaki'}
return annotations, markers, load_eq, load_eq1, fill
def _draw_supports(self, length, l):
height = float(length/10)
support_markers = []
support_rectangles = []
for support in self._applied_supports:
if l:
pos = support[0].subs(l)
else:
pos = support[0]
if support[1] == "pin":
support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"})
elif support[1] == "roller":
support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"})
elif support[1] == "fixed":
if pos == 0:
support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'})
else:
support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'})
return support_markers, support_rectangles
class Beam3D(Beam):
"""
This class handles loads applied in any direction of a 3D space along
with unequal values of Second moment along different axes.
.. note::
A consistent sign convention must be used while solving a beam
bending problem; the results will
automatically follow the chosen sign convention.
This class assumes that any kind of distributed load/moment is
applied through out the span of a beam.
Examples
========
There is a beam of l meters long. A constant distributed load of magnitude q
is applied along y-axis from start till the end of beam. A constant distributed
moment of magnitude m is also applied along z-axis from start till the end of beam.
Beam is fixed at both of its end. So, deflection of the beam at the both ends
is restricted.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols, simplify, collect, factor
>>> l, E, G, I, A = symbols('l, E, G, I, A')
>>> b = Beam3D(l, E, G, I, A)
>>> x, q, m = symbols('x, q, m')
>>> b.apply_load(q, 0, 0, dir="y")
>>> b.apply_moment_load(m, 0, -1, dir="z")
>>> b.shear_force()
[0, -q*x, 0]
>>> b.bending_moment()
[0, 0, -m*x + q*x**2/2]
>>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
>>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
>>> b.solve_slope_deflection()
>>> factor(b.slope())
[0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q
- 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))]
>>> dx, dy, dz = b.deflection()
>>> dy = collect(simplify(dy), x)
>>> dx == dz == 0
True
>>> dy == (x*(12*E*I*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q)
... + x*(A*G*l*(3*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) + x*(-2*A*G*l**2*q + 4*A*G*l*m - 24*E*I*q))
... + A*G*(A*G*l**2 + 12*E*I)*(-2*l**2*q + 6*l*m - 4*m*x + q*x**2)
... - 12*E*I*q*(A*G*l**2 + 12*E*I)))/(24*A*E*G*I*(A*G*l**2 + 12*E*I)))
True
References
==========
.. [1] http://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf
"""
def __init__(self, length, elastic_modulus, shear_modulus, second_moment,
area, variable=Symbol('x')):
"""Initializes the class.
Parameters
==========
length : Sympifyable
A Symbol or value representing the Beam's length.
elastic_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of Elasticity.
It is a measure of the stiffness of the Beam material.
shear_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of rigidity.
It is a measure of rigidity of the Beam material.
second_moment : Sympifyable or list
A list of two elements having SymPy expression representing the
Beam's Second moment of area. First value represent Second moment
across y-axis and second across z-axis.
Single SymPy expression can be passed if both values are same
area : Sympifyable
A SymPy expression representing the Beam's cross-sectional area
in a plane prependicular to length of the Beam.
variable : Symbol, optional
A Symbol object that will be used as the variable along the beam
while representing the load, shear, moment, slope and deflection
curve. By default, it is set to ``Symbol('x')``.
"""
super().__init__(length, elastic_modulus, second_moment, variable)
self.shear_modulus = shear_modulus
self._area = area
self._load_vector = [0, 0, 0]
self._moment_load_vector = [0, 0, 0]
self._load_Singularity = [0, 0, 0]
self._slope = [0, 0, 0]
self._deflection = [0, 0, 0]
@property
def shear_modulus(self):
"""Young's Modulus of the Beam. """
return self._shear_modulus
@shear_modulus.setter
def shear_modulus(self, e):
self._shear_modulus = sympify(e)
@property
def second_moment(self):
"""Second moment of area of the Beam. """
return self._second_moment
@second_moment.setter
def second_moment(self, i):
if isinstance(i, list):
i = [sympify(x) for x in i]
self._second_moment = i
else:
self._second_moment = sympify(i)
@property
def area(self):
"""Cross-sectional area of the Beam. """
return self._area
@area.setter
def area(self, a):
self._area = sympify(a)
@property
def load_vector(self):
"""
Returns a three element list representing the load vector.
"""
return self._load_vector
@property
def moment_load_vector(self):
"""
Returns a three element list representing moment loads on Beam.
"""
return self._moment_load_vector
@property
def boundary_conditions(self):
"""
Returns a dictionary of boundary conditions applied on the beam.
The dictionary has two keywords namely slope and deflection.
The value of each keyword is a list of tuple, where each tuple
contains location and value of a boundary condition in the format
(location, value). Further each value is a list corresponding to
slope or deflection(s) values along three axes at that location.
Examples
========
There is a beam of length 4 meters. The slope at 0 should be 4 along
the x-axis and 0 along others. At the other end of beam, deflection
along all the three axes should be zero.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(30, E, G, I, A, x)
>>> b.bc_slope = [(0, (4, 0, 0))]
>>> b.bc_deflection = [(4, [0, 0, 0])]
>>> b.boundary_conditions
{'deflection': [(4, [0, 0, 0])], 'slope': [(0, (4, 0, 0))]}
Here the deflection of the beam should be ``0`` along all the three axes at ``4``.
Similarly, the slope of the beam should be ``4`` along x-axis and ``0``
along y and z axis at ``0``.
"""
return self._boundary_conditions
def polar_moment(self):
"""
Returns the polar moment of area of the beam
about the X axis with respect to the centroid.
Examples
========
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A = symbols('l, E, G, I, A')
>>> b = Beam3D(l, E, G, I, A)
>>> b.polar_moment()
2*I
>>> I1 = [9, 15]
>>> b = Beam3D(l, E, G, I1, A)
>>> b.polar_moment()
24
"""
if not iterable(self.second_moment):
return 2*self.second_moment
return sum(self.second_moment)
def apply_load(self, value, start, order, dir="y"):
"""
This method adds up the force load to a particular beam object.
Parameters
==========
value : Sympifyable
The magnitude of an applied load.
dir : String
Axis along which load is applied.
order : Integer
The order of the applied load.
- For point loads, order=-1
- For constant distributed load, order=0
- For ramp loads, order=1
- For parabolic ramp loads, order=2
- ... so on.
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if dir == "x":
if not order == -1:
self._load_vector[0] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
elif dir == "y":
if not order == -1:
self._load_vector[1] += value
self._load_Singularity[1] += value*SingularityFunction(x, start, order)
else:
if not order == -1:
self._load_vector[2] += value
self._load_Singularity[2] += value*SingularityFunction(x, start, order)
def apply_moment_load(self, value, start, order, dir="y"):
"""
This method adds up the moment loads to a particular beam object.
Parameters
==========
value : Sympifyable
The magnitude of an applied moment.
dir : String
Axis along which moment is applied.
order : Integer
The order of the applied load.
- For point moments, order=-2
- For constant distributed moment, order=-1
- For ramp moments, order=0
- For parabolic ramp moments, order=1
- ... so on.
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if dir == "x":
if not order == -2:
self._moment_load_vector[0] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
elif dir == "y":
if not order == -2:
self._moment_load_vector[1] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
else:
if not order == -2:
self._moment_load_vector[2] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
def apply_support(self, loc, type="fixed"):
if type in ("pin", "roller"):
reaction_load = Symbol('R_'+str(loc))
self._reaction_loads[reaction_load] = reaction_load
self.bc_deflection.append((loc, [0, 0, 0]))
else:
reaction_load = Symbol('R_'+str(loc))
reaction_moment = Symbol('M_'+str(loc))
self._reaction_loads[reaction_load] = [reaction_load, reaction_moment]
self.bc_deflection.append((loc, [0, 0, 0]))
self.bc_slope.append((loc, [0, 0, 0]))
def solve_for_reaction_loads(self, *reaction):
"""
Solves for the reaction forces.
Examples
========
There is a beam of length 30 meters. It it supported by rollers at
of its end. A constant distributed load of magnitude 8 N is applied
from start till its end along y-axis. Another linear load having
slope equal to 9 is applied along z-axis.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(30, E, G, I, A, x)
>>> b.apply_load(8, start=0, order=0, dir="y")
>>> b.apply_load(9*x, start=0, order=0, dir="z")
>>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="y")
>>> b.apply_load(R2, start=30, order=-1, dir="y")
>>> b.apply_load(R3, start=0, order=-1, dir="z")
>>> b.apply_load(R4, start=30, order=-1, dir="z")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.reaction_loads
{R1: -120, R2: -120, R3: -1350, R4: -2700}
"""
x = self.variable
l = self.length
q = self._load_Singularity
shear_curves = [integrate(load, x) for load in q]
moment_curves = [integrate(shear, x) for shear in shear_curves]
for i in range(3):
react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))]
if len(react) == 0:
continue
shear_curve = limit(shear_curves[i], x, l)
moment_curve = limit(moment_curves[i], x, l)
sol = list((linsolve([shear_curve, moment_curve], react).args)[0])
sol_dict = dict(zip(react, sol))
reaction_loads = self._reaction_loads
# Check if any of the evaluated rection exists in another direction
# and if it exists then it should have same value.
for key in sol_dict:
if key in reaction_loads and sol_dict[key] != reaction_loads[key]:
raise ValueError("Ambiguous solution for %s in different directions." % key)
self._reaction_loads.update(sol_dict)
def shear_force(self):
"""
Returns a list of three expressions which represents the shear force
curve of the Beam object along all three axes.
"""
x = self.variable
q = self._load_vector
return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)]
def axial_force(self):
"""
Returns expression of Axial shear force present inside the Beam object.
"""
return self.shear_force()[0]
def shear_stress(self):
"""
Returns a list of three expressions which represents the shear stress
curve of the Beam object along all three axes.
"""
return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area]
def axial_stress(self):
"""
Returns expression of Axial stress present inside the Beam object.
"""
return self.axial_force()/self._area
def bending_moment(self):
"""
Returns a list of three expressions which represents the bending moment
curve of the Beam object along all three axes.
"""
x = self.variable
m = self._moment_load_vector
shear = self.shear_force()
return [integrate(-m[0], x), integrate(-m[1] + shear[2], x),
integrate(-m[2] - shear[1], x) ]
def torsional_moment(self):
"""
Returns expression of Torsional moment present inside the Beam object.
"""
return self.bending_moment()[0]
def solve_slope_deflection(self):
x = self.variable
l = self.length
E = self.elastic_modulus
G = self.shear_modulus
I = self.second_moment
if isinstance(I, list):
I_y, I_z = I[0], I[1]
else:
I_y = I_z = I
A = self._area
load = self._load_vector
moment = self._moment_load_vector
defl = Function('defl')
theta = Function('theta')
# Finding deflection along x-axis(and corresponding slope value by differentiating it)
# Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0
eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0]
def_x = dsolve(Eq(eq, 0), defl(x)).args[1]
# Solving constants originated from dsolve
C1 = Symbol('C1')
C2 = Symbol('C2')
constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0])
def_x = def_x.subs({C1:constants[0], C2:constants[1]})
slope_x = def_x.diff(x)
self._deflection[0] = def_x
self._slope[0] = slope_x
# Finding deflection along y-axis and slope across z-axis. System of equation involved:
# 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0
# 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0
C_i = Symbol('C_i')
# Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1)
eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2]
slope_z = dsolve(Eq(eq1, 0)).args[1]
# Solve for constants originated from using dsolve on eq1
constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0])
slope_z = slope_z.subs({C1:constants[0], C2:constants[1]})
# Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis
eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z
def_y = dsolve(Eq(eq2, 0), defl(x)).args[1]
# Solve for constants originated from using dsolve on eq2
constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0])
self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]})
self._slope[2] = slope_z.subs(C_i, constants[1])
# Finding deflection along z-axis and slope across y-axis. System of equation involved:
# 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0
# 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0
# Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1)
eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1]
slope_y = dsolve(Eq(eq1, 0)).args[1]
# Solve for constants originated from using dsolve on eq1
constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0])
slope_y = slope_y.subs({C1:constants[0], C2:constants[1]})
# Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis
eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y
def_z = dsolve(Eq(eq2,0)).args[1]
# Solve for constants originated from using dsolve on eq2
constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0])
self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]})
self._slope[1] = slope_y.subs(C_i, constants[1])
def slope(self):
"""
Returns a three element list representing slope of deflection curve
along all the three axes.
"""
return self._slope
def deflection(self):
"""
Returns a three element list representing deflection curve along all
the three axes.
"""
return self._deflection
def _plot_shear_force(self, dir, subs=None):
shear_force = self.shear_force()
if dir == 'x':
dir_num = 0
color = 'r'
elif dir == 'y':
dir_num = 1
color = 'g'
elif dir == 'z':
dir_num = 2
color = 'b'
if subs is None:
subs = {}
for sym in shear_force[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V(%c)}$'%dir, line_color=color)
def plot_shear_force(self, dir="all", subs=None):
"""
Returns a plot for Shear force along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which shear force plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_shear_force()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -15*x for x over (0.0, 20.0)
"""
dir = dir.lower()
# For shear force along x direction
if dir == "x":
Px = self._plot_shear_force('x', subs)
return Px.show()
# For shear force along y direction
elif dir == "y":
Py = self._plot_shear_force('y', subs)
return Py.show()
# For shear force along z direction
elif dir == "z":
Pz = self._plot_shear_force('z', subs)
return Pz.show()
# For shear force along all direction
else:
Px = self._plot_shear_force('x', subs)
Py = self._plot_shear_force('y', subs)
Pz = self._plot_shear_force('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_bending_moment(self, dir, subs=None):
bending_moment = self.bending_moment()
if dir == 'x':
dir_num = 0
color = 'g'
elif dir == 'y':
dir_num = 1
color = 'c'
elif dir == 'z':
dir_num = 2
color = 'm'
if subs is None:
subs = {}
for sym in bending_moment[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(bending_moment[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Bending Moment along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M(%c)}$'%dir, line_color=color)
def plot_bending_moment(self, dir="all", subs=None):
"""
Returns a plot for bending moment along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which bending moment plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_bending_moment()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: 2*x**3 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For bending moment along x direction
if dir == "x":
Px = self._plot_bending_moment('x', subs)
return Px.show()
# For bending moment along y direction
elif dir == "y":
Py = self._plot_bending_moment('y', subs)
return Py.show()
# For bending moment along z direction
elif dir == "z":
Pz = self._plot_bending_moment('z', subs)
return Pz.show()
# For bending moment along all direction
else:
Px = self._plot_bending_moment('x', subs)
Py = self._plot_bending_moment('y', subs)
Pz = self._plot_bending_moment('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_slope(self, dir, subs=None):
slope = self.slope()
if dir == 'x':
dir_num = 0
color = 'b'
elif dir == 'y':
dir_num = 1
color = 'm'
elif dir == 'z':
dir_num = 2
color = 'g'
if subs is None:
subs = {}
for sym in slope[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(slope[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Slope along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\theta(%c)}$'%dir, line_color=color)
def plot_slope(self, dir="all", subs=None):
"""
Returns a plot for Slope along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which Slope plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as keys and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_slope()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: x**4/8000 - 19*x**2/172 + 52*x/43 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For Slope along x direction
if dir == "x":
Px = self._plot_slope('x', subs)
return Px.show()
# For Slope along y direction
elif dir == "y":
Py = self._plot_slope('y', subs)
return Py.show()
# For Slope along z direction
elif dir == "z":
Pz = self._plot_slope('z', subs)
return Pz.show()
# For Slope along all direction
else:
Px = self._plot_slope('x', subs)
Py = self._plot_slope('y', subs)
Pz = self._plot_slope('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_deflection(self, dir, subs=None):
deflection = self.deflection()
if dir == 'x':
dir_num = 0
color = 'm'
elif dir == 'y':
dir_num = 1
color = 'r'
elif dir == 'z':
dir_num = 2
color = 'c'
if subs is None:
subs = {}
for sym in deflection[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(deflection[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Deflection along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\delta(%c)}$'%dir, line_color=color)
def plot_deflection(self, dir="all", subs=None):
"""
Returns a plot for Deflection along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which deflection plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as keys and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_deflection()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: x**4/6400 - x**3/160 + 27*x**2/560 + 2*x/7 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For deflection along x direction
if dir == "x":
Px = self._plot_deflection('x', subs)
return Px.show()
# For deflection along y direction
elif dir == "y":
Py = self._plot_deflection('y', subs)
return Py.show()
# For deflection along z direction
elif dir == "z":
Pz = self._plot_deflection('z', subs)
return Pz.show()
# For deflection along all direction
else:
Px = self._plot_deflection('x', subs)
Py = self._plot_deflection('y', subs)
Pz = self._plot_deflection('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def plot_loading_results(self, dir='x', subs=None):
"""
Returns a subplot of Shear Force, Bending Moment,
Slope and Deflection of the Beam object along the direction specified.
Parameters
==========
dir : string (default : "x")
Direction along which plots are required.
If no direction is specified, plots along x-axis are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> subs = {E:40, G:21, I:100, A:25}
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_loading_results('y',subs)
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
Plot[3]:Plot object containing:
[0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
"""
dir = dir.lower()
if subs is None:
subs = {}
ax1 = self._plot_shear_force(dir, subs)
ax2 = self._plot_bending_moment(dir, subs)
ax3 = self._plot_slope(dir, subs)
ax4 = self._plot_deflection(dir, subs)
return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
def _plot_shear_stress(self, dir, subs=None):
shear_stress = self.shear_stress()
if dir == 'x':
dir_num = 0
color = 'r'
elif dir == 'y':
dir_num = 1
color = 'g'
elif dir == 'z':
dir_num = 2
color = 'b'
if subs is None:
subs = {}
for sym in shear_stress[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_stress[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear stress along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\tau(%c)$'%dir, line_color=color)
def plot_shear_stress(self, dir="all", subs=None):
"""
Returns a plot for Shear Stress along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which shear stress plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters and area of cross section 2 square
meters. It it supported by rollers at of its end. A linear load having
slope equal to 12 is applied along y-axis. A constant distributed load
of magnitude 15 N is applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, 2, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_shear_stress()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -3*x**2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -15*x/2 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For shear stress along x direction
if dir == "x":
Px = self._plot_shear_stress('x', subs)
return Px.show()
# For shear stress along y direction
elif dir == "y":
Py = self._plot_shear_stress('y', subs)
return Py.show()
# For shear stress along z direction
elif dir == "z":
Pz = self._plot_shear_stress('z', subs)
return Pz.show()
# For shear stress along all direction
else:
Px = self._plot_shear_stress('x', subs)
Py = self._plot_shear_stress('y', subs)
Pz = self._plot_shear_stress('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _max_shear_force(self, dir):
"""
Helper function for max_shear_force().
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.shear_force()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
load_curve = Piecewise((float("nan"), self.variable<=0),
(self._load_vector[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(load_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self.length)
shear_curve = self.shear_force()[dir_num]
shear_values = [shear_curve.subs(self.variable, x) for x in points]
shear_values = list(map(abs, shear_values))
max_shear = max(shear_values)
return (points[shear_values.index(max_shear)], max_shear)
def max_shear_force(self):
"""
Returns point of max shear force and its corresponding shear value
along all directions in a Beam object as a list.
solve_for_reaction_loads() must be called before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.max_shear_force()
[(0, 0), (20, 2400), (20, 300)]
"""
max_shear = []
max_shear.append(self._max_shear_force('x'))
max_shear.append(self._max_shear_force('y'))
max_shear.append(self._max_shear_force('z'))
return max_shear
def _max_bending_moment(self, dir):
"""
Helper function for max_bending_moment().
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.bending_moment()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
shear_curve = Piecewise((float("nan"), self.variable<=0),
(self.shear_force()[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(shear_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self.length)
bending_moment_curve = self.bending_moment()[dir_num]
bending_moments = [bending_moment_curve.subs(self.variable, x) for x in points]
bending_moments = list(map(abs, bending_moments))
max_bending_moment = max(bending_moments)
return (points[bending_moments.index(max_bending_moment)], max_bending_moment)
def max_bending_moment(self):
"""
Returns point of max bending moment and its corresponding bending moment value
along all directions in a Beam object as a list.
solve_for_reaction_loads() must be called before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.max_bending_moment()
[(0, 0), (20, 3000), (20, 16000)]
"""
max_bmoment = []
max_bmoment.append(self._max_bending_moment('x'))
max_bmoment.append(self._max_bending_moment('y'))
max_bmoment.append(self._max_bending_moment('z'))
return max_bmoment
max_bmoment = max_bending_moment
def _max_deflection(self, dir):
"""
Helper function for max_Deflection()
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.deflection()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
slope_curve = Piecewise((float("nan"), self.variable<=0),
(self.slope()[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(slope_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self._length)
deflection_curve = self.deflection()[dir_num]
deflections = [deflection_curve.subs(self.variable, x) for x in points]
deflections = list(map(abs, deflections))
max_def = max(deflections)
return (points[deflections.index(max_def)], max_def)
def max_deflection(self):
"""
Returns point of max deflection and its corresponding deflection value
along all directions in a Beam object as a list.
solve_for_reaction_loads() and solve_slope_deflection() must be called
before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.max_deflection()
[(0, 0), (10, 495/14), (-10 + 10*sqrt(10793)/43, (10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560)]
"""
max_def = []
max_def.append(self._max_deflection('x'))
max_def.append(self._max_deflection('y'))
max_def.append(self._max_deflection('z'))
return max_def
|
d2f2033a7f8c5e1cea5823f3546ed6d4ad62786cb0823d17c799118622ee29d5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The module implements routines to model the polarization of optical fields
and can be used to calculate the effects of polarization optical elements on
the fields.
- Jones vectors.
- Stokes vectors.
- Jones matrices.
- Mueller matrices.
Examples
========
We calculate a generic Jones vector:
>>> from sympy import symbols, pprint, zeros, simplify
>>> from sympy.physics.optics.polarization import (jones_vector, stokes_vector,
... half_wave_retarder, polarizing_beam_splitter, jones_2_stokes)
>>> psi, chi, p, I0 = symbols("psi, chi, p, I0", real=True)
>>> x0 = jones_vector(psi, chi)
>>> pprint(x0, use_unicode=True)
⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
⎢ ⎥
⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
And the more general Stokes vector:
>>> s0 = stokes_vector(psi, chi, p, I0)
>>> pprint(s0, use_unicode=True)
⎡ I₀ ⎤
⎢ ⎥
⎢I₀⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
⎢ ⎥
⎢I₀⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
⎢ ⎥
⎣ I₀⋅p⋅sin(2⋅χ) ⎦
We calculate how the Jones vector is modified by a half-wave plate:
>>> alpha = symbols("alpha", real=True)
>>> HWP = half_wave_retarder(alpha)
>>> x1 = simplify(HWP*x0)
We calculate the very common operation of passing a beam through a half-wave
plate and then through a polarizing beam-splitter. We do this by putting this
Jones vector as the first entry of a two-Jones-vector state that is transformed
by a 4x4 Jones matrix modelling the polarizing beam-splitter to get the
transmitted and reflected Jones vectors:
>>> PBS = polarizing_beam_splitter()
>>> X1 = zeros(4, 1)
>>> X1[:2, :] = x1
>>> X2 = PBS*X1
>>> transmitted_port = X2[:2, :]
>>> reflected_port = X2[2:, :]
This allows us to calculate how the power in both ports depends on the initial
polarization:
>>> transmitted_power = jones_2_stokes(transmitted_port)[0]
>>> reflected_power = jones_2_stokes(reflected_port)[0]
>>> print(transmitted_power)
cos(-2*alpha + chi + psi)**2/2 + cos(2*alpha + chi - psi)**2/2
>>> print(reflected_power)
sin(-2*alpha + chi + psi)**2/2 + sin(2*alpha + chi - psi)**2/2
Please see the description of the individual functions for further
details and examples.
References
==========
.. [1] https://en.wikipedia.org/wiki/Jones_calculus
.. [2] https://en.wikipedia.org/wiki/Mueller_calculus
.. [3] https://en.wikipedia.org/wiki/Stokes_parameters
"""
from sympy.core.numbers import (I, pi)
from sympy.functions.elementary.complexes import (Abs, im, re)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import Matrix
from sympy.simplify.simplify import simplify
from sympy.physics.quantum import TensorProduct
def jones_vector(psi, chi):
"""A Jones vector corresponding to a polarization ellipse with `psi` tilt,
and `chi` circularity.
Parameters
==========
``psi`` : numeric type or SymPy Symbol
The tilt of the polarization relative to the `x` axis.
``chi`` : numeric type or SymPy Symbol
The angle adjacent to the mayor axis of the polarization ellipse.
Returns
=======
Matrix :
A Jones vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, symbols, pi
>>> from sympy.physics.optics.polarization import jones_vector
>>> psi, chi = symbols("psi, chi", real=True)
A general Jones vector.
>>> pprint(jones_vector(psi, chi), use_unicode=True)
⎡-ⅈ⋅sin(χ)⋅sin(ψ) + cos(χ)⋅cos(ψ)⎤
⎢ ⎥
⎣ⅈ⋅sin(χ)⋅cos(ψ) + sin(ψ)⋅cos(χ) ⎦
Horizontal polarization.
>>> pprint(jones_vector(0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎣0⎦
Vertical polarization.
>>> pprint(jones_vector(pi/2, 0), use_unicode=True)
⎡0⎤
⎢ ⎥
⎣1⎦
Diagonal polarization.
>>> pprint(jones_vector(pi/4, 0), use_unicode=True)
⎡√2⎤
⎢──⎥
⎢2 ⎥
⎢ ⎥
⎢√2⎥
⎢──⎥
⎣2 ⎦
Anti-diagonal polarization.
>>> pprint(jones_vector(-pi/4, 0), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢-√2 ⎥
⎢────⎥
⎣ 2 ⎦
Right-hand circular polarization.
>>> pprint(jones_vector(0, pi/4), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢√2⋅ⅈ⎥
⎢────⎥
⎣ 2 ⎦
Left-hand circular polarization.
>>> pprint(jones_vector(0, -pi/4), use_unicode=True)
⎡ √2 ⎤
⎢ ── ⎥
⎢ 2 ⎥
⎢ ⎥
⎢-√2⋅ⅈ ⎥
⎢──────⎥
⎣ 2 ⎦
"""
return Matrix([-I*sin(chi)*sin(psi) + cos(chi)*cos(psi),
I*sin(chi)*cos(psi) + sin(psi)*cos(chi)])
def stokes_vector(psi, chi, p=1, I=1):
"""A Stokes vector corresponding to a polarization ellipse with ``psi``
tilt, and ``chi`` circularity.
Parameters
==========
``psi`` : numeric type or SymPy Symbol
The tilt of the polarization relative to the ``x`` axis.
``chi`` : numeric type or SymPy Symbol
The angle adjacent to the mayor axis of the polarization ellipse.
``p`` : numeric type or SymPy Symbol
The degree of polarization.
``I`` : numeric type or SymPy Symbol
The intensity of the field.
Returns
=======
Matrix :
A Stokes vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, symbols, pi
>>> from sympy.physics.optics.polarization import stokes_vector
>>> psi, chi, p, I = symbols("psi, chi, p, I", real=True)
>>> pprint(stokes_vector(psi, chi, p, I), use_unicode=True)
⎡ I ⎤
⎢ ⎥
⎢I⋅p⋅cos(2⋅χ)⋅cos(2⋅ψ)⎥
⎢ ⎥
⎢I⋅p⋅sin(2⋅ψ)⋅cos(2⋅χ)⎥
⎢ ⎥
⎣ I⋅p⋅sin(2⋅χ) ⎦
Horizontal polarization
>>> pprint(stokes_vector(0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢1⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣0⎦
Vertical polarization
>>> pprint(stokes_vector(pi/2, 0), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢-1⎥
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎣0 ⎦
Diagonal polarization
>>> pprint(stokes_vector(pi/4, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢1⎥
⎢ ⎥
⎣0⎦
Anti-diagonal polarization
>>> pprint(stokes_vector(-pi/4, 0), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎢-1⎥
⎢ ⎥
⎣0 ⎦
Right-hand circular polarization
>>> pprint(stokes_vector(0, pi/4), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣1⎦
Left-hand circular polarization
>>> pprint(stokes_vector(0, -pi/4), use_unicode=True)
⎡1 ⎤
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎢0 ⎥
⎢ ⎥
⎣-1⎦
Unpolarized light
>>> pprint(stokes_vector(0, 0, 0), use_unicode=True)
⎡1⎤
⎢ ⎥
⎢0⎥
⎢ ⎥
⎢0⎥
⎢ ⎥
⎣0⎦
"""
S0 = I
S1 = I*p*cos(2*psi)*cos(2*chi)
S2 = I*p*sin(2*psi)*cos(2*chi)
S3 = I*p*sin(2*chi)
return Matrix([S0, S1, S2, S3])
def jones_2_stokes(e):
"""Return the Stokes vector for a Jones vector `e`.
Parameters
==========
``e`` : SymPy Matrix
A Jones vector.
Returns
=======
SymPy Matrix
A Jones vector.
Examples
========
The axes on the Poincaré sphere.
>>> from sympy import pprint, pi
>>> from sympy.physics.optics.polarization import jones_vector
>>> from sympy.physics.optics.polarization import jones_2_stokes
>>> H = jones_vector(0, 0)
>>> V = jones_vector(pi/2, 0)
>>> D = jones_vector(pi/4, 0)
>>> A = jones_vector(-pi/4, 0)
>>> R = jones_vector(0, pi/4)
>>> L = jones_vector(0, -pi/4)
>>> pprint([jones_2_stokes(e) for e in [H, V, D, A, R, L]],
... use_unicode=True)
⎡⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤ ⎡1⎤ ⎡1 ⎤⎤
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎢⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥ ⎢0⎥ ⎢0 ⎥⎥
⎢⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥, ⎢ ⎥⎥
⎢⎢0⎥ ⎢0 ⎥ ⎢1⎥ ⎢-1⎥ ⎢0⎥ ⎢0 ⎥⎥
⎢⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥⎥
⎣⎣0⎦ ⎣0 ⎦ ⎣0⎦ ⎣0 ⎦ ⎣1⎦ ⎣-1⎦⎦
"""
ex, ey = e
return Matrix([Abs(ex)**2 + Abs(ey)**2,
Abs(ex)**2 - Abs(ey)**2,
2*re(ex*ey.conjugate()),
-2*im(ex*ey.conjugate())])
def linear_polarizer(theta=0):
"""A linear polarizer Jones matrix with transmission axis at
an angle ``theta``.
Parameters
==========
``theta`` : numeric type or SymPy Symbol
The angle of the transmission axis relative to the horizontal plane.
Returns
=======
SymPy Matrix
A Jones matrix representing the polarizer.
Examples
========
A generic polarizer.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import linear_polarizer
>>> theta = symbols("theta", real=True)
>>> J = linear_polarizer(theta)
>>> pprint(J, use_unicode=True)
⎡ 2 ⎤
⎢ cos (θ) sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ 2 ⎥
⎣sin(θ)⋅cos(θ) sin (θ) ⎦
"""
M = Matrix([[cos(theta)**2, sin(theta)*cos(theta)],
[sin(theta)*cos(theta), sin(theta)**2]])
return M
def phase_retarder(theta=0, delta=0):
"""A phase retarder Jones matrix with retardance `delta` at angle `theta`.
Parameters
==========
``theta`` : numeric type or SymPy Symbol
The angle of the fast axis relative to the horizontal plane.
``delta`` : numeric type or SymPy Symbol
The phase difference between the fast and slow axes of the
transmitted light.
Returns
=======
SymPy Matrix :
A Jones matrix representing the retarder.
Examples
========
A generic retarder.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import phase_retarder
>>> theta, delta = symbols("theta, delta", real=True)
>>> R = phase_retarder(theta, delta)
>>> pprint(R, use_unicode=True)
⎡ -ⅈ⋅δ -ⅈ⋅δ ⎤
⎢ ───── ───── ⎥
⎢⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎛ ⅈ⋅δ⎞ 2 ⎥
⎢⎝ℯ ⋅sin (θ) + cos (θ)⎠⋅ℯ ⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ -ⅈ⋅δ -ⅈ⋅δ ⎥
⎢ ───── ─────⎥
⎢⎛ ⅈ⋅δ⎞ 2 ⎛ ⅈ⋅δ 2 2 ⎞ 2 ⎥
⎣⎝1 - ℯ ⎠⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝ℯ ⋅cos (θ) + sin (θ)⎠⋅ℯ ⎦
"""
R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
(1-exp(I*delta))*cos(theta)*sin(theta)],
[(1-exp(I*delta))*cos(theta)*sin(theta),
sin(theta)**2 + exp(I*delta)*cos(theta)**2]])
return R*exp(-I*delta/2)
def half_wave_retarder(theta):
"""A half-wave retarder Jones matrix at angle `theta`.
Parameters
==========
``theta`` : numeric type or SymPy Symbol
The angle of the fast axis relative to the horizontal plane.
Returns
=======
SymPy Matrix
A Jones matrix representing the retarder.
Examples
========
A generic half-wave plate.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import half_wave_retarder
>>> theta= symbols("theta", real=True)
>>> HWP = half_wave_retarder(theta)
>>> pprint(HWP, use_unicode=True)
⎡ ⎛ 2 2 ⎞ ⎤
⎢-ⅈ⋅⎝- sin (θ) + cos (θ)⎠ -2⋅ⅈ⋅sin(θ)⋅cos(θ) ⎥
⎢ ⎥
⎢ ⎛ 2 2 ⎞⎥
⎣ -2⋅ⅈ⋅sin(θ)⋅cos(θ) -ⅈ⋅⎝sin (θ) - cos (θ)⎠⎦
"""
return phase_retarder(theta, pi)
def quarter_wave_retarder(theta):
"""A quarter-wave retarder Jones matrix at angle `theta`.
Parameters
==========
``theta`` : numeric type or SymPy Symbol
The angle of the fast axis relative to the horizontal plane.
Returns
=======
SymPy Matrix
A Jones matrix representing the retarder.
Examples
========
A generic quarter-wave plate.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import quarter_wave_retarder
>>> theta= symbols("theta", real=True)
>>> QWP = quarter_wave_retarder(theta)
>>> pprint(QWP, use_unicode=True)
⎡ -ⅈ⋅π -ⅈ⋅π ⎤
⎢ ───── ───── ⎥
⎢⎛ 2 2 ⎞ 4 4 ⎥
⎢⎝ⅈ⋅sin (θ) + cos (θ)⎠⋅ℯ (1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ)⎥
⎢ ⎥
⎢ -ⅈ⋅π -ⅈ⋅π ⎥
⎢ ───── ─────⎥
⎢ 4 ⎛ 2 2 ⎞ 4 ⎥
⎣(1 - ⅈ)⋅ℯ ⋅sin(θ)⋅cos(θ) ⎝sin (θ) + ⅈ⋅cos (θ)⎠⋅ℯ ⎦
"""
return phase_retarder(theta, pi/2)
def transmissive_filter(T):
"""An attenuator Jones matrix with transmittance `T`.
Parameters
==========
``T`` : numeric type or SymPy Symbol
The transmittance of the attenuator.
Returns
=======
SymPy Matrix
A Jones matrix representing the filter.
Examples
========
A generic filter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import transmissive_filter
>>> T = symbols("T", real=True)
>>> NDF = transmissive_filter(T)
>>> pprint(NDF, use_unicode=True)
⎡√T 0 ⎤
⎢ ⎥
⎣0 √T⎦
"""
return Matrix([[sqrt(T), 0], [0, sqrt(T)]])
def reflective_filter(R):
"""A reflective filter Jones matrix with reflectance `R`.
Parameters
==========
``R`` : numeric type or SymPy Symbol
The reflectance of the filter.
Returns
=======
SymPy Matrix
A Jones matrix representing the filter.
Examples
========
A generic filter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import reflective_filter
>>> R = symbols("R", real=True)
>>> pprint(reflective_filter(R), use_unicode=True)
⎡√R 0 ⎤
⎢ ⎥
⎣0 -√R⎦
"""
return Matrix([[sqrt(R), 0], [0, -sqrt(R)]])
def mueller_matrix(J):
"""The Mueller matrix corresponding to Jones matrix `J`.
Parameters
==========
``J`` : SymPy Matrix
A Jones matrix.
Returns
=======
SymPy Matrix
The corresponding Mueller matrix.
Examples
========
Generic optical components.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import (mueller_matrix,
... linear_polarizer, half_wave_retarder, quarter_wave_retarder)
>>> theta = symbols("theta", real=True)
A linear_polarizer
>>> pprint(mueller_matrix(linear_polarizer(theta)), use_unicode=True)
⎡ cos(2⋅θ) sin(2⋅θ) ⎤
⎢ 1/2 ──────── ──────── 0⎥
⎢ 2 2 ⎥
⎢ ⎥
⎢cos(2⋅θ) cos(4⋅θ) 1 sin(4⋅θ) ⎥
⎢──────── ──────── + ─ ──────── 0⎥
⎢ 2 4 4 4 ⎥
⎢ ⎥
⎢sin(2⋅θ) sin(4⋅θ) 1 cos(4⋅θ) ⎥
⎢──────── ──────── ─ - ──────── 0⎥
⎢ 2 4 4 4 ⎥
⎢ ⎥
⎣ 0 0 0 0⎦
A half-wave plate
>>> pprint(mueller_matrix(half_wave_retarder(theta)), use_unicode=True)
⎡1 0 0 0 ⎤
⎢ ⎥
⎢ 4 2 ⎥
⎢0 8⋅sin (θ) - 8⋅sin (θ) + 1 sin(4⋅θ) 0 ⎥
⎢ ⎥
⎢ 4 2 ⎥
⎢0 sin(4⋅θ) - 8⋅sin (θ) + 8⋅sin (θ) - 1 0 ⎥
⎢ ⎥
⎣0 0 0 -1⎦
A quarter-wave plate
>>> pprint(mueller_matrix(quarter_wave_retarder(theta)), use_unicode=True)
⎡1 0 0 0 ⎤
⎢ ⎥
⎢ cos(4⋅θ) 1 sin(4⋅θ) ⎥
⎢0 ──────── + ─ ──────── -sin(2⋅θ)⎥
⎢ 2 2 2 ⎥
⎢ ⎥
⎢ sin(4⋅θ) 1 cos(4⋅θ) ⎥
⎢0 ──────── ─ - ──────── cos(2⋅θ) ⎥
⎢ 2 2 2 ⎥
⎢ ⎥
⎣0 sin(2⋅θ) -cos(2⋅θ) 0 ⎦
"""
A = Matrix([[1, 0, 0, 1],
[1, 0, 0, -1],
[0, 1, 1, 0],
[0, -I, I, 0]])
return simplify(A*TensorProduct(J, J.conjugate())*A.inv())
def polarizing_beam_splitter(Tp=1, Rs=1, Ts=0, Rp=0, phia=0, phib=0):
r"""A polarizing beam splitter Jones matrix at angle `theta`.
Parameters
==========
``J`` : SymPy Matrix
A Jones matrix.
``Tp`` : numeric type or SymPy Symbol
The transmissivity of the P-polarized component.
``Rs`` : numeric type or SymPy Symbol
The reflectivity of the S-polarized component.
``Ts`` : numeric type or SymPy Symbol
The transmissivity of the S-polarized component.
``Rp`` : numeric type or SymPy Symbol
The reflectivity of the P-polarized component.
``phia`` : numeric type or SymPy Symbol
The phase difference between transmitted and reflected component for
output mode a.
``phib`` : numeric type or SymPy Symbol
The phase difference between transmitted and reflected component for
output mode b.
Returns
=======
SymPy Matrix
A 4x4 matrix representing the PBS. This matrix acts on a 4x1 vector
whose first two entries are the Jones vector on one of the PBS ports,
and the last two entries the Jones vector on the other port.
Examples
========
Generic polarizing beam-splitter.
>>> from sympy import pprint, symbols
>>> from sympy.physics.optics.polarization import polarizing_beam_splitter
>>> Ts, Rs, Tp, Rp = symbols(r"Ts, Rs, Tp, Rp", positive=True)
>>> phia, phib = symbols("phi_a, phi_b", real=True)
>>> PBS = polarizing_beam_splitter(Tp, Rs, Ts, Rp, phia, phib)
>>> pprint(PBS, use_unicode=False)
[ ____ ____ ]
[ \/ Tp 0 I*\/ Rp 0 ]
[ ]
[ ____ ____ I*phi_a]
[ 0 \/ Ts 0 -I*\/ Rs *e ]
[ ]
[ ____ ____ ]
[I*\/ Rp 0 \/ Tp 0 ]
[ ]
[ ____ I*phi_b ____ ]
[ 0 -I*\/ Rs *e 0 \/ Ts ]
"""
PBS = Matrix([[sqrt(Tp), 0, I*sqrt(Rp), 0],
[0, sqrt(Ts), 0, -I*sqrt(Rs)*exp(I*phia)],
[I*sqrt(Rp), 0, sqrt(Tp), 0],
[0, -I*sqrt(Rs)*exp(I*phib), 0, sqrt(Ts)]])
return PBS
|
9debed11d60787a445da30a03cbaff7fa3d488fea54ff01735632debf393fb9a | """
**Contains**
* Medium
"""
from sympy.physics.units import second, meter, kilogram, ampere
__all__ = ['Medium']
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.units import speed_of_light, u0, e0
c = speed_of_light.convert_to(meter/second)
_e0mksa = e0.convert_to(ampere**2*second**4/(kilogram*meter**3))
_u0mksa = u0.convert_to(meter*kilogram/(ampere**2*second**2))
class Medium(Symbol):
"""
This class represents an optical medium. The prime reason to implement this is
to facilitate refraction, Fermat's principle, etc.
Explanation
===========
An optical medium is a material through which electromagnetic waves propagate.
The permittivity and permeability of the medium define how electromagnetic
waves propagate in it.
Parameters
==========
name: string
The display name of the Medium.
permittivity: Sympifyable
Electric permittivity of the space.
permeability: Sympifyable
Magnetic permeability of the space.
n: Sympifyable
Index of refraction of the medium.
Examples
========
>>> from sympy.abc import epsilon, mu
>>> from sympy.physics.optics import Medium
>>> m1 = Medium('m1')
>>> m2 = Medium('m2', epsilon, mu)
>>> m1.intrinsic_impedance
149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
>>> m2.refractive_index
299792458*meter*sqrt(epsilon*mu)/second
References
==========
.. [1] https://en.wikipedia.org/wiki/Optical_medium
"""
def __new__(cls, name, permittivity=None, permeability=None, n=None):
obj = super().__new__(cls, name)
obj._permittivity = sympify(permittivity)
obj._permeability = sympify(permeability)
obj._n = sympify(n)
if n is not None:
if permittivity is not None and permeability is None:
obj._permeability = n**2/(c**2*obj._permittivity)
if permeability is not None and permittivity is None:
obj._permittivity = n**2/(c**2*obj._permeability)
if permittivity is not None and permittivity is not None:
if abs(n - c*sqrt(obj._permittivity*obj._permeability)) > 1e-6:
raise ValueError("Values are not consistent.")
elif permittivity is not None and permeability is not None:
obj._n = c*sqrt(permittivity*permeability)
elif permittivity is None and permeability is None:
obj._permittivity = _e0mksa
obj._permeability = _u0mksa
return obj
@property
def intrinsic_impedance(self):
"""
Returns intrinsic impedance of the medium.
Explanation
===========
The intrinsic impedance of a medium is the ratio of the
transverse components of the electric and magnetic fields
of the electromagnetic wave travelling in the medium.
In a region with no electrical conductivity it simplifies
to the square root of ratio of magnetic permeability to
electric permittivity.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.intrinsic_impedance
149896229*pi*kilogram*meter**2/(1250000*ampere**2*second**3)
"""
return sqrt(self._permeability/self._permittivity)
@property
def speed(self):
"""
Returns speed of the electromagnetic wave travelling in the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.speed
299792458*meter/second
>>> m2 = Medium('m2', n=1)
>>> m.speed == m2.speed
True
"""
if self._permittivity is not None and self._permeability is not None:
return 1/sqrt(self._permittivity*self._permeability)
else:
return c/self._n
@property
def refractive_index(self):
"""
Returns refractive index of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.refractive_index
1
"""
return (c/self.speed)
@property
def permittivity(self):
"""
Returns electric permittivity of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permittivity
625000*ampere**2*second**4/(22468879468420441*pi*kilogram*meter**3)
"""
return self._permittivity
@property
def permeability(self):
"""
Returns magnetic permeability of the medium.
Examples
========
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permeability
pi*kilogram*meter/(2500000*ampere**2*second**2)
"""
return self._permeability
def __str__(self):
from sympy.printing import sstr
return type(self).__name__ + ': ' + sstr([self._permittivity,
self._permeability, self._n])
def __lt__(self, other):
"""
Compares based on refractive index of the medium.
"""
return self.refractive_index < other.refractive_index
def __gt__(self, other):
return not self < other
def __eq__(self, other):
return self.refractive_index == other.refractive_index
def __ne__(self, other):
return not self == other
|
aa84a5cee8cc4c70f1219bc140f27f705d8fc41f9ac325d5a829ddae251df8f4 | """
**Contains**
* refraction_angle
* fresnel_coefficients
* deviation
* brewster_angle
* critical_angle
* lens_makers_formula
* mirror_formula
* lens_formula
* hyperfocal_distance
* transverse_magnification
"""
__all__ = ['refraction_angle',
'deviation',
'fresnel_coefficients',
'brewster_angle',
'critical_angle',
'lens_makers_formula',
'mirror_formula',
'lens_formula',
'hyperfocal_distance',
'transverse_magnification'
]
from sympy.core.numbers import (Float, I, oo, pi, zoo)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (acos, asin, atan2, cos, sin, tan)
from sympy.matrices.dense import Matrix
from sympy.polys.polytools import cancel
from sympy.series.limits import Limit
from sympy.geometry.line import Ray3D
from sympy.geometry.util import intersection
from sympy.geometry.plane import Plane
from sympy.utilities.iterables import is_sequence
from .medium import Medium
def refractive_index_of_medium(medium):
"""
Helper function that returns refractive index, given a medium
"""
if isinstance(medium, Medium):
n = medium.refractive_index
else:
n = sympify(medium)
return n
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
"""
This function calculates transmitted vector after refraction at planar
surface. ``medium1`` and ``medium2`` can be ``Medium`` or any sympifiable object.
If ``incident`` is a number then treated as angle of incidence (in radians)
in which case refraction angle is returned.
If ``incident`` is an object of `Ray3D`, `normal` also has to be an instance
of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
plane of separation is not provided and normal is an instance of `Ray3D`,
``normal`` will be assumed to be intersecting incident ray at the plane of
separation. This will not be the case when `normal` is a `Matrix` or
any other sequence.
If ``incident`` is an instance of `Ray3D` and `plane` has not been provided
and ``normal`` is not `Ray3D`, output will be a `Matrix`.
Parameters
==========
incident : Matrix, Ray3D, sequence or a number
Incident vector or angle of incidence
medium1 : sympy.physics.optics.medium.Medium or sympifiable
Medium 1 or its refractive index
medium2 : sympy.physics.optics.medium.Medium or sympifiable
Medium 2 or its refractive index
normal : Matrix, Ray3D, or sequence
Normal vector
plane : Plane
Plane of separation of the two media.
Returns
=======
Returns an angle of refraction or a refracted ray depending on inputs.
Examples
========
>>> from sympy.physics.optics import refraction_angle
>>> from sympy.geometry import Point3D, Ray3D, Plane
>>> from sympy.matrices import Matrix
>>> from sympy import symbols, pi
>>> n = Matrix([0, 0, 1])
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
>>> refraction_angle(r1, 1, 1, n)
Matrix([
[ 1],
[ 1],
[-1]])
>>> refraction_angle(r1, 1, 1, plane=P)
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
With different index of refraction of the two media
>>> n1, n2 = symbols('n1, n2')
>>> refraction_angle(r1, n1, n2, n)
Matrix([
[ n1/n2],
[ n1/n2],
[-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
>>> refraction_angle(r1, n1, n2, plane=P)
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
>>> round(refraction_angle(pi/6, 1.2, 1.5), 5)
0.41152
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
# check if an incidence angle was supplied instead of a ray
try:
angle_of_incidence = float(incident)
except TypeError:
angle_of_incidence = None
try:
critical_angle_ = critical_angle(medium1, medium2)
except (ValueError, TypeError):
critical_angle_ = None
if angle_of_incidence is not None:
if normal is not None or plane is not None:
raise ValueError('Normal/plane not allowed if incident is an angle')
if not 0.0 <= angle_of_incidence < pi*0.5:
raise ValueError('Angle of incidence not in range [0:pi/2)')
if critical_angle_ and angle_of_incidence > critical_angle_:
raise ValueError('Ray undergoes total internal reflection')
return asin(n1*sin(angle_of_incidence)/n2)
# Treat the incident as ray below
# A flag to check whether to return Ray3D or not
return_ray = False
if plane is not None and normal is not None:
raise ValueError("Either plane or normal is acceptable.")
if not isinstance(incident, Matrix):
if is_sequence(incident):
_incident = Matrix(incident)
elif isinstance(incident, Ray3D):
_incident = Matrix(incident.direction_ratio)
else:
raise TypeError(
"incident should be a Matrix, Ray3D, or sequence")
else:
_incident = incident
# If plane is provided, get direction ratios of the normal
# to the plane from the plane else go with `normal` param.
if plane is not None:
if not isinstance(plane, Plane):
raise TypeError("plane should be an instance of geometry.plane.Plane")
# If we have the plane, we can get the intersection
# point of incident ray and the plane and thus return
# an instance of Ray3D.
if isinstance(incident, Ray3D):
return_ray = True
intersection_pt = plane.intersection(incident)[0]
_normal = Matrix(plane.normal_vector)
else:
if not isinstance(normal, Matrix):
if is_sequence(normal):
_normal = Matrix(normal)
elif isinstance(normal, Ray3D):
_normal = Matrix(normal.direction_ratio)
if isinstance(incident, Ray3D):
intersection_pt = intersection(incident, normal)
if len(intersection_pt) == 0:
raise ValueError(
"Normal isn't concurrent with the incident ray.")
else:
return_ray = True
intersection_pt = intersection_pt[0]
else:
raise TypeError(
"Normal should be a Matrix, Ray3D, or sequence")
else:
_normal = normal
eta = n1/n2 # Relative index of refraction
# Calculating magnitude of the vectors
mag_incident = sqrt(sum([i**2 for i in _incident]))
mag_normal = sqrt(sum([i**2 for i in _normal]))
# Converting vectors to unit vectors by dividing
# them with their magnitudes
_incident /= mag_incident
_normal /= mag_normal
c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
if cs2.is_negative: # This is the case of total internal reflection(TIR).
return S.Zero
drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
# Multiplying unit vector by its magnitude
drs = drs*mag_incident
if not return_ray:
return drs
else:
return Ray3D(intersection_pt, direction_ratio=drs)
def fresnel_coefficients(angle_of_incidence, medium1, medium2):
"""
This function uses Fresnel equations to calculate reflection and
transmission coefficients. Those are obtained for both polarisations
when the electric field vector is in the plane of incidence (labelled 'p')
and when the electric field vector is perpendicular to the plane of
incidence (labelled 's'). There are four real coefficients unless the
incident ray reflects in total internal in which case there are two complex
ones. Angle of incidence is the angle between the incident ray and the
surface normal. ``medium1`` and ``medium2`` can be ``Medium`` or any
sympifiable object.
Parameters
==========
angle_of_incidence : sympifiable
medium1 : Medium or sympifiable
Medium 1 or its refractive index
medium2 : Medium or sympifiable
Medium 2 or its refractive index
Returns
=======
Returns a list with four real Fresnel coefficients:
[reflection p (TM), reflection s (TE),
transmission p (TM), transmission s (TE)]
If the ray is undergoes total internal reflection then returns a
list of two complex Fresnel coefficients:
[reflection p (TM), reflection s (TE)]
Examples
========
>>> from sympy.physics.optics import fresnel_coefficients
>>> fresnel_coefficients(0.3, 1, 2)
[0.317843553417859, -0.348645229818821,
0.658921776708929, 0.651354770181179]
>>> fresnel_coefficients(0.6, 2, 1)
[-0.235625382192159 - 0.971843958291041*I,
0.816477005968898 - 0.577377951366403*I]
References
==========
.. [1] https://en.wikipedia.org/wiki/Fresnel_equations
"""
if not 0 <= 2*angle_of_incidence < pi:
raise ValueError('Angle of incidence not in range [0:pi/2)')
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
angle_of_refraction = asin(n1*sin(angle_of_incidence)/n2)
try:
angle_of_total_internal_reflection_onset = critical_angle(n1, n2)
except ValueError:
angle_of_total_internal_reflection_onset = None
if angle_of_total_internal_reflection_onset is None or\
angle_of_total_internal_reflection_onset > angle_of_incidence:
R_s = -sin(angle_of_incidence - angle_of_refraction)\
/sin(angle_of_incidence + angle_of_refraction)
R_p = tan(angle_of_incidence - angle_of_refraction)\
/tan(angle_of_incidence + angle_of_refraction)
T_s = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
/sin(angle_of_incidence + angle_of_refraction)
T_p = 2*sin(angle_of_refraction)*cos(angle_of_incidence)\
/(sin(angle_of_incidence + angle_of_refraction)\
*cos(angle_of_incidence - angle_of_refraction))
return [R_p, R_s, T_p, T_s]
else:
n = n2/n1
R_s = cancel((cos(angle_of_incidence)-\
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
/(cos(angle_of_incidence)+\
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
R_p = cancel((n**2*cos(angle_of_incidence)-\
I*sqrt(sin(angle_of_incidence)**2 - n**2))\
/(n**2*cos(angle_of_incidence)+\
I*sqrt(sin(angle_of_incidence)**2 - n**2)))
return [R_p, R_s]
def deviation(incident, medium1, medium2, normal=None, plane=None):
"""
This function calculates the angle of deviation of a ray
due to refraction at planar surface.
Parameters
==========
incident : Matrix, Ray3D, sequence or float
Incident vector or angle of incidence
medium1 : sympy.physics.optics.medium.Medium or sympifiable
Medium 1 or its refractive index
medium2 : sympy.physics.optics.medium.Medium or sympifiable
Medium 2 or its refractive index
normal : Matrix, Ray3D, or sequence
Normal vector
plane : Plane
Plane of separation of the two media.
Returns angular deviation between incident and refracted rays
Examples
========
>>> from sympy.physics.optics import deviation
>>> from sympy.geometry import Point3D, Ray3D, Plane
>>> from sympy.matrices import Matrix
>>> from sympy import symbols
>>> n1, n2 = symbols('n1, n2')
>>> n = Matrix([0, 0, 1])
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
>>> deviation(r1, 1, 1, n)
0
>>> deviation(r1, n1, n2, plane=P)
-acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
>>> round(deviation(0.1, 1.2, 1.5), 5)
-0.02005
"""
refracted = refraction_angle(incident,
medium1,
medium2,
normal=normal,
plane=plane)
try:
angle_of_incidence = Float(incident)
except TypeError:
angle_of_incidence = None
if angle_of_incidence is not None:
return float(refracted) - angle_of_incidence
if refracted != 0:
if isinstance(refracted, Ray3D):
refracted = Matrix(refracted.direction_ratio)
if not isinstance(incident, Matrix):
if is_sequence(incident):
_incident = Matrix(incident)
elif isinstance(incident, Ray3D):
_incident = Matrix(incident.direction_ratio)
else:
raise TypeError(
"incident should be a Matrix, Ray3D, or sequence")
else:
_incident = incident
if plane is None:
if not isinstance(normal, Matrix):
if is_sequence(normal):
_normal = Matrix(normal)
elif isinstance(normal, Ray3D):
_normal = Matrix(normal.direction_ratio)
else:
raise TypeError(
"normal should be a Matrix, Ray3D, or sequence")
else:
_normal = normal
else:
_normal = Matrix(plane.normal_vector)
mag_incident = sqrt(sum([i**2 for i in _incident]))
mag_normal = sqrt(sum([i**2 for i in _normal]))
mag_refracted = sqrt(sum([i**2 for i in refracted]))
_incident /= mag_incident
_normal /= mag_normal
refracted /= mag_refracted
i = acos(_incident.dot(_normal))
r = acos(refracted.dot(_normal))
return i - r
def brewster_angle(medium1, medium2):
"""
This function calculates the Brewster's angle of incidence to Medium 2 from
Medium 1 in radians.
Parameters
==========
medium 1 : Medium or sympifiable
Refractive index of Medium 1
medium 2 : Medium or sympifiable
Refractive index of Medium 1
Examples
========
>>> from sympy.physics.optics import brewster_angle
>>> brewster_angle(1, 1.33)
0.926093295503462
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
return atan2(n2, n1)
def critical_angle(medium1, medium2):
"""
This function calculates the critical angle of incidence (marking the onset
of total internal) to Medium 2 from Medium 1 in radians.
Parameters
==========
medium 1 : Medium or sympifiable
Refractive index of Medium 1.
medium 2 : Medium or sympifiable
Refractive index of Medium 1.
Examples
========
>>> from sympy.physics.optics import critical_angle
>>> critical_angle(1.33, 1)
0.850908514477849
"""
n1 = refractive_index_of_medium(medium1)
n2 = refractive_index_of_medium(medium2)
if n2 > n1:
raise ValueError('Total internal reflection impossible for n1 < n2')
else:
return asin(n2/n1)
def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):
"""
This function calculates focal length of a lens.
It follows cartesian sign convention.
Parameters
==========
n_lens : Medium or sympifiable
Index of refraction of lens.
n_surr : Medium or sympifiable
Index of reflection of surrounding.
r1 : sympifiable
Radius of curvature of first surface.
r2 : sympifiable
Radius of curvature of second surface.
d : sympifiable, optional
Thickness of lens, default value is 0.
Examples
========
>>> from sympy.physics.optics import lens_makers_formula
>>> from sympy import S
>>> lens_makers_formula(1.33, 1, 10, -10)
15.1515151515151
>>> lens_makers_formula(1.2, 1, 10, S.Infinity)
50.0000000000000
>>> lens_makers_formula(1.33, 1, 10, -10, d=1)
15.3418463277618
"""
if isinstance(n_lens, Medium):
n_lens = n_lens.refractive_index
else:
n_lens = sympify(n_lens)
if isinstance(n_surr, Medium):
n_surr = n_surr.refractive_index
else:
n_surr = sympify(n_surr)
d = sympify(d)
focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))
if focal_length == zoo:
return S.Infinity
return focal_length
def mirror_formula(focal_length=None, u=None, v=None):
"""
This function provides one of the three parameters
when two of them are supplied.
This is valid only for paraxial rays.
Parameters
==========
focal_length : sympifiable
Focal length of the mirror.
u : sympifiable
Distance of object from the pole on
the principal axis.
v : sympifiable
Distance of the image from the pole
on the principal axis.
Examples
========
>>> from sympy.physics.optics import mirror_formula
>>> from sympy.abc import f, u, v
>>> mirror_formula(focal_length=f, u=u)
f*u/(-f + u)
>>> mirror_formula(focal_length=f, v=v)
f*v/(-f + v)
>>> mirror_formula(u=u, v=v)
u*v/(u + v)
"""
if focal_length and u and v:
raise ValueError("Please provide only two parameters")
focal_length = sympify(focal_length)
u = sympify(u)
v = sympify(v)
if u is oo:
_u = Symbol('u')
if v is oo:
_v = Symbol('v')
if focal_length is oo:
_f = Symbol('f')
if focal_length is None:
if u is oo and v is oo:
return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
if u is oo:
return Limit(v*_u/(v + _u), _u, oo).doit()
if v is oo:
return Limit(_v*u/(_v + u), _v, oo).doit()
return v*u/(v + u)
if u is None:
if v is oo and focal_length is oo:
return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
if v is oo:
return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
if focal_length is oo:
return Limit(v*_f/(v - _f), _f, oo).doit()
return v*focal_length/(v - focal_length)
if v is None:
if u is oo and focal_length is oo:
return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
if u is oo:
return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
if focal_length is oo:
return Limit(u*_f/(u - _f), _f, oo).doit()
return u*focal_length/(u - focal_length)
def lens_formula(focal_length=None, u=None, v=None):
"""
This function provides one of the three parameters
when two of them are supplied.
This is valid only for paraxial rays.
Parameters
==========
focal_length : sympifiable
Focal length of the mirror.
u : sympifiable
Distance of object from the optical center on
the principal axis.
v : sympifiable
Distance of the image from the optical center
on the principal axis.
Examples
========
>>> from sympy.physics.optics import lens_formula
>>> from sympy.abc import f, u, v
>>> lens_formula(focal_length=f, u=u)
f*u/(f + u)
>>> lens_formula(focal_length=f, v=v)
f*v/(f - v)
>>> lens_formula(u=u, v=v)
u*v/(u - v)
"""
if focal_length and u and v:
raise ValueError("Please provide only two parameters")
focal_length = sympify(focal_length)
u = sympify(u)
v = sympify(v)
if u is oo:
_u = Symbol('u')
if v is oo:
_v = Symbol('v')
if focal_length is oo:
_f = Symbol('f')
if focal_length is None:
if u is oo and v is oo:
return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
if u is oo:
return Limit(v*_u/(_u - v), _u, oo).doit()
if v is oo:
return Limit(_v*u/(u - _v), _v, oo).doit()
return v*u/(u - v)
if u is None:
if v is oo and focal_length is oo:
return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
if v is oo:
return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
if focal_length is oo:
return Limit(v*_f/(_f - v), _f, oo).doit()
return v*focal_length/(focal_length - v)
if v is None:
if u is oo and focal_length is oo:
return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
if u is oo:
return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
if focal_length is oo:
return Limit(u*_f/(u + _f), _f, oo).doit()
return u*focal_length/(u + focal_length)
def hyperfocal_distance(f, N, c):
"""
Parameters
==========
f: sympifiable
Focal length of a given lens.
N: sympifiable
F-number of a given lens.
c: sympifiable
Circle of Confusion (CoC) of a given image format.
Example
=======
>>> from sympy.physics.optics import hyperfocal_distance
>>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
9.47
"""
f = sympify(f)
N = sympify(N)
c = sympify(c)
return (1/(N * c))*(f**2)
def transverse_magnification(si, so):
"""
Calculates the transverse magnification, which is the ratio of the
image size to the object size.
Parameters
==========
so: sympifiable
Lens-object distance.
si: sympifiable
Lens-image distance.
Example
=======
>>> from sympy.physics.optics import transverse_magnification
>>> transverse_magnification(30, 15)
-2
"""
si = sympify(si)
so = sympify(so)
return (-(si/so))
|
f7ddbec5de0100c99def2d3b31f3c5dfcc2b7c11233cb762b0fad5d2251ff849 | """
This module has all the classes and functions related to waves in optics.
**Contains**
* TWave
"""
__all__ = ['TWave']
from sympy.core.expr import Expr
from sympy.core.function import Derivative, Function
from sympy.core.numbers import (Number, pi, I)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
from sympy.physics.units import speed_of_light, meter, second
c = speed_of_light.convert_to(meter/second)
class TWave(Expr):
r"""
This is a simple transverse sine wave travelling in a one-dimensional space.
Basic properties are required at the time of creation of the object,
but they can be changed later with respective methods provided.
Explanation
===========
It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
where :math:`A` is the amplitude, :math:`\omega` is the angular frequency,
:math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
to represent the position on the dimension on which the wave propagates,
and :math:`\phi` is the phase angle of the wave.
Arguments
=========
amplitude : Sympifyable
Amplitude of the wave.
frequency : Sympifyable
Frequency of the wave.
phase : Sympifyable
Phase angle of the wave.
time_period : Sympifyable
Time period of the wave.
n : Sympifyable
Refractive index of the medium.
Raises
=======
ValueError : When neither frequency nor time period is provided
or they are not consistent.
TypeError : When anything other than TWave objects is added.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
>>> w1 = TWave(A1, f, phi1)
>>> w2 = TWave(A2, f, phi2)
>>> w3 = w1 + w2 # Superposition of two waves
>>> w3
TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)))
>>> w3.amplitude
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
>>> w3.phase
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
>>> w3.speed
299792458*meter/(second*n)
>>> w3.angular_velocity
2*pi*f
"""
def __init__(
self,
amplitude,
frequency=None,
phase=S.Zero,
time_period=None,
n=Symbol('n')):
frequency = sympify(frequency)
amplitude = sympify(amplitude)
phase = sympify(phase)
time_period = sympify(time_period)
n = sympify(n)
self._frequency = frequency
self._amplitude = amplitude
self._phase = phase
self._time_period = time_period
self._n = n
if time_period is not None:
self._frequency = 1/self._time_period
if frequency is not None:
self._time_period = 1/self._frequency
if time_period is not None:
if frequency != 1/time_period:
raise ValueError("frequency and time_period should be consistent.")
if frequency is None and time_period is None:
raise ValueError("Either frequency or time period is needed.")
@property
def frequency(self):
"""
Returns the frequency of the wave,
in cycles per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.frequency
f
"""
return self._frequency
@property
def time_period(self):
"""
Returns the temporal period of the wave,
in seconds per cycle.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.time_period
1/f
"""
return self._time_period
@property
def wavelength(self):
"""
Returns the wavelength (spatial period) of the wave,
in meters per cycle.
It depends on the medium of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
299792458*meter/(second*f*n)
"""
return c/(self._frequency*self._n)
@property
def amplitude(self):
"""
Returns the amplitude of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.amplitude
A
"""
return self._amplitude
@property
def phase(self):
"""
Returns the phase angle of the wave,
in radians.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.phase
phi
"""
return self._phase
@property
def speed(self):
"""
Returns the propagation speed of the wave,
in meters per second.
It is dependent on the propagation medium.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
299792458*meter/(second*n)
"""
return self.wavelength*self._frequency
@property
def angular_velocity(self):
"""
Returns the angular velocity of the wave,
in radians per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.angular_velocity
2*pi*f
"""
return 2*pi*self._frequency
@property
def wavenumber(self):
"""
Returns the wavenumber of the wave,
in radians per meter.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavenumber
pi*second*f*n/(149896229*meter)
"""
return 2*pi/self.wavelength
def __str__(self):
"""String representation of a TWave."""
from sympy.printing import sstr
return type(self).__name__ + sstr(self.args)
__repr__ = __str__
def __add__(self, other):
"""
Addition of two waves will result in their superposition.
The type of interference will depend on their phase angles.
"""
if isinstance(other, TWave):
if self._frequency == other._frequency and self.wavelength == other.wavelength:
return TWave(sqrt(self._amplitude**2 + other._amplitude**2 + 2 *
self._amplitude*other._amplitude*cos(
self._phase - other.phase)),
self._frequency,
atan2(self._amplitude*sin(self._phase)
+ other._amplitude*sin(other._phase),
self._amplitude*cos(self._phase)
+ other._amplitude*cos(other._phase))
)
else:
raise NotImplementedError("Interference of waves with different frequencies"
" has not been implemented.")
else:
raise TypeError(type(other).__name__ + " and TWave objects cannot be added.")
def __mul__(self, other):
"""
Multiplying a wave by a scalar rescales the amplitude of the wave.
"""
other = sympify(other)
if isinstance(other, Number):
return TWave(self._amplitude*other, *self.args[1:])
else:
raise TypeError(type(other).__name__ + " and TWave objects cannot be multiplied.")
def __sub__(self, other):
return self.__add__(-1*other)
def __neg__(self):
return self.__mul__(-1)
def __radd__(self, other):
return self.__add__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __rsub__(self, other):
return (-self).__radd__(other)
def _eval_rewrite_as_sin(self, *args, **kwargs):
return self._amplitude*sin(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
def _eval_rewrite_as_cos(self, *args, **kwargs):
return self._amplitude*cos(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase)
def _eval_rewrite_as_pde(self, *args, **kwargs):
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
E = Function('E')
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
def _eval_rewrite_as_exp(self, *args, **kwargs):
return self._amplitude*exp(I*(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase))
|
a21776c118e5bed4d4c2539d5cee700142757a49a91600a557c8da96a5440d45 | """
Gaussian optics.
The module implements:
- Ray transfer matrices for geometrical and gaussian optics.
See RayTransferMatrix, GeometricRay and BeamParameter
- Conjugation relations for geometrical and gaussian optics.
See geometric_conj*, gauss_conj and conjugate_gauss_beams
The conventions for the distances are as follows:
focal distance
positive for convergent lenses
object distance
positive for real objects
image distance
positive for real images
"""
__all__ = [
'RayTransferMatrix',
'FreeSpace',
'FlatRefraction',
'CurvedRefraction',
'FlatMirror',
'CurvedMirror',
'ThinLens',
'GeometricRay',
'BeamParameter',
'waist2rayleigh',
'rayleigh2waist',
'geometric_conj_ab',
'geometric_conj_af',
'geometric_conj_bf',
'gaussian_conj',
'conjugate_gauss_beams',
]
from sympy.core.expr import Expr
from sympy.core.numbers import (I, pi)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import (im, re)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import atan2
from sympy.matrices.dense import Matrix, MutableDenseMatrix
from sympy.polys.rationaltools import together
from sympy.utilities.misc import filldedent
###
# A, B, C, D matrices
###
class RayTransferMatrix(MutableDenseMatrix):
"""
Base class for a Ray Transfer Matrix.
It should be used if there isn't already a more specific subclass mentioned
in See Also.
Parameters
==========
parameters :
A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix, ThinLens
>>> from sympy import Symbol, Matrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat
Matrix([
[1, 2],
[3, 4]])
>>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
Matrix([
[1, 2],
[3, 4]])
>>> mat.A
1
>>> f = Symbol('f')
>>> lens = ThinLens(f)
>>> lens
Matrix([
[ 1, 0],
[-1/f, 1]])
>>> lens.C
-1/f
See Also
========
GeometricRay, BeamParameter,
FreeSpace, FlatRefraction, CurvedRefraction,
FlatMirror, CurvedMirror, ThinLens
References
==========
.. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
"""
def __new__(cls, *args):
if len(args) == 4:
temp = ((args[0], args[1]), (args[2], args[3]))
elif len(args) == 1 \
and isinstance(args[0], Matrix) \
and args[0].shape == (2, 2):
temp = args[0]
else:
raise ValueError(filldedent('''
Expecting 2x2 Matrix or the 4 elements of
the Matrix but got %s''' % str(args)))
return Matrix.__new__(cls, temp)
def __mul__(self, other):
if isinstance(other, RayTransferMatrix):
return RayTransferMatrix(Matrix.__mul__(self, other))
elif isinstance(other, GeometricRay):
return GeometricRay(Matrix.__mul__(self, other))
elif isinstance(other, BeamParameter):
temp = self*Matrix(((other.q,), (1,)))
q = (temp[0]/temp[1]).expand(complex=True)
return BeamParameter(other.wavelen,
together(re(q)),
z_r=together(im(q)))
else:
return Matrix.__mul__(self, other)
@property
def A(self):
"""
The A parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.A
1
"""
return self[0, 0]
@property
def B(self):
"""
The B parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.B
2
"""
return self[0, 1]
@property
def C(self):
"""
The C parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.C
3
"""
return self[1, 0]
@property
def D(self):
"""
The D parameter of the Matrix.
Examples
========
>>> from sympy.physics.optics import RayTransferMatrix
>>> mat = RayTransferMatrix(1, 2, 3, 4)
>>> mat.D
4
"""
return self[1, 1]
class FreeSpace(RayTransferMatrix):
"""
Ray Transfer Matrix for free space.
Parameters
==========
distance
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FreeSpace
>>> from sympy import symbols
>>> d = symbols('d')
>>> FreeSpace(d)
Matrix([
[1, d],
[0, 1]])
"""
def __new__(cls, d):
return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
class FlatRefraction(RayTransferMatrix):
"""
Ray Transfer Matrix for refraction.
Parameters
==========
n1 :
Refractive index of one medium.
n2 :
Refractive index of other medium.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FlatRefraction
>>> from sympy import symbols
>>> n1, n2 = symbols('n1 n2')
>>> FlatRefraction(n1, n2)
Matrix([
[1, 0],
[0, n1/n2]])
"""
def __new__(cls, n1, n2):
n1, n2 = map(sympify, (n1, n2))
return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
class CurvedRefraction(RayTransferMatrix):
"""
Ray Transfer Matrix for refraction on curved interface.
Parameters
==========
R :
Radius of curvature (positive for concave).
n1 :
Refractive index of one medium.
n2 :
Refractive index of other medium.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import CurvedRefraction
>>> from sympy import symbols
>>> R, n1, n2 = symbols('R n1 n2')
>>> CurvedRefraction(R, n1, n2)
Matrix([
[ 1, 0],
[(n1 - n2)/(R*n2), n1/n2]])
"""
def __new__(cls, R, n1, n2):
R, n1, n2 = map(sympify, (R, n1, n2))
return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
class FlatMirror(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FlatMirror
>>> FlatMirror()
Matrix([
[1, 0],
[0, 1]])
"""
def __new__(cls):
return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
class CurvedMirror(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection from curved surface.
Parameters
==========
R : radius of curvature (positive for concave)
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import CurvedMirror
>>> from sympy import symbols
>>> R = symbols('R')
>>> CurvedMirror(R)
Matrix([
[ 1, 0],
[-2/R, 1]])
"""
def __new__(cls, R):
R = sympify(R)
return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
class ThinLens(RayTransferMatrix):
"""
Ray Transfer Matrix for a thin lens.
Parameters
==========
f :
The focal distance.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import ThinLens
>>> from sympy import symbols
>>> f = symbols('f')
>>> ThinLens(f)
Matrix([
[ 1, 0],
[-1/f, 1]])
"""
def __new__(cls, f):
f = sympify(f)
return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
###
# Representation for geometric ray
###
class GeometricRay(MutableDenseMatrix):
"""
Representation for a geometric ray in the Ray Transfer Matrix formalism.
Parameters
==========
h : height, and
angle : angle, or
matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
Examples
========
>>> from sympy.physics.optics import GeometricRay, FreeSpace
>>> from sympy import symbols, Matrix
>>> d, h, angle = symbols('d, h, angle')
>>> GeometricRay(h, angle)
Matrix([
[ h],
[angle]])
>>> FreeSpace(d)*GeometricRay(h, angle)
Matrix([
[angle*d + h],
[ angle]])
>>> GeometricRay( Matrix( ((h,), (angle,)) ) )
Matrix([
[ h],
[angle]])
See Also
========
RayTransferMatrix
"""
def __new__(cls, *args):
if len(args) == 1 and isinstance(args[0], Matrix) \
and args[0].shape == (2, 1):
temp = args[0]
elif len(args) == 2:
temp = ((args[0],), (args[1],))
else:
raise ValueError(filldedent('''
Expecting 2x1 Matrix or the 2 elements of
the Matrix but got %s''' % str(args)))
return Matrix.__new__(cls, temp)
@property
def height(self):
"""
The distance from the optical axis.
Examples
========
>>> from sympy.physics.optics import GeometricRay
>>> from sympy import symbols
>>> h, angle = symbols('h, angle')
>>> gRay = GeometricRay(h, angle)
>>> gRay.height
h
"""
return self[0]
@property
def angle(self):
"""
The angle with the optical axis.
Examples
========
>>> from sympy.physics.optics import GeometricRay
>>> from sympy import symbols
>>> h, angle = symbols('h, angle')
>>> gRay = GeometricRay(h, angle)
>>> gRay.angle
angle
"""
return self[1]
###
# Representation for gauss beam
###
class BeamParameter(Expr):
"""
Representation for a gaussian ray in the Ray Transfer Matrix formalism.
Parameters
==========
wavelen : the wavelength,
z : the distance to waist, and
w : the waist, or
z_r : the rayleigh range.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.q
1 + 1.88679245283019*I*pi
>>> p.q.n()
1.0 + 5.92753330865999*I
>>> p.w_0.n()
0.00100000000000000
>>> p.z_r.n()
5.92753330865999
>>> from sympy.physics.optics import FreeSpace
>>> fs = FreeSpace(10)
>>> p1 = fs*p
>>> p.w.n()
0.00101413072159615
>>> p1.w.n()
0.00210803120913829
See Also
========
RayTransferMatrix
References
==========
.. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter
.. [2] https://en.wikipedia.org/wiki/Gaussian_beam
"""
#TODO A class Complex may be implemented. The BeamParameter may
# subclass it. See:
# https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
def __new__(cls, wavelen, z, z_r=None, w=None):
wavelen = sympify(wavelen)
z = sympify(z)
if z_r is not None and w is None:
z_r = sympify(z_r)
elif w is not None and z_r is None:
z_r = waist2rayleigh(sympify(w), wavelen)
else:
raise ValueError('Constructor expects exactly one named argument.')
return Expr.__new__(cls, wavelen, z, z_r)
@property
def wavelen(self):
return self.args[0]
@property
def z(self):
return self.args[1]
@property
def z_r(self):
return self.args[2]
@property
def q(self):
"""
The complex parameter representing the beam.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.q
1 + 1.88679245283019*I*pi
"""
return self.z + I*self.z_r
@property
def radius(self):
"""
The radius of curvature of the phase front.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.radius
1 + 3.55998576005696*pi**2
"""
return self.z*(1 + (self.z_r/self.z)**2)
@property
def w(self):
"""
The beam radius at `1/e^2` intensity.
See Also
========
w_0 :
The minimal radius of beam.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.w
0.001*sqrt(0.2809/pi**2 + 1)
"""
return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
@property
def w_0(self):
"""
The beam waist (minimal radius).
See Also
========
w : the beam radius at `1/e^2` intensity
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.w_0
0.00100000000000000
"""
return sqrt(self.z_r/pi*self.wavelen)
@property
def divergence(self):
"""
Half of the total angular spread.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.divergence
0.00053/pi
"""
return self.wavelen/pi/self.w_0
@property
def gouy(self):
"""
The Gouy phase.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.gouy
atan(0.53/pi)
"""
return atan2(self.z, self.z_r)
@property
def waist_approximation_limit(self):
"""
The minimal waist for which the gauss beam approximation is valid.
Explanation
===========
The gauss beam is a solution to the paraxial equation. For curvatures
that are too great it is not a valid approximation.
Examples
========
>>> from sympy.physics.optics import BeamParameter
>>> p = BeamParameter(530e-9, 1, w=1e-3)
>>> p.waist_approximation_limit
1.06e-6/pi
"""
return 2*self.wavelen/pi
###
# Utilities
###
def waist2rayleigh(w, wavelen):
"""
Calculate the rayleigh range from the waist of a gaussian beam.
See Also
========
rayleigh2waist, BeamParameter
Examples
========
>>> from sympy.physics.optics import waist2rayleigh
>>> from sympy import symbols
>>> w, wavelen = symbols('w wavelen')
>>> waist2rayleigh(w, wavelen)
pi*w**2/wavelen
"""
w, wavelen = map(sympify, (w, wavelen))
return w**2*pi/wavelen
def rayleigh2waist(z_r, wavelen):
"""Calculate the waist from the rayleigh range of a gaussian beam.
See Also
========
waist2rayleigh, BeamParameter
Examples
========
>>> from sympy.physics.optics import rayleigh2waist
>>> from sympy import symbols
>>> z_r, wavelen = symbols('z_r wavelen')
>>> rayleigh2waist(z_r, wavelen)
sqrt(wavelen*z_r)/sqrt(pi)
"""
z_r, wavelen = map(sympify, (z_r, wavelen))
return sqrt(z_r/pi*wavelen)
def geometric_conj_ab(a, b):
"""
Conjugation relation for geometrical beams under paraxial conditions.
Explanation
===========
Takes the distances to the optical element and returns the needed
focal distance.
See Also
========
geometric_conj_af, geometric_conj_bf
Examples
========
>>> from sympy.physics.optics import geometric_conj_ab
>>> from sympy import symbols
>>> a, b = symbols('a b')
>>> geometric_conj_ab(a, b)
a*b/(a + b)
"""
a, b = map(sympify, (a, b))
if a.is_infinite or b.is_infinite:
return a if b.is_infinite else b
else:
return a*b/(a + b)
def geometric_conj_af(a, f):
"""
Conjugation relation for geometrical beams under paraxial conditions.
Explanation
===========
Takes the object distance (for geometric_conj_af) or the image distance
(for geometric_conj_bf) to the optical element and the focal distance.
Then it returns the other distance needed for conjugation.
See Also
========
geometric_conj_ab
Examples
========
>>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
>>> from sympy import symbols
>>> a, b, f = symbols('a b f')
>>> geometric_conj_af(a, f)
a*f/(a - f)
>>> geometric_conj_bf(b, f)
b*f/(b - f)
"""
a, f = map(sympify, (a, f))
return -geometric_conj_ab(a, -f)
geometric_conj_bf = geometric_conj_af
def gaussian_conj(s_in, z_r_in, f):
"""
Conjugation relation for gaussian beams.
Parameters
==========
s_in :
The distance to optical element from the waist.
z_r_in :
The rayleigh range of the incident beam.
f :
The focal length of the optical element.
Returns
=======
a tuple containing (s_out, z_r_out, m)
s_out :
The distance between the new waist and the optical element.
z_r_out :
The rayleigh range of the emergent beam.
m :
The ration between the new and the old waists.
Examples
========
>>> from sympy.physics.optics import gaussian_conj
>>> from sympy import symbols
>>> s_in, z_r_in, f = symbols('s_in z_r_in f')
>>> gaussian_conj(s_in, z_r_in, f)[0]
1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
>>> gaussian_conj(s_in, z_r_in, f)[1]
z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
>>> gaussian_conj(s_in, z_r_in, f)[2]
1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
"""
s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
return (s_out, z_r_out, m)
def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
"""
Find the optical setup conjugating the object/image waists.
Parameters
==========
wavelen :
The wavelength of the beam.
waist_in and waist_out :
The waists to be conjugated.
f :
The focal distance of the element used in the conjugation.
Returns
=======
a tuple containing (s_in, s_out, f)
s_in :
The distance before the optical element.
s_out :
The distance after the optical element.
f :
The focal distance of the optical element.
Examples
========
>>> from sympy.physics.optics import conjugate_gauss_beams
>>> from sympy import symbols, factor
>>> l, w_i, w_o, f = symbols('l w_i w_o f')
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))
>>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
pi**2*w_i**4/(f**2*l**2)))/w_i**2
>>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
f
"""
#TODO add the other possible arguments
wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
m = waist_out / waist_in
z = waist2rayleigh(waist_in, wavelen)
if len(kwargs) != 1:
raise ValueError("The function expects only one named argument")
elif 'dist' in kwargs:
raise NotImplementedError(filldedent('''
Currently only focal length is supported as a parameter'''))
elif 'f' in kwargs:
f = sympify(kwargs['f'])
s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
s_out = gaussian_conj(s_in, z, f)[0]
elif 's_in' in kwargs:
raise NotImplementedError(filldedent('''
Currently only focal length is supported as a parameter'''))
else:
raise ValueError(filldedent('''
The functions expects the focal length as a named argument'''))
return (s_in, s_out, f)
#TODO
#def plot_beam():
# """Plot the beam radius as it propagates in space."""
# pass
#TODO
#def plot_beam_conjugation():
# """
# Plot the intersection of two beams.
#
# Represents the conjugation relation.
#
# See Also
# ========
#
# conjugate_gauss_beams
# """
# pass
|
9047cf3bd09bca990d80bd69705d230e6fb0ffb1e5e744333e6aff1c3b73a9d2 | from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import eye
from sympy.polys.polytools import factor
from sympy.polys.rootoftools import CRootOf
from sympy.simplify.simplify import simplify
from sympy.core.containers import Tuple
from sympy.matrices import ImmutableMatrix, Matrix
from sympy.physics.control import (TransferFunction, Series, Parallel,
Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback)
from sympy.testing.pytest import raises
a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn = symbols('a, x, b, s, g, d, p, k,\
a0:3, b0:3, tau, zeta, wn')
TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
TF2 = TransferFunction(k, 1, s)
TF3 = TransferFunction(a2*p - s, a2*s + p, s)
def test_TransferFunction_construction():
tf = TransferFunction(s + 1, s**2 + s + 1, s)
assert tf.num == (s + 1)
assert tf.den == (s**2 + s + 1)
assert tf.args == (s + 1, s**2 + s + 1, s)
tf1 = TransferFunction(s + 4, s - 5, s)
assert tf1.num == (s + 4)
assert tf1.den == (s - 5)
assert tf1.args == (s + 4, s - 5, s)
# using different polynomial variables.
tf2 = TransferFunction(p + 3, p**2 - 9, p)
assert tf2.num == (p + 3)
assert tf2.den == (p**2 - 9)
assert tf2.args == (p + 3, p**2 - 9, p)
tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
# no pole-zero cancellation on its own.
tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
assert tf4.den == (s - 1)*(s + 5)
assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
tf4_ = TransferFunction(p + 2, p + 2, p)
assert tf4_.args == (p + 2, p + 2, p)
tf5 = TransferFunction(s - 1, 4 - p, s)
assert tf5.args == (s - 1, 4 - p, s)
tf5_ = TransferFunction(s - 1, s - 1, s)
assert tf5_.args == (s - 1, s - 1, s)
tf6 = TransferFunction(5, 6, s)
assert tf6.num == 5
assert tf6.den == 6
assert tf6.args == (5, 6, s)
tf6_ = TransferFunction(1/2, 4, s)
assert tf6_.num == 0.5
assert tf6_.den == 4
assert tf6_.args == (0.500000000000000, 4, s)
tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
assert not tf7 == tf8
tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
assert tf7_ == tf8_
assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
assert tf10_ == tf10
tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
assert tf11.num == (a0 + a1*s)
assert tf11.den == (b0 + b1*s + b2*s**2)
assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
# when just the numerator is 0, leave the denominator alone.
tf12 = TransferFunction(0, p**2 - p + 1, p)
assert tf12.args == (0, p**2 - p + 1, p)
tf13 = TransferFunction(0, 1, s)
assert tf13.args == (0, 1, s)
# float exponents
tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
assert tf18.num == k_i/s + k_o*s + k_p
assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
# ValueError when denominator is zero.
raises(ValueError, lambda: TransferFunction(4, 0, s))
raises(ValueError, lambda: TransferFunction(s, 0, s))
raises(ValueError, lambda: TransferFunction(0, 0, s))
raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
raises(TypeError, lambda: TransferFunction(3, 4, 8))
def test_TransferFunction_functions():
# classmethod from_rational_expression
expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
expr_2 = s/0
expr_3 = (p*s**2 + 5*s)/(s + 1)**3
expr_4 = 6
expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
tf = TransferFunction(s + 1, s**2 + 2, s)
delay = exp(-s/tau)
expr_7 = delay*tf.to_expr()
H1 = TransferFunction.from_rational_expression(expr_7, s)
H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
assert TransferFunction.from_rational_expression(expr_5, s) == \
TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
assert TransferFunction.from_rational_expression(expr_6, s) == \
TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
assert H1 == H2
assert TransferFunction.from_rational_expression(expr_8, s) == \
TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
# explicitly cancel poles and zeros.
tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
assert tf0.simplify() == simplify(tf0) == a
tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
b = TransferFunction(p + 3, p + 5, p)
assert tf1.simplify() == simplify(tf1) == b
# expand the numerator and the denominator.
G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
G2 = TransferFunction(1, -3, p)
c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
G3 = TransferFunction(c, d, s)
G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
assert G2.expand() == G2
assert G3.expand() == TransferFunction(e, f, s)
assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
# purely symbolic polynomials.
p1 = a1*s + a0
p2 = b2*s**2 + b1*s + b0
SP1 = TransferFunction(p1, p2, s)
expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
assert expect1_.evalf() == expect1
c1, d0, d1, d2 = symbols('c1, d0:3')
p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
SP2 = TransferFunction(p3, p4, p)
expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
assert expect2_.evalf() == expect2
SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
assert expect3_.evalf() == expect3
SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
expect4_ = TransferFunction(7*p**3 + s, p - s, p)
assert SP4.subs({a0: -1, a1: -7}) == expect4_
assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
assert expect4_.evalf() == expect4
# Low-frequency (or DC) gain.
assert tf0.dc_gain() == 1
assert tf1.dc_gain() == Rational(3, 5)
assert SP2.dc_gain() == 0
assert expect4.dc_gain() == -1
assert expect2_.dc_gain() == 0
assert TransferFunction(1, s, s).dc_gain() == oo
# Poles of a transfer function.
tf_ = TransferFunction(x**3 - k, k, x)
_tf = TransferFunction(k, x**4 - k, x)
TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
_TF = TransferFunction(x**10 + x + x**2, x**2, x)
assert G1.poles() == [I, I, -I, -I]
assert G2.poles() == []
assert tf1.poles() == [-5, 1]
assert expect4_.poles() == [s]
assert SP4.poles() == [-a0*s]
assert expect3.poles() == [-0.25*p]
assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
# Stability of a transfer function.
q, r = symbols('q, r', negative=True)
t = symbols('t', positive=True)
TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
assert G1.is_stable() is False
assert G2.is_stable() is True
assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
assert expect2.is_stable() is False
assert expect1.is_stable() is True
assert stable_tf.is_stable() is True
assert stable_tf_.is_stable() is True
assert TF_.is_stable() is False
assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
assert SP4.is_stable() is None
# Zeros of a transfer function.
assert G1.zeros() == [1, 1]
assert G2.zeros() == []
assert tf1.zeros() == [-3, 1]
assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
-(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
-k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
# negation of TF.
tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
tf3 = TransferFunction(-3*p + 3, 1 - p, p)
assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
# taking power of a TF.
tf4 = TransferFunction(p + 4, p - 3, p)
tf5 = TransferFunction(s**2 + 1, 1 - s, s)
expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
raises(ValueError, lambda: tf4**(s**2 + s - 1))
raises(ValueError, lambda: tf5**s)
raises(ValueError, lambda: tf4**tf5)
# SymPy's own functions.
tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
tf6 = TransferFunction(s + p, p**2 - 5, s)
assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
# subs & xreplace
assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
assert tf3.subs(p, exp(2)) == tf3
tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
# Conversion to Expr with to_expr()
tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
tf10 = TransferFunction(0, 1, s)
tf11 = TransferFunction(1, 1, s)
assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
assert tf11.to_expr() == Pow(1, -1, evaluate=False)
def test_TransferFunction_addition_and_subtraction():
tf1 = TransferFunction(s + 6, s - 5, s)
tf2 = TransferFunction(s + 3, s + 1, s)
tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
tf4 = TransferFunction(p, 2 - p, p)
# addition
assert tf1 + tf2 == Parallel(tf1, tf2)
assert tf3 + tf1 == Parallel(tf3, tf1)
assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
c = symbols("c", commutative=False)
raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
raises(ValueError, lambda: tf2 + c)
raises(ValueError, lambda: tf3 + tf4)
raises(ValueError, lambda: tf1 + (s - 1))
raises(ValueError, lambda: tf1 + 8)
raises(ValueError, lambda: (1 - p**3) + tf1)
# subtraction
assert tf1 - tf2 == Parallel(tf1, -tf2)
assert tf3 - tf2 == Parallel(tf3, -tf2)
assert -tf1 - tf3 == Parallel(-tf1, -tf3)
assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
raises(ValueError, lambda: tf3 - tf4)
raises(ValueError, lambda: tf1 - (s - 1))
raises(ValueError, lambda: tf1 - 8)
raises(ValueError, lambda: (s + 5) - tf2)
raises(ValueError, lambda: (1 + p**4) - tf1)
def test_TransferFunction_multiplication_and_division():
G1 = TransferFunction(s + 3, -s**3 + 9, s)
G2 = TransferFunction(s + 1, s - 5, s)
G3 = TransferFunction(p, p**4 - 6, p)
G4 = TransferFunction(p + 4, p - 5, p)
G5 = TransferFunction(s + 6, s - 5, s)
G6 = TransferFunction(s + 3, s + 1, s)
G7 = TransferFunction(1, 1, s)
# multiplication
assert G1*G2 == Series(G1, G2)
assert -G1*G5 == Series(-G1, G5)
assert -G2*G5*-G6 == Series(-G2, G5, -G6)
assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
assert G3*G4 == Series(G3, G4)
assert (G1*G2)*-(G5*G6) == \
Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
c = symbols("c", commutative=False)
raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
raises(ValueError, lambda: G1 * c)
raises(ValueError, lambda: G3 * G5)
raises(ValueError, lambda: G5 * (s - 1))
raises(ValueError, lambda: 9 * G5)
raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
raises(ValueError, lambda: G6 / 0)
raises(ValueError, lambda: G3 / G5)
raises(ValueError, lambda: G5 / 2)
raises(ValueError, lambda: G5 / s**2)
raises(ValueError, lambda: (s - 4*s**2) / G2)
raises(ValueError, lambda: 0 / G4)
raises(ValueError, lambda: G5 / G6)
raises(ValueError, lambda: -G3 /G4)
raises(ValueError, lambda: G7 / (1 + G6))
raises(ValueError, lambda: G7 / (G5 * G6))
raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
def test_TransferFunction_is_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
G2 = TransferFunction(tau - s**3, tau + p**4, tau)
G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert G1.is_proper
assert G2.is_proper
assert G3.is_proper
assert not G4.is_proper
def test_TransferFunction_is_strictly_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert not tf1.is_strictly_proper
assert not tf2.is_strictly_proper
assert tf3.is_strictly_proper
assert not tf4.is_strictly_proper
def test_TransferFunction_is_biproper():
tau, omega_o, zeta = symbols('tau, omega_o, zeta')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert tf1.is_biproper
assert tf2.is_biproper
assert not tf3.is_biproper
assert not tf4.is_biproper
def test_Series_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
s0 = Series(tf, tf2)
assert s0.args == (tf, tf2)
assert s0.var == s
s1 = Series(Parallel(tf, -tf2), tf2)
assert s1.args == (Parallel(tf, -tf2), tf2)
assert s1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
s3 = Series(tf, tf2, tf4)
assert s3.args == (tf, tf2, tf4)
s4 = Series(tf3_, tf4_)
assert s4.args == (tf3_, tf4_)
assert s4.var == s
s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
s7 = Series(tf, tf2)
assert s0 == s7
assert not s0 == s2
raises(ValueError, lambda: Series(tf, tf3))
raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Series(-tf3, tf2))
raises(TypeError, lambda: Series(2, tf, tf4))
raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOSeries_construction():
tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
tfm_3 = TransferFunctionMatrix([[-tf_3]])
tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
s8 = MIMOSeries(tfm_2, tfm_1)
assert s8.args == (tfm_2, tfm_1)
assert s8.var == s
assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
assert s9.args == (tfm_3, tfm_2, tfm_1)
assert s9.var == s
assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
# arg cannot be empty tuple.
raises(ValueError, lambda: MIMOSeries())
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
# for all the adjascent transfer function matrices:
# no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
# all the TFMs must use the same complex variable.
raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
def test_Series_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
== Series(tf1, Series(tf2, tf3))
assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
assert -tf1*tf2 == Series(-tf1, tf2)
assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
raises(ValueError, lambda: tf1*tf2*tf4)
raises(ValueError, lambda: tf1*(tf2 - tf4))
raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(-tf1, -tf2, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Series(tf1, tf2, tf3).doit() == \
TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
assert S1.is_proper
assert not S1.is_strictly_proper
assert S1.is_biproper
S2 = Series(tf1, tf2, tf3)
assert S2.is_proper
assert S2.is_strictly_proper
assert not S2.is_biproper
S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
assert S3.is_proper
assert S3.is_strictly_proper
assert not S3.is_biproper
def test_MIMOSeries_functions():
tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
tfm3 = TransferFunctionMatrix([[-TF1]])
tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
raises(ValueError, lambda: tfm1*tfm2 + TF1)
raises(TypeError, lambda: tfm1*tfm2 + a0)
raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
raises(TypeError, lambda: tfm4*-tfm6 - 8)
raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
# Shape criteria.
raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
# Multiplication of a Series object with a SISO TF not allowed.
raises(ValueError, lambda: tfm4*tfm5*TF1)
raises(TypeError, lambda: tfm4*tfm5*a1)
raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
raises(TypeError, lambda: tfm5*tfm4*9)
raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
# Transfer function matrix in the arguments.
assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
(TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
# doit() should not cancel poles and zeros.
mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
assert (MIMOSeries(tm_2, tm_1).doit()
== TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
# calling doit() will expand the internal Series and Parallel objects.
assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
== MIMOSeries(-tfm3, -tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
(TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
== MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
== TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
def test_Parallel_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
p0 = Parallel(tf, tf2)
assert p0.args == (tf, tf2)
assert p0.var == s
p1 = Parallel(Series(tf, -tf2), tf2)
assert p1.args == (Series(tf, -tf2), tf2)
assert p1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
p3 = Parallel(tf, tf2, tf4)
assert p3.args == (tf, tf2, tf4)
p4 = Parallel(tf3_, tf4_)
assert p4.args == (tf3_, tf4_)
assert p4.var == s
p5 = Parallel(tf, tf2)
assert p0 == p5
assert not p0 == p1
p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
assert p6.args == (tf2, tf4, Series(tf2, -tf4))
p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
raises(ValueError, lambda: Parallel(tf, tf3))
raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Parallel(-tf3, tf4))
raises(TypeError, lambda: Parallel(2, tf, tf4))
raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOParallel_construction():
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
tfm3 = TransferFunctionMatrix([[TF1]])
tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
p8 = MIMOParallel(tfm1, tfm2)
assert p8.args == (tfm1, tfm2)
assert p8.var == s
assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
assert p9.var == s
assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.var == s
assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
p11 = MIMOParallel(tfm2, tfm1, tfm4)
assert p11.args == (tfm2, tfm1, tfm4)
assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
p12 = MIMOParallel(tfm6, tfm5)
assert p12.args == (tfm6, tfm5)
assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
# arg cannot be empty tuple.
raises(TypeError, lambda: MIMOParallel(()))
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
# all TFMs must have same shapes.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
# all TFMs must be using the same complex variable.
raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
def test_Parallel_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
assert -tf1 - tf2 == Parallel(-tf1, -tf2)
assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
raises(ValueError, lambda: tf1 + tf2 + tf4)
raises(ValueError, lambda: tf1 - tf2*tf4)
raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
(-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
2*s*wn*zeta + wn**2)**2, s)
assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
, (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(-tf1, -tf2, -tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Parallel(tf1, tf2, tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
assert P1.is_proper
assert not P1.is_strictly_proper
assert P1.is_biproper
P2 = Parallel(tf1, -tf2, -tf3)
assert P2.is_proper
assert not P2.is_strictly_proper
assert P2.is_biproper
P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
assert P3.is_proper
assert not P3.is_strictly_proper
assert P3.is_biproper
def test_MIMOParallel_functions():
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
tfm6 = TransferFunctionMatrix([[-TF2]])
tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
raises(ValueError, lambda: tfm1 + tfm2 + TF2)
raises(TypeError, lambda: tfm1 - tfm2 - a1)
raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
raises(TypeError, lambda: -tfm3 - tfm2 - 9)
raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
# All TFMs must use the same complex var. tfm7 uses 'p'.
raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
# (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
raises(TypeError, lambda: (tfm2 - tfm3)*a2)
raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
# (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
# (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
# TFM in the arguments.
assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
== MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
== TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
(TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
def test_Feedback_construction():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
assert f1.sys1 == TransferFunction(1, 1, s)
assert f1.sys2 == Series(tf1, tf2, tf3)
assert f1.var == s
f2 = Feedback(tf1, tf2*tf3)
assert f2.args == (tf1, Series(tf2, tf3), -1)
assert f2.sys1 == tf1
assert f2.sys2 == Series(tf2, tf3)
assert f2.var == s
f3 = Feedback(tf1*tf2, tf5)
assert f3.args == (Series(tf1, tf2), tf5, -1)
assert f3.sys1 == Series(tf1, tf2)
f4 = Feedback(tf4, tf6)
assert f4.args == (tf4, tf6, -1)
assert f4.sys1 == tf4
assert f4.var == p
f5 = Feedback(tf5, TransferFunction(1, 1, s))
assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
assert f5.var == s
assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
f6 = Feedback(TransferFunction(1, 1, p), tf4)
assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
assert f6.var == p
f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
# denominator can't be a Parallel instance
raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
raises(TypeError, lambda: Feedback(1, 1))
# raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
def test_Feedback_functions():
tf = TransferFunction(1, 1, s)
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
assert tf / (tf + tf1) == Feedback(tf, tf1)
assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
assert tf5 / (tf + tf5) == Feedback(tf5, tf)
raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5)
raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
assert Feedback(tf, tf1*tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1, tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1, tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1*tf2, tf5).doit() == \
TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf4, tf6).doit() == \
TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
TransferFunction(p, a0*p + p + p**a1 - s, p)
def test_MIMOFeedback_construction():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s + 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
f1 = MIMOFeedback(tfm_1, tfm_2)
assert f1.args == (tfm_1, tfm_2, -1)
assert f1.sys1 == tfm_1
assert f1.sys2 == tfm_2
assert f1.var == s
assert f1.sign == -1
assert -(-f1) == f1
f2 = MIMOFeedback(tfm_2, tfm_1, 1)
assert f2.args == (tfm_2, tfm_1, 1)
assert f2.sys1 == tfm_2
assert f2.sys2 == tfm_1
assert f2.var == s
assert f2.sign == 1
f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
assert f3.sys1 == tfm_1
assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
assert f3.var == s
assert f3.sign == -1
mat = Matrix([[1, 1/s], [0, 1]])
sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
f4 = MIMOFeedback(sys1, controller)
assert f4.args == (sys1, controller, -1)
assert f4.sys1 == f4.sys2 == sys1
def test_MIMOFeedback_errors():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s - 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tf5 = TransferFunction(1, 1, s)
tf6 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
# tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
tfm_6 = TransferFunctionMatrix([[-tf3]])
tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
# Unsupported Types
raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
# Shape Errors
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
# sign not 1/-1
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
# Non-Invertible Systems
raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
# Variable not same in both the systems
tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
def test_MIMOFeedback_functions():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s - 1, s)
tf3 = TransferFunction(1, 1, s)
tf4 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
# sensitivity, doit(), rewrite()
F_1 = MIMOFeedback(tfm_2, tfm_3)
F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
assert F_1.sensitivity == Matrix([[1/2, 0], [0, 1/2]])
assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
(2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
assert F_1.doit() == \
TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
assert F_2.doit(cancel=False, expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit(cancel=False) == \
TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
(-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit() == \
TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
TransferFunction(2*s**3*(1 - s), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
assert F_2.doit(expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
def test_TransferFunctionMatrix_construction():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tfm3_ = TransferFunctionMatrix([[-TF3]])
assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
assert tfm3_.var == s
tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
assert tfm5.var == s
tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
assert tfm7.var == s
# all transfer functions will use the same complex variable. tf4 uses 'p'.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
# length of all the lists in the TFM should be equal.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
# lists should only support transfer functions in them.
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
# `arg` should strictly be nested list of TransferFunction
raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
def test_TransferFunctionMatrix_functions():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
# Classmethod (from_matrix)
mat_1 = ImmutableMatrix([
[s*(s + 1)*(s - 3)/(s**4 + 1), 2],
[p, p*(s + 1)/(s*(s**1 + 1))]
])
mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
[TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
[TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
# Negating a TFM
tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
# subs()
H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
# transpose()
assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
assert H_1.transpose().transpose() == H_1
assert H_2.transpose().transpose() == H_2
# elem_poles()
assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
[[], [0]]]
assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
[[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
# elem_zeros()
assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
assert H_2.elem_zeros() == [[[0], [0]]]
assert tfm2.elem_zeros() == [[[], [], [a2*p]],
[[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
# doit()
H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
# _flat()
assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
# evalf()
assert H_1.evalf() == \
TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
# simplify()
H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
assert H_5.simplify() == simplify(H_5) == \
TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
# expand()
assert (H_1.expand()
== TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
(TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
assert H_5.expand() == \
TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
|
01664a59aa382d06faee197b16d12cada1b396501c4462b1b8c37304d210b566 | from sympy.core.numbers import I
from sympy.core.symbol import Dummy
from sympy.functions.elementary.complexes import (Abs, arg)
from sympy.functions.elementary.exponential import log
from sympy.abc import s, p, a
from sympy.external import import_module
from sympy.physics.control.control_plots import \
(pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
step_response_plot, impulse_response_numerical_data,
impulse_response_plot, ramp_response_numerical_data,
ramp_response_plot, bode_magnitude_numerical_data,
bode_phase_numerical_data, bode_plot)
from sympy.physics.control.lti import (TransferFunction,
Series, Parallel, TransferFunctionMatrix)
from sympy.testing.pytest import raises, skip
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,))
numpy = import_module('numpy')
tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
tf3 = TransferFunction(p, p**3 - 1, p)
tf4 = TransferFunction(10, p**3, p)
tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
tf6 = TransferFunction(1, 1, s)
tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
ser1 = Series(tf4, TransferFunction(1, p - 5, p))
ser2 = Series(tf3, TransferFunction(p, p + 2, p))
par1 = Parallel(tf1, tf2)
par2 = Parallel(tf1, tf2, tf3)
def _to_tuple(a, b):
return tuple(a), tuple(b)
def _trim_tuple(a, b):
a, b = _to_tuple(a, b)
return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
def y_coordinate_equality(plot_data_func, evalf_func, system):
"""Checks whether the y-coordinate value of the plotted
data point is equal to the value of the function at a
particular x."""
x, y = plot_data_func(system)
x, y = _trim_tuple(x, y)
y_exp = tuple(evalf_func(system, x_i) for x_i in x)
return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
def test_errors():
if not matplotlib:
skip("Matplotlib not the default backend")
# Invalid `system` check
tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
expr = 1/(s**2 - 1)
raises(NotImplementedError, lambda: pole_zero_plot(tfm))
raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
raises(NotImplementedError, lambda: impulse_response_plot(expr))
raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
raises(NotImplementedError, lambda: step_response_plot(tfm))
raises(NotImplementedError, lambda: step_response_numerical_data(expr))
raises(NotImplementedError, lambda: ramp_response_plot(expr))
raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
raises(NotImplementedError, lambda: bode_plot(tfm))
# More than 1 variables
tf_a = TransferFunction(a, s + 1, s)
raises(ValueError, lambda: pole_zero_plot(tf_a))
raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
raises(ValueError, lambda: impulse_response_plot(tf_a))
raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
raises(ValueError, lambda: step_response_plot(tf_a))
raises(ValueError, lambda: step_response_numerical_data(tf_a))
raises(ValueError, lambda: ramp_response_plot(tf_a))
raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
raises(ValueError, lambda: bode_plot(tf_a))
# lower_limit > 0 for response plots
raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
# slope in ramp_response_plot() is negative
raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
def test_pole_zero():
if not matplotlib:
skip("Matplotlib not the default backend")
assert _to_tuple(*pole_zero_numerical_data(tf1)) == \
((), ((-0.24999999999999994+1.3919410907075054j), (-0.24999999999999994-1.3919410907075054j)))
assert _to_tuple(*pole_zero_numerical_data(tf2)) == \
((0.0,), ((-0.25+0.3227486121839514j), (-0.25-0.3227486121839514j)))
assert _to_tuple(*pole_zero_numerical_data(tf3)) == \
((0.0,), ((-0.5000000000000004+0.8660254037844395j),
(-0.5000000000000004-0.8660254037844395j), (0.9999999999999998+0j)))
assert _to_tuple(*pole_zero_numerical_data(tf7)) == \
(((-0.6722222222222222+0.8776898690157247j), (-0.6722222222222222-0.8776898690157247j)),
((2.220446049250313e-16+1.2797182176061541j), (2.220446049250313e-16-1.2797182176061541j),
(-0.7657146670186428+0.5744385024099056j), (-0.7657146670186428-0.5744385024099056j),
(0.7657146670186427+0.5744385024099052j), (0.7657146670186427-0.5744385024099052j)))
assert _to_tuple(*pole_zero_numerical_data(ser1)) == \
((), (5.0, 0.0, 0.0, 0.0))
assert _to_tuple(*pole_zero_numerical_data(par1)) == \
((-5.645751311064592, -0.5000000000000008, -0.3542486889354093),
((-0.24999999999999986+1.3919410907075052j),
(-0.24999999999999986-1.3919410907075052j), (-0.2499999999999998+0.32274861218395134j),
(-0.2499999999999998-0.32274861218395134j)))
def test_bode():
if not matplotlib:
skip("Matplotlib not the default backend")
def bode_phase_evalf(system, point):
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
return arg(w_expr).subs({_w: point}).evalf()
def bode_mag_evalf(system, point):
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
def test_bode_data(sys):
return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
assert test_bode_data(tf1)
assert test_bode_data(tf2)
assert test_bode_data(tf3)
assert test_bode_data(tf4)
assert test_bode_data(tf5)
def check_point_accuracy(a, b):
return all(Abs(a_i - b_i) < 1e-12 for \
a_i, b_i in zip(a, b))
def test_impulse_response():
if not matplotlib:
skip("Matplotlib not the default backend")
def impulse_res_tester(sys, expected_value):
x, y = _to_tuple(*impulse_response_numerical_data(sys,
adaptive=False, nb_of_points=10))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
-0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
795.6538758627842, 2416.9920942096983, 7342.159505206647))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
395.0617283950618, 500.0))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
-1747.0262164682233))
exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
4.147764422869658e+20))
assert impulse_res_tester(tf1, exp1)
assert impulse_res_tester(tf2, exp2)
assert impulse_res_tester(tf3, exp3)
assert impulse_res_tester(tf4, exp4)
assert impulse_res_tester(tf5, exp5)
assert impulse_res_tester(tf7, exp6)
assert impulse_res_tester(ser1, exp7)
def test_step_response():
if not matplotlib:
skip("Matplotlib not the default backend")
def step_res_tester(sys, expected_value):
x, y = _to_tuple(*step_response_numerical_data(sys,
adaptive=False, nb_of_points=10))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
0.4486997874319281, 0.4839358435839171))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
-0.003636420058445484))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
0.49997448824584123, 0.5000039745919259))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
2447.387582370878))
assert step_res_tester(tf1, exp1)
assert step_res_tester(tf2, exp2)
assert step_res_tester(tf3, exp3)
assert step_res_tester(tf4, exp4)
assert step_res_tester(tf5, exp5)
assert step_res_tester(ser2, exp6)
def test_ramp_response():
if not matplotlib:
skip("Matplotlib not the default backend")
def ramp_res_tester(sys, num_points, expected_value, slope=1):
x, y = _to_tuple(*ramp_response_numerical_data(sys,
slope=slope, adaptive=False, nb_of_points=num_points))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
2.7956587704217783, 3.9224897567931514, 4.85022655284895))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
1.304684417610106))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
7803.688462124678, 12500.0))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
39.09983919254265, 44.10006013058409))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
assert ramp_res_tester(tf1, 6, exp1)
assert ramp_res_tester(tf2, 10, exp2, 1.2)
assert ramp_res_tester(tf3, 10, exp3, 1.5)
assert ramp_res_tester(tf4, 10, exp4, 3)
assert ramp_res_tester(tf5, 10, exp5, 9)
assert ramp_res_tester(tf6, 10, exp6)
|
22f778191582f89ca5837e19c1828a0e146d424ca854c2f54f1a821e74308102 | from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import log
from sympy.external import import_module
from sympy.physics.quantum.density import Density, entropy, fidelity
from sympy.physics.quantum.state import Ket, TimeDepKet
from sympy.physics.quantum.qubit import Qubit
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp
from sympy.physics.quantum.spin import JzKet
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum.trace import Tr
from sympy.functions import sqrt
from sympy.testing.pytest import raises
from sympy.physics.quantum.matrixutils import scipy_sparse_matrix
from sympy.physics.quantum.tensorproduct import TensorProduct
def test_eval_args():
# check instance created
assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density)
assert isinstance(Density([Qubit('00'), 1/sqrt(2)],
[Qubit('11'), 1/sqrt(2)]), Density)
#test if Qubit object type preserved
d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)])
for (state, prob) in d.args:
assert isinstance(state, Qubit)
# check for value error, when prob is not provided
raises(ValueError, lambda: Density([Ket(0)], [Ket(1)]))
def test_doit():
x, y = symbols('x y')
A, B, C, D, E, F = symbols('A B C D E F', commutative=False)
d = Density([XKet(), 0.5], [PxKet(), 0.5])
assert (0.5*(PxKet()*Dagger(PxKet())) +
0.5*(XKet()*Dagger(XKet()))) == d.doit()
# check for kets with expr in them
d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) +
0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit()
d = Density([(A + B)*C, 1.0])
assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) +
1.0*A*C*Dagger(C)*Dagger(B) +
1.0*B*C*Dagger(C)*Dagger(A) +
1.0*B*C*Dagger(C)*Dagger(B))
# With TensorProducts as args
# Density with simple tensor products as args
t = TensorProduct(A, B, C)
d = Density([t, 1.0])
assert d.doit() == \
1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C))
# Density with multiple Tensorproducts as states
t2 = TensorProduct(A, B)
t3 = TensorProduct(C, D)
d = Density([t2, 0.5], [t3, 0.5])
assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
0.5 * TensorProduct(C*Dagger(C), D*Dagger(D)))
#Density with mixed states
d = Density([t2 + t3, 1.0])
assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) +
1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) +
1.0 * TensorProduct(C*Dagger(C), D*Dagger(D)))
#Density operators with spin states
tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1))
d = Density([tp1, 1])
# full trace
t = Tr(d)
assert t.doit() == 1
#Partial trace on density operators with spin states
t = Tr(d, [0])
assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1))
t = Tr(d, [1])
assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1))
# with another spin state
tp2 = TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))
d = Density([tp2, 1])
#full trace
t = Tr(d)
assert t.doit() == 1
#Partial trace on density operators with spin states
t = Tr(d, [0])
assert t.doit() == JzKet(S.Half, Rational(-1, 2)) * Dagger(JzKet(S.Half, Rational(-1, 2)))
t = Tr(d, [1])
assert t.doit() == JzKet(S.Half, S.Half) * Dagger(JzKet(S.Half, S.Half))
def test_apply_op():
d = Density([Ket(0), 0.5], [Ket(1), 0.5])
assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5],
[XOp()*Ket(1), 0.5])
def test_represent():
x, y = symbols('x y')
d = Density([XKet(), 0.5], [PxKet(), 0.5])
assert (represent(0.5*(PxKet()*Dagger(PxKet()))) +
represent(0.5*(XKet()*Dagger(XKet())))) == represent(d)
# check for kets with expr in them
d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) +
represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \
represent(d_with_sym)
# check when given explicit basis
assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) +
represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \
represent(d, basis=PxOp())
def test_states():
d = Density([Ket(0), 0.5], [Ket(1), 0.5])
states = d.states()
assert states[0] == Ket(0) and states[1] == Ket(1)
def test_probs():
d = Density([Ket(0), .75], [Ket(1), 0.25])
probs = d.probs()
assert probs[0] == 0.75 and probs[1] == 0.25
#probs can be symbols
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
probs = d.probs()
assert probs[0] == x and probs[1] == y
def test_get_state():
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
states = (d.get_state(0), d.get_state(1))
assert states[0] == Ket(0) and states[1] == Ket(1)
def test_get_prob():
x, y = symbols('x y')
d = Density([Ket(0), x], [Ket(1), y])
probs = (d.get_prob(0), d.get_prob(1))
assert probs[0] == x and probs[1] == y
def test_entropy():
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
d = Density((up, S.Half), (down, S.Half))
# test for density object
ent = entropy(d)
assert entropy(d) == log(2)/2
assert d.entropy() == log(2)/2
np = import_module('numpy', min_module_version='1.4.0')
if np:
#do this test only if 'numpy' is available on test machine
np_mat = represent(d, format='numpy')
ent = entropy(np_mat)
assert isinstance(np_mat, np.matrixlib.defmatrix.matrix)
assert ent.real == 0.69314718055994529
assert ent.imag == 0
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
if scipy and np:
#do this test only if numpy and scipy are available
mat = represent(d, format="scipy.sparse")
assert isinstance(mat, scipy_sparse_matrix)
assert ent.real == 0.69314718055994529
assert ent.imag == 0
def test_eval_trace():
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
d = Density((up, 0.5), (down, 0.5))
t = Tr(d)
assert t.doit() == 1
#test dummy time dependent states
class TestTimeDepKet(TimeDepKet):
def _eval_trace(self, bra, **options):
return 1
x, t = symbols('x t')
k1 = TestTimeDepKet(0, 0.5)
k2 = TestTimeDepKet(0, 1)
d = Density([k1, 0.5], [k2, 0.5])
assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) +
0.5 * OuterProduct(k2, k2.dual))
t = Tr(d)
assert t.doit() == 1
def test_fidelity():
#test with kets
up = JzKet(S.Half, S.Half)
down = JzKet(S.Half, Rational(-1, 2))
updown = (S.One/sqrt(2))*up + (S.One/sqrt(2))*down
#check with matrices
up_dm = represent(up * Dagger(up))
down_dm = represent(down * Dagger(down))
updown_dm = represent(updown * Dagger(updown))
assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
assert fidelity(up_dm, down_dm) < 1e-3
assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
#check with density
up_dm = Density([up, 1.0])
down_dm = Density([down, 1.0])
updown_dm = Density([updown, 1.0])
assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
assert abs(fidelity(up_dm, down_dm)) < 1e-3
assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
#check mixed states with density
updown2 = sqrt(3)/2*up + S.Half*down
d1 = Density([updown, 0.25], [updown2, 0.75])
d2 = Density([updown, 0.75], [updown2, 0.25])
assert abs(fidelity(d1, d2) - 0.991) < 1e-3
assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3
#using qubits/density(pure states)
state1 = Qubit('0')
state2 = Qubit('1')
state3 = S.One/sqrt(2)*state1 + S.One/sqrt(2)*state2
state4 = sqrt(Rational(2, 3))*state1 + S.One/sqrt(3)*state2
state1_dm = Density([state1, 1])
state2_dm = Density([state2, 1])
state3_dm = Density([state3, 1])
assert fidelity(state1_dm, state1_dm) == 1
assert fidelity(state1_dm, state2_dm) == 0
assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3
assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3
#using qubits/density(mixed states)
d1 = Density([state3, 0.70], [state4, 0.30])
d2 = Density([state3, 0.20], [state4, 0.80])
assert abs(fidelity(d1, d1) - 1) < 1e-3
assert abs(fidelity(d1, d2) - 0.996) < 1e-3
assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3
#TODO: test for invalid arguments
# non-square matrix
mat1 = [[0, 0],
[0, 0],
[0, 0]]
mat2 = [[0, 0],
[0, 0]]
raises(ValueError, lambda: fidelity(mat1, mat2))
# unequal dimensions
mat1 = [[0, 0],
[0, 0]]
mat2 = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
raises(ValueError, lambda: fidelity(mat1, mat2))
# unsupported data-type
x, y = 1, 2 # random values that is not a matrix
raises(ValueError, lambda: fidelity(x, y))
|
ac473f722ac826fa14d7100db8e4e432324776be8396e3f827db160f60fc5e97 | from sympy.core.numbers import (Float, I, Integer)
from sympy.matrices.dense import Matrix
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.represent import (represent, rep_innerproduct,
rep_expectation, enumerate_states)
from sympy.physics.quantum.state import Bra, Ket
from sympy.physics.quantum.operator import Operator, OuterProduct
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.tensorproduct import matrix_tensor_product
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.matrixutils import (numpy_ndarray,
scipy_sparse_matrix, to_numpy,
to_scipy_sparse, to_sympy)
from sympy.physics.quantum.cartesian import XKet, XOp, XBra
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.operatorset import operators_to_state
Amat = Matrix([[1, I], [-I, 1]])
Bmat = Matrix([[1, 2], [3, 4]])
Avec = Matrix([[1], [I]])
class AKet(Ket):
@classmethod
def dual_class(self):
return ABra
def _represent_default_basis(self, **options):
return self._represent_AOp(None, **options)
def _represent_AOp(self, basis, **options):
return Avec
class ABra(Bra):
@classmethod
def dual_class(self):
return AKet
class AOp(Operator):
def _represent_default_basis(self, **options):
return self._represent_AOp(None, **options)
def _represent_AOp(self, basis, **options):
return Amat
class BOp(Operator):
def _represent_default_basis(self, **options):
return self._represent_AOp(None, **options)
def _represent_AOp(self, basis, **options):
return Bmat
k = AKet('a')
b = ABra('a')
A = AOp('A')
B = BOp('B')
_tests = [
# Bra
(b, Dagger(Avec)),
(Dagger(b), Avec),
# Ket
(k, Avec),
(Dagger(k), Dagger(Avec)),
# Operator
(A, Amat),
(Dagger(A), Dagger(Amat)),
# OuterProduct
(OuterProduct(k, b), Avec*Avec.H),
# TensorProduct
(TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)),
# Pow
(A**2, Amat**2),
# Add/Mul
(A*B + 2*A, Amat*Bmat + 2*Amat),
# Commutator
(Commutator(A, B), Amat*Bmat - Bmat*Amat),
# AntiCommutator
(AntiCommutator(A, B), Amat*Bmat + Bmat*Amat),
# InnerProduct
(InnerProduct(b, k), (Avec.H*Avec)[0])
]
def test_format_sympy():
for test in _tests:
lhs = represent(test[0], basis=A, format='sympy')
rhs = to_sympy(test[1])
assert lhs == rhs
def test_scalar_sympy():
assert represent(Integer(1)) == Integer(1)
assert represent(Float(1.0)) == Float(1.0)
assert represent(1.0 + I) == 1.0 + I
np = import_module('numpy')
def test_format_numpy():
if not np:
skip("numpy not installed.")
for test in _tests:
lhs = represent(test[0], basis=A, format='numpy')
rhs = to_numpy(test[1])
if isinstance(lhs, numpy_ndarray):
assert (lhs == rhs).all()
else:
assert lhs == rhs
def test_scalar_numpy():
if not np:
skip("numpy not installed.")
assert represent(Integer(1), format='numpy') == 1
assert represent(Float(1.0), format='numpy') == 1.0
assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def test_format_scipy_sparse():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
for test in _tests:
lhs = represent(test[0], basis=A, format='scipy.sparse')
rhs = to_scipy_sparse(test[1])
if isinstance(lhs, scipy_sparse_matrix):
assert np.linalg.norm((lhs - rhs).todense()) == 0.0
else:
assert lhs == rhs
def test_scalar_scipy_sparse():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
assert represent(Integer(1), format='scipy.sparse') == 1
assert represent(Float(1.0), format='scipy.sparse') == 1.0
assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j
x_ket = XKet('x')
x_bra = XBra('x')
x_op = XOp('X')
def test_innerprod_represent():
assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit()
assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit()
try:
rep_innerproduct(x_op)
except TypeError:
return True
def test_operator_represent():
basis_kets = enumerate_states(operators_to_state(x_op), 1, 2)
assert rep_expectation(
x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0])
def test_enumerate_states():
test = XKet("foo")
assert enumerate_states(test, 1, 1) == [XKet("foo_1")]
assert enumerate_states(
test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
|
1d5475289d7c688a78d0e2da66f4f3e4d045ac93b0740e1c32fdf8368d432d38 | from sympy.core.mul import prod
from sympy.core.numbers import Rational
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum import Dagger, Commutator, qapply
from sympy.physics.quantum.boson import BosonOp
from sympy.physics.quantum.boson import (
BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra)
def test_bosonoperator():
a = BosonOp('a')
b = BosonOp('b')
assert isinstance(a, BosonOp)
assert isinstance(Dagger(a), BosonOp)
assert a.is_annihilation
assert not Dagger(a).is_annihilation
assert BosonOp("a") == BosonOp("a", True)
assert BosonOp("a") != BosonOp("c")
assert BosonOp("a", True) != BosonOp("a", False)
assert Commutator(a, Dagger(a)).doit() == 1
assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a
assert Dagger(exp(a)) == exp(Dagger(a))
def test_boson_states():
a = BosonOp("a")
# Fock states
n = 3
assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0
assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1
assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \
== sqrt(prod(range(1, n+1)))
# Coherent states
alpha1, alpha2 = 1.2, 4.3
assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1
assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1
assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() -
exp((alpha1 - alpha2) ** 2 * Rational(-1, 2))) < 1e-12
assert qapply(a * BosonCoherentKet(alpha1)) == \
alpha1 * BosonCoherentKet(alpha1)
|
45634855e5dbb5c178e723167b4d7278446e2a682111089ee580661b1a990d7e | from sympy.core.numbers import Integer
from sympy.core.symbol import Symbol
from sympy.physics.quantum.qexpr import QExpr, _qsympify_sequence
from sympy.physics.quantum.hilbert import HilbertSpace
from sympy.core.containers import Tuple
x = Symbol('x')
y = Symbol('y')
def test_qexpr_new():
q = QExpr(0)
assert q.label == (0,)
assert q.hilbert_space == HilbertSpace()
assert q.is_commutative is False
q = QExpr(0, 1)
assert q.label == (Integer(0), Integer(1))
q = QExpr._new_rawargs(HilbertSpace(), Integer(0), Integer(1))
assert q.label == (Integer(0), Integer(1))
assert q.hilbert_space == HilbertSpace()
def test_qexpr_commutative():
q1 = QExpr(x)
q2 = QExpr(y)
assert q1.is_commutative is False
assert q2.is_commutative is False
assert q1*q2 != q2*q1
q = QExpr._new_rawargs(0, 1, HilbertSpace())
assert q.is_commutative is False
def test_qexpr_commutative_free_symbols():
q1 = QExpr(x)
assert q1.free_symbols.pop().is_commutative is False
q2 = QExpr('q2')
assert q2.free_symbols.pop().is_commutative is False
def test_qexpr_subs():
q1 = QExpr(x, y)
assert q1.subs(x, y) == QExpr(y, y)
assert q1.subs({x: 1, y: 2}) == QExpr(1, 2)
def test_qsympify():
assert _qsympify_sequence([[1, 2], [1, 3]]) == (Tuple(1, 2), Tuple(1, 3))
assert _qsympify_sequence(([1, 2, [3, 4, [2, ]], 1], 3)) == \
(Tuple(1, 2, Tuple(3, 4, Tuple(2,)), 1), 3)
assert _qsympify_sequence((1,)) == (1,)
|
dd81ab5c2b052e12ed379311c93e5917c10bad2764bc3293bfac4a3388b68a6b | from sympy.external import import_module
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.gate import (X, Y, Z, H, CNOT,
IdentityGate, CGate, PhaseGate, TGate)
from sympy.physics.quantum.identitysearch import (generate_gate_rules,
generate_equivalent_ids, GateIdentity, bfs_identity_search,
is_scalar_sparse_matrix,
is_scalar_nonsparse_matrix, is_degenerate, is_reducible)
from sympy.testing.pytest import skip
def create_gate_sequence(qubit=0):
gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
return gates
def test_generate_gate_rules_1():
# Test with tuples
(x, y, z, h) = create_gate_sequence()
ph = PhaseGate(0)
cgate_t = CGate(0, TGate(1))
assert generate_gate_rules((x,)) == {((x,), ())}
gate_rules = {((x, x), ()),
((x,), (x,))}
assert generate_gate_rules((x, x)) == gate_rules
gate_rules = {((x, y, x), ()),
((y, x, x), ()),
((x, x, y), ()),
((y, x), (x,)),
((x, y), (x,)),
((y,), (x, x))}
assert generate_gate_rules((x, y, x)) == gate_rules
gate_rules = {((x, y, z), ()), ((y, z, x), ()), ((z, x, y), ()),
((), (x, z, y)), ((), (y, x, z)), ((), (z, y, x)),
((x,), (z, y)), ((y, z), (x,)), ((y,), (x, z)),
((z, x), (y,)), ((z,), (y, x)), ((x, y), (z,))}
actual = generate_gate_rules((x, y, z))
assert actual == gate_rules
gate_rules = {
((), (h, z, y, x)), ((), (x, h, z, y)), ((), (y, x, h, z)),
((), (z, y, x, h)), ((h,), (z, y, x)), ((x,), (h, z, y)),
((y,), (x, h, z)), ((z,), (y, x, h)), ((h, x), (z, y)),
((x, y), (h, z)), ((y, z), (x, h)), ((z, h), (y, x)),
((h, x, y), (z,)), ((x, y, z), (h,)), ((y, z, h), (x,)),
((z, h, x), (y,)), ((h, x, y, z), ()), ((x, y, z, h), ()),
((y, z, h, x), ()), ((z, h, x, y), ())}
actual = generate_gate_rules((x, y, z, h))
assert actual == gate_rules
gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
((), (ph**(-1), x, cgate_t**(-1))),
((), (x, cgate_t**(-1), ph**(-1))),
((cgate_t,), (ph**(-1), x)),
((ph,), (x, cgate_t**(-1))),
((x,), (cgate_t**(-1), ph**(-1))),
((cgate_t, x), (ph**(-1),)),
((ph, cgate_t), (x,)),
((x, ph), (cgate_t**(-1),)),
((cgate_t, x, ph), ()),
((ph, cgate_t, x), ()),
((x, ph, cgate_t), ())}
actual = generate_gate_rules((x, ph, cgate_t))
assert actual == gate_rules
gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
(Integer(1), ph**(-1)*x*cgate_t**(-1)),
(Integer(1), x*cgate_t**(-1)*ph**(-1)),
(cgate_t, ph**(-1)*x),
(ph, x*cgate_t**(-1)),
(x, cgate_t**(-1)*ph**(-1)),
(cgate_t*x, ph**(-1)),
(ph*cgate_t, x),
(x*ph, cgate_t**(-1)),
(cgate_t*x*ph, Integer(1)),
(ph*cgate_t*x, Integer(1)),
(x*ph*cgate_t, Integer(1))}
actual = generate_gate_rules((x, ph, cgate_t), return_as_muls=True)
assert actual == gate_rules
def test_generate_gate_rules_2():
# Test with Muls
(x, y, z, h) = create_gate_sequence()
ph = PhaseGate(0)
cgate_t = CGate(0, TGate(1))
# Note: 1 (type int) is not the same as 1 (type One)
expected = {(x, Integer(1))}
assert generate_gate_rules((x,), return_as_muls=True) == expected
expected = {(Integer(1), Integer(1))}
assert generate_gate_rules(x*x, return_as_muls=True) == expected
expected = {((), ())}
assert generate_gate_rules(x*x, return_as_muls=False) == expected
gate_rules = {(x*y*x, Integer(1)),
(y, Integer(1)),
(y*x, x),
(x*y, x)}
assert generate_gate_rules(x*y*x, return_as_muls=True) == gate_rules
gate_rules = {(x*y*z, Integer(1)),
(y*z*x, Integer(1)),
(z*x*y, Integer(1)),
(Integer(1), x*z*y),
(Integer(1), y*x*z),
(Integer(1), z*y*x),
(x, z*y),
(y*z, x),
(y, x*z),
(z*x, y),
(z, y*x),
(x*y, z)}
actual = generate_gate_rules(x*y*z, return_as_muls=True)
assert actual == gate_rules
gate_rules = {(Integer(1), h*z*y*x),
(Integer(1), x*h*z*y),
(Integer(1), y*x*h*z),
(Integer(1), z*y*x*h),
(h, z*y*x), (x, h*z*y),
(y, x*h*z), (z, y*x*h),
(h*x, z*y), (z*h, y*x),
(x*y, h*z), (y*z, x*h),
(h*x*y, z), (x*y*z, h),
(y*z*h, x), (z*h*x, y),
(h*x*y*z, Integer(1)),
(x*y*z*h, Integer(1)),
(y*z*h*x, Integer(1)),
(z*h*x*y, Integer(1))}
actual = generate_gate_rules(x*y*z*h, return_as_muls=True)
assert actual == gate_rules
gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
(Integer(1), ph**(-1)*x*cgate_t**(-1)),
(Integer(1), x*cgate_t**(-1)*ph**(-1)),
(cgate_t, ph**(-1)*x),
(ph, x*cgate_t**(-1)),
(x, cgate_t**(-1)*ph**(-1)),
(cgate_t*x, ph**(-1)),
(ph*cgate_t, x),
(x*ph, cgate_t**(-1)),
(cgate_t*x*ph, Integer(1)),
(ph*cgate_t*x, Integer(1)),
(x*ph*cgate_t, Integer(1))}
actual = generate_gate_rules(x*ph*cgate_t, return_as_muls=True)
assert actual == gate_rules
gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
((), (ph**(-1), x, cgate_t**(-1))),
((), (x, cgate_t**(-1), ph**(-1))),
((cgate_t,), (ph**(-1), x)),
((ph,), (x, cgate_t**(-1))),
((x,), (cgate_t**(-1), ph**(-1))),
((cgate_t, x), (ph**(-1),)),
((ph, cgate_t), (x,)),
((x, ph), (cgate_t**(-1),)),
((cgate_t, x, ph), ()),
((ph, cgate_t, x), ()),
((x, ph, cgate_t), ())}
actual = generate_gate_rules(x*ph*cgate_t)
assert actual == gate_rules
def test_generate_equivalent_ids_1():
# Test with tuples
(x, y, z, h) = create_gate_sequence()
assert generate_equivalent_ids((x,)) == {(x,)}
assert generate_equivalent_ids((x, x)) == {(x, x)}
assert generate_equivalent_ids((x, y)) == {(x, y), (y, x)}
gate_seq = (x, y, z)
gate_ids = {(x, y, z), (y, z, x), (z, x, y), (z, y, x),
(y, x, z), (x, z, y)}
assert generate_equivalent_ids(gate_seq) == gate_ids
gate_ids = {Mul(x, y, z), Mul(y, z, x), Mul(z, x, y),
Mul(z, y, x), Mul(y, x, z), Mul(x, z, y)}
assert generate_equivalent_ids(gate_seq, return_as_muls=True) == gate_ids
gate_seq = (x, y, z, h)
gate_ids = {(x, y, z, h), (y, z, h, x),
(h, x, y, z), (h, z, y, x),
(z, y, x, h), (y, x, h, z),
(z, h, x, y), (x, h, z, y)}
assert generate_equivalent_ids(gate_seq) == gate_ids
gate_seq = (x, y, x, y)
gate_ids = {(x, y, x, y), (y, x, y, x)}
assert generate_equivalent_ids(gate_seq) == gate_ids
cgate_y = CGate((1,), y)
gate_seq = (y, cgate_y, y, cgate_y)
gate_ids = {(y, cgate_y, y, cgate_y), (cgate_y, y, cgate_y, y)}
assert generate_equivalent_ids(gate_seq) == gate_ids
cnot = CNOT(1, 0)
cgate_z = CGate((0,), Z(1))
gate_seq = (cnot, h, cgate_z, h)
gate_ids = {(cnot, h, cgate_z, h), (h, cgate_z, h, cnot),
(h, cnot, h, cgate_z), (cgate_z, h, cnot, h)}
assert generate_equivalent_ids(gate_seq) == gate_ids
def test_generate_equivalent_ids_2():
# Test with Muls
(x, y, z, h) = create_gate_sequence()
assert generate_equivalent_ids((x,), return_as_muls=True) == {x}
gate_ids = {Integer(1)}
assert generate_equivalent_ids(x*x, return_as_muls=True) == gate_ids
gate_ids = {x*y, y*x}
assert generate_equivalent_ids(x*y, return_as_muls=True) == gate_ids
gate_ids = {(x, y), (y, x)}
assert generate_equivalent_ids(x*y) == gate_ids
circuit = Mul(*(x, y, z))
gate_ids = {x*y*z, y*z*x, z*x*y, z*y*x,
y*x*z, x*z*y}
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
circuit = Mul(*(x, y, z, h))
gate_ids = {x*y*z*h, y*z*h*x,
h*x*y*z, h*z*y*x,
z*y*x*h, y*x*h*z,
z*h*x*y, x*h*z*y}
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
circuit = Mul(*(x, y, x, y))
gate_ids = {x*y*x*y, y*x*y*x}
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
cgate_y = CGate((1,), y)
circuit = Mul(*(y, cgate_y, y, cgate_y))
gate_ids = {y*cgate_y*y*cgate_y, cgate_y*y*cgate_y*y}
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
cnot = CNOT(1, 0)
cgate_z = CGate((0,), Z(1))
circuit = Mul(*(cnot, h, cgate_z, h))
gate_ids = {cnot*h*cgate_z*h, h*cgate_z*h*cnot,
h*cnot*h*cgate_z, cgate_z*h*cnot*h}
assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
def test_is_scalar_nonsparse_matrix():
numqubits = 2
id_only = False
id_gate = (IdentityGate(1),)
actual = is_scalar_nonsparse_matrix(id_gate, numqubits, id_only)
assert actual is True
x0 = X(0)
xx_circuit = (x0, x0)
actual = is_scalar_nonsparse_matrix(xx_circuit, numqubits, id_only)
assert actual is True
x1 = X(1)
y1 = Y(1)
xy_circuit = (x1, y1)
actual = is_scalar_nonsparse_matrix(xy_circuit, numqubits, id_only)
assert actual is False
z1 = Z(1)
xyz_circuit = (x1, y1, z1)
actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
assert actual is True
cnot = CNOT(1, 0)
cnot_circuit = (cnot, cnot)
actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
assert actual is True
h = H(0)
hh_circuit = (h, h)
actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
assert actual is True
h1 = H(1)
xhzh_circuit = (x1, h1, z1, h1)
actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
assert actual is True
id_only = True
actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
assert actual is True
actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
assert actual is False
actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
assert actual is True
actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
assert actual is True
def test_is_scalar_sparse_matrix():
np = import_module('numpy')
if not np:
skip("numpy not installed.")
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
if not scipy:
skip("scipy not installed.")
numqubits = 2
id_only = False
id_gate = (IdentityGate(1),)
assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True
x0 = X(0)
xx_circuit = (x0, x0)
assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True
x1 = X(1)
y1 = Y(1)
xy_circuit = (x1, y1)
assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False
z1 = Z(1)
xyz_circuit = (x1, y1, z1)
assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True
cnot = CNOT(1, 0)
cnot_circuit = (cnot, cnot)
assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
h = H(0)
hh_circuit = (h, h)
assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
# NOTE:
# The elements of the sparse matrix for the following circuit
# is actually 1.0000000000000002+0.0j.
h1 = H(1)
xhzh_circuit = (x1, h1, z1, h1)
assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
id_only = True
assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False
assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
def test_is_degenerate():
(x, y, z, h) = create_gate_sequence()
gate_id = GateIdentity(x, y, z)
ids = {gate_id}
another_id = (z, y, x)
assert is_degenerate(ids, another_id) is True
def test_is_reducible():
nqubits = 2
(x, y, z, h) = create_gate_sequence()
circuit = (x, y, y)
assert is_reducible(circuit, nqubits, 1, 3) is True
circuit = (x, y, x)
assert is_reducible(circuit, nqubits, 1, 3) is False
circuit = (x, y, y, x)
assert is_reducible(circuit, nqubits, 0, 4) is True
circuit = (x, y, y, x)
assert is_reducible(circuit, nqubits, 1, 3) is True
circuit = (x, y, z, y, y)
assert is_reducible(circuit, nqubits, 1, 5) is True
def test_bfs_identity_search():
assert bfs_identity_search([], 1) == set()
(x, y, z, h) = create_gate_sequence()
gate_list = [x]
id_set = {GateIdentity(x, x)}
assert bfs_identity_search(gate_list, 1, max_depth=2) == id_set
# Set should not contain degenerate quantum circuits
gate_list = [x, y, z]
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(x, y, z)}
assert bfs_identity_search(gate_list, 1) == id_set
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(x, y, z),
GateIdentity(x, y, x, y),
GateIdentity(x, z, x, z),
GateIdentity(y, z, y, z)}
assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
gate_list = [x, y, z, h]
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(h, h),
GateIdentity(x, y, z),
GateIdentity(x, y, x, y),
GateIdentity(x, z, x, z),
GateIdentity(x, h, z, h),
GateIdentity(y, z, y, z),
GateIdentity(y, h, y, h)}
assert bfs_identity_search(gate_list, 1) == id_set
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(h, h)}
assert id_set == bfs_identity_search(gate_list, 1, max_depth=3,
identity_only=True)
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(h, h),
GateIdentity(x, y, z),
GateIdentity(x, y, x, y),
GateIdentity(x, z, x, z),
GateIdentity(x, h, z, h),
GateIdentity(y, z, y, z),
GateIdentity(y, h, y, h),
GateIdentity(x, y, h, x, h),
GateIdentity(x, z, h, y, h),
GateIdentity(y, z, h, z, h)}
assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
id_set = {GateIdentity(x, x),
GateIdentity(y, y),
GateIdentity(z, z),
GateIdentity(h, h),
GateIdentity(x, h, z, h)}
assert id_set == bfs_identity_search(gate_list, 1, max_depth=4,
identity_only=True)
cnot = CNOT(1, 0)
gate_list = [x, cnot]
id_set = {GateIdentity(x, x),
GateIdentity(cnot, cnot),
GateIdentity(x, cnot, x, cnot)}
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
cgate_x = CGate((1,), x)
gate_list = [x, cgate_x]
id_set = {GateIdentity(x, x),
GateIdentity(cgate_x, cgate_x),
GateIdentity(x, cgate_x, x, cgate_x)}
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
cgate_z = CGate((0,), Z(1))
gate_list = [cnot, cgate_z, h]
id_set = {GateIdentity(h, h),
GateIdentity(cgate_z, cgate_z),
GateIdentity(cnot, cnot),
GateIdentity(cnot, h, cgate_z, h)}
assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
s = PhaseGate(0)
t = TGate(0)
gate_list = [s, t]
id_set = {GateIdentity(s, s, s, s)}
assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
def test_bfs_identity_search_xfail():
s = PhaseGate(0)
t = TGate(0)
gate_list = [Dagger(s), t]
id_set = {GateIdentity(Dagger(s), t, t)}
assert bfs_identity_search(gate_list, 1, max_depth=3) == id_set
|
ee8057d47a169eb62d1e3001468aafff040307d07cdbd13df5f75c2736aa6b03 | from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer, Rational, pi)
from sympy.core.symbol import (Wild, symbols)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices import Matrix, ImmutableMatrix
from sympy.physics.quantum.gate import (XGate, YGate, ZGate, random_circuit,
CNOT, IdentityGate, H, X, Y, S, T, Z, SwapGate, gate_simp, gate_sort,
CNotGate, TGate, HadamardGate, PhaseGate, UGate, CGate)
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qubit import Qubit, IntQubit, qubit_to_matrix, \
matrix_to_qubit
from sympy.physics.quantum.matrixutils import matrix_to_zero
from sympy.physics.quantum.matrixcache import sqrt2_inv
from sympy.physics.quantum import Dagger
def test_gate():
"""Test a basic gate."""
h = HadamardGate(1)
assert h.min_qubits == 2
assert h.nqubits == 1
i0 = Wild('i0')
i1 = Wild('i1')
h0_w1 = HadamardGate(i0)
h0_w2 = HadamardGate(i0)
h1_w1 = HadamardGate(i1)
assert h0_w1 == h0_w2
assert h0_w1 != h1_w1
assert h1_w1 != h0_w2
cnot_10_w1 = CNOT(i1, i0)
cnot_10_w2 = CNOT(i1, i0)
cnot_01_w1 = CNOT(i0, i1)
assert cnot_10_w1 == cnot_10_w2
assert cnot_10_w1 != cnot_01_w1
assert cnot_10_w2 != cnot_01_w1
def test_UGate():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
# Test basic case where gate exists in 1-qubit space
u1 = UGate((0,), uMat)
assert represent(u1, nqubits=1) == uMat
assert qapply(u1*Qubit('0')) == a*Qubit('0') + c*Qubit('1')
assert qapply(u1*Qubit('1')) == b*Qubit('0') + d*Qubit('1')
# Test case where gate exists in a larger space
u2 = UGate((1,), uMat)
u2Rep = represent(u2, nqubits=2)
for i in range(4):
assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
def test_cgate():
"""Test the general CGate."""
# Test single control functionality
CNOTMatrix = Matrix(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
assert represent(CGate(1, XGate(0)), nqubits=2) == CNOTMatrix
# Test multiple control bit functionality
ToffoliGate = CGate((1, 2), XGate(0))
assert represent(ToffoliGate, nqubits=3) == \
Matrix(
[[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0,
1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
ToffoliGate = CGate((3, 0), XGate(1))
assert qapply(ToffoliGate*Qubit('1001')) == \
matrix_to_qubit(represent(ToffoliGate*Qubit('1001'), nqubits=4))
assert qapply(ToffoliGate*Qubit('0000')) == \
matrix_to_qubit(represent(ToffoliGate*Qubit('0000'), nqubits=4))
CYGate = CGate(1, YGate(0))
CYGate_matrix = Matrix(
((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, -I), (0, 0, I, 0)))
# Test 2 qubit controlled-Y gate decompose method.
assert represent(CYGate.decompose(), nqubits=2) == CYGate_matrix
CZGate = CGate(0, ZGate(1))
CZGate_matrix = Matrix(
((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, -1)))
assert qapply(CZGate*Qubit('11')) == -Qubit('11')
assert matrix_to_qubit(represent(CZGate*Qubit('11'), nqubits=2)) == \
-Qubit('11')
# Test 2 qubit controlled-Z gate decompose method.
assert represent(CZGate.decompose(), nqubits=2) == CZGate_matrix
CPhaseGate = CGate(0, PhaseGate(1))
assert qapply(CPhaseGate*Qubit('11')) == \
I*Qubit('11')
assert matrix_to_qubit(represent(CPhaseGate*Qubit('11'), nqubits=2)) == \
I*Qubit('11')
# Test that the dagger, inverse, and power of CGate is evaluated properly
assert Dagger(CZGate) == CZGate
assert pow(CZGate, 1) == Dagger(CZGate)
assert Dagger(CZGate) == CZGate.inverse()
assert Dagger(CPhaseGate) != CPhaseGate
assert Dagger(CPhaseGate) == CPhaseGate.inverse()
assert Dagger(CPhaseGate) == pow(CPhaseGate, -1)
assert pow(CPhaseGate, -1) == CPhaseGate.inverse()
def test_UGate_CGate_combo():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
cMat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, c, d]])
# Test basic case where gate exists in 1-qubit space.
u1 = UGate((0,), uMat)
cu1 = CGate(1, u1)
assert represent(cu1, nqubits=2) == cMat
assert qapply(cu1*Qubit('10')) == a*Qubit('10') + c*Qubit('11')
assert qapply(cu1*Qubit('11')) == b*Qubit('10') + d*Qubit('11')
assert qapply(cu1*Qubit('01')) == Qubit('01')
assert qapply(cu1*Qubit('00')) == Qubit('00')
# Test case where gate exists in a larger space.
u2 = UGate((1,), uMat)
u2Rep = represent(u2, nqubits=2)
for i in range(4):
assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
def test_UGate_OneQubitGate_combo():
v, w, f, g = symbols('v w f g')
uMat1 = ImmutableMatrix([[v, w], [f, g]])
cMat1 = Matrix([[v, w + 1, 0, 0], [f + 1, g, 0, 0], [0, 0, v, w + 1], [0, 0, f + 1, g]])
u1 = X(0) + UGate(0, uMat1)
assert represent(u1, nqubits=2) == cMat1
uMat2 = ImmutableMatrix([[1/sqrt(2), 1/sqrt(2)], [I/sqrt(2), -I/sqrt(2)]])
cMat2_1 = Matrix([[Rational(1, 2) + I/2, Rational(1, 2) - I/2],
[Rational(1, 2) - I/2, Rational(1, 2) + I/2]])
cMat2_2 = Matrix([[1, 0], [0, I]])
u2 = UGate(0, uMat2)
assert represent(H(0)*u2, nqubits=1) == cMat2_1
assert represent(u2*H(0), nqubits=1) == cMat2_2
def test_represent_hadamard():
"""Test the representation of the hadamard gate."""
circuit = HadamardGate(0)*Qubit('00')
answer = represent(circuit, nqubits=2)
# Check that the answers are same to within an epsilon.
assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0])
def test_represent_xgate():
"""Test the representation of the X gate."""
circuit = XGate(0)*Qubit('00')
answer = represent(circuit, nqubits=2)
assert Matrix([0, 1, 0, 0]) == answer
def test_represent_ygate():
"""Test the representation of the Y gate."""
circuit = YGate(0)*Qubit('00')
answer = represent(circuit, nqubits=2)
assert answer[0] == 0 and answer[1] == I and \
answer[2] == 0 and answer[3] == 0
def test_represent_zgate():
"""Test the representation of the Z gate."""
circuit = ZGate(0)*Qubit('00')
answer = represent(circuit, nqubits=2)
assert Matrix([1, 0, 0, 0]) == answer
def test_represent_phasegate():
"""Test the representation of the S gate."""
circuit = PhaseGate(0)*Qubit('01')
answer = represent(circuit, nqubits=2)
assert Matrix([0, I, 0, 0]) == answer
def test_represent_tgate():
"""Test the representation of the T gate."""
circuit = TGate(0)*Qubit('01')
assert Matrix([0, exp(I*pi/4), 0, 0]) == represent(circuit, nqubits=2)
def test_compound_gates():
"""Test a compound gate representation."""
circuit = YGate(0)*ZGate(0)*XGate(0)*HadamardGate(0)*Qubit('00')
answer = represent(circuit, nqubits=2)
assert Matrix([I/sqrt(2), I/sqrt(2), 0, 0]) == answer
def test_cnot_gate():
"""Test the CNOT gate."""
circuit = CNotGate(1, 0)
assert represent(circuit, nqubits=2) == \
Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
circuit = circuit*Qubit('111')
assert matrix_to_qubit(represent(circuit, nqubits=3)) == \
qapply(circuit)
circuit = CNotGate(1, 0)
assert Dagger(circuit) == circuit
assert Dagger(Dagger(circuit)) == circuit
assert circuit*circuit == 1
def test_gate_sort():
"""Test gate_sort."""
for g in (X, Y, Z, H, S, T):
assert gate_sort(g(2)*g(1)*g(0)) == g(0)*g(1)*g(2)
e = gate_sort(X(1)*H(0)**2*CNOT(0, 1)*X(1)*X(0))
assert e == H(0)**2*CNOT(0, 1)*X(0)*X(1)**2
assert gate_sort(Z(0)*X(0)) == -X(0)*Z(0)
assert gate_sort(Z(0)*X(0)**2) == X(0)**2*Z(0)
assert gate_sort(Y(0)*H(0)) == -H(0)*Y(0)
assert gate_sort(Y(0)*X(0)) == -X(0)*Y(0)
assert gate_sort(Z(0)*Y(0)) == -Y(0)*Z(0)
assert gate_sort(T(0)*S(0)) == S(0)*T(0)
assert gate_sort(Z(0)*S(0)) == S(0)*Z(0)
assert gate_sort(Z(0)*T(0)) == T(0)*Z(0)
assert gate_sort(Z(0)*CNOT(0, 1)) == CNOT(0, 1)*Z(0)
assert gate_sort(S(0)*CNOT(0, 1)) == CNOT(0, 1)*S(0)
assert gate_sort(T(0)*CNOT(0, 1)) == CNOT(0, 1)*T(0)
assert gate_sort(X(1)*CNOT(0, 1)) == CNOT(0, 1)*X(1)
# This takes a long time and should only be uncommented once in a while.
# nqubits = 5
# ngates = 10
# trials = 10
# for i in range(trials):
# c = random_circuit(ngates, nqubits)
# assert represent(c, nqubits=nqubits) == \
# represent(gate_sort(c), nqubits=nqubits)
def test_gate_simp():
"""Test gate_simp."""
e = H(0)*X(1)*H(0)**2*CNOT(0, 1)*X(1)**3*X(0)*Z(3)**2*S(4)**3
assert gate_simp(e) == H(0)*CNOT(0, 1)*S(4)*X(0)*Z(4)
assert gate_simp(X(0)*X(0)) == 1
assert gate_simp(Y(0)*Y(0)) == 1
assert gate_simp(Z(0)*Z(0)) == 1
assert gate_simp(H(0)*H(0)) == 1
assert gate_simp(T(0)*T(0)) == S(0)
assert gate_simp(S(0)*S(0)) == Z(0)
assert gate_simp(Integer(1)) == Integer(1)
assert gate_simp(X(0)**2 + Y(0)**2) == Integer(2)
def test_swap_gate():
"""Test the SWAP gate."""
swap_gate_matrix = Matrix(
((1, 0, 0, 0), (0, 0, 1, 0), (0, 1, 0, 0), (0, 0, 0, 1)))
assert represent(SwapGate(1, 0).decompose(), nqubits=2) == swap_gate_matrix
assert qapply(SwapGate(1, 3)*Qubit('0010')) == Qubit('1000')
nqubits = 4
for i in range(nqubits):
for j in range(i):
assert represent(SwapGate(i, j), nqubits=nqubits) == \
represent(SwapGate(i, j).decompose(), nqubits=nqubits)
def test_one_qubit_commutators():
"""Test single qubit gate commutation relations."""
for g1 in (IdentityGate, X, Y, Z, H, T, S):
for g2 in (IdentityGate, X, Y, Z, H, T, S):
e = Commutator(g1(0), g2(0))
a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
assert a == b
e = Commutator(g1(0), g2(1))
assert e.doit() == 0
def test_one_qubit_anticommutators():
"""Test single qubit gate anticommutation relations."""
for g1 in (IdentityGate, X, Y, Z, H):
for g2 in (IdentityGate, X, Y, Z, H):
e = AntiCommutator(g1(0), g2(0))
a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
assert a == b
e = AntiCommutator(g1(0), g2(1))
a = matrix_to_zero(represent(e, nqubits=2, format='sympy'))
b = matrix_to_zero(represent(e.doit(), nqubits=2, format='sympy'))
assert a == b
def test_cnot_commutators():
"""Test commutators of involving CNOT gates."""
assert Commutator(CNOT(0, 1), Z(0)).doit() == 0
assert Commutator(CNOT(0, 1), T(0)).doit() == 0
assert Commutator(CNOT(0, 1), S(0)).doit() == 0
assert Commutator(CNOT(0, 1), X(1)).doit() == 0
assert Commutator(CNOT(0, 1), CNOT(0, 1)).doit() == 0
assert Commutator(CNOT(0, 1), CNOT(0, 2)).doit() == 0
assert Commutator(CNOT(0, 2), CNOT(0, 1)).doit() == 0
assert Commutator(CNOT(1, 2), CNOT(1, 0)).doit() == 0
def test_random_circuit():
c = random_circuit(10, 3)
assert isinstance(c, Mul)
m = represent(c, nqubits=3)
assert m.shape == (8, 8)
assert isinstance(m, Matrix)
def test_hermitian_XGate():
x = XGate(1, 2)
x_dagger = Dagger(x)
assert (x == x_dagger)
def test_hermitian_YGate():
y = YGate(1, 2)
y_dagger = Dagger(y)
assert (y == y_dagger)
def test_hermitian_ZGate():
z = ZGate(1, 2)
z_dagger = Dagger(z)
assert (z == z_dagger)
def test_unitary_XGate():
x = XGate(1, 2)
x_dagger = Dagger(x)
assert (x*x_dagger == 1)
def test_unitary_YGate():
y = YGate(1, 2)
y_dagger = Dagger(y)
assert (y*y_dagger == 1)
def test_unitary_ZGate():
z = ZGate(1, 2)
z_dagger = Dagger(z)
assert (z*z_dagger == 1)
|
7d65f248c857b679e3fc67fdd202f3f18a4104116143b13058e020f66ab3b94f | from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.gate import H
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.spin import Jx, Jy, Jz, Jplus, Jminus, J2, JzKet
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.state import Ket
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.qubit import Qubit
from sympy.physics.quantum.boson import BosonOp, BosonFockKet, BosonFockBra
j, jp, m, mp = symbols("j j' m m'")
z = JzKet(1, 0)
po = JzKet(1, 1)
mo = JzKet(1, -1)
A = Operator('A')
class Foo(Operator):
def _apply_operator_JzKet(self, ket, **options):
return ket
def test_basic():
assert qapply(Jz*po) == hbar*po
assert qapply(Jx*z) == hbar*po/sqrt(2) + hbar*mo/sqrt(2)
assert qapply((Jplus + Jminus)*z/sqrt(2)) == hbar*po + hbar*mo
assert qapply(Jz*(po + mo)) == hbar*po - hbar*mo
assert qapply(Jz*po + Jz*mo) == hbar*po - hbar*mo
assert qapply(Jminus*Jminus*po) == 2*hbar**2*mo
assert qapply(Jplus**2*mo) == 2*hbar**2*po
assert qapply(Jplus**2*Jminus**2*po) == 4*hbar**4*po
def test_extra():
extra = z.dual*A*z
assert qapply(Jz*po*extra) == hbar*po*extra
assert qapply(Jx*z*extra) == (hbar*po/sqrt(2) + hbar*mo/sqrt(2))*extra
assert qapply(
(Jplus + Jminus)*z/sqrt(2)*extra) == hbar*po*extra + hbar*mo*extra
assert qapply(Jz*(po + mo)*extra) == hbar*po*extra - hbar*mo*extra
assert qapply(Jz*po*extra + Jz*mo*extra) == hbar*po*extra - hbar*mo*extra
assert qapply(Jminus*Jminus*po*extra) == 2*hbar**2*mo*extra
assert qapply(Jplus**2*mo*extra) == 2*hbar**2*po*extra
assert qapply(Jplus**2*Jminus**2*po*extra) == 4*hbar**4*po*extra
def test_innerproduct():
assert qapply(po.dual*Jz*po, ip_doit=False) == hbar*(po.dual*po)
assert qapply(po.dual*Jz*po) == hbar
def test_zero():
assert qapply(0) == 0
assert qapply(Integer(0)) == 0
def test_commutator():
assert qapply(Commutator(Jx, Jy)*Jz*po) == I*hbar**3*po
assert qapply(Commutator(J2, Jz)*Jz*po) == 0
assert qapply(Commutator(Jz, Foo('F'))*po) == 0
assert qapply(Commutator(Foo('F'), Jz)*po) == 0
def test_anticommutator():
assert qapply(AntiCommutator(Jz, Foo('F'))*po) == 2*hbar*po
assert qapply(AntiCommutator(Foo('F'), Jz)*po) == 2*hbar*po
def test_outerproduct():
e = Jz*(mo*po.dual)*Jz*po
assert qapply(e) == -hbar**2*mo
assert qapply(e, ip_doit=False) == -hbar**2*(po.dual*po)*mo
assert qapply(e).doit() == -hbar**2*mo
def test_tensorproduct():
a = BosonOp("a")
b = BosonOp("b")
ket1 = TensorProduct(BosonFockKet(1), BosonFockKet(2))
ket2 = TensorProduct(BosonFockKet(0), BosonFockKet(0))
ket3 = TensorProduct(BosonFockKet(0), BosonFockKet(2))
bra1 = TensorProduct(BosonFockBra(0), BosonFockBra(0))
bra2 = TensorProduct(BosonFockBra(1), BosonFockBra(2))
assert qapply(TensorProduct(a, b ** 2) * ket1) == sqrt(2) * ket2
assert qapply(TensorProduct(a, Dagger(b) * b) * ket1) == 2 * ket3
assert qapply(bra1 * TensorProduct(a, b * b),
dagger=True) == sqrt(2) * bra2
assert qapply(bra2 * ket1).doit() == TensorProduct(1, 1)
assert qapply(TensorProduct(a, b * b) * ket1) == sqrt(2) * ket2
assert qapply(Dagger(TensorProduct(a, b * b) * ket1),
dagger=True) == sqrt(2) * Dagger(ket2)
def test_dagger():
lhs = Dagger(Qubit(0))*Dagger(H(0))
rhs = Dagger(Qubit(1))/sqrt(2) + Dagger(Qubit(0))/sqrt(2)
assert qapply(lhs, dagger=True) == rhs
def test_issue_6073():
x, y = symbols('x y', commutative=False)
A = Ket(x, y)
B = Operator('B')
assert qapply(A) == A
assert qapply(A.dual*B) == A.dual*B
def test_density():
d = Density([Jz*mo, 0.5], [Jz*po, 0.5])
assert qapply(d) == Density([-hbar*mo, 0.5], [hbar*po, 0.5])
def test_issue3044():
expr1 = TensorProduct(Jz*JzKet(S(2),S.NegativeOne)/sqrt(2), Jz*JzKet(S.Half,S.Half))
result = Mul(S.NegativeOne, Rational(1, 4), 2**S.Half, hbar**2)
result *= TensorProduct(JzKet(2,-1), JzKet(S.Half,S.Half))
assert qapply(expr1) == result
|
6fc7812f098bf22cdef9adf44cc0e4a16b83ca6d363ef063afb6b27cbc1a47f2 | """Tests for cartesian.py"""
from sympy.core.numbers import (I, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.special.delta_functions import DiracDelta
from sympy.sets.sets import Interval
from sympy.physics.quantum import qapply, represent, L2, Dagger
from sympy.physics.quantum import Commutator, hbar
from sympy.physics.quantum.cartesian import (
XOp, YOp, ZOp, PxOp, X, Y, Z, Px, XKet, XBra, PxKet, PxBra,
PositionKet3D, PositionBra3D
)
from sympy.physics.quantum.operator import DifferentialOperator
x, y, z, x_1, x_2, x_3, y_1, z_1 = symbols('x,y,z,x_1,x_2,x_3,y_1,z_1')
px, py, px_1, px_2 = symbols('px py px_1 px_2')
def test_x():
assert X.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
assert Commutator(X, Px).doit() == I*hbar
assert qapply(X*XKet(x)) == x*XKet(x)
assert XKet(x).dual_class() == XBra
assert XBra(x).dual_class() == XKet
assert (Dagger(XKet(y))*XKet(x)).doit() == DiracDelta(x - y)
assert (PxBra(px)*XKet(x)).doit() == \
exp(-I*x*px/hbar)/sqrt(2*pi*hbar)
assert represent(XKet(x)) == DiracDelta(x - x_1)
assert represent(XBra(x)) == DiracDelta(-x + x_1)
assert XBra(x).position == x
assert represent(XOp()*XKet()) == x*DiracDelta(x - x_2)
assert represent(XOp()*XKet()*XBra('y')) == \
x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
assert represent(XBra("y")*XKet()) == DiracDelta(x - y)
assert represent(
XKet()*XBra()) == DiracDelta(x - x_2) * DiracDelta(x_1 - x)
rep_p = represent(XOp(), basis=PxOp)
assert rep_p == hbar*I*DiracDelta(px_1 - px_2)*DifferentialOperator(px_1)
assert rep_p == represent(XOp(), basis=PxOp())
assert rep_p == represent(XOp(), basis=PxKet)
assert rep_p == represent(XOp(), basis=PxKet())
assert represent(XOp()*PxKet(), basis=PxKet) == \
hbar*I*DiracDelta(px - px_2)*DifferentialOperator(px)
def test_p():
assert Px.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
assert qapply(Px*PxKet(px)) == px*PxKet(px)
assert PxKet(px).dual_class() == PxBra
assert PxBra(x).dual_class() == PxKet
assert (Dagger(PxKet(py))*PxKet(px)).doit() == DiracDelta(px - py)
assert (XBra(x)*PxKet(px)).doit() == \
exp(I*x*px/hbar)/sqrt(2*pi*hbar)
assert represent(PxKet(px)) == DiracDelta(px - px_1)
rep_x = represent(PxOp(), basis=XOp)
assert rep_x == -hbar*I*DiracDelta(x_1 - x_2)*DifferentialOperator(x_1)
assert rep_x == represent(PxOp(), basis=XOp())
assert rep_x == represent(PxOp(), basis=XKet)
assert rep_x == represent(PxOp(), basis=XKet())
assert represent(PxOp()*XKet(), basis=XKet) == \
-hbar*I*DiracDelta(x - x_2)*DifferentialOperator(x)
assert represent(XBra("y")*PxOp()*XKet(), basis=XKet) == \
-hbar*I*DiracDelta(x - y)*DifferentialOperator(x)
def test_3dpos():
assert Y.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
assert Z.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
test_ket = PositionKet3D(x, y, z)
assert qapply(X*test_ket) == x*test_ket
assert qapply(Y*test_ket) == y*test_ket
assert qapply(Z*test_ket) == z*test_ket
assert qapply(X*Y*test_ket) == x*y*test_ket
assert qapply(X*Y*Z*test_ket) == x*y*z*test_ket
assert qapply(Y*Z*test_ket) == y*z*test_ket
assert PositionKet3D() == test_ket
assert YOp() == Y
assert ZOp() == Z
assert PositionKet3D.dual_class() == PositionBra3D
assert PositionBra3D.dual_class() == PositionKet3D
other_ket = PositionKet3D(x_1, y_1, z_1)
assert (Dagger(other_ket)*test_ket).doit() == \
DiracDelta(x - x_1)*DiracDelta(y - y_1)*DiracDelta(z - z_1)
assert test_ket.position_x == x
assert test_ket.position_y == y
assert test_ket.position_z == z
assert other_ket.position_x == x_1
assert other_ket.position_y == y_1
assert other_ket.position_z == z_1
# TODO: Add tests for representations
|
090588299152a6451ee57ec0176ec4a95c19e25d19ab2725ddb758815663dc7b | from sympy.core.numbers import (I, pi)
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.qft import QFT, IQFT, RkGate
from sympy.physics.quantum.gate import (ZGate, SwapGate, HadamardGate, CGate,
PhaseGate, TGate)
from sympy.physics.quantum.qubit import Qubit
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
def test_RkGate():
x = Symbol('x')
assert RkGate(1, x).k == x
assert RkGate(1, x).targets == (1,)
assert RkGate(1, 1) == ZGate(1)
assert RkGate(2, 2) == PhaseGate(2)
assert RkGate(3, 3) == TGate(3)
assert represent(
RkGate(0, x), nqubits=1) == Matrix([[1, 0], [0, exp(2*I*pi/2**x)]])
def test_quantum_fourier():
assert QFT(0, 3).decompose() == \
SwapGate(0, 2)*HadamardGate(0)*CGate((0,), PhaseGate(1)) * \
HadamardGate(1)*CGate((0,), TGate(2))*CGate((1,), PhaseGate(2)) * \
HadamardGate(2)
assert IQFT(0, 3).decompose() == \
HadamardGate(2)*CGate((1,), RkGate(2, -2))*CGate((0,), RkGate(2, -3)) * \
HadamardGate(1)*CGate((0,), RkGate(1, -2))*HadamardGate(0)*SwapGate(0, 2)
assert represent(QFT(0, 3), nqubits=3) == \
Matrix([[exp(2*pi*I/8)**(i*j % 8)/sqrt(8) for i in range(8)] for j in range(8)])
assert QFT(0, 4).decompose() # non-trivial decomposition
assert qapply(QFT(0, 3).decompose()*Qubit(0, 0, 0)).expand() == qapply(
HadamardGate(0)*HadamardGate(1)*HadamardGate(2)*Qubit(0, 0, 0)
).expand()
def test_qft_represent():
c = QFT(0, 3)
a = represent(c, nqubits=3)
b = represent(c.decompose(), nqubits=3)
assert a.evalf(n=10) == b.evalf(n=10)
|
bb37bad801ba1f8c7631824903e118dcdb64ab0beb0c843690e36ebc8450899e | from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.qubit import IntQubit
from sympy.physics.quantum.grover import (apply_grover, superposition_basis,
OracleGate, grover_iteration, WGate)
def return_one_on_two(qubits):
return qubits == IntQubit(2, qubits.nqubits)
def return_one_on_one(qubits):
return qubits == IntQubit(1, nqubits=qubits.nqubits)
def test_superposition_basis():
nbits = 2
first_half_state = IntQubit(0, nqubits=nbits)/2 + IntQubit(1, nqubits=nbits)/2
second_half_state = IntQubit(2, nbits)/2 + IntQubit(3, nbits)/2
assert first_half_state + second_half_state == superposition_basis(nbits)
nbits = 3
firstq = (1/sqrt(8))*IntQubit(0, nqubits=nbits) + (1/sqrt(8))*IntQubit(1, nqubits=nbits)
secondq = (1/sqrt(8))*IntQubit(2, nbits) + (1/sqrt(8))*IntQubit(3, nbits)
thirdq = (1/sqrt(8))*IntQubit(4, nbits) + (1/sqrt(8))*IntQubit(5, nbits)
fourthq = (1/sqrt(8))*IntQubit(6, nbits) + (1/sqrt(8))*IntQubit(7, nbits)
assert firstq + secondq + thirdq + fourthq == superposition_basis(nbits)
def test_OracleGate():
v = OracleGate(1, lambda qubits: qubits == IntQubit(0))
assert qapply(v*IntQubit(0)) == -IntQubit(0)
assert qapply(v*IntQubit(1)) == IntQubit(1)
nbits = 2
v = OracleGate(2, return_one_on_two)
assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nqubits=nbits)
assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nqubits=nbits)
assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits)
assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits)
assert represent(OracleGate(1, lambda qubits: qubits == IntQubit(0)), nqubits=1) == \
Matrix([[-1, 0], [0, 1]])
assert represent(v, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]])
def test_WGate():
nqubits = 2
basis_states = superposition_basis(nqubits)
assert qapply(WGate(nqubits)*basis_states) == basis_states
expected = ((2/sqrt(pow(2, nqubits)))*basis_states) - IntQubit(1, nqubits=nqubits)
assert qapply(WGate(nqubits)*IntQubit(1, nqubits=nqubits)) == expected
def test_grover_iteration_1():
numqubits = 2
basis_states = superposition_basis(numqubits)
v = OracleGate(numqubits, return_one_on_one)
expected = IntQubit(1, nqubits=numqubits)
assert qapply(grover_iteration(basis_states, v)) == expected
def test_grover_iteration_2():
numqubits = 4
basis_states = superposition_basis(numqubits)
v = OracleGate(numqubits, return_one_on_two)
# After (pi/4)sqrt(pow(2, n)), IntQubit(2) should have highest prob
# In this case, after around pi times (3 or 4)
iterated = grover_iteration(basis_states, v)
iterated = qapply(iterated)
iterated = grover_iteration(iterated, v)
iterated = qapply(iterated)
iterated = grover_iteration(iterated, v)
iterated = qapply(iterated)
# In this case, probability was highest after 3 iterations
# Probability of Qubit('0010') was 251/256 (3) vs 781/1024 (4)
# Ask about measurement
expected = (-13*basis_states)/64 + 264*IntQubit(2, numqubits)/256
assert qapply(expected) == iterated
def test_grover():
nqubits = 2
assert apply_grover(return_one_on_one, nqubits) == IntQubit(1, nqubits=nqubits)
nqubits = 4
basis_states = superposition_basis(nqubits)
expected = (-13*basis_states)/64 + 264*IntQubit(2, nqubits)/256
assert apply_grover(return_one_on_two, 4) == qapply(expected)
|
0cd7c179805aff9f24486ecf339225a3ac67cde93c952880197d35b8c15162a2 | from sympy.core.singleton import S
from sympy.physics.quantum.operatorset import (
operators_to_state, state_to_operators
)
from sympy.physics.quantum.cartesian import (
XOp, XKet, PxOp, PxKet, XBra, PxBra
)
from sympy.physics.quantum.state import Ket, Bra
from sympy.physics.quantum.operator import Operator
from sympy.physics.quantum.spin import (
JxKet, JyKet, JzKet, JxBra, JyBra, JzBra,
JxOp, JyOp, JzOp, J2Op
)
from sympy.testing.pytest import raises
def test_spin():
assert operators_to_state({J2Op, JxOp}) == JxKet
assert operators_to_state({J2Op, JyOp}) == JyKet
assert operators_to_state({J2Op, JzOp}) == JzKet
assert operators_to_state({J2Op(), JxOp()}) == JxKet
assert operators_to_state({J2Op(), JyOp()}) == JyKet
assert operators_to_state({J2Op(), JzOp()}) == JzKet
assert state_to_operators(JxKet) == {J2Op, JxOp}
assert state_to_operators(JyKet) == {J2Op, JyOp}
assert state_to_operators(JzKet) == {J2Op, JzOp}
assert state_to_operators(JxBra) == {J2Op, JxOp}
assert state_to_operators(JyBra) == {J2Op, JyOp}
assert state_to_operators(JzBra) == {J2Op, JzOp}
assert state_to_operators(JxKet(S.Half, S.Half)) == {J2Op(), JxOp()}
assert state_to_operators(JyKet(S.Half, S.Half)) == {J2Op(), JyOp()}
assert state_to_operators(JzKet(S.Half, S.Half)) == {J2Op(), JzOp()}
assert state_to_operators(JxBra(S.Half, S.Half)) == {J2Op(), JxOp()}
assert state_to_operators(JyBra(S.Half, S.Half)) == {J2Op(), JyOp()}
assert state_to_operators(JzBra(S.Half, S.Half)) == {J2Op(), JzOp()}
def test_op_to_state():
assert operators_to_state(XOp) == XKet()
assert operators_to_state(PxOp) == PxKet()
assert operators_to_state(Operator) == Ket()
assert state_to_operators(operators_to_state(XOp("Q"))) == XOp("Q")
assert state_to_operators(operators_to_state(XOp())) == XOp()
raises(NotImplementedError, lambda: operators_to_state(XKet))
def test_state_to_op():
assert state_to_operators(XKet) == XOp()
assert state_to_operators(PxKet) == PxOp()
assert state_to_operators(XBra) == XOp()
assert state_to_operators(PxBra) == PxOp()
assert state_to_operators(Ket) == Operator()
assert state_to_operators(Bra) == Operator()
assert operators_to_state(state_to_operators(XKet("test"))) == XKet("test")
assert operators_to_state(state_to_operators(XBra("test"))) == XKet("test")
assert operators_to_state(state_to_operators(XKet())) == XKet()
assert operators_to_state(state_to_operators(XBra())) == XKet()
raises(NotImplementedError, lambda: state_to_operators(XOp))
|
f27767cf222c8c5e003aeffd93a62a6a9ff55d40d36e21a7bfba2725dad90560 | """Tests for piab.py"""
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.sets.sets import Interval
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum import L2, qapply, hbar, represent
from sympy.physics.quantum.piab import PIABHamiltonian, PIABKet, PIABBra, m, L
i, j, n, x = symbols('i j n x')
def test_H():
assert PIABHamiltonian('H').hilbert_space == \
L2(Interval(S.NegativeInfinity, S.Infinity))
assert qapply(PIABHamiltonian('H')*PIABKet(n)) == \
(n**2*pi**2*hbar**2)/(2*m*L**2)*PIABKet(n)
def test_states():
assert PIABKet(n).dual_class() == PIABBra
assert PIABKet(n).hilbert_space == \
L2(Interval(S.NegativeInfinity, S.Infinity))
assert represent(PIABKet(n)) == sqrt(2/L)*sin(n*pi*x/L)
assert (PIABBra(i)*PIABKet(j)).doit() == KroneckerDelta(i, j)
assert PIABBra(n).dual_class() == PIABKet
|
60c260d88d01fa220aeb5a56e167a98be9ed09333d14936eab790440cd8fdbbb | from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer)
from sympy.core.symbol import symbols
from sympy.functions.elementary.complexes import conjugate
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.dagger import adjoint, Dagger
from sympy.external import import_module
from sympy.testing.pytest import skip
from sympy.physics.quantum.operator import Operator, IdentityOperator
def test_scalars():
x = symbols('x', complex=True)
assert Dagger(x) == conjugate(x)
assert Dagger(I*x) == -I*conjugate(x)
i = symbols('i', real=True)
assert Dagger(i) == i
p = symbols('p')
assert isinstance(Dagger(p), adjoint)
i = Integer(3)
assert Dagger(i) == i
A = symbols('A', commutative=False)
assert Dagger(A).is_commutative is False
def test_matrix():
x = symbols('x')
m = Matrix([[I, x*I], [2, 4]])
assert Dagger(m) == m.H
def test_dagger_mul():
O = Operator('O')
I = IdentityOperator()
assert Dagger(O)*O == Dagger(O)*O
assert Dagger(O)*O*I == Mul(Dagger(O), O)*I
assert Dagger(O)*Dagger(O) == Dagger(O)**2
assert Dagger(O)*Dagger(I) == Dagger(O)
class Foo(Expr):
def _eval_adjoint(self):
return I
def test_eval_adjoint():
f = Foo()
d = Dagger(f)
assert d == I
np = import_module('numpy')
def test_numpy_dagger():
if not np:
skip("numpy not installed.")
a = np.matrix([[1.0, 2.0j], [-1.0j, 2.0]])
adag = a.copy().transpose().conjugate()
assert (Dagger(a) == adag).all()
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def test_scipy_sparse_dagger():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
else:
sparse = scipy.sparse
a = sparse.csr_matrix([[1.0 + 0.0j, 2.0j], [-1.0j, 2.0 + 0.0j]])
adag = a.copy().transpose().conjugate()
assert np.linalg.norm((Dagger(a) - adag).todense()) == 0.0
|
78d9c08a0669475a52dbdbc3f216e578e526094d0be9a10312559642b0bdc3c9 | from sympy.core.function import (Derivative, Function, diff)
from sympy.core.mul import Mul
from sympy.core.numbers import (Integer, pi)
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.trigonometric import sin
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.hilbert import HilbertSpace
from sympy.physics.quantum.operator import (Operator, UnitaryOperator,
HermitianOperator, OuterProduct,
DifferentialOperator,
IdentityOperator)
from sympy.physics.quantum.state import Ket, Bra, Wavefunction
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.spin import JzKet, JzBra
from sympy.physics.quantum.trace import Tr
from sympy.matrices import eye
class CustomKet(Ket):
@classmethod
def default_args(self):
return ("t",)
class CustomOp(HermitianOperator):
@classmethod
def default_args(self):
return ("T",)
t_ket = CustomKet()
t_op = CustomOp()
def test_operator():
A = Operator('A')
B = Operator('B')
C = Operator('C')
assert isinstance(A, Operator)
assert isinstance(A, QExpr)
assert A.label == (Symbol('A'),)
assert A.is_commutative is False
assert A.hilbert_space == HilbertSpace()
assert A*B != B*A
assert (A*(B + C)).expand() == A*B + A*C
assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2
assert t_op.label[0] == Symbol(t_op.default_args()[0])
assert Operator() == Operator("O")
assert A*IdentityOperator() == A
def test_operator_inv():
A = Operator('A')
assert A*A.inv() == 1
assert A.inv()*A == 1
def test_hermitian():
H = HermitianOperator('H')
assert isinstance(H, HermitianOperator)
assert isinstance(H, Operator)
assert Dagger(H) == H
assert H.inv() != H
assert H.is_commutative is False
assert Dagger(H).is_commutative is False
def test_unitary():
U = UnitaryOperator('U')
assert isinstance(U, UnitaryOperator)
assert isinstance(U, Operator)
assert U.inv() == Dagger(U)
assert U*Dagger(U) == 1
assert Dagger(U)*U == 1
assert U.is_commutative is False
assert Dagger(U).is_commutative is False
def test_identity():
I = IdentityOperator()
O = Operator('O')
x = Symbol("x")
assert isinstance(I, IdentityOperator)
assert isinstance(I, Operator)
assert I * O == O
assert O * I == O
assert I * Dagger(O) == Dagger(O)
assert Dagger(O) * I == Dagger(O)
assert isinstance(I * I, IdentityOperator)
assert isinstance(3 * I, Mul)
assert isinstance(I * x, Mul)
assert I.inv() == I
assert Dagger(I) == I
assert qapply(I * O) == O
assert qapply(O * I) == O
for n in [2, 3, 5]:
assert represent(IdentityOperator(n)) == eye(n)
def test_outer_product():
k = Ket('k')
b = Bra('b')
op = OuterProduct(k, b)
assert isinstance(op, OuterProduct)
assert isinstance(op, Operator)
assert op.ket == k
assert op.bra == b
assert op.label == (k, b)
assert op.is_commutative is False
op = k*b
assert isinstance(op, OuterProduct)
assert isinstance(op, Operator)
assert op.ket == k
assert op.bra == b
assert op.label == (k, b)
assert op.is_commutative is False
op = 2*k*b
assert op == Mul(Integer(2), k, b)
op = 2*(k*b)
assert op == Mul(Integer(2), OuterProduct(k, b))
assert Dagger(k*b) == OuterProduct(Dagger(b), Dagger(k))
assert Dagger(k*b).is_commutative is False
#test the _eval_trace
assert Tr(OuterProduct(JzKet(1, 1), JzBra(1, 1))).doit() == 1
# test scaled kets and bras
assert OuterProduct(2 * k, b) == 2 * OuterProduct(k, b)
assert OuterProduct(k, 2 * b) == 2 * OuterProduct(k, b)
# test sums of kets and bras
k1, k2 = Ket('k1'), Ket('k2')
b1, b2 = Bra('b1'), Bra('b2')
assert (OuterProduct(k1 + k2, b1) ==
OuterProduct(k1, b1) + OuterProduct(k2, b1))
assert (OuterProduct(k1, b1 + b2) ==
OuterProduct(k1, b1) + OuterProduct(k1, b2))
assert (OuterProduct(1 * k1 + 2 * k2, 3 * b1 + 4 * b2) ==
3 * OuterProduct(k1, b1) +
4 * OuterProduct(k1, b2) +
6 * OuterProduct(k2, b1) +
8 * OuterProduct(k2, b2))
def test_operator_dagger():
A = Operator('A')
B = Operator('B')
assert Dagger(A*B) == Dagger(B)*Dagger(A)
assert Dagger(A + B) == Dagger(A) + Dagger(B)
assert Dagger(A**2) == Dagger(A)**2
def test_differential_operator():
x = Symbol('x')
f = Function('f')
d = DifferentialOperator(Derivative(f(x), x), f(x))
g = Wavefunction(x**2, x)
assert qapply(d*g) == Wavefunction(2*x, x)
assert d.expr == Derivative(f(x), x)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 2), f(x))
d = DifferentialOperator(Derivative(f(x), x, 2), f(x))
g = Wavefunction(x**3, x)
assert qapply(d*g) == Wavefunction(6*x, x)
assert d.expr == Derivative(f(x), x, 2)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 3), f(x))
d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
assert d.expr == 1/x*Derivative(f(x), x)
assert d.function == f(x)
assert d.variables == (x,)
assert diff(d, x) == \
DifferentialOperator(Derivative(1/x*Derivative(f(x), x), x), f(x))
assert qapply(d*g) == Wavefunction(3*x, x)
# 2D cartesian Laplacian
y = Symbol('y')
d = DifferentialOperator(Derivative(f(x, y), x, 2) +
Derivative(f(x, y), y, 2), f(x, y))
w = Wavefunction(x**3*y**2 + y**3*x**2, x, y)
assert d.expr == Derivative(f(x, y), x, 2) + Derivative(f(x, y), y, 2)
assert d.function == f(x, y)
assert d.variables == (x, y)
assert diff(d, x) == \
DifferentialOperator(Derivative(d.expr, x), f(x, y))
assert diff(d, y) == \
DifferentialOperator(Derivative(d.expr, y), f(x, y))
assert qapply(d*w) == Wavefunction(2*x**3 + 6*x*y**2 + 6*x**2*y + 2*y**3,
x, y)
# 2D polar Laplacian (th = theta)
r, th = symbols('r th')
d = DifferentialOperator(1/r*Derivative(r*Derivative(f(r, th), r), r) +
1/(r**2)*Derivative(f(r, th), th, 2), f(r, th))
w = Wavefunction(r**2*sin(th), r, (th, 0, pi))
assert d.expr == \
1/r*Derivative(r*Derivative(f(r, th), r), r) + \
1/(r**2)*Derivative(f(r, th), th, 2)
assert d.function == f(r, th)
assert d.variables == (r, th)
assert diff(d, r) == \
DifferentialOperator(Derivative(d.expr, r), f(r, th))
assert diff(d, th) == \
DifferentialOperator(Derivative(d.expr, th), f(r, th))
assert qapply(d*w) == Wavefunction(3*sin(th), r, (th, 0, pi))
|
d7209335faee069f85ef92abc67751d8f3de765161b475827c28a71cd4187847 | from sympy.core.mul import Mul
from sympy.core.numbers import I
from sympy.matrices.dense import Matrix
from sympy.printing.latex import latex
from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply,
Operator, represent)
from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ,
SigmaMinus, SigmaPlus,
qsimplify_pauli)
from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra
from sympy.testing.pytest import raises
sx, sy, sz = SigmaX(), SigmaY(), SigmaZ()
sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1)
sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2)
sm, sp = SigmaMinus(), SigmaPlus()
sm1, sp1 = SigmaMinus(1), SigmaPlus(1)
A, B = Operator("A"), Operator("B")
def test_pauli_operators_types():
assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX)
assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY)
assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ)
assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus)
assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus)
def test_pauli_operators_commutator():
assert Commutator(sx, sy).doit() == 2 * I * sz
assert Commutator(sy, sz).doit() == 2 * I * sx
assert Commutator(sz, sx).doit() == 2 * I * sy
def test_pauli_operators_commutator_with_labels():
assert Commutator(sx1, sy1).doit() == 2 * I * sz1
assert Commutator(sy1, sz1).doit() == 2 * I * sx1
assert Commutator(sz1, sx1).doit() == 2 * I * sy1
assert Commutator(sx2, sy2).doit() == 2 * I * sz2
assert Commutator(sy2, sz2).doit() == 2 * I * sx2
assert Commutator(sz2, sx2).doit() == 2 * I * sy2
assert Commutator(sx1, sy2).doit() == 0
assert Commutator(sy1, sz2).doit() == 0
assert Commutator(sz1, sx2).doit() == 0
def test_pauli_operators_anticommutator():
assert AntiCommutator(sy, sz).doit() == 0
assert AntiCommutator(sz, sx).doit() == 0
assert AntiCommutator(sx, sm).doit() == 1
assert AntiCommutator(sx, sp).doit() == 1
def test_pauli_operators_adjoint():
assert Dagger(sx) == sx
assert Dagger(sy) == sy
assert Dagger(sz) == sz
def test_pauli_operators_adjoint_with_labels():
assert Dagger(sx1) == sx1
assert Dagger(sy1) == sy1
assert Dagger(sz1) == sz1
assert Dagger(sx1) != sx2
assert Dagger(sy1) != sy2
assert Dagger(sz1) != sz2
def test_pauli_operators_multiplication():
assert qsimplify_pauli(sx * sx) == 1
assert qsimplify_pauli(sy * sy) == 1
assert qsimplify_pauli(sz * sz) == 1
assert qsimplify_pauli(sx * sy) == I * sz
assert qsimplify_pauli(sy * sz) == I * sx
assert qsimplify_pauli(sz * sx) == I * sy
assert qsimplify_pauli(sy * sx) == - I * sz
assert qsimplify_pauli(sz * sy) == - I * sx
assert qsimplify_pauli(sx * sz) == - I * sy
def test_pauli_operators_multiplication_with_labels():
assert qsimplify_pauli(sx1 * sx1) == 1
assert qsimplify_pauli(sy1 * sy1) == 1
assert qsimplify_pauli(sz1 * sz1) == 1
assert isinstance(sx1 * sx2, Mul)
assert isinstance(sy1 * sy2, Mul)
assert isinstance(sz1 * sz2, Mul)
assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2
assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2
def test_pauli_states():
sx, sz = SigmaX(), SigmaZ()
up = SigmaZKet(0)
down = SigmaZKet(1)
assert qapply(sx * up) == down
assert qapply(sx * down) == up
assert qapply(sz * up) == up
assert qapply(sz * down) == - down
up = SigmaZBra(0)
down = SigmaZBra(1)
assert qapply(up * sx, dagger=True) == down
assert qapply(down * sx, dagger=True) == up
assert qapply(up * sz, dagger=True) == up
assert qapply(down * sz, dagger=True) == - down
assert Dagger(SigmaZKet(0)) == SigmaZBra(0)
assert Dagger(SigmaZBra(1)) == SigmaZKet(1)
raises(ValueError, lambda: SigmaZBra(2))
raises(ValueError, lambda: SigmaZKet(2))
def test_use_name():
assert sm.use_name is False
assert sm1.use_name is True
assert sx.use_name is False
assert sx1.use_name is True
def test_printing():
assert latex(sx) == r'{\sigma_x}'
assert latex(sx1) == r'{\sigma_x^{(1)}}'
assert latex(sy) == r'{\sigma_y}'
assert latex(sy1) == r'{\sigma_y^{(1)}}'
assert latex(sz) == r'{\sigma_z}'
assert latex(sz1) == r'{\sigma_z^{(1)}}'
assert latex(sm) == r'{\sigma_-}'
assert latex(sm1) == r'{\sigma_-^{(1)}}'
assert latex(sp) == r'{\sigma_+}'
assert latex(sp1) == r'{\sigma_+^{(1)}}'
def test_represent():
represent(sx) == Matrix([[0, 1], [1, 0]])
represent(sy) == Matrix([[0, -I], [I, 0]])
represent(sz) == Matrix([[1, 0], [0, -1]])
represent(sm) == Matrix([[0, 0], [1, 0]])
represent(sp) == Matrix([[0, 1], [0, 0]])
|
7245872b040588031670369849aff6eaf8bf188b2fb37dbfd0eeb6239946b2bf | from sympy.core.numbers import Integer
from sympy.core.symbol import symbols
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.anticommutator import AntiCommutator as AComm
from sympy.physics.quantum.operator import Operator
a, b, c = symbols('a,b,c')
A, B, C, D = symbols('A,B,C,D', commutative=False)
def test_anticommutator():
ac = AComm(A, B)
assert isinstance(ac, AComm)
assert ac.is_commutative is False
assert ac.subs(A, C) == AComm(C, B)
def test_commutator_identities():
assert AComm(a*A, b*B) == a*b*AComm(A, B)
assert AComm(A, A) == 2*A**2
assert AComm(A, B) == AComm(B, A)
assert AComm(a, b) == 2*a*b
assert AComm(A, B).doit() == A*B + B*A
def test_anticommutator_dagger():
assert Dagger(AComm(A, B)) == AComm(Dagger(A), Dagger(B))
class Foo(Operator):
def _eval_anticommutator_Bar(self, bar):
return Integer(0)
class Bar(Operator):
pass
class Tam(Operator):
def _eval_anticommutator_Foo(self, foo):
return Integer(1)
def test_eval_commutator():
F = Foo('F')
B = Bar('B')
T = Tam('T')
assert AComm(F, B).doit() == 0
assert AComm(B, F).doit() == 0
assert AComm(F, T).doit() == 1
assert AComm(T, F).doit() == 1
assert AComm(B, T).doit() == B*T + T*B
|
2063faadcdbe6f7c1ef5d4436e9467885021430a7f4d8b4c7c5cf1bac029af1d | from sympy.physics.quantum.hilbert import (
HilbertSpace, ComplexSpace, L2, FockSpace, TensorProductHilbertSpace,
DirectSumHilbertSpace, TensorPowerHilbertSpace
)
from sympy.core.numbers import oo
from sympy.core.symbol import Symbol
from sympy.printing.repr import srepr
from sympy.printing.str import sstr
from sympy.sets.sets import Interval
def test_hilbert_space():
hs = HilbertSpace()
assert isinstance(hs, HilbertSpace)
assert sstr(hs) == 'H'
assert srepr(hs) == 'HilbertSpace()'
def test_complex_space():
c1 = ComplexSpace(2)
assert isinstance(c1, ComplexSpace)
assert c1.dimension == 2
assert sstr(c1) == 'C(2)'
assert srepr(c1) == 'ComplexSpace(Integer(2))'
n = Symbol('n')
c2 = ComplexSpace(n)
assert isinstance(c2, ComplexSpace)
assert c2.dimension == n
assert sstr(c2) == 'C(n)'
assert srepr(c2) == "ComplexSpace(Symbol('n'))"
assert c2.subs(n, 2) == ComplexSpace(2)
def test_L2():
b1 = L2(Interval(-oo, 1))
assert isinstance(b1, L2)
assert b1.dimension is oo
assert b1.interval == Interval(-oo, 1)
x = Symbol('x', real=True)
y = Symbol('y', real=True)
b2 = L2(Interval(x, y))
assert b2.dimension is oo
assert b2.interval == Interval(x, y)
assert b2.subs(x, -1) == L2(Interval(-1, y))
def test_fock_space():
f1 = FockSpace()
f2 = FockSpace()
assert isinstance(f1, FockSpace)
assert f1.dimension is oo
assert f1 == f2
def test_tensor_product():
n = Symbol('n')
hs1 = ComplexSpace(2)
hs2 = ComplexSpace(n)
h = hs1*hs2
assert isinstance(h, TensorProductHilbertSpace)
assert h.dimension == 2*n
assert h.spaces == (hs1, hs2)
h = hs2*hs2
assert isinstance(h, TensorPowerHilbertSpace)
assert h.base == hs2
assert h.exp == 2
assert h.dimension == n**2
f = FockSpace()
h = hs1*hs2*f
assert h.dimension is oo
def test_tensor_power():
n = Symbol('n')
hs1 = ComplexSpace(2)
hs2 = ComplexSpace(n)
h = hs1**2
assert isinstance(h, TensorPowerHilbertSpace)
assert h.base == hs1
assert h.exp == 2
assert h.dimension == 4
h = hs2**3
assert isinstance(h, TensorPowerHilbertSpace)
assert h.base == hs2
assert h.exp == 3
assert h.dimension == n**3
def test_direct_sum():
n = Symbol('n')
hs1 = ComplexSpace(2)
hs2 = ComplexSpace(n)
h = hs1 + hs2
assert isinstance(h, DirectSumHilbertSpace)
assert h.dimension == 2 + n
assert h.spaces == (hs1, hs2)
f = FockSpace()
h = hs1 + f + hs2
assert h.dimension is oo
assert h.spaces == (hs1, f, hs2)
|
2ce20f34659a95f3cb2fb0cd01a88b0a9e09fc6d6666951899308dc77923aa0c | from sympy.concrete.summations import Sum
from sympy.core.function import expand
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import Matrix
from sympy.abc import alpha, beta, gamma, j, m
from sympy.physics.quantum import hbar, represent, Commutator, InnerProduct
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.cg import CG
from sympy.physics.quantum.spin import (
Jx, Jy, Jz, Jplus, Jminus, J2,
JxBra, JyBra, JzBra,
JxKet, JyKet, JzKet,
JxKetCoupled, JyKetCoupled, JzKetCoupled,
couple, uncouple,
Rotation, WignerD
)
from sympy.testing.pytest import raises, slow
j1, j2, j3, j4, m1, m2, m3, m4 = symbols('j1:5 m1:5')
j12, j13, j24, j34, j123, j134, mi, mi1, mp = symbols(
'j12 j13 j24 j34 j123 j134 mi mi1 mp')
def test_represent_spin_operators():
assert represent(Jx) == hbar*Matrix([[0, 1], [1, 0]])/2
assert represent(
Jx, j=1) == hbar*sqrt(2)*Matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])/2
assert represent(Jy) == hbar*I*Matrix([[0, -1], [1, 0]])/2
assert represent(Jy, j=1) == hbar*I*sqrt(2)*Matrix([[0, -1, 0], [1,
0, -1], [0, 1, 0]])/2
assert represent(Jz) == hbar*Matrix([[1, 0], [0, -1]])/2
assert represent(
Jz, j=1) == hbar*Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]])
def test_represent_spin_states():
# Jx basis
assert represent(JxKet(S.Half, S.Half), basis=Jx) == Matrix([1, 0])
assert represent(JxKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, 1])
assert represent(JxKet(1, 1), basis=Jx) == Matrix([1, 0, 0])
assert represent(JxKet(1, 0), basis=Jx) == Matrix([0, 1, 0])
assert represent(JxKet(1, -1), basis=Jx) == Matrix([0, 0, 1])
assert represent(
JyKet(S.Half, S.Half), basis=Jx) == Matrix([exp(-I*pi/4), 0])
assert represent(
JyKet(S.Half, Rational(-1, 2)), basis=Jx) == Matrix([0, exp(I*pi/4)])
assert represent(JyKet(1, 1), basis=Jx) == Matrix([-I, 0, 0])
assert represent(JyKet(1, 0), basis=Jx) == Matrix([0, 1, 0])
assert represent(JyKet(1, -1), basis=Jx) == Matrix([0, 0, I])
assert represent(
JzKet(S.Half, S.Half), basis=Jx) == sqrt(2)*Matrix([-1, 1])/2
assert represent(
JzKet(S.Half, Rational(-1, 2)), basis=Jx) == sqrt(2)*Matrix([-1, -1])/2
assert represent(JzKet(1, 1), basis=Jx) == Matrix([1, -sqrt(2), 1])/2
assert represent(JzKet(1, 0), basis=Jx) == sqrt(2)*Matrix([1, 0, -1])/2
assert represent(JzKet(1, -1), basis=Jx) == Matrix([1, sqrt(2), 1])/2
# Jy basis
assert represent(
JxKet(S.Half, S.Half), basis=Jy) == Matrix([exp(I*pi*Rational(-3, 4)), 0])
assert represent(
JxKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, exp(I*pi*Rational(3, 4))])
assert represent(JxKet(1, 1), basis=Jy) == Matrix([I, 0, 0])
assert represent(JxKet(1, 0), basis=Jy) == Matrix([0, 1, 0])
assert represent(JxKet(1, -1), basis=Jy) == Matrix([0, 0, -I])
assert represent(JyKet(S.Half, S.Half), basis=Jy) == Matrix([1, 0])
assert represent(JyKet(S.Half, Rational(-1, 2)), basis=Jy) == Matrix([0, 1])
assert represent(JyKet(1, 1), basis=Jy) == Matrix([1, 0, 0])
assert represent(JyKet(1, 0), basis=Jy) == Matrix([0, 1, 0])
assert represent(JyKet(1, -1), basis=Jy) == Matrix([0, 0, 1])
assert represent(
JzKet(S.Half, S.Half), basis=Jy) == sqrt(2)*Matrix([-1, I])/2
assert represent(
JzKet(S.Half, Rational(-1, 2)), basis=Jy) == sqrt(2)*Matrix([I, -1])/2
assert represent(JzKet(1, 1), basis=Jy) == Matrix([1, -I*sqrt(2), -1])/2
assert represent(
JzKet(1, 0), basis=Jy) == Matrix([-sqrt(2)*I, 0, -sqrt(2)*I])/2
assert represent(JzKet(1, -1), basis=Jy) == Matrix([-1, -sqrt(2)*I, 1])/2
# Jz basis
assert represent(
JxKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([1, 1])/2
assert represent(
JxKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-1, 1])/2
assert represent(JxKet(1, 1), basis=Jz) == Matrix([1, sqrt(2), 1])/2
assert represent(JxKet(1, 0), basis=Jz) == sqrt(2)*Matrix([-1, 0, 1])/2
assert represent(JxKet(1, -1), basis=Jz) == Matrix([1, -sqrt(2), 1])/2
assert represent(
JyKet(S.Half, S.Half), basis=Jz) == sqrt(2)*Matrix([-1, -I])/2
assert represent(
JyKet(S.Half, Rational(-1, 2)), basis=Jz) == sqrt(2)*Matrix([-I, -1])/2
assert represent(JyKet(1, 1), basis=Jz) == Matrix([1, sqrt(2)*I, -1])/2
assert represent(JyKet(1, 0), basis=Jz) == sqrt(2)*Matrix([I, 0, I])/2
assert represent(JyKet(1, -1), basis=Jz) == Matrix([-1, sqrt(2)*I, 1])/2
assert represent(JzKet(S.Half, S.Half), basis=Jz) == Matrix([1, 0])
assert represent(JzKet(S.Half, Rational(-1, 2)), basis=Jz) == Matrix([0, 1])
assert represent(JzKet(1, 1), basis=Jz) == Matrix([1, 0, 0])
assert represent(JzKet(1, 0), basis=Jz) == Matrix([0, 1, 0])
assert represent(JzKet(1, -1), basis=Jz) == Matrix([0, 0, 1])
def test_represent_uncoupled_states():
# Jx basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jx) == \
Matrix([-I, 0, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jx) == \
Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([S.Half, S.Half, Rational(-1, 2), Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jx) == \
Matrix([S.Half, Rational(-1, 2), S.Half, Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jx) == \
Matrix([S.Half, S.Half, S.Half, S.Half])
# Jy basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jy) == \
Matrix([I, 0, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jy) == \
Matrix([S.Half, -I/2, -I/2, Rational(-1, 2)])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([-I/2, S.Half, Rational(-1, 2), -I/2])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jy) == \
Matrix([-I/2, Rational(-1, 2), S.Half, -I/2])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jy) == \
Matrix([Rational(-1, 2), -I/2, -I/2, S.Half])
# Jz basis
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, S.Half)), basis=Jz) == \
Matrix([S.Half, S.Half, S.Half, S.Half])
assert represent(TensorProduct(JxKet(S.Half, S.Half), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([Rational(-1, 2), S.Half, Rational(-1, 2), S.Half])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, S.Half)), basis=Jz) == \
Matrix([Rational(-1, 2), Rational(-1, 2), S.Half, S.Half])
assert represent(TensorProduct(JxKet(S.Half, Rational(-1, 2)), JxKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([S.Half, Rational(-1, 2), Rational(-1, 2), S.Half])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, S.Half)), basis=Jz) == \
Matrix([S.Half, I/2, I/2, Rational(-1, 2)])
assert represent(TensorProduct(JyKet(S.Half, S.Half), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([I/2, S.Half, Rational(-1, 2), I/2])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, S.Half)), basis=Jz) == \
Matrix([I/2, Rational(-1, 2), S.Half, I/2])
assert represent(TensorProduct(JyKet(S.Half, Rational(-1, 2)), JyKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([Rational(-1, 2), I/2, I/2, S.Half])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), basis=Jz) == \
Matrix([0, 0, 0, 1])
def test_represent_coupled_states():
# Jx basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, -I, 0, 0])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, S.Half, -sqrt(2)/2, S.Half])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, sqrt(2)/2, 0, -sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jx) == \
Matrix([0, S.Half, sqrt(2)/2, S.Half])
# Jy basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, I, 0, 0])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, S.Half, -I*sqrt(2)/2, Rational(-1, 2)])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, -I*sqrt(2)/2, 0, -I*sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jy) == \
Matrix([0, Rational(-1, 2), -I*sqrt(2)/2, S.Half])
# Jz basis
assert represent(JxKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, sqrt(2)/2, S.Half])
assert represent(JxKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, -sqrt(2)/2, 0, sqrt(2)/2])
assert represent(JxKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, -sqrt(2)/2, S.Half])
assert represent(JyKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, S.Half, I*sqrt(2)/2, Rational(-1, 2)])
assert represent(JyKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, I*sqrt(2)/2, 0, I*sqrt(2)/2])
assert represent(JyKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, Rational(-1, 2), I*sqrt(2)/2, S.Half])
assert represent(JzKetCoupled(0, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(JzKetCoupled(1, 0, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(JzKetCoupled(1, -1, (S.Half, S.Half)), basis=Jz) == \
Matrix([0, 0, 0, 1])
def test_represent_rotation():
assert represent(Rotation(0, pi/2, 0)) == \
Matrix(
[[WignerD(
S(
1)/2, S(
1)/2, S(
1)/2, 0, pi/2, 0), WignerD(
S.Half, S.Half, Rational(-1, 2), 0, pi/2, 0)],
[WignerD(S.Half, Rational(-1, 2), S.Half, 0, pi/2, 0), WignerD(S.Half, Rational(-1, 2), Rational(-1, 2), 0, pi/2, 0)]])
assert represent(Rotation(0, pi/2, 0), doit=True) == \
Matrix([[sqrt(2)/2, -sqrt(2)/2],
[sqrt(2)/2, sqrt(2)/2]])
def test_rewrite_same():
# Rewrite to same basis
assert JxBra(1, 1).rewrite('Jx') == JxBra(1, 1)
assert JxBra(j, m).rewrite('Jx') == JxBra(j, m)
assert JxKet(1, 1).rewrite('Jx') == JxKet(1, 1)
assert JxKet(j, m).rewrite('Jx') == JxKet(j, m)
def test_rewrite_Bra():
# Numerical
assert JxBra(1, 1).rewrite('Jy') == -I*JyBra(1, 1)
assert JxBra(1, 0).rewrite('Jy') == JyBra(1, 0)
assert JxBra(1, -1).rewrite('Jy') == I*JyBra(1, -1)
assert JxBra(1, 1).rewrite(
'Jz') == JzBra(1, 1)/2 + JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2
assert JxBra(
1, 0).rewrite('Jz') == -sqrt(2)*JzBra(1, 1)/2 + sqrt(2)*JzBra(1, -1)/2
assert JxBra(1, -1).rewrite(
'Jz') == JzBra(1, 1)/2 - JzBra(1, 0)/sqrt(2) + JzBra(1, -1)/2
assert JyBra(1, 1).rewrite('Jx') == I*JxBra(1, 1)
assert JyBra(1, 0).rewrite('Jx') == JxBra(1, 0)
assert JyBra(1, -1).rewrite('Jx') == -I*JxBra(1, -1)
assert JyBra(1, 1).rewrite(
'Jz') == JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 - JzBra(1, -1)/2
assert JyBra(1, 0).rewrite(
'Jz') == -sqrt(2)*I*JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, -1)/2
assert JyBra(1, -1).rewrite(
'Jz') == -JzBra(1, 1)/2 - sqrt(2)*I*JzBra(1, 0)/2 + JzBra(1, -1)/2
assert JzBra(1, 1).rewrite(
'Jx') == JxBra(1, 1)/2 - sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2
assert JzBra(
1, 0).rewrite('Jx') == sqrt(2)*JxBra(1, 1)/2 - sqrt(2)*JxBra(1, -1)/2
assert JzBra(1, -1).rewrite(
'Jx') == JxBra(1, 1)/2 + sqrt(2)*JxBra(1, 0)/2 + JxBra(1, -1)/2
assert JzBra(1, 1).rewrite(
'Jy') == JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 - JyBra(1, -1)/2
assert JzBra(1, 0).rewrite(
'Jy') == sqrt(2)*I*JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, -1)/2
assert JzBra(1, -1).rewrite(
'Jy') == -JyBra(1, 1)/2 + sqrt(2)*I*JyBra(1, 0)/2 + JyBra(1, -1)/2
# Symbolic
assert JxBra(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyBra(j, mi), (mi, -j, j))
assert JxBra(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, 0, pi/2, 0) * JzBra(j, mi), (mi, -j, j))
assert JyBra(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 0, pi/2) * JxBra(j, mi), (mi, -j, j))
assert JyBra(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyBra(j, mi), (mi, -j, j))
def test_rewrite_Ket():
# Numerical
assert JxKet(1, 1).rewrite('Jy') == I*JyKet(1, 1)
assert JxKet(1, 0).rewrite('Jy') == JyKet(1, 0)
assert JxKet(1, -1).rewrite('Jy') == -I*JyKet(1, -1)
assert JxKet(1, 1).rewrite(
'Jz') == JzKet(1, 1)/2 + JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2
assert JxKet(
1, 0).rewrite('Jz') == -sqrt(2)*JzKet(1, 1)/2 + sqrt(2)*JzKet(1, -1)/2
assert JxKet(1, -1).rewrite(
'Jz') == JzKet(1, 1)/2 - JzKet(1, 0)/sqrt(2) + JzKet(1, -1)/2
assert JyKet(1, 1).rewrite('Jx') == -I*JxKet(1, 1)
assert JyKet(1, 0).rewrite('Jx') == JxKet(1, 0)
assert JyKet(1, -1).rewrite('Jx') == I*JxKet(1, -1)
assert JyKet(1, 1).rewrite(
'Jz') == JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 - JzKet(1, -1)/2
assert JyKet(1, 0).rewrite(
'Jz') == sqrt(2)*I*JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, -1)/2
assert JyKet(1, -1).rewrite(
'Jz') == -JzKet(1, 1)/2 + sqrt(2)*I*JzKet(1, 0)/2 + JzKet(1, -1)/2
assert JzKet(1, 1).rewrite(
'Jx') == JxKet(1, 1)/2 - sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2
assert JzKet(
1, 0).rewrite('Jx') == sqrt(2)*JxKet(1, 1)/2 - sqrt(2)*JxKet(1, -1)/2
assert JzKet(1, -1).rewrite(
'Jx') == JxKet(1, 1)/2 + sqrt(2)*JxKet(1, 0)/2 + JxKet(1, -1)/2
assert JzKet(1, 1).rewrite(
'Jy') == JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 - JyKet(1, -1)/2
assert JzKet(1, 0).rewrite(
'Jy') == -sqrt(2)*I*JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, -1)/2
assert JzKet(1, -1).rewrite(
'Jy') == -JyKet(1, 1)/2 - sqrt(2)*I*JyKet(1, 0)/2 + JyKet(1, -1)/2
# Symbolic
assert JxKet(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKet(j, mi), (mi, -j, j))
assert JxKet(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, 0, pi/2, 0) * JzKet(j, mi), (mi, -j, j))
assert JyKet(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 0, pi/2) * JxKet(j, mi), (mi, -j, j))
assert JyKet(j, m).rewrite('Jz') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi), (mi, -j, j))
def test_rewrite_uncoupled_state():
# Numerical
assert TensorProduct(JyKet(1, 1), JxKet(
1, 1)).rewrite('Jx') == -I*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert TensorProduct(JyKet(1, 0), JxKet(
1, 1)).rewrite('Jx') == TensorProduct(JxKet(1, 0), JxKet(1, 1))
assert TensorProduct(JyKet(1, -1), JxKet(
1, 1)).rewrite('Jx') == I*TensorProduct(JxKet(1, -1), JxKet(1, 1))
assert TensorProduct(JzKet(1, 1), JxKet(1, 1)).rewrite('Jx') == \
TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 - sqrt(2)*TensorProduct(JxKet(
1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JzKet(1, 0), JxKet(1, 1)).rewrite('Jx') == \
-sqrt(2)*TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt(
2)*TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JzKet(1, -1), JxKet(1, 1)).rewrite('Jx') == \
TensorProduct(JxKet(1, -1), JxKet(1, 1))/2 + sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2 + TensorProduct(JxKet(1, 1), JxKet(1, 1))/2
assert TensorProduct(JxKet(1, 1), JyKet(
1, 1)).rewrite('Jy') == I*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert TensorProduct(JxKet(1, 0), JyKet(
1, 1)).rewrite('Jy') == TensorProduct(JyKet(1, 0), JyKet(1, 1))
assert TensorProduct(JxKet(1, -1), JyKet(
1, 1)).rewrite('Jy') == -I*TensorProduct(JyKet(1, -1), JyKet(1, 1))
assert TensorProduct(JzKet(1, 1), JyKet(1, 1)).rewrite('Jy') == \
-TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 + TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JzKet(1, 0), JyKet(1, 1)).rewrite('Jy') == \
-sqrt(2)*I*TensorProduct(JyKet(1, -1), JyKet(
1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JzKet(1, -1), JyKet(1, 1)).rewrite('Jy') == \
TensorProduct(JyKet(1, -1), JyKet(1, 1))/2 - sqrt(2)*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2 - TensorProduct(JyKet(1, 1), JyKet(1, 1))/2
assert TensorProduct(JxKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JxKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(
1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JxKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 - sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, 1), JzKet(1, 1)).rewrite('Jz') == \
-TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 + TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, 0), JzKet(1, 1)).rewrite('Jz') == \
sqrt(2)*I*TensorProduct(JzKet(1, -1), JzKet(
1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
assert TensorProduct(JyKet(1, -1), JzKet(1, 1)).rewrite('Jz') == \
TensorProduct(JzKet(1, -1), JzKet(1, 1))/2 + sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2 - TensorProduct(JzKet(1, 1), JzKet(1, 1))/2
# Symbolic
assert TensorProduct(JyKet(j1, m1), JxKet(j2, m2)).rewrite('Jy') == \
TensorProduct(JyKet(j1, m1), Sum(
WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * JyKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JzKet(j1, m1), JxKet(j2, m2)).rewrite('Jz') == \
TensorProduct(JzKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, pi/2, 0) * JzKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JxKet(j1, m1), JyKet(j2, m2)).rewrite('Jx') == \
TensorProduct(JxKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, 0, pi/2) * JxKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JzKet(j1, m1), JyKet(j2, m2)).rewrite('Jz') == \
TensorProduct(JzKet(j1, m1), Sum(WignerD(
j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) * JzKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JxKet(j1, m1), JzKet(j2, m2)).rewrite('Jx') == \
TensorProduct(JxKet(j1, m1), Sum(
WignerD(j2, mi, m2, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi), (mi, -j2, j2)))
assert TensorProduct(JyKet(j1, m1), JzKet(j2, m2)).rewrite('Jy') == \
TensorProduct(JyKet(j1, m1), Sum(WignerD(
j2, mi, m2, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi), (mi, -j2, j2)))
def test_rewrite_coupled_state():
# Numerical
assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S.Half, S.Half))
assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \
-I*JxKetCoupled(1, 1, (S.Half, S.Half))
assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 0, (S.Half, S.Half))
assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \
I*JxKetCoupled(1, -1, (S.Half, S.Half))
assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S.Half, S.Half))
assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JxKetCoupled(1, 0, (
S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jx') == \
sqrt(2)*JxKetCoupled(1, 1, (S(
1)/2, S.Half))/2 - sqrt(2)*JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JxKetCoupled(1, 0, (
S.Half, S.Half))/2 + JxKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S.Half, S.Half))
assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \
I*JyKetCoupled(1, 1, (S.Half, S.Half))
assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(1, 0, (S.Half, S.Half))
assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \
-I*JyKetCoupled(1, -1, (S.Half, S.Half))
assert JzKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S.Half, S.Half))
assert JzKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jy') == \
JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (
S.Half, S.Half))/2 - JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jy') == \
-I*sqrt(2)*JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(
2)*JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JzKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jy') == \
-JyKetCoupled(1, 1, (S.Half, S.Half))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (S.Half, S.Half))/2 + JyKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S.Half, S.Half))
assert JxKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \
-sqrt(2)*JzKetCoupled(1, 1, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JxKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 - sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(0, 0, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S.Half, S.Half))
assert JyKetCoupled(1, 1, (S.Half, S.Half)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (
S.Half, S.Half))/2 - JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(1, 0, (S.Half, S.Half)).rewrite('Jz') == \
I*sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(
2)*JzKetCoupled(1, -1, (S.Half, S.Half))/2
assert JyKetCoupled(1, -1, (S.Half, S.Half)).rewrite('Jz') == \
-JzKetCoupled(1, 1, (S.Half, S.Half))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2 + JzKetCoupled(1, -1, (S.Half, S.Half))/2
# Symbolic
assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \
Sum(WignerD(j, mi, m, 0, 0, pi/2) * JxKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jx') == \
Sum(WignerD(j, mi, m, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), 0, 0) * JyKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), pi/2, pi/2) * JyKetCoupled(j,
mi, (j1, j2)), (mi, -j, j))
assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \
Sum(WignerD(j, mi, m, 0, pi/2, 0) * JzKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JyKetCoupled(j, m, (j1, j2)).rewrite('Jz') == \
Sum(WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) * JzKetCoupled(
j, mi, (j1, j2)), (mi, -j, j))
def test_innerproducts_of_rewritten_states():
# Numerical
assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 1)*JxKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JxBra(1, 0)*JxKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JxBra(1, -1)*JxKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jx')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 1)*JyKet(1, 1).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, 0)*JyKet(1, 0).rewrite('Jz')).doit() == 1
assert qapply(JyBra(1, -1)*JyKet(1, -1).rewrite('Jz')).doit() == 1
assert qapply(JzBra(1, 1)*JzKet(1, 1).rewrite('Jy')).doit() == 1
assert qapply(JzBra(1, 0)*JzKet(1, 0).rewrite('Jy')).doit() == 1
assert qapply(JzBra(1, -1)*JzKet(1, -1).rewrite('Jy')).doit() == 1
assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 1)*JxKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JxBra(1, 1)*JxKet(1, -1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 1)*JyKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JyBra(1, 1)*JyKet(1, -1).rewrite('Jz')) == 0
assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 1)*JzKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JzBra(1, 1)*JzKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, 1).rewrite('Jz')) == 0
assert qapply(JxBra(1, 0)*JxKet(1, -1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jx')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, 1).rewrite('Jz')) == 0
assert qapply(JyBra(1, 0)*JyKet(1, -1).rewrite('Jz')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jx')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, 1).rewrite('Jy')) == 0
assert qapply(JzBra(1, 0)*JzKet(1, -1).rewrite('Jy')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jy')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jy')).doit() == 0
assert qapply(JxBra(1, -1)*JxKet(1, 1).rewrite('Jz')) == 0
assert qapply(JxBra(1, -1)*JxKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jx')) == 0
assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JyBra(1, -1)*JyKet(1, 1).rewrite('Jz')) == 0
assert qapply(JyBra(1, -1)*JyKet(1, 0).rewrite('Jz')).doit() == 0
assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jx')) == 0
assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jx')).doit() == 0
assert qapply(JzBra(1, -1)*JzKet(1, 1).rewrite('Jy')) == 0
assert qapply(JzBra(1, -1)*JzKet(1, 0).rewrite('Jy')).doit() == 0
def test_uncouple_2_coupled_states():
# j1=1/2, j2=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple(
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)) )))
# j1=1, j2=1
assert TensorProduct(JzKet(1, 1), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, 1), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, 1), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 1), JzKet(1, -1)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, 0), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, 0), JzKet(1, -1)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, 1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 1)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, 0)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, 0)) )))
assert TensorProduct(JzKet(1, -1), JzKet(1, -1)) == \
expand(uncouple(couple( TensorProduct(JzKet(1, -1), JzKet(1, -1)) )))
def test_uncouple_3_coupled_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/
2), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
# Coupling j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
1)/2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S(
-1)/2), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.NegativeOne/
2), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) )))
@slow
def test_uncouple_4_coupled_states():
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S(
1)/2, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(
S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) )))
# Couple j1+j3=j13, j2+j4=j24, j13+j24=j
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, S.Half)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))) == \
expand(uncouple(couple( TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (2, 4), (1, 2)) )))
def test_uncouple_2_coupled_states_numerical():
# j1=1/2, j2=1/2
assert uncouple(JzKetCoupled(0, 0, (S.Half, S.Half))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half))) == \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/2 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))
# j1=1, j2=1/2
assert uncouple(JzKetCoupled(S.Half, S.Half, (1, S.Half))) == \
-sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 - \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half))) == \
TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))) == \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half))) == \
TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2)))
# j1=1, j2=1
assert uncouple(JzKetCoupled(0, 0, (1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/3
assert uncouple(JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 - \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(1, 0, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(1, -1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 2, (1, 1))) == \
TensorProduct(JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(2, 1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert uncouple(JzKetCoupled(2, 0, (1, 1))) == \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 1))/6
assert uncouple(JzKetCoupled(2, -1, (1, 1))) == \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2 + \
sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, -2, (1, 1))) == \
TensorProduct(JzKet(1, -1), JzKet(1, -1))
def test_uncouple_3_coupled_states_numerical():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))/3 + \
sqrt(3)*TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half))) == \
TensorProduct(JzKet(
S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))
# j1=1/2, j2=1/2, j3=1
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1))) == \
TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1))) == \
TensorProduct(
JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/2
# j1=1/2, j2=1, j3=1
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/5 + \
sqrt(5)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1))) == \
-sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 - \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1))) == \
-4*sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 - \
2*sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1))) == \
-sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
2*sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 - \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
4*sqrt(5)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1))) == \
-sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/5 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/2
assert uncouple(JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3
# j1=1, j2=1, j3=1
assert uncouple(JzKetCoupled(3, 3, (1, 1, 1))) == \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (1, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (1, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/15 + \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (1, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(3, -3, (1, 1, 1))) == \
TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (1, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(2, 1, (1, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, 0, (1, 1, 1))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (1, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -2, (1, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(1, 1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/15 - \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(1, 0, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/10 - \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/10 - \
2*sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/10 - \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (1, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/30
# Defined j13
# j1=1/2, j2=1/2, j3=1, j13=1/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))/3
# j1=1/2, j2=1, j3=1, j13=1/2
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, 0))/3
assert uncouple(JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-2*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1),
JzKet(1, -1))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/3 + \
2*TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3
# j1=1, j2=1, j3=1, j13=1
assert uncouple(JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 + \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)))) == \
-TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))/2 - \
TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))/2 + \
TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))/2
def test_uncouple_4_coupled_states_numerical():
# j1=1/2, j2=1/2, j3=1, j4=1, default coupling
assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1))) == \
TensorProduct(JzKet(S.Half, -S(
1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/4 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/30 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 - \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/20 - \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/30
# j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=1
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 - \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/4
# j1=1/2, j2=1/2, j3=1, j4=1, j12=1, j34=2
assert uncouple(JzKetCoupled(3, 3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(
S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(S.Half, -S(
1)/2), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/6
assert uncouple(JzKetCoupled(2, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/12 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/3 - \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, -2, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, 1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))/5 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 1), JzKet(1, -1))/30
assert uncouple(JzKetCoupled(1, 0, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))/10 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S.Half, S.Half, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))/20 + \
sqrt(15)*TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half,
S.Half), JzKet(1, -1), JzKet(1, -1))/5
def test_uncouple_symbolic():
assert uncouple(JzKetCoupled(j, m, (j1, j2) )) == \
Sum(CG(j1, m1, j2, m2, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2)),
(m1, -j1, j1), (m2, -j2, j2))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3) )) == \
Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) )) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m) *
TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4) )) == \
Sum(CG(j1, m1, j2, m2, j1 + j2, m1 + m2) * CG(j1 + j2, m1 + m2, j3, m3, j1 + j2 + j3, m1 + m2 + m3) * CG(j1 + j2 + j3, m1 + m2 + m3, j4, m4, j, m) *
TensorProduct(
JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4))
assert uncouple(JzKetCoupled(j, m, (j1, j2, j3, j4), ((1, 3, j13), (2, 4, j24), (1, 2, j)) )) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j2, m2, j4, m4, j24, m2 + m4) * CG(j13, m1 + m3, j24, m2 + m4, j, m) *
TensorProduct(
JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)),
(m1, -j1, j1), (m2, -j2, j2), (m3, -j3, j3), (m4, -j4, j4))
def test_couple_2_states():
# j1=1/2, j2=1/2
assert JzKetCoupled(0, 0, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half)) )))
assert JzKetCoupled(1, 1, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half)) )))
# j1=1, j2=1/2
assert JzKetCoupled(S.Half, S.Half, (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (1, S.Half)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half)) )))
# j1=1, j2=1
assert JzKetCoupled(0, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (1, 1)) )))
assert JzKetCoupled(1, 1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (1, 1)) )))
assert JzKetCoupled(1, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (1, 1)) )))
assert JzKetCoupled(1, -1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (1, 1)) )))
assert JzKetCoupled(2, 2, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (1, 1)) )))
assert JzKetCoupled(2, 1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (1, 1)) )))
assert JzKetCoupled(2, 0, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (1, 1)) )))
assert JzKetCoupled(2, -1, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (1, 1)) )))
assert JzKetCoupled(2, -2, (1, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (1, 1)) )))
# j1=1/2, j2=3/2
assert JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, Rational(3, 2))) )))
assert JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, Rational(3, 2))) )))
def test_couple_3_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half)) )))
# j1=1/2, j2=1/2, j3=1
assert JzKetCoupled(0, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, 1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 2, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, 0, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, -1, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, S.Half, 1)) )))
assert JzKetCoupled(2, -2, (S.Half, S.Half, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, S.Half, 1)) )))
# Couple j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2, j13=0
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S(
1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S(
1)/2, S.Half), ((1, 3, 0), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
# j1=1, j2=1/2, j3=1, j13=1
assert JzKetCoupled(S.Half, S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (
1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, S.Half))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (
1, S.Half, 1), ((1, 3, 1), (1, 2, Rational(3, 2)))) ), ((1, 3), (1, 2)) ))
def test_couple_4_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 2, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(
uncouple( JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(2, -1, (S.Half, S.Half, S.Half, S.Half)) )))
assert JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) == \
expand(couple(uncouple(
JzKetCoupled(2, -2, (S.Half, S.Half, S.Half, S.Half)) )))
# j1=1/2, j2=1/2, j3=1/2, j4=1
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1)) )))
assert JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) == \
expand(couple(uncouple(
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S.Half, S.Half, 1)) )))
# Coupling j1+j3=j13, j2+j4=j24, j13+j24=j
# j1=1/2, j2=1/2, j3=1/2, j4=1/2, j13=1, j24=0
assert JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1/2, j3=1/2, j4=1, j13=1, j24=1/2
assert JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \
expand(couple(uncouple( JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) )), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) == \
expand(couple(uncouple( JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, S.Half)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) == \
expand(couple(uncouple( JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 3, 1), (2, 4, S.Half), (1, 2, Rational(3, 2))) ) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1, j3=1/2, j4=1, j13=0, j24=1
assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
# j1=1/2, j2=1, j3=1/2, j4=1, j13=1, j24=1
assert JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 0)) ) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 0))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S.Half, 1, S.Half, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
def test_couple_2_states_numerical():
# j1=1/2, j2=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(1, 1, (S.Half, S.Half))
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half))/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(1, -1, (S.Half, S.Half))
# j1=1, j2=1/2
assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, S.Half))) == \
JzKetCoupled(Rational(3, 2), Rational(3, 2), (1, S.Half))
assert couple(TensorProduct(JzKet(1, 1), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + sqrt(
3)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (1, S.Half))/3 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S.Half))/3 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (1, S(
1)/2))/3 + sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (1, S.Half))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(Rational(3, 2), Rational(-3, 2), (1, S.Half))
# j1=1, j2=1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(2, 2, (1, 1))
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(
1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 + sqrt(2)*JzKetCoupled(
1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(
1, 1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, 1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0))) == \
-sqrt(3)*JzKetCoupled(
0, 0, (1, 1))/3 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(
1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(0, 0, (1, 1))/3 - sqrt(2)*JzKetCoupled(
1, 0, (1, 1))/2 + sqrt(6)*JzKetCoupled(2, 0, (1, 1))/6
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(
1, -1, (1, 1))/2 + sqrt(2)*JzKetCoupled(2, -1, (1, 1))/2
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(2, -2, (1, 1))
# j1=3/2, j2=1/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, S.Half))) == \
JzKetCoupled(2, 2, (Rational(3, 2), S.Half))
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(
1, 1, (Rational(3, 2), S.Half))/2 + JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, S.Half))) == \
-JzKetCoupled(1, 1, (S(
3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, 1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S.Half))/2 + sqrt(2)*JzKetCoupled(2, 0, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(1, -1, (S(
3)/2, S.Half))/2 + sqrt(3)*JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(1, -1, (Rational(3, 2), S.Half))/2 + \
JzKetCoupled(2, -1, (Rational(3, 2), S.Half))/2
assert couple(TensorProduct(JzKet(Rational(3, 2), Rational(-3, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(2, -2, (Rational(3, 2), S.Half))
def test_couple_3_states_numerical():
# Default coupling
# j1=1/2,j2=1/2,j3=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(Rational(3, 2), S(
3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 2, 1), (1, 3, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(Rational(3, 2), -S(
3)/2, (S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2))) )
# j1=S.Half, j2=S.Half, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 2, 1), (1, 3, 2)) )
# j1=S.Half, j2=1, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(
Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1))) == \
-2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1))) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1))) == \
-2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
2, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(S(
5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 2, Rational(3, 2)), (1, 3, Rational(5, 2))) )
# j1=1, j2=1, j3=1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(3, 3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0))) == \
-JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0))) == \
-sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/5
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0))) == \
-JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 + \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 0), (1, 3, 1)) )/3 - \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/30 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1))) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/10 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 1), (1, 3, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 1)) )/5 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(3, -3, (1, 1, 1), ((1, 2, 2), (1, 3, 3)) )
# j1=S.Half, j2=S.Half, j3=Rational(3, 2)
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \
JzKetCoupled(Rational(5, 2), S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
2*sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2)))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/30 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 0), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2)))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half))) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, S.Half)) )/6 - \
2*sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/15 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2)))) == \
-sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(3, 2))) )/5 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(
3)/2), ((1, 2, 1), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2)))) == \
JzKetCoupled(Rational(5, 2), -S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 2, 1), (1, 3, Rational(5, 2))) )
# Couple j1 to j3
# j1=1/2, j2=1/2, j3=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), S(
3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 - \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.One/
2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 0), (1, 2, S.Half)) )/2 + \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.One
/2), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), -S(
3)/2, (S.Half, S.Half, S.Half), ((1, 3, 1), (1, 2, Rational(3, 2))) )
# j1=1/2, j2=1/2, j3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, 2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/2 + \
JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, S.Half), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, -1, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, -2, (S.Half, S.Half, 1), ((1, 3, Rational(3, 2)), (1, 2, 2)) )
# j 1=1/2, j 2=1, j 3=1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(
Rational(5, 2), Rational(5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, Rational(3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S.Half, (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, S.Half), (1, 2, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, 1, 1), ((1,
3, Rational(3, 2)), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(
5)/2, Rational(-5, 2), (S.Half, 1, 1), ((1, 3, Rational(3, 2)), (1, 2, Rational(5, 2))) )
# j1=1, 1, 1
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(3, 3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(6)*JzKetCoupled(2, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, 2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
2*sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/5
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 + \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 - \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 + \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, 0), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 + \
JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \
JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, 1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/6 - \
JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/2 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/5 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 0)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
sqrt(15)*JzKetCoupled(1, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/15 - \
sqrt(3)*JzKetCoupled(2, 0, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/3 + \
sqrt(10)*JzKetCoupled(3, 0, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/10
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 - \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/10 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 - \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
2*sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/3 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 0), (1, 2, 1)) )/3 - \
JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 1)) )/2 + \
sqrt(15)*JzKetCoupled(1, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 1)) )/30 - \
JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(3)*JzKetCoupled(2, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(15)*JzKetCoupled(3, -1, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/15
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 1), (1, 2, 2)) )/2 + \
sqrt(6)*JzKetCoupled(2, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 2)) )/6 + \
sqrt(3)*JzKetCoupled(3, -2, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(3, -3, (1, 1, 1), ((1, 3, 2), (1, 2, 3)) )
# j1=1/2, j2=1/2, j3=3/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(5, 2), S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 + \
3*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S.Half, S(3)/
2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/6 - \
3*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
-2*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(3)
/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(3, 2))), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/2 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(15)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), S.Half)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, S.Half)) )/6 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/5 + \
sqrt(30)*JzKetCoupled(Rational(5, 2), -S(
1)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-1, 2))), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 1), (1, 2, Rational(3, 2))) )/2 + \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(3, 2))) )/10 + \
sqrt(15)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S.Half, S(
3)/2), ((1, 3, 2), (1, 2, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(Rational(3, 2), Rational(-3, 2))), ((1, 3), (1, 2)) ) == \
JzKetCoupled(Rational(5, 2), -S(
5)/2, (S.Half, S.Half, Rational(3, 2)), ((1, 3, 2), (1, 2, Rational(5, 2))) )
def test_couple_4_states_numerical():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
JzKetCoupled(2, 2, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)),
JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 0), (1, 3, S.Half), (1, 4, 0)))/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, S.Half), (1, 4, 0)))/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 0), (1, 3, S.Half), (1, 4, 1)))/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, S.Half), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.Half),
((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)))/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (1, 3, S.Half), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half))) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))) == \
-sqrt(6)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, S.Half), (1, 4, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half))) == \
-sqrt(3)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)))) == \
JzKetCoupled(2, -2, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, 2)) )
# j1=S.Half, S.Half, S.Half, 1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
2*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/2 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/6 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1))) == \
2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, S.Half)) )/3 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/3 - \
2*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1))) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, S.Half), (1, 4, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1))) == \
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (1, 3, Rational(3, 2)), (1, 4, Rational(5, 2))) )
# Couple j1 to j2, j3 to j4
# j1=1/2, j2=1/2, j3=1/2, j4=1/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, 2, (S(
1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S.Half, S.Half, S.Half, S.One/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S.Half, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S.Half, S(
1)/2, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2))), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, -2, (S(
1)/2, S.Half, S.Half, S.Half), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
# j1=S.Half, S.Half, S.Half, 1
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(Rational(5, 2), Rational(5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 + \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 + \
JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(5)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 + \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 - \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(6)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/30 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/6 - \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 - \
sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/3 - \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 + \
sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 0), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/2 + \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/10 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S.Half, S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/2 - \
sqrt(10)*JzKetCoupled(Rational(3, 2), S.Half, (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/5 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), S.Half, (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/3 + \
JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
4*sqrt(5)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, S.Half), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
sqrt(30)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(5)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, S.Half)) )/3 + \
sqrt(2)*JzKetCoupled(S.Half, Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, S.Half)) )/6 - \
sqrt(2)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(10)*JzKetCoupled(Rational(3, 2), Rational(-1, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-1, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/10
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, S.Half), (1, 3, Rational(3, 2))) )/3 - \
2*sqrt(15)*JzKetCoupled(Rational(3, 2), Rational(-3, 2), (S.Half, S.Half, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(3, 2))) )/15 + \
sqrt(10)*JzKetCoupled(Rational(5, 2), Rational(-3, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )/5
assert couple(TensorProduct(JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(S.Half, Rational(-1, 2)), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(Rational(5, 2), Rational(-5, 2), (S.Half, S(
1)/2, S.Half, 1), ((1, 2, 1), (3, 4, Rational(3, 2)), (1, 3, Rational(5, 2))) )
def test_couple_symbolic():
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
Sum(CG(j1, m1, j2, m2, j, m1 + m2) * JzKetCoupled(j, m1 + m2, (
j1, j2)), (j, m1 + m2, j1 + j2))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3))) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j, m1 + m2 + m3) *
JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 2, j12), (1, 3, j)) ),
(j12, m1 + m2, j1 + j2), (j, m1 + m2 + m3, j12 + j3))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3)), ((1, 3), (1, 2)) ) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j2, m2, j, m1 + m2 + m3) *
JzKetCoupled(j, m1 + m2 + m3, (j1, j2, j3), ((1, 3, j13), (1, 2, j)) ),
(j13, m1 + m3, j1 + j3), (j, m1 + m2 + m3, j13 + j2))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4))) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j12, m1 + m2, j3, m3, j123, m1 + m2 + m3) * CG(j123, m1 + m2 + m3, j4, m4, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 2, j12), (1, 3, j123), (1, 4, j)) ),
(j12, m1 + m2, j1 + j2), (j123, m1 + m2 + m3, j12 + j3), (j, m1 + m2 + m3 + m4, j123 + j4))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 2), (3, 4), (1, 3)) ) == \
Sum(CG(j1, m1, j2, m2, j12, m1 + m2) * CG(j3, m3, j4, m4, j34, m3 + m4) * CG(j12, m1 + m2, j34, m3 + m4, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 2, j12), (3, 4, j34), (1, 3, j)) ),
(j12, m1 + m2, j1 + j2), (j34, m3 + m4, j3 + j4), (j, m1 + m2 + m3 + m4, j12 + j34))
assert couple(TensorProduct(JzKet(j1, m1), JzKet(j2, m2), JzKet(j3, m3), JzKet(j4, m4)), ((1, 3), (1, 4), (1, 2)) ) == \
Sum(CG(j1, m1, j3, m3, j13, m1 + m3) * CG(j13, m1 + m3, j4, m4, j134, m1 + m3 + m4) * CG(j134, m1 + m3 + m4, j2, m2, j, m1 + m2 + m3 + m4) *
JzKetCoupled(j, m1 + m2 + m3 + m4, (
j1, j2, j3, j4), ((1, 3, j13), (1, 4, j134), (1, 2, j)) ),
(j13, m1 + m3, j1 + j3), (j134, m1 + m3 + m4, j13 + j4), (j, m1 + m2 + m3 + m4, j134 + j2))
def test_innerproduct():
assert InnerProduct(JzBra(1, 1), JzKet(1, 1)).doit() == 1
assert InnerProduct(
JzBra(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))).doit() == 0
assert InnerProduct(JzBra(j, m), JzKet(j, m)).doit() == 1
assert InnerProduct(JzBra(1, 0), JyKet(1, 1)).doit() == I/sqrt(2)
assert InnerProduct(
JxBra(S.Half, S.Half), JzKet(S.Half, S.Half)).doit() == -sqrt(2)/2
assert InnerProduct(JyBra(1, 1), JzKet(1, 1)).doit() == S.Half
assert InnerProduct(JxBra(1, -1), JyKet(1, 1)).doit() == 0
def test_rotation_small_d():
# Symbolic tests
# j = 1/2
assert Rotation.d(S.Half, S.Half, S.Half, beta).doit() == cos(beta/2)
assert Rotation.d(S.Half, S.Half, Rational(-1, 2), beta).doit() == -sin(beta/2)
assert Rotation.d(S.Half, Rational(-1, 2), S.Half, beta).doit() == sin(beta/2)
assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), beta).doit() == cos(beta/2)
# j = 1
assert Rotation.d(1, 1, 1, beta).doit() == (1 + cos(beta))/2
assert Rotation.d(1, 1, 0, beta).doit() == -sin(beta)/sqrt(2)
assert Rotation.d(1, 1, -1, beta).doit() == (1 - cos(beta))/2
assert Rotation.d(1, 0, 1, beta).doit() == sin(beta)/sqrt(2)
assert Rotation.d(1, 0, 0, beta).doit() == cos(beta)
assert Rotation.d(1, 0, -1, beta).doit() == -sin(beta)/sqrt(2)
assert Rotation.d(1, -1, 1, beta).doit() == (1 - cos(beta))/2
assert Rotation.d(1, -1, 0, beta).doit() == sin(beta)/sqrt(2)
assert Rotation.d(1, -1, -1, beta).doit() == (1 + cos(beta))/2
# j = 3/2
assert Rotation.d(S(
3)/2, Rational(3, 2), Rational(3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, S.Half, beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
3)/2, Rational(-3, 2), beta).doit() == (-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, S.Half, S.Half, beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, S.Half, Rational(-1, 2), beta).doit() == (sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), S(
1)/2, Rational(-3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(3, 2), beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, S.Half, beta).doit() == (-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(-1, 2), beta).doit() == (cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
1)/2, Rational(-3, 2), beta).doit() == -sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(S(
3)/2, Rational(-3, 2), Rational(3, 2), beta).doit() == (3*sin(beta/2) - sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, S.Half, beta).doit() == sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, Rational(-1, 2), beta).doit() == sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4
assert Rotation.d(Rational(3, 2), -S(
3)/2, Rational(-3, 2), beta).doit() == (3*cos(beta/2) + cos(beta*Rational(3, 2)))/4
# j = 2
assert Rotation.d(2, 2, 2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, 2, 1, beta).doit() == -((cos(beta) + 1)*sin(beta))/2
assert Rotation.d(2, 2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, 2, -1, beta).doit() == (cos(beta) - 1)*sin(beta)/2
assert Rotation.d(2, 2, -2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, 1, 2, beta).doit() == (cos(beta) + 1)*sin(beta)/2
assert Rotation.d(2, 1, 1, beta).doit() == (cos(beta) + cos(2*beta))/2
assert Rotation.d(2, 1, 0, beta).doit() == -sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 1, -1, beta).doit() == (cos(beta) - cos(2*beta))/2
assert Rotation.d(2, 1, -2, beta).doit() == (cos(beta) - 1)*sin(beta)/2
assert Rotation.d(2, 0, 2, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, 0, 1, beta).doit() == sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 0, 0, beta).doit() == (1 + 3*cos(2*beta))/4
assert Rotation.d(2, 0, -1, beta).doit() == -sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, 0, -2, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, -1, 2, beta).doit() == (2*sin(beta) - sin(2*beta))/4
assert Rotation.d(2, -1, 1, beta).doit() == (cos(beta) - cos(2*beta))/2
assert Rotation.d(2, -1, 0, beta).doit() == sqrt(6)*sin(2*beta)/4
assert Rotation.d(2, -1, -1, beta).doit() == (cos(beta) + cos(2*beta))/2
assert Rotation.d(2, -1, -2, beta).doit() == -((cos(beta) + 1)*sin(beta))/2
assert Rotation.d(2, -2, 2, beta).doit() == (3 - 4*cos(beta) + cos(2*beta))/8
assert Rotation.d(2, -2, 1, beta).doit() == (2*sin(beta) - sin(2*beta))/4
assert Rotation.d(2, -2, 0, beta).doit() == sqrt(6)*sin(beta)**2/4
assert Rotation.d(2, -2, -1, beta).doit() == (cos(beta) + 1)*sin(beta)/2
assert Rotation.d(2, -2, -2, beta).doit() == (3 + 4*cos(beta) + cos(2*beta))/8
# Numerical tests
# j = 1/2
assert Rotation.d(S.Half, S.Half, S.Half, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S.Half, S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/2
assert Rotation.d(S.Half, Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S.Half, Rational(-1, 2), Rational(-1, 2), pi/2).doit() == sqrt(2)/2
# j = 1
assert Rotation.d(1, 1, 1, pi/2).doit() == S.Half
assert Rotation.d(1, 1, 0, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(1, 1, -1, pi/2).doit() == S.Half
assert Rotation.d(1, 0, 1, pi/2).doit() == sqrt(2)/2
assert Rotation.d(1, 0, 0, pi/2).doit() == 0
assert Rotation.d(1, 0, -1, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(1, -1, 1, pi/2).doit() == S.Half
assert Rotation.d(1, -1, 0, pi/2).doit() == sqrt(2)/2
assert Rotation.d(1, -1, -1, pi/2).doit() == S.Half
# j = 3/2
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), S.Half, pi/2).doit() == -sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), S.Half, S.Half, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(-1, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), S.Half, Rational(-3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), S.Half, pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2).doit() == -sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2).doit() == -sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2).doit() == sqrt(2)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), S.Half, pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2).doit() == sqrt(6)/4
assert Rotation.d(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2).doit() == sqrt(2)/4
# j = 2
assert Rotation.d(2, 2, 2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, 2, 1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, 2, -1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 2, -2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, 1, 2, pi/2).doit() == S.Half
assert Rotation.d(2, 1, 1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 1, 0, pi/2).doit() == 0
assert Rotation.d(2, 1, -1, pi/2).doit() == S.Half
assert Rotation.d(2, 1, -2, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 0, 2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, 0, 1, pi/2).doit() == 0
assert Rotation.d(2, 0, 0, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, 0, -1, pi/2).doit() == 0
assert Rotation.d(2, 0, -2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, -1, 2, pi/2).doit() == S.Half
assert Rotation.d(2, -1, 1, pi/2).doit() == S.Half
assert Rotation.d(2, -1, 0, pi/2).doit() == 0
assert Rotation.d(2, -1, -1, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, -1, -2, pi/2).doit() == Rational(-1, 2)
assert Rotation.d(2, -2, 2, pi/2).doit() == Rational(1, 4)
assert Rotation.d(2, -2, 1, pi/2).doit() == S.Half
assert Rotation.d(2, -2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, -2, -1, pi/2).doit() == S.Half
assert Rotation.d(2, -2, -2, pi/2).doit() == Rational(1, 4)
def test_rotation_d():
# Symbolic tests
# j = 1/2
assert Rotation.D(S.Half, S.Half, S.Half, alpha, beta, gamma).doit() == \
cos(beta/2)*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S.Half, S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \
-sin(beta/2)*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S.Half, Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \
sin(beta/2)*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S.Half, Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
cos(beta/2)*exp(I*alpha/2)*exp(I*gamma/2)
# j = 1
assert Rotation.D(1, 1, 1, alpha, beta, gamma).doit() == \
(1 + cos(beta))/2*exp(-I*alpha)*exp(-I*gamma)
assert Rotation.D(1, 1, 0, alpha, beta, gamma).doit() == -sin(
beta)/sqrt(2)*exp(-I*alpha)
assert Rotation.D(1, 1, -1, alpha, beta, gamma).doit() == \
(1 - cos(beta))/2*exp(-I*alpha)*exp(I*gamma)
assert Rotation.D(1, 0, 1, alpha, beta, gamma).doit() == \
sin(beta)/sqrt(2)*exp(-I*gamma)
assert Rotation.D(1, 0, 0, alpha, beta, gamma).doit() == cos(beta)
assert Rotation.D(1, 0, -1, alpha, beta, gamma).doit() == \
-sin(beta)/sqrt(2)*exp(I*gamma)
assert Rotation.D(1, -1, 1, alpha, beta, gamma).doit() == \
(1 - cos(beta))/2*exp(I*alpha)*exp(-I*gamma)
assert Rotation.D(1, -1, 0, alpha, beta, gamma).doit() == \
sin(beta)/sqrt(2)*exp(I*alpha)
assert Rotation.D(1, -1, -1, alpha, beta, gamma).doit() == \
(1 + cos(beta))/2*exp(I*alpha)*exp(I*gamma)
# j = 3/2
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(3, 2), S.Half, alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
(-3*sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(-3, 2))*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), S.Half, Rational(3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), S.Half, S.Half, alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), S.Half, Rational(-1, 2), alpha, beta, gamma).doit() == \
(sin(beta/2) - 3*sin(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), S.Half, Rational(-3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(-I*alpha/2)*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(-1, 2), S.Half, alpha, beta, gamma).doit() == \
(-sin(beta/2) + 3*sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-1, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha/2)*exp(I*gamma*Rational(3, 2))
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(3, 2), alpha, beta, gamma).doit() == \
(3*sin(beta/2) - sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(-3, 2))
assert Rotation.D(Rational(3, 2), Rational(-3, 2), S.Half, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(-I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-1, 2), alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma/2)
assert Rotation.D(Rational(3, 2), Rational(-3, 2), Rational(-3, 2), alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(beta*Rational(3, 2)))/4*exp(I*alpha*Rational(3, 2))*exp(I*gamma*Rational(3, 2))
# j = 2
assert Rotation.D(2, 2, 2, alpha, beta, gamma).doit() == \
(3 + 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, 2, 1, alpha, beta, gamma).doit() == \
-((cos(beta) + 1)*exp(-2*I*alpha)*exp(-I*gamma)*sin(beta))/2
assert Rotation.D(2, 2, 0, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(-2*I*alpha)
assert Rotation.D(2, 2, -1, alpha, beta, gamma).doit() == \
(cos(beta) - 1)*sin(beta)/2*exp(-2*I*alpha)*exp(I*gamma)
assert Rotation.D(2, 2, -2, alpha, beta, gamma).doit() == \
(3 - 4*cos(beta) + cos(2*beta))/8*exp(-2*I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, 1, 2, alpha, beta, gamma).doit() == \
(cos(beta) + 1)*sin(beta)/2*exp(-I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, 1, 1, alpha, beta, gamma).doit() == \
(cos(beta) + cos(2*beta))/2*exp(-I*alpha)*exp(-I*gamma)
assert Rotation.D(2, 1, 0, alpha, beta, gamma).doit() == -sqrt(6)* \
sin(2*beta)/4*exp(-I*alpha)
assert Rotation.D(2, 1, -1, alpha, beta, gamma).doit() == \
(cos(beta) - cos(2*beta))/2*exp(-I*alpha)*exp(I*gamma)
assert Rotation.D(2, 1, -2, alpha, beta, gamma).doit() == \
(cos(beta) - 1)*sin(beta)/2*exp(-I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, 0, 2, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(-2*I*gamma)
assert Rotation.D(2, 0, 1, alpha, beta, gamma).doit() == sqrt(6)* \
sin(2*beta)/4*exp(-I*gamma)
assert Rotation.D(
2, 0, 0, alpha, beta, gamma).doit() == (1 + 3*cos(2*beta))/4
assert Rotation.D(2, 0, -1, alpha, beta, gamma).doit() == -sqrt(6)* \
sin(2*beta)/4*exp(I*gamma)
assert Rotation.D(2, 0, -2, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(2*I*gamma)
assert Rotation.D(2, -1, 2, alpha, beta, gamma).doit() == \
(2*sin(beta) - sin(2*beta))/4*exp(I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, -1, 1, alpha, beta, gamma).doit() == \
(cos(beta) - cos(2*beta))/2*exp(I*alpha)*exp(-I*gamma)
assert Rotation.D(2, -1, 0, alpha, beta, gamma).doit() == sqrt(6)* \
sin(2*beta)/4*exp(I*alpha)
assert Rotation.D(2, -1, -1, alpha, beta, gamma).doit() == \
(cos(beta) + cos(2*beta))/2*exp(I*alpha)*exp(I*gamma)
assert Rotation.D(2, -1, -2, alpha, beta, gamma).doit() == \
-((cos(beta) + 1)*sin(beta))/2*exp(I*alpha)*exp(2*I*gamma)
assert Rotation.D(2, -2, 2, alpha, beta, gamma).doit() == \
(3 - 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(-2*I*gamma)
assert Rotation.D(2, -2, 1, alpha, beta, gamma).doit() == \
(2*sin(beta) - sin(2*beta))/4*exp(2*I*alpha)*exp(-I*gamma)
assert Rotation.D(2, -2, 0, alpha, beta, gamma).doit() == \
sqrt(6)*sin(beta)**2/4*exp(2*I*alpha)
assert Rotation.D(2, -2, -1, alpha, beta, gamma).doit() == \
(cos(beta) + 1)*sin(beta)/2*exp(2*I*alpha)*exp(I*gamma)
assert Rotation.D(2, -2, -2, alpha, beta, gamma).doit() == \
(3 + 4*cos(beta) + cos(2*beta))/8*exp(2*I*alpha)*exp(2*I*gamma)
# Numerical tests
# j = 1/2
assert Rotation.D(
S.Half, S.Half, S.Half, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(
S.Half, S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/2
assert Rotation.D(
S.Half, Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/2
assert Rotation.D(
S.Half, Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
# j = 1
assert Rotation.D(1, 1, 1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
assert Rotation.D(1, 1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
assert Rotation.D(1, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(1, 0, 1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(1, 0, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(1, 0, -1, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(1, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(1, -1, 0, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/2
assert Rotation.D(1, -1, -1, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
# j = 3/2
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(3, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
Rational(3, 2), S.Half, S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
Rational(3, 2), S.Half, Rational(-3, 2), pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), S.Half, pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-1, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(3, 2), pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), S.Half, pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(-1, 2), pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
Rational(3, 2), Rational(-3, 2), Rational(-3, 2), pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4
# j = 2
assert Rotation.D(2, 2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, 2, 1, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, 2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, 2, -1, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, 2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, 1, 2, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, 1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, 1, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, 1, -2, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, 0, 2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, 0, 1, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 0, 0, pi/2, pi/2, pi/2).doit() == Rational(-1, 2)
assert Rotation.D(2, 0, -1, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, 0, -2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, -1, 2, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, -1, 1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, -1, 0, pi/2, pi/2, pi/2).doit() == 0
assert Rotation.D(2, -1, -1, pi/2, pi/2, pi/2).doit() == S.Half
assert Rotation.D(2, -1, -2, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, -2, 2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
assert Rotation.D(2, -2, 1, pi/2, pi/2, pi/2).doit() == I/2
assert Rotation.D(2, -2, 0, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(2, -2, -1, pi/2, pi/2, pi/2).doit() == -I/2
assert Rotation.D(2, -2, -2, pi/2, pi/2, pi/2).doit() == Rational(1, 4)
def test_wignerd():
assert Rotation.D(
j, m, mp, alpha, beta, gamma) == WignerD(j, m, mp, alpha, beta, gamma)
assert Rotation.d(j, m, mp, beta) == WignerD(j, m, mp, 0, beta, 0)
def test_wignerD():
i,j=symbols('i j')
assert Rotation.D(1, 1, 1, 0, 0, 0) == WignerD(1, 1, 1, 0, 0, 0)
assert Rotation.D(1, 1, 2, 0, 0, 0) == WignerD(1, 1, 2, 0, 0, 0)
assert Rotation.D(1, i**2 - j**2, i**2 - j**2, 0, 0, 0) == WignerD(1, i**2 - j**2, i**2 - j**2, 0, 0, 0)
assert Rotation.D(1, i, i, 0, 0, 0) == WignerD(1, i, i, 0, 0, 0)
assert Rotation.D(1, i, i+1, 0, 0, 0) == WignerD(1, i, i+1, 0, 0, 0)
assert Rotation.D(1, 0, 0, 0, 0, 0) == WignerD(1, 0, 0, 0, 0, 0)
def test_jplus():
assert Commutator(Jplus, Jminus).doit() == 2*hbar*Jz
assert Jplus.matrix_element(1, 1, 1, 1) == 0
assert Jplus.rewrite('xyz') == Jx + I*Jy
# Normal operators, normal states
# Numerical
assert qapply(Jplus*JxKet(1, 1)) == \
-hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1)
assert qapply(Jplus*JyKet(1, 1)) == \
hbar*sqrt(2)*JyKet(1, 0)/2 + I*hbar*JyKet(1, 1)
assert qapply(Jplus*JzKet(1, 1)) == 0
# Symbolic
assert qapply(Jplus*JxKet(j, m)) == \
Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JyKet(j, m)) == \
Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)
# Normal operators, coupled states
# Numerical
assert qapply(Jplus*JxKetCoupled(1, 1, (1, 1))) == -hbar*sqrt(2) * \
JxKetCoupled(1, 0, (1, 1))/2 + hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jplus*JyKetCoupled(1, 1, (1, 1))) == hbar*sqrt(2) * \
JyKetCoupled(1, 0, (1, 1))/2 + I*hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jplus*JzKet(1, 1)) == 0
# Symbolic
assert qapply(Jplus*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar * sqrt(-mi**2 - mi + j**2 + j) * WignerD(j, mi, m, 0, pi/2, 0) *
Sum(
WignerD(
j, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar * sqrt(j**2 + j - mi**2 - mi) * WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) *
JyKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jplus*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 + \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(
TensorProduct(Jplus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))
# Symbolic
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar * sqrt(-mi**2 - mi + j1**2 + j1) * WignerD(j1, mi, m1, 0, pi/2, 0) *
Sum(WignerD(j1, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar * sqrt(-mi**2 - mi + j2**2 + j2) * WignerD(j2, mi, m2, 0, pi/2, 0) *
Sum(WignerD(j2, mi1, mi + 1, 0, pi*Rational(3, 2), 0) * JxKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar * sqrt(j1**2 + j1 - mi**2 - mi) * WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar * sqrt(j2**2 + j2 - mi**2 - mi) * WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi + 1, pi*Rational(3, 2), pi/2, pi/2) * JyKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jplus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jplus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))
def test_jminus():
assert qapply(Jminus*JzKet(1, -1)) == 0
assert Jminus.matrix_element(1, 0, 1, 1) == sqrt(2)*hbar
assert Jminus.rewrite('xyz') == Jx - I*Jy
# Normal operators, normal states
# Numerical
assert qapply(Jminus*JxKet(1, 1)) == \
hbar*sqrt(2)*JxKet(1, 0)/2 + hbar*JxKet(1, 1)
assert qapply(Jminus*JyKet(1, 1)) == \
hbar*sqrt(2)*JyKet(1, 0)/2 - hbar*I*JyKet(1, 1)
assert qapply(Jminus*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)
# Symbolic
assert qapply(Jminus*JxKet(j, m)) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JyKet(j, m)) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)
# Normal operators, coupled states
# Numerical
assert qapply(Jminus*JxKetCoupled(1, 1, (1, 1))) == \
hbar*sqrt(2)*JxKetCoupled(1, 0, (1, 1))/2 + \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jminus*JyKetCoupled(1, 1, (1, 1))) == \
hbar*sqrt(2)*JyKetCoupled(1, 0, (1, 1))/2 - \
hbar*I*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jminus*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))
# Symbolic
assert qapply(Jminus*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, 0, pi/2, 0) *
Sum(WignerD(j, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*sqrt(j**2 + j - mi**2 + mi)*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*
JyKetCoupled(j, mi1, (j1, j2)),
(mi1, -j, j)), (mi, -j, j))
assert qapply(Jminus*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2 + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1)) - \
hbar*sqrt(2)*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2 - \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, -1)) + \
hbar*sqrt(2)*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, -1))
assert qapply(TensorProduct(
1, Jminus)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
# Symbolic
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, 0, pi/2, 0) *
Sum(WignerD(j1, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, 0, pi/2, 0) *
Sum(WignerD(j2, mi1, mi - 1, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*sqrt(j1**2 + j1 - mi**2 + mi)*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1),
(mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*sqrt(j2**2 + j2 - mi**2 + mi)*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi - 1, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1),
(mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jminus, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jminus)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))
def test_j2():
assert Commutator(J2, Jz).doit() == 0
assert J2.matrix_element(1, 1, 1, 1) == 2*hbar**2
# Normal operators, normal states
# Numerical
assert qapply(J2*JxKet(1, 1)) == 2*hbar**2*JxKet(1, 1)
assert qapply(J2*JyKet(1, 1)) == 2*hbar**2*JyKet(1, 1)
assert qapply(J2*JzKet(1, 1)) == 2*hbar**2*JzKet(1, 1)
# Symbolic
assert qapply(J2*JxKet(j, m)) == \
hbar**2*j**2*JxKet(j, m) + hbar**2*j*JxKet(j, m)
assert qapply(J2*JyKet(j, m)) == \
hbar**2*j**2*JyKet(j, m) + hbar**2*j*JyKet(j, m)
assert qapply(J2*JzKet(j, m)) == \
hbar**2*j**2*JzKet(j, m) + hbar**2*j*JzKet(j, m)
# Normal operators, coupled states
# Numerical
assert qapply(J2*JxKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JxKetCoupled(1, 1, (1, 1))
assert qapply(J2*JyKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JyKetCoupled(1, 1, (1, 1))
assert qapply(J2*JzKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JzKetCoupled(1, 1, (1, 1))
# Symbolic
assert qapply(J2*JxKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JxKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JxKetCoupled(j, m, (j1, j2))
assert qapply(J2*JyKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JyKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JyKetCoupled(j, m, (j1, j2))
assert qapply(J2*JzKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JzKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JzKetCoupled(j, m, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
# Symbolic
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
def test_jx():
assert Commutator(Jx, Jz).doit() == -I*hbar*Jy
assert Jx.rewrite('plusminus') == (Jminus + Jplus)/2
assert represent(Jx, basis=Jz, j=1) == (
represent(Jplus, basis=Jz, j=1) + represent(Jminus, basis=Jz, j=1))/2
# Normal operators, normal states
# Numerical
assert qapply(Jx*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jx*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jx*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)/2
# Symbolic
assert qapply(Jx*JxKet(j, m)) == hbar*m*JxKet(j, m)
assert qapply(Jx*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j,
mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)/2 + hbar*sqrt(j**2 +
j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jx*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jx*JxKetCoupled(j, m, (j1, j2))) == \
hbar*m*JxKetCoupled(j, m, (j1, j2))
assert qapply(Jx*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
2*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jx*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jx*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == 0
# Symbolic
assert qapply(Jx*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(Jx*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(Jx*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2
# Symbolic
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2) * Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2) * Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
def test_jy():
assert Commutator(Jy, Jz).doit() == I*hbar*Jx
assert Jy.rewrite('plusminus') == (Jplus - Jminus)/(2*I)
assert represent(Jy, basis=Jz) == (
represent(Jplus, basis=Jz) - represent(Jminus, basis=Jz))/(2*I)
# Normal operators, normal states
# Numerical
assert qapply(Jy*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jy*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jy*JzKet(1, 1)) == sqrt(2)*hbar*I*JzKet(1, 0)/2
# Symbolic
assert qapply(Jy*JxKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD(
j, mi1, mi, 0, 0, pi/2)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKet(j, m)) == hbar*m*JyKet(j, m)
assert qapply(Jy*JzKet(j, m)) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKet(
j, m + 1)/2 + hbar*I*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jy*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*I*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jy*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j, mi1, mi, 0, 0, pi/2)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKetCoupled(j, m, (j1, j2))) == \
hbar*m*JyKetCoupled(j, m, (j1, j2))
assert qapply(Jy*JzKetCoupled(j, m, (j1, j2))) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*I*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jy*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
2*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jy*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == 0
# Symbolic
assert qapply(Jy*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0)*Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(Jy*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m1*TensorProduct(JyKet(j1, m1), JyKet(
j2, m2)) + hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(Jy*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*I*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \
-hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*I*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*I*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2
assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
-hbar*sqrt(2)*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2
# Symbolic
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j1, mi1, mi, 0, 0, pi/2)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), 0, 0) * Sum(WignerD(j2, mi1, mi, 0, 0, pi/2)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jy)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar*m2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(Jy, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*I*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2
assert qapply(TensorProduct(1, Jy)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
-hbar*I*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*I*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
def test_jz():
assert Commutator(Jz, Jminus).doit() == -hbar*Jminus
# Normal operators, normal states
# Numerical
assert qapply(Jz*JxKet(1, 1)) == -sqrt(2)*hbar*JxKet(1, 0)/2
assert qapply(Jz*JyKet(1, 1)) == -sqrt(2)*hbar*I*JyKet(1, 0)/2
assert qapply(Jz*JzKet(2, 1)) == hbar*JzKet(2, 1)
# Symbolic
assert qapply(Jz*JxKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j,
mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1,
mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JzKet(j, m)) == hbar*m*JzKet(j, m)
# Normal operators, coupled states
# Numerical
assert qapply(Jz*JxKetCoupled(1, 1, (1, 1))) == \
-sqrt(2)*hbar*JxKetCoupled(1, 0, (1, 1))/2
assert qapply(Jz*JyKetCoupled(1, 1, (1, 1))) == \
-sqrt(2)*hbar*I*JyKetCoupled(1, 0, (1, 1))/2
assert qapply(Jz*JzKetCoupled(1, 1, (1, 1))) == \
hbar*JzKetCoupled(1, 1, (1, 1))
# Symbolic
assert qapply(Jz*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, pi/2, 0)*Sum(WignerD(j, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JzKetCoupled(j, m, (j1, j2))) == \
hbar*m*JzKetCoupled(j, m, (j1, j2))
# Normal operators, uncoupled states
# Numerical
assert qapply(Jz*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2 - \
sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, 1))/2
assert qapply(Jz*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
-sqrt(2)*hbar*I*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2 - \
sqrt(2)*hbar*I*TensorProduct(JyKet(1, 0), JyKet(1, 1))/2
assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
2*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 1))
assert qapply(Jz*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == 0
# Symbolic
assert qapply(Jz*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(Jz*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(Jz*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m1*TensorProduct(JzKet(j1, m1), JzKet(
j2, m2)) + hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
# Uncoupled Operators
# Numerical
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 0), JxKet(1, -1))/2
assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-sqrt(2)*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 0))/2
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-sqrt(2)*I*hbar*TensorProduct(JyKet(1, 0), JyKet(1, -1))/2
assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
sqrt(2)*I*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 0))/2
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
-hbar*TensorProduct(JzKet(1, 1), JzKet(1, -1))
# Symbolic
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, pi/2, 0)*Sum(WignerD(j1, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, pi/2, 0)*Sum(WignerD(j2, mi1, mi, 0, pi*Rational(3, 2), 0)*JxKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, pi*Rational(3, 2), -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, pi*Rational(3, 2), pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jz, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
assert qapply(TensorProduct(1, Jz)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*m2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
def test_rotation():
a, b, g = symbols('a b g')
j, m = symbols('j m')
#Uncoupled
answ = [JxKet(1,-1)/2 - sqrt(2)*JxKet(1,0)/2 + JxKet(1,1)/2 ,
JyKet(1,-1)/2 - sqrt(2)*JyKet(1,0)/2 + JyKet(1,1)/2 ,
JzKet(1,-1)/2 - sqrt(2)*JzKet(1,0)/2 + JzKet(1,1)/2]
fun = [state(1, 1) for state in (JxKet, JyKet, JzKet)]
for state in fun:
got = qapply(Rotation(0, pi/2, 0)*state)
assert got in answ
answ.remove(got)
assert not answ
arg = Rotation(a, b, g)*fun[0]
assert qapply(arg) == (-exp(-I*a)*exp(I*g)*cos(b)*JxKet(1,-1)/2 +
exp(-I*a)*exp(I*g)*JxKet(1,-1)/2 - sqrt(2)*exp(-I*a)*sin(b)*JxKet(1,0)/2 +
exp(-I*a)*exp(-I*g)*cos(b)*JxKet(1,1)/2 + exp(-I*a)*exp(-I*g)*JxKet(1,1)/2)
#dummy effective
assert str(qapply(Rotation(a, b, g)*JzKet(j, m), dummy=False)) == str(
qapply(Rotation(a, b, g)*JzKet(j, m), dummy=True)).replace('_','')
#Coupled
ans = [JxKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JxKetCoupled(1,0,(1,1))/2 +
JxKetCoupled(1,1,(1,1))/2 ,
JyKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JyKetCoupled(1,0,(1,1))/2 +
JyKetCoupled(1,1,(1,1))/2 ,
JzKetCoupled(1,-1,(1,1))/2 - sqrt(2)*JzKetCoupled(1,0,(1,1))/2 +
JzKetCoupled(1,1,(1,1))/2]
fun = [state(1, 1, (1,1)) for state in (JxKetCoupled, JyKetCoupled, JzKetCoupled)]
for state in fun:
got = qapply(Rotation(0, pi/2, 0)*state)
assert got in ans
ans.remove(got)
assert not ans
arg = Rotation(a, b, g)*fun[0]
assert qapply(arg) == (
-exp(-I*a)*exp(I*g)*cos(b)*JxKetCoupled(1,-1,(1,1))/2 +
exp(-I*a)*exp(I*g)*JxKetCoupled(1,-1,(1,1))/2 -
sqrt(2)*exp(-I*a)*sin(b)*JxKetCoupled(1,0,(1,1))/2 +
exp(-I*a)*exp(-I*g)*cos(b)*JxKetCoupled(1,1,(1,1))/2 +
exp(-I*a)*exp(-I*g)*JxKetCoupled(1,1,(1,1))/2)
#dummy effective
assert str(qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=False)) == str(
qapply(Rotation(a,b,g)*JzKetCoupled(j,m,(j1,j2)), dummy=True)).replace('_','')
def test_jzket():
j, m = symbols('j m')
# j not integer or half integer
raises(ValueError, lambda: JzKet(Rational(2, 3), Rational(-1, 3)))
raises(ValueError, lambda: JzKet(Rational(2, 3), m))
# j < 0
raises(ValueError, lambda: JzKet(-1, 1))
raises(ValueError, lambda: JzKet(-1, m))
# m not integer or half integer
raises(ValueError, lambda: JzKet(j, Rational(-1, 3)))
# abs(m) > j
raises(ValueError, lambda: JzKet(1, 2))
raises(ValueError, lambda: JzKet(1, -2))
# j-m not integer
raises(ValueError, lambda: JzKet(1, S.Half))
def test_jzketcoupled():
j, m = symbols('j m')
# j not integer or half integer
raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), Rational(-1, 3), (1,)))
raises(ValueError, lambda: JzKetCoupled(Rational(2, 3), m, (1,)))
# j < 0
raises(ValueError, lambda: JzKetCoupled(-1, 1, (1,)))
raises(ValueError, lambda: JzKetCoupled(-1, m, (1,)))
# m not integer or half integer
raises(ValueError, lambda: JzKetCoupled(j, Rational(-1, 3), (1,)))
# abs(m) > j
raises(ValueError, lambda: JzKetCoupled(1, 2, (1,)))
raises(ValueError, lambda: JzKetCoupled(1, -2, (1,)))
# j-m not integer
raises(ValueError, lambda: JzKetCoupled(1, S.Half, (1,)))
# checks types on coupling scheme
raises(TypeError, lambda: JzKetCoupled(1, 1, 1))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1,), 1))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1), (1,)))
raises(TypeError, lambda: JzKetCoupled(1, 1, (1, 1, 1), (1, 2, 1),
(1, 3, 1)))
# checks length of coupling terms
raises(ValueError, lambda: JzKetCoupled(1, 1, (1,), ((1, 2, 1),)))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2),)))
# all jn are integer or half-integer
raises(ValueError, lambda: JzKetCoupled(1, 1, (Rational(1, 3), Rational(2, 3))))
# indices in coupling scheme must be integers
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((S.Half, 1, 2),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, S.Half, 2),) ))
# indices out of range
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((0, 2, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((3, 2, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 0, 1),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 3, 1),) ))
# all j values in coupling scheme must by integer or half-integer
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1, 1), ((1, 2, S(
4)/3), (1, 3, 1)) ))
# each coupling must satisfy |j1-j2| <= j3 <= j1+j2
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 5)))
raises(ValueError, lambda: JzKetCoupled(5, 1, (1, 1)))
# final j of coupling must be j of the state
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, 2, 2),) ))
|
91e06cb460e93484c546bd3ab9516b91afcb8dee7a83aa05a09404a595e69d8c | from sympy.core.numbers import Integer
from sympy.core.symbol import symbols
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.commutator import Commutator as Comm
from sympy.physics.quantum.operator import Operator
a, b, c = symbols('a,b,c')
n = symbols('n', integer=True)
A, B, C, D = symbols('A,B,C,D', commutative=False)
def test_commutator():
c = Comm(A, B)
assert c.is_commutative is False
assert isinstance(c, Comm)
assert c.subs(A, C) == Comm(C, B)
def test_commutator_identities():
assert Comm(a*A, b*B) == a*b*Comm(A, B)
assert Comm(A, A) == 0
assert Comm(a, b) == 0
assert Comm(A, B) == -Comm(B, A)
assert Comm(A, B).doit() == A*B - B*A
assert Comm(A, B*C).expand(commutator=True) == Comm(A, B)*C + B*Comm(A, C)
assert Comm(A*B, C*D).expand(commutator=True) == \
A*C*Comm(B, D) + A*Comm(B, C)*D + C*Comm(A, D)*B + Comm(A, C)*D*B
assert Comm(A, B**2).expand(commutator=True) == Comm(A, B)*B + B*Comm(A, B)
assert Comm(A**2, C**2).expand(commutator=True) == \
Comm(A*B, C*D).expand(commutator=True).replace(B, A).replace(D, C) == \
A*C*Comm(A, C) + A*Comm(A, C)*C + C*Comm(A, C)*A + Comm(A, C)*C*A
assert Comm(A, C**-2).expand(commutator=True) == \
Comm(A, (1/C)*(1/D)).expand(commutator=True).replace(D, C)
assert Comm(A + B, C + D).expand(commutator=True) == \
Comm(A, C) + Comm(A, D) + Comm(B, C) + Comm(B, D)
assert Comm(A, B + C).expand(commutator=True) == Comm(A, B) + Comm(A, C)
assert Comm(A**n, B).expand(commutator=True) == Comm(A**n, B)
e = Comm(A, Comm(B, C)) + Comm(B, Comm(C, A)) + Comm(C, Comm(A, B))
assert e.doit().expand() == 0
def test_commutator_dagger():
comm = Comm(A*B, C)
assert Dagger(comm).expand(commutator=True) == \
- Comm(Dagger(B), Dagger(C))*Dagger(A) - \
Dagger(B)*Comm(Dagger(A), Dagger(C))
class Foo(Operator):
def _eval_commutator_Bar(self, bar):
return Integer(0)
class Bar(Operator):
pass
class Tam(Operator):
def _eval_commutator_Foo(self, foo):
return Integer(1)
def test_eval_commutator():
F = Foo('F')
B = Bar('B')
T = Tam('T')
assert Comm(F, B).doit() == 0
assert Comm(B, F).doit() == 0
assert Comm(F, T).doit() == -1
assert Comm(T, F).doit() == 1
assert Comm(B, T).doit() == B*T - T*B
assert Comm(F**2, B).expand(commutator=True).doit() == 0
assert Comm(F**2, T).expand(commutator=True).doit() == -2*F
assert Comm(F, T**2).expand(commutator=True).doit() == -2*T
assert Comm(T**2, F).expand(commutator=True).doit() == 2*T
assert Comm(T**2, F**3).expand(commutator=True).doit() == 2*F*T*F + 2*F**2*T + 2*T*F**2
|
389c59c88cc5d9fe862ffe72d86451c3b7e2743145898b10c378de6a604bb0bf | import random
from sympy.core.numbers import (Integer, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import Matrix
from sympy.physics.quantum.qubit import (measure_all, measure_partial,
matrix_to_qubit, matrix_to_density,
qubit_to_matrix, IntQubit,
IntQubitBra, QubitBra)
from sympy.physics.quantum.gate import (HadamardGate, CNOT, XGate, YGate,
ZGate, PhaseGate)
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.shor import Qubit
from sympy.testing.pytest import raises
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.trace import Tr
x, y = symbols('x,y')
epsilon = .000001
def test_Qubit():
array = [0, 0, 1, 1, 0]
qb = Qubit('00110')
assert qb.flip(0) == Qubit('00111')
assert qb.flip(1) == Qubit('00100')
assert qb.flip(4) == Qubit('10110')
assert qb.qubit_values == (0, 0, 1, 1, 0)
assert qb.dimension == 5
for i in range(5):
assert qb[i] == array[4 - i]
assert len(qb) == 5
qb = Qubit('110')
def test_QubitBra():
qb = Qubit(0)
qb_bra = QubitBra(0)
assert qb.dual_class() == QubitBra
assert qb_bra.dual_class() == Qubit
qb = Qubit(1, 1, 0)
qb_bra = QubitBra(1, 1, 0)
assert represent(qb, nqubits=3).H == represent(qb_bra, nqubits=3)
qb = Qubit(0, 1)
qb_bra = QubitBra(1,0)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(0)
qb_bra = QubitBra(0, 1)
assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(1)
def test_IntQubit():
# issue 9136
iqb = IntQubit(0, nqubits=1)
assert qubit_to_matrix(Qubit('0')) == qubit_to_matrix(iqb)
qb = Qubit('1010')
assert qubit_to_matrix(IntQubit(qb)) == qubit_to_matrix(qb)
iqb = IntQubit(1, nqubits=1)
assert qubit_to_matrix(Qubit('1')) == qubit_to_matrix(iqb)
assert qubit_to_matrix(IntQubit(1)) == qubit_to_matrix(iqb)
iqb = IntQubit(7, nqubits=4)
assert qubit_to_matrix(Qubit('0111')) == qubit_to_matrix(iqb)
assert qubit_to_matrix(IntQubit(7, 4)) == qubit_to_matrix(iqb)
iqb = IntQubit(8)
assert iqb.as_int() == 8
assert iqb.qubit_values == (1, 0, 0, 0)
iqb = IntQubit(7, 4)
assert iqb.qubit_values == (0, 1, 1, 1)
assert IntQubit(3) == IntQubit(3, 2)
#test Dual Classes
iqb = IntQubit(3)
iqb_bra = IntQubitBra(3)
assert iqb.dual_class() == IntQubitBra
assert iqb_bra.dual_class() == IntQubit
iqb = IntQubit(5)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1)
iqb = IntQubit(4)
iqb_bra = IntQubitBra(5)
assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0)
raises(ValueError, lambda: IntQubit(4, 1))
raises(ValueError, lambda: IntQubit('5'))
raises(ValueError, lambda: IntQubit(5, '5'))
raises(ValueError, lambda: IntQubit(5, nqubits='5'))
raises(TypeError, lambda: IntQubit(5, bad_arg=True))
def test_superposition_of_states():
state = 1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10')
state_gate = CNOT(0, 1)*HadamardGate(0)*state
state_expanded = Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2
assert qapply(state_gate).expand() == state_expanded
assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded
#test apply methods
def test_apply_represent_equality():
gates = [HadamardGate(int(3*random.random())),
XGate(int(3*random.random())), ZGate(int(3*random.random())),
YGate(int(3*random.random())), ZGate(int(3*random.random())),
PhaseGate(int(3*random.random()))]
circuit = Qubit(int(random.random()*2), int(random.random()*2),
int(random.random()*2), int(random.random()*2), int(random.random()*2),
int(random.random()*2))
for i in range(int(random.random()*6)):
circuit = gates[int(random.random()*6)]*circuit
mat = represent(circuit, nqubits=6)
states = qapply(circuit)
state_rep = matrix_to_qubit(mat)
states = states.expand()
state_rep = state_rep.expand()
assert state_rep == states
def test_matrix_to_qubits():
qb = Qubit(0, 0, 0, 0)
mat = Matrix([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert matrix_to_qubit(mat) == qb
assert qubit_to_matrix(qb) == mat
state = 2*sqrt(2)*(Qubit(0, 0, 0) + Qubit(0, 0, 1) + Qubit(0, 1, 0) +
Qubit(0, 1, 1) + Qubit(1, 0, 0) + Qubit(1, 0, 1) +
Qubit(1, 1, 0) + Qubit(1, 1, 1))
ones = sqrt(2)*2*Matrix([1, 1, 1, 1, 1, 1, 1, 1])
assert matrix_to_qubit(ones) == state.expand()
assert qubit_to_matrix(state) == ones
def test_measure_normalize():
a, b = symbols('a b')
state = a*Qubit('110') + b*Qubit('111')
assert measure_partial(state, (0,), normalize=False) == \
[(a*Qubit('110'), a*a.conjugate()), (b*Qubit('111'), b*b.conjugate())]
assert measure_all(state, normalize=False) == \
[(Qubit('110'), a*a.conjugate()), (Qubit('111'), b*b.conjugate())]
def test_measure_partial():
#Basic test of collapse of entangled two qubits (Bell States)
state = Qubit('01') + Qubit('10')
assert measure_partial(state, (0,)) == \
[(Qubit('10'), S.Half), (Qubit('01'), S.Half)]
assert measure_partial(state, int(0)) == \
[(Qubit('10'), S.Half), (Qubit('01'), S.Half)]
assert measure_partial(state, (0,)) == \
measure_partial(state, (1,))[::-1]
#Test of more complex collapse and probability calculation
state1 = sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111')
assert measure_partial(state1, (0,)) == \
[(sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111'), 1)]
assert measure_partial(state1, (1, 2)) == measure_partial(state1, (3, 4))
assert measure_partial(state1, (1, 2, 3)) == \
[(Qubit('00001'), Rational(2, 3)), (Qubit('11111'), Rational(1, 3))]
#test of measuring multiple bits at once
state2 = Qubit('1111') + Qubit('1101') + Qubit('1011') + Qubit('1000')
assert measure_partial(state2, (0, 1, 3)) == \
[(Qubit('1000'), Rational(1, 4)), (Qubit('1101'), Rational(1, 4)),
(Qubit('1011')/sqrt(2) + Qubit('1111')/sqrt(2), S.Half)]
assert measure_partial(state2, (0,)) == \
[(Qubit('1000'), Rational(1, 4)),
(Qubit('1111')/sqrt(3) + Qubit('1101')/sqrt(3) +
Qubit('1011')/sqrt(3), Rational(3, 4))]
def test_measure_all():
assert measure_all(Qubit('11')) == [(Qubit('11'), 1)]
state = Qubit('11') + Qubit('10')
assert measure_all(state) == [(Qubit('10'), S.Half),
(Qubit('11'), S.Half)]
state2 = Qubit('11')/sqrt(5) + 2*Qubit('00')/sqrt(5)
assert measure_all(state2) == \
[(Qubit('00'), Rational(4, 5)), (Qubit('11'), Rational(1, 5))]
# from issue #12585
assert measure_all(qapply(Qubit('0'))) == [(Qubit('0'), 1)]
def test_eval_trace():
q1 = Qubit('10110')
q2 = Qubit('01010')
d = Density([q1, 0.6], [q2, 0.4])
t = Tr(d)
assert t.doit() == 1
# extreme bits
t = Tr(d, 0)
assert t.doit() == (0.4*Density([Qubit('0101'), 1]) +
0.6*Density([Qubit('1011'), 1]))
t = Tr(d, 4)
assert t.doit() == (0.4*Density([Qubit('1010'), 1]) +
0.6*Density([Qubit('0110'), 1]))
# index somewhere in between
t = Tr(d, 2)
assert t.doit() == (0.4*Density([Qubit('0110'), 1]) +
0.6*Density([Qubit('1010'), 1]))
#trace all indices
t = Tr(d, [0, 1, 2, 3, 4])
assert t.doit() == 1
# trace some indices, initialized in
# non-canonical order
t = Tr(d, [2, 1, 3])
assert t.doit() == (0.4*Density([Qubit('00'), 1]) +
0.6*Density([Qubit('10'), 1]))
# mixed states
q = (1/sqrt(2)) * (Qubit('00') + Qubit('11'))
d = Density( [q, 1.0] )
t = Tr(d, 0)
assert t.doit() == (0.5*Density([Qubit('0'), 1]) +
0.5*Density([Qubit('1'), 1]))
def test_matrix_to_density():
mat = Matrix([[0, 0], [0, 1]])
assert matrix_to_density(mat) == Density([Qubit('1'), 1])
mat = Matrix([[1, 0], [0, 0]])
assert matrix_to_density(mat) == Density([Qubit('0'), 1])
mat = Matrix([[0, 0], [0, 0]])
assert matrix_to_density(mat) == 0
mat = Matrix([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('10'), 1])
mat = Matrix([[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
assert matrix_to_density(mat) == Density([Qubit('00'), 1])
|
16834cd0d5387a3bb7961d8f8568d712070ab87e5beb64a2cc700e055cafdd7b | from sympy.core.numbers import I
from sympy.core.symbol import symbols
from sympy.core.expr import unchanged
from sympy.matrices import Matrix, SparseMatrix
from sympy.physics.quantum.commutator import Commutator as Comm
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.tensorproduct import TensorProduct as TP
from sympy.physics.quantum.tensorproduct import tensor_product_simp
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.qubit import Qubit, QubitBra
from sympy.physics.quantum.operator import OuterProduct
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.trace import Tr
A, B, C, D = symbols('A,B,C,D', commutative=False)
x = symbols('x')
mat1 = Matrix([[1, 2*I], [1 + I, 3]])
mat2 = Matrix([[2*I, 3], [4*I, 2]])
def test_sparse_matrices():
spm = SparseMatrix.diag(1, 0)
assert unchanged(TensorProduct, spm, spm)
def test_tensor_product_dagger():
assert Dagger(TensorProduct(I*A, B)) == \
-I*TensorProduct(Dagger(A), Dagger(B))
assert Dagger(TensorProduct(mat1, mat2)) == \
TensorProduct(Dagger(mat1), Dagger(mat2))
def test_tensor_product_abstract():
assert TP(x*A, 2*B) == x*2*TP(A, B)
assert TP(A, B) != TP(B, A)
assert TP(A, B).is_commutative is False
assert isinstance(TP(A, B), TP)
assert TP(A, B).subs(A, C) == TP(C, B)
def test_tensor_product_expand():
assert TP(A + B, B + C).expand(tensorproduct=True) == \
TP(A, B) + TP(A, C) + TP(B, B) + TP(B, C)
def test_tensor_product_commutator():
assert TP(Comm(A, B), C).doit().expand(tensorproduct=True) == \
TP(A*B, C) - TP(B*A, C)
assert Comm(TP(A, B), TP(B, C)).doit() == \
TP(A, B)*TP(B, C) - TP(B, C)*TP(A, B)
def test_tensor_product_simp():
assert tensor_product_simp(TP(A, B)*TP(B, C)) == TP(A*B, B*C)
# tests for Pow-expressions
assert tensor_product_simp(TP(A, B)**x) == TP(A**x, B**x)
assert tensor_product_simp(x*TP(A, B)**2) == x*TP(A**2,B**2)
assert tensor_product_simp(x*(TP(A, B)**2)*TP(C,D)) == x*TP(A**2*C,B**2*D)
assert tensor_product_simp(TP(A,B)-TP(C,D)**x) == TP(A,B)-TP(C**x,D**x)
def test_issue_5923():
# most of the issue regarding sympification of args has been handled
# and is tested internally by the use of args_cnc through the quantum
# module, but the following is a test from the issue that used to raise.
assert TensorProduct(1, Qubit('1')*Qubit('1').dual) == \
TensorProduct(1, OuterProduct(Qubit(1), QubitBra(1)))
def test_eval_trace():
# This test includes tests with dependencies between TensorProducts
#and density operators. Since, the test is more to test the behavior of
#TensorProducts it remains here
A, B, C, D, E, F = symbols('A B C D E F', commutative=False)
# Density with simple tensor products as args
t = TensorProduct(A, B)
d = Density([t, 1.0])
tr = Tr(d)
assert tr.doit() == 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B))
## partial trace with simple tensor products as args
t = TensorProduct(A, B, C)
d = Density([t, 1.0])
tr = Tr(d, [1])
assert tr.doit() == 1.0*A*Dagger(A)*Tr(B*Dagger(B))*C*Dagger(C)
tr = Tr(d, [0, 2])
assert tr.doit() == 1.0*Tr(A*Dagger(A))*B*Dagger(B)*Tr(C*Dagger(C))
# Density with multiple Tensorproducts as states
t2 = TensorProduct(A, B)
t3 = TensorProduct(C, D)
d = Density([t2, 0.5], [t3, 0.5])
t = Tr(d)
assert t.doit() == (0.5*Tr(A*Dagger(A))*Tr(B*Dagger(B)) +
0.5*Tr(C*Dagger(C))*Tr(D*Dagger(D)))
t = Tr(d, [0])
assert t.doit() == (0.5*Tr(A*Dagger(A))*B*Dagger(B) +
0.5*Tr(C*Dagger(C))*D*Dagger(D))
#Density with mixed states
d = Density([t2 + t3, 1.0])
t = Tr(d)
assert t.doit() == ( 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B)) +
1.0*Tr(A*Dagger(C))*Tr(B*Dagger(D)) +
1.0*Tr(C*Dagger(A))*Tr(D*Dagger(B)) +
1.0*Tr(C*Dagger(C))*Tr(D*Dagger(D)))
t = Tr(d, [1] )
assert t.doit() == ( 1.0*A*Dagger(A)*Tr(B*Dagger(B)) +
1.0*A*Dagger(C)*Tr(B*Dagger(D)) +
1.0*C*Dagger(A)*Tr(D*Dagger(B)) +
1.0*C*Dagger(C)*Tr(D*Dagger(D)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.