repo_name
stringlengths 5
100
| path
stringlengths 4
375
| copies
stringclasses 991
values | size
stringlengths 4
7
| content
stringlengths 666
1M
| license
stringclasses 15
values |
|---|---|---|---|---|---|
oliverlee/sympy
|
sympy/physics/quantum/tests/test_spin.py
|
80
|
320440
|
from __future__ import division
from sympy import cos, exp, expand, I, Matrix, pi, S, sin, sqrt, Sum, symbols
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.utilities.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(1)/2, S(1)/2), basis=Jx) == Matrix([1, 0])
assert represent(JxKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jx) == Matrix([exp(-I*pi/4), 0])
assert represent(
JyKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jx) == sqrt(2)*Matrix([-1, 1])/2
assert represent(
JzKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jy) == Matrix([exp(-3*I*pi/4), 0])
assert represent(
JxKet(S(1)/2, -S(1)/2), basis=Jy) == Matrix([0, exp(3*I*pi/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(1)/2, S(1)/2), basis=Jy) == Matrix([1, 0])
assert represent(JyKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jy) == sqrt(2)*Matrix([-1, I])/2
assert represent(
JzKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jz) == sqrt(2)*Matrix([1, 1])/2
assert represent(
JxKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jz) == sqrt(2)*Matrix([-1, -I])/2
assert represent(
JyKet(S(1)/2, -S(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(1)/2, S(1)/2), basis=Jz) == Matrix([1, 0])
assert represent(JzKet(S(1)/2, -S(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(1)/2, S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JxKet(S(1)/2, S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([-I, 0, 0, 0])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([S(1)/2, -S(1)/2, -S(1)/2, S(1)/2])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([S(1)/2, S(1)/2, -S(1)/2, -S(1)/2])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([S(1)/2, -S(1)/2, S(1)/2, -S(1)/2])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jx) == \
Matrix([S(1)/2, S(1)/2, S(1)/2, S(1)/2])
# Jy basis
assert represent(TensorProduct(JxKet(S(1)/2, S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([I, 0, 0, 0])
assert represent(TensorProduct(JxKet(S(1)/2, S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([S(1)/2, -I/2, -I/2, -S(1)/2])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([-I/2, S(1)/2, -S(1)/2, -I/2])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([-I/2, -S(1)/2, S(1)/2, -I/2])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jy) == \
Matrix([-S(1)/2, -I/2, -I/2, S(1)/2])
# Jz basis
assert represent(TensorProduct(JxKet(S(1)/2, S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([S(1)/2, S(1)/2, S(1)/2, S(1)/2])
assert represent(TensorProduct(JxKet(S(1)/2, S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([-S(1)/2, S(1)/2, -S(1)/2, S(1)/2])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([-S(1)/2, -S(1)/2, S(1)/2, S(1)/2])
assert represent(TensorProduct(JxKet(S(1)/2, -S(1)/2), JxKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([S(1)/2, -S(1)/2, -S(1)/2, S(1)/2])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([S(1)/2, I/2, I/2, -S(1)/2])
assert represent(TensorProduct(JyKet(S(1)/2, S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([I/2, S(1)/2, -S(1)/2, I/2])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([I/2, -S(1)/2, S(1)/2, I/2])
assert represent(TensorProduct(JyKet(S(1)/2, -S(1)/2), JyKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([-S(1)/2, I/2, I/2, S(1)/2])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2)), basis=Jz) == \
Matrix([0, 0, 0, 1])
def test_represent_coupled_states():
# Jx basis
assert represent(JxKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 1, 0, 0])
assert represent(JxKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 0, 1])
assert represent(JyKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, -I, 0, 0])
assert represent(JyKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, 0, 0, I])
assert represent(JzKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, S(1)/2, -sqrt(2)/2, S(1)/2])
assert represent(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, sqrt(2)/2, 0, -sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jx) == \
Matrix([0, S(1)/2, sqrt(2)/2, S(1)/2])
# Jy basis
assert represent(JxKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, I, 0, 0])
assert represent(JxKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JxKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 0, -I])
assert represent(JyKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 1, 0, 0])
assert represent(JyKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 1, 0])
assert represent(JyKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, 0, 0, 1])
assert represent(JzKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, S(1)/2, -I*sqrt(2)/2, -S(1)/2])
assert represent(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, -I*sqrt(2)/2, 0, -I*sqrt(2)/2])
assert represent(JzKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jy) == \
Matrix([0, -S(1)/2, -I*sqrt(2)/2, S(1)/2])
# Jz basis
assert represent(JxKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JxKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, S(1)/2, sqrt(2)/2, S(1)/2])
assert represent(JxKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, -sqrt(2)/2, 0, sqrt(2)/2])
assert represent(JxKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, S(1)/2, -sqrt(2)/2, S(1)/2])
assert represent(JyKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JyKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, S(1)/2, I*sqrt(2)/2, -S(1)/2])
assert represent(JyKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, I*sqrt(2)/2, 0, I*sqrt(2)/2])
assert represent(JyKetCoupled(1, -1, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, -S(1)/2, I*sqrt(2)/2, S(1)/2])
assert represent(JzKetCoupled(0, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([1, 0, 0, 0])
assert represent(JzKetCoupled(1, 1, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, 1, 0, 0])
assert represent(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)), basis=Jz) == \
Matrix([0, 0, 1, 0])
assert represent(JzKetCoupled(1, -1, (S(1)/2, S(1)/2)), 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(1)/2, S(1)/2, -S(1)/2, 0, pi/2, 0)],
[WignerD(S(1)/2, -S(1)/2, S(1)/2, 0, pi/2, 0), WignerD(S(1)/2, -S(1)/2, -S(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, 3*pi/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, 3*pi/2, -pi/2, pi/2) * JzBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 3*pi/2, 0) * JxBra(j, mi), (mi, -j, j))
assert JzBra(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) * JzKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jx') == Sum(
WignerD(j, mi, m, 0, 3*pi/2, 0) * JxKet(j, mi), (mi, -j, j))
assert JzKet(j, m).rewrite('Jy') == Sum(
WignerD(j, mi, m, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, pi/2, pi/2) * JyKet(j2, mi), (mi, -j2, j2)))
def test_rewrite_coupled_state():
# Numerical
assert JyKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JyKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jx') == \
-I*JxKetCoupled(1, 1, (S(1)/2, S(1)/2))
assert JyKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jx') == \
JxKetCoupled(1, 0, (S(1)/2, S(1)/2))
assert JyKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jx') == \
I*JxKetCoupled(1, -1, (S(1)/2, S(1)/2))
assert JzKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jx') == \
JxKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JzKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 - sqrt(2)*JxKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 + JxKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jx') == \
sqrt(2)*JxKetCoupled(1, 1, (S(
1)/2, S(1)/2))/2 - sqrt(2)*JxKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jx') == \
JxKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 + sqrt(2)*JxKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 + JxKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JxKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JxKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jy') == \
I*JyKetCoupled(1, 1, (S(1)/2, S(1)/2))
assert JxKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jy') == \
JyKetCoupled(1, 0, (S(1)/2, S(1)/2))
assert JxKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jy') == \
-I*JyKetCoupled(1, -1, (S(1)/2, S(1)/2))
assert JzKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jy') == \
JyKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JzKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jy') == \
JyKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 - JyKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jy') == \
-I*sqrt(2)*JyKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 - I*sqrt(
2)*JyKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jy') == \
-JyKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 - I*sqrt(2)*JyKetCoupled(1, 0, (S(1)/2, S(1)/2))/2 + JyKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JxKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JxKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 + JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JxKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jz') == \
-sqrt(2)*JzKetCoupled(1, 1, (S(
1)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JxKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 - sqrt(2)*JzKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 + JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JyKetCoupled(0, 0, (S(1)/2, S(1)/2)).rewrite('Jz') == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2))
assert JyKetCoupled(1, 1, (S(1)/2, S(1)/2)).rewrite('Jz') == \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (
S(1)/2, S(1)/2))/2 - JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JyKetCoupled(1, 0, (S(1)/2, S(1)/2)).rewrite('Jz') == \
I*sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 + I*sqrt(
2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/2
assert JyKetCoupled(1, -1, (S(1)/2, S(1)/2)).rewrite('Jz') == \
-JzKetCoupled(1, 1, (S(1)/2, S(1)/2))/2 + I*sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2))/2 + JzKetCoupled(1, -1, (S(1)/2, S(1)/2))/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, 3*pi/2, 0) * JxKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JxKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, 3*pi/2, 0, 0) * JyKetCoupled(j, mi, (
j1, j2)), (mi, -j, j))
assert JzKetCoupled(j, m, (j1, j2)).rewrite('Jy') == \
Sum(WignerD(j, mi, m, 3*pi/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, 3*pi/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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2)) == \
expand(uncouple(couple(
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2)) )))
# j1=1/2, j2=1
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)) == \
expand(uncouple(
couple( TensorProduct(JzKet(S(1)/2, S(-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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/
2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(
JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) )))
# Coupling j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
# j1=1/2, j2=1, j3=1/2
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(
-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/
2), JzKet(1, -1), JzKet(S(1)/2, S(-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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(
1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2),
JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(
S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
# j1=1/2, j2=1/2, j3=1, j4=1/2
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(1)/2)), ((1, 3), (2, 4), (1, 2)) )))
assert TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-1)/2)) == \
expand(uncouple(couple( TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(S(1)/2, S(-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(1)/2, S(1)/2))) == \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))/2 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))/2
assert uncouple(JzKetCoupled(1, 1, (S(1)/2, S(1)/2))) == \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2))) == \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))/2 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))/2
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2))
# j1=1, j2=1/2
assert uncouple(JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2))) == \
-sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S(1)/2, S(1)/2))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 1), JzKet(S(1)/2, -S(1)/2))/3
assert uncouple(JzKetCoupled(S(1)/2, -S(1)/2, (1, S(1)/2))) == \
sqrt(3)*TensorProduct(JzKet(1, 0), JzKet(S(1)/2, -S(1)/2))/3 - \
sqrt(6)*TensorProduct(JzKet(1, -1), JzKet(S(1)/2, S(1)/2))/3
assert uncouple(JzKetCoupled(S(3)/2, S(3)/2, (1, S(1)/2))) == \
TensorProduct(JzKet(1, 1), JzKet(S(1)/2, S(1)/2))
assert uncouple(JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2))) == \
sqrt(3)*TensorProduct(JzKet(1, 1), JzKet(S(1)/2, -S(1)/2))/3 + \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S(1)/2, S(1)/2))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(1)/2, (1, S(1)/2))) == \
sqrt(6)*TensorProduct(JzKet(1, 0), JzKet(S(1)/2, -S(1)/2))/3 + \
sqrt(3)*TensorProduct(JzKet(1, -1), JzKet(S(1)/2, S(1)/2))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(3)/2, (1, S(1)/2))) == \
TensorProduct(JzKet(1, -1), JzKet(S(1)/2, -S(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(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2))) == \
TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))
assert uncouple(JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2))) == \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))/3 + \
sqrt(3)*TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2))) == \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))/3 + \
sqrt(3)*TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2))) == \
TensorProduct(JzKet(
S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2))
# j1=1/2, j2=1/2, j3=1
assert uncouple(JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1))) == \
TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))
assert uncouple(JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1))) == \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1))) == \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1))) == \
TensorProduct(
JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1))
assert uncouple(JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1))) == \
-TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))/2 + \
TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1))/2
# j1=1/2, j2=1, j3=1
assert uncouple(JzKetCoupled(S(5)/2, S(5)/2, (S(1)/2, 1, 1))) == \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, 1, 1))) == \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/5 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/5 + \
sqrt(5)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(S(5)/2, -S(5)/2, (S(1)/2, 1, 1))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1))) == \
-sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/15 - \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, 0))/5
assert uncouple(JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1))) == \
-4*sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 - \
2*sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/15 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, -1))/5
assert uncouple(JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1))) == \
-sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
2*sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/15 - \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
4*sqrt(5)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1))) == \
-sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/5 + \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, -1))/2
assert uncouple(JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1))) == \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/6 - \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S(1)/2, S(1)/2), 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(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )) == \
-sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1))/3
# j1=1/2, j2=1, j3=1, j13=1/2
assert uncouple(JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)))) == \
-sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, 0))/3
assert uncouple(JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)))) == \
-2*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/3 - \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1),
JzKet(1, -1))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 + \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
2*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(
JzKet(S(1)/2, S(1)/2), 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(1)/2, S(1)/2, 1, 1))) == \
TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S(1)/2, S(1)/2, 1, 1))) == \
TensorProduct(JzKet(S(1)/2, -S(
1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1, 1))) == \
-TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/2 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/4 + \
TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1, 1))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1, 1))) == \
-sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/30 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/5
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/10 - \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/20 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/20 - \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1, 1))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/5 - \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/20 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), 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(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/2 + \
sqrt(2)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/2
assert uncouple(JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/6 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/6 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, 0), JzKet(1, -1))/4
assert uncouple(JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 2)))) == \
-sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/2 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/4 - \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/2 + \
TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/2 - \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 1), (1, 3, 1)))) == \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/2 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/4 - \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/4 + \
sqrt(2)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(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(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(
S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))
assert uncouple(JzKetCoupled(3, 2, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/3
assert uncouple(JzKetCoupled(3, 1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, 0, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/10 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/5 + \
sqrt(5)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(10)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(3, -1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/15 + \
2*sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/15 + \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, -1), JzKet(1, -1))/15
assert uncouple(JzKetCoupled(3, -2, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/3 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, -1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(3, -3, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 3)))) == \
TensorProduct(JzKet(S(1)/2, -S(
1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, -1))
assert uncouple(JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/3 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/6
assert uncouple(JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/3 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/12 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/12 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/12 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 + \
sqrt(3)*TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/6
assert uncouple(JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/2 - \
TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/2 + \
TensorProduct(JzKet(S(
1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/2
assert uncouple(JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/6 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/3 - \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/6 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/12 + \
sqrt(6)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/12 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 2)))) == \
-sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/6 - \
sqrt(6)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/6 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))/3 + \
sqrt(3)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
-S(1)/2), JzKet(1, -1), JzKet(1, -1))/3
assert uncouple(JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 1))/5 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/20 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 1), JzKet(1, -1))/30
assert uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 1))/10 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, 0))/10 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/30 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/10 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), JzKet(1, 0), JzKet(1, -1))/10
assert uncouple(JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1, 1), ((1, 2, 1), (3, 4, 2), (1, 3, 1)))) == \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 1))/30 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, 0))/15 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1), JzKet(1, -1))/30 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1), JzKet(1, 0))/20 - \
sqrt(30)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0), JzKet(1, -1))/20 + \
sqrt(15)*TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2,
S(1)/2), 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(1)/2, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S(1)/2, S(1)/2)) )))
assert JzKetCoupled(1, 1, (S(1)/2, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, S(1)/2)) )))
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, S(1)/2)) )))
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, S(1)/2)) )))
# j1=1, j2=1/2
assert JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2)) )))
assert JzKetCoupled(S(1)/2, -S(1)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, -S(1)/2, (1, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(3)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(3)/2, (1, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, -S(1)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, -S(1)/2, (1, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, -S(3)/2, (1, S(1)/2)) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, -S(3)/2, (1, S(1)/2)) )))
# 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(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(1, 0, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(1, -1, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(2, 2, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(2, 1, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(2, 0, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(2, -1, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S(1)/2, S(3)/2)) )))
assert JzKetCoupled(2, -2, (S(1)/2, S(3)/2)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S(1)/2, S(3)/2)) )))
def test_couple_3_states():
# Default coupling
# j1=1/2, j2=1/2, j3=1/2
assert JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2)) )))
# j1=1/2, j2=1/2, j3=1
assert JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1)) )))
# Couple j1+j3=j13, j13+j2=j
# j1=1/2, j2=1/2, j3=1/2, j13=0
assert JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(
1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2))) ), ((1, 3), (1, 2)) ))
# j1=1, j2=1/2, j3=1, j13=1
assert JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(1)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(1)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(1)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(1)/2, S(-1)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(1)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(-1)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(1)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(3)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(3)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(1)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(-1)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(-1)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) ), ((1, 3), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(-3)/2, (1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(3)/2))) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(-3)/2, (
1, S(1)/2, 1), ((1, 3, 1), (1, 2, S(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(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(
uncouple( JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(
uncouple( JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(2, 2, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(
uncouple( JzKetCoupled(2, 2, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(2, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(
uncouple( JzKetCoupled(2, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(
uncouple( JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(2, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(2, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
assert JzKetCoupled(2, -2, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) == \
expand(couple(uncouple(
JzKetCoupled(2, -2, (S(1)/2, S(1)/2, S(1)/2, S(1)/2)) )))
# j1=1/2, j2=1/2, j3=1/2, j4=1
assert JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(5)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(5)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) )))
assert JzKetCoupled(S(5)/2, S(-5)/2, (S(1)/2, S(1)/2, S(1)/2, 1)) == \
expand(couple(uncouple(
JzKetCoupled(S(5)/2, S(-5)/2, (S(1)/2, S(1)/2, S(1)/2, 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(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (2, 4, 0), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((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(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(1)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(1)/2)) )), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(1)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(1)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(1)/2)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(-1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(3)/2)) ) == \
expand(couple(uncouple( JzKetCoupled(S(3)/2, S(-3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 3, 1), (2, 4, S(1)/2), (1, 2, S(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(1)/2, 1, S(1)/2, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 0), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 0), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, 1, S(1)/2, 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(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 0)) ) == \
expand(couple(uncouple( JzKetCoupled(0, 0, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 0))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 1, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 1, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, 0, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, 0, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(1, -1, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 1)) ) == \
expand(couple(uncouple( JzKetCoupled(1, -1, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 1))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 2, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 2, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 1, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 1, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, 0, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, 0, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -1, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -1, (S(1)/2, 1, S(1)/2, 1), (
(1, 3, 1), (2, 4, 1), (1, 2, 2))) ), ((1, 3), (2, 4), (1, 2)) ))
assert JzKetCoupled(2, -2, (S(1)/2, 1, S(1)/2, 1), ((1, 3, 1), (2, 4, 1), (1, 2, 2)) ) == \
expand(couple(uncouple( JzKetCoupled(2, -2, (S(1)/2, 1, S(1)/2, 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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2))
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))) == \
sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(2)*JzKetCoupled(0, 0, (S(
1)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2))) == \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2))
# j1=1, j2=1/2
assert couple(TensorProduct(JzKet(1, 1), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(S(3)/2, S(3)/2, (1, S(1)/2))
assert couple(TensorProduct(JzKet(1, 1), JzKet(S(1)/2, -S(1)/2))) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2))/3 + sqrt(
3)*JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(3)*JzKetCoupled(S(1)/2, S(1)/2, (1, S(1)/2))/3 + \
sqrt(6)*JzKetCoupled(S(3)/2, S(1)/2, (1, S(1)/2))/3
assert couple(TensorProduct(JzKet(1, 0), JzKet(S(1)/2, -S(1)/2))) == \
sqrt(3)*JzKetCoupled(S(1)/2, -S(1)/2, (1, S(1)/2))/3 + \
sqrt(6)*JzKetCoupled(S(3)/2, -S(1)/2, (1, S(1)/2))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (1, S(
1)/2))/3 + sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (1, S(1)/2))/3
assert couple(TensorProduct(JzKet(1, -1), JzKet(S(1)/2, -S(1)/2))) == \
JzKetCoupled(S(3)/2, -S(3)/2, (1, S(1)/2))
# 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(S(3)/2, S(3)/2), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(2, 2, (S(3)/2, S(1)/2))
assert couple(TensorProduct(JzKet(S(3)/2, S(3)/2), JzKet(S(1)/2, -S(1)/2))) == \
sqrt(3)*JzKetCoupled(
1, 1, (S(3)/2, S(1)/2))/2 + JzKetCoupled(2, 1, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
-JzKetCoupled(1, 1, (S(
3)/2, S(1)/2))/2 + sqrt(3)*JzKetCoupled(2, 1, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2))) == \
sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(2, 0, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(2)*JzKetCoupled(1, 0, (S(
3)/2, S(1)/2))/2 + sqrt(2)*JzKetCoupled(2, 0, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2))) == \
JzKetCoupled(1, -1, (S(
3)/2, S(1)/2))/2 + sqrt(3)*JzKetCoupled(2, -1, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, -S(3)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(3)*JzKetCoupled(1, -1, (S(3)/2, S(1)/2))/2 + \
JzKetCoupled(2, -1, (S(3)/2, S(1)/2))/2
assert couple(TensorProduct(JzKet(S(3)/2, -S(3)/2), JzKet(S(1)/2, -S(1)/2))) == \
JzKetCoupled(2, -2, (S(3)/2, S(1)/2))
def test_couple_3_states_numerical():
# Default coupling
# j1=1/2,j2=1/2,j3=1/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(S(3)/2, S(
3)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 2, 1), (1, 3, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
JzKetCoupled(S(3)/2, -S(
3)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2)) )
# j1=S(1)/2, j2=S(1)/2, j3=1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 0)) )/6 + \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 0)) )/6 - \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
sqrt(3)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 1)) )/2 + \
sqrt(2)*JzKetCoupled(
2, -1, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, -S(1)/2), JzKet(S(1)/2, -S(1)/2), JzKet(1, -1))) == \
JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, 2)) )
# j1=S(1)/2, j2=1, j3=1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1))) == \
JzKetCoupled(
S(5)/2, S(5)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/2 + \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
2*sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
4*sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1))) == \
-2*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 + \
2*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1))) == \
sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, 1))) == \
-sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, 0))) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 - \
2*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, -1))) == \
-2*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
4*sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, 0))) == \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(1)/2), (1, 3, S(3)/2)) )/3 + \
2*sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(1)/2)) )/2 - \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
2, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, -1))) == \
JzKetCoupled(S(
5)/2, -S(5)/2, (S(1)/2, 1, 1), ((1, 2, S(3)/2), (1, 3, S(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(1)/2, j2=S(1)/2, j3=S(3)/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(3)/2))) == \
JzKetCoupled(S(5)/2, S(
5)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(1)/2))) == \
sqrt(10)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/5 + \
sqrt(15)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-1)/2))) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
2*sqrt(30)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/15 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-3)/2))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/2 + \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(3)/2))) == \
sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/
2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/30 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/30 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-3)/2))) == \
sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(3)/2))) == \
-sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/
2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/30 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-1)/2))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/30 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-3)/2))) == \
-sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 0), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(3)/2))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/2 - \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(1)/2))) == \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(1)/2)) )/6 - \
2*sqrt(30)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/15 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-1)/2))) == \
-sqrt(10)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(3)/2)) )/5 + \
sqrt(15)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(
3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-3)/2))) == \
JzKetCoupled(S(5)/2, -S(
5)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 2, 1), (1, 3, S(5)/2)) )
# Couple j1 to j3
# j1=1/2, j2=1/2, j3=1/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(3)/2, S(
3)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(3)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/
2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 0), (1, 2, S(1)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)
/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(3)/2, -S(
3)/2, (S(1)/2, S(1)/2, S(1)/2), ((1, 3, 1), (1, 2, S(3)/2)) )
# j1=1/2, j2=1/2, j3=1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, 2, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 0)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
JzKetCoupled(
2, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
JzKetCoupled(2, 1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 0)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/3 + \
sqrt(3)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/3
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/2 + \
JzKetCoupled(
2, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
sqrt(6)*JzKetCoupled(
2, 0, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(1)/2), (1, 2, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 1)) )/6 + \
sqrt(2)*JzKetCoupled(
2, -1, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(2, -2, (S(1)/2, S(1)/2, 1), ((1, 3, S(3)/2), (1, 2, 2)) )
# j 1=1/2, j 2=1, j 3=1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(
S(5)/2, S(5)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
2*sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 + \
2*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/2 + \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
4*sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
4*sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/2 - \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 - \
2*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(
5)/2, S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 - \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, 0), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
-sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, 1)), ((1, 3), (1, 2)) ) == \
-2*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, 0)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(1)/2), (1, 2, S(3)/2)) )/3 + \
2*sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, 1, 1), ((1,
3, S(3)/2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(1, -1), JzKet(1, -1)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(
5)/2, -S(5)/2, (S(1)/2, 1, 1), ((1, 3, S(3)/2), (1, 2, S(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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(3)/2)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(5)/2, S(
5)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 - \
sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(15)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-3)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/2 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 - \
sqrt(15)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(3)/2)), ((1, 3), (1, 2)) ) == \
2*sqrt(5)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/
2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/6 + \
3*sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-3)/2)), ((1, 3), (1, 2)) ) == \
sqrt(3)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 + \
sqrt(5)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(3)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(3)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 - \
sqrt(5)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(1)/2, S(3)/
2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 - \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(30)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 - \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/6 - \
3*sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(3)/2, S(-3)/2)), ((1, 3), (1, 2)) ) == \
-2*sqrt(5)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)
/2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(3)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/2 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 + \
sqrt(15)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(1)/2)), ((1, 3), (1, 2)) ) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(1)/2)) )/6 - \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/5 + \
sqrt(30)*JzKetCoupled(S(5)/2, -S(
1)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-1)/2)), ((1, 3), (1, 2)) ) == \
-JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 1), (1, 2, S(3)/2)) )/2 + \
sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(3)/2)) )/10 + \
sqrt(15)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(1)/2, S(
3)/2), ((1, 3, 2), (1, 2, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(3)/2, S(-3)/2)), ((1, 3), (1, 2)) ) == \
JzKetCoupled(S(5)/2, -S(
5)/2, (S(1)/2, S(1)/2, S(3)/2), ((1, 3, 2), (1, 2, S(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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(2, 2, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
sqrt(6)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/3 - \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)) )/3 + \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/3 + \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2),
JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 0), (1, 3, S(1)/2), (1, 4, 0)))/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)))/6 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)))/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)))/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2),
((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)))/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
-JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)) )/6 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 - \
sqrt(6)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 - \
sqrt(3)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
-JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 - \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)) )/6 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 + \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 - \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
-sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, 1)) )/2 + \
sqrt(6)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/6 + \
sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2))) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 0)) )/3 - \
sqrt(3)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/3 - \
sqrt(6)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2))) == \
-sqrt(6)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, 1)) )/3 + \
sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/6 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2))) == \
-sqrt(3)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2))) == \
JzKetCoupled(2, -2, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, 2)) )
# j1=S(1)/2, S(1)/2, S(1)/2, 1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
JzKetCoupled(S(5)/2, S(5)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/2 + \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1))) == \
sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 + \
2*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1))) == \
2*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
sqrt(3)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 + \
sqrt(6)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1))) == \
-sqrt(3)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 + \
sqrt(6)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1))) == \
sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
-sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/2 - \
sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
-sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 - \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
-sqrt(3)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(6)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1))) == \
sqrt(3)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(6)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0))) == \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 - \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1))) == \
-sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/2 + \
sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/6 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1))) == \
2*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(1)/2)) )/3 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/3 - \
2*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1))) == \
-sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(1)/2), (1, 4, S(3)/2)) )/3 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1))) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(1)/2)) )/2 - \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0))) == \
-sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1))) == \
JzKetCoupled(S(5)/2, -S(5)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (1, 3, S(3)/2), (1, 4, S(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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, 2, (S(
1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 + \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, 1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 0), (1, 3, 0)) )/2 - \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/6 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 - \
JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 0), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(0, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 0)) )/3 - \
sqrt(2)*JzKetCoupled(1, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
sqrt(6)*JzKetCoupled(2, 0, (S(1)/2, S(1)/2, S(1)/2, S(1)/
2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/6
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 0), (1, 3, 1)) )/2 - \
JzKetCoupled(1, -1, (S(1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 1)) )/2 + \
JzKetCoupled(2, -1, (S(1)/2, S(
1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )/2
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(2, -2, (S(
1)/2, S(1)/2, S(1)/2, S(1)/2), ((1, 2, 1), (3, 4, 1), (1, 3, 2)) )
# j1=S(1)/2, S(1)/2, S(1)/2, 1
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(S(5)/2, S(5)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
2*sqrt(15)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
2*sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 - \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
4*sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/2 + \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/3 + \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 + \
sqrt(6)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/30 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 + \
sqrt(6)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/30 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/3 - \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/2 - \
sqrt(30)*JzKetCoupled(S(3)/2, S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(6)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(3)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/3 + \
JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(5)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(6)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/6 + \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/30 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(3)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(6)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/30 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/6 - \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 - \
sqrt(3)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/3 - \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 + \
sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 0), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/2 + \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/10 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(2)*JzKetCoupled(S(1)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/2 - \
sqrt(10)*JzKetCoupled(S(3)/2, S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/5 + \
sqrt(10)*JzKetCoupled(S(5)/2, S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/3 + \
JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
4*sqrt(5)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
sqrt(6)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
sqrt(30)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(5)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 1)), ((1, 2), (3, 4), (1, 3)) ) == \
2*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(1)/2)) )/3 + \
sqrt(2)*JzKetCoupled(S(1)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(1)/2)) )/6 - \
sqrt(2)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
2*sqrt(10)*JzKetCoupled(S(3)/2, -S(1)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(1)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/10
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, 0)), ((1, 2), (3, 4), (1, 3)) ) == \
-sqrt(3)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(1)/2), (1, 3, S(3)/2)) )/3 - \
2*sqrt(15)*JzKetCoupled(S(3)/2, -S(3)/2, (S(1)/2, S(1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(3)/2)) )/15 + \
sqrt(10)*JzKetCoupled(S(5)/2, -S(3)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(5)/2)) )/5
assert couple(TensorProduct(JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(S(1)/2, S(-1)/2), JzKet(1, -1)), ((1, 2), (3, 4), (1, 3)) ) == \
JzKetCoupled(S(5)/2, -S(5)/2, (S(1)/2, S(
1)/2, S(1)/2, 1), ((1, 2, 1), (3, 4, S(3)/2), (1, 3, S(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(1)/2, S(1)/2), JzKet(S(1)/2, -S(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(1)/2, S(1)/2), JzKet(S(1)/2, S(1)/2)).doit() == -sqrt(2)/2
assert InnerProduct(JyBra(1, 1), JzKet(1, 1)).doit() == S(1)/2
assert InnerProduct(JxBra(1, -1), JyKet(1, 1)).doit() == 0
def test_rotation_small_d():
# Symbolic tests
# j = 1/2
assert Rotation.d(S(1)/2, S(1)/2, S(1)/2, beta).doit() == cos(beta/2)
assert Rotation.d(S(1)/2, S(1)/2, -S(1)/2, beta).doit() == -sin(beta/2)
assert Rotation.d(S(1)/2, -S(1)/2, S(1)/2, beta).doit() == sin(beta/2)
assert Rotation.d(S(1)/2, -S(1)/2, -S(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, S(3)/2, S(3)/2, beta).doit() == (3*cos(beta/2) + cos(3*beta/2))/4
assert Rotation.d(S(3)/2, S(
3)/2, S(1)/2, beta).doit() == -sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4
assert Rotation.d(S(3)/2, S(
3)/2, -S(1)/2, beta).doit() == sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4
assert Rotation.d(S(3)/2, S(
3)/2, -S(3)/2, beta).doit() == (-3*sin(beta/2) + sin(3*beta/2))/4
assert Rotation.d(S(3)/2, S(
1)/2, S(3)/2, beta).doit() == sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4
assert Rotation.d(S(
3)/2, S(1)/2, S(1)/2, beta).doit() == (cos(beta/2) + 3*cos(3*beta/2))/4
assert Rotation.d(S(
3)/2, S(1)/2, -S(1)/2, beta).doit() == (sin(beta/2) - 3*sin(3*beta/2))/4
assert Rotation.d(S(3)/2, S(
1)/2, -S(3)/2, beta).doit() == sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
1)/2, S(3)/2, beta).doit() == sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
1)/2, S(1)/2, beta).doit() == (-sin(beta/2) + 3*sin(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
1)/2, -S(1)/2, beta).doit() == (cos(beta/2) + 3*cos(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
1)/2, -S(3)/2, beta).doit() == -sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4
assert Rotation.d(S(
3)/2, -S(3)/2, S(3)/2, beta).doit() == (3*sin(beta/2) - sin(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
3)/2, S(1)/2, beta).doit() == sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
3)/2, -S(1)/2, beta).doit() == sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4
assert Rotation.d(S(3)/2, -S(
3)/2, -S(3)/2, beta).doit() == (3*cos(beta/2) + cos(3*beta/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(1)/2, S(1)/2, S(1)/2, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S(1)/2, S(1)/2, -S(1)/2, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(S(1)/2, -S(1)/2, S(1)/2, pi/2).doit() == sqrt(2)/2
assert Rotation.d(S(1)/2, -S(1)/2, -S(1)/2, pi/2).doit() == sqrt(2)/2
# j = 1
assert Rotation.d(1, 1, 1, pi/2).doit() == 1/2
assert Rotation.d(1, 1, 0, pi/2).doit() == -sqrt(2)/2
assert Rotation.d(1, 1, -1, pi/2).doit() == 1/2
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() == 1/2
assert Rotation.d(1, -1, 0, pi/2).doit() == sqrt(2)/2
assert Rotation.d(1, -1, -1, pi/2).doit() == 1/2
# j = 3/2
assert Rotation.d(S(3)/2, S(3)/2, S(3)/2, pi/2).doit() == sqrt(2)/4
assert Rotation.d(S(3)/2, S(3)/2, S(1)/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.d(S(3)/2, S(3)/2, -S(1)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, S(3)/2, -S(3)/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(S(3)/2, S(1)/2, S(3)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, S(1)/2, S(1)/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(S(3)/2, S(1)/2, -S(1)/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(S(3)/2, S(1)/2, -S(3)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, -S(1)/2, S(3)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, -S(1)/2, S(1)/2, pi/2).doit() == sqrt(2)/4
assert Rotation.d(S(3)/2, -S(1)/2, -S(1)/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.d(S(3)/2, -S(1)/2, -S(3)/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.d(S(3)/2, -S(3)/2, S(3)/2, pi/2).doit() == sqrt(2)/4
assert Rotation.d(S(3)/2, -S(3)/2, S(1)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, -S(3)/2, -S(1)/2, pi/2).doit() == sqrt(6)/4
assert Rotation.d(S(3)/2, -S(3)/2, -S(3)/2, pi/2).doit() == sqrt(2)/4
# j = 2
assert Rotation.d(2, 2, 2, pi/2).doit() == 1/4
assert Rotation.d(2, 2, 1, pi/2).doit() == -1/2
assert Rotation.d(2, 2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, 2, -1, pi/2).doit() == -1/2
assert Rotation.d(2, 2, -2, pi/2).doit() == 1/4
assert Rotation.d(2, 1, 2, pi/2).doit() == 1/2
assert Rotation.d(2, 1, 1, pi/2).doit() == -1/2
assert Rotation.d(2, 1, 0, pi/2).doit() == 0
assert Rotation.d(2, 1, -1, pi/2).doit() == 1/2
assert Rotation.d(2, 1, -2, pi/2).doit() == -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() == -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() == 1/2
assert Rotation.d(2, -1, 1, pi/2).doit() == 1/2
assert Rotation.d(2, -1, 0, pi/2).doit() == 0
assert Rotation.d(2, -1, -1, pi/2).doit() == -1/2
assert Rotation.d(2, -1, -2, pi/2).doit() == -1/2
assert Rotation.d(2, -2, 2, pi/2).doit() == 1/4
assert Rotation.d(2, -2, 1, pi/2).doit() == 1/2
assert Rotation.d(2, -2, 0, pi/2).doit() == sqrt(6)/4
assert Rotation.d(2, -2, -1, pi/2).doit() == 1/2
assert Rotation.d(2, -2, -2, pi/2).doit() == 1/4
def test_rotation_d():
# Symbolic tests
# j = 1/2
assert Rotation.D(S(1)/2, S(1)/2, S(1)/2, alpha, beta, gamma).doit() == \
cos(beta/2)*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(1)/2, S(1)/2, -S(1)/2, alpha, beta, gamma).doit() == \
-sin(beta/2)*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S(1)/2, -S(1)/2, S(1)/2, alpha, beta, gamma).doit() == \
sin(beta/2)*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(1)/2, -S(1)/2, -S(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(S(3)/2, S(3)/2, S(3)/2, alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(3*beta/2))/4*exp(-3*I*alpha/2)*exp(-3*I*gamma/2)
assert Rotation.D(S(3)/2, S(3)/2, S(1)/2, alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4*exp(-3*I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(3)/2, S(3)/2, -S(1)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4*exp(-3*I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S(3)/2, S(3)/2, -S(3)/2, alpha, beta, gamma).doit() == \
(-3*sin(beta/2) + sin(3*beta/2))/4*exp(-3*I*alpha/2)*exp(3*I*gamma/2)
assert Rotation.D(S(3)/2, S(1)/2, S(3)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4*exp(-I*alpha/2)*exp(-3*I*gamma/2)
assert Rotation.D(S(3)/2, S(1)/2, S(1)/2, alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(3*beta/2))/4*exp(-I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(3)/2, S(1)/2, -S(1)/2, alpha, beta, gamma).doit() == \
(sin(beta/2) - 3*sin(3*beta/2))/4*exp(-I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S(3)/2, S(1)/2, -S(3)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4*exp(-I*alpha/2)*exp(3*I*gamma/2)
assert Rotation.D(S(3)/2, -S(1)/2, S(3)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4*exp(I*alpha/2)*exp(-3*I*gamma/2)
assert Rotation.D(S(3)/2, -S(1)/2, S(1)/2, alpha, beta, gamma).doit() == \
(-sin(beta/2) + 3*sin(3*beta/2))/4*exp(I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(3)/2, -S(1)/2, -S(1)/2, alpha, beta, gamma).doit() == \
(cos(beta/2) + 3*cos(3*beta/2))/4*exp(I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S(3)/2, -S(1)/2, -S(3)/2, alpha, beta, gamma).doit() == \
-sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4*exp(I*alpha/2)*exp(3*I*gamma/2)
assert Rotation.D(S(3)/2, -S(3)/2, S(3)/2, alpha, beta, gamma).doit() == \
(3*sin(beta/2) - sin(3*beta/2))/4*exp(3*I*alpha/2)*exp(-3*I*gamma/2)
assert Rotation.D(S(3)/2, -S(3)/2, S(1)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(cos(beta/2) - cos(3*beta/2))/4*exp(3*I*alpha/2)*exp(-I*gamma/2)
assert Rotation.D(S(3)/2, -S(3)/2, -S(1)/2, alpha, beta, gamma).doit() == \
sqrt(3)*(sin(beta/2) + sin(3*beta/2))/4*exp(3*I*alpha/2)*exp(I*gamma/2)
assert Rotation.D(S(3)/2, -S(3)/2, -S(3)/2, alpha, beta, gamma).doit() == \
(3*cos(beta/2) + cos(3*beta/2))/4*exp(3*I*alpha/2)*exp(3*I*gamma/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(1)/2, S(1)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/2
assert Rotation.D(
S(1)/2, S(1)/2, -S(1)/2, pi/2, pi/2, pi/2).doit() == -sqrt(2)/2
assert Rotation.D(
S(1)/2, -S(1)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == sqrt(2)/2
assert Rotation.D(
S(1)/2, -S(1)/2, -S(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() == -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() == 1/2
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() == 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() == -1/2
# j = 3/2
assert Rotation.D(
S(3)/2, S(3)/2, S(3)/2, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
S(3)/2, S(3)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
S(3)/2, S(3)/2, -S(1)/2, pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
S(3)/2, S(3)/2, -S(3)/2, pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
S(3)/2, S(1)/2, S(3)/2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
S(3)/2, S(1)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == I*sqrt(2)/4
assert Rotation.D(
S(3)/2, S(1)/2, -S(1)/2, pi/2, pi/2, pi/2).doit() == -sqrt(2)/4
assert Rotation.D(
S(3)/2, S(1)/2, -S(3)/2, pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
S(3)/2, -S(1)/2, S(3)/2, pi/2, pi/2, pi/2).doit() == -I*sqrt(6)/4
assert Rotation.D(
S(3)/2, -S(1)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
S(3)/2, -S(1)/2, -S(1)/2, pi/2, pi/2, pi/2).doit() == -I*sqrt(2)/4
assert Rotation.D(
S(3)/2, -S(1)/2, -S(3)/2, pi/2, pi/2, pi/2).doit() == sqrt(6)/4
assert Rotation.D(
S(3)/2, -S(3)/2, S(3)/2, pi/2, pi/2, pi/2).doit() == sqrt(2)/4
assert Rotation.D(
S(3)/2, -S(3)/2, S(1)/2, pi/2, pi/2, pi/2).doit() == I*sqrt(6)/4
assert Rotation.D(
S(3)/2, -S(3)/2, -S(1)/2, pi/2, pi/2, pi/2).doit() == -sqrt(6)/4
assert Rotation.D(
S(3)/2, -S(3)/2, -S(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() == 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() == 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() == 1/2
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() == 1/2
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() == -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() == 1/2
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() == 1/2
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() == 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() == 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_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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi + 1, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi + 1, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi + 1, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi + 1, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j, mi1, mi - 1, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(
WignerD(j, mi1, mi - 1, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j1, mi1, mi - 1, 3*pi/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, 3*pi/2, -pi/2, pi/2) *
Sum(WignerD(j2, mi1, mi - 1, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, 0)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jz*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j, mi1,
mi, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j, mi1, mi, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, 3*pi/2, pi/2, pi/2)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2))) + \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, 3*pi/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, 3*pi/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, 3*pi/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, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j1, mi1, mi, 3*pi/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, 3*pi/2, -pi/2, pi/2)*Sum(WignerD(j2, mi1, mi, 3*pi/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(S(2)/3, -S(1)/3))
raises(ValueError, lambda: JzKet(S(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, -S(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(1)/2))
def test_jzketcoupled():
j, m = symbols('j m')
# j not integer or half integer
raises(ValueError, lambda: JzKetCoupled(S(2)/3, -S(1)/3, (1,)))
raises(ValueError, lambda: JzKetCoupled(S(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, -S(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(1)/2, (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, (S(1)/3, S(2)/3)))
# indicies in coupling scheme must be integers
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((S(1)/2, 1, 2),) ))
raises(ValueError, lambda: JzKetCoupled(1, 1, (1, 1), ((1, S(1)/2, 2),) ))
# indicies 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),) ))
|
bsd-3-clause
|
dkcoinus/dkcoin_src
|
qa/rpc-tests/bipdersig-p2p.py
|
69
|
6594
|
#!/usr/bin/env python2
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript
from binascii import hexlify, unhexlify
import cStringIO
import time
# A canonical signature consists of:
# <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
def unDERify(tx):
'''
Make the signature in vin 0 of a tx non-DER-compliant,
by adding padding after the S-value.
'''
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
newscript.append(i[0:-1] + '\0' + i[-1])
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
'''
This test is meant to exercise BIP66 (DER SIG).
Connect to a single node.
Mine 2 (version 2) blocks (save the coinbases for later).
Generate 98 more version 2 blocks, verify the node accepts.
Mine 749 version 3 blocks, verify the node accepts.
Check that the new DERSIG rules are not enforced on the 750th version 3 block.
Check that the new DERSIG rules are enforced on the 751st version 3 block.
Mine 199 new version blocks.
Mine 1 old-version block.
Mine 1 new version block.
Mine 1 old version block, see that the node rejects.
'''
class BIP66Test(ComparisonTestFramework):
def __init__(self):
self.num_nodes = 1
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(1, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-blockversion=2']],
binary=[self.options.testbinary])
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
test.run()
def create_transaction(self, node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = cStringIO.StringIO(unhexlify(signresult['hex']))
tx.deserialize(f)
return tx
def get_tests(self):
self.coinbase_blocks = self.nodes[0].generate(2)
self.tip = int ("0x" + self.nodes[0].getbestblockhash() + "L", 0)
self.nodeaddress = self.nodes[0].getnewaddress()
self.last_block_time = time.time()
''' 98 more version 2 blocks '''
test_blocks = []
for i in xrange(98):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 2
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 749 version 3 blocks '''
test_blocks = []
for i in xrange(749):
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
'''
Check that the new DERSIG rules are not enforced in the 750th
version 3 block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[0], self.nodeaddress, 1.0)
unDERify(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(2), self.last_block_time + 1)
block.nVersion = 3
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
'''
Check that the new DERSIG rules are enforced in the 751st version 3
block.
'''
spendtx = self.create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
unDERify(spendtx)
spendtx.rehash()
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
''' Mine 199 new version blocks on last valid tip '''
test_blocks = []
for i in xrange(199):
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance(test_blocks, sync_every_block=False)
''' Mine 1 old version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 2
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 new version block '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 3
block.rehash()
block.solve()
self.last_block_time += 1
self.tip = block.sha256
yield TestInstance([[block, True]])
''' Mine 1 old version block, should be invalid '''
block = create_block(self.tip, create_coinbase(1), self.last_block_time + 1)
block.nVersion = 2
block.rehash()
block.solve()
self.last_block_time += 1
yield TestInstance([[block, False]])
if __name__ == '__main__':
BIP66Test().main()
|
mit
|
2014c2g4/c2g4
|
w2/static/Brython2.0.0-20140209-164925/Lib/unittest/test/test_case.py
|
738
|
51689
|
import difflib
import pprint
import pickle
import re
import sys
import warnings
import weakref
import inspect
from copy import deepcopy
from test import support
import unittest
from .support import (
TestEquality, TestHashing, LoggingResult,
ResultWithNoStartTestRunStopTestRun
)
class Test(object):
"Keep these TestCase classes out of the main namespace"
class Foo(unittest.TestCase):
def runTest(self): pass
def test1(self): pass
class Bar(Foo):
def test2(self): pass
class LoggingTestCase(unittest.TestCase):
"""A test case which logs its calls."""
def __init__(self, events):
super(Test.LoggingTestCase, self).__init__('test')
self.events = events
def setUp(self):
self.events.append('setUp')
def test(self):
self.events.append('test')
def tearDown(self):
self.events.append('tearDown')
class Test_TestCase(unittest.TestCase, TestEquality, TestHashing):
### Set up attributes used by inherited tests
################################################################
# Used by TestHashing.test_hash and TestEquality.test_eq
eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))]
# Used by TestEquality.test_ne
ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')),
(Test.Foo('test1'), Test.Bar('test1')),
(Test.Foo('test1'), Test.Bar('test2'))]
################################################################
### /Set up attributes used by inherited tests
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
# ...
# "methodName defaults to "runTest"."
#
# Make sure it really is optional, and that it defaults to the proper
# thing.
def test_init__no_test_name(self):
class Test(unittest.TestCase):
def runTest(self): raise MyException()
def test(self): pass
self.assertEqual(Test().id()[-13:], '.Test.runTest')
# test that TestCase can be instantiated with no args
# primarily for use at the interactive interpreter
test = unittest.TestCase()
test.assertEqual(3, 3)
with test.assertRaises(test.failureException):
test.assertEqual(3, 2)
with self.assertRaises(AttributeError):
test.run()
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
def test_init__test_name__valid(self):
class Test(unittest.TestCase):
def runTest(self): raise MyException()
def test(self): pass
self.assertEqual(Test('test').id()[-10:], '.Test.test')
# "class TestCase([methodName])"
# ...
# "Each instance of TestCase will run a single test method: the
# method named methodName."
def test_init__test_name__invalid(self):
class Test(unittest.TestCase):
def runTest(self): raise MyException()
def test(self): pass
try:
Test('testfoo')
except ValueError:
pass
else:
self.fail("Failed to raise ValueError")
# "Return the number of tests represented by the this test object. For
# TestCase instances, this will always be 1"
def test_countTestCases(self):
class Foo(unittest.TestCase):
def test(self): pass
self.assertEqual(Foo('test').countTestCases(), 1)
# "Return the default type of test result object to be used to run this
# test. For TestCase instances, this will always be
# unittest.TestResult; subclasses of TestCase should
# override this as necessary."
def test_defaultTestResult(self):
class Foo(unittest.TestCase):
def runTest(self):
pass
result = Foo().defaultTestResult()
self.assertEqual(type(result), unittest.TestResult)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if setUp() raises
# an exception.
def test_run_call_order__error_in_setUp(self):
events = []
result = LoggingResult(events)
class Foo(Test.LoggingTestCase):
def setUp(self):
super(Foo, self).setUp()
raise RuntimeError('raised by Foo.setUp')
Foo(events).run(result)
expected = ['startTest', 'setUp', 'addError', 'stopTest']
self.assertEqual(events, expected)
# "With a temporary result stopTestRun is called when setUp errors.
def test_run_call_order__error_in_setUp_default_result(self):
events = []
class Foo(Test.LoggingTestCase):
def defaultTestResult(self):
return LoggingResult(self.events)
def setUp(self):
super(Foo, self).setUp()
raise RuntimeError('raised by Foo.setUp')
Foo(events).run()
expected = ['startTestRun', 'startTest', 'setUp', 'addError',
'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if the test raises
# an error (as opposed to a failure).
def test_run_call_order__error_in_test(self):
events = []
result = LoggingResult(events)
class Foo(Test.LoggingTestCase):
def test(self):
super(Foo, self).test()
raise RuntimeError('raised by Foo.test')
expected = ['startTest', 'setUp', 'test', 'tearDown',
'addError', 'stopTest']
Foo(events).run(result)
self.assertEqual(events, expected)
# "With a default result, an error in the test still results in stopTestRun
# being called."
def test_run_call_order__error_in_test_default_result(self):
events = []
class Foo(Test.LoggingTestCase):
def defaultTestResult(self):
return LoggingResult(self.events)
def test(self):
super(Foo, self).test()
raise RuntimeError('raised by Foo.test')
expected = ['startTestRun', 'startTest', 'setUp', 'test',
'tearDown', 'addError', 'stopTest', 'stopTestRun']
Foo(events).run()
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if the test signals
# a failure (as opposed to an error).
def test_run_call_order__failure_in_test(self):
events = []
result = LoggingResult(events)
class Foo(Test.LoggingTestCase):
def test(self):
super(Foo, self).test()
self.fail('raised by Foo.test')
expected = ['startTest', 'setUp', 'test', 'tearDown',
'addFailure', 'stopTest']
Foo(events).run(result)
self.assertEqual(events, expected)
# "When a test fails with a default result stopTestRun is still called."
def test_run_call_order__failure_in_test_default_result(self):
class Foo(Test.LoggingTestCase):
def defaultTestResult(self):
return LoggingResult(self.events)
def test(self):
super(Foo, self).test()
self.fail('raised by Foo.test')
expected = ['startTestRun', 'startTest', 'setUp', 'test',
'tearDown', 'addFailure', 'stopTest', 'stopTestRun']
events = []
Foo(events).run()
self.assertEqual(events, expected)
# "When a setUp() method is defined, the test runner will run that method
# prior to each test. Likewise, if a tearDown() method is defined, the
# test runner will invoke that method after each test. In the example,
# setUp() was used to create a fresh sequence for each test."
#
# Make sure the proper call order is maintained, even if tearDown() raises
# an exception.
def test_run_call_order__error_in_tearDown(self):
events = []
result = LoggingResult(events)
class Foo(Test.LoggingTestCase):
def tearDown(self):
super(Foo, self).tearDown()
raise RuntimeError('raised by Foo.tearDown')
Foo(events).run(result)
expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
'stopTest']
self.assertEqual(events, expected)
# "When tearDown errors with a default result stopTestRun is still called."
def test_run_call_order__error_in_tearDown_default_result(self):
class Foo(Test.LoggingTestCase):
def defaultTestResult(self):
return LoggingResult(self.events)
def tearDown(self):
super(Foo, self).tearDown()
raise RuntimeError('raised by Foo.tearDown')
events = []
Foo(events).run()
expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
'addError', 'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "TestCase.run() still works when the defaultTestResult is a TestResult
# that does not support startTestRun and stopTestRun.
def test_run_call_order_default_result(self):
class Foo(unittest.TestCase):
def defaultTestResult(self):
return ResultWithNoStartTestRunStopTestRun()
def test(self):
pass
Foo('test').run()
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework. The initial value of this
# attribute is AssertionError"
def test_failureException__default(self):
class Foo(unittest.TestCase):
def test(self):
pass
self.assertTrue(Foo('test').failureException is AssertionError)
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework."
#
# Make sure TestCase.run() respects the designated failureException
def test_failureException__subclassing__explicit_raise(self):
events = []
result = LoggingResult(events)
class Foo(unittest.TestCase):
def test(self):
raise RuntimeError()
failureException = RuntimeError
self.assertTrue(Foo('test').failureException is RuntimeError)
Foo('test').run(result)
expected = ['startTest', 'addFailure', 'stopTest']
self.assertEqual(events, expected)
# "This class attribute gives the exception raised by the test() method.
# If a test framework needs to use a specialized exception, possibly to
# carry additional information, it must subclass this exception in
# order to ``play fair'' with the framework."
#
# Make sure TestCase.run() respects the designated failureException
def test_failureException__subclassing__implicit_raise(self):
events = []
result = LoggingResult(events)
class Foo(unittest.TestCase):
def test(self):
self.fail("foo")
failureException = RuntimeError
self.assertTrue(Foo('test').failureException is RuntimeError)
Foo('test').run(result)
expected = ['startTest', 'addFailure', 'stopTest']
self.assertEqual(events, expected)
# "The default implementation does nothing."
def test_setUp(self):
class Foo(unittest.TestCase):
def runTest(self):
pass
# ... and nothing should happen
Foo().setUp()
# "The default implementation does nothing."
def test_tearDown(self):
class Foo(unittest.TestCase):
def runTest(self):
pass
# ... and nothing should happen
Foo().tearDown()
# "Return a string identifying the specific test case."
#
# Because of the vague nature of the docs, I'm not going to lock this
# test down too much. Really all that can be asserted is that the id()
# will be a string (either 8-byte or unicode -- again, because the docs
# just say "string")
def test_id(self):
class Foo(unittest.TestCase):
def runTest(self):
pass
self.assertIsInstance(Foo().id(), str)
# "If result is omitted or None, a temporary result object is created,
# used, and is made available to the caller. As TestCase owns the
# temporary result startTestRun and stopTestRun are called.
def test_run__uses_defaultTestResult(self):
events = []
defaultResult = LoggingResult(events)
class Foo(unittest.TestCase):
def test(self):
events.append('test')
def defaultTestResult(self):
return defaultResult
# Make run() find a result object on its own
result = Foo('test').run()
self.assertIs(result, defaultResult)
expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
'stopTest', 'stopTestRun']
self.assertEqual(events, expected)
# "The result object is returned to run's caller"
def test_run__returns_given_result(self):
class Foo(unittest.TestCase):
def test(self):
pass
result = unittest.TestResult()
retval = Foo('test').run(result)
self.assertIs(retval, result)
# "The same effect [as method run] may be had by simply calling the
# TestCase instance."
def test_call__invoking_an_instance_delegates_to_run(self):
resultIn = unittest.TestResult()
resultOut = unittest.TestResult()
class Foo(unittest.TestCase):
def test(self):
pass
def run(self, result):
self.assertIs(result, resultIn)
return resultOut
retval = Foo('test')(resultIn)
self.assertIs(retval, resultOut)
def testShortDescriptionWithoutDocstring(self):
self.assertIsNone(self.shortDescription())
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def testShortDescriptionWithOneLineDocstring(self):
"""Tests shortDescription() for a method with a docstring."""
self.assertEqual(
self.shortDescription(),
'Tests shortDescription() for a method with a docstring.')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def testShortDescriptionWithMultiLineDocstring(self):
"""Tests shortDescription() for a method with a longer docstring.
This method ensures that only the first line of a docstring is
returned used in the short description, no matter how long the
whole thing is.
"""
self.assertEqual(
self.shortDescription(),
'Tests shortDescription() for a method with a longer '
'docstring.')
def testAddTypeEqualityFunc(self):
class SadSnake(object):
"""Dummy class for test_addTypeEqualityFunc."""
s1, s2 = SadSnake(), SadSnake()
self.assertFalse(s1 == s2)
def AllSnakesCreatedEqual(a, b, msg=None):
return type(a) == type(b) == SadSnake
self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
self.assertEqual(s1, s2)
# No this doesn't clean up and remove the SadSnake equality func
# from this TestCase instance but since its a local nothing else
# will ever notice that.
def testAssertIs(self):
thing = object()
self.assertIs(thing, thing)
self.assertRaises(self.failureException, self.assertIs, thing, object())
def testAssertIsNot(self):
thing = object()
self.assertIsNot(thing, object())
self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
def testAssertIsInstance(self):
thing = []
self.assertIsInstance(thing, list)
self.assertRaises(self.failureException, self.assertIsInstance,
thing, dict)
def testAssertNotIsInstance(self):
thing = []
self.assertNotIsInstance(thing, dict)
self.assertRaises(self.failureException, self.assertNotIsInstance,
thing, list)
def testAssertIn(self):
animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
self.assertIn('a', 'abc')
self.assertIn(2, [1, 2, 3])
self.assertIn('monkey', animals)
self.assertNotIn('d', 'abc')
self.assertNotIn(0, [1, 2, 3])
self.assertNotIn('otter', animals)
self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
self.assertRaises(self.failureException, self.assertIn, 'elephant',
animals)
self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
self.assertRaises(self.failureException, self.assertNotIn, 'cow',
animals)
def testAssertDictContainsSubset(self):
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.assertDictContainsSubset({}, {})
self.assertDictContainsSubset({}, {'a': 1})
self.assertDictContainsSubset({'a': 1}, {'a': 1})
self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({1: "one"}, {})
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({'a': 2}, {'a': 1})
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({'c': 1}, {'a': 1})
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
one = ''.join(chr(i) for i in range(255))
# this used to cause a UnicodeDecodeError constructing the failure msg
with self.assertRaises(self.failureException):
self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
def testAssertEqual(self):
equal_pairs = [
((), ()),
({}, {}),
([], []),
(set(), set()),
(frozenset(), frozenset())]
for a, b in equal_pairs:
# This mess of try excepts is to test the assertEqual behavior
# itself.
try:
self.assertEqual(a, b)
except self.failureException:
self.fail('assertEqual(%r, %r) failed' % (a, b))
try:
self.assertEqual(a, b, msg='foo')
except self.failureException:
self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
try:
self.assertEqual(a, b, 'foo')
except self.failureException:
self.fail('assertEqual(%r, %r) with third parameter failed' %
(a, b))
unequal_pairs = [
((), []),
({}, set()),
(set([4,1]), frozenset([4,2])),
(frozenset([4,5]), set([2,3])),
(set([3,4]), set([5,4]))]
for a, b in unequal_pairs:
self.assertRaises(self.failureException, self.assertEqual, a, b)
self.assertRaises(self.failureException, self.assertEqual, a, b,
'foo')
self.assertRaises(self.failureException, self.assertEqual, a, b,
msg='foo')
def testEquality(self):
self.assertListEqual([], [])
self.assertTupleEqual((), ())
self.assertSequenceEqual([], ())
a = [0, 'a', []]
b = []
self.assertRaises(unittest.TestCase.failureException,
self.assertListEqual, a, b)
self.assertRaises(unittest.TestCase.failureException,
self.assertListEqual, tuple(a), tuple(b))
self.assertRaises(unittest.TestCase.failureException,
self.assertSequenceEqual, a, tuple(b))
b.extend(a)
self.assertListEqual(a, b)
self.assertTupleEqual(tuple(a), tuple(b))
self.assertSequenceEqual(a, tuple(b))
self.assertSequenceEqual(tuple(a), b)
self.assertRaises(self.failureException, self.assertListEqual,
a, tuple(b))
self.assertRaises(self.failureException, self.assertTupleEqual,
tuple(a), b)
self.assertRaises(self.failureException, self.assertListEqual, None, b)
self.assertRaises(self.failureException, self.assertTupleEqual, None,
tuple(b))
self.assertRaises(self.failureException, self.assertSequenceEqual,
None, tuple(b))
self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
self.assertRaises(self.failureException, self.assertSequenceEqual,
1, 1)
self.assertDictEqual({}, {})
c = { 'x': 1 }
d = {}
self.assertRaises(unittest.TestCase.failureException,
self.assertDictEqual, c, d)
d.update(c)
self.assertDictEqual(c, d)
d['x'] = 0
self.assertRaises(unittest.TestCase.failureException,
self.assertDictEqual, c, d, 'These are unequal')
self.assertRaises(self.failureException, self.assertDictEqual, None, d)
self.assertRaises(self.failureException, self.assertDictEqual, [], d)
self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
def testAssertSequenceEqualMaxDiff(self):
self.assertEqual(self.maxDiff, 80*8)
seq1 = 'a' + 'x' * 80**2
seq2 = 'b' + 'x' * 80**2
diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
# the +1 is the leading \n added by assertSequenceEqual
omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,)
self.maxDiff = len(diff)//2
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) < len(diff))
self.assertIn(omitted, msg)
self.maxDiff = len(diff) * 2
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) > len(diff))
self.assertNotIn(omitted, msg)
self.maxDiff = None
try:
self.assertSequenceEqual(seq1, seq2)
except self.failureException as e:
msg = e.args[0]
else:
self.fail('assertSequenceEqual did not fail.')
self.assertTrue(len(msg) > len(diff))
self.assertNotIn(omitted, msg)
def testTruncateMessage(self):
self.maxDiff = 1
message = self._truncateMessage('foo', 'bar')
omitted = unittest.case.DIFF_OMITTED % len('bar')
self.assertEqual(message, 'foo' + omitted)
self.maxDiff = None
message = self._truncateMessage('foo', 'bar')
self.assertEqual(message, 'foobar')
self.maxDiff = 4
message = self._truncateMessage('foo', 'bar')
self.assertEqual(message, 'foobar')
def testAssertDictEqualTruncates(self):
test = unittest.TestCase('assertEqual')
def truncate(msg, diff):
return 'foo'
test._truncateMessage = truncate
try:
test.assertDictEqual({}, {1: 0})
except self.failureException as e:
self.assertEqual(str(e), 'foo')
else:
self.fail('assertDictEqual did not fail')
def testAssertMultiLineEqualTruncates(self):
test = unittest.TestCase('assertEqual')
def truncate(msg, diff):
return 'foo'
test._truncateMessage = truncate
try:
test.assertMultiLineEqual('foo', 'bar')
except self.failureException as e:
self.assertEqual(str(e), 'foo')
else:
self.fail('assertMultiLineEqual did not fail')
def testAssertEqual_diffThreshold(self):
# check threshold value
self.assertEqual(self._diffThreshold, 2**16)
# disable madDiff to get diff markers
self.maxDiff = None
# set a lower threshold value and add a cleanup to restore it
old_threshold = self._diffThreshold
self._diffThreshold = 2**8
self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
# under the threshold: diff marker (^) in error message
s = 'x' * (2**7)
with self.assertRaises(self.failureException) as cm:
self.assertEqual(s + 'a', s + 'b')
self.assertIn('^', str(cm.exception))
self.assertEqual(s + 'a', s + 'a')
# over the threshold: diff not used and marker (^) not in error message
s = 'x' * (2**9)
# if the path that uses difflib is taken, _truncateMessage will be
# called -- replace it with explodingTruncation to verify that this
# doesn't happen
def explodingTruncation(message, diff):
raise SystemError('this should not be raised')
old_truncate = self._truncateMessage
self._truncateMessage = explodingTruncation
self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate))
s1, s2 = s + 'a', s + 'b'
with self.assertRaises(self.failureException) as cm:
self.assertEqual(s1, s2)
self.assertNotIn('^', str(cm.exception))
self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2))
self.assertEqual(s + 'a', s + 'a')
def testAssertCountEqual(self):
a = object()
self.assertCountEqual([1, 2, 3], [3, 2, 1])
self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 2] + [3] * 100, [1] * 100 + [2, 3])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, "2", "a", "a"], ["a", "2", True, 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[10], [10, 11])
self.assertRaises(self.failureException, self.assertCountEqual,
[10, 11], [10])
self.assertRaises(self.failureException, self.assertCountEqual,
[10, 11, 10], [10, 11])
# Test that sequences of unhashable objects can be tested for sameness:
self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
# Test that iterator of unhashable objects can be tested for sameness:
self.assertCountEqual(iter([1, 2, [], 3, 4]),
iter([1, 2, [], 3, 4]))
# hashable types, but not orderable
self.assertRaises(self.failureException, self.assertCountEqual,
[], [divmod, 'x', 1, 5j, 2j, frozenset()])
# comparing dicts
self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
# comparing heterogenous non-hashable sequences
self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[], [divmod, [], 'x', 1, 5j, 2j, set()])
self.assertRaises(self.failureException, self.assertCountEqual,
[[1]], [[2]])
# Same elements, but not same sequence length
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 1, 2], [2, 1])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, 1, "2", "a", "a"], ["2", "2", True, "a"])
self.assertRaises(self.failureException, self.assertCountEqual,
[1, {'b': 2}, None, True], [{'b': 2}, True, None])
# Same elements which don't reliably compare, in
# different order, see issue 10242
a = [{2,4}, {1,2}]
b = a[::-1]
self.assertCountEqual(a, b)
# test utility functions supporting assertCountEqual()
diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce'))
expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
self.assertEqual(diffs, expected)
diffs = unittest.util._count_diff_all_purpose([[]], [])
self.assertEqual(diffs, [(1, 0, [])])
diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce'))
expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
self.assertEqual(diffs, expected)
def testAssertSetEqual(self):
set1 = set()
set2 = set()
self.assertSetEqual(set1, set2)
self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
set1 = set(['a'])
set2 = set()
self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
set1 = set(['a'])
set2 = set(['a'])
self.assertSetEqual(set1, set2)
set1 = set(['a'])
set2 = set(['a', 'b'])
self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
set1 = set(['a'])
set2 = frozenset(['a', 'b'])
self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
set1 = set(['a', 'b'])
set2 = frozenset(['a', 'b'])
self.assertSetEqual(set1, set2)
set1 = set()
set2 = "foo"
self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
# make sure any string formatting is tuple-safe
set1 = set([(0, 1), (2, 3)])
set2 = set([(4, 5)])
self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
def testInequality(self):
# Try ints
self.assertGreater(2, 1)
self.assertGreaterEqual(2, 1)
self.assertGreaterEqual(1, 1)
self.assertLess(1, 2)
self.assertLessEqual(1, 2)
self.assertLessEqual(1, 1)
self.assertRaises(self.failureException, self.assertGreater, 1, 2)
self.assertRaises(self.failureException, self.assertGreater, 1, 1)
self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
self.assertRaises(self.failureException, self.assertLess, 2, 1)
self.assertRaises(self.failureException, self.assertLess, 1, 1)
self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
# Try Floats
self.assertGreater(1.1, 1.0)
self.assertGreaterEqual(1.1, 1.0)
self.assertGreaterEqual(1.0, 1.0)
self.assertLess(1.0, 1.1)
self.assertLessEqual(1.0, 1.1)
self.assertLessEqual(1.0, 1.0)
self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
# Try Strings
self.assertGreater('bug', 'ant')
self.assertGreaterEqual('bug', 'ant')
self.assertGreaterEqual('ant', 'ant')
self.assertLess('ant', 'bug')
self.assertLessEqual('ant', 'bug')
self.assertLessEqual('ant', 'ant')
self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
# Try bytes
self.assertGreater(b'bug', b'ant')
self.assertGreaterEqual(b'bug', b'ant')
self.assertGreaterEqual(b'ant', b'ant')
self.assertLess(b'ant', b'bug')
self.assertLessEqual(b'ant', b'bug')
self.assertLessEqual(b'ant', b'ant')
self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
b'bug')
self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
def testAssertMultiLineEqual(self):
sample_text = """\
http://www.python.org/doc/2.3/lib/module-unittest.html
test case
A test case is the smallest unit of testing. [...]
"""
revised_sample_text = """\
http://www.python.org/doc/2.4.1/lib/module-unittest.html
test case
A test case is the smallest unit of testing. [...] You may provide your
own implementation that does not subclass from TestCase, of course.
"""
sample_text_error = """\
- http://www.python.org/doc/2.3/lib/module-unittest.html
? ^
+ http://www.python.org/doc/2.4.1/lib/module-unittest.html
? ^^^
test case
- A test case is the smallest unit of testing. [...]
+ A test case is the smallest unit of testing. [...] You may provide your
? +++++++++++++++++++++
+ own implementation that does not subclass from TestCase, of course.
"""
self.maxDiff = None
try:
self.assertMultiLineEqual(sample_text, revised_sample_text)
except self.failureException as e:
# need to remove the first line of the error message
error = str(e).split('\n', 1)[1]
# no fair testing ourself with ourself, and assertEqual is used for strings
# so can't use assertEqual either. Just use assertTrue.
self.assertTrue(sample_text_error == error)
def testAsertEqualSingleLine(self):
sample_text = "laden swallows fly slowly"
revised_sample_text = "unladen swallows fly quickly"
sample_text_error = """\
- laden swallows fly slowly
? ^^^^
+ unladen swallows fly quickly
? ++ ^^^^^
"""
try:
self.assertEqual(sample_text, revised_sample_text)
except self.failureException as e:
error = str(e).split('\n', 1)[1]
self.assertTrue(sample_text_error == error)
def testAssertIsNone(self):
self.assertIsNone(None)
self.assertRaises(self.failureException, self.assertIsNone, False)
self.assertIsNotNone('DjZoPloGears on Rails')
self.assertRaises(self.failureException, self.assertIsNotNone, None)
def testAssertRegex(self):
self.assertRegex('asdfabasdf', r'ab+')
self.assertRaises(self.failureException, self.assertRegex,
'saaas', r'aaaa')
def testAssertRaisesRegex(self):
class ExceptionMock(Exception):
pass
def Stub():
raise ExceptionMock('We expect')
self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
def testAssertNotRaisesRegex(self):
self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
self.assertRaisesRegex, Exception, re.compile('x'),
lambda: None)
self.assertRaisesRegex(
self.failureException, '^Exception not raised by <lambda>$',
self.assertRaisesRegex, Exception, 'x',
lambda: None)
def testAssertRaisesRegexMismatch(self):
def Stub():
raise Exception('Unexpected')
self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
self.assertRaisesRegex, Exception, '^Expected$',
Stub)
self.assertRaisesRegex(
self.failureException,
r'"\^Expected\$" does not match "Unexpected"',
self.assertRaisesRegex, Exception,
re.compile('^Expected$'), Stub)
def testAssertRaisesExcValue(self):
class ExceptionMock(Exception):
pass
def Stub(foo):
raise ExceptionMock(foo)
v = "particular value"
ctx = self.assertRaises(ExceptionMock)
with ctx:
Stub(v)
e = ctx.exception
self.assertIsInstance(e, ExceptionMock)
self.assertEqual(e.args[0], v)
def testAssertWarnsCallable(self):
def _runtime_warn():
warnings.warn("foo", RuntimeWarning)
# Success when the right warning is triggered, even several times
self.assertWarns(RuntimeWarning, _runtime_warn)
self.assertWarns(RuntimeWarning, _runtime_warn)
# A tuple of warning classes is accepted
self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn)
# *args and **kwargs also work
self.assertWarns(RuntimeWarning,
warnings.warn, "foo", category=RuntimeWarning)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
self.assertWarns(RuntimeWarning, lambda: 0)
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
self.assertWarns(DeprecationWarning, _runtime_warn)
# Filters for other warnings are not modified
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises(RuntimeWarning):
self.assertWarns(DeprecationWarning, _runtime_warn)
def testAssertWarnsContext(self):
# Believe it or not, it is preferrable to duplicate all tests above,
# to make sure the __warningregistry__ $@ is circumvented correctly.
def _runtime_warn():
warnings.warn("foo", RuntimeWarning)
_runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
with self.assertWarns(RuntimeWarning) as cm:
_runtime_warn()
# A tuple of warning classes is accepted
with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm:
_runtime_warn()
# The context manager exposes various useful attributes
self.assertIsInstance(cm.warning, RuntimeWarning)
self.assertEqual(cm.warning.args[0], "foo")
self.assertIn("test_case.py", cm.filename)
self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
# Same with several warnings
with self.assertWarns(RuntimeWarning):
_runtime_warn()
_runtime_warn()
with self.assertWarns(RuntimeWarning):
warnings.warn("foo", category=RuntimeWarning)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
with self.assertWarns(RuntimeWarning):
pass
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
with self.assertWarns(DeprecationWarning):
_runtime_warn()
# Filters for other warnings are not modified
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises(RuntimeWarning):
with self.assertWarns(DeprecationWarning):
_runtime_warn()
def testAssertWarnsRegexCallable(self):
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "foox")
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
self.assertWarnsRegex(RuntimeWarning, "o+",
lambda: 0)
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
self.assertWarnsRegex(DeprecationWarning, "o+",
_runtime_warn, "foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
# non-matching RuntimeWarnings are simply re-raised, or produce a
# failureException.
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
self.assertWarnsRegex(RuntimeWarning, "o+",
_runtime_warn, "barz")
def testAssertWarnsRegexContext(self):
# Same as above, but with assertWarnsRegex as a context manager
def _runtime_warn(msg):
warnings.warn(msg, RuntimeWarning)
_runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
_runtime_warn("foox")
self.assertIsInstance(cm.warning, RuntimeWarning)
self.assertEqual(cm.warning.args[0], "foox")
self.assertIn("test_case.py", cm.filename)
self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
# Failure when no warning is triggered
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
pass
# Failure when another warning is triggered
with warnings.catch_warnings():
# Force default filter (in case tests are run with -We)
warnings.simplefilter("default", RuntimeWarning)
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(DeprecationWarning, "o+"):
_runtime_warn("foox")
# Failure when message doesn't match
with self.assertRaises(self.failureException):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
# A little trickier: we ask RuntimeWarnings to be raised, and then
# check for some of them. It is implementation-defined whether
# non-matching RuntimeWarnings are simply re-raised, or produce a
# failureException.
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
with self.assertRaises((RuntimeWarning, self.failureException)):
with self.assertWarnsRegex(RuntimeWarning, "o+"):
_runtime_warn("barz")
def testDeprecatedMethodNames(self):
"""
Test that the deprecated methods raise a DeprecationWarning. See #9424.
"""
old = (
(self.failIfEqual, (3, 5)),
(self.assertNotEquals, (3, 5)),
(self.failUnlessEqual, (3, 3)),
(self.assertEquals, (3, 3)),
(self.failUnlessAlmostEqual, (2.0, 2.0)),
(self.assertAlmostEquals, (2.0, 2.0)),
(self.failIfAlmostEqual, (3.0, 5.0)),
(self.assertNotAlmostEquals, (3.0, 5.0)),
(self.failUnless, (True,)),
(self.assert_, (True,)),
(self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
(self.failIf, (False,)),
(self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))),
(self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
(self.assertRegexpMatches, ('bar', 'bar')),
)
for meth, args in old:
with self.assertWarns(DeprecationWarning):
meth(*args)
# disable this test for now. When the version where the fail* methods will
# be removed is decided, re-enable it and update the version
def _testDeprecatedFailMethods(self):
"""Test that the deprecated fail* methods get removed in 3.x"""
if sys.version_info[:2] < (3, 3):
return
deprecated_names = [
'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual',
'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf',
'assertDictContainsSubset',
]
for deprecated_name in deprecated_names:
with self.assertRaises(AttributeError):
getattr(self, deprecated_name) # remove these in 3.x
def testDeepcopy(self):
# Issue: 5660
class TestableTest(unittest.TestCase):
def testNothing(self):
pass
test = TestableTest('testNothing')
# This shouldn't blow up
deepcopy(test)
def testPickle(self):
# Issue 10326
# Can't use TestCase classes defined in Test class as
# pickle does not work with inner classes
test = unittest.TestCase('run')
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
# blew up prior to fix
pickled_test = pickle.dumps(test, protocol=protocol)
unpickled_test = pickle.loads(pickled_test)
self.assertEqual(test, unpickled_test)
# exercise the TestCase instance in a way that will invoke
# the type equality lookup mechanism
unpickled_test.assertEqual(set(), set())
def testKeyboardInterrupt(self):
def _raise(self=None):
raise KeyboardInterrupt
def nothing(self):
pass
class Test1(unittest.TestCase):
test_something = _raise
class Test2(unittest.TestCase):
setUp = _raise
test_something = nothing
class Test3(unittest.TestCase):
test_something = nothing
tearDown = _raise
class Test4(unittest.TestCase):
def test_something(self):
self.addCleanup(_raise)
for klass in (Test1, Test2, Test3, Test4):
with self.assertRaises(KeyboardInterrupt):
klass('test_something').run()
def testSkippingEverywhere(self):
def _skip(self=None):
raise unittest.SkipTest('some reason')
def nothing(self):
pass
class Test1(unittest.TestCase):
test_something = _skip
class Test2(unittest.TestCase):
setUp = _skip
test_something = nothing
class Test3(unittest.TestCase):
test_something = nothing
tearDown = _skip
class Test4(unittest.TestCase):
def test_something(self):
self.addCleanup(_skip)
for klass in (Test1, Test2, Test3, Test4):
result = unittest.TestResult()
klass('test_something').run(result)
self.assertEqual(len(result.skipped), 1)
self.assertEqual(result.testsRun, 1)
def testSystemExit(self):
def _raise(self=None):
raise SystemExit
def nothing(self):
pass
class Test1(unittest.TestCase):
test_something = _raise
class Test2(unittest.TestCase):
setUp = _raise
test_something = nothing
class Test3(unittest.TestCase):
test_something = nothing
tearDown = _raise
class Test4(unittest.TestCase):
def test_something(self):
self.addCleanup(_raise)
for klass in (Test1, Test2, Test3, Test4):
result = unittest.TestResult()
klass('test_something').run(result)
self.assertEqual(len(result.errors), 1)
self.assertEqual(result.testsRun, 1)
@support.cpython_only
def testNoCycles(self):
case = unittest.TestCase()
wr = weakref.ref(case)
with support.disable_gc():
del case
self.assertFalse(wr())
|
gpl-2.0
|
guettli/django
|
django/core/handlers/base.py
|
96
|
10769
|
from __future__ import unicode_literals
import logging
import sys
import types
import warnings
from django.conf import settings
from django.core import signals
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
from django.db import connections, transaction
from django.urls import get_resolver, get_urlconf, set_urlconf
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.module_loading import import_string
from .exception import (
convert_exception_to_response, get_exception_response,
handle_uncaught_exception,
)
logger = logging.getLogger('django.request')
class BaseHandler(object):
def __init__(self):
self._request_middleware = None
self._view_middleware = None
self._template_response_middleware = None
self._response_middleware = None
self._exception_middleware = None
self._middleware_chain = None
def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE (or the deprecated
MIDDLEWARE_CLASSES).
Must be called after the environment is fixed (see __call__ in subclasses).
"""
self._request_middleware = []
self._view_middleware = []
self._template_response_middleware = []
self._response_middleware = []
self._exception_middleware = []
if settings.MIDDLEWARE is None:
warnings.warn(
"Old-style middleware using settings.MIDDLEWARE_CLASSES is "
"deprecated. Update your middleware and use settings.MIDDLEWARE "
"instead.", RemovedInDjango20Warning
)
handler = convert_exception_to_response(self._legacy_get_response)
for middleware_path in settings.MIDDLEWARE_CLASSES:
mw_class = import_string(middleware_path)
try:
mw_instance = mw_class()
except MiddlewareNotUsed as exc:
if settings.DEBUG:
if six.text_type(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
continue
if hasattr(mw_instance, 'process_request'):
self._request_middleware.append(mw_instance.process_request)
if hasattr(mw_instance, 'process_view'):
self._view_middleware.append(mw_instance.process_view)
if hasattr(mw_instance, 'process_template_response'):
self._template_response_middleware.insert(0, mw_instance.process_template_response)
if hasattr(mw_instance, 'process_response'):
self._response_middleware.insert(0, mw_instance.process_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.insert(0, mw_instance.process_exception)
else:
handler = convert_exception_to_response(self._get_response)
for middleware_path in reversed(settings.MIDDLEWARE):
middleware = import_string(middleware_path)
try:
mw_instance = middleware(handler)
except MiddlewareNotUsed as exc:
if settings.DEBUG:
if six.text_type(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
continue
if mw_instance is None:
raise ImproperlyConfigured(
'Middleware factory %s returned None.' % middleware_path
)
if hasattr(mw_instance, 'process_view'):
self._view_middleware.insert(0, mw_instance.process_view)
if hasattr(mw_instance, 'process_template_response'):
self._template_response_middleware.append(mw_instance.process_template_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.append(mw_instance.process_exception)
handler = convert_exception_to_response(mw_instance)
# We only assign to this when initialization is complete as it is used
# as a flag for initialization being complete.
self._middleware_chain = handler
def make_view_atomic(self, view):
non_atomic_requests = getattr(view, '_non_atomic_requests', set())
for db in connections.all():
if db.settings_dict['ATOMIC_REQUESTS'] and db.alias not in non_atomic_requests:
view = transaction.atomic(using=db.alias)(view)
return view
def get_exception_response(self, request, resolver, status_code, exception):
return get_exception_response(request, resolver, status_code, exception, self.__class__)
def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; if
# MIDDLEWARE is used, self._response_middleware will be empty.
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
except Exception: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
response._closable_objects.append(request)
# If the exception handler returns a TemplateResponse that has not
# been rendered, force it to be rendered.
if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
response = response.render()
if response.status_code == 404:
logger.warning(
'Not Found: %s', request.path,
extra={'status_code': 404, 'request': request},
)
return response
def _get_response(self, request):
"""
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
"""
response = None
if hasattr(request, 'urlconf'):
urlconf = request.urlconf
set_urlconf(urlconf)
resolver = get_resolver(urlconf)
else:
resolver = get_resolver()
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
response = self.process_exception_by_middleware(e, request)
# Complain if the view returned None (a common error).
if response is None:
if isinstance(callback, types.FunctionType): # FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError(
"The view %s.%s didn't return an HttpResponse object. It "
"returned None instead." % (callback.__module__, view_name)
)
# If the response supports deferred rendering, apply template
# response middleware and then render the response
elif hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
# Complain if the template response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_template_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__)
)
try:
response = response.render()
except Exception as e:
response = self.process_exception_by_middleware(e, request)
return response
def process_exception_by_middleware(self, exception, request):
"""
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
"""
for middleware_method in self._exception_middleware:
response = middleware_method(request, exception)
if response:
return response
raise
def handle_uncaught_exception(self, request, resolver, exc_info):
"""Allow subclasses to override uncaught exception handling."""
return handle_uncaught_exception(request, resolver, exc_info)
def _legacy_get_response(self, request):
"""
Apply process_request() middleware and call the main _get_response(),
if needed. Used only for legacy MIDDLEWARE_CLASSES.
"""
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
response = self._get_response(request)
return response
|
bsd-3-clause
|
skycucumber/restful
|
python/venv/lib/python2.7/site-packages/requests/packages/urllib3/fields.py
|
1007
|
5833
|
import email.utils
import mimetypes
from .packages import six
def guess_content_type(filename, default='application/octet-stream'):
"""
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
"""
if filename:
return mimetypes.guess_type(filename)[0] or default
return default
def format_header_param(name, value):
"""
Helper function to format and quote a single header parameter.
Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows RFC 2231, as
suggested by RFC 2388 Section 4.4.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
if not any(ch in value for ch in '"\\\r\n'):
result = '%s="%s"' % (name, value)
try:
result.encode('ascii')
except UnicodeEncodeError:
pass
else:
return result
if not six.PY3: # Python 2:
value = value.encode('utf-8')
value = email.utils.encode_rfc2231(value, 'utf-8')
value = '%s*=%s' % (name, value)
return value
class RequestField(object):
"""
A data container for request body parameters.
:param name:
The name of this request field.
:param data:
The data/value body.
:param filename:
An optional filename of the request field.
:param headers:
An optional dict-like object of headers to initially use for the field.
"""
def __init__(self, name, data, filename=None, headers=None):
self._name = name
self._filename = filename
self.data = data
self.headers = {}
if headers:
self.headers = dict(headers)
@classmethod
def from_tuples(cls, fieldname, value):
"""
A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.
Supports constructing :class:`~urllib3.fields.RequestField` from
parameter of key/value strings AND key/filetuple. A filetuple is a
(filename, data, MIME type) tuple where the MIME type is optional.
For example::
'foo': 'bar',
'fakefile': ('foofile.txt', 'contents of foofile'),
'realfile': ('barfile.txt', open('realfile').read()),
'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
'nonamefile': 'contents of nonamefile field',
Field names and filenames must be unicode.
"""
if isinstance(value, tuple):
if len(value) == 3:
filename, data, content_type = value
else:
filename, data = value
content_type = guess_content_type(filename)
else:
filename = None
content_type = None
data = value
request_param = cls(fieldname, data, filename=filename)
request_param.make_multipart(content_type=content_type)
return request_param
def _render_part(self, name, value):
"""
Overridable helper function to format a single header parameter.
:param name:
The name of the parameter, a string expected to be ASCII only.
:param value:
The value of the parameter, provided as a unicode string.
"""
return format_header_param(name, value)
def _render_parts(self, header_parts):
"""
Helper function to format and quote a single header.
Useful for single headers that are composed of multiple items. E.g.,
'Content-Disposition' fields.
:param header_parts:
A sequence of (k, v) typles or a :class:`dict` of (k, v) to format
as `k1="v1"; k2="v2"; ...`.
"""
parts = []
iterable = header_parts
if isinstance(header_parts, dict):
iterable = header_parts.items()
for name, value in iterable:
if value:
parts.append(self._render_part(name, value))
return '; '.join(parts)
def render_headers(self):
"""
Renders the headers for this request field.
"""
lines = []
sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
for sort_key in sort_keys:
if self.headers.get(sort_key, False):
lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
if header_name not in sort_keys:
if header_value:
lines.append('%s: %s' % (header_name, header_value))
lines.append('\r\n')
return '\r\n'.join(lines)
def make_multipart(self, content_disposition=None, content_type=None,
content_location=None):
"""
Makes this request field into a multipart request field.
This method overrides "Content-Disposition", "Content-Type" and
"Content-Location" headers to the request parameter.
:param content_type:
The 'Content-Type' of the request body.
:param content_location:
The 'Content-Location' of the request body.
"""
self.headers['Content-Disposition'] = content_disposition or 'form-data'
self.headers['Content-Disposition'] += '; '.join([
'', self._render_parts(
(('name', self._name), ('filename', self._filename))
)
])
self.headers['Content-Type'] = content_type
self.headers['Content-Location'] = content_location
|
gpl-2.0
|
MatthewWilkes/reportlab
|
tests/test_platypus_wrapping.py
|
1
|
3925
|
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
"""Tests for context-dependent indentation
"""
__version__='''$Id: test_platypus_indents.py 3660 2010-02-08 18:17:33Z damian $'''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name__)
import sys, os, random
from string import split, strip, join, whitespace
from operator import truth
from types import StringType, ListType
import unittest
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.platypus.paraparser import ParaParser
from reportlab.platypus.flowables import Flowable
from reportlab.lib.colors import Color
from reportlab.lib.units import cm
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib.utils import _className
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus.paragraph import Paragraph
from reportlab.platypus.frames import Frame
from reportlab.platypus.doctemplate \
import PageTemplate, BaseDocTemplate, Indenter, FrameBreak, NextPageTemplate
from reportlab.platypus import tableofcontents
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.platypus.tables import TableStyle, Table
from reportlab.platypus.paragraph import *
from reportlab.platypus.paragraph import _getFragWords
from reportlab.platypus.flowables import Spacer
def myMainPageFrame(canvas, doc):
"The page frame used for all PDF documents."
canvas.saveState()
canvas.rect(2.5*cm, 2.5*cm, 15*cm, 25*cm)
canvas.setFont('Times-Roman', 12)
pageNumber = canvas.getPageNumber()
canvas.drawString(10*cm, cm, str(pageNumber))
canvas.restoreState()
class MyDocTemplate(BaseDocTemplate):
_invalidInitArgs = ('pageTemplates',)
def __init__(self, filename, **kw):
frame1 = Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')
self.allowSplitting = 0
BaseDocTemplate.__init__(self, filename, **kw)
template1 = PageTemplate('normal', [frame1], myMainPageFrame)
frame2 = Frame(2.5*cm, 16*cm, 15*cm, 10*cm, id='F2', showBoundary=1)
frame3 = Frame(2.5*cm, 2.5*cm, 15*cm, 10*cm, id='F3', showBoundary=1)
template2 = PageTemplate('updown', [frame2, frame3])
self.addPageTemplates([template1, template2])
class WrappingTestCase(unittest.TestCase):
"Test wrapping of long urls"
def test0(self):
"This makes one long multi-page paragraph."
# Build story.
story = []
styleSheet = getSampleStyleSheet()
h1 = styleSheet['Heading1']
h1.spaceBefore = 18
bt = styleSheet['BodyText']
bt.spaceBefore = 6
story.append(Paragraph('Test of paragraph wrapping',h1))
story.append(Spacer(18,18))
txt = "Normally we wrap paragraphs by looking for spaces between the words. However, with long technical command references and URLs, sometimes this gives ugly results. We attempt to split really long words on certain tokens: slashes, dots etc."
story.append(Paragraph(txt,bt))
story.append(Paragraph('This is an attempt to break long URLs sanely. Here is a file name: <font face="Courier">C:\\Windows\\System32\\Drivers\\etc\\hosts</font>. ', bt))
story.append(Paragraph('This paragraph has a URL (basically, a word) too long to fit on one line, so it just overflows. http://some-really-long-site.somewhere-verbose.com/webthingies/framework/xc4987236hgsdlkafh/foo?format=dingbats&content=rubbish. Ideally, we would wrap it in the middle.', bt))
doc = MyDocTemplate(outputfile('test_platypus_wrapping.pdf'))
doc.multiBuild(story)
#noruntests
def makeSuite():
return makeSuiteForClasses(WrappingTestCase)
#noruntests
if __name__ == "__main__":
unittest.TextTestRunner().run(makeSuite())
printLocation()
|
bsd-3-clause
|
datenbetrieb/odoo
|
addons/stock_dropshipping/__init__.py
|
223
|
1085
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import stock_dropshipping
import wizard
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
urbansearchTUD/UrbanSearch
|
urbansearch/server/predict.py
|
1
|
1632
|
import config
from flask import Blueprint, jsonify, request
from urbansearch.server.decorators import is_json
from urbansearch.clustering.classifytext import ClassifyText
predict_api = Blueprint('predict_api', __name__)
ct = ClassifyText()
@predict_api.route('/', methods=['POST'])
@predict_api.route('/predict', methods=['POST'])
@is_json
def predict():
"""
API route for predicting the category of the supplied text.
The request should have type set to application/json and the provided JSON
should have a text attribute containing the text for which we want to
predict the category.
"""
try:
prediction = ct.predict(request.json['document'])
return jsonify(category=str(prediction[0]),
status=200)
except Exception as e:
return jsonify(error=True,
status=500,
message='Getting the prediction failed')
@predict_api.route('/probabilities', methods=['POST'])
@is_json
def probabilities():
"""
API route for getting the probabilities per category of the supplied text.
The request should have type set to application/json and the provided JSON
should have a text attribute containing the text for which we want to
get the probabilities per category
"""
try:
probabilities = ct.probability_per_category(request.json['document'])
return jsonify(probabilities=probabilities,
status=200)
except:
return jsonify(error=True,
status=500,
message='Getting the probabilities failed')
|
gpl-3.0
|
encbladexp/ansible
|
test/support/integration/plugins/module_utils/database.py
|
54
|
5942
|
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c) 2014, Toshio Kuratomi <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class SQLParseError(Exception):
pass
class UnclosedQuoteError(SQLParseError):
pass
# maps a type of identifier to the maximum number of dot levels that are
# allowed to specify that identifier. For example, a database column can be
# specified by up to 4 levels: database.schema.table.column
_PG_IDENTIFIER_TO_DOT_LEVEL = dict(
database=1,
schema=2,
table=3,
column=4,
role=1,
tablespace=1,
sequence=3,
publication=1,
)
_MYSQL_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, table=2, column=3, role=1, vars=1)
def _find_end_quote(identifier, quote_char):
accumulate = 0
while True:
try:
quote = identifier.index(quote_char)
except ValueError:
raise UnclosedQuoteError
accumulate = accumulate + quote
try:
next_char = identifier[quote + 1]
except IndexError:
return accumulate
if next_char == quote_char:
try:
identifier = identifier[quote + 2:]
accumulate = accumulate + 2
except IndexError:
raise UnclosedQuoteError
else:
return accumulate
def _identifier_parse(identifier, quote_char):
if not identifier:
raise SQLParseError('Identifier name unspecified or unquoted trailing dot')
already_quoted = False
if identifier.startswith(quote_char):
already_quoted = True
try:
end_quote = _find_end_quote(identifier[1:], quote_char=quote_char) + 1
except UnclosedQuoteError:
already_quoted = False
else:
if end_quote < len(identifier) - 1:
if identifier[end_quote + 1] == '.':
dot = end_quote + 1
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
further_identifiers.insert(0, first_identifier)
else:
raise SQLParseError('User escaped identifiers must escape extra quotes')
else:
further_identifiers = [identifier]
if not already_quoted:
try:
dot = identifier.index('.')
except ValueError:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
if dot == 0 or dot >= len(identifier) - 1:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
first_identifier = first_identifier.replace(quote_char, quote_char * 2)
first_identifier = ''.join((quote_char, first_identifier, quote_char))
further_identifiers.insert(0, first_identifier)
return further_identifiers
def pg_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='"')
if len(identifier_fragments) > _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('PostgreSQL does not support %s with more than %i dots' % (id_type, _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]))
return '.'.join(identifier_fragments)
def mysql_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='`')
if (len(identifier_fragments) - 1) > _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('MySQL does not support %s with more than %i dots' % (id_type, _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]))
special_cased_fragments = []
for fragment in identifier_fragments:
if fragment == '`*`':
special_cased_fragments.append('*')
else:
special_cased_fragments.append(fragment)
return '.'.join(special_cased_fragments)
|
gpl-3.0
|
sidmitra/django_nonrel_testapp
|
django/dispatch/saferef.py
|
345
|
10495
|
"""
"Safe weakrefs", originally from pyDispatcher.
Provides a way to safely weakref any function, including bound methods (which
aren't handled by the core weakref module).
"""
import weakref, traceback
def safeRef(target, onDelete = None):
"""Return a *safe* weak reference to a callable target
target -- the object to be weakly referenced, if it's a
bound method reference, will create a BoundMethodWeakref,
otherwise creates a simple weakref.
onDelete -- if provided, will have a hard reference stored
to the callable to be called after the safe reference
goes out of scope with the reference object, (either a
weakref or a BoundMethodWeakref) as argument.
"""
if hasattr(target, 'im_self'):
if target.im_self is not None:
# Turn a bound method into a BoundMethodWeakref instance.
# Keep track of these instances for lookup by disconnect().
assert hasattr(target, 'im_func'), """safeRef target %r has im_self, but no im_func, don't know how to create reference"""%( target,)
reference = get_bound_method_weakref(
target=target,
onDelete=onDelete
)
return reference
if callable(onDelete):
return weakref.ref(target, onDelete)
else:
return weakref.ref( target )
class BoundMethodWeakref(object):
"""'Safe' and reusable weak references to instance methods
BoundMethodWeakref objects provide a mechanism for
referencing a bound method without requiring that the
method object itself (which is normally a transient
object) is kept alive. Instead, the BoundMethodWeakref
object keeps weak references to both the object and the
function which together define the instance method.
Attributes:
key -- the identity key for the reference, calculated
by the class's calculateKey method applied to the
target instance method
deletionMethods -- sequence of callable objects taking
single argument, a reference to this object which
will be called when *either* the target object or
target function is garbage collected (i.e. when
this object becomes invalid). These are specified
as the onDelete parameters of safeRef calls.
weakSelf -- weak reference to the target object
weakFunc -- weak reference to the target function
Class Attributes:
_allInstances -- class attribute pointing to all live
BoundMethodWeakref objects indexed by the class's
calculateKey(target) method applied to the target
objects. This weak value dictionary is used to
short-circuit creation so that multiple references
to the same (object, function) pair produce the
same BoundMethodWeakref instance.
"""
_allInstances = weakref.WeakValueDictionary()
def __new__( cls, target, onDelete=None, *arguments,**named ):
"""Create new instance or return current instance
Basically this method of construction allows us to
short-circuit creation of references to already-
referenced instance methods. The key corresponding
to the target is calculated, and if there is already
an existing reference, that is returned, with its
deletionMethods attribute updated. Otherwise the
new instance is created and registered in the table
of already-referenced methods.
"""
key = cls.calculateKey(target)
current =cls._allInstances.get(key)
if current is not None:
current.deletionMethods.append( onDelete)
return current
else:
base = super( BoundMethodWeakref, cls).__new__( cls )
cls._allInstances[key] = base
base.__init__( target, onDelete, *arguments,**named)
return base
def __init__(self, target, onDelete=None):
"""Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be called
when this weak reference ceases to be valid
(i.e. either the object or the function is garbage
collected). Should take a single argument,
which will be passed a pointer to this object.
"""
def remove(weak, self=self):
"""Set self.isDead to true when method or instance is destroyed"""
methods = self.deletionMethods[:]
del self.deletionMethods[:]
try:
del self.__class__._allInstances[ self.key ]
except KeyError:
pass
for function in methods:
try:
if callable( function ):
function( self )
except Exception, e:
try:
traceback.print_exc()
except AttributeError, err:
print '''Exception during saferef %s cleanup function %s: %s'''%(
self, function, e
)
self.deletionMethods = [onDelete]
self.key = self.calculateKey( target )
self.weakSelf = weakref.ref(target.im_self, remove)
self.weakFunc = weakref.ref(target.im_func, remove)
self.selfName = str(target.im_self)
self.funcName = str(target.im_func.__name__)
def calculateKey( cls, target ):
"""Calculate the reference key for this reference
Currently this is a two-tuple of the id()'s of the
target object and the target function respectively.
"""
return (id(target.im_self),id(target.im_func))
calculateKey = classmethod( calculateKey )
def __str__(self):
"""Give a friendly representation of the object"""
return """%s( %s.%s )"""%(
self.__class__.__name__,
self.selfName,
self.funcName,
)
__repr__ = __str__
def __nonzero__( self ):
"""Whether we are still a valid reference"""
return self() is not None
def __cmp__( self, other ):
"""Compare with another reference"""
if not isinstance (other,self.__class__):
return cmp( self.__class__, type(other) )
return cmp( self.key, other.key)
def __call__(self):
"""Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.
"""
target = self.weakSelf()
if target is not None:
function = self.weakFunc()
if function is not None:
return function.__get__(target)
return None
class BoundNonDescriptorMethodWeakref(BoundMethodWeakref):
"""A specialized BoundMethodWeakref, for platforms where instance methods
are not descriptors.
It assumes that the function name and the target attribute name are the
same, instead of assuming that the function is a descriptor. This approach
is equally fast, but not 100% reliable because functions can be stored on an
attribute named differenty than the function's name such as in:
class A: pass
def foo(self): return "foo"
A.bar = foo
But this shouldn't be a common use case. So, on platforms where methods
aren't descriptors (such as Jython) this implementation has the advantage
of working in the most cases.
"""
def __init__(self, target, onDelete=None):
"""Return a weak-reference-like instance for a bound method
target -- the instance-method target for the weak
reference, must have im_self and im_func attributes
and be reconstructable via:
target.im_func.__get__( target.im_self )
which is true of built-in instance methods.
onDelete -- optional callback which will be called
when this weak reference ceases to be valid
(i.e. either the object or the function is garbage
collected). Should take a single argument,
which will be passed a pointer to this object.
"""
assert getattr(target.im_self, target.__name__) == target, \
("method %s isn't available as the attribute %s of %s" %
(target, target.__name__, target.im_self))
super(BoundNonDescriptorMethodWeakref, self).__init__(target, onDelete)
def __call__(self):
"""Return a strong reference to the bound method
If the target cannot be retrieved, then will
return None, otherwise returns a bound instance
method for our object and function.
Note:
You may call this method any number of times,
as it does not invalidate the reference.
"""
target = self.weakSelf()
if target is not None:
function = self.weakFunc()
if function is not None:
# Using curry() would be another option, but it erases the
# "signature" of the function. That is, after a function is
# curried, the inspect module can't be used to determine how
# many arguments the function expects, nor what keyword
# arguments it supports, and pydispatcher needs this
# information.
return getattr(target, function.__name__)
return None
def get_bound_method_weakref(target, onDelete):
"""Instantiates the appropiate BoundMethodWeakRef, depending on the details of
the underlying class method implementation"""
if hasattr(target, '__get__'):
# target method is a descriptor, so the default implementation works:
return BoundMethodWeakref(target=target, onDelete=onDelete)
else:
# no luck, use the alternative implementation:
return BoundNonDescriptorMethodWeakref(target=target, onDelete=onDelete)
|
bsd-3-clause
|
sdgdsffdsfff/ngender
|
ngender/ngender.py
|
2
|
1973
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
__all__ = ['guess']
def py2compat(name):
try:
name = name.decode('utf-8')
except:
pass
return name
class Guesser(object):
def __init__(self):
self._load_model()
def _load_model(self):
self.male_total = 0
self.female_total = 0
self.freq = {}
with open(os.path.join(os.path.dirname(__file__),
'charfreq.csv'),
'rb') as f:
# skip first line
next(f)
for line in f:
line = line.decode('utf-8')
char, male, female = line.split(',')
char = py2compat(char)
self.male_total += int(male)
self.female_total += int(female)
self.freq[char] = (int(female), int(male))
self.total = self.male_total + self.female_total
for char in self.freq:
female, male = self.freq[char]
self.freq[char] = (1. * female / self.female_total,
1. * male / self.male_total)
def guess(self, name):
name = py2compat(name)
firstname = name[1:]
for char in firstname:
assert u'\u4e00' <= char <= u'\u9fa0', u'姓名必须为中文'
pf = self.prob_for_gender(firstname, 0)
pm = self.prob_for_gender(firstname, 1)
if pm > pf:
return ('male', 1. * pm / (pm + pf))
elif pm < pf:
return ('female', 1. * pf / (pm + pf))
else:
return ('unknown', 0)
def prob_for_gender(self, firstname, gender=0):
p = 1. * self.female_total / self.total \
if gender == 0 \
else 1. * self.male_total / self.total
for char in firstname:
p *= self.freq.get(char, (0, 0))[gender]
return p
guesser = Guesser()
def guess(name):
return guesser.guess(name)
|
mit
|
pombredanne/zero-install
|
zeroinstall/injector/requirements.py
|
1
|
1734
|
"""
Holds information about what the user asked for (which program, version constraints, etc).
"""
# Copyright (C) 2011, Thomas Leonard
# See the README file for details, or visit http://0install.net.
from zeroinstall import _
class Requirements(object):
"""
Holds information about what the user asked for (which program, version constraints, etc).
"""
__slots__ = [
'interface_uri',
'command',
'source',
'before', 'not_before',
'os', 'cpu',
'message',
]
def __init__(self, interface_uri):
self.interface_uri = interface_uri
self.command = 'run'
self.source = False
self.before = self.not_before = None
self.os = self.cpu = None
self.message = None
def parse_options(self, options):
self.not_before = options.not_before
self.before = options.before
self.source = bool(options.source)
self.message = options.message
self.cpu = options.cpu
self.os = options.os
# (None becomes 'run', while '' becomes None)
if options.command is None:
if self.source:
self.command = 'compile'
else:
self.command = 'run'
else:
self.command = options.command or None
def get_as_options(self):
gui_args = []
if self.not_before:
gui_args.insert(0, self.not_before)
gui_args.insert(0, '--not-before')
if self.before:
gui_args.insert(0, self.before)
gui_args.insert(0, '--before')
if self.source:
gui_args.insert(0, '--source')
if self.message:
gui_args.insert(0, self.message)
gui_args.insert(0, '--message')
if self.cpu:
gui_args.insert(0, self.cpu)
gui_args.insert(0, '--cpu')
if self.os:
gui_args.insert(0, self.os)
gui_args.insert(0, '--os')
gui_args.append('--command')
gui_args.append(self.command or '')
return gui_args
|
lgpl-2.1
|
mollstam/UnrealPy
|
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Twisted-15.2.1/twisted/python/monkey.py
|
62
|
2227
|
# -*- test-case-name: twisted.test.test_monkey -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, absolute_import
class MonkeyPatcher(object):
"""
Cover up attributes with new objects. Neat for monkey-patching things for
unit-testing purposes.
"""
def __init__(self, *patches):
# List of patches to apply in (obj, name, value).
self._patchesToApply = []
# List of the original values for things that have been patched.
# (obj, name, value) format.
self._originals = []
for patch in patches:
self.addPatch(*patch)
def addPatch(self, obj, name, value):
"""
Add a patch so that the attribute C{name} on C{obj} will be assigned to
C{value} when C{patch} is called or during C{runWithPatches}.
You can restore the original values with a call to restore().
"""
self._patchesToApply.append((obj, name, value))
def _alreadyPatched(self, obj, name):
"""
Has the C{name} attribute of C{obj} already been patched by this
patcher?
"""
for o, n, v in self._originals:
if (o, n) == (obj, name):
return True
return False
def patch(self):
"""
Apply all of the patches that have been specified with L{addPatch}.
Reverse this operation using L{restore}.
"""
for obj, name, value in self._patchesToApply:
if not self._alreadyPatched(obj, name):
self._originals.append((obj, name, getattr(obj, name)))
setattr(obj, name, value)
def restore(self):
"""
Restore all original values to any patched objects.
"""
while self._originals:
obj, name, value = self._originals.pop()
setattr(obj, name, value)
def runWithPatches(self, f, *args, **kw):
"""
Apply each patch already specified. Then run the function f with the
given args and kwargs. Restore everything when done.
"""
self.patch()
try:
return f(*args, **kw)
finally:
self.restore()
|
mit
|
mdesco/dipy
|
scratch/very_scratch/simulation_comparisons_modified.py
|
20
|
13117
|
import nibabel
import os
import numpy as np
import dipy as dp
import dipy.core.generalized_q_sampling as dgqs
import dipy.io.pickles as pkl
import scipy as sp
from matplotlib.mlab import find
import dipy.core.sphere_plots as splots
import dipy.core.sphere_stats as sphats
import dipy.core.geometry as geometry
import get_vertices as gv
#old SimData files
'''
results_SNR030_1fibre
results_SNR030_1fibre+iso
results_SNR030_2fibres_15deg
results_SNR030_2fibres_30deg
results_SNR030_2fibres_60deg
results_SNR030_2fibres_90deg
results_SNR030_2fibres+iso_15deg
results_SNR030_2fibres+iso_30deg
results_SNR030_2fibres+iso_60deg
results_SNR030_2fibres+iso_90deg
results_SNR030_isotropic
'''
#fname='/home/ian/Data/SimData/results_SNR030_1fibre'
''' file has one row for every voxel, every voxel is repeating 1000
times with the same noise level , then we have 100 different
directions. 1000 * 100 is the number of all rows.
The 100 conditions are given by 10 polar angles (in degrees) 0, 20, 40, 60, 80,
80, 60, 40, 20 and 0, and each of these with longitude angle 0, 40, 80,
120, 160, 200, 240, 280, 320, 360.
'''
#new complete SimVoxels files
simdata = ['fibres_2_SNR_80_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_60_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_40_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_40_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_20_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_100_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_20_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_40_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_60_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_100_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_60_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_80_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_100_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_100_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_80_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_60_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_40_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_80_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_20_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_60_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_100_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_100_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_20_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_1_SNR_20_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_40_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_20_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_80_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_80_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_20_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_60_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_100_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_80_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_60_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_20_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_100_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_20_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_80_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_80_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_100_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_40_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_1_SNR_60_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_40_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_60_angle_30_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_40_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_60_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_80_angle_15_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_1_SNR_40_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_100_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00',
'fibres_2_SNR_40_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7',
'fibres_2_SNR_20_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
simdir = '/home/ian/Data/SimVoxels/'
def gq_tn_calc_save():
for simfile in simdata:
dataname = simfile
print dataname
sim_data=np.loadtxt(simdir+dataname)
marta_table_fname='/home/ian/Data/SimData/Dir_and_bvals_DSI_marta.txt'
b_vals_dirs=np.loadtxt(marta_table_fname)
bvals=b_vals_dirs[:,0]*1000
gradients=b_vals_dirs[:,1:]
gq = dp.GeneralizedQSampling(sim_data,bvals,gradients)
gqfile = simdir+'gq/'+dataname+'.pkl'
pkl.save_pickle(gqfile,gq)
'''
gq.IN gq.__doc__ gq.glob_norm_param
gq.QA gq.__init__ gq.odf
gq.__class__ gq.__module__ gq.q2odf_params
'''
tn = dp.Tensor(sim_data,bvals,gradients)
tnfile = simdir+'tn/'+dataname+'.pkl'
pkl.save_pickle(tnfile,tn)
'''
tn.ADC tn.__init__ tn._getevals
tn.B tn.__module__ tn._getevecs
tn.D tn.__new__ tn._getndim
tn.FA tn.__reduce__ tn._getshape
tn.IN tn.__reduce_ex__ tn._setevals
tn.MD tn.__repr__ tn._setevecs
tn.__class__ tn.__setattr__ tn.adc
tn.__delattr__ tn.__sizeof__ tn.evals
tn.__dict__ tn.__str__ tn.evecs
tn.__doc__ tn.__subclasshook__ tn.fa
tn.__format__ tn.__weakref__ tn.md
tn.__getattribute__ tn._evals tn.ndim
tn.__getitem__ tn._evecs tn.shape
tn.__hash__ tn._getD
'''
''' file has one row for every voxel, every voxel is repeating 1000
times with the same noise level , then we have 100 different
directions. 100 * 1000 is the number of all rows.
At the moment this module is hardwired to the use of the EDS362
spherical mesh. I am assumung (needs testing) that directions 181 to 361
are the antipodal partners of directions 0 to 180. So when counting the
number of different vertices that occur as maximal directions we wll map
the indices modulo 181.
'''
def analyze_maxima(indices, max_dirs, subsets):
'''This calculates the eigenstats for each of the replicated batches
of the simulation data
'''
results = []
for direction in subsets:
batch = max_dirs[direction,:,:]
index_variety = np.array([len(set(np.remainder(indices[direction,:],181)))])
#normed_centroid, polar_centroid, centre, b1 = sphats.eigenstats(batch)
centre, b1 = sphats.eigenstats(batch)
# make azimuth be in range (0,360) rather than (-180,180)
centre[1] += 360*(centre[1] < 0)
#results.append(np.concatenate((normed_centroid, polar_centroid, centre, b1, index_variety)))
results.append(np.concatenate((centre, b1, index_variety)))
return results
#dt_first_directions = tn.evecs[:,:,0].reshape((100,1000,3))
# these are the principal directions for the full set of simulations
#gq_tn_calc_save()
eds=np.load(os.path.join(os.path.dirname(dp.__file__),'core','matrices','evenly_distributed_sphere_362.npz'))
odf_vertices=eds['vertices']
def run_comparisons(sample_data=35):
for simfile in [simdata[sample_data]]:
dataname = simfile
print dataname
sim_data=np.loadtxt(simdir+dataname)
gqfile = simdir+'gq/'+dataname+'.pkl'
gq = pkl.load_pickle(gqfile)
tnfile = simdir+'tn/'+dataname+'.pkl'
tn = pkl.load_pickle(tnfile)
dt_first_directions_in=odf_vertices[tn.IN]
dt_indices = tn.IN.reshape((100,1000))
dt_results = analyze_maxima(dt_indices, dt_first_directions_in.reshape((100,1000,3)),range(10,90))
gq_indices = np.array(gq.IN[:,0],dtype='int').reshape((100,1000))
gq_first_directions_in=odf_vertices[np.array(gq.IN[:,0],dtype='int')]
#print gq_first_directions_in.shape
gq_results = analyze_maxima(gq_indices, gq_first_directions_in.reshape((100,1000,3)),range(10,90))
#for gqi see example dicoms_2_tracks gq.IN[:,0]
np.set_printoptions(precision=3, suppress=True, linewidth=200, threshold=5000)
out = open('/home/ian/Data/SimVoxels/Out/'+'***_'+dataname,'w')
#print np.vstack(dt_results).shape, np.vstack(gq_results).shape
results = np.hstack((np.vstack(dt_results), np.vstack(gq_results)))
#print results.shape
#results = np.vstack(dt_results)
print >> out, results[:,:]
out.close()
#up = dt_batch[:,2]>= 0
#splots.plot_sphere(dt_batch[up], 'batch '+str(direction))
#splots.plot_lambert(dt_batch[up],'batch '+str(direction), centre)
#spread = gq.q2odf_params e,v = np.linalg.eigh(np.dot(spread,spread.transpose())) effective_dimension = len(find(np.cumsum(e) > 0.05*np.sum(e))) #95%
#rotated = np.dot(dt_batch,evecs)
#rot_evals, rot_evecs = np.linalg.eig(np.dot(rotated.T,rotated)/rotated.shape[0])
#eval_order = np.argsort(rot_evals)
#rotated = rotated[:,eval_order]
#up = rotated[:,2]>= 0
#splot.plot_sphere(rotated[up],'first1000')
#splot.plot_lambert(rotated[up],'batch '+str(direction))
def run_gq_sims(sample_data=[35,23,46,39,40,10,37,27,21,20]):
results = []
out = open('/home/ian/Data/SimVoxels/Out/'+'npa+fa','w')
for j in range(len(sample_data)):
sample = sample_data[j]
simfile = simdata[sample]
dataname = simfile
print dataname
sim_data=np.loadtxt(simdir+dataname)
marta_table_fname='/home/ian/Data/SimData/Dir_and_bvals_DSI_marta.txt'
b_vals_dirs=np.loadtxt(marta_table_fname)
bvals=b_vals_dirs[:,0]*1000
gradients=b_vals_dirs[:,1:]
for j in np.vstack((np.arange(100)*1000,np.arange(100)*1000+1)).T.ravel():
# 0,1,1000,1001,2000,2001,...
s = sim_data[j,:]
gqs = dp.GeneralizedQSampling(s.reshape((1,102)),bvals,gradients,Lambda=3.5)
tn = dp.Tensor(s.reshape((1,102)),bvals,gradients,fit_method='LS')
t0, t1, t2, npa = gqs.npa(s, width = 5)
print >> out, dataname, j, npa, tn.fa()[0]
'''
for (i,o) in enumerate(gqs.odf(s)):
print i,o
for (i,o) in enumerate(gqs.odf_vertices):
print i,o
'''
#o = gqs.odf(s)
#v = gqs.odf_vertices
#pole = v[t0[0]]
#eqv = dgqs.equatorial_zone_vertices(v, pole, 5)
#print 'Number of equatorial vertices: ', len(eqv)
#print np.max(o[eqv]),np.min(o[eqv])
#cos_e_pole = [np.dot(pole.T, v[i]) for i in eqv]
#print np.min(cos1), np.max(cos1)
#print 'equatorial max in equatorial vertices:', t1[0] in eqv
#x = np.cross(v[t0[0]],v[t1[0]])
#x = x/np.sqrt(np.sum(x**2))
#print x
#ptchv = dgqs.patch_vertices(v, x, 5)
#print len(ptchv)
#eqp = eqv[np.argmin([np.abs(np.dot(v[t1[0]].T,v[p])) for p in eqv])]
#print (eqp, o[eqp])
#print t2[0] in ptchv, t2[0] in eqv
#print np.dot(pole.T, v[t1[0]]), np.dot(pole.T, v[t2[0]])
#print ptchv[np.argmin([o[v] for v in ptchv])]
#gq_indices = np.array(gq.IN[:,0],dtype='int').reshape((100,1000))
#gq_first_directions_in=odf_vertices[np.array(gq.IN[:,0],dtype='int')]
#print gq_first_directions_in.shape
#gq_results = analyze_maxima(gq_indices, gq_first_directions_in.reshape((100,1000,3)),range(100))
#for gqi see example dicoms_2_tracks gq.IN[:,0]
#np.set_printoptions(precision=6, suppress=True, linewidth=200, threshold=5000)
#out = open('/home/ian/Data/SimVoxels/Out/'+'+++_'+dataname,'w')
#results = np.hstack((np.vstack(dt_results), np.vstack(gq_results)))
#results = np.vstack(dt_results)
#print >> out, results[:,:]
out.close()
run_comparisons()
#run_gq_sims()
|
bsd-3-clause
|
edx/edx-enterprise
|
tests/test_enterprise/api_client/test_discovery.py
|
1
|
22331
|
# -*- coding: utf-8 -*-
"""
Tests for the `edx-enterprise` course catalogs api module.
"""
import json
import logging
import unittest
import ddt
import mock
import responses
from six.moves.urllib.parse import urljoin # pylint: disable=import-error
from slumber.exceptions import HttpClientError
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from enterprise.api_client.discovery import CourseCatalogApiClient, CourseCatalogApiServiceClient
from enterprise.utils import NotConnectedToOpenEdX
from test_utils import MockLoggingHandler
from test_utils.fake_catalog_api import CourseDiscoveryApiTestMixin
User = auth.get_user_model()
class TestCourseCatalogApiInitialization(unittest.TestCase):
"""
Test initialization of CourseCatalogAPI.
"""
@mock.patch('enterprise.api_client.discovery.CatalogIntegration')
@mock.patch('enterprise.api_client.discovery.get_edx_api_data')
def test_raise_error_missing_course_discovery_api(self, *args): # pylint: disable=unused-argument
with self.assertRaises(NotConnectedToOpenEdX):
CourseCatalogApiClient(mock.Mock(spec=User))
@mock.patch('enterprise.api_client.discovery.JwtBuilder')
@mock.patch('enterprise.api_client.discovery.get_edx_api_data')
def test_raise_error_missing_catalog_integration(self, *args): # pylint: disable=unused-argument
with self.assertRaises(NotConnectedToOpenEdX):
CourseCatalogApiClient(mock.Mock(spec=User))
@mock.patch('enterprise.api_client.discovery.CatalogIntegration')
@mock.patch('enterprise.api_client.discovery.JwtBuilder')
def test_raise_error_missing_get_edx_api_data(self, *args): # pylint: disable=unused-argument
with self.assertRaises(NotConnectedToOpenEdX):
CourseCatalogApiClient(mock.Mock(spec=User))
@ddt.ddt
class TestCourseCatalogApi(CourseDiscoveryApiTestMixin, unittest.TestCase):
"""
Test course catalog API methods.
"""
EMPTY_RESPONSES = (None, {}, [], set(), "")
def setUp(self):
super().setUp()
self.user_mock = mock.Mock(spec=User)
self.get_data_mock = self._make_patch(self._make_catalog_api_location("get_edx_api_data"))
self.catalog_api_config_mock = self._make_patch(self._make_catalog_api_location("CatalogIntegration"))
self.jwt_builder_mock = self._make_patch(self._make_catalog_api_location("JwtBuilder"))
self.api = CourseCatalogApiClient(self.user_mock)
@staticmethod
def _make_course_run(key, *seat_types):
"""
Return course_run json representation expected by CourseCatalogAPI.
"""
return {
"key": key,
"seats": [{"type": seat_type} for seat_type in seat_types]
}
_make_run = _make_course_run.__func__ # unwrapping to use within class definition
def test_get_course_details(self):
"""
Verify get_course_details of CourseCatalogApiClient works as expected.
"""
course_key = 'edX+DemoX'
expected_result = {"complex": "dict"}
self.get_data_mock.return_value = expected_result
actual_result = self.api.get_course_details(course_key)
assert self.get_data_mock.call_count == 1
resource, resource_id = self._get_important_parameters(self.get_data_mock)
assert resource == CourseCatalogApiClient.COURSES_ENDPOINT
assert resource_id == 'edX+DemoX'
assert actual_result == expected_result
@ddt.data(*EMPTY_RESPONSES)
def test_get_course_details_empty_response(self, response):
"""
Verify get_course_details of CourseCatalogApiClient works as expected for empty responses.
"""
self.get_data_mock.return_value = response
assert self.api.get_course_details(course_id='edX+DemoX') == {}
@ddt.data(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
"course-v1:TrantorAcademy+Psychohistory101+T1",
"course-v1:StarfleetAcademy+WarpspeedNavigation+T2337",
"course-v1:SinhonCompanionAcademy+Calligraphy+TermUnknown",
"course-v1:CampArthurCurrie+HeavyWeapons+T2245_5",
)
def test_get_course_run(self, course_run_id):
"""
Verify get_course_run of CourseCatalogApiClient works as expected.
"""
response_dict = {"very": "complex", "json": {"with": " nested object"}}
self.get_data_mock.return_value = response_dict
actual_result = self.api.get_course_run(course_run_id)
assert self.get_data_mock.call_count == 1
resource, resource_id = self._get_important_parameters(self.get_data_mock)
assert resource == CourseCatalogApiClient.COURSE_RUNS_ENDPOINT
assert resource_id is course_run_id
assert actual_result == response_dict
@ddt.data(*EMPTY_RESPONSES)
def test_get_course_run_empty_response(self, response):
"""
Verify get_course_run of CourseCatalogApiClient works as expected for empty responses.
"""
self.get_data_mock.return_value = response
assert self.api.get_course_run("any") == {}
@ddt.data(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
"course-v1:TrantorAcademy+Psychohistory101+T1",
)
def test_get_course_run_identifiers(self, course_run_id):
self.get_data_mock.return_value = {}
actual_result = self.api.get_course_run_identifiers(course_run_id)
assert 'course_key' in actual_result
assert actual_result['course_key'] is None
assert 'course_uuid' in actual_result
assert actual_result['course_uuid'] is None
assert 'course_run_key' in actual_result
assert actual_result['course_run_key'] is None
assert 'course_run_uuid' in actual_result
assert actual_result['course_run_uuid'] is None
mock_response = {
"key": "JediAcademy+AppliedTelekinesis",
"uuid": "785b11f5-fad5-4ce1-9233-e1a3ed31aadb",
}
self.get_data_mock.return_value = mock_response
actual_result = self.api.get_course_run_identifiers(course_run_id)
assert 'course_key' in actual_result
assert actual_result['course_key'] == 'JediAcademy+AppliedTelekinesis'
assert 'course_uuid' in actual_result
assert actual_result['course_uuid'] == '785b11f5-fad5-4ce1-9233-e1a3ed31aadb'
assert 'course_run_key' in actual_result
assert actual_result['course_run_key'] is None
assert 'course_run_uuid' in actual_result
assert actual_result['course_run_uuid'] is None
mock_response = {
"key": "JediAcademy+AppliedTelekinesis",
"uuid": "785b11f5-fad5-4ce1-9233-e1a3ed31aadb",
"course_runs": [],
}
self.get_data_mock.return_value = mock_response
actual_result = self.api.get_course_run_identifiers(course_run_id)
assert 'course_key' in actual_result
assert actual_result['course_key'] == 'JediAcademy+AppliedTelekinesis'
assert 'course_uuid' in actual_result
assert actual_result['course_uuid'] == '785b11f5-fad5-4ce1-9233-e1a3ed31aadb'
assert 'course_run_key' in actual_result
assert actual_result['course_run_key'] is None
assert 'course_run_uuid' in actual_result
assert actual_result['course_run_uuid'] is None
mock_response = {
"key": "JediAcademy+AppliedTelekinesis",
"uuid": "785b11f5-fad5-4ce1-9233-e1a3ed31aadb",
"course_runs": [{
"key": course_run_id,
"uuid": "1234abcd-fad5-4ce1-9233-e1a3ed31aadb"
}],
}
self.get_data_mock.return_value = mock_response
actual_result = self.api.get_course_run_identifiers(course_run_id)
assert 'course_key' in actual_result
assert actual_result['course_key'] == 'JediAcademy+AppliedTelekinesis'
assert 'course_uuid' in actual_result
assert actual_result['course_uuid'] == '785b11f5-fad5-4ce1-9233-e1a3ed31aadb'
assert 'course_run_key' in actual_result
assert actual_result['course_run_key'] == course_run_id
assert 'course_run_uuid' in actual_result
assert actual_result['course_run_uuid'] == '1234abcd-fad5-4ce1-9233-e1a3ed31aadb'
@ddt.data("Apollo", "Star Wars", "mk Ultra")
def test_get_program_by_uuid(self, program_id):
"""
Verify get_program_by_uuid of CourseCatalogApiClient works as expected.
"""
response_dict = {"very": "complex", "json": {"with": " nested object"}}
self.get_data_mock.return_value = response_dict
actual_result = self.api.get_program_by_uuid(program_id)
assert self.get_data_mock.call_count == 1
resource, resource_id = self._get_important_parameters(self.get_data_mock)
assert resource == CourseCatalogApiClient.PROGRAMS_ENDPOINT
assert resource_id is program_id
assert actual_result == response_dict
@ddt.data(*EMPTY_RESPONSES)
def test_get_program_by_uuid_empty_response(self, response):
"""
Verify get_program_by_uuid of CourseCatalogApiClient works as expected for empty responses.
"""
self.get_data_mock.return_value = response
assert self.api.get_program_by_uuid("any") is None
@ddt.data("MicroMasters Certificate", "Professional Certificate", "XSeries Certificate")
def test_get_program_type_by_slug(self, slug):
"""
Verify get_program_type_by_slug of CourseCatalogApiClient works as expected.
"""
response_dict = {"very": "complex", "json": {"with": " nested object"}}
self.get_data_mock.return_value = response_dict
actual_result = self.api.get_program_type_by_slug(slug)
assert self.get_data_mock.call_count == 1
resource, resource_id = self._get_important_parameters(self.get_data_mock)
assert resource == CourseCatalogApiClient.PROGRAM_TYPES_ENDPOINT
assert resource_id is slug
assert actual_result == response_dict
@ddt.data(*EMPTY_RESPONSES)
def test_get_program_type_by_slug_empty_response(self, response):
"""
Verify get_program_type_by_slug of CourseCatalogApiClient works as expected for empty responses.
"""
self.get_data_mock.return_value = response
assert self.api.get_program_type_by_slug('slug') is None
@ddt.data(
(None, []),
({}, []),
(
{
'courses': [
{'key': 'first+key'},
{'key': 'second+key'}
]
},
[
'first+key',
'second+key'
]
)
)
@ddt.unpack
def test_get_program_course_keys(self, response_body, expected_result):
self.get_data_mock.return_value = response_body
result = self.api.get_program_course_keys('fake-uuid')
assert result == expected_result
@ddt.data(
(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
{
"course": "JediAcademy+AppliedTelekinesis"
},
{
"course_runs": [{"key": "course-v1:JediAcademy+AppliedTelekinesis+T1"}]
},
"JediAcademy+AppliedTelekinesis",
{"key": "course-v1:JediAcademy+AppliedTelekinesis+T1"}
),
(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
{},
{},
None,
None
),
(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
{
"course": "JediAcademy+AppliedTelekinesis"
},
{
"course_runs": [
{"key": "course-v1:JediAcademy+AppliedTelekinesis+T222"},
{"key": "course-v1:JediAcademy+AppliedTelekinesis+T1"}
]
},
"JediAcademy+AppliedTelekinesis",
{"key": "course-v1:JediAcademy+AppliedTelekinesis+T1"}
),
(
"course-v1:JediAcademy+AppliedTelekinesis+T1",
{
"course": "JediAcademy+AppliedTelekinesis"
},
{
"course_runs": []
},
"JediAcademy+AppliedTelekinesis",
None
)
)
@ddt.unpack
def test_get_course_and_course_run(
self,
course_run_id,
course_runs_endpoint_response,
course_endpoint_response,
expected_resource_id,
expected_course_run
):
"""
Verify get_course_and_course_run of CourseCatalogApiClient works as expected.
"""
self.get_data_mock.side_effect = [course_runs_endpoint_response, course_endpoint_response]
expected_result = course_endpoint_response, expected_course_run
actual_result = self.api.get_course_and_course_run(course_run_id)
assert self.get_data_mock.call_count == 2
resource, resource_id = self._get_important_parameters(self.get_data_mock)
assert resource == CourseCatalogApiClient.COURSES_ENDPOINT
assert resource_id == expected_resource_id
assert actual_result == expected_result
@ddt.data(*EMPTY_RESPONSES)
def test_load_data_with_exception(self, default):
"""
``_load_data`` returns a default value given an exception.
"""
self.get_data_mock.side_effect = HttpClientError
assert self.api._load_data('', default=default) == default # pylint: disable=protected-access
@responses.activate
def test_get_catalog_results(self):
"""
Verify `get_catalog_results` of CourseCatalogApiClient works as expected.
"""
content_filter_query = {'content_type': 'course', 'aggregation_key': ['course:edX+DemoX']}
response_dict = {
'next': 'next',
'previous': 'previous',
'results': [{
'enterprise_id': 'a9e8bb52-0c8d-4579-8496-1a8becb0a79c',
'catalog_id': 1111,
'uuid': '785b11f5-fad5-4ce1-9233-e1a3ed31aadb',
'aggregation_key': 'course:edX+DemoX',
'content_type': 'course',
'title': 'edX Demonstration Course',
}],
}
responses.add(
responses.POST,
url=urljoin(self.api.catalog_url, self.api.SEARCH_ALL_ENDPOINT),
json=response_dict,
status=200,
)
actual_result = self.api.get_catalog_results(
content_filter_query=content_filter_query,
query_params={'page': 2}
)
assert actual_result == response_dict
@responses.activate
@mock.patch.object(CourseCatalogApiClient, 'get_catalog_results_from_discovery', return_value={'result': 'dummy'})
def test_get_catalog_results_cache(self, mocked_get_catalog_results_from_discovery): # pylint: disable=invalid-name
"""
Verify `get_catalog_results` of CourseCatalogApiClient works as expected.
"""
content_filter_query = {'content_type': 'course', 'aggregation_key': ['course:edX+DemoX']}
self.api.get_catalog_results(content_filter_query=content_filter_query)
assert mocked_get_catalog_results_from_discovery.call_count == 1
# searching same query should not hit discovery service again
self.api.get_catalog_results(content_filter_query=content_filter_query)
assert mocked_get_catalog_results_from_discovery.call_count == 1
# getting catalog with different params should hit discovery
content_filter_query.update({'partner': 'edx'})
self.api.get_catalog_results(content_filter_query=content_filter_query)
assert mocked_get_catalog_results_from_discovery.call_count == 2
@responses.activate
def test_get_catalog_results_with_traverse_pagination(self):
"""
Verify `get_catalog_results` of CourseCatalogApiClient works as expected with traverse_pagination=True.
"""
content_filter_query = {'content_type': 'course', 'aggregation_key': ['course:edX+DemoX']}
response_dict = {
'next': 'next',
'previous': None,
'results': [{
'enterprise_id': 'a9e8bb52-0c8d-4579-8496-1a8becb0a79c',
'catalog_id': 1111,
'uuid': '785b11f5-fad5-4ce1-9233-e1a3ed31aadb',
'aggregation_key': 'course:edX+DemoX',
'content_type': 'course',
'title': 'edX Demonstration Course',
}],
}
def request_callback(request):
"""
Mocked callback for POST request to search/all endpoint.
"""
response = response_dict
if 'page=2' in request.url:
response = dict(response, next=None)
return (200, {}, json.dumps(response))
responses.add_callback(
responses.POST,
url=urljoin(self.api.catalog_url, self.api.SEARCH_ALL_ENDPOINT),
callback=request_callback,
content_type='application/json',
)
responses.add_callback(
responses.POST,
url='{}?{}'.format(urljoin(self.api.catalog_url, self.api.SEARCH_ALL_ENDPOINT), '?page=2&page_size=100'),
callback=request_callback,
content_type='application/json',
)
recieved_response = self.api.get_catalog_results(
content_filter_query=content_filter_query,
traverse_pagination=True
)
complete_response = {
'next': None,
'previous': None,
'results': response_dict['results'] * 2
}
assert recieved_response == complete_response
@responses.activate
def test_get_catalog_results_with_exception(self):
"""
Verify `get_catalog_results` of CourseCatalogApiClient works as expected in case of exception.
"""
responses.add(
responses.POST,
url=urljoin(self.api.catalog_url, self.api.SEARCH_ALL_ENDPOINT),
body=HttpClientError(content='boom'),
)
logger = logging.getLogger('enterprise.api_client.discovery')
handler = MockLoggingHandler(level="ERROR")
logger.addHandler(handler)
with self.assertRaises(HttpClientError):
self.api.get_catalog_results(
content_filter_query='query',
query_params={u'page': 2}
)
expected_message = ('Attempted to call course-discovery search/all/ endpoint with the following parameters: '
'content_filter_query: query, query_params: {}, traverse_pagination: False. '
'Failed to retrieve data from the catalog API. content -- [boom]').format({u'page': 2})
assert handler.messages['error'][0] == expected_message
class TestCourseCatalogApiServiceClientInitialization(unittest.TestCase):
"""
Test initialization of CourseCatalogAPIServiceClient.
"""
def test_raise_error_missing_catalog_integration(self, *args): # pylint: disable=unused-argument
with self.assertRaises(NotConnectedToOpenEdX):
CourseCatalogApiServiceClient()
@mock.patch('enterprise.api_client.discovery.CatalogIntegration')
def test_raise_error_catalog_integration_disabled(self, mock_catalog_integration):
mock_catalog_integration.current.return_value = mock.Mock(enabled=False)
with self.assertRaises(ImproperlyConfigured):
CourseCatalogApiServiceClient()
@mock.patch('enterprise.api_client.discovery.CatalogIntegration')
def test_raise_error_object_does_not_exist(self, mock_catalog_integration):
mock_integration_config = mock.Mock(enabled=True)
mock_integration_config.get_service_user.side_effect = ObjectDoesNotExist
mock_catalog_integration.current.return_value = mock_integration_config
with self.assertRaises(ImproperlyConfigured):
CourseCatalogApiServiceClient()
@mock.patch('enterprise.api_client.discovery.JwtBuilder')
@mock.patch('enterprise.api_client.discovery.get_edx_api_data')
@mock.patch('enterprise.api_client.discovery.CatalogIntegration')
def test_success(self, mock_catalog_integration, *args): # pylint: disable=unused-argument
mock_integration_config = mock.Mock(enabled=True)
mock_integration_config.get_service_user.return_value = mock.Mock(spec=User)
mock_catalog_integration.current.return_value = mock_integration_config
CourseCatalogApiServiceClient()
@ddt.ddt
class TestCourseCatalogApiService(CourseDiscoveryApiTestMixin, unittest.TestCase):
"""
Tests for the CourseCatalogAPIServiceClient.
"""
def setUp(self):
"""
Set up mocks for the test suite.
"""
super().setUp()
self.user_mock = mock.Mock(spec=User)
self.get_data_mock = self._make_patch(self._make_catalog_api_location("get_edx_api_data"))
self.jwt_builder_mock = self._make_patch(self._make_catalog_api_location("JwtBuilder"))
self.integration_config_mock = mock.Mock(enabled=True)
self.integration_config_mock.get_service_user.return_value = self.user_mock
self.integration_mock = self._make_patch(self._make_catalog_api_location("CatalogIntegration"))
self.integration_mock.current.return_value = self.integration_config_mock
self.api = CourseCatalogApiServiceClient()
@ddt.data({}, {'program': 'data'})
def test_program_exists_no_exception(self, response):
"""
The client should return the appropriate boolean value for program existence depending on the response.
"""
self.get_data_mock.return_value = response
assert CourseCatalogApiServiceClient.program_exists('a-s-d-f') == bool(response)
def test_program_exists_with_exception(self):
"""
The client should capture improper configuration for the class method and return False.
"""
self.integration_mock.current.return_value.enabled = False
assert not CourseCatalogApiServiceClient.program_exists('a-s-d-f')
|
agpl-3.0
|
Eagles2F/sync-engine
|
tests/imap/network/test_send.py
|
6
|
1737
|
import json
from datetime import datetime
import pytest
from tests.util.base import default_account
from tests.util.crispin import crispin_client
from tests.api.base import api_client
__all__ = ['default_account', 'api_client']
@pytest.fixture
def example_draft(db, default_account):
return {
'subject': 'Draft test at {}'.format(datetime.utcnow()),
'body': '<html><body><h2>Sea, birds and sand.</h2></body></html>',
'to': [{'name': 'The red-haired mermaid',
'email': default_account.email_address}]
}
def test_send_draft(db, api_client, example_draft, default_account):
r = api_client.post_data('/drafts', example_draft)
assert r.status_code == 200
public_id = json.loads(r.data)['id']
version = json.loads(r.data)['version']
r = api_client.post_data('/send', {'draft_id': public_id,
'version': version})
assert r.status_code == 200
draft = api_client.get_data('/drafts/{}'.format(public_id))
assert draft is not None
assert draft['object'] != 'draft'
with crispin_client(default_account.id, default_account.provider) as c:
criteria = ['NOT DELETED', 'SUBJECT "{0}"'.format(
example_draft['subject'])]
c.conn.select_folder(default_account.drafts_folder.name,
readonly=False)
draft_uids = c.conn.search(criteria)
assert not draft_uids, 'Message still in Drafts folder'
c.conn.select_folder(default_account.sent_folder.name, readonly=False)
sent_uids = c.conn.search(criteria)
assert sent_uids, 'Message missing from Sent folder'
c.conn.delete_messages(sent_uids)
c.conn.expunge()
|
agpl-3.0
|
aduric/crossfit
|
nonrel/docs/_ext/applyxrefs.py
|
143
|
2148
|
"""Adds xref targets to the top of files."""
import sys
import os
testing = False
DONT_TOUCH = (
'./index.txt',
)
def target_name(fn):
if fn.endswith('.txt'):
fn = fn[:-4]
return '_' + fn.lstrip('./').replace('/', '-')
def process_file(fn, lines):
lines.insert(0, '\n')
lines.insert(0, '.. %s:\n' % target_name(fn))
try:
f = open(fn, 'w')
except IOError:
print("Can't open %s for writing. Not touching it." % fn)
return
try:
f.writelines(lines)
except IOError:
print("Can't write to %s. Not touching it." % fn)
finally:
f.close()
def has_target(fn):
try:
f = open(fn, 'r')
except IOError:
print("Can't open %s. Not touching it." % fn)
return (True, None)
readok = True
try:
lines = f.readlines()
except IOError:
print("Can't read %s. Not touching it." % fn)
readok = False
finally:
f.close()
if not readok:
return (True, None)
#print fn, len(lines)
if len(lines) < 1:
print("Not touching empty file %s." % fn)
return (True, None)
if lines[0].startswith('.. _'):
return (True, None)
return (False, lines)
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) == 1:
argv.extend('.')
files = []
for root in argv[1:]:
for (dirpath, dirnames, filenames) in os.walk(root):
files.extend([(dirpath, f) for f in filenames])
files.sort()
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
#print files
for fn in files:
if fn in DONT_TOUCH:
print("Skipping blacklisted file %s." % fn)
continue
target_found, lines = has_target(fn)
if not target_found:
if testing:
print '%s: %s' % (fn, lines[0]),
else:
print "Adding xref to %s" % fn
process_file(fn, lines)
else:
print "Skipping %s: already has a xref" % fn
if __name__ == '__main__':
sys.exit(main())
|
bsd-3-clause
|
ahnitz/pycbc
|
pycbc/strain/calibration.py
|
9
|
5785
|
# Copyright (C) 2018 Colm Talbot
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
""" Functions for adding calibration factors to waveform templates.
"""
import numpy as np
from scipy.interpolate import UnivariateSpline
from abc import (ABCMeta, abstractmethod)
from six import add_metaclass
@add_metaclass(ABCMeta)
class Recalibrate(object):
name = None
def __init__(self, ifo_name):
self.ifo_name = ifo_name
self.params = dict()
@abstractmethod
def apply_calibration(self, strain):
"""Apply calibration model
This method should be overwritten by subclasses
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain.
"""
return
def map_to_adjust(self, strain, prefix='recalib_', **params):
"""Map an input dictionary of sampling parameters to the
adjust_strain function by filtering the dictionary for the
calibration parameters, then calling adjust_strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
prefix: str
Prefix for calibration parameter names
params : dict
Dictionary of sampling parameters which includes
calibration parameters.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain.
"""
self.params.update({
key[len(prefix):]: params[key]
for key in params if prefix in key and self.ifo_name in key})
strain_adjusted = self.apply_calibration(strain)
return strain_adjusted
@classmethod
def from_config(cls, cp, ifo, section):
"""Read a config file to get calibration options and transfer
functions which will be used to intialize the model.
Parameters
----------
cp : WorkflowConfigParser
An open config file.
ifo : string
The detector (H1, L1) for which the calibration model will
be loaded.
section : string
The section name in the config file from which to retrieve
the calibration options.
Return
------
instance
An instance of the class.
"""
all_params = dict(cp.items(section))
params = {key[len(ifo)+1:]: all_params[key]
for key in all_params if ifo.lower() in key}
model = params.pop('model')
params['ifo_name'] = ifo.lower()
return all_models[model](**params)
class CubicSpline(Recalibrate):
name = 'cubic_spline'
def __init__(self, minimum_frequency, maximum_frequency, n_points,
ifo_name):
"""
Cubic spline recalibration
see https://dcc.ligo.org/LIGO-T1400682/public
This assumes the spline points follow
np.logspace(np.log(minimum_frequency), np.log(maximum_frequency),
n_points)
Parameters
----------
minimum_frequency: float
minimum frequency of spline points
maximum_frequency: float
maximum frequency of spline points
n_points: int
number of spline points
"""
Recalibrate.__init__(self, ifo_name=ifo_name)
minimum_frequency = float(minimum_frequency)
maximum_frequency = float(maximum_frequency)
n_points = int(n_points)
if n_points < 4:
raise ValueError(
'Use at least 4 spline points for calibration model')
self.n_points = n_points
self.spline_points = np.logspace(np.log10(minimum_frequency),
np.log10(maximum_frequency), n_points)
def apply_calibration(self, strain):
"""Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySeries
The recalibrated strain.
"""
amplitude_parameters =\
[self.params['amplitude_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
amplitude_spline = UnivariateSpline(self.spline_points,
amplitude_parameters)
delta_amplitude = amplitude_spline(strain.sample_frequencies.numpy())
phase_parameters =\
[self.params['phase_{}_{}'.format(self.ifo_name, ii)]
for ii in range(self.n_points)]
phase_spline = UnivariateSpline(self.spline_points, phase_parameters)
delta_phase = phase_spline(strain.sample_frequencies.numpy())
strain_adjusted = strain * (1.0 + delta_amplitude)\
* (2.0 + 1j * delta_phase) / (2.0 - 1j * delta_phase)
return strain_adjusted
all_models = {
CubicSpline.name: CubicSpline
}
|
gpl-3.0
|
CUCWD/edx-platform
|
cms/djangoapps/contentstore/views/user.py
|
21
|
7908
|
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseNotFound
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_http_methods, require_POST
from opaque_keys.edx.keys import CourseKey
from opaque_keys.edx.locator import LibraryLocator
from course_creators.views import user_requested_access
from edxmako.shortcuts import render_to_response
from student import auth
from student.auth import STUDIO_EDIT_ROLES, STUDIO_VIEW_USERS, get_user_permissions
from student.models import CourseEnrollment
from student.roles import CourseInstructorRole, CourseStaffRole, LibraryUserRole
from util.json_request import JsonResponse, expect_json
from xmodule.modulestore.django import modulestore
__all__ = ['request_course_creator', 'course_team_handler']
@require_POST
@login_required
def request_course_creator(request):
"""
User has requested course creation access.
"""
user_requested_access(request.user)
return JsonResponse({"Status": "OK"})
@login_required
@ensure_csrf_cookie
@require_http_methods(("GET", "POST", "PUT", "DELETE"))
def course_team_handler(request, course_key_string=None, email=None):
"""
The restful handler for course team users.
GET
html: return html page for managing course team
json: return json representation of a particular course team member (email is required).
POST or PUT
json: modify the permissions for a particular course team member (email is required, as well as role in the payload).
DELETE:
json: remove a particular course team member from the course team (email is required).
"""
course_key = CourseKey.from_string(course_key_string) if course_key_string else None
# No permissions check here - each helper method does its own check.
if 'application/json' in request.META.get('HTTP_ACCEPT', 'application/json'):
return _course_team_user(request, course_key, email)
elif request.method == 'GET': # assume html
return _manage_users(request, course_key)
else:
return HttpResponseNotFound()
def user_with_role(user, role):
""" Build user representation with attached role """
return {
'id': user.id,
'username': user.username,
'email': user.email,
'role': role
}
def _manage_users(request, course_key):
"""
This view will return all CMS users who are editors for the specified course
"""
# check that logged in user has permissions to this item
user_perms = get_user_permissions(request.user, course_key)
if not user_perms & STUDIO_VIEW_USERS:
raise PermissionDenied()
course_module = modulestore().get_course(course_key)
instructors = set(CourseInstructorRole(course_key).users_with_role())
# the page only lists staff and assumes they're a superset of instructors. Do a union to ensure.
staff = set(CourseStaffRole(course_key).users_with_role()).union(instructors)
formatted_users = []
for user in instructors:
formatted_users.append(user_with_role(user, 'instructor'))
for user in staff - instructors:
formatted_users.append(user_with_role(user, 'staff'))
return render_to_response('manage_users.html', {
'context_course': course_module,
'show_transfer_ownership_hint': request.user in instructors and len(instructors) == 1,
'users': formatted_users,
'allow_actions': bool(user_perms & STUDIO_EDIT_ROLES),
})
@expect_json
def _course_team_user(request, course_key, email):
"""
Handle the add, remove, promote, demote requests ensuring the requester has authority
"""
# check that logged in user has permissions to this item
requester_perms = get_user_permissions(request.user, course_key)
permissions_error_response = JsonResponse({"error": _("Insufficient permissions")}, 403)
if (requester_perms & STUDIO_VIEW_USERS) or (email == request.user.email):
# This user has permissions to at least view the list of users or is editing themself
pass
else:
# This user is not even allowed to know who the authorized users are.
return permissions_error_response
try:
user = User.objects.get(email=email)
except Exception:
msg = {
"error": _("Could not find user by email address '{email}'.").format(email=email),
}
return JsonResponse(msg, 404)
is_library = isinstance(course_key, LibraryLocator)
# Ordered list of roles: can always move self to the right, but need STUDIO_EDIT_ROLES to move any user left
if is_library:
role_hierarchy = (CourseInstructorRole, CourseStaffRole, LibraryUserRole)
else:
role_hierarchy = (CourseInstructorRole, CourseStaffRole)
if request.method == "GET":
# just return info about the user
msg = {
"email": user.email,
"active": user.is_active,
"role": None,
}
# what's the highest role that this user has? (How should this report global staff?)
for role in role_hierarchy:
if role(course_key).has_user(user):
msg["role"] = role.ROLE
break
return JsonResponse(msg)
# All of the following code is for editing/promoting/deleting users.
# Check that the user has STUDIO_EDIT_ROLES permission or is editing themselves:
if not ((requester_perms & STUDIO_EDIT_ROLES) or (user.id == request.user.id)):
return permissions_error_response
if request.method == "DELETE":
new_role = None
else:
# only other operation supported is to promote/demote a user by changing their role:
# role may be None or "" (equivalent to a DELETE request) but must be set.
# Check that the new role was specified:
if "role" in request.json or "role" in request.POST:
new_role = request.json.get("role", request.POST.get("role"))
else:
return JsonResponse({"error": _("No `role` specified.")}, 400)
# can't modify an inactive user but can remove it
if not (user.is_active or new_role is None):
msg = {
"error": _('User {email} has registered but has not yet activated his/her account.').format(email=email),
}
return JsonResponse(msg, 400)
old_roles = set()
role_added = False
for role_type in role_hierarchy:
role = role_type(course_key)
if role_type.ROLE == new_role:
if (requester_perms & STUDIO_EDIT_ROLES) or (user.id == request.user.id and old_roles):
# User has STUDIO_EDIT_ROLES permission or
# is currently a member of a higher role, and is thus demoting themself
auth.add_users(request.user, role, user)
role_added = True
else:
return permissions_error_response
elif role.has_user(user, check_user_activation=False):
# Remove the user from this old role:
old_roles.add(role)
if new_role and not role_added:
return JsonResponse({"error": _("Invalid `role` specified.")}, 400)
for role in old_roles:
if isinstance(role, CourseInstructorRole) and role.users_with_role().count() == 1:
msg = {"error": _("You may not remove the last Admin. Add another Admin first.")}
return JsonResponse(msg, 400)
auth.remove_users(request.user, role, user)
if new_role and not is_library:
# The user may be newly added to this course.
# auto-enroll the user in the course so that "View Live" will work.
CourseEnrollment.enroll(user, course_key)
return JsonResponse()
|
agpl-3.0
|
marcinzaremba/libcloud
|
docs/conf.py
|
29
|
8465
|
# -*- coding: utf-8 -*-
#
# Apache Libcloud documentation build configuration file, created by
# sphinx-quickstart on Wed Jul 31 12:16:27 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import subprocess
# Detect if we are running on read the docs
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
cmd = 'sphinx-apidoc -d 3 -o apidocs/ ../libcloud/'
subprocess.call(cmd, shell=True)
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Apache Libcloud'
copyright = u'2013, The Apache Software Foundation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.14.0'
# The full version, including alpha/beta/rc tags.
release = '0.14.0-dev'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = [
'_build',
'*/_*.rst'
]
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if on_rtd:
html_theme = 'default'
RTD_NEW_THEME = True
else:
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static', '_static/images/']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'ApacheLibclouddoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'ApacheLibcloud.tex', u'Apache Libcloud Documentation',
u'The Apache Software Foundation', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'apachelibcloud', u'Apache Libcloud Documentation',
[u'The Apache Software Foundation'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ApacheLibcloud', u'Apache Libcloud Documentation',
u'The Apache Software Foundation', 'ApacheLibcloud', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
autoclass_content = 'both'
|
apache-2.0
|
tedder/ansible
|
lib/ansible/modules/cloud/openstack/os_server.py
|
25
|
25051
|
#!/usr/bin/python
# coding: utf-8 -*-
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013, Benno Joy <[email protected]>
# Copyright (c) 2013, John Dewey <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_server
short_description: Create/Delete Compute Instances from OpenStack
extends_documentation_fragment: openstack
version_added: "2.0"
author: "Monty Taylor (@emonty)"
description:
- Create or Remove compute instances from OpenStack.
options:
name:
description:
- Name that has to be given to the instance. It is also possible to
specify the ID of the instance instead of its name if I(state) is I(absent).
required: true
image:
description:
- The name or id of the base image to boot.
required: true
image_exclude:
description:
- Text to use to filter image names, for the case, such as HP, where
there are multiple image names matching the common identifying
portions. image_exclude is a negative match filter - it is text that
may not exist in the image name. Defaults to "(deprecated)"
flavor:
description:
- The name or id of the flavor in which the new instance has to be
created. Mutually exclusive with flavor_ram
default: 1
flavor_ram:
description:
- The minimum amount of ram in MB that the flavor in which the new
instance has to be created must have. Mutually exclusive with flavor.
default: 1
flavor_include:
description:
- Text to use to filter flavor names, for the case, such as Rackspace,
where there are multiple flavors that have the same ram count.
flavor_include is a positive match filter - it must exist in the
flavor name.
key_name:
description:
- The key pair name to be used when creating a instance
security_groups:
description:
- Names of the security groups to which the instance should be
added. This may be a YAML list or a comma separated string.
network:
description:
- Name or ID of a network to attach this instance to. A simpler
version of the nics parameter, only one of network or nics should
be supplied.
nics:
description:
- A list of networks to which the instance's interface should
be attached. Networks may be referenced by net-id/net-name/port-id
or port-name.
- 'Also this accepts a string containing a list of (net/port)-(id/name)
Eg: nics: "net-id=uuid-1,port-name=myport"
Only one of network or nics should be supplied.'
auto_ip:
description:
- Ensure instance has public ip however the cloud wants to do that
type: bool
default: 'yes'
aliases: ['auto_floating_ip', 'public_ip']
floating_ips:
description:
- list of valid floating IPs that pre-exist to assign to this node
floating_ip_pools:
description:
- Name of floating IP pool from which to choose a floating IP
meta:
description:
- 'A list of key value pairs that should be provided as a metadata to
the new instance or a string containing a list of key-value pairs.
Eg: meta: "key1=value1,key2=value2"'
wait:
description:
- If the module should wait for the instance to be created.
type: bool
default: 'yes'
timeout:
description:
- The amount of time the module should wait for the instance to get
into active state.
default: 180
config_drive:
description:
- Whether to boot the server with config drive enabled
type: bool
default: 'no'
userdata:
description:
- Opaque blob of data which is made available to the instance
boot_from_volume:
description:
- Should the instance boot from a persistent volume created based on
the image given. Mututally exclusive with boot_volume.
type: bool
default: 'no'
volume_size:
description:
- The size of the volume to create in GB if booting from volume based
on an image.
boot_volume:
description:
- Volume name or id to use as the volume to boot from. Implies
boot_from_volume. Mutually exclusive with image and boot_from_volume.
aliases: ['root_volume']
terminate_volume:
description:
- If C(yes), delete volume when deleting instance (if booted from volume)
type: bool
default: 'no'
volumes:
description:
- A list of preexisting volumes names or ids to attach to the instance
default: []
scheduler_hints:
description:
- Arbitrary key/value pairs to the scheduler for custom use
version_added: "2.1"
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
delete_fip:
description:
- When I(state) is absent and this option is true, any floating IP
associated with the instance will be deleted along with the instance.
type: bool
default: 'no'
version_added: "2.2"
reuse_ips:
description:
- When I(auto_ip) is true and this option is true, the I(auto_ip) code
will attempt to re-use unassigned floating ips in the project before
creating a new one. It is important to note that it is impossible
to safely do this concurrently, so if your use case involves
concurrent server creation, it is highly recommended to set this to
false and to delete the floating ip associated with a server when
the server is deleted using I(delete_fip).
type: bool
default: 'yes'
version_added: "2.2"
availability_zone:
description:
- Availability zone in which to create the server.
requirements:
- "python >= 2.7"
- "openstacksdk"
'''
EXAMPLES = '''
- name: Create a new instance and attaches to a network and passes metadata to the instance
os_server:
state: present
auth:
auth_url: https://identity.example.com
username: admin
password: admin
project_name: admin
name: vm1
image: 4f905f38-e52a-43d2-b6ec-754a13ffb529
key_name: ansible_key
timeout: 200
flavor: 4
nics:
- net-id: 34605f38-e52a-25d2-b6ec-754a13ffb723
- net-name: another_network
meta:
hostname: test1
group: uge_master
# Create a new instance in HP Cloud AE1 region availability zone az2 and
# automatically assigns a floating IP
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
state: present
auth:
auth_url: https://identity.example.com
username: username
password: Equality7-2521
project_name: username-project1
name: vm1
region_name: region-b.geo-1
availability_zone: az2
image: 9302692b-b787-4b52-a3a6-daebb79cb498
key_name: test
timeout: 200
flavor: 101
security_groups: default
auto_ip: yes
# Create a new instance in named cloud mordred availability zone az2
# and assigns a pre-known floating IP
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
state: present
cloud: mordred
name: vm1
availability_zone: az2
image: 9302692b-b787-4b52-a3a6-daebb79cb498
key_name: test
timeout: 200
flavor: 101
floating_ips:
- 12.34.56.79
# Create a new instance with 4G of RAM on Ubuntu Trusty, ignoring
# deprecated images
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
state: present
cloud: mordred
region_name: region-b.geo-1
image: Ubuntu Server 14.04
image_exclude: deprecated
flavor_ram: 4096
# Create a new instance with 4G of RAM on Ubuntu Trusty on a Performance node
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
cloud: rax-dfw
state: present
image: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)
flavor_ram: 4096
flavor_include: Performance
# Creates a new instance and attaches to multiple network
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance with a string
os_server:
auth:
auth_url: https://identity.example.com
username: admin
password: admin
project_name: admin
name: vm1
image: 4f905f38-e52a-43d2-b6ec-754a13ffb529
key_name: ansible_key
timeout: 200
flavor: 4
nics: "net-id=4cb08b20-62fe-11e5-9d70-feff819cdc9f,net-id=542f0430-62fe-11e5-9d70-feff819cdc9f..."
- name: Creates a new instance and attaches to a network and passes metadata to the instance
os_server:
state: present
auth:
auth_url: https://identity.example.com
username: admin
password: admin
project_name: admin
name: vm1
image: 4f905f38-e52a-43d2-b6ec-754a13ffb529
key_name: ansible_key
timeout: 200
flavor: 4
nics:
- net-id: 34605f38-e52a-25d2-b6ec-754a13ffb723
- net-name: another_network
meta: "hostname=test1,group=uge_master"
- name: Creates a new instance and attaches to a specific network
os_server:
state: present
auth:
auth_url: https://identity.example.com
username: admin
password: admin
project_name: admin
name: vm1
image: 4f905f38-e52a-43d2-b6ec-754a13ffb529
key_name: ansible_key
timeout: 200
flavor: 4
network: another_network
# Create a new instance with 4G of RAM on a 75G Ubuntu Trusty volume
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
state: present
cloud: mordred
region_name: ams01
image: Ubuntu Server 14.04
flavor_ram: 4096
boot_from_volume: True
volume_size: 75
# Creates a new instance with 2 volumes attached
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
state: present
cloud: mordred
region_name: ams01
image: Ubuntu Server 14.04
flavor_ram: 4096
volumes:
- photos
- music
# Creates a new instance with provisioning userdata using Cloud-Init
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
state: present
image: "Ubuntu Server 14.04"
flavor: "P-1"
network: "Production"
userdata: |
#cloud-config
chpasswd:
list: |
ubuntu:{{ default_password }}
expire: False
packages:
- ansible
package_upgrade: true
# Creates a new instance with provisioning userdata using Bash Scripts
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
name: vm1
state: present
image: "Ubuntu Server 14.04"
flavor: "P-1"
network: "Production"
userdata: |
{%- raw -%}#!/bin/bash
echo " up ip route add 10.0.0.0/8 via {% endraw -%}{{ intra_router }}{%- raw -%}" >> /etc/network/interfaces.d/eth0.conf
echo " down ip route del 10.0.0.0/8" >> /etc/network/interfaces.d/eth0.conf
ifdown eth0 && ifup eth0
{% endraw %}
# Create a new instance with server group for (anti-)affinity
# server group ID is returned from os_server_group module.
- name: launch a compute instance
hosts: localhost
tasks:
- name: launch an instance
os_server:
state: present
name: vm1
image: 4f905f38-e52a-43d2-b6ec-754a13ffb529
flavor: 4
scheduler_hints:
group: f5c8c61a-9230-400a-8ed2-3b023c190a7f
# Deletes an instance via its ID
- name: remove an instance
hosts: localhost
tasks:
- name: remove an instance
os_server:
name: abcdef01-2345-6789-0abc-def0123456789
state: absent
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import (
openstack_find_nova_addresses, openstack_cloud_from_module,
openstack_full_argument_spec, openstack_module_kwargs)
def _exit_hostvars(module, cloud, server, changed=True):
hostvars = cloud.get_openstack_vars(server)
module.exit_json(
changed=changed, server=server, id=server.id, openstack=hostvars)
def _parse_nics(nics):
for net in nics:
if isinstance(net, str):
for nic in net.split(','):
yield dict((nic.split('='),))
else:
yield net
def _network_args(module, cloud):
args = []
nics = module.params['nics']
if not isinstance(nics, list):
module.fail_json(msg='The \'nics\' parameter must be a list.')
for net in _parse_nics(nics):
if not isinstance(net, dict):
module.fail_json(
msg='Each entry in the \'nics\' parameter must be a dict.')
if net.get('net-id'):
args.append(net)
elif net.get('net-name'):
by_name = cloud.get_network(net['net-name'])
if not by_name:
module.fail_json(
msg='Could not find network by net-name: %s' %
net['net-name'])
args.append({'net-id': by_name['id']})
elif net.get('port-id'):
args.append(net)
elif net.get('port-name'):
by_name = cloud.get_port(net['port-name'])
if not by_name:
module.fail_json(
msg='Could not find port by port-name: %s' %
net['port-name'])
args.append({'port-id': by_name['id']})
return args
def _parse_meta(meta):
if isinstance(meta, str):
metas = {}
for kv_str in meta.split(","):
k, v = kv_str.split("=")
metas[k] = v
return metas
if not meta:
return {}
return meta
def _delete_server(module, cloud):
try:
cloud.delete_server(
module.params['name'], wait=module.params['wait'],
timeout=module.params['timeout'],
delete_ips=module.params['delete_fip'])
except Exception as e:
module.fail_json(msg="Error in deleting vm: %s" % e.message)
module.exit_json(changed=True, result='deleted')
def _create_server(module, cloud):
flavor = module.params['flavor']
flavor_ram = module.params['flavor_ram']
flavor_include = module.params['flavor_include']
image_id = None
if not module.params['boot_volume']:
image_id = cloud.get_image_id(
module.params['image'], module.params['image_exclude'])
if not image_id:
module.fail_json(msg="Could not find image %s" %
module.params['image'])
if flavor:
flavor_dict = cloud.get_flavor(flavor)
if not flavor_dict:
module.fail_json(msg="Could not find flavor %s" % flavor)
else:
flavor_dict = cloud.get_flavor_by_ram(flavor_ram, flavor_include)
if not flavor_dict:
module.fail_json(msg="Could not find any matching flavor")
nics = _network_args(module, cloud)
module.params['meta'] = _parse_meta(module.params['meta'])
bootkwargs = dict(
name=module.params['name'],
image=image_id,
flavor=flavor_dict['id'],
nics=nics,
meta=module.params['meta'],
security_groups=module.params['security_groups'],
userdata=module.params['userdata'],
config_drive=module.params['config_drive'],
)
for optional_param in (
'key_name', 'availability_zone', 'network',
'scheduler_hints', 'volume_size', 'volumes'):
if module.params[optional_param]:
bootkwargs[optional_param] = module.params[optional_param]
server = cloud.create_server(
ip_pool=module.params['floating_ip_pools'],
ips=module.params['floating_ips'],
auto_ip=module.params['auto_ip'],
boot_volume=module.params['boot_volume'],
boot_from_volume=module.params['boot_from_volume'],
terminate_volume=module.params['terminate_volume'],
reuse_ips=module.params['reuse_ips'],
wait=module.params['wait'], timeout=module.params['timeout'],
**bootkwargs
)
_exit_hostvars(module, cloud, server)
def _update_server(module, cloud, server):
changed = False
module.params['meta'] = _parse_meta(module.params['meta'])
# cloud.set_server_metadata only updates the key=value pairs, it doesn't
# touch existing ones
update_meta = {}
for (k, v) in module.params['meta'].items():
if k not in server.metadata or server.metadata[k] != v:
update_meta[k] = v
if update_meta:
cloud.set_server_metadata(server, update_meta)
changed = True
# Refresh server vars
server = cloud.get_server(module.params['name'])
return (changed, server)
def _detach_ip_list(cloud, server, extra_ips):
for ip in extra_ips:
ip_id = cloud.get_floating_ip(
id=None, filters={'floating_ip_address': ip})
cloud.detach_ip_from_server(
server_id=server.id, floating_ip_id=ip_id)
def _check_ips(module, cloud, server):
changed = False
auto_ip = module.params['auto_ip']
floating_ips = module.params['floating_ips']
floating_ip_pools = module.params['floating_ip_pools']
if floating_ip_pools or floating_ips:
ips = openstack_find_nova_addresses(server.addresses, 'floating')
if not ips:
# If we're configured to have a floating but we don't have one,
# let's add one
server = cloud.add_ips_to_server(
server,
auto_ip=auto_ip,
ips=floating_ips,
ip_pool=floating_ip_pools,
wait=module.params['wait'],
timeout=module.params['timeout'],
)
changed = True
elif floating_ips:
# we were configured to have specific ips, let's make sure we have
# those
missing_ips = []
for ip in floating_ips:
if ip not in ips:
missing_ips.append(ip)
if missing_ips:
server = cloud.add_ip_list(server, missing_ips,
wait=module.params['wait'],
timeout=module.params['timeout'])
changed = True
extra_ips = []
for ip in ips:
if ip not in floating_ips:
extra_ips.append(ip)
if extra_ips:
_detach_ip_list(cloud, server, extra_ips)
changed = True
elif auto_ip:
if server['interface_ip']:
changed = False
else:
# We're configured for auto_ip but we're not showing an
# interface_ip. Maybe someone deleted an IP out from under us.
server = cloud.add_ips_to_server(
server,
auto_ip=auto_ip,
ips=floating_ips,
ip_pool=floating_ip_pools,
wait=module.params['wait'],
timeout=module.params['timeout'],
)
changed = True
return (changed, server)
def _check_security_groups(module, cloud, server):
changed = False
# server security groups were added to shade in 1.19. Until then this
# module simply ignored trying to update security groups and only set them
# on newly created hosts.
if not (hasattr(cloud, 'add_server_security_groups') and
hasattr(cloud, 'remove_server_security_groups')):
return changed, server
module_security_groups = set(module.params['security_groups'])
server_security_groups = set(sg['name'] for sg in server.security_groups)
add_sgs = module_security_groups - server_security_groups
remove_sgs = server_security_groups - module_security_groups
if add_sgs:
cloud.add_server_security_groups(server, list(add_sgs))
changed = True
if remove_sgs:
cloud.remove_server_security_groups(server, list(remove_sgs))
changed = True
return (changed, server)
def _get_server_state(module, cloud):
state = module.params['state']
server = cloud.get_server(module.params['name'])
if server and state == 'present':
if server.status not in ('ACTIVE', 'SHUTOFF', 'PAUSED', 'SUSPENDED'):
module.fail_json(
msg="The instance is available but not Active state: " + server.status)
(ip_changed, server) = _check_ips(module, cloud, server)
(sg_changed, server) = _check_security_groups(module, cloud, server)
(server_changed, server) = _update_server(module, cloud, server)
_exit_hostvars(module, cloud, server,
ip_changed or sg_changed or server_changed)
if server and state == 'absent':
return True
if state == 'absent':
module.exit_json(changed=False, result="not present")
return True
def main():
argument_spec = openstack_full_argument_spec(
name=dict(required=True),
image=dict(default=None),
image_exclude=dict(default='(deprecated)'),
flavor=dict(default=None),
flavor_ram=dict(default=None, type='int'),
flavor_include=dict(default=None),
key_name=dict(default=None),
security_groups=dict(default=['default'], type='list'),
network=dict(default=None),
nics=dict(default=[], type='list'),
meta=dict(default=None, type='raw'),
userdata=dict(default=None, aliases=['user_data']),
config_drive=dict(default=False, type='bool'),
auto_ip=dict(default=True, type='bool', aliases=['auto_floating_ip', 'public_ip']),
floating_ips=dict(default=None, type='list'),
floating_ip_pools=dict(default=None, type='list'),
volume_size=dict(default=False, type='int'),
boot_from_volume=dict(default=False, type='bool'),
boot_volume=dict(default=None, aliases=['root_volume']),
terminate_volume=dict(default=False, type='bool'),
volumes=dict(default=[], type='list'),
scheduler_hints=dict(default=None, type='dict'),
state=dict(default='present', choices=['absent', 'present']),
delete_fip=dict(default=False, type='bool'),
reuse_ips=dict(default=True, type='bool'),
)
module_kwargs = openstack_module_kwargs(
mutually_exclusive=[
['auto_ip', 'floating_ips'],
['auto_ip', 'floating_ip_pools'],
['floating_ips', 'floating_ip_pools'],
['flavor', 'flavor_ram'],
['image', 'boot_volume'],
['boot_from_volume', 'boot_volume'],
['nics', 'network'],
],
required_if=[
('boot_from_volume', True, ['volume_size', 'image']),
],
)
module = AnsibleModule(argument_spec, **module_kwargs)
state = module.params['state']
image = module.params['image']
boot_volume = module.params['boot_volume']
flavor = module.params['flavor']
flavor_ram = module.params['flavor_ram']
if state == 'present':
if not (image or boot_volume):
module.fail_json(
msg="Parameter 'image' or 'boot_volume' is required "
"if state == 'present'"
)
if not flavor and not flavor_ram:
module.fail_json(
msg="Parameter 'flavor' or 'flavor_ram' is required "
"if state == 'present'"
)
sdk, cloud = openstack_cloud_from_module(module)
try:
if state == 'present':
_get_server_state(module, cloud)
_create_server(module, cloud)
elif state == 'absent':
_get_server_state(module, cloud)
_delete_server(module, cloud)
except sdk.exceptions.OpenStackCloudException as e:
module.fail_json(msg=str(e), extra_data=e.extra_data)
if __name__ == '__main__':
main()
|
gpl-3.0
|
iliTheFallen/UHVision
|
SelfDrivingCar/sandbox/sandbox.py
|
1
|
7885
|
'''
Copyright 2017-2022 Department of Electrical and Computer Engineering
University of Houston, TX/USA
This file is part of UHVision Libraries.
UH Vision libraries are free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
UH Vision Libraries are distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with licenses for all the 3rd party libraries used in this repository.
If not, see <http://www.gnu.org/licenses/>.
Please contact Hien Nguyen V for more info about licensing [email protected],
and other members of the UHVision Lab via github issues section.
**********************************************************************************
Author: Ilker GURCAN
Date: 4/7/17
File: sandbox
Comments:
**********************************************************************************
'''
import tensorflow as tf
from PIL import Image
from data.convert_to_tf_record import ConvertToTFRecord
from data.convert_to_tf_seq import ConvertToTFSeq
from data.gtav_data_reader import GTAVDataReader
from data.tf_record_feeder import TFRecordFeeder
from data.tf_seq_rec_feeder import TFSeqRecFeeder
from metalearning_tf.utils import loss_funcs
from utils import constants as consts
def test_huber_m_cost():
targets = [[4, 3],
[2, 4],
[5, 5],
[10, 6]]
targets = tf.constant(targets, dtype=tf.float32, name="targets")
labels = [[20, 8],
[1, 8],
[5, 8],
[13, 8]]
labels = tf.constant(labels, dtype=tf.float32, name="labels")
loss_tensor = loss_funcs.huber_m_loss(labels, targets, 0.5)
init = tf.global_variables_initializer()
with tf.Graph().as_default(), tf.device("/gpu:0"):
with tf.Session() as sess:
sess.run(init)
res = sess.run(loss_tensor)
print('Loss function for 2 features: \n', res)
def convert_to_tf_record():
reader = GTAVDataReader(episodeSize=1,
max_iter=0,
drive_folder=
'/home/ilithefallen/Documents/GTAVDrives')
names = [
consts.STEERING_ANGLE,
consts.THROTTLE,
consts.BRAKE
]
converter = ConvertToTFRecord(reader,
'/home/ilithefallen/Documents/phdThesis'
'/UHVision/SelfDrivingCar/samples',
'gtav_training',
names,
tf.float32)
converter.convert(13056, im_size=(300, 400))
def convert_to_tf_seq_record():
reader = GTAVDataReader(episodeSize=1,
max_iter=0,
drive_folder=
'/home/ilithefallen/Documents/GTAVDrives')
names = [
consts.STEERING_ANGLE,
consts.THROTTLE,
consts.BRAKE
]
converter = ConvertToTFSeq(reader,
'/home/ilithefallen/Documents/phdThesis'
'/UHVision/SelfDrivingCar/samples',
'gtav_seq_training',
names,
tf.float32,
80)
converter.convert(-1, im_size=(300, 400))
def test_parallel_data_feeder():
names = [
consts.STEERING_ANGLE,
consts.THROTTLE,
consts.BRAKE
]
data_feeder = TFRecordFeeder(2,
'/home/ilithefallen/Documents/phdThesis'
'/UHVision/SelfDrivingCar/samples'
'/gtav_training.tfrecords',
1,
names,
tf.float32,
[300, 400, 3])
images, labels = data_feeder.inputs(64, 13056, 0.4, True)
init = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
with tf.device("/cpu:0"):
with tf.Session() as sess:
sess.run(init)
# Start input enqueue threads for reading input data using 'parallel data feeder' mechanism
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
step = 0
try:
while not coord.should_stop():
im_out, la_out = sess.run([images, labels])
num_im = im_out.shape[0]
for i in range(num_im):
image = Image.fromarray(im_out[i, :, :, :], 'RGB')
image.show()
step += 1
except tf.errors.OutOfRangeError:
print('Done reading for %d steps.' % (step))
except KeyboardInterrupt:
print('Done reading for %d steps.' % (step))
finally:
# When done, ask all threads to stop
coord.request_stop()
# Wait for threads to finish
coord.join(threads)
def test_seq_rec_feeder():
names = [
consts.STEERING_ANGLE,
consts.THROTTLE,
consts.BRAKE
]
data_feeder = TFSeqRecFeeder(1,
'/home/ilithefallen/Documents/phdThesis'
'/UHVision/SelfDrivingCar/samples'
'/gtav_seq_training.tfrecords',
1,
names,
[tf.string, tf.float32],
[300, 400, 3],
80)
images, labels, labels2 = data_feeder.inputs(1, 13110, 0.4, True)
init = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
with tf.device("/cpu:0"):
with tf.Session() as sess:
sess.run(init)
# Start input enqueue threads for reading input data using 'parallel data feeder' mechanism
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
step = 0
try:
while not coord.should_stop():
la_out = sess.run(labels)
deneme = sess.run(labels2)
# num_im = im_out.shape[0]
# for i in range(num_im):
# image = Image.fromarray(im_out[i, :, :, :], 'RGB')
# image.show()
step += 1
except tf.errors.OutOfRangeError:
print('Done reading for %d steps.' % (step))
except KeyboardInterrupt:
print('Done reading for %d steps.' % (step))
finally:
# When done, ask all threads to stop
coord.request_stop()
# Wait for threads to finish
coord.join(threads)
def func1(name, soft_id):
print('Name %s / SoftId: %d' % (name, soft_id))
def pack_unpack(**kwargs):
print('Calling the function func1')
func1(**kwargs)
if __name__ == "__main__":
# test_huber_m_cost()
# convert_to_tf_record()
# convert_to_tf_seq_record()
test_seq_rec_feeder()
# test_parallel_data_feeder()
# pack_unpack(name='Ilker GURCAN', soft_id=1456789)
|
gpl-3.0
|
VinGarcia/kivy
|
kivy/resources.py
|
46
|
1556
|
'''
Resources management
====================
Resource management can be a pain if you have multiple paths and projects. Kivy
offers 2 functions for searching for specific resources across a list of
paths.
'''
__all__ = ('resource_find', 'resource_add_path', 'resource_remove_path')
from os.path import join, dirname, exists
from kivy import kivy_data_dir
from kivy.utils import platform
from kivy.logger import Logger
import sys
import kivy
resource_paths = ['.', dirname(sys.argv[0])]
if platform == 'ios':
resource_paths += [join(dirname(sys.argv[0]), 'YourApp')]
resource_paths += [dirname(kivy.__file__), join(kivy_data_dir, '..')]
def resource_find(filename):
'''Search for a resource in the list of paths.
Use resource_add_path to add a custom path to the search.
'''
if not filename:
return None
if filename[:8] == 'atlas://':
return filename
if exists(filename):
return filename
for path in reversed(resource_paths):
output = join(path, filename)
if exists(output):
return output
return None
def resource_add_path(path):
'''Add a custom path to search in.
'''
if path in resource_paths:
return
Logger.debug('Resource: add <%s> in path list' % path)
resource_paths.append(path)
def resource_remove_path(path):
'''Remove a search path.
.. versionadded:: 1.0.8
'''
if path not in resource_paths:
return
Logger.debug('Resource: remove <%s> from path list' % path)
resource_paths.remove(path)
|
mit
|
Flexget/Flexget
|
flexget/components/sites/sites/site_rutracker.py
|
1
|
1776
|
# -*- coding: utf-8 -*-
from urllib.parse import parse_qs, urlencode, urlparse
from loguru import logger
from requests.exceptions import RequestException
from flexget import plugin
from flexget.components.sites.urlrewriting import UrlRewritingError
from flexget.event import event
logger = logger.bind(name='rutracker')
class SiteRutracker:
schema = {'type': 'boolean'}
base_url = 'https://api.t-ru.org'
# urlrewriter API
def url_rewritable(self, task, entry):
url = entry['url']
return url.startswith('https://rutracker.org/forum/viewtopic.php?t=')
@plugin.internet(logger)
def url_rewrite(self, task, entry):
"""
Gets torrent information for topic from rutracker api
"""
url = entry['url']
logger.info('rewriting download url: {}', url)
topic_id = parse_qs(urlparse(url).query)['t'][0]
api_url = f"{self.base_url}/v1/get_tor_topic_data"
api_params = {
'by': 'topic_id',
'val': topic_id,
}
try:
topic_request = task.requests.get(api_url, params=api_params)
except RequestException as e:
raise UrlRewritingError(f'rutracker request failed: {e}')
topic = topic_request.json()['result'][topic_id]
magnet = {
'xt': f"urn:btih:{topic['info_hash']}",
'tr': [f'http://bt{i}.t-ru.org/ann?magnet' for i in ['', '2', '3', '4']],
'dn': topic['topic_title'],
}
magnet_qs = urlencode(magnet, doseq=True, safe=':')
magnet_uri = f"magnet:?{magnet_qs}"
entry['url'] = magnet_uri
@event('plugin.register')
def register_plugin():
plugin.register(SiteRutracker, 'rutracker', interfaces=['urlrewriter'], api_ver=2)
|
mit
|
etos/django
|
tests/migrations/test_multidb.py
|
68
|
6865
|
import unittest
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
from django.test import override_settings
from .test_operations import OperationTestBase
try:
import sqlparse
except ImportError:
sqlparse = None
class AgnosticRouter:
"""
A router that doesn't have an opinion regarding migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return None
class MigrateNothingRouter:
"""
A router that doesn't allow migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return False
class MigrateEverythingRouter:
"""
A router that always allows migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return True
class MigrateWhenFooRouter:
"""
A router that allows migrating depending on a hint.
"""
def allow_migrate(self, db, app_label, **hints):
return hints.get('foo', False)
class MultiDBOperationTests(OperationTestBase):
multi_db = True
def _test_create_model(self, app_label, should_run):
"""
CreateModel honors multi-db settings.
"""
operation = migrations.CreateModel(
"Pony",
[("id", models.AutoField(primary_key=True))],
)
# Test the state alteration
project_state = ProjectState()
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
# Test the database alteration
self.assertTableNotExists("%s_pony" % app_label)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
if should_run:
self.assertTableExists("%s_pony" % app_label)
else:
self.assertTableNotExists("%s_pony" % app_label)
# And test reversal
with connection.schema_editor() as editor:
operation.database_backwards(app_label, editor, new_state, project_state)
self.assertTableNotExists("%s_pony" % app_label)
@override_settings(DATABASE_ROUTERS=[AgnosticRouter()])
def test_create_model(self):
"""
Test when router doesn't have an opinion (i.e. CreateModel should run).
"""
self._test_create_model("test_mltdb_crmo", should_run=True)
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_create_model2(self):
"""
Test when router returns False (i.e. CreateModel shouldn't run).
"""
self._test_create_model("test_mltdb_crmo2", should_run=False)
@override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()])
def test_create_model3(self):
"""
Test when router returns True (i.e. CreateModel should run).
"""
self._test_create_model("test_mltdb_crmo3", should_run=True)
def test_create_model4(self):
"""
Test multiple routers.
"""
with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=False)
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
def _test_run_sql(self, app_label, should_run, hints=None):
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
project_state = self.set_up_test_model(app_label)
sql = """
INSERT INTO {0}_pony (pink, weight) VALUES (1, 3.55);
INSERT INTO {0}_pony (pink, weight) VALUES (3, 5.0);
""".format(app_label)
operation = migrations.RunSQL(sql, hints=hints or {})
# Test the state alteration does nothing
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
self.assertEqual(new_state, project_state)
# Test the database alteration
self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
Pony = project_state.apps.get_model(app_label, "Pony")
if should_run:
self.assertEqual(Pony.objects.count(), 2)
else:
self.assertEqual(Pony.objects.count(), 0)
@unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_run_sql(self):
self._test_run_sql("test_mltdb_runsql", should_run=False)
@unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
@override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()])
def test_run_sql2(self):
self._test_run_sql("test_mltdb_runsql2", should_run=False)
self._test_run_sql("test_mltdb_runsql2", should_run=True, hints={'foo': True})
def _test_run_python(self, app_label, should_run, hints=None):
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
project_state = self.set_up_test_model(app_label)
# Create the operation
def inner_method(models, schema_editor):
Pony = models.get_model(app_label, "Pony")
Pony.objects.create(pink=1, weight=3.55)
Pony.objects.create(weight=5)
operation = migrations.RunPython(inner_method, hints=hints or {})
# Test the state alteration does nothing
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
self.assertEqual(new_state, project_state)
# Test the database alteration
self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
Pony = project_state.apps.get_model(app_label, "Pony")
if should_run:
self.assertEqual(Pony.objects.count(), 2)
else:
self.assertEqual(Pony.objects.count(), 0)
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_run_python(self):
self._test_run_python("test_mltdb_runpython", should_run=False)
@override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()])
def test_run_python2(self):
self._test_run_python("test_mltdb_runpython2", should_run=False)
self._test_run_python("test_mltdb_runpython2", should_run=True, hints={'foo': True})
|
bsd-3-clause
|
merll/server-tracking
|
server_tracking/google/client.py
|
2
|
15043
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from . import (HIT_TYPE_TRANSACTION, HIT_TYPE_TRANSACTION_ITEM, HIT_TYPE_EVENT, HIT_TYPE_SCREENVIEW, HIT_TYPE_PAGEVIEW,
HIT_TYPE_SOCIAL, HIT_TYPE_TIMING, HIT_TYPE_EXCEPTION)
from .parameters import (GeneralParameters, PageViewParameters, EventParameters, AppTrackingParameters,
EComTransactionParameters, EComItemParameters, HitParameters, SessionParameters,
SocialInteractionParameters, TimingParameters, ExceptionParameters)
log = logging.getLogger(__name__)
class AnalyticsClient(object):
"""
Client implementation that uses the Google Analytics Measurement Protocol.
:param send_func: A function that takes request parameters as input and sends a request to the appropriate URL.
:type send_func: callable
:param general_parameters: Default general parameters to pass with each hit.
:type general_parameters: server_tracking.google.parameters.GeneralParameters | dict
:param misc_parameters: Additional UrlGenerator objects to use as default parameters.
:type misc_parameters: tuple[server_tracking.parameters.UrlGenerator] |
list[server_tracking.parameters.UrlGenerator]
:param kwargs: Keyword arguments for general parameters.
"""
def __init__(self, send_func, general_parameters=None, misc_parameters=(), **kwargs):
if isinstance(general_parameters, (dict, GeneralParameters)):
self._general_parameters = GeneralParameters(general_parameters)
elif general_parameters is not None:
raise ValueError("Invalid type of default parameters: {0}.", type(general_parameters).__name__)
self._general_parameters.update(kwargs)
self._misc_parameters = misc_parameters
self._misc_url = None
self.update_misc_parameters()
self._send_func = send_func
def update_misc_parameters(self):
"""
Updates the generated parameters from :attr:`AnalyticsClient.misc_parameters`. Only needs to be called
explicitly, if the objects have gotten modified after the assignment.
"""
self._misc_url = misc_url = {}
for p in self._misc_parameters:
misc_url.update(p.url())
def request(self, hit_type, *params, **kwargs):
"""
Sends a request to Google Analytics.
:param hit_type: Hit type.
:type hit_type: unicode | str
:param params: UrlGenerator objects to provide parameters.
:type params: Tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: In normal scenarios always returns ``True``. For synchronous requests actually processes the status
code, but Google Analytics does not return error codes for invalid hits. In debug mode, hits are validated
by GA and this method returns the parsed result.
:rtype: bool | server_tracking.google.debug.HitParserResults
"""
request_params = self._general_parameters.url(hit_type)
for p in params:
if p:
request_params.update(p.url())
request_params.update(self._misc_url)
request_params.update(kwargs)
response = self._send_func(request_params)
if response:
return response.status_code <= 400
return True
def pageview(self, params=None, location_url=None, host_name=None, path=None, session_params=None, misc_params=(),
**kwargs):
"""
Generates and sends a page view.
:param params: Initial page view parameters. Where applicable, overridden by following arguments.
:type params: dict | server_tracking.google.parameters.PageViewParameters
:param location_url: Full location URL.
:type location_url: unicode | str
:param host_name: Host name.
:type host_name: unicode | str
:param path: URL path.
:type path: unicode | str
:param session_params: Optional session parameters.
:type session_params: server_tracking.google.parameters.SessionParameters
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
page = PageViewParameters(params,
location_url=location_url,
host_name=host_name,
path=path,
**kwargs)
return self.request(HIT_TYPE_PAGEVIEW, page, session_params, *misc_params)
def screenview(self, screen_name, app_name, page_params=None, misc_params=(), **kwargs):
"""
Generates and sends a screen view.
:param screen_name: Screen name.
:type screen_name: unicode | str
:param app_name: App name.
:type app_name: unicode | str
:param page_params: Optional additional page view parameters.
:type page_params: dict | server_tracking.google.parameters.PageViewParameters
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
page = PageViewParameters(page_params, screen_name=screen_name)
app = AppTrackingParameters(name=app_name, **kwargs)
return self.request(HIT_TYPE_SCREENVIEW, page, app, *misc_params)
def event(self, category, action, label=None, value=None, location_url=None, host_name=None, path=None,
non_interaction_hit=None, page_params=None, session_params=None, hit_params=None, misc_params=(),
**kwargs):
"""
Generates and sends an event.
:param category: Event category.
:type category: unicode | str
:param action: Event action.
:type action: unicode | str
:param label: Event label.
:type label: unicode | str
:param value: Event value.
:type value: int | float
:param location_url: Location URL. Alternative to providing ``host_name`` and ``path``.
:type location_url: unicode | str
:param host_name: Host name.
:type host_name: unicode | str
:param path: URL path.
:type path: unicode | str
:param non_interaction_hit: Set to ``1`` if event is not based on a user interaction.
:type non_interaction_hit: int
:param page_params: Page view parameters. Where provided, updated with previous parameters ``location_url``,
``host_name``, and ``path``.
:param session_params: Optional session parameters.
:type session_params: server_tracking.google.parameters.SessionParameters
:param hit_params: Optional hit parameters. Where provided, updated with previous parameter
``non_interaction_hit``.
:type hit_params: server_tracking.google.parameters.HitParameters
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
if any((page_params, location_url, host_name, path)):
page = PageViewParameters(page_params, location_url=location_url, host_name=host_name, path=path)
else:
page = None
event = EventParameters(category, action=action, label=label, value=value)
session = SessionParameters(session_params)
hit = HitParameters(hit_params, non_interaction_hit=non_interaction_hit)
return self.request(HIT_TYPE_EVENT, page, event, session, hit, *misc_params, **kwargs)
def transaction(self, transaction_id, items, affiliation=None, revenue='sum', shipping=None, tax=None,
currency_code=None, page_params=None, misc_params=(), **kwargs):
"""
Sends an E-Commerce transaction and items.
:param transaction_id: Transaction id.
:type transaction_id: int | unicode | str
:param items: List of items in the transaction.
:type items: list[server_tracking.google.parameters.EComItem]
:param affiliation: Transaction affiliation.
:type affiliation: unicode | str
:param revenue: Transaction revenue. Pass ``sum`` if this is the sum of each item ``price * quantity`` plus
``shipping`` and ``tax``.
:type revenue: float | unicode | str
:param shipping: Transaction shipping.
:type shipping: float
:param tax: Transaction tax.
:type tax: float
:param currency_code: Transaction currency code. Also applied to all items that do not have one on their own.
:type currency_code: unicode | str
:param page_params: Page view parameters.
:type page_params: server_tracking.google.parameters.PageViewParameters | dict
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Returns ``True`` when all generated hits got sent or deferred to a separate thread / task.
:rtype: bool
"""
page = PageViewParameters(page_params) if page_params else None
if revenue == 'sum':
revenue = shipping or 0 + tax or 0 + sum((item.price or 0) * (item.quantity or 1) for item in items)
transaction = EComTransactionParameters(transaction_id=transaction_id, affiliation=affiliation, revenue=revenue,
shipping=shipping, tax=tax, **kwargs)
item_params = [EComItemParameters.from_item(item, transaction_id, transaction_currency=currency_code)
for item in items]
tr = self.request(HIT_TYPE_TRANSACTION, transaction, page, *misc_params)
ti = all(self.request(HIT_TYPE_TRANSACTION_ITEM, item, page) for item in item_params) if item_params else True
return tr and ti
def social(self, network, action, target, page_params=None, misc_params=(), **kwargs):
"""
Sends a social interaction hit.
:param network: Social network.
:type network: unicode | str
:param action: Social action.
:type action: unicode | str
:param target: Social action target, e.g. URL.
:type target: unicode | str
:param page_params: Page view parameters.
:type page_params: server_tracking.google.parameters.PageViewParameters | dict
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
social = SocialInteractionParameters(network=network, action=action, target=target)
page = PageViewParameters(page_params) if page_params else None
return self.request(HIT_TYPE_SOCIAL, social, page, *misc_params, **kwargs)
def timing(self, user_timing_category, user_timing_variable, user_timing_value, page_params=None, misc_params=(),
**kwargs):
"""
Generates and sends a timing event.
:param user_timing_category: User timing category.
:param user_timing_variable: User timing variable.
:param user_timing_value: User timing value.
:param page_params: Page view parameters.
:type page_params: server_tracking.google.parameters.PageViewParameters | dict
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
timing = TimingParameters(user_timing_category=user_timing_category, user_timing_variable=user_timing_variable,
user_timing_value=user_timing_value)
page = PageViewParameters(page_params) if page_params else None
return self.request(HIT_TYPE_TIMING, timing, page, *misc_params, **kwargs)
def exception(self, description=None, fatal=None, page_params=None, misc_params=(), **kwargs):
"""
Sends an exception hit.
:param description: Exception description.
:type description: unicode | str
:param fatal: Set to ``True`` if the exception was fatal.
:type fatal: int
:param page_params: Page view parameters.
:type page_params: server_tracking.google.parameters.PageViewParameters | dict
:param misc_params: Miscellaneous parameters to add to the hit.
:type misc_params: tuple[server_tracking.parameters.UrlGenerator]
:param kwargs: Raw url parameters to update the generated url with.
:return: Varies, see :meth:`request`.
:rtype: bool | unicode | str
"""
if description or fatal is not None:
exception = ExceptionParameters(description=description, fatal=fatal)
else:
exception = None
page = PageViewParameters(page_params) if page_params else None
return self.request(HIT_TYPE_EXCEPTION, exception, page, *misc_params, **kwargs)
@property
def general_parameters(self):
"""
General parameters to be sent with every hit, e.g. page view or event.
:return: GeneralParameters object. Input can also be provided as a dictionary.
:rtype: server_tracking.google.parameters.GeneralParameters
"""
return self._general_parameters
@general_parameters.setter
def general_parameters(self, value):
self._general_parameters = GeneralParameters(value)
@property
def misc_parameters(self):
"""
Miscellaneous parameters to be sent with every hit, e.g. page view or event. Can for example include
a :class:`server_tracking.google.parameters.SessionParameters` object, if you repeatedly send in data from the
same client.
:return: Parameter objects.
:rtype: tuple[server_tracking.parameters.UrlGenerator] | list[server_tracking.parameters.UrlGenerator]
"""
return self._misc_parameters
@misc_parameters.setter
def misc_parameters(self, value):
self._misc_parameters = value
self.update_misc_parameters()
|
mit
|
duanhjlt/gyp
|
test/mac/gyptest-app.py
|
43
|
3949
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are built correctly.
"""
import TestGyp
import TestMac
import os
import plistlib
import subprocess
import sys
def CheckFileXMLPropertyList(file):
output = subprocess.check_output(['file', file])
# The double space after XML is intentional.
if not 'XML document text' in output:
print 'File: Expected XML document text, got %s' % output
test.fail_test()
def ExpectEq(expected, actual):
if expected != actual:
print >>sys.stderr, 'Expected "%s", got "%s"' % (expected, actual)
test.fail_test()
def ls(path):
'''Returns a list of all files in a directory, relative to the directory.'''
result = []
for dirpath, _, files in os.walk(path):
for f in files:
result.append(os.path.join(dirpath, f)[len(path) + 1:])
return result
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir='app-bundle')
test.build('test.gyp', test.ALL, chdir='app-bundle')
# Binary
test.built_file_must_exist('Test App Gyp.app/Contents/MacOS/Test App Gyp',
chdir='app-bundle')
# Info.plist
info_plist = test.built_file_path('Test App Gyp.app/Contents/Info.plist',
chdir='app-bundle')
test.must_exist(info_plist)
test.must_contain(info_plist, 'com.google.Test-App-Gyp') # Variable expansion
test.must_not_contain(info_plist, '${MACOSX_DEPLOYMENT_TARGET}');
CheckFileXMLPropertyList(info_plist)
if test.format != 'make':
# TODO: Synthesized plist entries aren't hooked up in the make generator.
machine = subprocess.check_output(['sw_vers', '-buildVersion']).rstrip('\n')
plist = plistlib.readPlist(info_plist)
ExpectEq(machine, plist['BuildMachineOSBuild'])
# Prior to Xcode 5.0.0, SDKROOT (and thus DTSDKName) was only defined if
# set in the Xcode project file. Starting with that version, it is always
# defined.
expected = ''
if TestMac.Xcode.Version() >= '0500':
version = TestMac.Xcode.SDKVersion()
expected = 'macosx' + version
ExpectEq(expected, plist['DTSDKName'])
sdkbuild = TestMac.Xcode.SDKBuild()
if not sdkbuild:
# Above command doesn't work in Xcode 4.2.
sdkbuild = plist['BuildMachineOSBuild']
ExpectEq(sdkbuild, plist['DTSDKBuild'])
ExpectEq(TestMac.Xcode.Version(), plist['DTXcode'])
ExpectEq(TestMac.Xcode.Build(), plist['DTXcodeBuild'])
# Resources
strings_files = ['InfoPlist.strings', 'utf-16be.strings', 'utf-16le.strings']
for f in strings_files:
strings = test.built_file_path(
os.path.join('Test App Gyp.app/Contents/Resources/English.lproj', f),
chdir='app-bundle')
test.must_exist(strings)
# Xcodes writes UTF-16LE with BOM.
contents = open(strings, 'rb').read()
if not contents.startswith('\xff\xfe' + '/* Localized'.encode('utf-16le')):
test.fail_test()
test.built_file_must_exist(
'Test App Gyp.app/Contents/Resources/English.lproj/MainMenu.nib',
chdir='app-bundle')
# Packaging
test.built_file_must_exist('Test App Gyp.app/Contents/PkgInfo',
chdir='app-bundle')
test.built_file_must_match('Test App Gyp.app/Contents/PkgInfo', 'APPLause',
chdir='app-bundle')
# Check that no other files get added to the bundle.
if set(ls(test.built_file_path('Test App Gyp.app', chdir='app-bundle'))) != \
set(['Contents/MacOS/Test App Gyp',
'Contents/Info.plist',
'Contents/Resources/English.lproj/MainMenu.nib',
'Contents/PkgInfo',
] +
[os.path.join('Contents/Resources/English.lproj', f)
for f in strings_files]):
test.fail_test()
test.pass_test()
|
bsd-3-clause
|
job/exscript
|
src/Exscriptd/DBObject.py
|
6
|
2180
|
# Copyright (C) 2007-2010 Samuel Abels.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
class DBObject(object):
def __init__(self, obj = None):
# Since we override setattr below, we can't access our properties
# directly.
self.__dict__['__object__'] = obj
self.__dict__['__changed__'] = True
def __setattr__(self, name, value):
"""
Overwritten to proxy any calls to the associated object
(decorator pattern).
@type name: string
@param name: The attribute name.
@type value: string
@param value: The attribute value.
"""
if self.__dict__.get('__object__') is None:
self.__dict__[name] = value
if name in self.__dict__.keys():
self.__dict__[name] = value
else:
setattr(self.__object__, name, value)
def __getattr__(self, name):
"""
Overwritten to proxy any calls to the associated object
(decorator pattern).
@type name: string
@param name: The attribute name.
@rtype: object
@return: Whatever the protocol adapter returns.
"""
if self.__dict__.get('__object__') is None:
return self.__dict__[name]
if name in self.__dict__.keys():
return self.__dict__[name]
return getattr(self.__object__, name)
def touch(self):
self.__dict__['__changed__'] = True
def untouch(self):
self.__dict__['__changed__'] = False
def is_dirty(self):
return self.__dict__['__changed__']
|
gpl-2.0
|
akashsinghal/Speech-Memorization-App
|
Python_Backend/env/lib/python3.6/site-packages/pip/_vendor/lockfile/symlinklockfile.py
|
536
|
2616
|
from __future__ import absolute_import
import os
import time
from . import (LockBase, NotLocked, NotMyLock, LockTimeout,
AlreadyLocked)
class SymlinkLockFile(LockBase):
"""Lock access to a file using symlink(2)."""
def __init__(self, path, threaded=True, timeout=None):
# super(SymlinkLockFile).__init(...)
LockBase.__init__(self, path, threaded, timeout)
# split it back!
self.unique_name = os.path.split(self.unique_name)[1]
def acquire(self, timeout=None):
# Hopefully unnecessary for symlink.
# try:
# open(self.unique_name, "wb").close()
# except IOError:
# raise LockFailed("failed to create %s" % self.unique_name)
timeout = timeout if timeout is not None else self.timeout
end_time = time.time()
if timeout is not None and timeout > 0:
end_time += timeout
while True:
# Try and create a symbolic link to it.
try:
os.symlink(self.unique_name, self.lock_file)
except OSError:
# Link creation failed. Maybe we've double-locked?
if self.i_am_locking():
# Linked to out unique name. Proceed.
return
else:
# Otherwise the lock creation failed.
if timeout is not None and time.time() > end_time:
if timeout > 0:
raise LockTimeout("Timeout waiting to acquire"
" lock for %s" %
self.path)
else:
raise AlreadyLocked("%s is already locked" %
self.path)
time.sleep(timeout / 10 if timeout is not None else 0.1)
else:
# Link creation succeeded. We're good to go.
return
def release(self):
if not self.is_locked():
raise NotLocked("%s is not locked" % self.path)
elif not self.i_am_locking():
raise NotMyLock("%s is locked, but not by me" % self.path)
os.unlink(self.lock_file)
def is_locked(self):
return os.path.islink(self.lock_file)
def i_am_locking(self):
return (os.path.islink(self.lock_file)
and os.readlink(self.lock_file) == self.unique_name)
def break_lock(self):
if os.path.islink(self.lock_file): # exists && link
os.unlink(self.lock_file)
|
apache-2.0
|
NB-Dev/django-shop
|
shop/views/product.py
|
11
|
1177
|
# -*- coding: utf-8 -*-
from shop.models.productmodel import Product
from shop.views import (ShopListView, ShopDetailView)
class ProductListView(ShopListView):
"""
This view handles displaying the product catalogue to customers.
It filters out inactive products and shows only those that are active.
"""
generic_template = 'shop/product_list.html'
def get_queryset(self):
"""
Return all active products.
"""
return Product.objects.filter(active=True)
class ProductDetailView(ShopDetailView):
"""
This view handles displaying the right template for the subclasses of
Product.
It will look for a template at the normal (conventional) place, but will
fallback to using the default product template in case no template is
found for the subclass.
"""
model = Product # It must be the biggest ancestor of the inheritance tree.
generic_template = 'shop/product_detail.html'
def get_template_names(self):
ret = super(ProductDetailView, self).get_template_names()
if not self.generic_template in ret:
ret.append(self.generic_template)
return ret
|
bsd-3-clause
|
pablo2000/picochess
|
web/websockets_test.py
|
4
|
1302
|
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return """
<span id="now">loading<span>
<script type="text/javascript">
window.WebSocket=window.WebSocket || window.MozWebSocket || false;
if(!window.WebSocket){
alert("No WebSocket Support");
}else {
var ws=new WebSocket("ws://"+location.host+"/now");
var now_el=document.getElementById("now");
ws.onmessage=function(e){
now_el.innerHTML=e.data;
}
ws.onclose=function(){
now_el.innerHTML='closed';
}
}
</script>
"""
import time
import tornado.web
from tornado.websocket import WebSocketHandler
from tornado.ioloop import PeriodicCallback,IOLoop
import tornado.wsgi
class NowHandler(WebSocketHandler):
clients = set()
@staticmethod
def echo_now():
for client in NowHandler.clients:
client.write_message(time.ctime())
def open(self):
NowHandler.clients.add(self)
def on_close(self):
NowHandler.clients.remove(self)
wsgi_app=tornado.wsgi.WSGIContainer(app)
application=tornado.web.Application([
(r'/now',NowHandler),
(r'.*',tornado.web.FallbackHandler, {'fallback': wsgi_app})
])
PeriodicCallback(NowHandler.echo_now, 1000).start()
application.listen(5000)
IOLoop.instance().start()
|
gpl-3.0
|
Chatmetaleux/MissionPlanner
|
Scripts/example4 wp.py
|
61
|
1193
|
import sys
import math
import clr
import time
import System
from System import Byte
clr.AddReference("MissionPlanner")
import MissionPlanner
clr.AddReference("MissionPlanner.Utilities") # includes the Utilities class
from MissionPlanner.Utilities import Locationwp
clr.AddReference("MAVLink") # includes the Utilities class
import MAVLink
idmavcmd = MAVLink.MAV_CMD.WAYPOINT
id = int(idmavcmd)
home = Locationwp().Set(-34.9805,117.8518,0, id)
to = Locationwp()
Locationwp.id.SetValue(to, int(MAVLink.MAV_CMD.TAKEOFF))
Locationwp.p1.SetValue(to, 15)
Locationwp.alt.SetValue(to, 50)
wp1 = Locationwp().Set(-35,117.8,50, id)
wp2 = Locationwp().Set(-35,117.89,50, id)
wp3 = Locationwp().Set(-35,117.85,20, id)
print "set wp total"
MAV.setWPTotal(5)
print "upload home - reset on arm"
MAV.setWP(home,0,MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT);
print "upload to"
MAV.setWP(to,1,MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT);
print "upload wp1"
MAV.setWP(wp1,2,MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT);
print "upload wp2"
MAV.setWP(wp2,3,MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT);
print "upload wp3"
MAV.setWP(wp3,4,MAVLink.MAV_FRAME.GLOBAL_RELATIVE_ALT);
print "final ack"
MAV.setWPACK();
print "done"
|
gpl-3.0
|
coderbone/SickRage-alt
|
lib/unidecode/x000.py
|
17
|
3041
|
data = (
# Code points u+007f and below are equivalent to ASCII and are handled by a
# special case in the code. Hence they are not present in this table.
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', # 0x80
'', # 0x81
'', # 0x82
'', # 0x83
'', # 0x84
'', # 0x85
'', # 0x86
'', # 0x87
'', # 0x88
'', # 0x89
'', # 0x8a
'', # 0x8b
'', # 0x8c
'', # 0x8d
'', # 0x8e
'', # 0x8f
'', # 0x90
'', # 0x91
'', # 0x92
'', # 0x93
'', # 0x94
'', # 0x95
'', # 0x96
'', # 0x97
'', # 0x98
'', # 0x99
'', # 0x9a
'', # 0x9b
'', # 0x9c
'', # 0x9d
'', # 0x9e
'', # 0x9f
' ', # 0xa0
'!', # 0xa1
'C/', # 0xa2
# Not "GBP" - Pound Sign is used for more than just British Pounds.
'PS', # 0xa3
'$?', # 0xa4
'Y=', # 0xa5
'|', # 0xa6
'SS', # 0xa7
'"', # 0xa8
'(c)', # 0xa9
'a', # 0xaa
'<<', # 0xab
'!', # 0xac
'', # 0xad
'(r)', # 0xae
'-', # 0xaf
'deg', # 0xb0
'+-', # 0xb1
# These might be combined with other superscript digits (u+2070 - u+2079)
'2', # 0xb2
'3', # 0xb3
'\'', # 0xb4
'u', # 0xb5
'P', # 0xb6
'*', # 0xb7
',', # 0xb8
'1', # 0xb9
'o', # 0xba
'>>', # 0xbb
' 1/4 ', # 0xbc
' 1/2 ', # 0xbd
' 3/4 ', # 0xbe
'?', # 0xbf
'A', # 0xc0
'A', # 0xc1
'A', # 0xc2
'A', # 0xc3
# Not "AE" - used in languages other than German
'A', # 0xc4
'A', # 0xc5
'AE', # 0xc6
'C', # 0xc7
'E', # 0xc8
'E', # 0xc9
'E', # 0xca
'E', # 0xcb
'I', # 0xcc
'I', # 0xcd
'I', # 0xce
'I', # 0xcf
'D', # 0xd0
'N', # 0xd1
'O', # 0xd2
'O', # 0xd3
'O', # 0xd4
'O', # 0xd5
# Not "OE" - used in languages other than German
'O', # 0xd6
'x', # 0xd7
'O', # 0xd8
'U', # 0xd9
'U', # 0xda
'U', # 0xdb
# Not "UE" - used in languages other than German
'U', # 0xdc
'Y', # 0xdd
'Th', # 0xde
'ss', # 0xdf
'a', # 0xe0
'a', # 0xe1
'a', # 0xe2
'a', # 0xe3
# Not "ae" - used in languages other than German
'a', # 0xe4
'a', # 0xe5
'ae', # 0xe6
'c', # 0xe7
'e', # 0xe8
'e', # 0xe9
'e', # 0xea
'e', # 0xeb
'i', # 0xec
'i', # 0xed
'i', # 0xee
'i', # 0xef
'd', # 0xf0
'n', # 0xf1
'o', # 0xf2
'o', # 0xf3
'o', # 0xf4
'o', # 0xf5
# Not "oe" - used in languages other than German
'o', # 0xf6
'/', # 0xf7
'o', # 0xf8
'u', # 0xf9
'u', # 0xfa
'u', # 0xfb
# Not "ue" - used in languages other than German
'u', # 0xfc
'y', # 0xfd
'th', # 0xfe
'y', # 0xff
)
|
gpl-3.0
|
paweljasinski/ironpython3
|
Src/StdLib/Lib/test/test_wait4.py
|
111
|
1140
|
"""This test checks for correct wait4() behavior.
"""
import os
import time
import sys
from test.fork_wait import ForkWait
from test.support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
def wait_impl(self, cpid):
option = os.WNOHANG
if sys.platform.startswith('aix'):
# Issue #11185: wait4 is broken on AIX and will always return 0
# with WNOHANG.
option = 0
for i in range(10):
# wait4() shouldn't hang, but some of the buildbots seem to hang
# in the forking tests. This is an attempt to fix the problem.
spid, status, rusage = os.wait4(cpid, option)
if spid == cpid:
break
time.sleep(1.0)
self.assertEqual(spid, cpid)
self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
self.assertTrue(rusage)
def test_main():
run_unittest(Wait4Test)
reap_children()
if __name__ == "__main__":
test_main()
|
apache-2.0
|
freakboy3742/django
|
tests/many_to_one_null/tests.py
|
19
|
6085
|
from django.test import TestCase
from .models import Article, Car, Driver, Reporter
class ManyToOneNullTests(TestCase):
@classmethod
def setUpTestData(cls):
# Create a Reporter.
cls.r = Reporter(name='John Smith')
cls.r.save()
# Create an Article.
cls.a = Article(headline='First', reporter=cls.r)
cls.a.save()
# Create an Article via the Reporter object.
cls.a2 = cls.r.article_set.create(headline='Second')
# Create an Article with no Reporter by passing "reporter=None".
cls.a3 = Article(headline='Third', reporter=None)
cls.a3.save()
# Create another article and reporter
cls.r2 = Reporter(name='Paul Jones')
cls.r2.save()
cls.a4 = cls.r2.article_set.create(headline='Fourth')
def test_get_related(self):
self.assertEqual(self.a.reporter.id, self.r.id)
# Article objects have access to their related Reporter objects.
r = self.a.reporter
self.assertEqual(r.id, self.r.id)
def test_created_via_related_set(self):
self.assertEqual(self.a2.reporter.id, self.r.id)
def test_related_set(self):
# Reporter objects have access to their related Article objects.
self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2])
self.assertSequenceEqual(self.r.article_set.filter(headline__startswith='Fir'), [self.a])
self.assertEqual(self.r.article_set.count(), 2)
def test_created_without_related(self):
self.assertIsNone(self.a3.reporter)
# Need to reget a3 to refresh the cache
a3 = Article.objects.get(pk=self.a3.pk)
with self.assertRaises(AttributeError):
getattr(a3.reporter, 'id')
# Accessing an article's 'reporter' attribute returns None
# if the reporter is set to None.
self.assertIsNone(a3.reporter)
# To retrieve the articles with no reporters set, use "reporter__isnull=True".
self.assertSequenceEqual(Article.objects.filter(reporter__isnull=True), [self.a3])
# We can achieve the same thing by filtering for the case where the
# reporter is None.
self.assertSequenceEqual(Article.objects.filter(reporter=None), [self.a3])
# Set the reporter for the Third article
self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2])
self.r.article_set.add(a3)
self.assertSequenceEqual(
self.r.article_set.all(),
[self.a, self.a2, self.a3],
)
# Remove an article from the set, and check that it was removed.
self.r.article_set.remove(a3)
self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2])
self.assertSequenceEqual(Article.objects.filter(reporter__isnull=True), [self.a3])
def test_remove_from_wrong_set(self):
self.assertSequenceEqual(self.r2.article_set.all(), [self.a4])
# Try to remove a4 from a set it does not belong to
with self.assertRaises(Reporter.DoesNotExist):
self.r.article_set.remove(self.a4)
self.assertSequenceEqual(self.r2.article_set.all(), [self.a4])
def test_set(self):
# Use manager.set() to allocate ForeignKey. Null is legal, so existing
# members of the set that are not in the assignment set are set to null.
self.r2.article_set.set([self.a2, self.a3])
self.assertSequenceEqual(self.r2.article_set.all(), [self.a2, self.a3])
# Use manager.set(clear=True)
self.r2.article_set.set([self.a3, self.a4], clear=True)
self.assertSequenceEqual(self.r2.article_set.all(), [self.a4, self.a3])
# Clear the rest of the set
self.r2.article_set.set([])
self.assertSequenceEqual(self.r2.article_set.all(), [])
self.assertSequenceEqual(
Article.objects.filter(reporter__isnull=True),
[self.a4, self.a2, self.a3],
)
def test_set_clear_non_bulk(self):
# 2 queries for clear(), 1 for add(), and 1 to select objects.
with self.assertNumQueries(4):
self.r.article_set.set([self.a], bulk=False, clear=True)
def test_assign_clear_related_set(self):
# Use descriptor assignment to allocate ForeignKey. Null is legal, so
# existing members of the set that are not in the assignment set are
# set to null.
self.r2.article_set.set([self.a2, self.a3])
self.assertSequenceEqual(self.r2.article_set.all(), [self.a2, self.a3])
# Clear the rest of the set
self.r.article_set.clear()
self.assertSequenceEqual(self.r.article_set.all(), [])
self.assertSequenceEqual(
Article.objects.filter(reporter__isnull=True),
[self.a, self.a4],
)
def test_assign_with_queryset(self):
# Querysets used in reverse FK assignments are pre-evaluated
# so their value isn't affected by the clearing operation in
# RelatedManager.set() (#19816).
self.r2.article_set.set([self.a2, self.a3])
qs = self.r2.article_set.filter(headline="Second")
self.r2.article_set.set(qs)
self.assertEqual(1, self.r2.article_set.count())
self.assertEqual(1, qs.count())
def test_add_efficiency(self):
r = Reporter.objects.create()
articles = []
for _ in range(3):
articles.append(Article.objects.create())
with self.assertNumQueries(1):
r.article_set.add(*articles)
self.assertEqual(r.article_set.count(), 3)
def test_clear_efficiency(self):
r = Reporter.objects.create()
for _ in range(3):
r.article_set.create()
with self.assertNumQueries(1):
r.article_set.clear()
self.assertEqual(r.article_set.count(), 0)
def test_related_null_to_field(self):
c1 = Car.objects.create()
d1 = Driver.objects.create()
self.assertIs(d1.car, None)
with self.assertNumQueries(0):
self.assertEqual(list(c1.drivers.all()), [])
|
bsd-3-clause
|
kkuunnddaannkk/vispy
|
examples/demo/gloo/game_of_life.py
|
18
|
5765
|
# -*- coding: utf-8 -*-
# vispy: gallery 200
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
# Author: Nicolas P .Rougier
# Date: 06/03/2014
# Abstract: GPU computing using the framebuffer
# Keywords: framebuffer, GPU computing, cellular automata
# -----------------------------------------------------------------------------
"""
Conway game of life.
"""
import numpy as np
from vispy.gloo import (Program, FrameBuffer, RenderBuffer,
clear, set_viewport, set_state)
from vispy import app
render_vertex = """
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
"""
render_fragment = """
uniform int pingpong;
uniform sampler2D texture;
varying vec2 v_texcoord;
void main()
{
float v;
v = texture2D(texture, v_texcoord)[pingpong];
gl_FragColor = vec4(1.0-v, 1.0-v, 1.0-v, 1.0);
}
"""
compute_vertex = """
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
"""
compute_fragment = """
uniform int pingpong;
uniform sampler2D texture;
uniform float dx; // horizontal distance between texels
uniform float dy; // vertical distance between texels
varying vec2 v_texcoord;
void main(void)
{
vec2 p = v_texcoord;
float old_state, new_state, count;
old_state = texture2D(texture, p)[pingpong];
count = texture2D(texture, p + vec2(-dx,-dy))[pingpong]
+ texture2D(texture, p + vec2( dx,-dy))[pingpong]
+ texture2D(texture, p + vec2(-dx, dy))[pingpong]
+ texture2D(texture, p + vec2( dx, dy))[pingpong]
+ texture2D(texture, p + vec2(-dx, 0.0))[pingpong]
+ texture2D(texture, p + vec2( dx, 0.0))[pingpong]
+ texture2D(texture, p + vec2(0.0,-dy))[pingpong]
+ texture2D(texture, p + vec2(0.0, dy))[pingpong];
new_state = old_state;
if( old_state > 0.5 ) {
// Any live cell with fewer than two live neighbours dies
// as if caused by under-population.
if( count < 1.5 )
new_state = 0.0;
// Any live cell with two or three live neighbours
// lives on to the next generation.
// Any live cell with more than three live neighbours dies,
// as if by overcrowding.
else if( count > 3.5 )
new_state = 0.0;
} else {
// Any dead cell with exactly three live neighbours becomes
// a live cell, as if by reproduction.
if( (count > 2.5) && (count < 3.5) )
new_state = 1.0;
}
if( pingpong == 0) {
gl_FragColor[1] = new_state;
gl_FragColor[0] = old_state;
} else {
gl_FragColor[1] = old_state;
gl_FragColor[0] = new_state;
}
}
"""
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title="Conway game of life",
size=(512, 512), keys='interactive')
# Build programs
# --------------
self.comp_size = self.size
size = self.comp_size + (4,)
Z = np.zeros(size, dtype=np.float32)
Z[...] = np.random.randint(0, 2, size)
Z[:256, :256, :] = 0
gun = """
........................O...........
......................O.O...........
............OO......OO............OO
...........O...O....OO............OO
OO........O.....O...OO..............
OO........O...O.OO....O.O...........
..........O.....O.......O...........
...........O...O....................
............OO......................"""
x, y = 0, 0
for i in range(len(gun)):
if gun[i] == '\n':
y += 1
x = 0
elif gun[i] == 'O':
Z[y, x] = 1
x += 1
self.pingpong = 1
self.compute = Program(compute_vertex, compute_fragment, 4)
self.compute["texture"] = Z
self.compute["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
self.compute["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
self.compute['dx'] = 1.0 / size[1]
self.compute['dy'] = 1.0 / size[0]
self.compute['pingpong'] = self.pingpong
self.render = Program(render_vertex, render_fragment, 4)
self.render["position"] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
self.render["texcoord"] = [(0, 0), (0, 1), (1, 0), (1, 1)]
self.render["texture"] = self.compute["texture"]
self.render['pingpong'] = self.pingpong
self.fbo = FrameBuffer(self.compute["texture"],
RenderBuffer(self.comp_size))
set_state(depth_test=False, clear_color='black')
self._timer = app.Timer('auto', connect=self.update, start=True)
self.show()
def on_draw(self, event):
with self.fbo:
set_viewport(0, 0, *self.comp_size)
self.compute["texture"].interpolation = 'nearest'
self.compute.draw('triangle_strip')
clear()
set_viewport(0, 0, *self.physical_size)
self.render["texture"].interpolation = 'linear'
self.render.draw('triangle_strip')
self.pingpong = 1 - self.pingpong
self.compute["pingpong"] = self.pingpong
self.render["pingpong"] = self.pingpong
if __name__ == '__main__':
canvas = Canvas()
app.run()
|
bsd-3-clause
|
zubair-arbi/edx-platform
|
lms/djangoapps/instructor/views/registration_codes.py
|
86
|
5504
|
"""
E-commerce Tab Instructor Dashboard Query Registration Code Status.
"""
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_GET, require_POST
from instructor.enrollment import get_email_params, send_mail_to_student
from django.utils.translation import ugettext as _
from courseware.courses import get_course_by_id
from instructor.views.api import require_level
from student.models import CourseEnrollment
from util.json_request import JsonResponse
from shoppingcart.models import CourseRegistrationCode, RegistrationCodeRedemption
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from django.views.decorators.cache import cache_control
import logging
log = logging.getLogger(__name__)
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_GET
def look_up_registration_code(request, course_id): # pylint: disable=unused-argument
"""
Look for the registration_code in the database.
and check if it is still valid, allowed to redeem or not.
"""
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
code = request.GET.get('registration_code')
course = get_course_by_id(course_key, depth=0)
try:
registration_code = CourseRegistrationCode.objects.get(code=code)
except CourseRegistrationCode.DoesNotExist:
return JsonResponse({
'is_registration_code_exists': False,
'is_registration_code_valid': False,
'is_registration_code_redeemed': False,
'message': _('The enrollment code ({code}) was not found for the {course_name} course.').format(
code=code, course_name=course.display_name
)
}, status=400) # status code 200: OK by default
reg_code_already_redeemed = RegistrationCodeRedemption.is_registration_code_redeemed(code)
registration_code_detail_url = reverse('registration_code_details', kwargs={'course_id': unicode(course_id)})
return JsonResponse({
'is_registration_code_exists': True,
'is_registration_code_valid': registration_code.is_valid,
'is_registration_code_redeemed': reg_code_already_redeemed,
'registration_code_detail_url': registration_code_detail_url
}) # status code 200: OK by default
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_level('staff')
@require_POST
def registration_code_details(request, course_id):
"""
Post handler to mark the registration code as
1) valid
2) invalid
3) Unredeem.
"""
course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
code = request.POST.get('registration_code')
action_type = request.POST.get('action_type')
course = get_course_by_id(course_key, depth=0)
action_type_messages = {
'invalidate_registration_code': _('This enrollment code has been canceled. It can no longer be used.'),
'unredeem_registration_code': _('This enrollment code has been marked as unused.'),
'validate_registration_code': _('The enrollment code has been restored.')
}
try:
registration_code = CourseRegistrationCode.objects.get(code=code)
except CourseRegistrationCode.DoesNotExist:
return JsonResponse({
'message': _('The enrollment code ({code}) was not found for the {course_name} course.').format(
code=code, course_name=course.display_name
)}, status=400)
if action_type == 'invalidate_registration_code':
registration_code.is_valid = False
registration_code.save()
if RegistrationCodeRedemption.is_registration_code_redeemed(code):
code_redemption = RegistrationCodeRedemption.get_registration_code_redemption(code, course_key)
delete_redemption_entry(request, code_redemption, course_key)
if action_type == 'validate_registration_code':
registration_code.is_valid = True
registration_code.save()
if action_type == 'unredeem_registration_code':
code_redemption = RegistrationCodeRedemption.get_registration_code_redemption(code, course_key)
if code_redemption is None:
return JsonResponse({
'message': _('The redemption does not exist against enrollment code ({code}).').format(
code=code)}, status=400)
delete_redemption_entry(request, code_redemption, course_key)
return JsonResponse({'message': action_type_messages[action_type]})
def delete_redemption_entry(request, code_redemption, course_key):
"""
delete the redemption entry from the table and
unenroll the user who used the registration code
for the enrollment and send him/her the unenrollment email.
"""
user = code_redemption.redeemed_by
email_address = code_redemption.redeemed_by.email
full_name = code_redemption.redeemed_by.profile.name
CourseEnrollment.unenroll(user, course_key, skip_refund=True)
course = get_course_by_id(course_key, depth=0)
email_params = get_email_params(course, True, secure=request.is_secure())
email_params['message'] = 'enrolled_unenroll'
email_params['email_address'] = email_address
email_params['full_name'] = full_name
send_mail_to_student(email_address, email_params)
# remove the redemption entry from the database.
log.info('deleting redemption entry (%s) from the database.', code_redemption.id)
code_redemption.delete()
|
agpl-3.0
|
encukou/samba
|
source4/heimdal/lib/wind/UnicodeData.py
|
82
|
2167
|
#!/usr/local/bin/python
# -*- coding: iso-8859-1 -*-
# $Id$
# Copyright (c) 2004 Kungliga Tekniska Högskolan
# (Royal Institute of Technology, Stockholm, Sweden).
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the Institute nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
import re
import string
def read(filename):
"""return a dict of unicode characters"""
ud = open(filename, 'r')
ret = {}
while True:
l = ud.readline()
if not l:
break
l = re.sub('#.*$', '', l)
if l == "\n":
continue
f = l.split(';')
key = int(f[0], 0x10)
if key in ret:
raise Exception('Duplicate key in UnicodeData')
ret[key] = f[1:]
ud.close()
return ret
|
gpl-3.0
|
codepantry/django
|
django/db/backends/oracle/introspection.py
|
517
|
11463
|
import cx_Oracle
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
from django.utils.encoding import force_text
class DatabaseIntrospection(BaseDatabaseIntrospection):
# Maps type objects to Django Field types.
data_types_reverse = {
cx_Oracle.BLOB: 'BinaryField',
cx_Oracle.CLOB: 'TextField',
cx_Oracle.DATETIME: 'DateField',
cx_Oracle.FIXED_CHAR: 'CharField',
cx_Oracle.NCLOB: 'TextField',
cx_Oracle.NUMBER: 'DecimalField',
cx_Oracle.STRING: 'CharField',
cx_Oracle.TIMESTAMP: 'DateTimeField',
}
try:
data_types_reverse[cx_Oracle.NATIVE_FLOAT] = 'FloatField'
except AttributeError:
pass
try:
data_types_reverse[cx_Oracle.UNICODE] = 'CharField'
except AttributeError:
pass
cache_bust_counter = 1
def get_field_type(self, data_type, description):
# If it's a NUMBER with scale == 0, consider it an IntegerField
if data_type == cx_Oracle.NUMBER:
precision, scale = description[4:6]
if scale == 0:
if precision > 11:
return 'BigIntegerField'
elif precision == 1:
return 'BooleanField'
else:
return 'IntegerField'
elif scale == -127:
return 'FloatField'
return super(DatabaseIntrospection, self).get_field_type(data_type, description)
def get_table_list(self, cursor):
"""
Returns a list of table and view names in the current database.
"""
cursor.execute("SELECT TABLE_NAME, 't' FROM USER_TABLES UNION ALL "
"SELECT VIEW_NAME, 'v' FROM USER_VIEWS")
return [TableInfo(row[0].lower(), row[1]) for row in cursor.fetchall()]
def get_table_description(self, cursor, table_name):
"Returns a description of the table, with the DB-API cursor.description interface."
self.cache_bust_counter += 1
cursor.execute("SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format(
self.connection.ops.quote_name(table_name),
self.cache_bust_counter))
description = []
for desc in cursor.description:
name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3
name = name % {} # cx_Oracle, for some reason, doubles percent signs.
description.append(FieldInfo(*(name.lower(),) + desc[1:]))
return description
def table_name_converter(self, name):
"Table name comparison is case insensitive under Oracle"
return name.lower()
def _name_to_index(self, cursor, table_name):
"""
Returns a dictionary of {field_name: field_index} for the given table.
Indexes are 0-based.
"""
return {d[0]: i for i, d in enumerate(self.get_table_description(cursor, table_name))}
def get_relations(self, cursor, table_name):
"""
Returns a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
"""
table_name = table_name.upper()
cursor.execute("""
SELECT ta.column_name, tb.table_name, tb.column_name
FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb,
user_tab_cols ta, user_tab_cols tb
WHERE user_constraints.table_name = %s AND
ta.table_name = user_constraints.table_name AND
ta.column_name = ca.column_name AND
ca.table_name = ta.table_name AND
user_constraints.constraint_name = ca.constraint_name AND
user_constraints.r_constraint_name = cb.constraint_name AND
cb.table_name = tb.table_name AND
cb.column_name = tb.column_name AND
ca.position = cb.position""", [table_name])
relations = {}
for row in cursor.fetchall():
relations[row[0].lower()] = (row[2].lower(), row[1].lower())
return relations
def get_key_columns(self, cursor, table_name):
cursor.execute("""
SELECT ccol.column_name, rcol.table_name AS referenced_table, rcol.column_name AS referenced_column
FROM user_constraints c
JOIN user_cons_columns ccol
ON ccol.constraint_name = c.constraint_name
JOIN user_cons_columns rcol
ON rcol.constraint_name = c.r_constraint_name
WHERE c.table_name = %s AND c.constraint_type = 'R'""", [table_name.upper()])
return [tuple(cell.lower() for cell in row)
for row in cursor.fetchall()]
def get_indexes(self, cursor, table_name):
sql = """
SELECT LOWER(uic1.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1 ELSE 0
END AS is_primary_key,
CASE user_indexes.uniqueness
WHEN 'UNIQUE' THEN 1 ELSE 0
END AS is_unique
FROM user_constraints, user_indexes, user_ind_columns uic1
WHERE user_constraints.constraint_type (+) = 'P'
AND user_constraints.index_name (+) = uic1.index_name
AND user_indexes.uniqueness (+) = 'UNIQUE'
AND user_indexes.index_name (+) = uic1.index_name
AND uic1.table_name = UPPER(%s)
AND uic1.column_position = 1
AND NOT EXISTS (
SELECT 1
FROM user_ind_columns uic2
WHERE uic2.index_name = uic1.index_name
AND uic2.column_position = 2
)
"""
cursor.execute(sql, [table_name])
indexes = {}
for row in cursor.fetchall():
indexes[row[0]] = {'primary_key': bool(row[1]),
'unique': bool(row[2])}
return indexes
def get_constraints(self, cursor, table_name):
"""
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
"""
constraints = {}
# Loop over the constraints, getting PKs and uniques
cursor.execute("""
SELECT
user_constraints.constraint_name,
LOWER(cols.column_name) AS column_name,
CASE user_constraints.constraint_type
WHEN 'P' THEN 1
ELSE 0
END AS is_primary_key,
CASE user_indexes.uniqueness
WHEN 'UNIQUE' THEN 1
ELSE 0
END AS is_unique,
CASE user_constraints.constraint_type
WHEN 'C' THEN 1
ELSE 0
END AS is_check_constraint
FROM
user_constraints
INNER JOIN
user_indexes ON user_indexes.index_name = user_constraints.index_name
LEFT OUTER JOIN
user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name
WHERE
(
user_constraints.constraint_type = 'P' OR
user_constraints.constraint_type = 'U'
)
AND user_constraints.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column, pk, unique, check in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": pk,
"unique": unique,
"foreign_key": None,
"check": check,
"index": True, # All P and U come with index, see inner join above
}
# Record the details
constraints[constraint]['columns'].append(column)
# Check constraints
cursor.execute("""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name
FROM
user_constraints cons
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'C' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": None,
"check": True,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Foreign key constraints
cursor.execute("""
SELECT
cons.constraint_name,
LOWER(cols.column_name) AS column_name,
LOWER(rcons.table_name),
LOWER(rcols.column_name)
FROM
user_constraints cons
INNER JOIN
user_constraints rcons ON cons.r_constraint_name = rcons.constraint_name
INNER JOIN
user_cons_columns rcols ON rcols.constraint_name = rcons.constraint_name
LEFT OUTER JOIN
user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE
cons.constraint_type = 'R' AND
cons.table_name = UPPER(%s)
ORDER BY cols.position
""", [table_name])
for constraint, column, other_table, other_column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": (other_table, other_column),
"check": False,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get indexes
cursor.execute("""
SELECT
index_name,
LOWER(column_name)
FROM
user_ind_columns cols
WHERE
table_name = UPPER(%s) AND
NOT EXISTS (
SELECT 1
FROM user_constraints cons
WHERE cols.index_name = cons.index_name
)
ORDER BY cols.column_position
""", [table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": None,
"check": False,
"index": True,
}
# Record the details
constraints[constraint]['columns'].append(column)
return constraints
|
bsd-3-clause
|
KorlaMarch/Ant-bot
|
mapgen/amstan/cavemap.py
|
4
|
1869
|
#!/usr/bin/env python
import random
from symmetricmap import *
class Cavemap(SymmetricMap):
def __init__(self, **kwargs):
kwargs["defaultterrain"]=WATER
SymmetricMap.__init__(self, **kwargs)
def add_water_randomly(self,percent=0.49):
for point in self.size.upto():
self[point]=LAND
if random.random() < percent:
self[point]=WATER
def random_walk(self,start,cover=0.5):
total_squares=self.size.x*self.size.y
squares_water=0
symmetric_locations=len(self.symmetry_vector(Point(0,0)))
location=start
end_reached=False
while squares_water<total_squares*cover:
if self[location]==WATER:
self[location]=LAND
squares_water+=symmetric_locations
location+=random.choice(directions.values())
def smooth(self, times=1):
"""Apply a cellular automaton to smoothen the walls"""
for time in xrange(times):
oldmap=self.copy()
for point in self.size.upto():
neighbour_water=[d for d in diag_directions.values() if oldmap[point+d]==WATER]
if len(neighbour_water)<4:
self[point]=LAND
if len(neighbour_water)>4:
self[point]=WATER
def generate(self,**kwargs):
self.random_walk(list(self.hills())[0])
try:
self.smooth(kwargs["smooth"])
except KeyError:
self.smooth(4)
if __name__=="__main__":
#random.seed(6)
size=Point(60,60)
playerone=size.random_upto()*(0.5/3)+size*(0.5/3)
map=Cavemap(size=size,num_players=4,symmetry="translational")
map.add_hill(playerone)
map.generate()
print map
|
mit
|
fkorotkov/pants
|
contrib/android/src/python/pants/contrib/android/targets/android_target.py
|
14
|
2242
|
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.backend.jvm.targets.jvm_target import JvmTarget
from pants.base.exceptions import TargetDefinitionException
from pants.util.memo import memoized_property
from pants.contrib.android.android_manifest_parser import AndroidManifestParser
class AndroidTarget(JvmTarget):
"""A base class for all Android targets."""
def __init__(self,
address=None,
# TODO (mateor) add support for minSDk
# most recent build_tools_version should be defined elsewhere
build_tools_version="19.1.0",
manifest=None,
**kwargs):
"""
:param build_tools_version: API for the Build Tools (separate from SDK version).
Defaults to the latest full release.
:param manifest: path/to/file of 'AndroidManifest.xml' (required name). Paths are relative
to the BUILD file's directory.
"""
super(AndroidTarget, self).__init__(address=address, **kwargs)
self.add_labels('android')
# TODO(pl): These attributes should live in the payload
self.build_tools_version = build_tools_version
self._spec_path = address.spec_path
self._manifest_file = manifest
@memoized_property
def manifest(self):
"""Return an AndroidManifest object made from a manifest by AndroidManifestParser."""
# If there was no 'manifest' field in the BUILD file, try to find one with the default value.
if self._manifest_file is None:
self._manifest_file = 'AndroidManifest.xml'
manifest_path = os.path.join(self._spec_path, self._manifest_file)
if not os.path.isfile(manifest_path):
raise TargetDefinitionException(self, "There is no AndroidManifest.xml at path {0}. Please "
"declare a 'manifest' field with its relative "
"path.".format(manifest_path))
return AndroidManifestParser.parse_manifest(manifest_path)
|
apache-2.0
|
laperry1/android_external_chromium_org
|
third_party/libxml/src/check-relaxng-test-suite2.py
|
343
|
10578
|
#!/usr/bin/python
import sys
import time
import os
import string
import StringIO
sys.path.insert(0, "python")
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
debug = 0
quiet = 1
#
# the testsuite description
#
CONF=os.path.join(os.path.dirname(__file__), "test/relaxng/testsuite.xml")
LOG="check-relaxng-test-suite2.log"
log = open(LOG, "w")
nb_schemas_tests = 0
nb_schemas_success = 0
nb_schemas_failed = 0
nb_instances_tests = 0
nb_instances_success = 0
nb_instances_failed = 0
libxml2.lineNumbersDefault(1)
#
# Resolver callback
#
resources = {}
def resolver(URL, ID, ctxt):
global resources
if resources.has_key(URL):
return(StringIO.StringIO(resources[URL]))
log.write("Resolver failure: asked %s\n" % (URL))
log.write("resources: %s\n" % (resources))
return None
#
# Load the previous results
#
#results = {}
#previous = {}
#
#try:
# res = libxml2.parseFile(RES)
#except:
# log.write("Could not parse %s" % (RES))
#
# handle a valid instance
#
def handle_valid(node, schema):
global log
global nb_instances_success
global nb_instances_failed
instance = node.prop("dtd")
if instance == None:
instance = ""
child = node.children
while child != None:
if child.type != 'text':
instance = instance + child.serialize()
child = child.next
# mem = libxml2.debugMemory(1);
try:
doc = libxml2.parseDoc(instance)
except:
doc = None
if doc == None:
log.write("\nFailed to parse correct instance:\n-----\n")
log.write(instance)
log.write("\n-----\n")
nb_instances_failed = nb_instances_failed + 1
return
if debug:
print "instance line %d" % (node.lineNo())
try:
ctxt = schema.relaxNGNewValidCtxt()
ret = doc.relaxNGValidateDoc(ctxt)
del ctxt
except:
ret = -1
doc.freeDoc()
# if mem != libxml2.debugMemory(1):
# print "validating instance %d line %d leaks" % (
# nb_instances_tests, node.lineNo())
if ret != 0:
log.write("\nFailed to validate correct instance:\n-----\n")
log.write(instance)
log.write("\n-----\n")
nb_instances_failed = nb_instances_failed + 1
else:
nb_instances_success = nb_instances_success + 1
#
# handle an invalid instance
#
def handle_invalid(node, schema):
global log
global nb_instances_success
global nb_instances_failed
instance = node.prop("dtd")
if instance == None:
instance = ""
child = node.children
while child != None:
if child.type != 'text':
instance = instance + child.serialize()
child = child.next
# mem = libxml2.debugMemory(1);
try:
doc = libxml2.parseDoc(instance)
except:
doc = None
if doc == None:
log.write("\nStrange: failed to parse incorrect instance:\n-----\n")
log.write(instance)
log.write("\n-----\n")
return
if debug:
print "instance line %d" % (node.lineNo())
try:
ctxt = schema.relaxNGNewValidCtxt()
ret = doc.relaxNGValidateDoc(ctxt)
del ctxt
except:
ret = -1
doc.freeDoc()
# mem2 = libxml2.debugMemory(1)
# if mem != mem2:
# print "validating instance %d line %d leaks %d bytes" % (
# nb_instances_tests, node.lineNo(), mem2 - mem)
if ret == 0:
log.write("\nFailed to detect validation problem in instance:\n-----\n")
log.write(instance)
log.write("\n-----\n")
nb_instances_failed = nb_instances_failed + 1
else:
nb_instances_success = nb_instances_success + 1
#
# handle an incorrect test
#
def handle_correct(node):
global log
global nb_schemas_success
global nb_schemas_failed
schema = ""
child = node.children
while child != None:
if child.type != 'text':
schema = schema + child.serialize()
child = child.next
try:
rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema))
rngs = rngp.relaxNGParse()
except:
rngs = None
if rngs == None:
log.write("\nFailed to compile correct schema:\n-----\n")
log.write(schema)
log.write("\n-----\n")
nb_schemas_failed = nb_schemas_failed + 1
else:
nb_schemas_success = nb_schemas_success + 1
return rngs
def handle_incorrect(node):
global log
global nb_schemas_success
global nb_schemas_failed
schema = ""
child = node.children
while child != None:
if child.type != 'text':
schema = schema + child.serialize()
child = child.next
try:
rngp = libxml2.relaxNGNewMemParserCtxt(schema, len(schema))
rngs = rngp.relaxNGParse()
except:
rngs = None
if rngs != None:
log.write("\nFailed to detect schema error in:\n-----\n")
log.write(schema)
log.write("\n-----\n")
nb_schemas_failed = nb_schemas_failed + 1
else:
# log.write("\nSuccess detecting schema error in:\n-----\n")
# log.write(schema)
# log.write("\n-----\n")
nb_schemas_success = nb_schemas_success + 1
return None
#
# resource handling: keep a dictionary of URL->string mappings
#
def handle_resource(node, dir):
global resources
try:
name = node.prop('name')
except:
name = None
if name == None or name == '':
log.write("resource has no name")
return;
if dir != None:
# name = libxml2.buildURI(name, dir)
name = dir + '/' + name
res = ""
child = node.children
while child != None:
if child.type != 'text':
res = res + child.serialize()
child = child.next
resources[name] = res
#
# dir handling: pseudo directory resources
#
def handle_dir(node, dir):
try:
name = node.prop('name')
except:
name = None
if name == None or name == '':
log.write("resource has no name")
return;
if dir != None:
# name = libxml2.buildURI(name, dir)
name = dir + '/' + name
dirs = node.xpathEval('dir')
for dir in dirs:
handle_dir(dir, name)
res = node.xpathEval('resource')
for r in res:
handle_resource(r, name)
#
# handle a testCase element
#
def handle_testCase(node):
global nb_schemas_tests
global nb_instances_tests
global resources
sections = node.xpathEval('string(section)')
log.write("\n ======== test %d line %d section %s ==========\n" % (
nb_schemas_tests, node.lineNo(), sections))
resources = {}
if debug:
print "test %d line %d" % (nb_schemas_tests, node.lineNo())
dirs = node.xpathEval('dir')
for dir in dirs:
handle_dir(dir, None)
res = node.xpathEval('resource')
for r in res:
handle_resource(r, None)
tsts = node.xpathEval('incorrect')
if tsts != []:
if len(tsts) != 1:
print "warning test line %d has more than one <incorrect> example" %(node.lineNo())
schema = handle_incorrect(tsts[0])
else:
tsts = node.xpathEval('correct')
if tsts != []:
if len(tsts) != 1:
print "warning test line %d has more than one <correct> example"% (node.lineNo())
schema = handle_correct(tsts[0])
else:
print "warning <testCase> line %d has no <correct> nor <incorrect> child" % (node.lineNo())
nb_schemas_tests = nb_schemas_tests + 1;
valids = node.xpathEval('valid')
invalids = node.xpathEval('invalid')
nb_instances_tests = nb_instances_tests + len(valids) + len(invalids)
if schema != None:
for valid in valids:
handle_valid(valid, schema)
for invalid in invalids:
handle_invalid(invalid, schema)
#
# handle a testSuite element
#
def handle_testSuite(node, level = 0):
global nb_schemas_tests, nb_schemas_success, nb_schemas_failed
global nb_instances_tests, nb_instances_success, nb_instances_failed
if level >= 1:
old_schemas_tests = nb_schemas_tests
old_schemas_success = nb_schemas_success
old_schemas_failed = nb_schemas_failed
old_instances_tests = nb_instances_tests
old_instances_success = nb_instances_success
old_instances_failed = nb_instances_failed
docs = node.xpathEval('documentation')
authors = node.xpathEval('author')
if docs != []:
msg = ""
for doc in docs:
msg = msg + doc.content + " "
if authors != []:
msg = msg + "written by "
for author in authors:
msg = msg + author.content + " "
if quiet == 0:
print msg
sections = node.xpathEval('section')
if sections != [] and level <= 0:
msg = ""
for section in sections:
msg = msg + section.content + " "
if quiet == 0:
print "Tests for section %s" % (msg)
for test in node.xpathEval('testCase'):
handle_testCase(test)
for test in node.xpathEval('testSuite'):
handle_testSuite(test, level + 1)
if level >= 1 and sections != []:
msg = ""
for section in sections:
msg = msg + section.content + " "
print "Result of tests for section %s" % (msg)
if nb_schemas_tests != old_schemas_tests:
print "found %d test schemas: %d success %d failures" % (
nb_schemas_tests - old_schemas_tests,
nb_schemas_success - old_schemas_success,
nb_schemas_failed - old_schemas_failed)
if nb_instances_tests != old_instances_tests:
print "found %d test instances: %d success %d failures" % (
nb_instances_tests - old_instances_tests,
nb_instances_success - old_instances_success,
nb_instances_failed - old_instances_failed)
#
# Parse the conf file
#
libxml2.substituteEntitiesDefault(1);
testsuite = libxml2.parseFile(CONF)
#
# Error and warnng callbacks
#
def callback(ctx, str):
global log
log.write("%s%s" % (ctx, str))
libxml2.registerErrorHandler(callback, "")
libxml2.setEntityLoader(resolver)
root = testsuite.getRootElement()
if root.name != 'testSuite':
print "%s doesn't start with a testSuite element, aborting" % (CONF)
sys.exit(1)
if quiet == 0:
print "Running Relax NG testsuite"
handle_testSuite(root)
if quiet == 0:
print "\nTOTAL:\n"
if quiet == 0 or nb_schemas_failed != 0:
print "found %d test schemas: %d success %d failures" % (
nb_schemas_tests, nb_schemas_success, nb_schemas_failed)
if quiet == 0 or nb_instances_failed != 0:
print "found %d test instances: %d success %d failures" % (
nb_instances_tests, nb_instances_success, nb_instances_failed)
testsuite.freeDoc()
# Memory debug specific
libxml2.relaxNGCleanupTypes()
libxml2.cleanupParser()
if libxml2.debugMemory(1) == 0:
if quiet == 0:
print "OK"
else:
print "Memory leak %d bytes" % (libxml2.debugMemory(1))
libxml2.dumpMemory()
|
bsd-3-clause
|
proxysh/Safejumper-for-Mac
|
buildmac/Resources/env/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/contrib/appengine.py
|
360
|
7937
|
from __future__ import absolute_import
import logging
import os
import warnings
from ..exceptions import (
HTTPError,
HTTPWarning,
MaxRetryError,
ProtocolError,
TimeoutError,
SSLError
)
from ..packages.six import BytesIO
from ..request import RequestMethods
from ..response import HTTPResponse
from ..util.timeout import Timeout
from ..util.retry import Retry
try:
from google.appengine.api import urlfetch
except ImportError:
urlfetch = None
log = logging.getLogger(__name__)
class AppEnginePlatformWarning(HTTPWarning):
pass
class AppEnginePlatformError(HTTPError):
pass
class AppEngineManager(RequestMethods):
"""
Connection manager for Google App Engine sandbox applications.
This manager uses the URLFetch service directly instead of using the
emulated httplib, and is subject to URLFetch limitations as described in
the App Engine documentation here:
https://cloud.google.com/appengine/docs/python/urlfetch
Notably it will raise an AppEnginePlatformError if:
* URLFetch is not available.
* If you attempt to use this on GAEv2 (Managed VMs), as full socket
support is available.
* If a request size is more than 10 megabytes.
* If a response size is more than 32 megabtyes.
* If you use an unsupported request method such as OPTIONS.
Beyond those cases, it will raise normal urllib3 errors.
"""
def __init__(self, headers=None, retries=None, validate_certificate=True):
if not urlfetch:
raise AppEnginePlatformError(
"URLFetch is not available in this environment.")
if is_prod_appengine_mvms():
raise AppEnginePlatformError(
"Use normal urllib3.PoolManager instead of AppEngineManager"
"on Managed VMs, as using URLFetch is not necessary in "
"this environment.")
warnings.warn(
"urllib3 is using URLFetch on Google App Engine sandbox instead "
"of sockets. To use sockets directly instead of URLFetch see "
"https://urllib3.readthedocs.io/en/latest/contrib.html.",
AppEnginePlatformWarning)
RequestMethods.__init__(self, headers)
self.validate_certificate = validate_certificate
self.retries = retries or Retry.DEFAULT
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Return False to re-raise any potential exceptions
return False
def urlopen(self, method, url, body=None, headers=None,
retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,
**response_kw):
retries = self._get_retries(retries, redirect)
try:
response = urlfetch.fetch(
url,
payload=body,
method=method,
headers=headers or {},
allow_truncated=False,
follow_redirects=(
redirect and
retries.redirect != 0 and
retries.total),
deadline=self._get_absolute_timeout(timeout),
validate_certificate=self.validate_certificate,
)
except urlfetch.DeadlineExceededError as e:
raise TimeoutError(self, e)
except urlfetch.InvalidURLError as e:
if 'too large' in str(e):
raise AppEnginePlatformError(
"URLFetch request too large, URLFetch only "
"supports requests up to 10mb in size.", e)
raise ProtocolError(e)
except urlfetch.DownloadError as e:
if 'Too many redirects' in str(e):
raise MaxRetryError(self, url, reason=e)
raise ProtocolError(e)
except urlfetch.ResponseTooLargeError as e:
raise AppEnginePlatformError(
"URLFetch response too large, URLFetch only supports"
"responses up to 32mb in size.", e)
except urlfetch.SSLCertificateError as e:
raise SSLError(e)
except urlfetch.InvalidMethodError as e:
raise AppEnginePlatformError(
"URLFetch does not support method: %s" % method, e)
http_response = self._urlfetch_response_to_http_response(
response, **response_kw)
# Check for redirect response
if (http_response.get_redirect_location() and
retries.raise_on_redirect and redirect):
raise MaxRetryError(self, url, "too many redirects")
# Check if we should retry the HTTP response.
if retries.is_forced_retry(method, status_code=http_response.status):
retries = retries.increment(
method, url, response=http_response, _pool=self)
log.info("Forced retry: %s", url)
retries.sleep()
return self.urlopen(
method, url,
body=body, headers=headers,
retries=retries, redirect=redirect,
timeout=timeout, **response_kw)
return http_response
def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):
if is_prod_appengine():
# Production GAE handles deflate encoding automatically, but does
# not remove the encoding header.
content_encoding = urlfetch_resp.headers.get('content-encoding')
if content_encoding == 'deflate':
del urlfetch_resp.headers['content-encoding']
transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')
# We have a full response's content,
# so let's make sure we don't report ourselves as chunked data.
if transfer_encoding == 'chunked':
encodings = transfer_encoding.split(",")
encodings.remove('chunked')
urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)
return HTTPResponse(
# In order for decoding to work, we must present the content as
# a file-like object.
body=BytesIO(urlfetch_resp.content),
headers=urlfetch_resp.headers,
status=urlfetch_resp.status_code,
**response_kw
)
def _get_absolute_timeout(self, timeout):
if timeout is Timeout.DEFAULT_TIMEOUT:
return 5 # 5s is the default timeout for URLFetch.
if isinstance(timeout, Timeout):
if timeout._read is not timeout._connect:
warnings.warn(
"URLFetch does not support granular timeout settings, "
"reverting to total timeout.", AppEnginePlatformWarning)
return timeout.total
return timeout
def _get_retries(self, retries, redirect):
if not isinstance(retries, Retry):
retries = Retry.from_int(
retries, redirect=redirect, default=self.retries)
if retries.connect or retries.read or retries.redirect:
warnings.warn(
"URLFetch only supports total retries and does not "
"recognize connect, read, or redirect retry parameters.",
AppEnginePlatformWarning)
return retries
def is_appengine():
return (is_local_appengine() or
is_prod_appengine() or
is_prod_appengine_mvms())
def is_appengine_sandbox():
return is_appengine() and not is_prod_appengine_mvms()
def is_local_appengine():
return ('APPENGINE_RUNTIME' in os.environ and
'Development/' in os.environ['SERVER_SOFTWARE'])
def is_prod_appengine():
return ('APPENGINE_RUNTIME' in os.environ and
'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and
not is_prod_appengine_mvms())
def is_prod_appengine_mvms():
return os.environ.get('GAE_VM', False) == 'true'
|
gpl-2.0
|
NiclasEriksen/py-towerwars
|
src/numpy/lib/_datasource.py
|
148
|
21266
|
"""A file interface for handling local and remote data files.
The goal of datasource is to abstract some of the file system operations
when dealing with data files so the researcher doesn't have to know all the
low-level details. Through datasource, a researcher can obtain and use a
file with one function call, regardless of location of the file.
DataSource is meant to augment standard python libraries, not replace them.
It should work seemlessly with standard file IO operations and the os
module.
DataSource files can originate locally or remotely:
- local files : '/home/guido/src/local/data.txt'
- URLs (http, ftp, ...) : 'http://www.scipy.org/not/real/data.txt'
DataSource files can also be compressed or uncompressed. Currently only
gzip and bz2 are supported.
Example::
>>> # Create a DataSource, use os.curdir (default) for local storage.
>>> ds = datasource.DataSource()
>>>
>>> # Open a remote file.
>>> # DataSource downloads the file, stores it locally in:
>>> # './www.google.com/index.html'
>>> # opens the file and returns a file object.
>>> fp = ds.open('http://www.google.com/index.html')
>>>
>>> # Use the file as you normally would
>>> fp.read()
>>> fp.close()
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import shutil
_open = open
# Using a class instead of a module-level dictionary
# to reduce the inital 'import numpy' overhead by
# deferring the import of bz2 and gzip until needed
# TODO: .zip support, .tar support?
class _FileOpeners(object):
"""
Container for different methods to open (un-)compressed files.
`_FileOpeners` contains a dictionary that holds one method for each
supported file format. Attribute lookup is implemented in such a way
that an instance of `_FileOpeners` itself can be indexed with the keys
of that dictionary. Currently uncompressed files as well as files
compressed with ``gzip`` or ``bz2`` compression are supported.
Notes
-----
`_file_openers`, an instance of `_FileOpeners`, is made available for
use in the `_datasource` module.
Examples
--------
>>> np.lib._datasource._file_openers.keys()
[None, '.bz2', '.gz']
>>> np.lib._datasource._file_openers['.gz'] is gzip.open
True
"""
def __init__(self):
self._loaded = False
self._file_openers = {None: open}
def _load(self):
if self._loaded:
return
try:
import bz2
self._file_openers[".bz2"] = bz2.BZ2File
except ImportError:
pass
try:
import gzip
self._file_openers[".gz"] = gzip.open
except ImportError:
pass
self._loaded = True
def keys(self):
"""
Return the keys of currently supported file openers.
Parameters
----------
None
Returns
-------
keys : list
The keys are None for uncompressed files and the file extension
strings (i.e. ``'.gz'``, ``'.bz2'``) for supported compression
methods.
"""
self._load()
return list(self._file_openers.keys())
def __getitem__(self, key):
self._load()
return self._file_openers[key]
_file_openers = _FileOpeners()
def open(path, mode='r', destpath=os.curdir):
"""
Open `path` with `mode` and return the file object.
If ``path`` is an URL, it will be downloaded, stored in the
`DataSource` `destpath` directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open.
mode : str, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing, 'a' to
append. Available modes depend on the type of object specified by
path. Default is 'r'.
destpath : str, optional
Path to the directory where the source file gets downloaded to for
use. If `destpath` is None, a temporary directory will be created.
The default path is the current directory.
Returns
-------
out : file object
The opened file.
Notes
-----
This is a convenience function that instantiates a `DataSource` and
returns the file object from ``DataSource.open(path)``.
"""
ds = DataSource(destpath)
return ds.open(path, mode)
class DataSource (object):
"""
DataSource(destpath='.')
A generic data source file (file, http, ftp, ...).
DataSources can be local files or remote files/URLs. The files may
also be compressed or uncompressed. DataSource hides some of the
low-level details of downloading the file, allowing you to simply pass
in a valid file path (or URL) and obtain a file object.
Parameters
----------
destpath : str or None, optional
Path to the directory where the source file gets downloaded to for
use. If `destpath` is None, a temporary directory will be created.
The default path is the current directory.
Notes
-----
URLs require a scheme string (``http://``) to be used, without it they
will fail::
>>> repos = DataSource()
>>> repos.exists('www.google.com/index.html')
False
>>> repos.exists('http://www.google.com/index.html')
True
Temporary directories are deleted when the DataSource is deleted.
Examples
--------
::
>>> ds = DataSource('/home/guido')
>>> urlname = 'http://www.google.com/index.html'
>>> gfile = ds.open('http://www.google.com/index.html') # remote file
>>> ds.abspath(urlname)
'/home/guido/www.google.com/site/index.html'
>>> ds = DataSource(None) # use with temporary file
>>> ds.open('/home/guido/foobar.txt')
<open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430>
>>> ds.abspath('/home/guido/foobar.txt')
'/tmp/tmpy4pgsP/home/guido/foobar.txt'
"""
def __init__(self, destpath=os.curdir):
"""Create a DataSource with a local path at destpath."""
if destpath:
self._destpath = os.path.abspath(destpath)
self._istmpdest = False
else:
import tempfile # deferring import to improve startup time
self._destpath = tempfile.mkdtemp()
self._istmpdest = True
def __del__(self):
# Remove temp directories
if self._istmpdest:
shutil.rmtree(self._destpath)
def _iszip(self, filename):
"""Test if the filename is a zip file by looking at the file extension.
"""
fname, ext = os.path.splitext(filename)
return ext in _file_openers.keys()
def _iswritemode(self, mode):
"""Test if the given mode will open a file for writing."""
# Currently only used to test the bz2 files.
_writemodes = ("w", "+")
for c in mode:
if c in _writemodes:
return True
return False
def _splitzipext(self, filename):
"""Split zip extension from filename and return filename.
*Returns*:
base, zip_ext : {tuple}
"""
if self._iszip(filename):
return os.path.splitext(filename)
else:
return filename, None
def _possible_names(self, filename):
"""Return a tuple containing compressed filename variations."""
names = [filename]
if not self._iszip(filename):
for zipext in _file_openers.keys():
if zipext:
names.append(filename+zipext)
return names
def _isurl(self, path):
"""Test if path is a net location. Tests the scheme and netloc."""
# We do this here to reduce the 'import numpy' initial import time.
if sys.version_info[0] >= 3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
# BUG : URLs require a scheme string ('http://') to be used.
# www.google.com will fail.
# Should we prepend the scheme for those that don't have it and
# test that also? Similar to the way we append .gz and test for
# for compressed versions of files.
scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
return bool(scheme and netloc)
def _cache(self, path):
"""Cache the file specified by path.
Creates a copy of the file in the datasource cache.
"""
# We import these here because importing urllib2 is slow and
# a significant fraction of numpy's total import time.
if sys.version_info[0] >= 3:
from urllib.request import urlopen
from urllib.error import URLError
else:
from urllib2 import urlopen
from urllib2 import URLError
upath = self.abspath(path)
# ensure directory exists
if not os.path.exists(os.path.dirname(upath)):
os.makedirs(os.path.dirname(upath))
# TODO: Doesn't handle compressed files!
if self._isurl(path):
try:
openedurl = urlopen(path)
f = _open(upath, 'wb')
try:
shutil.copyfileobj(openedurl, f)
finally:
f.close()
openedurl.close()
except URLError:
raise URLError("URL not found: %s" % path)
else:
shutil.copyfile(path, upath)
return upath
def _findfile(self, path):
"""Searches for ``path`` and returns full path if found.
If path is an URL, _findfile will cache a local copy and return the
path to the cached file. If path is a local file, _findfile will
return a path to that local file.
The search will include possible compressed versions of the file
and return the first occurence found.
"""
# Build list of possible local file paths
if not self._isurl(path):
# Valid local paths
filelist = self._possible_names(path)
# Paths in self._destpath
filelist += self._possible_names(self.abspath(path))
else:
# Cached URLs in self._destpath
filelist = self._possible_names(self.abspath(path))
# Remote URLs
filelist = filelist + self._possible_names(path)
for name in filelist:
if self.exists(name):
if self._isurl(name):
name = self._cache(name)
return name
return None
def abspath(self, path):
"""
Return absolute path of file in the DataSource directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----------
path : str
Can be a local file or a remote URL.
Returns
-------
out : str
Complete path, including the `DataSource` destination directory.
Notes
-----
The functionality is based on `os.path.abspath`.
"""
# We do this here to reduce the 'import numpy' initial import time.
if sys.version_info[0] >= 3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
# TODO: This should be more robust. Handles case where path includes
# the destpath, but not other sub-paths. Failing case:
# path = /home/guido/datafile.txt
# destpath = /home/alex/
# upath = self.abspath(path)
# upath == '/home/alex/home/guido/datafile.txt'
# handle case where path includes self._destpath
splitpath = path.split(self._destpath, 2)
if len(splitpath) > 1:
path = splitpath[1]
scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
netloc = self._sanitize_relative_path(netloc)
upath = self._sanitize_relative_path(upath)
return os.path.join(self._destpath, netloc, upath)
def _sanitize_relative_path(self, path):
"""Return a sanitised relative path for which
os.path.abspath(os.path.join(base, path)).startswith(base)
"""
last = None
path = os.path.normpath(path)
while path != last:
last = path
# Note: os.path.join treats '/' as os.sep on Windows
path = path.lstrip(os.sep).lstrip('/')
path = path.lstrip(os.pardir).lstrip('..')
drive, path = os.path.splitdrive(path) # for Windows
return path
def exists(self, path):
"""
Test if path exists.
Test if `path` exists as (and in this order):
- a local file.
- a remote URL that has been downloaded and stored locally in the
`DataSource` directory.
- a remote URL that has not been downloaded, but is valid and
accessible.
Parameters
----------
path : str
Can be a local file or a remote URL.
Returns
-------
out : bool
True if `path` exists.
Notes
-----
When `path` is an URL, `exists` will return True if it's either
stored locally in the `DataSource` directory, or is a valid remote
URL. `DataSource` does not discriminate between the two, the file
is accessible if it exists in either location.
"""
# We import this here because importing urllib2 is slow and
# a significant fraction of numpy's total import time.
if sys.version_info[0] >= 3:
from urllib.request import urlopen
from urllib.error import URLError
else:
from urllib2 import urlopen
from urllib2 import URLError
# Test local path
if os.path.exists(path):
return True
# Test cached url
upath = self.abspath(path)
if os.path.exists(upath):
return True
# Test remote url
if self._isurl(path):
try:
netfile = urlopen(path)
netfile.close()
del(netfile)
return True
except URLError:
return False
return False
def open(self, path, mode='r'):
"""
Open and return file-like object.
If `path` is an URL, it will be downloaded, stored in the
`DataSource` directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open.
mode : {'r', 'w', 'a'}, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing,
'a' to append. Available modes depend on the type of object
specified by `path`. Default is 'r'.
Returns
-------
out : file object
File object.
"""
# TODO: There is no support for opening a file for writing which
# doesn't exist yet (creating a file). Should there be?
# TODO: Add a ``subdir`` parameter for specifying the subdirectory
# used to store URLs in self._destpath.
if self._isurl(path) and self._iswritemode(mode):
raise ValueError("URLs are not writeable")
# NOTE: _findfile will fail on a new file opened for writing.
found = self._findfile(path)
if found:
_fname, ext = self._splitzipext(found)
if ext == 'bz2':
mode.replace("+", "")
return _file_openers[ext](found, mode=mode)
else:
raise IOError("%s not found." % path)
class Repository (DataSource):
"""
Repository(baseurl, destpath='.')
A data repository where multiple DataSource's share a base
URL/directory.
`Repository` extends `DataSource` by prepending a base URL (or
directory) to all the files it handles. Use `Repository` when you will
be working with multiple files from one base URL. Initialize
`Repository` with the base URL, then refer to each file by its filename
only.
Parameters
----------
baseurl : str
Path to the local directory or remote location that contains the
data files.
destpath : str or None, optional
Path to the directory where the source file gets downloaded to for
use. If `destpath` is None, a temporary directory will be created.
The default path is the current directory.
Examples
--------
To analyze all files in the repository, do something like this
(note: this is not self-contained code)::
>>> repos = np.lib._datasource.Repository('/home/user/data/dir/')
>>> for filename in filelist:
... fp = repos.open(filename)
... fp.analyze()
... fp.close()
Similarly you could use a URL for a repository::
>>> repos = np.lib._datasource.Repository('http://www.xyz.edu/data')
"""
def __init__(self, baseurl, destpath=os.curdir):
"""Create a Repository with a shared url or directory of baseurl."""
DataSource.__init__(self, destpath=destpath)
self._baseurl = baseurl
def __del__(self):
DataSource.__del__(self)
def _fullpath(self, path):
"""Return complete path for path. Prepends baseurl if necessary."""
splitpath = path.split(self._baseurl, 2)
if len(splitpath) == 1:
result = os.path.join(self._baseurl, path)
else:
result = path # path contains baseurl already
return result
def _findfile(self, path):
"""Extend DataSource method to prepend baseurl to ``path``."""
return DataSource._findfile(self, self._fullpath(path))
def abspath(self, path):
"""
Return absolute path of file in the Repository directory.
If `path` is an URL, then `abspath` will return either the location
the file exists locally or the location it would exist when opened
using the `open` method.
Parameters
----------
path : str
Can be a local file or a remote URL. This may, but does not
have to, include the `baseurl` with which the `Repository` was
initialized.
Returns
-------
out : str
Complete path, including the `DataSource` destination directory.
"""
return DataSource.abspath(self, self._fullpath(path))
def exists(self, path):
"""
Test if path exists prepending Repository base URL to path.
Test if `path` exists as (and in this order):
- a local file.
- a remote URL that has been downloaded and stored locally in the
`DataSource` directory.
- a remote URL that has not been downloaded, but is valid and
accessible.
Parameters
----------
path : str
Can be a local file or a remote URL. This may, but does not
have to, include the `baseurl` with which the `Repository` was
initialized.
Returns
-------
out : bool
True if `path` exists.
Notes
-----
When `path` is an URL, `exists` will return True if it's either
stored locally in the `DataSource` directory, or is a valid remote
URL. `DataSource` does not discriminate between the two, the file
is accessible if it exists in either location.
"""
return DataSource.exists(self, self._fullpath(path))
def open(self, path, mode='r'):
"""
Open and return file-like object prepending Repository base URL.
If `path` is an URL, it will be downloaded, stored in the
DataSource directory and opened from there.
Parameters
----------
path : str
Local file path or URL to open. This may, but does not have to,
include the `baseurl` with which the `Repository` was
initialized.
mode : {'r', 'w', 'a'}, optional
Mode to open `path`. Mode 'r' for reading, 'w' for writing,
'a' to append. Available modes depend on the type of object
specified by `path`. Default is 'r'.
Returns
-------
out : file object
File object.
"""
return DataSource.open(self, self._fullpath(path), mode)
def listdir(self):
"""
List files in the source Repository.
Returns
-------
files : list of str
List of file names (not containing a directory part).
Notes
-----
Does not currently work for remote repositories.
"""
if self._isurl(self._baseurl):
raise NotImplementedError(
"Directory listing of URLs, not supported yet.")
else:
return os.listdir(self._baseurl)
|
cc0-1.0
|
malaterre/ITK
|
Modules/ThirdParty/pygccxml/src/pygccxml/parser/project_reader.py
|
13
|
23391
|
# Copyright 2014-2017 Insight Software Consortium.
# Copyright 2004-2009 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
import os
import timeit
import pygccxml.declarations
from . import source_reader
from . import declarations_cache
from . import declarations_joiner
from .. import utils
class COMPILATION_MODE(object):
ALL_AT_ONCE = 'all at once'
FILE_BY_FILE = 'file by file'
class file_configuration_t(object):
"""
source code location configuration.
The class instance uses "variant" interface to represent the following
data:
1) path to a C++ source file
2) path to GCC-XML generated XML file
3) path to a C++ source file and path to GCC-XML generated file
In this case, if XML file does not exists, it will be created. Next
time you will ask to parse the source file, the XML file will be used
instead.
Small tip: you can setup your makefile to delete XML files every time,
the relevant source file was changed.
4) Python string, that contains valid C++ code
There are few functions, that will help you to construct
:class:`file_configuration_t` object:
* :func:`create_source_fc`
* :func:`create_gccxml_fc`
* :func:`create_cached_source_fc`
* :func:`create_text_fc`
"""
class CONTENT_TYPE(object):
STANDARD_SOURCE_FILE = 'standard source file'
CACHED_SOURCE_FILE = 'cached source file'
GCCXML_GENERATED_FILE = 'gccxml generated file'
TEXT = 'text'
def __init__(
self,
data,
start_with_declarations=None,
content_type=CONTENT_TYPE.STANDARD_SOURCE_FILE,
cached_source_file=None):
object.__init__(self)
self.__data = data
if not start_with_declarations:
start_with_declarations = []
self.__start_with_declarations = start_with_declarations
self.__content_type = content_type
self.__cached_source_file = cached_source_file
if not self.__cached_source_file \
and self.__content_type == self.CONTENT_TYPE.CACHED_SOURCE_FILE:
self.__cached_source_file = self.__data + '.xml'
@property
def data(self):
return self.__data
@property
def start_with_declarations(self):
return self.__start_with_declarations
@property
def content_type(self):
return self.__content_type
@property
def cached_source_file(self):
return self.__cached_source_file
def create_text_fc(text):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain Python string, that contains valid C++ code
:param text: C++ code
:type text: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=text,
content_type=file_configuration_t.CONTENT_TYPE.TEXT)
def create_source_fc(header):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to C++ source file
:param header: path to C++ source file
:type header: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=header,
content_type=file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE)
def create_gccxml_fc(xml_file):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to GCC-XML generated XML file.
:param xml_file: path to GCC-XML generated XML file
:type xml_file: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=xml_file,
content_type=file_configuration_t.CONTENT_TYPE.GCCXML_GENERATED_FILE)
def create_cached_source_fc(header, cached_source_file):
"""
Creates :class:`parser.file_configuration_t` instance, configured to
contain path to GCC-XML generated XML file and C++ source file. If XML file
does not exists, it will be created and used for parsing. If XML file
exists, it will be used for parsing.
:param header: path to C++ source file
:type header: str
:param cached_source_file: path to GCC-XML generated XML file
:type cached_source_file: str
:rtype: :class:`parser.file_configuration_t`
"""
return file_configuration_t(
data=header,
cached_source_file=cached_source_file,
content_type=file_configuration_t.CONTENT_TYPE.CACHED_SOURCE_FILE)
class project_reader_t(object):
"""parses header files and returns the contained declarations"""
def __init__(self, config, cache=None, decl_factory=None):
"""
:param config: GCCXML configuration
:type config: :class:xml_generator_configuration_t
:param cache: declaration cache, by default a cache functionality will
not be used
:type cache: :class:`cache_base_t` instance or `str`
:param decl_factory: declaration factory
:type decl_factory: :class:`decl_factory_t`
"""
self.__config = config
self.__dcache = None
if isinstance(cache, declarations_cache.cache_base_t):
self.__dcache = cache
elif utils.is_str(cache):
self.__dcache = declarations_cache.file_cache_t(cache)
else:
self.__dcache = declarations_cache.dummy_cache_t()
self.__decl_factory = decl_factory
if not decl_factory:
self.__decl_factory = pygccxml.declarations.decl_factory_t()
self.logger = utils.loggers.cxx_parser
self.__xml_generator_from_xml_file = None
@property
def xml_generator_from_xml_file(self):
"""
Configuration object containing information about the xml generator
read from the xml file.
Returns:
utils.xml_generators: configuration object
"""
return self.__xml_generator_from_xml_file
@staticmethod
def get_os_file_names(files):
"""
returns file names
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
"""
fnames = []
for f in files:
if utils.is_str(f):
fnames.append(f)
elif isinstance(f, file_configuration_t):
if f.content_type in (
file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE,
file_configuration_t.CONTENT_TYPE.CACHED_SOURCE_FILE):
fnames.append(f.data)
else:
pass
return fnames
def read_files(
self,
files,
compilation_mode=COMPILATION_MODE.FILE_BY_FILE):
"""
parses a set of files
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
:param compilation_mode: determines whether the files are parsed
individually or as one single chunk
:type compilation_mode: :class:`COMPILATION_MODE`
:rtype: [:class:`declaration_t`]
"""
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE \
and len(files) == len(self.get_os_file_names(files)):
return self.__parse_all_at_once(files)
else:
if compilation_mode == COMPILATION_MODE.ALL_AT_ONCE:
msg = ''.join([
"Unable to parse files using ALL_AT_ONCE mode. ",
"There is some file configuration that is not file. ",
"pygccxml.parser.project_reader_t switches to ",
"FILE_BY_FILE mode."])
self.logger.warning(msg)
return self.__parse_file_by_file(files)
def __parse_file_by_file(self, files):
namespaces = []
config = self.__config.clone()
self.logger.debug("Reading project files: file by file")
for prj_file in files:
if isinstance(prj_file, file_configuration_t):
del config.start_with_declarations[:]
config.start_with_declarations.extend(
prj_file.start_with_declarations)
header = prj_file.data
content_type = prj_file.content_type
else:
config = self.__config
header = prj_file
content_type = \
file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE
reader = source_reader.source_reader_t(
config,
self.__dcache,
self.__decl_factory)
if content_type == \
file_configuration_t.CONTENT_TYPE.STANDARD_SOURCE_FILE:
self.logger.info('Parsing source file "%s" ... ', header)
decls = reader.read_file(header)
elif content_type == \
file_configuration_t.CONTENT_TYPE.GCCXML_GENERATED_FILE:
self.logger.info('Parsing xml file "%s" ... ', header)
decls = reader.read_xml_file(header)
elif content_type == \
file_configuration_t.CONTENT_TYPE.CACHED_SOURCE_FILE:
# TODO: raise error when header file does not exist
if not os.path.exists(prj_file.cached_source_file):
dir_ = os.path.split(prj_file.cached_source_file)[0]
if dir_ and not os.path.exists(dir_):
os.makedirs(dir_)
self.logger.info(
'Creating xml file "%s" from source file "%s" ... ',
prj_file.cached_source_file, header)
reader.create_xml_file(header, prj_file.cached_source_file)
self.logger.info(
'Parsing xml file "%s" ... ',
prj_file.cached_source_file)
decls = reader.read_xml_file(prj_file.cached_source_file)
else:
decls = reader.read_string(header)
self.__xml_generator_from_xml_file = \
reader.xml_generator_from_xml_file
namespaces.append(decls)
self.logger.debug("Flushing cache... ")
start_time = timeit.default_timer()
self.__dcache.flush()
self.logger.debug(
"Cache has been flushed in %.1f secs",
(timeit.default_timer() - start_time))
answer = []
self.logger.debug("Joining namespaces ...")
for file_nss in namespaces:
answer = self._join_top_namespaces(answer, file_nss)
self.logger.debug("Joining declarations ...")
for ns in answer:
if isinstance(ns, pygccxml.declarations.namespace_t):
declarations_joiner.join_declarations(ns)
leaved_classes = self._join_class_hierarchy(answer)
types = self.__declarated_types(answer)
self.logger.debug("Relinking declared types ...")
self._relink_declarated_types(leaved_classes, types)
declarations_joiner.bind_aliases(
pygccxml.declarations.make_flatten(answer))
return answer
def __parse_all_at_once(self, files):
config = self.__config.clone()
self.logger.debug("Reading project files: all at once")
header_content = []
for header in files:
if isinstance(header, file_configuration_t):
del config.start_with_declarations[:]
config.start_with_declarations.extend(
header.start_with_declarations)
header_content.append(
'#include "%s" %s' %
(header.data, os.linesep))
else:
header_content.append(
'#include "%s" %s' %
(header, os.linesep))
return self.read_string(''.join(header_content))
def read_string(self, content):
"""Parse a string containing C/C++ source code.
:param content: C/C++ source code.
:type content: str
:rtype: Declarations
"""
reader = source_reader.source_reader_t(
self.__config,
None,
self.__decl_factory)
decls = reader.read_string(content)
self.__xml_generator_from_xml_file = reader.xml_generator_from_xml_file
return decls
def read_xml(self, file_configuration):
"""parses C++ code, defined on the file_configurations and returns
GCCXML generated file content"""
xml_file_path = None
delete_xml_file = True
fc = file_configuration
reader = source_reader.source_reader_t(
self.__config,
None,
self.__decl_factory)
try:
if fc.content_type == fc.CONTENT_TYPE.STANDARD_SOURCE_FILE:
self.logger.info('Parsing source file "%s" ... ', fc.data)
xml_file_path = reader.create_xml_file(fc.data)
elif fc.content_type == \
file_configuration_t.CONTENT_TYPE.GCCXML_GENERATED_FILE:
self.logger.info('Parsing xml file "%s" ... ', fc.data)
xml_file_path = fc.data
delete_xml_file = False
elif fc.content_type == fc.CONTENT_TYPE.CACHED_SOURCE_FILE:
# TODO: raise error when header file does not exist
if not os.path.exists(fc.cached_source_file):
dir_ = os.path.split(fc.cached_source_file)[0]
if dir_ and not os.path.exists(dir_):
os.makedirs(dir_)
self.logger.info(
'Creating xml file "%s" from source file "%s" ... ',
fc.cached_source_file, fc.data)
xml_file_path = reader.create_xml_file(
fc.data,
fc.cached_source_file)
else:
xml_file_path = fc.cached_source_file
else:
xml_file_path = reader.create_xml_file_from_string(fc.data)
with open(xml_file_path, "r") as xml_file:
xml = xml_file.read()
utils.remove_file_no_raise(xml_file_path, self.__config)
self.__xml_generator_from_xml_file = \
reader.xml_generator_from_xml_file
return xml
finally:
if xml_file_path and delete_xml_file:
utils.remove_file_no_raise(xml_file_path, self.__config)
@staticmethod
def _join_top_namespaces(main_ns_list, other_ns_list):
answer = main_ns_list[:]
for other_ns in other_ns_list:
main_ns = pygccxml.declarations.find_declaration(
answer,
decl_type=pygccxml.declarations.namespace_t,
name=other_ns._name,
recursive=False)
if main_ns:
main_ns.take_parenting(other_ns)
else:
answer.append(other_ns)
return answer
@staticmethod
def _create_key(decl):
return (
decl.location.as_tuple(),
tuple(pygccxml.declarations.declaration_path(decl)))
def _join_class_hierarchy(self, namespaces):
classes = [
decl for decl in pygccxml.declarations.make_flatten(namespaces)
if isinstance(decl, pygccxml.declarations.class_t)]
leaved_classes = {}
# selecting classes to leave
for class_ in classes:
key = self._create_key(class_)
if key not in leaved_classes:
leaved_classes[key] = class_
# replacing base and derived classes with those that should be leave
# also this loop will add missing derived classes to the base
for class_ in classes:
leaved_class = leaved_classes[self._create_key(class_)]
for base_info in class_.bases:
leaved_base = leaved_classes[
self._create_key(base_info.related_class)]
# treating base class hierarchy of leaved_class
leaved_base_info = pygccxml.declarations.hierarchy_info_t(
related_class=leaved_base, access=base_info.access)
if leaved_base_info not in leaved_class.bases:
leaved_class.bases.append(leaved_base_info)
else:
index = leaved_class.bases.index(leaved_base_info)
leaved_class.bases[
index].related_class = leaved_base_info.related_class
# treating derived class hierarchy of leaved_base
leaved_derived_for_base_info = \
pygccxml.declarations.hierarchy_info_t(
related_class=leaved_class,
access=base_info.access)
if leaved_derived_for_base_info not in leaved_base.derived:
leaved_base.derived.append(leaved_derived_for_base_info)
else:
index = leaved_base.derived.index(
leaved_derived_for_base_info)
leaved_base.derived[index].related_class = \
leaved_derived_for_base_info.related_class
for derived_info in class_.derived:
leaved_derived = leaved_classes[
self._create_key(
derived_info.related_class)]
# treating derived class hierarchy of leaved_class
leaved_derived_info = pygccxml.declarations.hierarchy_info_t(
related_class=leaved_derived, access=derived_info.access)
if leaved_derived_info not in leaved_class.derived:
leaved_class.derived.append(leaved_derived_info)
# treating base class hierarchy of leaved_derived
leaved_base_for_derived_info = \
pygccxml.declarations.hierarchy_info_t(
related_class=leaved_class,
access=derived_info.access)
if leaved_base_for_derived_info not in leaved_derived.bases:
leaved_derived.bases.append(leaved_base_for_derived_info)
# this loops remove instance we from parent.declarations
for class_ in classes:
key = self._create_key(class_)
if id(leaved_classes[key]) == id(class_):
continue
else:
if class_.parent:
declarations = class_.parent.declarations
else:
# yes, we are talking about global class that doesn't
# belong to any namespace. Usually is compiler generated
# top level classes
declarations = namespaces
declarations_ids = [id(decl) for decl in declarations]
del declarations[declarations_ids.index(id(class_))]
return leaved_classes
@staticmethod
def _create_name_key(decl):
# Not all declarations have a mangled name with castxml
# we can only rely on the name
if decl.mangled is not None:
# gccxml
return decl.location.as_tuple(), decl.mangled
# castxml
return decl.location.as_tuple(), decl.name
def _relink_declarated_types(self, leaved_classes, declarated_types):
mangled_leaved_classes = {}
for leaved_class in leaved_classes.values():
mangled_leaved_classes[
self._create_name_key(leaved_class)] = leaved_class
for decl_wrapper_type in declarated_types:
# it is possible, that cache contains reference to dropped class
# We need to clear it
decl_wrapper_type.cache.reset()
if isinstance(
decl_wrapper_type.declaration,
pygccxml.declarations.class_t):
key = self._create_key(decl_wrapper_type.declaration)
if key in leaved_classes:
decl_wrapper_type.declaration = leaved_classes[key]
else:
name = decl_wrapper_type.declaration._name
if name == "":
# Happens with gcc5, castxml + std=c++11
# See issue #45
continue
if name.startswith("__vmi_class_type_info_pseudo"):
continue
if name == "rebind<std::__tree_node" + \
"<std::basic_string<char>, void *> >":
continue
msg = []
msg.append(
"Unable to find out actual class definition: '%s'." %
decl_wrapper_type.declaration._name)
msg.append((
"Class definition has been changed from one " +
"compilation to an other."))
msg.append((
"Why did it happen to me? Here is a short list " +
"of reasons: "))
msg.append((
" 1. There are different preprocessor " +
"definitions applied on same file during compilation"))
msg.append(" 2. Bug in pygccxml.")
raise Exception(os.linesep.join(msg))
elif isinstance(
decl_wrapper_type.declaration,
pygccxml.declarations.class_declaration_t):
key = self._create_name_key(decl_wrapper_type.declaration)
if key in mangled_leaved_classes:
decl_wrapper_type.declaration = mangled_leaved_classes[key]
@staticmethod
def __declarated_types(namespaces):
def get_from_type(cpptype):
if not cpptype:
return []
elif isinstance(cpptype, pygccxml.declarations.fundamental_t):
return []
elif isinstance(cpptype, pygccxml.declarations.declarated_t):
return [cpptype]
elif isinstance(cpptype, pygccxml.declarations.compound_t):
return get_from_type(cpptype.base)
elif isinstance(cpptype, pygccxml.declarations.calldef_type_t):
types = get_from_type(cpptype.return_type)
for arg in cpptype.arguments_types:
types.extend(get_from_type(arg))
return types
assert isinstance(
cpptype,
(pygccxml.declarations.unknown_t,
pygccxml.declarations.ellipsis_t))
return []
types = []
for decl in pygccxml.declarations.make_flatten(namespaces):
if isinstance(decl, pygccxml.declarations.calldef_t):
types.extend(get_from_type(decl.function_type()))
elif isinstance(
decl, (pygccxml.declarations.typedef_t,
pygccxml.declarations.variable_t)):
types.extend(get_from_type(decl.decl_type))
return types
|
apache-2.0
|
facebookresearch/ParlAI
|
parlai/chat_service/utils/misc.py
|
1
|
6342
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Miscellaneous utils for chat services.
"""
import importlib
import math
import re
from enum import Enum
THREAD_MEDIUM_SLEEP = 0.3
class TaskState:
"""
Wrapper for an agent running on a Worker.
"""
def __init__(
self, task_name, world_name, agents, is_overworld=False, world_type=None
):
self.task_name = task_name
self.world_name = world_name
self.agents = agents
self.is_overworld = is_overworld # (bool): overworld or task world
self.world_type = world_type # name of the task world returned by the overworld
self.future = None
self.world = None # world object
def get_world_module(world_path):
"""
Import the module specified by the world_path.
"""
run_module = None
try:
run_module = importlib.import_module(world_path)
except Exception as e:
print("Could not import world file {}".format(world_path))
raise e
return run_module
def get_world_fn_attr(world_module, world_name, fn_name, raise_if_missing=True):
"""
Import and return the function from world.
:param world_module:
module. a python module encompassing the worlds
:param world_name:
string. the name of the world in the module
:param fn_name:
string. the name of the function in the world
:param raise_if_missing:
bool. if true, raise error if function not found
:return:
the function, if defined by the world.
"""
result_fn = None
try:
DesiredWorld = getattr(world_module, world_name)
result_fn = getattr(DesiredWorld, fn_name)
except Exception as e:
if raise_if_missing:
print("Could not find {} for {}".format(fn_name, world_name))
raise e
return result_fn
def get_eligibility_fn(world_module, world_name):
"""
Get eligibility function for a world.
:param world_module:
module. a python module encompassing the worlds
:param world_name:
string. the name of the world in the module
:return:
the eligibility function if available, else None
"""
return get_world_fn_attr(
world_module, world_name, 'eligibility_function', raise_if_missing=False
)
def get_assign_roles_fn(world_module, world_name):
"""
Get assign roles function for a world.
:param world_module:
module. a python module encompassing the worlds
:param world_name:
string. the name of the world in the module
:return:
the assign roles function if available, else None
"""
return get_world_fn_attr(
world_module, world_name, 'assign_roles', raise_if_missing=False
)
def default_assign_roles_fn(agents):
"""
Assign agent role.
Default role assignment.
:param:
list of agents
"""
for i, a in enumerate(agents):
a.disp_id = f'Agent_{i}'
class SafetyDetectionResult(Enum):
"""
Result of identfying offensive language in a response.
SAFE: the message is safe
BLOCKLIST: the message contains a word from the blocklist
UNSAFE: the message is deemed unsafe by the safety classifier
"""
SAFE = 0
BLOCKLIST = 1
UNSAFE = 2
class ReportResult(Enum):
"""
Result of filing a report.
FAILURE: a player timed out while reporting, or it was an accidental report
BLOCK: a player is blocked, for having been reported > 1 times
SUCCESS: a successful report
BOT: the offending agent was the bot
"""
FAILURE = 0
BLOCK = 1
SUCCESS = 2
BOT = 3
class UploadImageResult(Enum):
"""
Result of uploading an image.
SUCCESS: user successfully uploaded an image
OBJECTIONABLE: the image contains objectionable content
ERROR: there was an error
"""
SUCCESS = 0
OBJECTIONABLE = 1
ERROR = 2
class PersonalInfoDetector(object):
"""
Detects whether a string contains any of the following personal information
datapoints using regular expressions:
- credit card
- phone number
- email
- SSN
"""
def __init__(self):
self.credit_card_regex = r"((?:(?:\\d{4}[- ]?){3}\\d{4}|\\d{15,16}))(?![\\d])"
self.email_regex = (
r"([a-z0-9!#$%&'*+\/=?^_`{|.}~-]+@(?:[a-z0-9](?:[a-z0-9-]*"
+ r"[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)"
)
self.phone_number_regex = (
r"\D?(\d{0,3}?)\D{0,2}(\d{3})?\D{0,2}(\d{3})\D?(\d{4})$"
)
self.ssn_regex = r"^\d{3}-\d{2}-\d{4}$"
def detect_all(self, text):
contains = {}
contains["credit_card"] = self.detect_credit_card(text)
contains["email"] = self.detect_email(text)
contains["phone_number"] = self.detect_phone_number(text)
contains["ssn"] = self.detect_ssn(text)
return contains
def txt_format_detect_all(self, text):
contains = self.detect_all(text)
contains_personal_info = False
txt = "We believe this text contains the following personal " + "information:"
for k, v in contains.items():
if v != []:
contains_personal_info = True
txt += f"\n- {k.replace('_', ' ')}: {', '.join([str(x) for x in v])}"
if not contains_personal_info:
return ""
return txt
def detect_credit_card(self, text):
return re.findall(self.credit_card_regex, text)
def detect_email(self, text):
text = text.lower()
return re.findall(self.email_regex, text)
def detect_phone_number(self, text):
phones = re.findall(self.phone_number_regex, text)
edited = []
for tup in phones:
edited.append("".join(list(tup)))
return edited
def detect_ssn(self, text):
return re.findall(self.ssn_regex, text)
class DictFrequencies:
"""
Dict freqs.
"""
def __init__(self, freqs):
self.freqs = freqs
self.N = sum(freqs.values())
self.V = len(freqs)
self.logNV = math.log(self.N + self.V)
|
mit
|
ruyang/ironic
|
ironic/tests/unit/drivers/modules/drac/test_job.py
|
6
|
6492
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Test class for DRAC job specific methods
"""
from dracclient import exceptions as drac_exceptions
import mock
from ironic.common import exception
from ironic.conductor import task_manager
from ironic.drivers.modules.drac import common as drac_common
from ironic.drivers.modules.drac import job as drac_job
from ironic.tests.unit.conductor import mgr_utils
from ironic.tests.unit.db import base as db_base
from ironic.tests.unit.db import utils as db_utils
from ironic.tests.unit.drivers.modules.drac import utils as test_utils
from ironic.tests.unit.objects import utils as obj_utils
INFO_DICT = db_utils.get_test_drac_info()
@mock.patch.object(drac_common, 'get_drac_client', spec_set=True,
autospec=True)
class DracJobTestCase(db_base.DbTestCase):
def setUp(self):
super(DracJobTestCase, self).setUp()
mgr_utils.mock_the_extension_manager(driver='fake_drac')
self.node = obj_utils.create_test_node(self.context,
driver='fake_drac',
driver_info=INFO_DICT)
self.job_dict = {
'id': 'JID_001436912645',
'name': 'ConfigBIOS:BIOS.Setup.1-1',
'start_time': '00000101000000',
'until_time': 'TIME_NA',
'message': 'Job in progress',
'state': 'Running',
'percent_complete': 34}
self.job = test_utils.dict_to_namedtuple(values=self.job_dict)
def test_get_job(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
mock_client.get_job.return_value = self.job
job = drac_job.get_job(self.node, 'foo')
mock_client.get_job.assert_called_once_with('foo')
self.assertEqual(self.job, job)
def test_get_job_fail(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
exc = exception.DracOperationError('boom')
mock_client.get_job.side_effect = exc
self.assertRaises(exception.DracOperationError,
drac_job.get_job, self.node, 'foo')
def test_list_unfinished_jobs(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
mock_client.list_jobs.return_value = [self.job]
jobs = drac_job.list_unfinished_jobs(self.node)
mock_client.list_jobs.assert_called_once_with(only_unfinished=True)
self.assertEqual([self.job], jobs)
def test_list_unfinished_jobs_fail(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
exc = exception.DracOperationError('boom')
mock_client.list_jobs.side_effect = exc
self.assertRaises(exception.DracOperationError,
drac_job.list_unfinished_jobs, self.node)
def test_validate_job_queue(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
mock_client.list_jobs.return_value = []
drac_job.validate_job_queue(self.node)
mock_client.list_jobs.assert_called_once_with(only_unfinished=True)
def test_validate_job_queue_fail(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
exc = drac_exceptions.BaseClientException('boom')
mock_client.list_jobs.side_effect = exc
self.assertRaises(exception.DracOperationError,
drac_job.validate_job_queue, self.node)
def test_validate_job_queue_invalid(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
mock_client.list_jobs.return_value = [self.job]
self.assertRaises(exception.DracOperationError,
drac_job.validate_job_queue, self.node)
@mock.patch.object(drac_common, 'get_drac_client', spec_set=True,
autospec=True)
class DracVendorPassthruJobTestCase(db_base.DbTestCase):
def setUp(self):
super(DracVendorPassthruJobTestCase, self).setUp()
mgr_utils.mock_the_extension_manager(driver='fake_drac')
self.node = obj_utils.create_test_node(self.context,
driver='fake_drac',
driver_info=INFO_DICT)
self.job_dict = {
'id': 'JID_001436912645',
'name': 'ConfigBIOS:BIOS.Setup.1-1',
'start_time': '00000101000000',
'until_time': 'TIME_NA',
'message': 'Job in progress',
'state': 'Running',
'percent_complete': 34}
self.job = test_utils.dict_to_namedtuple(values=self.job_dict)
def test_list_unfinished_jobs(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
mock_client.list_jobs.return_value = [self.job]
with task_manager.acquire(self.context, self.node.uuid,
shared=False) as task:
resp = task.driver.vendor.list_unfinished_jobs(task)
mock_client.list_jobs.assert_called_once_with(only_unfinished=True)
self.assertEqual([self.job_dict], resp['unfinished_jobs'])
def test_list_unfinished_jobs_fail(self, mock_get_drac_client):
mock_client = mock.Mock()
mock_get_drac_client.return_value = mock_client
exc = exception.DracOperationError('boom')
mock_client.list_jobs.side_effect = exc
with task_manager.acquire(self.context, self.node.uuid,
shared=False) as task:
self.assertRaises(exception.DracOperationError,
task.driver.vendor.list_unfinished_jobs, task)
|
apache-2.0
|
zwChan/VATEC
|
~/eb-virt/Lib/encodings/iso8859_11.py
|
93
|
12898
|
""" Python Character Mapping Codec iso8859_11 generated from 'MAPPINGS/ISO8859/8859-11.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='iso8859-11',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\x80' # 0x80 -> <control>
u'\x81' # 0x81 -> <control>
u'\x82' # 0x82 -> <control>
u'\x83' # 0x83 -> <control>
u'\x84' # 0x84 -> <control>
u'\x85' # 0x85 -> <control>
u'\x86' # 0x86 -> <control>
u'\x87' # 0x87 -> <control>
u'\x88' # 0x88 -> <control>
u'\x89' # 0x89 -> <control>
u'\x8a' # 0x8A -> <control>
u'\x8b' # 0x8B -> <control>
u'\x8c' # 0x8C -> <control>
u'\x8d' # 0x8D -> <control>
u'\x8e' # 0x8E -> <control>
u'\x8f' # 0x8F -> <control>
u'\x90' # 0x90 -> <control>
u'\x91' # 0x91 -> <control>
u'\x92' # 0x92 -> <control>
u'\x93' # 0x93 -> <control>
u'\x94' # 0x94 -> <control>
u'\x95' # 0x95 -> <control>
u'\x96' # 0x96 -> <control>
u'\x97' # 0x97 -> <control>
u'\x98' # 0x98 -> <control>
u'\x99' # 0x99 -> <control>
u'\x9a' # 0x9A -> <control>
u'\x9b' # 0x9B -> <control>
u'\x9c' # 0x9C -> <control>
u'\x9d' # 0x9D -> <control>
u'\x9e' # 0x9E -> <control>
u'\x9f' # 0x9F -> <control>
u'\xa0' # 0xA0 -> NO-BREAK SPACE
u'\u0e01' # 0xA1 -> THAI CHARACTER KO KAI
u'\u0e02' # 0xA2 -> THAI CHARACTER KHO KHAI
u'\u0e03' # 0xA3 -> THAI CHARACTER KHO KHUAT
u'\u0e04' # 0xA4 -> THAI CHARACTER KHO KHWAI
u'\u0e05' # 0xA5 -> THAI CHARACTER KHO KHON
u'\u0e06' # 0xA6 -> THAI CHARACTER KHO RAKHANG
u'\u0e07' # 0xA7 -> THAI CHARACTER NGO NGU
u'\u0e08' # 0xA8 -> THAI CHARACTER CHO CHAN
u'\u0e09' # 0xA9 -> THAI CHARACTER CHO CHING
u'\u0e0a' # 0xAA -> THAI CHARACTER CHO CHANG
u'\u0e0b' # 0xAB -> THAI CHARACTER SO SO
u'\u0e0c' # 0xAC -> THAI CHARACTER CHO CHOE
u'\u0e0d' # 0xAD -> THAI CHARACTER YO YING
u'\u0e0e' # 0xAE -> THAI CHARACTER DO CHADA
u'\u0e0f' # 0xAF -> THAI CHARACTER TO PATAK
u'\u0e10' # 0xB0 -> THAI CHARACTER THO THAN
u'\u0e11' # 0xB1 -> THAI CHARACTER THO NANGMONTHO
u'\u0e12' # 0xB2 -> THAI CHARACTER THO PHUTHAO
u'\u0e13' # 0xB3 -> THAI CHARACTER NO NEN
u'\u0e14' # 0xB4 -> THAI CHARACTER DO DEK
u'\u0e15' # 0xB5 -> THAI CHARACTER TO TAO
u'\u0e16' # 0xB6 -> THAI CHARACTER THO THUNG
u'\u0e17' # 0xB7 -> THAI CHARACTER THO THAHAN
u'\u0e18' # 0xB8 -> THAI CHARACTER THO THONG
u'\u0e19' # 0xB9 -> THAI CHARACTER NO NU
u'\u0e1a' # 0xBA -> THAI CHARACTER BO BAIMAI
u'\u0e1b' # 0xBB -> THAI CHARACTER PO PLA
u'\u0e1c' # 0xBC -> THAI CHARACTER PHO PHUNG
u'\u0e1d' # 0xBD -> THAI CHARACTER FO FA
u'\u0e1e' # 0xBE -> THAI CHARACTER PHO PHAN
u'\u0e1f' # 0xBF -> THAI CHARACTER FO FAN
u'\u0e20' # 0xC0 -> THAI CHARACTER PHO SAMPHAO
u'\u0e21' # 0xC1 -> THAI CHARACTER MO MA
u'\u0e22' # 0xC2 -> THAI CHARACTER YO YAK
u'\u0e23' # 0xC3 -> THAI CHARACTER RO RUA
u'\u0e24' # 0xC4 -> THAI CHARACTER RU
u'\u0e25' # 0xC5 -> THAI CHARACTER LO LING
u'\u0e26' # 0xC6 -> THAI CHARACTER LU
u'\u0e27' # 0xC7 -> THAI CHARACTER WO WAEN
u'\u0e28' # 0xC8 -> THAI CHARACTER SO SALA
u'\u0e29' # 0xC9 -> THAI CHARACTER SO RUSI
u'\u0e2a' # 0xCA -> THAI CHARACTER SO SUA
u'\u0e2b' # 0xCB -> THAI CHARACTER HO HIP
u'\u0e2c' # 0xCC -> THAI CHARACTER LO CHULA
u'\u0e2d' # 0xCD -> THAI CHARACTER O ANG
u'\u0e2e' # 0xCE -> THAI CHARACTER HO NOKHUK
u'\u0e2f' # 0xCF -> THAI CHARACTER PAIYANNOI
u'\u0e30' # 0xD0 -> THAI CHARACTER SARA A
u'\u0e31' # 0xD1 -> THAI CHARACTER MAI HAN-AKAT
u'\u0e32' # 0xD2 -> THAI CHARACTER SARA AA
u'\u0e33' # 0xD3 -> THAI CHARACTER SARA AM
u'\u0e34' # 0xD4 -> THAI CHARACTER SARA I
u'\u0e35' # 0xD5 -> THAI CHARACTER SARA II
u'\u0e36' # 0xD6 -> THAI CHARACTER SARA UE
u'\u0e37' # 0xD7 -> THAI CHARACTER SARA UEE
u'\u0e38' # 0xD8 -> THAI CHARACTER SARA U
u'\u0e39' # 0xD9 -> THAI CHARACTER SARA UU
u'\u0e3a' # 0xDA -> THAI CHARACTER PHINTHU
u'\ufffe'
u'\ufffe'
u'\ufffe'
u'\ufffe'
u'\u0e3f' # 0xDF -> THAI CURRENCY SYMBOL BAHT
u'\u0e40' # 0xE0 -> THAI CHARACTER SARA E
u'\u0e41' # 0xE1 -> THAI CHARACTER SARA AE
u'\u0e42' # 0xE2 -> THAI CHARACTER SARA O
u'\u0e43' # 0xE3 -> THAI CHARACTER SARA AI MAIMUAN
u'\u0e44' # 0xE4 -> THAI CHARACTER SARA AI MAIMALAI
u'\u0e45' # 0xE5 -> THAI CHARACTER LAKKHANGYAO
u'\u0e46' # 0xE6 -> THAI CHARACTER MAIYAMOK
u'\u0e47' # 0xE7 -> THAI CHARACTER MAITAIKHU
u'\u0e48' # 0xE8 -> THAI CHARACTER MAI EK
u'\u0e49' # 0xE9 -> THAI CHARACTER MAI THO
u'\u0e4a' # 0xEA -> THAI CHARACTER MAI TRI
u'\u0e4b' # 0xEB -> THAI CHARACTER MAI CHATTAWA
u'\u0e4c' # 0xEC -> THAI CHARACTER THANTHAKHAT
u'\u0e4d' # 0xED -> THAI CHARACTER NIKHAHIT
u'\u0e4e' # 0xEE -> THAI CHARACTER YAMAKKAN
u'\u0e4f' # 0xEF -> THAI CHARACTER FONGMAN
u'\u0e50' # 0xF0 -> THAI DIGIT ZERO
u'\u0e51' # 0xF1 -> THAI DIGIT ONE
u'\u0e52' # 0xF2 -> THAI DIGIT TWO
u'\u0e53' # 0xF3 -> THAI DIGIT THREE
u'\u0e54' # 0xF4 -> THAI DIGIT FOUR
u'\u0e55' # 0xF5 -> THAI DIGIT FIVE
u'\u0e56' # 0xF6 -> THAI DIGIT SIX
u'\u0e57' # 0xF7 -> THAI DIGIT SEVEN
u'\u0e58' # 0xF8 -> THAI DIGIT EIGHT
u'\u0e59' # 0xF9 -> THAI DIGIT NINE
u'\u0e5a' # 0xFA -> THAI CHARACTER ANGKHANKHU
u'\u0e5b' # 0xFB -> THAI CHARACTER KHOMUT
u'\ufffe'
u'\ufffe'
u'\ufffe'
u'\ufffe'
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
|
apache-2.0
|
rversteegen/commandergenius
|
project/jni/python/src/Lib/shelve.py
|
59
|
7866
|
"""Manage shelves of pickled objects.
A "shelf" is a persistent, dictionary-like object. The difference
with dbm databases is that the values (not the keys!) in a shelf can
be essentially arbitrary Python objects -- anything that the "pickle"
module can handle. This includes most class instances, recursive data
types, and objects containing lots of shared sub-objects. The keys
are ordinary strings.
To summarize the interface (key is a string, data is an arbitrary
object):
import shelve
d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
d[key] = data # store data at key (overwrites old data if
# using an existing key)
data = d[key] # retrieve a COPY of the data at key (raise
# KeyError if no such key) -- NOTE that this
# access returns a *copy* of the entry!
del d[key] # delete data stored at key (raises KeyError
# if no such key)
flag = d.has_key(key) # true if the key exists; same as "key in d"
list = d.keys() # a list of all existing keys (slow!)
d.close() # close it
Dependent on the implementation, closing a persistent dictionary may
or may not be necessary to flush changes to disk.
Normally, d[key] returns a COPY of the entry. This needs care when
mutable entries are mutated: for example, if d[key] is a list,
d[key].append(anitem)
does NOT modify the entry d[key] itself, as stored in the persistent
mapping -- it only modifies the copy, which is then immediately
discarded, so that the append has NO effect whatsoever. To append an
item to d[key] in a way that will affect the persistent mapping, use:
data = d[key]
data.append(anitem)
d[key] = data
To avoid the problem with mutable entries, you may pass the keyword
argument writeback=True in the call to shelve.open. When you use:
d = shelve.open(filename, writeback=True)
then d keeps a cache of all entries you access, and writes them all back
to the persistent mapping when you call d.close(). This ensures that
such usage as d[key].append(anitem) works as intended.
However, using keyword argument writeback=True may consume vast amount
of memory for the cache, and it may make d.close() very slow, if you
access many of d's entries after opening it in this way: d has no way to
check which of the entries you access are mutable and/or which ones you
actually mutate, so it must cache, and write back at close, all of the
entries that you access. You can call d.sync() to write back all the
entries in the cache, and empty the cache (d.sync() also synchronizes
the persistent dictionary on disk, if feasible).
"""
# Try using cPickle and cStringIO if available.
try:
from cPickle import Pickler, Unpickler
except ImportError:
from pickle import Pickler, Unpickler
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import UserDict
__all__ = ["Shelf","BsdDbShelf","DbfilenameShelf","open"]
class _ClosedDict(UserDict.DictMixin):
'Marker for a closed dict. Access attempts raise a ValueError.'
def closed(self, *args):
raise ValueError('invalid operation on closed shelf')
__getitem__ = __setitem__ = __delitem__ = keys = closed
def __repr__(self):
return '<Closed Dictionary>'
class Shelf(UserDict.DictMixin):
"""Base class for shelf implementations.
This is initialized with a dictionary-like object.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, dict, protocol=None, writeback=False):
self.dict = dict
if protocol is None:
protocol = 0
self._protocol = protocol
self.writeback = writeback
self.cache = {}
def keys(self):
return self.dict.keys()
def __len__(self):
return len(self.dict)
def has_key(self, key):
return key in self.dict
def __contains__(self, key):
return key in self.dict
def get(self, key, default=None):
if key in self.dict:
return self[key]
return default
def __getitem__(self, key):
try:
value = self.cache[key]
except KeyError:
f = StringIO(self.dict[key])
value = Unpickler(f).load()
if self.writeback:
self.cache[key] = value
return value
def __setitem__(self, key, value):
if self.writeback:
self.cache[key] = value
f = StringIO()
p = Pickler(f, self._protocol)
p.dump(value)
self.dict[key] = f.getvalue()
def __delitem__(self, key):
del self.dict[key]
try:
del self.cache[key]
except KeyError:
pass
def close(self):
self.sync()
try:
self.dict.close()
except AttributeError:
pass
self.dict = _ClosedDict()
def __del__(self):
if not hasattr(self, 'writeback'):
# __init__ didn't succeed, so don't bother closing
return
self.close()
def sync(self):
if self.writeback and self.cache:
self.writeback = False
for key, entry in self.cache.iteritems():
self[key] = entry
self.writeback = True
self.cache = {}
if hasattr(self.dict, 'sync'):
self.dict.sync()
class BsdDbShelf(Shelf):
"""Shelf implementation using the "BSD" db interface.
This adds methods first(), next(), previous(), last() and
set_location() that have no counterpart in [g]dbm databases.
The actual database must be opened using one of the "bsddb"
modules "open" routines (i.e. bsddb.hashopen, bsddb.btopen or
bsddb.rnopen) and passed to the constructor.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, dict, protocol=None, writeback=False):
Shelf.__init__(self, dict, protocol, writeback)
def set_location(self, key):
(key, value) = self.dict.set_location(key)
f = StringIO(value)
return (key, Unpickler(f).load())
def next(self):
(key, value) = self.dict.next()
f = StringIO(value)
return (key, Unpickler(f).load())
def previous(self):
(key, value) = self.dict.previous()
f = StringIO(value)
return (key, Unpickler(f).load())
def first(self):
(key, value) = self.dict.first()
f = StringIO(value)
return (key, Unpickler(f).load())
def last(self):
(key, value) = self.dict.last()
f = StringIO(value)
return (key, Unpickler(f).load())
class DbfilenameShelf(Shelf):
"""Shelf implementation using the "anydbm" generic dbm interface.
This is initialized with the filename for the dbm database.
See the module's __doc__ string for an overview of the interface.
"""
def __init__(self, filename, flag='c', protocol=None, writeback=False):
import anydbm
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
def open(filename, flag='c', protocol=None, writeback=False):
"""Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
anydbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface.
"""
return DbfilenameShelf(filename, flag, protocol, writeback)
|
lgpl-2.1
|
MorganR/gaussian-processes
|
data/shapes.py
|
1
|
4350
|
import random
from math import sin, cos, sqrt, inf, degrees, pi, isclose, atan
from data.cartesian import Point, Vector
from utils.nums import is_zero
class Line:
"""Represents a straight line as distance 'd' from the origin and angle
'theta' from the x-axis"""
def __init__(self, d=0, theta=0):
self.d = d
self.theta = theta % (2*pi)
def get_slope(self):
return sin(self.theta) / cos(self.theta)
def calc_x(self, y):
if cos(self.theta) == 0:
if y == d/sin(self.theta):
return inf
return None
return (self.d - y*sin(self.theta))/cos(self.theta)
def calc_y(self, x):
if sin(self.theta) == 0:
if x == d/cos(self.theta):
return inf
return None
return (self.d - x*cos(self.theta))/sin(self.theta)
def get_dist_from_line(self, point):
return point.x*cos(self.theta) + point.y*sin(self.theta) - self.d
def is_parallel(self, line):
return isclose(line.theta, self.theta) \
or isclose(line.theta, ((self.theta + pi) % (2*pi)))
def _solve_with_x(self, line):
x = (line.d/sin(line.theta) - self.d/sin(self.theta)) \
/ (cos(line.theta)/sin(line.theta) - cos(self.theta)/sin(self.theta))
y = self.calc_y(x)
return Point(x, y)
def _solve_with_y(self, line):
y = (line.d/cos(line.theta) - self.d/cos(self.theta)) \
/ (sin(line.theta)/cos(line.theta) - sin(self.theta)/cos(self.theta))
x = self.calc_x(y)
return Point(x, y)
def get_intercept(self, line):
if (self.is_parallel(line)):
return None
if (not is_zero(sin(self.theta)) \
and not is_zero(sin(line.theta))):
# print("solving with x since sin(s.theta): %f and sin(l.theta): %f" % (sin(self.theta), sin(line.theta)))
return self._solve_with_x(line)
elif (not is_zero(cos(self.theta)) \
and not is_zero(cos(line.theta))):
# print("solving with y")
return self._solve_with_y(line)
# Else these lines are exactly horizontal and vertical
if is_zero(sin(self.theta)):
# self is vertical
# print("solving for vertical line")
return Point(self.d/cos(self.theta), line.d/sin(line.theta))
else:
# print("solving for horizontal line")
return Point(line.d/cos(line.theta), self.d/sin(self.theta))
def __str__(self):
return "Line with d: %d\ttheta (degrees): %f" \
% (self.d, degrees(self.theta))
def generate_line(d_min, d_max):
random.seed()
d = random.randint(d_min, d_max)
theta = random.uniform(0, 2*pi)
return Line(d, theta)
def get_perp_line_through_point(line, point):
inv_l = Line(0, (line.theta + pi/2) % (2*pi))
inv_l.d = point.x*cos(inv_l.theta) + point.y*sin(inv_l.theta)
return inv_l
class Circle:
"""Represents a circle as a center Point and distance r from the center"""
def __init__(self, r, center):
self.r = r
# The center as a Point
self.center = center
def get_point(self, theta):
d_y = r*sin(theta)
d_x = r*cos(theta)
return Point(self.center.x + d_x, self.center.y + d_y)
def get_theta(self, point):
if point == self.center:
return None
d_vect = point - self.center
return atan(d_vect.y, d_vect.x)
def __str__(self):
return "Circle with radius %f and center %s" \
% (self.r, str(self.center))
def generate_circle(r_min, r_max, offset_min=0, offset_max=0):
"""Generate a random circle with integer radius between r_min and r_max,
and with a center with abs(x) and abs(y) between offset_min and offset_max"""
if (r_min < 0 or r_max < 0 or offset_min < 0 or offset_max < 0):
raise AssertionError("All args to generate_circle must be >= 0")
random.seed()
r = random.randint(r_min, r_max)
x_off = random.randint(0, offset_max - offset_min) + offset_min
y_off = random.randint(0, offset_max - offset_min) + offset_min
if random.randint(0, 1) == 1:
x_off = x_off*(-1)
if random.randint(0, 1) == 1:
y_off = y_off*(-1)
return Circle(r, Point(x_off, y_off))
|
mit
|
robbles/turk
|
turk/drivers/tick.py
|
1
|
1612
|
#! /usr/bin/env python
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib
import turk
DRIVER_ID = 2
"""
Sends an update with the current date/time every one second. Useful for waking
up web-based Tapps.
"""
class Tick(dbus.service.Object):
def __init__(self, bus):
dbus.service.Object.__init__(self, bus, '/Drivers/Tick')
self.bus = bus
gobject.timeout_add(1000, self.tick)
print 'Tick: running'
def run(self):
loop = gobject.MainLoop()
loop.run()
def tick(self):
try:
update = '<tick />'
bridge = self.bus.get_object(turk.TURK_BRIDGE_SERVICE, '/Bridge')
bridge.PublishUpdate('app', update, unicode(DRIVER_ID),
reply_handler=self.handle_reply, error_handler=self.handle_error)
except dbus.DBusException, e:
print 'Tick: error posting data to app', e
except Exception, e:
print e
finally:
# Just keep ticking
return True
def handle_reply(*args): pass
def handle_error(*args): pass
@dbus.service.signal(dbus_interface=turk.TURK_DRIVER_ERROR, signature='s')
def Error(self, message):
""" Called when an error/exception occurs. Emits a signal for any relevant
system management daemons and loggers """
pass
if __name__ == '__main__':
import os
bus = os.getenv('BUS', turk.get_config('global.bus'))
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
driver = Tick(getattr(dbus, bus)())
driver.run()
|
mit
|
hopeall/odoo
|
openerp/report/render/rml2pdf/customfonts.py
|
261
|
3493
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 P. Christeas, Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2013 OpenERP SA. (http://www.openerp.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from reportlab import rl_config
import logging
import glob
import os
# .apidoc title: TTF Font Table
"""This module allows the mapping of some system-available TTF fonts to
the reportlab engine.
This file could be customized per distro (although most Linux/Unix ones)
should have the same filenames, only need the code below).
Due to an awful configuration that ships with reportlab at many Linux
and Ubuntu distros, we have to override the search path, too.
"""
_logger = logging.getLogger(__name__)
CustomTTFonts = []
# Search path for TTF files, in addition of rl_config.TTFSearchPath
TTFSearchPath = [
'/usr/share/fonts/truetype', # SuSE
'/usr/share/fonts/dejavu', '/usr/share/fonts/liberation', # Fedora, RHEL
'/usr/share/fonts/truetype/*','/usr/local/share/fonts' # Ubuntu,
'/usr/share/fonts/TTF/*', # Mandriva/Mageia
'/usr/share/fonts/TTF', # Arch Linux
'/usr/lib/openoffice/share/fonts/truetype/',
'~/.fonts',
'~/.local/share/fonts',
# mac os X - from
# http://developer.apple.com/technotes/tn/tn2024.html
'~/Library/Fonts',
'/Library/Fonts',
'/Network/Library/Fonts',
'/System/Library/Fonts',
# windows
'c:/winnt/fonts',
'c:/windows/fonts'
]
def list_all_sysfonts():
"""
This function returns list of font directories of system.
"""
filepath = []
# Perform the search for font files ourselves, as reportlab's
# TTFOpenFile is not very good at it.
searchpath = list(set(TTFSearchPath + rl_config.TTFSearchPath))
for dirname in searchpath:
for filename in glob.glob(os.path.join(os.path.expanduser(dirname), '*.[Tt][Tt][FfCc]')):
filepath.append(filename)
return filepath
def SetCustomFonts(rmldoc):
""" Map some font names to the corresponding TTF fonts
The ttf font may not even have the same name, as in
Times -> Liberation Serif.
This function is called once per report, so it should
avoid system-wide processing (cache it, instead).
"""
for family, font, filename, mode in CustomTTFonts:
if os.path.isabs(filename) and os.path.exists(filename):
rmldoc.setTTFontMapping(family, font, filename, mode)
return True
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
caioserra/apiAdwords
|
examples/adspygoogle/dfp/v201208/get_all_line_items.py
|
4
|
1714
|
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example gets all line items. To create line items, run
create_line_items.py."""
__author__ = '[email protected] (Jeff Sham)'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import DfpClient
from adspygoogle.dfp import DfpUtils
# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
# Initialize appropriate service.
line_item_service = client.GetService('LineItemService', version='v201208')
# Get line items by statement.
line_items = DfpUtils.GetAllEntitiesByStatementWithService(line_item_service)
# Display results.
for line_item in line_items:
print ('Line item with id \'%s\', belonging to order id \'%s\', and named '
'\'%s\' was found.' % (line_item['id'], line_item['orderId'],
line_item['name']))
print
print 'Number of results found: %s' % len(line_items)
|
apache-2.0
|
chainer/chainercv
|
chainercv/utils/testing/assertions/assert_is_instance_segmentation_link.py
|
3
|
2385
|
import numpy as np
import six
def assert_is_instance_segmentation_link(link, n_fg_class):
"""Checks if a link satisfies instance segmentation link APIs.
This function checks if a given link satisfies instance segmentation
link APIs or not.
If the link does not satifiy the APIs, this function raises an
:class:`AssertionError`.
Args:
link: A link to be checked.
n_fg_class (int): The number of foreground classes.
"""
imgs = [
np.random.randint(0, 256, size=(3, 480, 640)).astype(np.float32),
np.random.randint(0, 256, size=(3, 480, 320)).astype(np.float32)]
result = link.predict(imgs)
assert len(result) == 3, \
'Link must return three elements: masks, labels and scores.'
masks, labels, scores = result
assert len(masks) == len(imgs), \
'The length of masks must be same as that of imgs.'
assert len(labels) == len(imgs), \
'The length of labels must be same as that of imgs.'
assert len(scores) == len(imgs), \
'The length of scores must be same as that of imgs.'
for img, mask, label, score in six.moves.zip(imgs, masks, labels, scores):
assert isinstance(mask, np.ndarray), \
'mask must be a numpy.ndarray.'
assert mask.dtype == np.bool, \
'The type of mask must be bool'
assert mask.shape[1:] == img.shape[1:], \
'The shape of mask must be (R, H, W).'
assert isinstance(label, np.ndarray), \
'label must be a numpy.ndarray.'
assert label.dtype == np.int32, \
'The type of label must be numpy.int32.'
assert label.shape[1:] == (), \
'The shape of label must be (*,).'
assert len(label) == len(mask), \
'The length of label must be same as that of mask.'
if len(label) > 0:
assert label.min() >= 0 and label.max() < n_fg_class, \
'The value of label must be in [0, n_fg_class - 1].'
assert isinstance(score, np.ndarray), \
'score must be a numpy.ndarray.'
assert score.dtype == np.float32, \
'The type of score must be numpy.float32.'
assert score.shape[1:] == (), \
'The shape of score must be (*,).'
assert len(score) == len(mask), \
'The length of score must be same as that of mask.'
|
mit
|
xuxiao19910803/edx-platform
|
openedx/core/djangoapps/user_api/accounts/tests/test_views.py
|
39
|
33313
|
# -*- coding: utf-8 -*-
import datetime
from copy import deepcopy
import ddt
import hashlib
import json
from mock import patch
from pytz import UTC
import unittest
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.testcases import TransactionTestCase
from django.test.utils import override_settings
from rest_framework.test import APITestCase, APIClient
from student.tests.factories import UserFactory
from student.models import UserProfile, LanguageProficiency, PendingEmailChange
from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY
from openedx.core.djangoapps.user_api.preferences.api import set_user_preference
from .. import PRIVATE_VISIBILITY, ALL_USERS_VISIBILITY
TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 01, tzinfo=UTC)
# this is used in one test to check the behavior of profile image url
# generation with a relative url in the config.
TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND)
TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/'
class UserAPITestCase(APITestCase):
"""
The base class for all tests of the User API
"""
test_password = "test"
def setUp(self):
super(UserAPITestCase, self).setUp()
self.anonymous_client = APIClient()
self.different_user = UserFactory.create(password=self.test_password)
self.different_client = APIClient()
self.staff_user = UserFactory(is_staff=True, password=self.test_password)
self.staff_client = APIClient()
self.user = UserFactory.create(password=self.test_password) # will be assigned to self.client by default
def login_client(self, api_client, user):
"""Helper method for getting the client and user and logging in. Returns client. """
client = getattr(self, api_client)
user = getattr(self, user)
client.login(username=user.username, password=self.test_password)
return client
def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=204):
"""
Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type.
Verifies the expected status and returns the response.
"""
# pylint: disable=no-member
response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type)
self.assertEqual(expected_status, response.status_code)
return response
def send_get(self, client, query_parameters=None, expected_status=200):
"""
Helper method for sending a GET to the server. Verifies the expected status and returns the response.
"""
url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member
response = client.get(url)
self.assertEqual(expected_status, response.status_code)
return response
def send_put(self, client, json_data, content_type="application/json", expected_status=204):
"""
Helper method for sending a PUT to the server. Verifies the expected status and returns the response.
"""
response = client.put(self.url, data=json.dumps(json_data), content_type=content_type)
self.assertEqual(expected_status, response.status_code)
return response
def send_delete(self, client, expected_status=204):
"""
Helper method for sending a DELETE to the server. Verifies the expected status and returns the response.
"""
response = client.delete(self.url)
self.assertEqual(expected_status, response.status_code)
return response
def create_mock_profile(self, user):
"""
Helper method that creates a mock profile for the specified user
:return:
"""
legacy_profile = UserProfile.objects.get(id=user.id)
legacy_profile.country = "US"
legacy_profile.level_of_education = "m"
legacy_profile.year_of_birth = 2000
legacy_profile.goals = "world peace"
legacy_profile.mailing_address = "Park Ave"
legacy_profile.gender = "f"
legacy_profile.bio = "Tired mother of twins"
legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT
legacy_profile.language_proficiencies.add(LanguageProficiency(code='en'))
legacy_profile.save()
@ddt.ddt
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Account APIs are only supported in LMS')
@patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10])
@patch.dict(
'openedx.core.djangoapps.user_api.accounts.image_helpers.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True
)
class TestAccountAPI(UserAPITestCase):
"""
Unit tests for the Account API.
"""
def setUp(self):
super(TestAccountAPI, self).setUp()
self.url = reverse("accounts_api", kwargs={'username': self.user.username})
def _verify_profile_image_data(self, data, has_profile_image):
"""
Verify the profile image data in a GET response for self.user
corresponds to whether the user has or hasn't set a profile
image.
"""
template = '{root}/{filename}_{{size}}.{extension}'
if has_profile_image:
url_root = 'http://example-storage.com/profile-images'
filename = hashlib.md5('secret' + self.user.username).hexdigest()
file_extension = 'jpg'
template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s"))
else:
url_root = 'http://testserver/static'
filename = 'default'
file_extension = 'png'
template = template.format(root=url_root, filename=filename, extension=file_extension)
self.assertEqual(
data['profile_image'],
{
'has_image': has_profile_image,
'image_url_full': template.format(size=50),
'image_url_small': template.format(size=10),
}
)
def _verify_full_shareable_account_response(self, response):
"""
Verify that the shareable fields from the account are returned
"""
data = response.data
self.assertEqual(6, len(data))
self.assertEqual(self.user.username, data["username"])
self.assertEqual("US", data["country"])
self._verify_profile_image_data(data, True)
self.assertIsNone(data["time_zone"])
self.assertEqual([{"code": "en"}], data["language_proficiencies"])
self.assertEqual("Tired mother of twins", data["bio"])
def _verify_private_account_response(self, response, requires_parental_consent=False):
"""
Verify that only the public fields are returned if a user does not want to share account fields
"""
data = response.data
self.assertEqual(2, len(data))
self.assertEqual(self.user.username, data["username"])
self._verify_profile_image_data(data, not requires_parental_consent)
def _verify_full_account_response(self, response, requires_parental_consent=False):
"""
Verify that all account fields are returned (even those that are not shareable).
"""
data = response.data
self.assertEqual(15, len(data))
self.assertEqual(self.user.username, data["username"])
self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"])
self.assertEqual("US", data["country"])
self.assertEqual("f", data["gender"])
self.assertEqual(2000, data["year_of_birth"])
self.assertEqual("m", data["level_of_education"])
self.assertEqual("world peace", data["goals"])
self.assertEqual("Park Ave", data['mailing_address'])
self.assertEqual(self.user.email, data["email"])
self.assertTrue(data["is_active"])
self.assertIsNotNone(data["date_joined"])
self.assertEqual("Tired mother of twins", data["bio"])
self._verify_profile_image_data(data, not requires_parental_consent)
self.assertEquals(requires_parental_consent, data["requires_parental_consent"])
self.assertEqual([{"code": "en"}], data["language_proficiencies"])
def test_anonymous_access(self):
"""
Test that an anonymous client (not logged in) cannot call GET or PATCH.
"""
self.send_get(self.anonymous_client, expected_status=401)
self.send_patch(self.anonymous_client, {}, expected_status=401)
def test_unsupported_methods(self):
"""
Test that DELETE, POST, and PUT are not supported.
"""
self.client.login(username=self.user.username, password=self.test_password)
self.assertEqual(405, self.client.put(self.url).status_code)
self.assertEqual(405, self.client.post(self.url).status_code)
self.assertEqual(405, self.client.delete(self.url).status_code)
@ddt.data(
("client", "user"),
("staff_client", "staff_user"),
)
@ddt.unpack
def test_get_account_unknown_user(self, api_client, user):
"""
Test that requesting a user who does not exist returns a 404.
"""
client = self.login_client(api_client, user)
response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"}))
self.assertEqual(403 if user == "staff_user" else 404, response.status_code)
# Note: using getattr so that the patching works even if there is no configuration.
# This is needed when testing CMS as the patching is still executed even though the
# suite is skipped.
@patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"})
def test_get_account_different_user_visible(self):
"""
Test that a client (logged in) can only get the shareable fields for a different user.
This is the case when default_visibility is set to "all_users".
"""
self.different_client.login(username=self.different_user.username, password=self.test_password)
self.create_mock_profile(self.user)
response = self.send_get(self.different_client)
self._verify_full_shareable_account_response(response)
# Note: using getattr so that the patching works even if there is no configuration.
# This is needed when testing CMS as the patching is still executed even though the
# suite is skipped.
@patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"})
def test_get_account_different_user_private(self):
"""
Test that a client (logged in) can only get the shareable fields for a different user.
This is the case when default_visibility is set to "private".
"""
self.different_client.login(username=self.different_user.username, password=self.test_password)
self.create_mock_profile(self.user)
response = self.send_get(self.different_client)
self._verify_private_account_response(response)
@ddt.data(
("client", "user", PRIVATE_VISIBILITY),
("different_client", "different_user", PRIVATE_VISIBILITY),
("staff_client", "staff_user", PRIVATE_VISIBILITY),
("client", "user", ALL_USERS_VISIBILITY),
("different_client", "different_user", ALL_USERS_VISIBILITY),
("staff_client", "staff_user", ALL_USERS_VISIBILITY),
)
@ddt.unpack
def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility):
"""
Test the return from GET based on user visibility setting.
"""
def verify_fields_visible_to_all_users(response):
if preference_visibility == PRIVATE_VISIBILITY:
self._verify_private_account_response(response)
else:
self._verify_full_shareable_account_response(response)
client = self.login_client(api_client, requesting_username)
# Update user account visibility setting.
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility)
self.create_mock_profile(self.user)
response = self.send_get(client)
if requesting_username == "different_user":
verify_fields_visible_to_all_users(response)
else:
self._verify_full_account_response(response)
# Verify how the view parameter changes the fields that are returned.
response = self.send_get(client, query_parameters='view=shared')
verify_fields_visible_to_all_users(response)
def test_get_account_default(self):
"""
Test that a client (logged in) can get her own account information (using default legacy profile information,
as created by the test UserFactory).
"""
def verify_get_own_information():
response = self.send_get(self.client)
data = response.data
self.assertEqual(15, len(data))
self.assertEqual(self.user.username, data["username"])
self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"])
for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"):
self.assertIsNone(data[empty_field])
self.assertIsNone(data["country"])
self.assertEqual("m", data["gender"])
self.assertEqual("Learn a lot", data["goals"])
self.assertEqual(self.user.email, data["email"])
self.assertIsNotNone(data["date_joined"])
self.assertEqual(self.user.is_active, data["is_active"])
self._verify_profile_image_data(data, False)
self.assertTrue(data["requires_parental_consent"])
self.assertEqual([], data["language_proficiencies"])
self.client.login(username=self.user.username, password=self.test_password)
verify_get_own_information()
# Now make sure that the user can get the same information, even if not active
self.user.is_active = False
self.user.save()
verify_get_own_information()
def test_get_account_empty_string(self):
"""
Test the conversion of empty strings to None for certain fields.
"""
legacy_profile = UserProfile.objects.get(id=self.user.id)
legacy_profile.country = ""
legacy_profile.level_of_education = ""
legacy_profile.gender = ""
legacy_profile.save()
self.client.login(username=self.user.username, password=self.test_password)
response = self.send_get(self.client)
for empty_field in ("level_of_education", "gender", "country"):
self.assertIsNone(response.data[empty_field])
@ddt.data(
("different_client", "different_user"),
("staff_client", "staff_user"),
)
@ddt.unpack
def test_patch_account_disallowed_user(self, api_client, user):
"""
Test that a client cannot call PATCH on a different client's user account (even with
is_staff access).
"""
client = self.login_client(api_client, user)
self.send_patch(client, {}, expected_status=403 if user == "staff_user" else 404)
@ddt.data(
("client", "user"),
("staff_client", "staff_user"),
)
@ddt.unpack
def test_patch_account_unknown_user(self, api_client, user):
"""
Test that trying to update a user who does not exist returns a 404.
"""
client = self.login_client(api_client, user)
response = client.patch(
reverse("accounts_api", kwargs={'username': "does_not_exist"}),
data=json.dumps({}), content_type="application/merge-patch+json"
)
self.assertEqual(404, response.status_code)
@ddt.data(
("gender", "f", "not a gender", u"Select a valid choice. not a gender is not one of the available choices."),
("level_of_education", "none", u"ȻħȺɍłɇs", u"Select a valid choice. ȻħȺɍłɇs is not one of the available choices."),
("country", "GB", "XY", u"Select a valid choice. XY is not one of the available choices."),
("year_of_birth", 2009, "not_an_int", u"Enter a whole number."),
("name", "bob", "z" * 256, u"Ensure this value has at most 255 characters (it has 256)."),
("name", u"ȻħȺɍłɇs", "z ", u"The name field must be at least 2 characters long."),
("goals", "Smell the roses"),
("mailing_address", "Sesame Street"),
# Note that we store the raw data, so it is up to client to escape the HTML.
("bio", u"<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 3001, u"Ensure this value has at most 3000 characters (it has 3001)."),
# Note that email is tested below, as it is not immediately updated.
# Note that language_proficiencies is tested below as there are multiple error and success conditions.
)
@ddt.unpack
def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None):
"""
Test the behavior of patch, when using the correct content_type.
"""
client = self.login_client("client", "user")
self.send_patch(client, {field: value})
get_response = self.send_get(client)
self.assertEqual(value, get_response.data[field])
if fails_validation_value:
error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400)
self.assertEqual(
u'This value is invalid.',
error_response.data["field_errors"][field]["user_message"]
)
self.assertEqual(
u"Value '{value}' is not valid for field '{field}': {messages}".format(
value=fails_validation_value, field=field, messages=[developer_validation_message]
),
error_response.data["field_errors"][field]["developer_message"]
)
else:
# If there are no values that would fail validation, then empty string should be supported.
self.send_patch(client, {field: ""})
get_response = self.send_get(client)
self.assertEqual("", get_response.data[field])
def test_patch_inactive_user(self):
""" Verify that a user can patch her own account, even if inactive. """
self.client.login(username=self.user.username, password=self.test_password)
self.user.is_active = False
self.user.save()
self.send_patch(self.client, {"goals": "to not activate account"})
get_response = self.send_get(self.client)
self.assertEqual("to not activate account", get_response.data["goals"])
@ddt.unpack
def test_patch_account_noneditable(self):
"""
Tests the behavior of patch when a read-only field is attempted to be edited.
"""
client = self.login_client("client", "user")
def verify_error_response(field_name, data):
self.assertEqual(
"This field is not editable via this API", data["field_errors"][field_name]["developer_message"]
)
self.assertEqual(
"The '{0}' field cannot be edited.".format(field_name), data["field_errors"][field_name]["user_message"]
)
for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]:
response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400)
verify_error_response(field_name, response.data)
# Make sure that gender did not change.
response = self.send_get(client)
self.assertEqual("m", response.data["gender"])
# Test error message with multiple read-only items
response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400)
self.assertEqual(2, len(response.data["field_errors"]))
verify_error_response("username", response.data)
verify_error_response("date_joined", response.data)
def test_patch_bad_content_type(self):
"""
Test the behavior of patch when an incorrect content_type is specified.
"""
self.client.login(username=self.user.username, password=self.test_password)
self.send_patch(self.client, {}, content_type="application/json", expected_status=415)
self.send_patch(self.client, {}, content_type="application/xml", expected_status=415)
def test_patch_account_empty_string(self):
"""
Tests the behavior of patch when attempting to set fields with a select list of options to the empty string.
Also verifies the behaviour when setting to None.
"""
self.client.login(username=self.user.username, password=self.test_password)
for field_name in ["gender", "level_of_education", "country"]:
self.send_patch(self.client, {field_name: ""})
response = self.send_get(self.client)
# Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer
# is to convert to None, which also seems acceptable (and is difficult to override).
self.assertIsNone(response.data[field_name])
# Verify that the behavior is the same for sending None.
self.send_patch(self.client, {field_name: ""})
response = self.send_get(self.client)
self.assertIsNone(response.data[field_name])
def test_patch_name_metadata(self):
"""
Test the metadata stored when changing the name field.
"""
def get_name_change_info(expected_entries):
legacy_profile = UserProfile.objects.get(id=self.user.id)
name_change_info = legacy_profile.get_meta()["old_names"]
self.assertEqual(expected_entries, len(name_change_info))
return name_change_info
def verify_change_info(change_info, old_name, requester, new_name):
self.assertEqual(3, len(change_info))
self.assertEqual(old_name, change_info[0])
self.assertEqual("Name change requested through account API by {}".format(requester), change_info[1])
self.assertIsNotNone(change_info[2])
# Verify the new name was also stored.
get_response = self.send_get(self.client)
self.assertEqual(new_name, get_response.data["name"])
self.client.login(username=self.user.username, password=self.test_password)
legacy_profile = UserProfile.objects.get(id=self.user.id)
self.assertEqual({}, legacy_profile.get_meta())
old_name = legacy_profile.name
# First change the name as the user and verify meta information.
self.send_patch(self.client, {"name": "Mickey Mouse"})
name_change_info = get_name_change_info(1)
verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse")
# Now change the name again and verify meta information.
self.send_patch(self.client, {"name": "Donald Duck"})
name_change_info = get_name_change_info(2)
verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck",)
verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck")
def test_patch_email(self):
"""
Test that the user can request an email change through the accounts API.
Full testing of the helper method used (do_email_change_request) exists in the package with the code.
Here just do minimal smoke testing.
"""
client = self.login_client("client", "user")
old_email = self.user.email
new_email = "[email protected]"
self.send_patch(client, {"email": new_email, "goals": "change my email"})
# Since request is multi-step, the email won't change on GET immediately (though goals will update).
get_response = self.send_get(client)
self.assertEqual(old_email, get_response.data["email"])
self.assertEqual("change my email", get_response.data["goals"])
# Now call the method that will be invoked with the user clicks the activation key in the received email.
# First we must get the activation key that was sent.
pending_change = PendingEmailChange.objects.filter(user=self.user)
self.assertEqual(1, len(pending_change))
activation_key = pending_change[0].activation_key
confirm_change_url = reverse(
"student.views.confirm_email_change", kwargs={'key': activation_key}
)
response = self.client.post(confirm_change_url)
self.assertEqual(200, response.status_code)
get_response = self.send_get(client)
self.assertEqual(new_email, get_response.data["email"])
@ddt.data(
("not_an_email",),
("",),
(None,),
)
@ddt.unpack
def test_patch_invalid_email(self, bad_email):
"""
Test a few error cases for email validation (full test coverage lives with do_email_change_request).
"""
client = self.login_client("client", "user")
# Try changing to an invalid email to make sure error messages are appropriately returned.
error_response = self.send_patch(client, {"email": bad_email}, expected_status=400)
field_errors = error_response.data["field_errors"]
self.assertEqual(
"Error thrown from validate_new_email: 'Valid e-mail address required.'",
field_errors["email"]["developer_message"]
)
self.assertEqual("Valid e-mail address required.", field_errors["email"]["user_message"])
def test_patch_language_proficiencies(self):
"""
Verify that patching the language_proficiencies field of the user
profile completely overwrites the previous value.
"""
client = self.login_client("client", "user")
# Patching language_proficiencies exercises the
# `LanguageProficiencySerializer.get_identity` method, which compares
# identifies language proficiencies based on their language code rather
# than django model id.
for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []):
self.send_patch(client, {"language_proficiencies": proficiencies})
response = self.send_get(client)
self.assertItemsEqual(response.data["language_proficiencies"], proficiencies)
@ddt.data(
(u"not_a_list", [{u'non_field_errors': [u'Expected a list of items.']}]),
([u"not_a_JSON_object"], [{u'non_field_errors': [u'Invalid data']}]),
([{}], [{"code": [u"This field is required."]}]),
([{u"code": u"invalid_language_code"}], [{'code': [u'Select a valid choice. invalid_language_code is not one of the available choices.']}]),
([{u"code": u"kw"}, {u"code": u"el"}, {u"code": u"kw"}], [u'The language_proficiencies field must consist of unique languages']),
)
@ddt.unpack
def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message):
"""
Verify we handle error cases when patching the language_proficiencies
field.
"""
client = self.login_client("client", "user")
response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400)
self.assertEqual(
response.data["field_errors"]["language_proficiencies"]["developer_message"],
u"Value '{patch_value}' is not valid for field 'language_proficiencies': {error_message}".format(patch_value=patch_value, error_message=expected_error_message)
)
@patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save')
def test_patch_serializer_save_fails(self, serializer_save):
"""
Test that AccountUpdateErrors are passed through to the response.
"""
serializer_save.side_effect = [Exception("bummer"), None]
self.client.login(username=self.user.username, password=self.test_password)
error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400)
self.assertEqual(
"Error thrown when saving account updates: 'bummer'",
error_response.data["developer_message"]
)
self.assertIsNone(error_response.data["user_message"])
@override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND)
def test_convert_relative_profile_url(self):
"""
Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins
with a '/', the API generates the full URL to profile images based on
the URL of the request.
"""
self.client.login(username=self.user.username, password=self.test_password)
response = self.send_get(self.client)
# pylint: disable=no-member
self.assertEqual(
response.data["profile_image"],
{
"has_image": False,
"image_url_full": "http://testserver/static/default_50.png",
"image_url_small": "http://testserver/static/default_10.png"
}
)
@ddt.data(
("client", "user", True),
("different_client", "different_user", False),
("staff_client", "staff_user", True),
)
@ddt.unpack
def test_parental_consent(self, api_client, requesting_username, has_full_access):
"""
Verifies that under thirteens never return a public profile.
"""
client = self.login_client(api_client, requesting_username)
# Set the user to be ten years old with a public profile
legacy_profile = UserProfile.objects.get(id=self.user.id)
current_year = datetime.datetime.now().year
legacy_profile.year_of_birth = current_year - 10
legacy_profile.save()
set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY)
# Verify that the default view is still private (except for clients with full access)
response = self.send_get(client)
if has_full_access:
data = response.data
self.assertEqual(15, len(data))
self.assertEqual(self.user.username, data["username"])
self.assertEqual(self.user.first_name + " " + self.user.last_name, data["name"])
self.assertEqual(self.user.email, data["email"])
self.assertEqual(current_year - 10, data["year_of_birth"])
for empty_field in ("country", "level_of_education", "mailing_address", "bio"):
self.assertIsNone(data[empty_field])
self.assertEqual("m", data["gender"])
self.assertEqual("Learn a lot", data["goals"])
self.assertTrue(data["is_active"])
self.assertIsNotNone(data["date_joined"])
self._verify_profile_image_data(data, False)
self.assertTrue(data["requires_parental_consent"])
else:
self._verify_private_account_response(response, requires_parental_consent=True)
# Verify that the shared view is still private
response = self.send_get(client, query_parameters='view=shared')
self._verify_private_account_response(response, requires_parental_consent=True)
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
class TestAccountAPITransactions(TransactionTestCase):
"""
Tests the transactional behavior of the account API
"""
test_password = "test"
def setUp(self):
super(TestAccountAPITransactions, self).setUp()
self.client = APIClient()
self.user = UserFactory.create(password=self.test_password)
self.url = reverse("accounts_api", kwargs={'username': self.user.username})
@patch('student.views.do_email_change_request')
def test_update_account_settings_rollback(self, mock_email_change):
"""
Verify that updating account settings is transactional when a failure happens.
"""
# Send a PATCH request with updates to both profile information and email.
# Throw an error from the method that is used to process the email change request
# (this is the last thing done in the api method). Verify that the profile did not change.
mock_email_change.side_effect = [ValueError, "mock value error thrown"]
self.client.login(username=self.user.username, password=self.test_password)
old_email = self.user.email
json_data = {"email": "[email protected]", "gender": "o"}
response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json")
self.assertEqual(400, response.status_code)
# Verify that GET returns the original preferences
response = self.client.get(self.url)
data = response.data
self.assertEqual(old_email, data["email"])
self.assertEqual(u"m", data["gender"])
|
agpl-3.0
|
photoninger/ansible
|
lib/ansible/modules/windows/win_dns_client.py
|
47
|
2652
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_dns_client
version_added: "2.3"
short_description: Configures DNS lookup on Windows hosts
description:
- The C(win_dns_client) module configures the DNS client on Windows network adapters.
options:
adapter_names:
description:
- Adapter name or list of adapter names for which to manage DNS settings ('*' is supported as a wildcard value).
The adapter name used is the connection caption in the Network Control Panel or via C(Get-NetAdapter), eg C(Local Area Connection).
required: true
ipv4_addresses:
description:
- Single or ordered list of DNS server IPv4 addresses to configure for lookup. An empty list will configure the adapter to use the
DHCP-assigned values on connections where DHCP is enabled, or disable DNS lookup on statically-configured connections.
required: true
notes:
- When setting an empty list of DNS server addresses on an adapter with DHCP enabled, a change will always be registered, since it is not possible to
detect the difference between a DHCP-sourced server value and one that is statically set.
author: "Matt Davis (@nitzmahone)"
'''
EXAMPLES = r'''
# set a single address on the adapter named Ethernet
- win_dns_client:
adapter_names: Ethernet
ipv4_addresses: 192.168.34.5
# set multiple lookup addresses on all visible adapters (usually physical adapters that are in the Up state), with debug logging to a file
- win_dns_client:
adapter_names: "*"
ipv4_addresses:
- 192.168.34.5
- 192.168.34.6
log_path: c:\dns_log.txt
# configure all adapters whose names begin with Ethernet to use DHCP-assigned DNS values
- win_dns_client:
adapter_names: "Ethernet*"
ipv4_addresses: []
'''
RETURN = '''
'''
|
gpl-3.0
|
erwilan/ansible
|
lib/ansible/plugins/filter/ipaddr.py
|
36
|
18970
|
# (c) 2014, Maciej Delmanowski <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from functools import partial
import types
try:
import netaddr
except ImportError:
# in this case, we'll make the filters return error messages (see bottom)
netaddr = None
else:
class mac_linux(netaddr.mac_unix):
pass
mac_linux.word_fmt = '%.2x'
from ansible import errors
# ---- IP address and network query helpers ----
def _empty_ipaddr_query(v, vtype):
# We don't have any query to process, so just check what type the user
# expects, and return the IP address in a correct format
if v:
if vtype == 'address':
return str(v.ip)
elif vtype == 'network':
return str(v)
def _6to4_query(v, vtype, value):
if v.version == 4:
if v.size == 1:
ipconv = str(v.ip)
elif v.size > 1:
if v.ip != v.network:
ipconv = str(v.ip)
else:
ipconv = False
if ipaddr(ipconv, 'public'):
numbers = list(map(int, ipconv.split('.')))
try:
return '2002:{:02x}{:02x}:{:02x}{:02x}::1/48'.format(*numbers)
except:
return False
elif v.version == 6:
if vtype == 'address':
if ipaddr(str(v), '2002::/16'):
return value
elif vtype == 'network':
if v.ip != v.network:
if ipaddr(str(v.ip), '2002::/16'):
return value
else:
return False
def _ip_query(v):
if v.size == 1:
return str(v.ip)
if v.size > 1:
# /31 networks in netaddr have no broadcast address
if v.ip != v.network or not v.broadcast:
return str(v.ip)
def _gateway_query(v):
if v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
def _bool_ipaddr_query(v):
if v:
return True
def _broadcast_query(v):
if v.size > 1:
return str(v.broadcast)
def _cidr_query(v):
return str(v)
def _cidr_lookup_query(v, iplist, value):
try:
if v in iplist:
return value
except:
return False
def _host_query(v):
if v.size == 1:
return str(v)
elif v.size > 1:
if v.ip != v.network:
return str(v.ip) + '/' + str(v.prefixlen)
def _hostmask_query(v):
return str(v.hostmask)
def _int_query(v, vtype):
if vtype == 'address':
return int(v.ip)
elif vtype == 'network':
return str(int(v.ip)) + '/' + str(int(v.prefixlen))
def _ipv4_query(v, value):
if v.version == 6:
try:
return str(v.ipv4())
except:
return False
else:
return value
def _ipv6_query(v, value):
if v.version == 4:
return str(v.ipv6())
else:
return value
def _link_local_query(v, value):
v_ip = netaddr.IPAddress(str(v.ip))
if v.version == 4:
if ipaddr(str(v_ip), '169.254.0.0/24'):
return value
elif v.version == 6:
if ipaddr(str(v_ip), 'fe80::/10'):
return value
def _loopback_query(v, value):
v_ip = netaddr.IPAddress(str(v.ip))
if v_ip.is_loopback():
return value
def _multicast_query(v, value):
if v.is_multicast():
return value
def _net_query(v):
if v.size > 1:
if v.ip == v.network:
return str(v.network) + '/' + str(v.prefixlen)
def _netmask_query(v):
return str(v.netmask)
def _network_query(v):
if v.size > 1:
return str(v.network)
def _prefix_query(v):
return int(v.prefixlen)
def _private_query(v, value):
if v.is_private():
return value
def _public_query(v, value):
v_ip = netaddr.IPAddress(str(v.ip))
if (v_ip.is_unicast() and not v_ip.is_private() and
not v_ip.is_loopback() and not v_ip.is_netmask() and
not v_ip.is_hostmask()):
return value
def _revdns_query(v):
v_ip = netaddr.IPAddress(str(v.ip))
return v_ip.reverse_dns
def _size_query(v):
return v.size
def _subnet_query(v):
return str(v.cidr)
def _type_query(v):
if v.size == 1:
return 'address'
if v.size > 1:
if v.ip != v.network:
return 'address'
else:
return 'network'
def _unicast_query(v, value):
if v.is_unicast():
return value
def _version_query(v):
return v.version
def _wrap_query(v, vtype, value):
if v.version == 6:
if vtype == 'address':
return '[' + str(v.ip) + ']'
elif vtype == 'network':
return '[' + str(v.ip) + ']/' + str(v.prefixlen)
else:
return value
# ---- HWaddr query helpers ----
def _bare_query(v):
v.dialect = netaddr.mac_bare
return str(v)
def _bool_hwaddr_query(v):
if v:
return True
def _int_hwaddr_query(v):
return int(v)
def _cisco_query(v):
v.dialect = netaddr.mac_cisco
return str(v)
def _empty_hwaddr_query(v, value):
if v:
return value
def _linux_query(v):
v.dialect = mac_linux
return str(v)
def _postgresql_query(v):
v.dialect = netaddr.mac_pgsql
return str(v)
def _unix_query(v):
v.dialect = netaddr.mac_unix
return str(v)
def _win_query(v):
v.dialect = netaddr.mac_eui48
return str(v)
# ---- IP address and network filters ----
def ipaddr(value, query = '', version = False, alias = 'ipaddr'):
''' Check if string is an IP address or network and filter it '''
query_func_extra_args = {
'': ('vtype',),
'6to4': ('vtype', 'value'),
'cidr_lookup': ('iplist', 'value'),
'int': ('vtype',),
'ipv4': ('value',),
'ipv6': ('value',),
'link-local': ('value',),
'loopback': ('value',),
'lo': ('value',),
'multicast': ('value',),
'private': ('value',),
'public': ('value',),
'unicast': ('value',),
'wrap': ('vtype', 'value'),
}
query_func_map = {
'': _empty_ipaddr_query,
'6to4': _6to4_query,
'address': _ip_query,
'address/prefix': _gateway_query,
'bool': _bool_ipaddr_query,
'broadcast': _broadcast_query,
'cidr': _cidr_query,
'cidr_lookup': _cidr_lookup_query,
'gateway': _gateway_query,
'gw': _gateway_query,
'host': _host_query,
'host/prefix': _gateway_query,
'hostmask': _hostmask_query,
'hostnet': _gateway_query,
'int': _int_query,
'ip': _ip_query,
'ipv4': _ipv4_query,
'ipv6': _ipv6_query,
'link-local': _link_local_query,
'lo': _loopback_query,
'loopback': _loopback_query,
'multicast': _multicast_query,
'net': _net_query,
'netmask': _netmask_query,
'network': _network_query,
'prefix': _prefix_query,
'private': _private_query,
'public': _public_query,
'revdns': _revdns_query,
'router': _gateway_query,
'size': _size_query,
'subnet': _subnet_query,
'type': _type_query,
'unicast': _unicast_query,
'v4': _ipv4_query,
'v6': _ipv6_query,
'version': _version_query,
'wrap': _wrap_query,
}
vtype = None
if not value:
return False
elif value is True:
return False
# Check if value is a list and parse each element
elif isinstance(value, (list, tuple, types.GeneratorType)):
_ret = []
for element in value:
if ipaddr(element, str(query), version):
_ret.append(ipaddr(element, str(query), version))
if _ret:
return _ret
else:
return list()
# Check if value is a number and convert it to an IP address
elif str(value).isdigit():
# We don't know what IP version to assume, so let's check IPv4 first,
# then IPv6
try:
if ((not version) or (version and version == 4)):
v = netaddr.IPNetwork('0.0.0.0/0')
v.value = int(value)
v.prefixlen = 32
elif version and version == 6:
v = netaddr.IPNetwork('::/0')
v.value = int(value)
v.prefixlen = 128
# IPv4 didn't work the first time, so it definitely has to be IPv6
except:
try:
v = netaddr.IPNetwork('::/0')
v.value = int(value)
v.prefixlen = 128
# The value is too big for IPv6. Are you a nanobot?
except:
return False
# We got an IP address, let's mark it as such
value = str(v)
vtype = 'address'
# value has not been recognized, check if it's a valid IP string
else:
try:
v = netaddr.IPNetwork(value)
# value is a valid IP string, check if user specified
# CIDR prefix or just an IP address, this will indicate default
# output format
try:
address, prefix = value.split('/')
vtype = 'network'
except:
vtype = 'address'
# value hasn't been recognized, maybe it's a numerical CIDR?
except:
try:
address, prefix = value.split('/')
address.isdigit()
address = int(address)
prefix.isdigit()
prefix = int(prefix)
# It's not numerical CIDR, give up
except:
return False
# It is something, so let's try and build a CIDR from the parts
try:
v = netaddr.IPNetwork('0.0.0.0/0')
v.value = address
v.prefixlen = prefix
# It's not a valid IPv4 CIDR
except:
try:
v = netaddr.IPNetwork('::/0')
v.value = address
v.prefixlen = prefix
# It's not a valid IPv6 CIDR. Give up.
except:
return False
# We have a valid CIDR, so let's write it in correct format
value = str(v)
vtype = 'network'
# We have a query string but it's not in the known query types. Check if
# that string is a valid subnet, if so, we can check later if given IP
# address/network is inside that specific subnet
try:
### ?? 6to4 and link-local were True here before. Should they still?
if query and (query not in query_func_map or query == 'cidr_lookup') and ipaddr(query, 'network'):
iplist = netaddr.IPSet([netaddr.IPNetwork(query)])
query = 'cidr_lookup'
except:
pass
# This code checks if value maches the IP version the user wants, ie. if
# it's any version ("ipaddr()"), IPv4 ("ipv4()") or IPv6 ("ipv6()")
# If version does not match, return False
if version and v.version != version:
return False
extras = []
for arg in query_func_extra_args.get(query, tuple()):
extras.append(locals()[arg])
try:
return query_func_map[query](v, *extras)
except KeyError:
try:
float(query)
if v.size == 1:
if vtype == 'address':
return str(v.ip)
elif vtype == 'network':
return str(v)
elif v.size > 1:
try:
return str(v[query]) + '/' + str(v.prefixlen)
except:
return False
else:
return value
except:
raise errors.AnsibleFilterError(alias + ': unknown filter type: %s' % query)
return False
def ipwrap(value, query = ''):
try:
if isinstance(value, (list, tuple, types.GeneratorType)):
_ret = []
for element in value:
if ipaddr(element, query, version = False, alias = 'ipwrap'):
_ret.append(ipaddr(element, 'wrap'))
else:
_ret.append(element)
return _ret
else:
_ret = ipaddr(value, query, version = False, alias = 'ipwrap')
if _ret:
return ipaddr(_ret, 'wrap')
else:
return value
except:
return value
def ipv4(value, query = ''):
return ipaddr(value, query, version = 4, alias = 'ipv4')
def ipv6(value, query = ''):
return ipaddr(value, query, version = 6, alias = 'ipv6')
# Split given subnet into smaller subnets or find out the biggest subnet of
# a given IP address with given CIDR prefix
# Usage:
#
# - address or address/prefix | ipsubnet
# returns CIDR subnet of a given input
#
# - address/prefix | ipsubnet(cidr)
# returns number of possible subnets for given CIDR prefix
#
# - address/prefix | ipsubnet(cidr, index)
# returns new subnet with given CIDR prefix
#
# - address | ipsubnet(cidr)
# returns biggest subnet with given CIDR prefix that address belongs to
#
# - address | ipsubnet(cidr, index)
# returns next indexed subnet which contains given address
def ipsubnet(value, query = '', index = 'x'):
''' Manipulate IPv4/IPv6 subnets '''
try:
vtype = ipaddr(value, 'type')
if vtype == 'address':
v = ipaddr(value, 'cidr')
elif vtype == 'network':
v = ipaddr(value, 'subnet')
value = netaddr.IPNetwork(v)
except:
return False
if not query:
return str(value)
elif str(query).isdigit():
vsize = ipaddr(v, 'size')
query = int(query)
try:
float(index)
index = int(index)
if vsize > 1:
try:
return str(list(value.subnet(query))[index])
except:
return False
elif vsize == 1:
try:
return str(value.supernet(query)[index])
except:
return False
except:
if vsize > 1:
try:
return str(len(list(value.subnet(query))))
except:
return False
elif vsize == 1:
try:
return str(value.supernet(query)[0])
except:
return False
return False
# Returns the nth host within a network described by value.
# Usage:
#
# - address or address/prefix | nthhost(nth)
# returns the nth host within the given network
def nthhost(value, query=''):
''' Get the nth host within a given network '''
try:
vtype = ipaddr(value, 'type')
if vtype == 'address':
v = ipaddr(value, 'cidr')
elif vtype == 'network':
v = ipaddr(value, 'subnet')
value = netaddr.IPNetwork(v)
except:
return False
if not query:
return False
try:
nth = int(query)
if value.size > nth:
return value[nth]
except ValueError:
return False
return False
# Returns the SLAAC address within a network for a given HW/MAC address.
# Usage:
#
# - prefix | slaac(mac)
def slaac(value, query = ''):
''' Get the SLAAC address within given network '''
try:
vtype = ipaddr(value, 'type')
if vtype == 'address':
v = ipaddr(value, 'cidr')
elif vtype == 'network':
v = ipaddr(value, 'subnet')
if ipaddr(value, 'version') != 6:
return False
value = netaddr.IPNetwork(v)
except:
return False
if not query:
return False
try:
mac = hwaddr(query, alias = 'slaac')
eui = netaddr.EUI(mac)
except:
return False
return eui.ipv6(value.network)
# ---- HWaddr / MAC address filters ----
def hwaddr(value, query = '', alias = 'hwaddr'):
''' Check if string is a HW/MAC address and filter it '''
query_func_extra_args = {
'': ('value',),
}
query_func_map = {
'': _empty_hwaddr_query,
'bare': _bare_query,
'bool': _bool_hwaddr_query,
'int': _int_hwaddr_query,
'cisco': _cisco_query,
'eui48': _win_query,
'linux': _linux_query,
'pgsql': _postgresql_query,
'postgresql': _postgresql_query,
'psql': _postgresql_query,
'unix': _unix_query,
'win': _win_query,
}
try:
v = netaddr.EUI(value)
except:
if query and query != 'bool':
raise errors.AnsibleFilterError(alias + ': not a hardware address: %s' % value)
extras = []
for arg in query_func_extra_args.get(query, tuple()):
extras.append(locals()[arg])
try:
return query_func_map[query](v, *extras)
except KeyError:
raise errors.AnsibleFilterError(alias + ': unknown filter type: %s' % query)
return False
def macaddr(value, query = ''):
return hwaddr(value, query, alias = 'macaddr')
def _need_netaddr(f_name, *args, **kwargs):
raise errors.AnsibleFilterError('The {0} filter requires python-netaddr be'
' installed on the ansible controller'.format(f_name))
def ip4_hex(arg):
''' Convert an IPv4 address to Hexadecimal notation '''
numbers = list(map(int, arg.split('.')))
return '{:02x}{:02x}{:02x}{:02x}'.format(*numbers)
# ---- Ansible filters ----
class FilterModule(object):
''' IP address and network manipulation filters '''
filter_map = {
# IP addresses and networks
'ipaddr': ipaddr,
'ipwrap': ipwrap,
'ipv4': ipv4,
'ipv6': ipv6,
'ipsubnet': ipsubnet,
'nthhost': nthhost,
'slaac': slaac,
'ip4_hex': ip4_hex,
# MAC / HW addresses
'hwaddr': hwaddr,
'macaddr': macaddr
}
def filters(self):
if netaddr:
return self.filter_map
else:
# Need to install python-netaddr for these filters to work
return dict((f, partial(_need_netaddr, f)) for f in self.filter_map)
|
gpl-3.0
|
flashycud/timestack
|
django/contrib/gis/db/backends/mysql/operations.py
|
312
|
2418
|
from django.db.backends.mysql.base import DatabaseOperations
from django.contrib.gis.db.backends.adapter import WKTAdapter
from django.contrib.gis.db.backends.base import BaseSpatialOperations
class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
compiler_module = 'django.contrib.gis.db.models.sql.compiler'
mysql = True
name = 'mysql'
select = 'AsText(%s)'
from_wkb = 'GeomFromWKB'
from_text = 'GeomFromText'
Adapter = WKTAdapter
Adaptor = Adapter # Backwards-compatibility alias.
geometry_functions = {
'bbcontains' : 'MBRContains', # For consistency w/PostGIS API
'bboverlaps' : 'MBROverlaps', # .. ..
'contained' : 'MBRWithin', # .. ..
'contains' : 'MBRContains',
'disjoint' : 'MBRDisjoint',
'equals' : 'MBREqual',
'exact' : 'MBREqual',
'intersects' : 'MBRIntersects',
'overlaps' : 'MBROverlaps',
'same_as' : 'MBREqual',
'touches' : 'MBRTouches',
'within' : 'MBRWithin',
}
gis_terms = dict([(term, None) for term in geometry_functions.keys() + ['isnull']])
def geo_db_type(self, f):
return f.geom_type
def get_geom_placeholder(self, value, srid):
"""
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
"""
if hasattr(value, 'expression'):
placeholder = '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))
else:
placeholder = '%s(%%s)' % self.from_text
return placeholder
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
alias, col, db_type = lvalue
geo_col = '%s.%s' % (qn(alias), qn(col))
lookup_info = self.geometry_functions.get(lookup_type, False)
if lookup_info:
return "%s(%s, %s)" % (lookup_info, geo_col,
self.get_geom_placeholder(value, field.srid))
# TODO: Is this really necessary? MySQL can't handle NULL geometries
# in its spatial indexes anyways.
if lookup_type == 'isnull':
return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or ''))
raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type))
|
mit
|
googleapis/python-aiplatform
|
tests/unit/aiplatform/test_automl_tabular_training_jobs.py
|
1
|
24012
|
import importlib
import pytest
from unittest import mock
from google.cloud import aiplatform
from google.cloud.aiplatform import datasets
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import schema
from google.cloud.aiplatform import training_jobs
from google.cloud.aiplatform_v1.services.model_service import (
client as model_service_client,
)
from google.cloud.aiplatform_v1.services.pipeline_service import (
client as pipeline_service_client,
)
from google.cloud.aiplatform_v1.types import (
dataset as gca_dataset,
encryption_spec as gca_encryption_spec,
model as gca_model,
pipeline_state as gca_pipeline_state,
training_pipeline as gca_training_pipeline,
)
from google.protobuf import json_format
from google.protobuf import struct_pb2
_TEST_BUCKET_NAME = "test-bucket"
_TEST_GCS_PATH_WITHOUT_BUCKET = "path/to/folder"
_TEST_GCS_PATH = f"{_TEST_BUCKET_NAME}/{_TEST_GCS_PATH_WITHOUT_BUCKET}"
_TEST_GCS_PATH_WITH_TRAILING_SLASH = f"{_TEST_GCS_PATH}/"
_TEST_PROJECT = "test-project"
_TEST_DATASET_DISPLAY_NAME = "test-dataset-display-name"
_TEST_DATASET_NAME = "test-dataset-name"
_TEST_DISPLAY_NAME = "test-display-name"
_TEST_METADATA_SCHEMA_URI_TABULAR = schema.dataset.metadata.tabular
_TEST_METADATA_SCHEMA_URI_NONTABULAR = schema.dataset.metadata.image
_TEST_TRAINING_COLUMN_NAMES = [
"sepal_width",
"sepal_length",
"petal_length",
"petal_width",
]
_TEST_TRAINING_COLUMN_TRANSFORMATIONS = [
{"auto": {"column_name": "sepal_width"}},
{"auto": {"column_name": "sepal_length"}},
{"auto": {"column_name": "petal_length"}},
{"auto": {"column_name": "petal_width"}},
]
_TEST_TRAINING_TARGET_COLUMN = "target"
_TEST_TRAINING_BUDGET_MILLI_NODE_HOURS = 1000
_TEST_TRAINING_WEIGHT_COLUMN = "weight"
_TEST_TRAINING_DISABLE_EARLY_STOPPING = True
_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME = "minimize-log-loss"
_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE = "classification"
_TEST_ADDITIONAL_EXPERIMENTS = ["exp1", "exp2"]
_TEST_TRAINING_TASK_INPUTS_DICT = {
# required inputs
"targetColumn": _TEST_TRAINING_TARGET_COLUMN,
"transformations": _TEST_TRAINING_COLUMN_TRANSFORMATIONS,
"trainBudgetMilliNodeHours": _TEST_TRAINING_BUDGET_MILLI_NODE_HOURS,
# optional inputs
"weightColumnName": _TEST_TRAINING_WEIGHT_COLUMN,
"disableEarlyStopping": _TEST_TRAINING_DISABLE_EARLY_STOPPING,
"predictionType": _TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
"optimizationObjective": _TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
"optimizationObjectiveRecallValue": None,
"optimizationObjectivePrecisionValue": None,
}
_TEST_TRAINING_TASK_INPUTS = json_format.ParseDict(
_TEST_TRAINING_TASK_INPUTS_DICT, struct_pb2.Value(),
)
_TEST_TRAINING_TASK_INPUTS_WITH_ADDITIONAL_EXPERIMENTS = json_format.ParseDict(
{
**_TEST_TRAINING_TASK_INPUTS_DICT,
"additionalExperiments": _TEST_ADDITIONAL_EXPERIMENTS,
},
struct_pb2.Value(),
)
_TEST_DATASET_NAME = "test-dataset-name"
_TEST_MODEL_DISPLAY_NAME = "model-display-name"
_TEST_TRAINING_FRACTION_SPLIT = 0.6
_TEST_VALIDATION_FRACTION_SPLIT = 0.2
_TEST_TEST_FRACTION_SPLIT = 0.2
_TEST_PREDEFINED_SPLIT_COLUMN_NAME = "split"
_TEST_OUTPUT_PYTHON_PACKAGE_PATH = "gs://test/ouput/python/trainer.tar.gz"
_TEST_MODEL_NAME = "projects/my-project/locations/us-central1/models/12345"
_TEST_PIPELINE_RESOURCE_NAME = (
"projects/my-project/locations/us-central1/trainingPipeline/12345"
)
# CMEK encryption
_TEST_DEFAULT_ENCRYPTION_KEY_NAME = "key_default"
_TEST_DEFAULT_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_DEFAULT_ENCRYPTION_KEY_NAME
)
_TEST_PIPELINE_ENCRYPTION_KEY_NAME = "key_pipeline"
_TEST_PIPELINE_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_PIPELINE_ENCRYPTION_KEY_NAME
)
_TEST_MODEL_ENCRYPTION_KEY_NAME = "key_model"
_TEST_MODEL_ENCRYPTION_SPEC = gca_encryption_spec.EncryptionSpec(
kms_key_name=_TEST_MODEL_ENCRYPTION_KEY_NAME
)
@pytest.fixture
def mock_pipeline_service_create():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "create_training_pipeline"
) as mock_create_training_pipeline:
mock_create_training_pipeline.return_value = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
)
yield mock_create_training_pipeline
@pytest.fixture
def mock_pipeline_service_get():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.return_value = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED,
model_to_upload=gca_model.Model(name=_TEST_MODEL_NAME),
)
yield mock_get_training_pipeline
@pytest.fixture
def mock_pipeline_service_create_and_get_with_fail():
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "create_training_pipeline"
) as mock_create_training_pipeline:
mock_create_training_pipeline.return_value = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_RUNNING,
)
with mock.patch.object(
pipeline_service_client.PipelineServiceClient, "get_training_pipeline"
) as mock_get_training_pipeline:
mock_get_training_pipeline.return_value = gca_training_pipeline.TrainingPipeline(
name=_TEST_PIPELINE_RESOURCE_NAME,
state=gca_pipeline_state.PipelineState.PIPELINE_STATE_FAILED,
)
yield mock_create_training_pipeline, mock_get_training_pipeline
@pytest.fixture
def mock_model_service_get():
with mock.patch.object(
model_service_client.ModelServiceClient, "get_model"
) as mock_get_model:
mock_get_model.return_value = gca_model.Model()
yield mock_get_model
@pytest.fixture
def mock_dataset_tabular():
ds = mock.MagicMock(datasets.TabularDataset)
ds.name = _TEST_DATASET_NAME
ds._latest_future = None
ds._exception = None
ds._gca_resource = gca_dataset.Dataset(
display_name=_TEST_DATASET_DISPLAY_NAME,
metadata_schema_uri=_TEST_METADATA_SCHEMA_URI_TABULAR,
labels={},
name=_TEST_DATASET_NAME,
metadata={},
)
ds.column_names = _TEST_TRAINING_COLUMN_NAMES
yield ds
@pytest.fixture
def mock_dataset_nontabular():
ds = mock.MagicMock(datasets.ImageDataset)
ds.name = _TEST_DATASET_NAME
ds._latest_future = None
ds._exception = None
ds._gca_resource = gca_dataset.Dataset(
display_name=_TEST_DATASET_DISPLAY_NAME,
metadata_schema_uri=_TEST_METADATA_SCHEMA_URI_NONTABULAR,
labels={},
name=_TEST_DATASET_NAME,
metadata={},
)
return ds
class TestAutoMLTabularTrainingJob:
def setup_method(self):
importlib.reload(initializer)
importlib.reload(aiplatform)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
@pytest.mark.parametrize("sync", [True, False])
def test_run_call_pipeline_service_create(
self,
mock_pipeline_service_create,
mock_pipeline_service_get,
mock_dataset_tabular,
mock_model_service_get,
sync,
):
aiplatform.init(
project=_TEST_PROJECT,
staging_bucket=_TEST_BUCKET_NAME,
encryption_spec_key_name=_TEST_DEFAULT_ENCRYPTION_KEY_NAME,
)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
column_transformations=_TEST_TRAINING_COLUMN_TRANSFORMATIONS,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
model_from_job = job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
model_display_name=_TEST_MODEL_DISPLAY_NAME,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
predefined_split_column_name=_TEST_PREDEFINED_SPLIT_COLUMN_NAME,
weight_column=_TEST_TRAINING_WEIGHT_COLUMN,
budget_milli_node_hours=_TEST_TRAINING_BUDGET_MILLI_NODE_HOURS,
disable_early_stopping=_TEST_TRAINING_DISABLE_EARLY_STOPPING,
sync=sync,
)
if not sync:
model_from_job.wait()
true_fraction_split = gca_training_pipeline.FractionSplit(
training_fraction=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction=_TEST_TEST_FRACTION_SPLIT,
)
true_managed_model = gca_model.Model(
display_name=_TEST_MODEL_DISPLAY_NAME,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
true_input_data_config = gca_training_pipeline.InputDataConfig(
fraction_split=true_fraction_split,
predefined_split=gca_training_pipeline.PredefinedSplit(
key=_TEST_PREDEFINED_SPLIT_COLUMN_NAME
),
dataset_id=mock_dataset_tabular.name,
)
true_training_pipeline = gca_training_pipeline.TrainingPipeline(
display_name=_TEST_DISPLAY_NAME,
training_task_definition=schema.training_job.definition.automl_tabular,
training_task_inputs=_TEST_TRAINING_TASK_INPUTS,
model_to_upload=true_managed_model,
input_data_config=true_input_data_config,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
mock_pipeline_service_create.assert_called_once_with(
parent=initializer.global_config.common_location_path(),
training_pipeline=true_training_pipeline,
)
assert job._gca_resource is mock_pipeline_service_get.return_value
mock_model_service_get.assert_called_once_with(name=_TEST_MODEL_NAME)
assert model_from_job._gca_resource is mock_model_service_get.return_value
assert job.get_model()._gca_resource is mock_model_service_get.return_value
assert not job.has_failed
assert job.state == gca_pipeline_state.PipelineState.PIPELINE_STATE_SUCCEEDED
@pytest.mark.usefixtures("mock_pipeline_service_get")
@pytest.mark.parametrize("sync", [True, False])
def test_run_call_pipeline_if_no_model_display_name(
self,
mock_pipeline_service_create,
mock_dataset_tabular,
mock_model_service_get,
sync,
):
aiplatform.init(project=_TEST_PROJECT, staging_bucket=_TEST_BUCKET_NAME)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
column_transformations=_TEST_TRAINING_COLUMN_TRANSFORMATIONS,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
training_encryption_spec_key_name=_TEST_PIPELINE_ENCRYPTION_KEY_NAME,
model_encryption_spec_key_name=_TEST_MODEL_ENCRYPTION_KEY_NAME,
)
model_from_job = job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
weight_column=_TEST_TRAINING_WEIGHT_COLUMN,
budget_milli_node_hours=_TEST_TRAINING_BUDGET_MILLI_NODE_HOURS,
disable_early_stopping=_TEST_TRAINING_DISABLE_EARLY_STOPPING,
)
if not sync:
model_from_job.wait()
true_fraction_split = gca_training_pipeline.FractionSplit(
training_fraction=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction=_TEST_TEST_FRACTION_SPLIT,
)
# Test that if defaults to the job display name
true_managed_model = gca_model.Model(
display_name=_TEST_DISPLAY_NAME, encryption_spec=_TEST_MODEL_ENCRYPTION_SPEC
)
true_input_data_config = gca_training_pipeline.InputDataConfig(
fraction_split=true_fraction_split, dataset_id=mock_dataset_tabular.name,
)
true_training_pipeline = gca_training_pipeline.TrainingPipeline(
display_name=_TEST_DISPLAY_NAME,
training_task_definition=schema.training_job.definition.automl_tabular,
training_task_inputs=_TEST_TRAINING_TASK_INPUTS,
model_to_upload=true_managed_model,
input_data_config=true_input_data_config,
encryption_spec=_TEST_PIPELINE_ENCRYPTION_SPEC,
)
mock_pipeline_service_create.assert_called_once_with(
parent=initializer.global_config.common_location_path(),
training_pipeline=true_training_pipeline,
)
@pytest.mark.parametrize("sync", [True, False])
# This test checks that default transformations are used if no columns transformations are provided
def test_run_call_pipeline_service_create_if_no_column_transformations(
self,
mock_pipeline_service_create,
mock_pipeline_service_get,
mock_dataset_tabular,
mock_model_service_get,
sync,
):
aiplatform.init(
project=_TEST_PROJECT,
staging_bucket=_TEST_BUCKET_NAME,
encryption_spec_key_name=_TEST_DEFAULT_ENCRYPTION_KEY_NAME,
)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
column_transformations=None,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
model_from_job = job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
model_display_name=_TEST_MODEL_DISPLAY_NAME,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
predefined_split_column_name=_TEST_PREDEFINED_SPLIT_COLUMN_NAME,
weight_column=_TEST_TRAINING_WEIGHT_COLUMN,
budget_milli_node_hours=_TEST_TRAINING_BUDGET_MILLI_NODE_HOURS,
disable_early_stopping=_TEST_TRAINING_DISABLE_EARLY_STOPPING,
sync=sync,
)
if not sync:
model_from_job.wait()
true_fraction_split = gca_training_pipeline.FractionSplit(
training_fraction=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction=_TEST_TEST_FRACTION_SPLIT,
)
true_managed_model = gca_model.Model(
display_name=_TEST_MODEL_DISPLAY_NAME,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
true_input_data_config = gca_training_pipeline.InputDataConfig(
fraction_split=true_fraction_split,
predefined_split=gca_training_pipeline.PredefinedSplit(
key=_TEST_PREDEFINED_SPLIT_COLUMN_NAME
),
dataset_id=mock_dataset_tabular.name,
)
true_training_pipeline = gca_training_pipeline.TrainingPipeline(
display_name=_TEST_DISPLAY_NAME,
training_task_definition=schema.training_job.definition.automl_tabular,
training_task_inputs=_TEST_TRAINING_TASK_INPUTS,
model_to_upload=true_managed_model,
input_data_config=true_input_data_config,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
mock_pipeline_service_create.assert_called_once_with(
parent=initializer.global_config.common_location_path(),
training_pipeline=true_training_pipeline,
)
@pytest.mark.parametrize("sync", [True, False])
# This test checks that default transformations are used if no columns transformations are provided
def test_run_call_pipeline_service_create_if_set_additional_experiments(
self,
mock_pipeline_service_create,
mock_pipeline_service_get,
mock_dataset_tabular,
mock_model_service_get,
sync,
):
aiplatform.init(
project=_TEST_PROJECT,
staging_bucket=_TEST_BUCKET_NAME,
encryption_spec_key_name=_TEST_DEFAULT_ENCRYPTION_KEY_NAME,
)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
column_transformations=None,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
job._add_additional_experiments(_TEST_ADDITIONAL_EXPERIMENTS)
model_from_job = job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
model_display_name=_TEST_MODEL_DISPLAY_NAME,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
predefined_split_column_name=_TEST_PREDEFINED_SPLIT_COLUMN_NAME,
weight_column=_TEST_TRAINING_WEIGHT_COLUMN,
budget_milli_node_hours=_TEST_TRAINING_BUDGET_MILLI_NODE_HOURS,
disable_early_stopping=_TEST_TRAINING_DISABLE_EARLY_STOPPING,
sync=sync,
)
if not sync:
model_from_job.wait()
true_fraction_split = gca_training_pipeline.FractionSplit(
training_fraction=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction=_TEST_TEST_FRACTION_SPLIT,
)
true_managed_model = gca_model.Model(
display_name=_TEST_MODEL_DISPLAY_NAME,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
true_input_data_config = gca_training_pipeline.InputDataConfig(
fraction_split=true_fraction_split,
predefined_split=gca_training_pipeline.PredefinedSplit(
key=_TEST_PREDEFINED_SPLIT_COLUMN_NAME
),
dataset_id=mock_dataset_tabular.name,
)
true_training_pipeline = gca_training_pipeline.TrainingPipeline(
display_name=_TEST_DISPLAY_NAME,
training_task_definition=schema.training_job.definition.automl_tabular,
training_task_inputs=_TEST_TRAINING_TASK_INPUTS_WITH_ADDITIONAL_EXPERIMENTS,
model_to_upload=true_managed_model,
input_data_config=true_input_data_config,
encryption_spec=_TEST_DEFAULT_ENCRYPTION_SPEC,
)
mock_pipeline_service_create.assert_called_once_with(
parent=initializer.global_config.common_location_path(),
training_pipeline=true_training_pipeline,
)
@pytest.mark.usefixtures(
"mock_pipeline_service_create",
"mock_pipeline_service_get",
"mock_model_service_get",
)
@pytest.mark.parametrize("sync", [True, False])
def test_run_called_twice_raises(self, mock_dataset_tabular, sync):
aiplatform.init(project=_TEST_PROJECT, staging_bucket=_TEST_BUCKET_NAME)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
column_transformations=_TEST_TRAINING_COLUMN_TRANSFORMATIONS,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
model_display_name=_TEST_MODEL_DISPLAY_NAME,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
sync=sync,
)
with pytest.raises(RuntimeError):
job.run(
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
model_display_name=_TEST_MODEL_DISPLAY_NAME,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
sync=sync,
)
@pytest.mark.parametrize("sync", [True, False])
def test_run_raises_if_pipeline_fails(
self, mock_pipeline_service_create_and_get_with_fail, mock_dataset_tabular, sync
):
aiplatform.init(project=_TEST_PROJECT, staging_bucket=_TEST_BUCKET_NAME)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
column_transformations=_TEST_TRAINING_COLUMN_TRANSFORMATIONS,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
with pytest.raises(RuntimeError):
job.run(
model_display_name=_TEST_MODEL_DISPLAY_NAME,
dataset=mock_dataset_tabular,
target_column=_TEST_TRAINING_TARGET_COLUMN,
training_fraction_split=_TEST_TRAINING_FRACTION_SPLIT,
validation_fraction_split=_TEST_VALIDATION_FRACTION_SPLIT,
test_fraction_split=_TEST_TEST_FRACTION_SPLIT,
sync=sync,
)
if not sync:
job.wait()
with pytest.raises(RuntimeError):
job.get_model()
def test_raises_before_run_is_called(self, mock_pipeline_service_create):
aiplatform.init(project=_TEST_PROJECT, staging_bucket=_TEST_BUCKET_NAME)
job = training_jobs.AutoMLTabularTrainingJob(
display_name=_TEST_DISPLAY_NAME,
optimization_prediction_type=_TEST_TRAINING_OPTIMIZATION_PREDICTION_TYPE,
optimization_objective=_TEST_TRAINING_OPTIMIZATION_OBJECTIVE_NAME,
column_transformations=_TEST_TRAINING_COLUMN_TRANSFORMATIONS,
optimization_objective_recall_value=None,
optimization_objective_precision_value=None,
)
with pytest.raises(RuntimeError):
job.get_model()
with pytest.raises(RuntimeError):
job.has_failed
with pytest.raises(RuntimeError):
job.state
|
apache-2.0
|
40223136/2015w11
|
static/Brython3.1.1-20150328-091302/Lib/multiprocessing/process.py
|
694
|
2304
|
#
# Module providing the `Process` class which emulates `threading.Thread`
#
# multiprocessing/process.py
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#
__all__ = ['Process', 'current_process', 'active_children']
#
# Imports
#
import os
import sys
import signal
import itertools
from _weakrefset import WeakSet
#for brython
from _multiprocessing import Process
#
#
#
try:
ORIGINAL_DIR = os.path.abspath(os.getcwd())
except OSError:
ORIGINAL_DIR = None
#
# Public functions
#
def current_process():
'''
Return process object representing the current process
'''
return _current_process
def active_children():
'''
Return list of process objects corresponding to live child processes
'''
_cleanup()
return list(_current_process._children)
#
#
#
def _cleanup():
# check for processes which have finished
for p in list(_current_process._children):
if p._popen.poll() is not None:
_current_process._children.discard(p)
#
# The `Process` class
#
# brython note: class Process is defined in /usr/libs/_multiprocessing.js
#
# We subclass bytes to avoid accidental transmission of auth keys over network
#
class AuthenticationString(bytes):
def __reduce__(self):
from .forking import Popen
if not Popen.thread_is_spawning():
raise TypeError(
'Pickling an AuthenticationString object is '
'disallowed for security reasons'
)
return AuthenticationString, (bytes(self),)
#
# Create object representing the main process
#
class _MainProcess(Process):
def __init__(self):
self._identity = ()
self._daemonic = False
self._name = 'MainProcess'
self._parent_pid = None
self._popen = None
self._counter = itertools.count(1)
self._children = set()
self._authkey = AuthenticationString(os.urandom(32))
self._tempdir = None
_current_process = _MainProcess()
del _MainProcess
#
# Give names to some return codes
#
_exitcode_to_name = {}
for name, signum in list(signal.__dict__.items()):
if name[:3]=='SIG' and '_' not in name:
_exitcode_to_name[-signum] = name
# For debug and leak testing
_dangling = WeakSet()
|
gpl-3.0
|
idjaw/keystone
|
keystone/contrib/revoke/routers.py
|
23
|
1110
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from keystone.common import json_home
from keystone.common import wsgi
from keystone.contrib.revoke import controllers
class RevokeExtension(wsgi.V3ExtensionRouter):
PATH_PREFIX = '/OS-REVOKE'
def add_routes(self, mapper):
revoke_controller = controllers.RevokeController()
self._add_resource(
mapper, revoke_controller,
path=self.PATH_PREFIX + '/events',
get_action='list_revoke_events',
rel=json_home.build_v3_extension_resource_relation(
'OS-REVOKE', '1.0', 'events'))
|
apache-2.0
|
mbernasocchi/QGIS
|
python/plugins/processing/algs/gdal/GridLinear.py
|
15
|
7462
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
GridLinear.py
---------------------
Date : September 2017
Copyright : (C) 2017 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'September 2017'
__copyright__ = '(C) 2017, Alexander Bruy'
import os
from qgis.PyQt.QtGui import QIcon
from qgis.core import (QgsRasterFileWriter,
QgsProcessing,
QgsProcessingParameterDefinition,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterEnum,
QgsProcessingParameterField,
QgsProcessingParameterNumber,
QgsProcessingParameterString,
QgsProcessingParameterRasterDestination)
from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
from processing.algs.gdal.GdalUtils import GdalUtils
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
class GridLinear(GdalAlgorithm):
INPUT = 'INPUT'
Z_FIELD = 'Z_FIELD'
RADIUS = 'RADIUS'
NODATA = 'NODATA'
OPTIONS = 'OPTIONS'
EXTRA = 'EXTRA'
DATA_TYPE = 'DATA_TYPE'
OUTPUT = 'OUTPUT'
TYPES = ['Byte', 'Int16', 'UInt16', 'UInt32', 'Int32', 'Float32', 'Float64', 'CInt16', 'CInt32', 'CFloat32', 'CFloat64']
def __init__(self):
super().__init__()
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
self.tr('Point layer'),
[QgsProcessing.TypeVectorPoint]))
z_field_param = QgsProcessingParameterField(self.Z_FIELD,
self.tr('Z value from field'),
None,
self.INPUT,
QgsProcessingParameterField.Numeric,
optional=True)
z_field_param.setFlags(z_field_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(z_field_param)
self.addParameter(QgsProcessingParameterNumber(self.RADIUS,
self.tr('Search distance '),
type=QgsProcessingParameterNumber.Double,
minValue=-1.0,
defaultValue=-1.0))
self.addParameter(QgsProcessingParameterNumber(self.NODATA,
self.tr('NODATA marker to fill empty points'),
type=QgsProcessingParameterNumber.Double,
defaultValue=0.0))
options_param = QgsProcessingParameterString(self.OPTIONS,
self.tr('Additional creation options'),
defaultValue='',
optional=True)
options_param.setFlags(options_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
options_param.setMetadata({
'widget_wrapper': {
'class': 'processing.algs.gdal.ui.RasterOptionsWidget.RasterOptionsWidgetWrapper'}})
self.addParameter(options_param)
extra_param = QgsProcessingParameterString(self.EXTRA,
self.tr('Additional command-line parameters'),
defaultValue=None,
optional=True)
extra_param.setFlags(extra_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(extra_param)
dataType_param = QgsProcessingParameterEnum(self.DATA_TYPE,
self.tr('Output data type'),
self.TYPES,
allowMultiple=False,
defaultValue=5)
dataType_param.setFlags(dataType_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(dataType_param)
self.addParameter(QgsProcessingParameterRasterDestination(self.OUTPUT,
self.tr('Interpolated (Linear)')))
def name(self):
return 'gridlinear'
def displayName(self):
return self.tr('Grid (Linear)')
def group(self):
return self.tr('Raster analysis')
def groupId(self):
return 'rasteranalysis'
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'grid.png'))
def commandName(self):
return 'gdal_grid'
def getConsoleCommands(self, parameters, context, feedback, executing=True):
ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing)
arguments = [
'-l',
layerName
]
fieldName = self.parameterAsString(parameters, self.Z_FIELD, context)
if fieldName:
arguments.append('-zfield')
arguments.append(fieldName)
params = 'linear'
params += ':radius={}'.format(self.parameterAsDouble(parameters, self.RADIUS, context))
params += ':nodata={}'.format(self.parameterAsDouble(parameters, self.NODATA, context))
arguments.append('-a')
arguments.append(params)
arguments.append('-ot')
arguments.append(self.TYPES[self.parameterAsEnum(parameters, self.DATA_TYPE, context)])
out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
self.setOutputValue(self.OUTPUT, out)
arguments.append('-of')
arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1]))
options = self.parameterAsString(parameters, self.OPTIONS, context)
if options:
arguments.extend(GdalUtils.parseCreationOptions(options))
if self.EXTRA in parameters and parameters[self.EXTRA] not in (None, ''):
extra = self.parameterAsString(parameters, self.EXTRA, context)
arguments.append(extra)
arguments.append(ogrLayer)
arguments.append(out)
return [self.commandName(), GdalUtils.escapeAndJoin(arguments)]
|
gpl-2.0
|
ar7z1/ansible
|
lib/ansible/modules/monitoring/icinga2_host.py
|
35
|
9960
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This module is proudly sponsored by CGI (www.cgi.com) and
# KPN (www.kpn.com).
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: icinga2_host
short_description: Manage a host in Icinga2
description:
- "Add or remove a host to Icinga2 through the API."
- "See U(https://www.icinga.com/docs/icinga2/latest/doc/12-icinga2-api/)"
version_added: "2.5"
author: "Jurgen Brand (@t794104)"
options:
url:
description:
- HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path
required: true
use_proxy:
description:
- If C(no), it will not use a proxy, even if one is defined in
an environment variable on the target hosts.
type: bool
default: 'yes'
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
type: bool
default: 'yes'
url_username:
description:
- The username for use in HTTP basic authentication.
- This parameter can be used without C(url_password) for sites that allow empty passwords.
url_password:
description:
- The password for use in HTTP basic authentication.
- If the C(url_username) parameter is not specified, the C(url_password) parameter will not be used.
force_basic_auth:
description:
- httplib2, the library used by the uri module only sends authentication information when a webservice
responds to an initial request with a 401 status. Since some basic auth services do not properly
send a 401, logins will fail. This option forces the sending of the Basic authentication header
upon initial request.
type: bool
default: 'no'
client_cert:
description:
- PEM formatted certificate chain file to be used for SSL client
authentication. This file can also include the key as well, and if
the key is included, C(client_key) is not required.
client_key:
description:
- PEM formatted file that contains your private key to be used for SSL
client authentication. If C(client_cert) contains both the certificate
and key, this option is not required.
state:
description:
- Apply feature state.
choices: [ "present", "absent" ]
default: present
name:
description:
- Name used to create / delete the host. This does not need to be the FQDN, but does needs to be unique.
required: true
zone:
description:
- The zone from where this host should be polled.
template:
description:
- The template used to define the host.
- Template cannot be modified after object creation.
check_command:
description:
- The command used to check if the host is alive.
default: "hostalive"
display_name:
description:
- The name used to display the host.
default: if none is give it is the value of the <name> parameter
ip:
description:
- The IP address of the host.
required: true
variables:
description:
- List of variables.
'''
EXAMPLES = '''
- name: Add host to icinga
icinga2_host:
url: "https://icinga2.example.com"
url_username: "ansible"
url_password: "a_secret"
state: present
name: "{{ ansible_fqdn }}"
ip: "{{ ansible_default_ipv4.address }}"
delegate_to: 127.0.0.1
'''
RETURN = '''
name:
description: The name used to create, modify or delete the host
type: string
returned: always
data:
description: The data structure used for create, modify or delete of the host
type: dict
returned: always
'''
import json
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url, url_argument_spec
# ===========================================
# Icinga2 API class
#
class icinga2_api:
module = None
def call_url(self, path, data='', method='GET'):
headers = {
'Accept': 'application/json',
'X-HTTP-Method-Override': method,
}
url = self.module.params.get("url") + "/" + path
rsp, info = fetch_url(module=self.module, url=url, data=data, headers=headers, method=method)
body = ''
if rsp:
body = json.loads(rsp.read())
if info['status'] >= 400:
body = info['body']
return {'code': info['status'], 'data': body}
def check_connection(self):
ret = self.call_url('v1/status')
if ret['code'] == 200:
return True
return False
def exists(self, hostname):
data = {
"filter": "match(\"" + hostname + "\", host.name)",
}
ret = self.call_url(
path="v1/objects/hosts",
data=self.module.jsonify(data)
)
if ret['code'] == 200:
if len(ret['data']['results']) == 1:
return True
return False
def create(self, hostname, data):
ret = self.call_url(
path="v1/objects/hosts/" + hostname,
data=self.module.jsonify(data),
method="PUT"
)
return ret
def delete(self, hostname):
data = {"cascade": 1}
ret = self.call_url(
path="v1/objects/hosts/" + hostname,
data=self.module.jsonify(data),
method="DELETE"
)
return ret
def modify(self, hostname, data):
ret = self.call_url(
path="v1/objects/hosts/" + hostname,
data=self.module.jsonify(data),
method="POST"
)
return ret
def diff(self, hostname, data):
ret = self.call_url(
path="v1/objects/hosts/" + hostname,
method="GET"
)
changed = False
ic_data = ret['data']['results'][0]
for key in data['attrs']:
if key not in ic_data['attrs'].keys():
changed = True
elif data['attrs'][key] != ic_data['attrs'][key]:
changed = True
return changed
# ===========================================
# Module execution.
#
def main():
# use the predefined argument spec for url
argument_spec = url_argument_spec()
# remove unnecessary argument 'force'
del argument_spec['force']
# add our own arguments
argument_spec.update(
state=dict(default="present", choices=["absent", "present"]),
name=dict(required=True, aliases=['host']),
zone=dict(),
template=dict(default=None),
check_command=dict(default="hostalive"),
display_name=dict(default=None),
ip=dict(required=True),
variables=dict(type='dict', default=None),
)
# Define the main module
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
state = module.params["state"]
name = module.params["name"]
zone = module.params["zone"]
template = []
template.append(name)
if module.params["template"]:
template.append(module.params["template"])
check_command = module.params["check_command"]
ip = module.params["ip"]
display_name = module.params["display_name"]
if not display_name:
display_name = name
variables = module.params["variables"]
try:
icinga = icinga2_api()
icinga.module = module
icinga.check_connection()
except Exception as e:
module.fail_json(msg="unable to connect to Icinga. Exception message: %s" % (e))
data = {
'attrs': {
'address': ip,
'display_name': display_name,
'check_command': check_command,
'zone': zone,
'vars': {
'made_by': "ansible",
},
'templates': template,
}
}
if variables:
data['attrs']['vars'].update(variables)
changed = False
if icinga.exists(name):
if state == "absent":
if module.check_mode:
module.exit_json(changed=True, name=name, data=data)
else:
try:
ret = icinga.delete(name)
if ret['code'] == 200:
changed = True
else:
module.fail_json(msg="bad return code deleting host: %s" % (ret['data']))
except Exception as e:
module.fail_json(msg="exception deleting host: " + str(e))
elif icinga.diff(name, data):
if module.check_mode:
module.exit_json(changed=False, name=name, data=data)
# Template attribute is not allowed in modification
del data['attrs']['templates']
ret = icinga.modify(name, data)
if ret['code'] == 200:
changed = True
else:
module.fail_json(msg="bad return code modifying host: %s" % (ret['data']))
else:
if state == "present":
if module.check_mode:
changed = True
else:
try:
ret = icinga.create(name, data)
if ret['code'] == 200:
changed = True
else:
module.fail_json(msg="bad return code creating host: %s" % (ret['data']))
except Exception as e:
module.fail_json(msg="exception creating host: " + str(e))
module.exit_json(changed=changed, name=name, data=data)
# import module snippets
if __name__ == '__main__':
main()
|
gpl-3.0
|
nugget/home-assistant
|
homeassistant/components/camera/proxy.py
|
2
|
9029
|
"""
Proxy camera platform that enables image processing of camera data.
For more details about this platform, please refer to the documentation
https://www.home-assistant.io/components/camera.proxy/
"""
import asyncio
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.const import CONF_ENTITY_ID, CONF_NAME, CONF_MODE
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.util.async_ import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util
REQUIREMENTS = ['pillow==5.4.1']
_LOGGER = logging.getLogger(__name__)
CONF_CACHE_IMAGES = 'cache_images'
CONF_FORCE_RESIZE = 'force_resize'
CONF_IMAGE_QUALITY = 'image_quality'
CONF_IMAGE_REFRESH_RATE = 'image_refresh_rate'
CONF_MAX_IMAGE_WIDTH = 'max_image_width'
CONF_MAX_IMAGE_HEIGHT = 'max_image_height'
CONF_MAX_STREAM_WIDTH = 'max_stream_width'
CONF_MAX_STREAM_HEIGHT = 'max_stream_height'
CONF_IMAGE_TOP = 'image_top'
CONF_IMAGE_LEFT = 'image_left'
CONF_STREAM_QUALITY = 'stream_quality'
MODE_RESIZE = 'resize'
MODE_CROP = 'crop'
DEFAULT_BASENAME = "Camera Proxy"
DEFAULT_QUALITY = 75
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_CACHE_IMAGES, False): cv.boolean,
vol.Optional(CONF_FORCE_RESIZE, False): cv.boolean,
vol.Optional(CONF_MODE, default=MODE_RESIZE):
vol.In([MODE_RESIZE, MODE_CROP]),
vol.Optional(CONF_IMAGE_QUALITY): int,
vol.Optional(CONF_IMAGE_REFRESH_RATE): float,
vol.Optional(CONF_MAX_IMAGE_WIDTH): int,
vol.Optional(CONF_MAX_IMAGE_HEIGHT): int,
vol.Optional(CONF_MAX_STREAM_WIDTH): int,
vol.Optional(CONF_MAX_STREAM_HEIGHT): int,
vol.Optional(CONF_IMAGE_LEFT): int,
vol.Optional(CONF_IMAGE_TOP): int,
vol.Optional(CONF_STREAM_QUALITY): int,
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Proxy camera platform."""
async_add_entities([ProxyCamera(hass, config)])
def _precheck_image(image, opts):
"""Perform some pre-checks on the given image."""
from PIL import Image
import io
if not opts:
raise ValueError()
try:
img = Image.open(io.BytesIO(image))
except IOError:
_LOGGER.warning("Failed to open image")
raise ValueError()
imgfmt = str(img.format)
if imgfmt not in ('PNG', 'JPEG'):
_LOGGER.warning("Image is of unsupported type: %s", imgfmt)
raise ValueError()
return img
def _resize_image(image, opts):
"""Resize image."""
from PIL import Image
import io
try:
img = _precheck_image(image, opts)
except ValueError:
return image
quality = opts.quality or DEFAULT_QUALITY
new_width = opts.max_width
(old_width, old_height) = img.size
old_size = len(image)
if old_width <= new_width:
if opts.quality is None:
_LOGGER.debug("Image is smaller-than/equal-to requested width")
return image
new_width = old_width
scale = new_width / float(old_width)
new_height = int((float(old_height)*float(scale)))
img = img.resize((new_width, new_height), Image.ANTIALIAS)
imgbuf = io.BytesIO()
img.save(imgbuf, 'JPEG', optimize=True, quality=quality)
newimage = imgbuf.getvalue()
if not opts.force_resize and len(newimage) >= old_size:
_LOGGER.debug("Using original image (%d bytes) "
"because resized image (%d bytes) is not smaller",
old_size, len(newimage))
return image
_LOGGER.debug(
"Resized image from (%dx%d - %d bytes) to (%dx%d - %d bytes)",
old_width, old_height, old_size, new_width, new_height, len(newimage))
return newimage
def _crop_image(image, opts):
"""Crop image."""
import io
try:
img = _precheck_image(image, opts)
except ValueError:
return image
quality = opts.quality or DEFAULT_QUALITY
(old_width, old_height) = img.size
old_size = len(image)
if opts.top is None:
opts.top = 0
if opts.left is None:
opts.left = 0
if opts.max_width is None or opts.max_width > old_width - opts.left:
opts.max_width = old_width - opts.left
if opts.max_height is None or opts.max_height > old_height - opts.top:
opts.max_height = old_height - opts.top
img = img.crop((opts.left, opts.top,
opts.left+opts.max_width, opts.top+opts.max_height))
imgbuf = io.BytesIO()
img.save(imgbuf, 'JPEG', optimize=True, quality=quality)
newimage = imgbuf.getvalue()
_LOGGER.debug(
"Cropped image from (%dx%d - %d bytes) to (%dx%d - %d bytes)",
old_width, old_height, old_size, opts.max_width, opts.max_height,
len(newimage))
return newimage
class ImageOpts():
"""The representation of image options."""
def __init__(self, max_width, max_height, left, top,
quality, force_resize):
"""Initialize image options."""
self.max_width = max_width
self.max_height = max_height
self.left = left
self.top = top
self.quality = quality
self.force_resize = force_resize
def __bool__(self):
"""Bool evaluation rules."""
return bool(self.max_width or self.quality)
class ProxyCamera(Camera):
"""The representation of a Proxy camera."""
def __init__(self, hass, config):
"""Initialize a proxy camera component."""
super().__init__()
self.hass = hass
self._proxied_camera = config.get(CONF_ENTITY_ID)
self._name = (
config.get(CONF_NAME) or
"{} - {}".format(DEFAULT_BASENAME, self._proxied_camera))
self._image_opts = ImageOpts(
config.get(CONF_MAX_IMAGE_WIDTH),
config.get(CONF_MAX_IMAGE_HEIGHT),
config.get(CONF_IMAGE_LEFT),
config.get(CONF_IMAGE_TOP),
config.get(CONF_IMAGE_QUALITY),
config.get(CONF_FORCE_RESIZE))
self._stream_opts = ImageOpts(
config.get(CONF_MAX_STREAM_WIDTH),
config.get(CONF_MAX_STREAM_HEIGHT),
config.get(CONF_IMAGE_LEFT),
config.get(CONF_IMAGE_TOP),
config.get(CONF_STREAM_QUALITY),
True)
self._image_refresh_rate = config.get(CONF_IMAGE_REFRESH_RATE)
self._cache_images = bool(
config.get(CONF_IMAGE_REFRESH_RATE)
or config.get(CONF_CACHE_IMAGES))
self._last_image_time = dt_util.utc_from_timestamp(0)
self._last_image = None
self._mode = config.get(CONF_MODE)
def camera_image(self):
"""Return camera image."""
return run_coroutine_threadsafe(
self.async_camera_image(), self.hass.loop).result()
async def async_camera_image(self):
"""Return a still image response from the camera."""
now = dt_util.utcnow()
if (self._image_refresh_rate and
now < self._last_image_time +
timedelta(seconds=self._image_refresh_rate)):
return self._last_image
self._last_image_time = now
image = await self.hass.components.camera.async_get_image(
self._proxied_camera)
if not image:
_LOGGER.error("Error getting original camera image")
return self._last_image
if self._mode == MODE_RESIZE:
job = _resize_image
else:
job = _crop_image
image = await self.hass.async_add_executor_job(
job, image.content, self._image_opts)
if self._cache_images:
self._last_image = image
return image
async def handle_async_mjpeg_stream(self, request):
"""Generate an HTTP MJPEG stream from camera images."""
if not self._stream_opts:
return await self.hass.components.camera.async_get_mjpeg_stream(
request, self._proxied_camera)
return await self.hass.components.camera.async_get_still_stream(
request, self._async_stream_image,
self.content_type, self.frame_interval)
@property
def name(self):
"""Return the name of this camera."""
return self._name
async def _async_stream_image(self):
"""Return a still image response from the camera."""
try:
image = await self.hass.components.camera.async_get_image(
self._proxied_camera)
if not image:
return None
except HomeAssistantError:
raise asyncio.CancelledError()
if self._mode == MODE_RESIZE:
job = _resize_image
else:
job = _crop_image
return await self.hass.async_add_executor_job(
job, image.content, self._stream_opts)
|
apache-2.0
|
alfredfrancis/ai-chatbot-framework
|
app/nlu/entity_extractor.py
|
1
|
7280
|
# -*- coding: utf-8 -*-
import pycrfsuite
from flask import current_app as app
from app.nlu import spacy_tokenizer
class EntityExtractor:
"""
Performs NER training, prediction, model import/export
"""
def __init__(self, synonyms=[]):
self.synonyms = synonyms
def replace_synonyms(self, entities):
"""
replace extracted entity values with
root word by matching with synonyms dict.
:param entities:
:return:
"""
for entity in entities.keys():
entity_value = str(entities[entity])
if entity_value.lower() in self.synonyms:
entities[entity] = self.synonyms[entity_value.lower()]
return entities
def extract_features(self, sent, i):
"""
Extract features for a given sentence
:param sent:
:param i:
:return:
"""
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word.lower=' + word.lower(),
'word[-3:]=' + word[-3:],
'word[-2:]=' + word[-2:],
'word.isupper=%s' % word.isupper(),
'word.istitle=%s' % word.istitle(),
'word.isdigit=%s' % word.isdigit(),
'postag=' + postag,
'postag[:2]=' + postag[:2],
]
if i > 0:
word1 = sent[i - 1][0]
postag1 = sent[i - 1][1]
features.extend([
'-1:word.lower=' + word1.lower(),
'-1:word.istitle=%s' % word1.istitle(),
'-1:word.isupper=%s' % word1.isupper(),
'-1:postag=' + postag1,
'-1:postag[:2]=' + postag1[:2],
])
else:
features.append('BOS')
if i < len(sent) - 1:
word1 = sent[i + 1][0]
postag1 = sent[i + 1][1]
features.extend([
'+1:word.lower=' + word1.lower(),
'+1:word.istitle=%s' % word1.istitle(),
'+1:word.isupper=%s' % word1.isupper(),
'+1:postag=' + postag1,
'+1:postag[:2]=' + postag1[:2],
])
else:
features.append('EOS')
return features
def sent_to_features(self, sent):
"""
Extract features from training Data
:param sent:
:return:
"""
return [self.extract_features(sent, i) for i in range(len(sent))]
def sent_to_labels(self, sent):
"""
Extract labels from training data
:param sent:
:return:
"""
return [label for token, postag, label in sent]
def sent_to_tokens(self, sent):
"""
Extract tokens from training data
:param sent:
:return:
"""
return [token for token, postag, label in sent]
def train(self, train_sentences, model_name):
"""
Train NER model for given model
:param train_sentences:
:param model_name:
:return:
"""
features = [self.sent_to_features(s) for s in train_sentences]
labels = [self.sent_to_labels(s) for s in train_sentences]
trainer = pycrfsuite.Trainer(verbose=False)
for xseq, yseq in zip(features, labels):
trainer.append(xseq, yseq)
trainer.set_params({
'c1': 1.0, # coefficient for L1 penalty
'c2': 1e-3, # coefficient for L2 penalty
'max_iterations': 50, # stop earlier
# include transitions that are possible, but not observed
'feature.possible_transitions': True
})
trainer.train('model_files/%s.model' % model_name)
return True
# Extract Labels from BIO tagged sentence
def crf2json(self, tagged_sentence):
"""
Extract label-value pair from NER prediction output
:param tagged_sentence:
:return:
"""
labeled = {}
labels = set()
for s, tp in tagged_sentence:
if tp != "O":
label = tp[2:]
if tp.startswith("B"):
labeled[label] = s
labels.add(label)
elif tp.startswith("I") and (label in labels):
labeled[label] += " %s" % s
return labeled
def extract_ner_labels(self, predicted_labels):
"""
Extract name of labels from NER
:param predicted_labels:
:return:
"""
labels = []
for tp in predicted_labels:
if tp != "O":
labels.append(tp[2:])
return labels
def predict(self, model_name, sentence):
"""
Predict NER labels for given model and query
:param model_name:
:param sentence:
:return:
"""
from app.nlu.tasks import pos_tagger
doc = spacy_tokenizer(sentence)
words = [token.text for token in doc]
tagged_token = pos_tagger(sentence)
tagger = pycrfsuite.Tagger()
tagger.open("{}/{}.model".format(app.config["MODELS_DIR"], model_name))
predicted_labels = tagger.tag(self.sent_to_features(tagged_token))
extracted_entities = self.crf2json(
zip(words, predicted_labels))
return self.replace_synonyms(extracted_entities)
@staticmethod
def json2crf(training_data):
"""
Takes json annotated data and converts to
CRFSuite training data representation
:param training_data:
:return labeled_examples:
"""
from app.nlu.tasks import sentence_tokenize, pos_tag_and_label
labeled_examples = []
for example in training_data:
# POS tag and initialize bio label as 'O' for all the tokens
tagged_example = pos_tag_and_label(example.get("text"))
# find no of words before selection
for enitity in example.get("entities"):
try:
begin_index = enitity.get("begin")
end_index = enitity.get("end")
# find no of words before the entity
inverse_selection = example.get("text")[0:begin_index - 1]
inverse_selection = sentence_tokenize(inverse_selection)
inverse_selection = inverse_selection.split(" ")
inverse_word_count = len(inverse_selection)
# get the entity value from selection
selection = example.get("text")[begin_index:end_index]
tokens = sentence_tokenize(selection).split(" ")
selection_word_count = len(tokens)
# build BIO tagging
for i in range(1, selection_word_count + 1):
if i == 1:
bio = "B-" + enitity.get("name")
else:
bio = "I-" + enitity.get("name")
tagged_example[(inverse_word_count + i) - 1][2] = bio
except:
# catches and skips invalid offsets and annotation
continue
labeled_examples.append(tagged_example)
return labeled_examples
|
mit
|
BIT-SYS/gem5-spm-module
|
src/arch/x86/isa/insts/simd128/floating_point/arithmetic/reciprocal_square_root.py
|
91
|
2162
|
# Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Gabe Black
microcode = '''
# RSQRTPS
# RSQRTPD
'''
|
bsd-3-clause
|
dalf/searx
|
searx/engines/qwant.py
|
1
|
4616
|
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Qwant (Web, Images, News, Social)
"""
from datetime import datetime
from json import loads
from urllib.parse import urlencode
from searx.utils import html_to_text, match_language
from searx.exceptions import SearxEngineAPIException, SearxEngineCaptchaException
from searx.network import raise_for_httperror
# about
about = {
"website": 'https://www.qwant.com/',
"wikidata_id": 'Q14657870',
"official_api_documentation": None,
"use_official_api": True,
"require_api_key": False,
"results": 'JSON',
}
# engine dependent config
categories = []
paging = True
supported_languages_url = about['website']
category_to_keyword = {'general': 'web',
'images': 'images',
'news': 'news'}
# search-url
url = 'https://api.qwant.com/api/search/{keyword}?count=10&offset={offset}&f=&{query}&t={keyword}&uiv=4'
# do search-request
def request(query, params):
offset = (params['pageno'] - 1) * 10
if categories[0] and categories[0] in category_to_keyword:
params['url'] = url.format(keyword=category_to_keyword[categories[0]],
query=urlencode({'q': query}),
offset=offset)
else:
params['url'] = url.format(keyword='web',
query=urlencode({'q': query}),
offset=offset)
# add language tag
if params['language'] != 'all':
language = match_language(params['language'], supported_languages, language_aliases)
params['url'] += '&locale=' + language.replace('-', '_').lower()
params['headers']['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0'
params['raise_for_httperror'] = False
return params
# get response from search-request
def response(resp):
results = []
# According to https://www.qwant.com/js/app.js
if resp.status_code == 429:
raise SearxEngineCaptchaException()
# raise for other errors
raise_for_httperror(resp)
# load JSON result
search_results = loads(resp.text)
# check for an API error
if search_results.get('status') != 'success':
raise SearxEngineAPIException('API error ' + str(search_results.get('error', '')))
# return empty array if there are no results
if 'data' not in search_results:
return []
data = search_results.get('data', {})
res = data.get('result', {})
# parse results
for result in res.get('items', {}):
title = html_to_text(result['title'])
res_url = result['url']
content = html_to_text(result['desc'])
if category_to_keyword.get(categories[0], '') == 'web':
results.append({'title': title,
'content': content,
'url': res_url})
elif category_to_keyword.get(categories[0], '') == 'images':
thumbnail_src = result['thumbnail']
img_src = result['media']
results.append({'template': 'images.html',
'url': res_url,
'title': title,
'content': '',
'thumbnail_src': thumbnail_src,
'img_src': img_src})
elif category_to_keyword.get(categories[0], '') == 'news':
published_date = datetime.fromtimestamp(result['date'], None)
media = result.get('media', [])
if len(media) > 0:
img_src = media[0].get('pict', {}).get('url', None)
else:
img_src = None
results.append({'url': res_url,
'title': title,
'publishedDate': published_date,
'content': content,
'img_src': img_src})
return results
# get supported languages from their site
def _fetch_supported_languages(resp):
# list of regions is embedded in page as a js object
response_text = resp.text
response_text = response_text[response_text.find('INITIAL_PROPS'):]
response_text = response_text[response_text.find('{'):response_text.find('</script>')]
regions_json = loads(response_text)
supported_languages = []
for country, langs in regions_json['locales'].items():
for lang in langs['langs']:
lang_code = "{lang}-{country}".format(lang=lang, country=country)
supported_languages.append(lang_code)
return supported_languages
|
agpl-3.0
|
starwels/p2pool
|
p2pool/__init__.py
|
278
|
1595
|
import os
import re
import sys
import traceback
import subprocess
def check_output(*popenargs, **kwargs):
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
raise ValueError((retcode, output))
return output
def _get_version():
try:
try:
return check_output(['git', 'describe', '--always', '--dirty'], cwd=os.path.dirname(os.path.abspath(sys.argv[0]))).strip()
except:
pass
try:
return check_output(['git.cmd', 'describe', '--always', '--dirty'], cwd=os.path.dirname(os.path.abspath(sys.argv[0]))).strip()
except:
pass
root_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
git_dir = os.path.join(root_dir, '.git')
if os.path.exists(git_dir):
head = open(os.path.join(git_dir, 'HEAD')).read().strip()
prefix = 'ref: '
if head.startswith(prefix):
path = head[len(prefix):].split('/')
return open(os.path.join(git_dir, *path)).read().strip()[:7]
else:
return head[:7]
dir_name = os.path.split(root_dir)[1]
match = re.match('p2pool-([.0-9]+)', dir_name)
if match:
return match.groups()[0]
return 'unknown %s' % (dir_name.encode('hex'),)
except Exception, e:
traceback.print_exc()
return 'unknown %s' % (str(e).encode('hex'),)
__version__ = _get_version()
DEBUG = True
|
gpl-3.0
|
UNR-AERIAL/scikit-learn
|
sklearn/neural_network/rbm.py
|
206
|
12292
|
"""Restricted Boltzmann Machine
"""
# Authors: Yann N. Dauphin <[email protected]>
# Vlad Niculae
# Gabriel Synnaeve
# Lars Buitinck
# License: BSD 3 clause
import time
import numpy as np
import scipy.sparse as sp
from ..base import BaseEstimator
from ..base import TransformerMixin
from ..externals.six.moves import xrange
from ..utils import check_array
from ..utils import check_random_state
from ..utils import gen_even_slices
from ..utils import issparse
from ..utils.extmath import safe_sparse_dot
from ..utils.extmath import log_logistic
from ..utils.fixes import expit # logistic function
from ..utils.validation import check_is_fitted
class BernoulliRBM(BaseEstimator, TransformerMixin):
"""Bernoulli Restricted Boltzmann Machine (RBM).
A Restricted Boltzmann Machine with binary visible units and
binary hiddens. Parameters are estimated using Stochastic Maximum
Likelihood (SML), also known as Persistent Contrastive Divergence (PCD)
[2].
The time complexity of this implementation is ``O(d ** 2)`` assuming
d ~ n_features ~ n_components.
Read more in the :ref:`User Guide <rbm>`.
Parameters
----------
n_components : int, optional
Number of binary hidden units.
learning_rate : float, optional
The learning rate for weight updates. It is *highly* recommended
to tune this hyper-parameter. Reasonable values are in the
10**[0., -3.] range.
batch_size : int, optional
Number of examples per minibatch.
n_iter : int, optional
Number of iterations/sweeps over the training dataset to perform
during training.
verbose : int, optional
The verbosity level. The default, zero, means silent mode.
random_state : integer or numpy.RandomState, optional
A random number generator instance to define the state of the
random permutations generator. If an integer is given, it fixes the
seed. Defaults to the global numpy random number generator.
Attributes
----------
intercept_hidden_ : array-like, shape (n_components,)
Biases of the hidden units.
intercept_visible_ : array-like, shape (n_features,)
Biases of the visible units.
components_ : array-like, shape (n_components, n_features)
Weight matrix, where n_features in the number of
visible units and n_components is the number of hidden units.
Examples
--------
>>> import numpy as np
>>> from sklearn.neural_network import BernoulliRBM
>>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
>>> model = BernoulliRBM(n_components=2)
>>> model.fit(X)
BernoulliRBM(batch_size=10, learning_rate=0.1, n_components=2, n_iter=10,
random_state=None, verbose=0)
References
----------
[1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for
deep belief nets. Neural Computation 18, pp 1527-1554.
http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf
[2] Tieleman, T. Training Restricted Boltzmann Machines using
Approximations to the Likelihood Gradient. International Conference
on Machine Learning (ICML) 2008
"""
def __init__(self, n_components=256, learning_rate=0.1, batch_size=10,
n_iter=10, verbose=0, random_state=None):
self.n_components = n_components
self.learning_rate = learning_rate
self.batch_size = batch_size
self.n_iter = n_iter
self.verbose = verbose
self.random_state = random_state
def transform(self, X):
"""Compute the hidden layer activation probabilities, P(h=1|v=X).
Parameters
----------
X : {array-like, sparse matrix} shape (n_samples, n_features)
The data to be transformed.
Returns
-------
h : array, shape (n_samples, n_components)
Latent representations of the data.
"""
check_is_fitted(self, "components_")
X = check_array(X, accept_sparse='csr', dtype=np.float)
return self._mean_hiddens(X)
def _mean_hiddens(self, v):
"""Computes the probabilities P(h=1|v).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
h : array-like, shape (n_samples, n_components)
Corresponding mean field values for the hidden layer.
"""
p = safe_sparse_dot(v, self.components_.T)
p += self.intercept_hidden_
return expit(p, out=p)
def _sample_hiddens(self, v, rng):
"""Sample from the distribution P(h|v).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer to sample from.
rng : RandomState
Random number generator to use.
Returns
-------
h : array-like, shape (n_samples, n_components)
Values of the hidden layer.
"""
p = self._mean_hiddens(v)
return (rng.random_sample(size=p.shape) < p)
def _sample_visibles(self, h, rng):
"""Sample from the distribution P(v|h).
Parameters
----------
h : array-like, shape (n_samples, n_components)
Values of the hidden layer to sample from.
rng : RandomState
Random number generator to use.
Returns
-------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
"""
p = np.dot(h, self.components_)
p += self.intercept_visible_
expit(p, out=p)
return (rng.random_sample(size=p.shape) < p)
def _free_energy(self, v):
"""Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
free_energy : array-like, shape (n_samples,)
The value of the free energy.
"""
return (- safe_sparse_dot(v, self.intercept_visible_)
- np.logaddexp(0, safe_sparse_dot(v, self.components_.T)
+ self.intercept_hidden_).sum(axis=1))
def gibbs(self, v):
"""Perform one Gibbs sampling step.
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer to start from.
Returns
-------
v_new : array-like, shape (n_samples, n_features)
Values of the visible layer after one Gibbs step.
"""
check_is_fitted(self, "components_")
if not hasattr(self, "random_state_"):
self.random_state_ = check_random_state(self.random_state)
h_ = self._sample_hiddens(v, self.random_state_)
v_ = self._sample_visibles(h_, self.random_state_)
return v_
def partial_fit(self, X, y=None):
"""Fit the model to the data X which should contain a partial
segment of the data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data.
Returns
-------
self : BernoulliRBM
The fitted model.
"""
X = check_array(X, accept_sparse='csr', dtype=np.float)
if not hasattr(self, 'random_state_'):
self.random_state_ = check_random_state(self.random_state)
if not hasattr(self, 'components_'):
self.components_ = np.asarray(
self.random_state_.normal(
0,
0.01,
(self.n_components, X.shape[1])
),
order='fortran')
if not hasattr(self, 'intercept_hidden_'):
self.intercept_hidden_ = np.zeros(self.n_components, )
if not hasattr(self, 'intercept_visible_'):
self.intercept_visible_ = np.zeros(X.shape[1], )
if not hasattr(self, 'h_samples_'):
self.h_samples_ = np.zeros((self.batch_size, self.n_components))
self._fit(X, self.random_state_)
def _fit(self, v_pos, rng):
"""Inner fit for one mini-batch.
Adjust the parameters to maximize the likelihood of v using
Stochastic Maximum Likelihood (SML).
Parameters
----------
v_pos : array-like, shape (n_samples, n_features)
The data to use for training.
rng : RandomState
Random number generator to use for sampling.
"""
h_pos = self._mean_hiddens(v_pos)
v_neg = self._sample_visibles(self.h_samples_, rng)
h_neg = self._mean_hiddens(v_neg)
lr = float(self.learning_rate) / v_pos.shape[0]
update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T
update -= np.dot(h_neg.T, v_neg)
self.components_ += lr * update
self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0))
self.intercept_visible_ += lr * (np.asarray(
v_pos.sum(axis=0)).squeeze() -
v_neg.sum(axis=0))
h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial
self.h_samples_ = np.floor(h_neg, h_neg)
def score_samples(self, X):
"""Compute the pseudo-likelihood of X.
Parameters
----------
X : {array-like, sparse matrix} shape (n_samples, n_features)
Values of the visible layer. Must be all-boolean (not checked).
Returns
-------
pseudo_likelihood : array-like, shape (n_samples,)
Value of the pseudo-likelihood (proxy for likelihood).
Notes
-----
This method is not deterministic: it computes a quantity called the
free energy on X, then on a randomly corrupted version of X, and
returns the log of the logistic function of the difference.
"""
check_is_fitted(self, "components_")
v = check_array(X, accept_sparse='csr')
rng = check_random_state(self.random_state)
# Randomly corrupt one feature in each sample in v.
ind = (np.arange(v.shape[0]),
rng.randint(0, v.shape[1], v.shape[0]))
if issparse(v):
data = -2 * v[ind] + 1
v_ = v + sp.csr_matrix((data.A.ravel(), ind), shape=v.shape)
else:
v_ = v.copy()
v_[ind] = 1 - v_[ind]
fe = self._free_energy(v)
fe_ = self._free_energy(v_)
return v.shape[1] * log_logistic(fe_ - fe)
def fit(self, X, y=None):
"""Fit the model to the data X.
Parameters
----------
X : {array-like, sparse matrix} shape (n_samples, n_features)
Training data.
Returns
-------
self : BernoulliRBM
The fitted model.
"""
X = check_array(X, accept_sparse='csr', dtype=np.float)
n_samples = X.shape[0]
rng = check_random_state(self.random_state)
self.components_ = np.asarray(
rng.normal(0, 0.01, (self.n_components, X.shape[1])),
order='fortran')
self.intercept_hidden_ = np.zeros(self.n_components, )
self.intercept_visible_ = np.zeros(X.shape[1], )
self.h_samples_ = np.zeros((self.batch_size, self.n_components))
n_batches = int(np.ceil(float(n_samples) / self.batch_size))
batch_slices = list(gen_even_slices(n_batches * self.batch_size,
n_batches, n_samples))
verbose = self.verbose
begin = time.time()
for iteration in xrange(1, self.n_iter + 1):
for batch_slice in batch_slices:
self._fit(X[batch_slice], rng)
if verbose:
end = time.time()
print("[%s] Iteration %d, pseudo-likelihood = %.2f,"
" time = %.2fs"
% (type(self).__name__, iteration,
self.score_samples(X).mean(), end - begin))
begin = end
return self
|
bsd-3-clause
|
ddsc/ddsc-core
|
ddsc_core/management/commands/create_test_location.py
|
1
|
2966
|
from django.core.management.base import BaseCommand
from ddsc_core.models import (
Location,
Source,
Parameter,
Unit,
Timeseries
)
from lizard_security.models import DataSet
from django.contrib.gis.geos import Point
import pandas as pd
import numpy as np
import datetime
import pytz
TEST_LOCATION_NAME = 'Test Location'
TEST_TIMESERIES_NAME = 'Test Timeseries'
TEST_PARAMETER_NAME = 'Test Param'
TEST_UNIT_NAME = 'Test Unit'
class Command(BaseCommand):
args = '[nothing]'
help = 'Create a test location and timeseries in the database.'
def handle(self, *args, **options):
data_sets = DataSet.objects.all()
data_set = data_sets[0] if len(data_sets) > 0 else None
sources = Source.objects.all()
source = sources[0] if len(sources) > 0 else None
parameters = Parameter.objects.filter(code=TEST_PARAMETER_NAME)
parameter = parameters[0] if len(parameters) > 0 else None
if not parameter:
parameter = Parameter(
code=TEST_PARAMETER_NAME,
group='{} group'.format(TEST_PARAMETER_NAME),
begin_date=datetime.datetime.now(),
end_date=datetime.datetime.now(),
)
parameter.save()
units = Unit.objects.filter(code=TEST_UNIT_NAME)
unit = units[0] if len(units) > 0 else None
if not unit:
unit = Unit(
code=TEST_UNIT_NAME,
begin_date=datetime.datetime.now(),
end_date=datetime.datetime.now(),
)
unit.save()
locations = Location.objects.filter(name=TEST_LOCATION_NAME)
location = locations[0] if len(locations) > 0 else None
if not location:
location = Location(
name=TEST_LOCATION_NAME,
description='{} description'.format(TEST_LOCATION_NAME),
point_geometry=Point(0, 0),
)
location.save_under(None)
timeseriess = Timeseries.objects.filter(name=TEST_TIMESERIES_NAME)
timeseries = timeseriess[0] if len(timeseriess) > 0 else None
if not timeseries:
timeseries = Timeseries(
name=TEST_TIMESERIES_NAME,
description='{} description'.format(TEST_TIMESERIES_NAME),
source=source,
parameter=parameter,
unit=unit,
location=location
)
timeseries.save()
timeseries.data_sets = [data_set]
timeseries.save()
events = timeseries.get_events()
if len(events) == 0:
dates = pd.date_range('1/1/2011', periods=20000, freq='1Min', tz=pytz.UTC)
vals = np.linspace(-np.pi, np.pi, len(dates))
vals = np.sin(vals)
df = pd.DataFrame(vals, index=dates, columns=['value'])
timeseries.set_events(df)
timeseries.save()
|
mit
|
zanderle/django
|
django/core/mail/backends/base.py
|
577
|
1573
|
"""Base email backend class."""
class BaseEmailBackend(object):
"""
Base class for email backend implementations.
Subclasses must at least overwrite send_messages().
open() and close() can be called indirectly by using a backend object as a
context manager:
with backend as connection:
# do something with connection
pass
"""
def __init__(self, fail_silently=False, **kwargs):
self.fail_silently = fail_silently
def open(self):
"""Open a network connection.
This method can be overwritten by backend implementations to
open a network connection.
It's up to the backend implementation to track the status of
a network connection if it's needed by the backend.
This method can be called by applications to force a single
network connection to be used when sending mails. See the
send_messages() method of the SMTP backend for a reference
implementation.
The default implementation does nothing.
"""
pass
def close(self):
"""Close a network connection."""
pass
def __enter__(self):
self.open()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
messages sent.
"""
raise NotImplementedError('subclasses of BaseEmailBackend must override send_messages() method')
|
bsd-3-clause
|
Tatsh-ansible/ansible
|
test/runner/lib/sanity.py
|
4
|
26772
|
"""Execute Ansible sanity tests."""
from __future__ import absolute_import, print_function
import glob
import json
import os
import re
from xml.etree.ElementTree import (
fromstring,
Element,
)
from lib.util import (
ApplicationError,
SubprocessError,
display,
run_command,
deepest_path,
parse_to_dict,
remove_tree,
)
from lib.ansible_util import (
ansible_environment,
)
from lib.target import (
walk_external_targets,
walk_internal_targets,
walk_sanity_targets,
)
from lib.executor import (
get_changes_filter,
AllTargetsSkipped,
Delegate,
install_command_requirements,
SUPPORTED_PYTHON_VERSIONS,
intercept_command,
generate_pip_install,
)
from lib.config import (
SanityConfig,
)
from lib.test import (
TestSuccess,
TestFailure,
TestSkipped,
TestMessage,
calculate_best_confidence,
)
COMMAND = 'sanity'
PEP8_SKIP_PATH = 'test/sanity/pep8/skip.txt'
PEP8_LEGACY_PATH = 'test/sanity/pep8/legacy-files.txt'
PYLINT_SKIP_PATH = 'test/sanity/pylint/skip.txt'
def command_sanity(args):
"""
:type args: SanityConfig
"""
changes = get_changes_filter(args)
require = (args.require or []) + changes
targets = SanityTargets(args.include, args.exclude, require)
if not targets.include:
raise AllTargetsSkipped()
if args.delegate:
raise Delegate(require=changes)
install_command_requirements(args)
tests = sanity_get_tests()
if args.test:
tests = [t for t in tests if t.name in args.test]
if args.skip_test:
tests = [t for t in tests if t.name not in args.skip_test]
total = 0
failed = []
for test in tests:
if args.list_tests:
display.info(test.name)
continue
if test.intercept:
versions = SUPPORTED_PYTHON_VERSIONS
else:
versions = None,
for version in versions:
if args.python and version and version != args.python:
continue
display.info('Sanity check using %s%s' % (test.name, ' with Python %s' % version if version else ''))
options = ''
if test.script:
result = test.func(args, targets, test.script)
elif test.intercept:
result = test.func(args, targets, python_version=version)
options = ' --python %s' % version
else:
result = test.func(args, targets)
result.write(args)
total += 1
if isinstance(result, SanityFailure):
failed.append(result.test + options)
if failed:
message = 'The %d sanity test(s) listed below (out of %d) failed. See error output above for details.\n%s' % (
len(failed), total, '\n'.join(failed))
if args.failure_ok:
display.error(message)
else:
raise ApplicationError(message)
def command_sanity_code_smell(args, _, script):
"""
:type args: SanityConfig
:type _: SanityTargets
:type script: str
:rtype: SanityResult
"""
test = os.path.splitext(os.path.basename(script))[0]
cmd = [script]
env = ansible_environment(args, color=False)
try:
stdout, stderr = run_command(args, cmd, env=env, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr or status:
summary = str(SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout))
return SanityFailure(test, summary=summary)
return SanitySuccess(test)
def command_sanity_validate_modules(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'validate-modules'
env = ansible_environment(args, color=False)
paths = [deepest_path(i.path, 'lib/ansible/modules/') for i in targets.include_external]
paths = sorted(set(p for p in paths if p))
if not paths:
return SanitySkipped(test)
cmd = [
'test/sanity/validate-modules/validate-modules',
'--format', 'json',
] + paths
with open('test/sanity/validate-modules/skip.txt', 'r') as skip_fd:
skip_paths = skip_fd.read().splitlines()
skip_paths += [e.path for e in targets.exclude_external]
if skip_paths:
cmd += ['--exclude', '^(%s)' % '|'.join(skip_paths)]
if args.base_branch:
cmd.extend([
'--base-branch', args.base_branch,
])
else:
display.warning('Cannot perform module comparison against the base branch. Base branch not detected when running locally.')
try:
stdout, stderr = run_command(args, cmd, env=env, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr or status not in (0, 3):
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
messages = json.loads(stdout)
results = []
for filename in messages:
output = messages[filename]
for item in output['errors']:
results.append(SanityMessage(
path=filename,
line=int(item['line']) if 'line' in item else 0,
column=int(item['column']) if 'column' in item else 0,
level='error',
code='E%s' % item['code'],
message=item['msg'],
))
if results:
return SanityFailure(test, messages=results)
return SanitySuccess(test)
def command_sanity_shellcheck(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'shellcheck'
with open('test/sanity/shellcheck/skip.txt', 'r') as skip_fd:
skip_paths = set(skip_fd.read().splitlines())
with open('test/sanity/shellcheck/exclude.txt', 'r') as exclude_fd:
exclude = set(exclude_fd.read().splitlines())
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] == '.sh' and i.path not in skip_paths)
if not paths:
return SanitySkipped(test)
cmd = [
'shellcheck',
'-e', ','.join(sorted(exclude)),
'--format', 'checkstyle',
] + paths
try:
stdout, stderr = run_command(args, cmd, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr or status > 1:
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
# json output is missing file paths in older versions of shellcheck, so we'll use xml instead
root = fromstring(stdout) # type: Element
results = []
for item in root: # type: Element
for entry in item: # type: Element
results.append(SanityMessage(
message=entry.attrib['message'],
path=item.attrib['name'],
line=int(entry.attrib['line']),
column=int(entry.attrib['column']),
level=entry.attrib['severity'],
code=entry.attrib['source'].replace('ShellCheck.', ''),
))
if results:
return SanityFailure(test, messages=results)
return SanitySuccess(test)
def command_sanity_pep8(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'pep8'
with open(PEP8_SKIP_PATH, 'r') as skip_fd:
skip_paths = skip_fd.read().splitlines()
with open(PEP8_LEGACY_PATH, 'r') as legacy_fd:
legacy_paths = legacy_fd.read().splitlines()
with open('test/sanity/pep8/legacy-ignore.txt', 'r') as ignore_fd:
legacy_ignore = set(ignore_fd.read().splitlines())
with open('test/sanity/pep8/current-ignore.txt', 'r') as ignore_fd:
current_ignore = sorted(ignore_fd.read().splitlines())
skip_paths_set = set(skip_paths)
legacy_paths_set = set(legacy_paths)
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] == '.py' and i.path not in skip_paths_set)
if not paths:
return SanitySkipped(test)
cmd = [
'pycodestyle',
'--max-line-length', '160',
'--config', '/dev/null',
'--ignore', ','.join(sorted(current_ignore)),
] + paths
try:
stdout, stderr = run_command(args, cmd, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr:
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
pattern = '^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<code>[WE][0-9]{3}) (?P<message>.*)$'
results = [re.search(pattern, line).groupdict() for line in stdout.splitlines()]
results = [SanityMessage(
message=r['message'],
path=r['path'],
line=int(r['line']),
column=int(r['column']),
level='warning' if r['code'].startswith('W') else 'error',
code=r['code'],
) for r in results]
failed_result_paths = set([result.path for result in results])
used_paths = set(paths)
errors = []
summary = {}
line = 0
for path in legacy_paths:
line += 1
if not os.path.exists(path):
# Keep files out of the list which no longer exist in the repo.
errors.append(SanityMessage(
code='A101',
message='Remove "%s" since it does not exist' % path,
path=PEP8_LEGACY_PATH,
line=line,
column=1,
confidence=calculate_best_confidence(((PEP8_LEGACY_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
))
if path in used_paths and path not in failed_result_paths:
# Keep files out of the list which no longer require the relaxed rule set.
errors.append(SanityMessage(
code='A201',
message='Remove "%s" since it passes the current rule set' % path,
path=PEP8_LEGACY_PATH,
line=line,
column=1,
confidence=calculate_best_confidence(((PEP8_LEGACY_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
))
line = 0
for path in skip_paths:
line += 1
if not os.path.exists(path):
# Keep files out of the list which no longer exist in the repo.
errors.append(SanityMessage(
code='A101',
message='Remove "%s" since it does not exist' % path,
path=PEP8_SKIP_PATH,
line=line,
column=1,
confidence=calculate_best_confidence(((PEP8_SKIP_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
))
for result in results:
if result.path in legacy_paths_set and result.code in legacy_ignore:
# Files on the legacy list are permitted to have errors on the legacy ignore list.
# However, we want to report on their existence to track progress towards eliminating these exceptions.
display.info('PEP 8: %s (legacy)' % result, verbosity=3)
key = '%s %s' % (result.code, re.sub('[0-9]+', 'NNN', result.message))
if key not in summary:
summary[key] = 0
summary[key] += 1
else:
# Files not on the legacy list and errors not on the legacy ignore list are PEP 8 policy errors.
errors.append(result)
if summary:
lines = []
count = 0
for key in sorted(summary):
count += summary[key]
lines.append('PEP 8: %5d %s' % (summary[key], key))
display.info('PEP 8: There were %d different legacy issues found (%d total):' % (len(summary), count), verbosity=1)
display.info('PEP 8: Count Code Message', verbosity=1)
for line in lines:
display.info(line, verbosity=1)
if errors:
return SanityFailure(test, messages=errors)
return SanitySuccess(test)
def command_sanity_pylint(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'pylint'
with open(PYLINT_SKIP_PATH, 'r') as skip_fd:
skip_paths = skip_fd.read().splitlines()
with open('test/sanity/pylint/disable.txt', 'r') as disable_fd:
disable = set(disable_fd.read().splitlines())
skip_paths_set = set(skip_paths)
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] == '.py' and i.path not in skip_paths_set)
if not paths:
return SanitySkipped(test)
cmd = [
'pylint',
'--jobs', '0',
'--reports', 'n',
'--max-line-length', '160',
'--rcfile', '/dev/null',
'--ignored-modules', '_MovedItems',
'--output-format', 'json',
'--disable', ','.join(sorted(disable)),
] + paths
env = ansible_environment(args)
try:
stdout, stderr = run_command(args, cmd, env=env, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr or status >= 32:
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
if stdout:
messages = json.loads(stdout)
else:
messages = []
errors = [SanityMessage(
message=m['message'],
path=m['path'],
line=int(m['line']),
column=int(m['column']),
level=m['type'],
code=m['symbol'],
) for m in messages]
line = 0
for path in skip_paths:
line += 1
if not os.path.exists(path):
# Keep files out of the list which no longer exist in the repo.
errors.append(SanityMessage(
code='A101',
message='Remove "%s" since it does not exist' % path,
path=PYLINT_SKIP_PATH,
line=line,
column=1,
confidence=calculate_best_confidence(((PYLINT_SKIP_PATH, line), (path, 0)), args.metadata) if args.metadata.changes else None,
))
if errors:
return SanityFailure(test, messages=errors)
return SanitySuccess(test)
def command_sanity_yamllint(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'yamllint'
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] in ('.yml', '.yaml'))
if not paths:
return SanitySkipped(test)
cmd = [
'yamllint',
'--format', 'parsable',
] + paths
try:
stdout, stderr = run_command(args, cmd, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stderr:
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): \[(?P<level>warning|error)\] (?P<message>.*)$'
results = [re.search(pattern, line).groupdict() for line in stdout.splitlines()]
results = [SanityMessage(
message=r['message'],
path=r['path'],
line=int(r['line']),
column=int(r['column']),
level=r['level'],
) for r in results]
if results:
return SanityFailure(test, messages=results)
return SanitySuccess(test)
def command_sanity_rstcheck(args, targets):
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'rstcheck'
with open('test/sanity/rstcheck/ignore-substitutions.txt', 'r') as ignore_fd:
ignore_substitutions = sorted(set(ignore_fd.read().splitlines()))
paths = sorted(i.path for i in targets.include if os.path.splitext(i.path)[1] in ('.rst',))
if not paths:
return SanitySkipped(test)
cmd = [
'rstcheck',
'--report', 'warning',
'--ignore-substitutions', ','.join(ignore_substitutions),
] + paths
try:
stdout, stderr = run_command(args, cmd, capture=True)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if stdout:
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
if args.explain:
return SanitySkipped(test)
pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+): \((?P<level>INFO|WARNING|ERROR|SEVERE)/[0-4]\) (?P<message>.*)$'
results = [parse_to_dict(pattern, line) for line in stderr.splitlines()]
results = [SanityMessage(
message=r['message'],
path=r['path'],
line=int(r['line']),
column=0,
level=r['level'],
) for r in results]
if results:
return SanityFailure(test, messages=results)
return SanitySuccess(test)
# noinspection PyUnusedLocal
def command_sanity_sanity_docs(args, targets): # pylint: disable=locally-disabled, unused-argument
"""
:type args: SanityConfig
:type targets: SanityTargets
:rtype: SanityResult
"""
test = 'sanity-docs'
sanity_dir = 'docs/docsite/rst/dev_guide/testing/sanity'
sanity_docs = set(part[0] for part in (os.path.splitext(name) for name in os.listdir(sanity_dir)) if part[1] == '.rst')
sanity_tests = set(sanity_test.name for sanity_test in sanity_get_tests())
missing = sanity_tests - sanity_docs
results = []
results += [SanityMessage(
message='missing docs for ansible-test sanity --test %s' % r,
path=os.path.join(sanity_dir, '%s.rst' % r),
) for r in sorted(missing)]
if results:
return SanityFailure(test, messages=results)
return SanitySuccess(test)
def command_sanity_ansible_doc(args, targets, python_version):
"""
:type args: SanityConfig
:type targets: SanityTargets
:type python_version: str
:rtype: SanityResult
"""
test = 'ansible-doc'
with open('test/sanity/ansible-doc/skip.txt', 'r') as skip_fd:
skip_modules = set(skip_fd.read().splitlines())
modules = sorted(set(m for i in targets.include_external for m in i.modules) -
set(m for i in targets.exclude_external for m in i.modules) -
skip_modules)
if not modules:
return SanitySkipped(test, python_version=python_version)
env = ansible_environment(args, color=False)
cmd = ['ansible-doc'] + modules
try:
stdout, stderr = intercept_command(args, cmd, target_name='ansible-doc', env=env, capture=True, python_version=python_version)
status = 0
except SubprocessError as ex:
stdout = ex.stdout
stderr = ex.stderr
status = ex.status
if status:
summary = str(SubprocessError(cmd=cmd, status=status, stderr=stderr))
return SanityFailure(test, summary=summary, python_version=python_version)
if stdout:
display.info(stdout.strip(), verbosity=3)
if stderr:
summary = 'Output on stderr from ansible-doc is considered an error.\n\n%s' % SubprocessError(cmd, stderr=stderr)
return SanityFailure(test, summary=summary, python_version=python_version)
return SanitySuccess(test, python_version=python_version)
def command_sanity_import(args, targets, python_version):
"""
:type args: SanityConfig
:type targets: SanityTargets
:type python_version: str
:rtype: SanityResult
"""
test = 'import'
with open('test/sanity/import/skip.txt', 'r') as skip_fd:
skip_paths = skip_fd.read().splitlines()
skip_paths_set = set(skip_paths)
paths = sorted(
i.path
for i in targets.include
if os.path.splitext(i.path)[1] == '.py' and
(i.path.startswith('lib/ansible/modules/') or i.path.startswith('lib/ansible/module_utils/')) and
i.path not in skip_paths_set
)
if not paths:
return SanitySkipped(test, python_version=python_version)
env = ansible_environment(args, color=False)
# create a clean virtual environment to minimize the available imports beyond the python standard library
virtual_environment_path = os.path.abspath('test/runner/.tox/minimal-py%s' % python_version.replace('.', ''))
virtual_environment_bin = os.path.join(virtual_environment_path, 'bin')
remove_tree(virtual_environment_path)
cmd = ['virtualenv', virtual_environment_path, '--python', 'python%s' % python_version, '--no-setuptools', '--no-wheel']
if not args.coverage:
cmd.append('--no-pip')
run_command(args, cmd, capture=True)
# add the importer to our virtual environment so it can be accessed through the coverage injector
importer_path = os.path.join(virtual_environment_bin, 'importer.py')
os.symlink(os.path.abspath('test/runner/importer.py'), importer_path)
# activate the virtual environment
env['PATH'] = '%s:%s' % (virtual_environment_bin, env['PATH'])
env['PYTHONPATH'] = os.path.abspath('test/runner/import/lib')
# make sure coverage is available in the virtual environment if needed
if args.coverage:
run_command(args, generate_pip_install('sanity.import', packages=['coverage']), env=env)
run_command(args, ['pip', 'uninstall', '--disable-pip-version-check', '-y', 'pip'], env=env)
cmd = ['importer.py'] + paths
results = []
try:
stdout, stderr = intercept_command(args, cmd, target_name=test, env=env, capture=True, python_version=python_version, path=env['PATH'])
if stdout or stderr:
raise SubprocessError(cmd, stdout=stdout, stderr=stderr)
except SubprocessError as ex:
if ex.status != 10 or ex.stderr or not ex.stdout:
raise
pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<message>.*)$'
results = [re.search(pattern, line).groupdict() for line in ex.stdout.splitlines()]
results = [SanityMessage(
message=r['message'],
path=r['path'],
line=int(r['line']),
column=int(r['column']),
) for r in results]
results = [result for result in results if result.path not in skip_paths]
if results:
return SanityFailure(test, messages=results, python_version=python_version)
return SanitySuccess(test, python_version=python_version)
def collect_code_smell_tests():
"""
:rtype: tuple(SanityFunc)
"""
with open('test/sanity/code-smell/skip.txt', 'r') as skip_fd:
skip_tests = skip_fd.read().splitlines()
paths = glob.glob('test/sanity/code-smell/*')
paths = sorted(p for p in paths if os.access(p, os.X_OK) and os.path.isfile(p) and os.path.basename(p) not in skip_tests)
tests = tuple(SanityFunc(os.path.splitext(os.path.basename(p))[0], command_sanity_code_smell, script=p, intercept=False) for p in paths)
return tests
def sanity_get_tests():
"""
:rtype: tuple(SanityFunc)
"""
return SANITY_TESTS
class SanitySuccess(TestSuccess):
"""Sanity test success."""
def __init__(self, test, python_version=None):
"""
:type test: str
:type python_version: str
"""
super(SanitySuccess, self).__init__(COMMAND, test, python_version)
class SanitySkipped(TestSkipped):
"""Sanity test skipped."""
def __init__(self, test, python_version=None):
"""
:type test: str
:type python_version: str
"""
super(SanitySkipped, self).__init__(COMMAND, test, python_version)
class SanityFailure(TestFailure):
"""Sanity test failure."""
def __init__(self, test, python_version=None, messages=None, summary=None):
"""
:type test: str
:type python_version: str
:type messages: list[SanityMessage]
:type summary: str
"""
super(SanityFailure, self).__init__(COMMAND, test, python_version, messages, summary)
class SanityMessage(TestMessage):
"""Single sanity test message for one file."""
pass
class SanityTargets(object):
"""Sanity test target information."""
def __init__(self, include, exclude, require):
"""
:type include: list[str]
:type exclude: list[str]
:type require: list[str]
"""
self.all = not include
self.targets = tuple(sorted(walk_sanity_targets()))
self.include = walk_internal_targets(self.targets, include, exclude, require)
self.include_external, self.exclude_external = walk_external_targets(self.targets, include, exclude, require)
class SanityTest(object):
"""Sanity test base class."""
def __init__(self, name):
self.name = name
class SanityFunc(SanityTest):
"""Sanity test function information."""
def __init__(self, name, func, intercept=True, script=None):
"""
:type name: str
:type func: (SanityConfig, SanityTargets) -> SanityResult
:type intercept: bool
:type script: str | None
"""
super(SanityFunc, self).__init__(name)
self.func = func
self.intercept = intercept
self.script = script
SANITY_TESTS = (
SanityFunc('shellcheck', command_sanity_shellcheck, intercept=False),
SanityFunc('pep8', command_sanity_pep8, intercept=False),
SanityFunc('pylint', command_sanity_pylint, intercept=False),
SanityFunc('yamllint', command_sanity_yamllint, intercept=False),
SanityFunc('rstcheck', command_sanity_rstcheck, intercept=False),
SanityFunc('sanity-docs', command_sanity_sanity_docs, intercept=False),
SanityFunc('validate-modules', command_sanity_validate_modules, intercept=False),
SanityFunc('ansible-doc', command_sanity_ansible_doc),
SanityFunc('import', command_sanity_import),
)
def sanity_init():
"""Initialize full sanity test list (includes code-smell scripts determined at runtime)."""
global SANITY_TESTS # pylint: disable=locally-disabled, global-statement
SANITY_TESTS = tuple(sorted(SANITY_TESTS + collect_code_smell_tests(), key=lambda k: k.name))
|
gpl-3.0
|
shitolepriya/Saloon_erp
|
erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
|
60
|
3618
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from erpnext.accounts.report.accounts_receivable.accounts_receivable import ReceivablePayableReport
class AccountsReceivableSummary(ReceivablePayableReport):
def run(self, args):
party_naming_by = frappe.db.get_value(args.get("naming_by")[0], None, args.get("naming_by")[1])
return self.get_columns(party_naming_by, args), self.get_data(party_naming_by, args)
def get_columns(self, party_naming_by, args):
columns = [_(args.get("party_type")) + ":Link/" + args.get("party_type") + ":200"]
if party_naming_by == "Naming Series":
columns += [ args.get("party_type") + " Name::140"]
columns += [
_("Total Invoiced Amt") + ":Currency:140",
_("Total Paid Amt") + ":Currency:140",
_("Total Outstanding Amt") + ":Currency:160",
"0-" + str(self.filters.range1) + ":Currency:100",
str(self.filters.range1) + "-" + str(self.filters.range2) + ":Currency:100",
str(self.filters.range2) + "-" + str(self.filters.range3) + ":Currency:100",
str(self.filters.range3) + _("-Above") + ":Currency:100"]
if args.get("party_type") == "Customer":
columns += [_("Territory") + ":Link/Territory:80"]
if args.get("party_type") == "Supplier":
columns += [_("Supplier Type") + ":Link/Supplier Type:80"]
return columns
def get_data(self, party_naming_by, args):
data = []
partywise_total = self.get_partywise_total(party_naming_by, args)
for party, party_dict in partywise_total.items():
row = [party]
if party_naming_by == "Naming Series":
row += [self.get_party_name(args.get("party_type"), party)]
row += [
party_dict.invoiced_amt, party_dict.paid_amt, party_dict.outstanding_amt,
party_dict.range1, party_dict.range2, party_dict.range3, party_dict.range4,
]
if args.get("party_type") == "Customer":
row += [self.get_territory(party)]
if args.get("party_type") == "Supplier":
row += [self.get_supplier_type(party)]
data.append(row)
return data
def get_partywise_total(self, party_naming_by, args):
party_total = frappe._dict()
for d in self.get_voucherwise_data(party_naming_by, args):
party_total.setdefault(d.party,
frappe._dict({
"invoiced_amt": 0,
"paid_amt": 0,
"outstanding_amt": 0,
"range1": 0,
"range2": 0,
"range3": 0,
"range4": 0
})
)
for k in party_total[d.party].keys():
party_total[d.party][k] += d.get(k, 0)
return party_total
def get_voucherwise_data(self, party_naming_by, args):
voucherwise_data = ReceivablePayableReport(self.filters).run(args)[1]
cols = ["posting_date", "party"]
if party_naming_by == "Naming Series":
cols += ["party_name"]
cols += ["voucher_type", "voucher_no", "due_date"]
if args.get("party_type") == "Supplier":
cols += ["bill_no", "bill_date"]
cols += ["invoiced_amt", "paid_amt",
"outstanding_amt", "age", "range1", "range2", "range3", "range4"]
if args.get("party_type") == "Supplier":
cols += ["supplier_type", "remarks"]
if args.get("party_type") == "Customer":
cols += ["territory", "remarks"]
return self.make_data_dict(cols, voucherwise_data)
def make_data_dict(self, cols, data):
data_dict = []
for d in data:
data_dict.append(frappe._dict(zip(cols, d)))
return data_dict
def execute(filters=None):
args = {
"party_type": "Customer",
"naming_by": ["Selling Settings", "cust_master_name"],
}
return AccountsReceivableSummary(filters).run(args)
|
agpl-3.0
|
tinkerinestudio/Tinkerine-Suite
|
TinkerineSuite/python/Lib/OpenGL/GL/SGIX/resample.py
|
4
|
1244
|
'''OpenGL extension SGIX.resample
This module customises the behaviour of the
OpenGL.raw.GL.SGIX.resample to provide a more
Python-friendly API
Overview (from the spec)
This extension enhances the unpacking resampling capabilities
of the SGIX_subsample extension.
When pixel data is received from the client and an unpacking
upsampling mode other than PIXEL_SUBSAMPLE_RATE_4444_SGIX is
specified, the upsampling is performed via one of two methods:
RESAMPLE_REPLICATE_SGIX, RESAMPLE_ZERO_FILL_SGIX.
Replicate and zero fill are provided to
give the application greatest performance and control over the
filtering process.
However, when pixel data is read back to the client and a
packing downsampling mode other than PIXEL_SUBSAMPLE_RATE_4444_SGIX
is specified, downsampling is
performed via simple component decimation (point sampling). That is,
only the RESAMPLE_DECIMATE_SGIX is valid.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/SGIX/resample.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.SGIX.resample import *
### END AUTOGENERATED SECTION
|
agpl-3.0
|
echoi/snac_bmi
|
StGermain/pyre/Debug.py
|
6
|
3662
|
#!/usr/bin/env python
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##
## Copyright (C), 2003, Victorian Partnership for Advanced Computing (VPAC) Ltd, 110 Victoria Street, Melbourne, 3053, Australia.
##
## Authors:
## Stevan M. Quenette, Senior Software Engineer, VPAC. ([email protected])
## Patrick D. Sunter, Software Engineer, VPAC. ([email protected])
## Luke J. Hodkinson, Computational Engineer, VPAC. ([email protected])
## Siew-Ching Tan, Software Engineer, VPAC. ([email protected])
## Alan H. Lo, Computational Engineer, VPAC. ([email protected])
## Raquibul Hassan, Computational Engineer, VPAC. ([email protected])
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this library; if not, write to the Free Software
## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
##
## $Id$
##
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def indent( level ):
str = ''
for i in range( level ):
str += '\t'
return str
def _printRegistry( registry, level ):
print indent( level ) + 'Properties are:'
print indent( level + 1 ) + '---'
for name, descriptor in registry.properties.iteritems():
print indent( level + 1 ) + 'name: ' + name
print indent( level + 1 ) + 'value: ' + descriptor.value
print indent( level + 1 ) + '---'
print indent( level ) + 'Components are:'
print indent( level + 1 ) + '---'
for name, value in registry.facilities.iteritems():
print indent( level + 1 ) + 'name: ' + name
print indent( level + 1 ) + 'value: {'
_printRegistry( value, level + 2 )
print indent( level + 1 ) + '}'
print indent( level + 1 ) + '---'
def printRegistry( application, level = 0 ):
print indent( level ) + 'Input Registry:'
_printRegistry( application.registry, level + 1 )
def _printInventory( inventory, level ):
print indent( level ) + 'Properties are:'
print indent( level + 1 ) + '---'
for name, _value in inventory._traitRegistry.iteritems():
print indent( level + 1 ) + 'name: ' + name
# The raw value itself is stored on the inventory. _value is
# the pyre property of the value.
print indent( level + 1 ) + 'type: ' + _value.type
print indent( level + 1 ) + 'value: ', _value.__get__(inventory)
print indent( level + 1 ) + '---'
print indent( level ) + 'Components are:'
print indent( level + 1 ) + '---'
for name, _value in inventory._facilityRegistry.iteritems():
print indent( level + 1 ) + 'facility name: ' + name
# The raw value itself (i.e. the component) is stored on the
# inventory. _value is the facility of the value.
value = inventory.__getattribute__( name )
print indent( level + 1 ) + 'component name: ' + value.name
print indent( level + 1 ) + 'value: {'
_printInventory( value.inventory, level + 2 )
print indent( level + 1 ) + '}'
print indent( level + 1 ) + '---'
def printInventory( application, level = 0 ):
print indent( level ) + 'Inventory:'
_printInventory( application.inventory, level + 1 )
|
gpl-2.0
|
OCForks/phantomjs
|
src/qt/qtwebkit/Tools/Scripts/webkitpy/style/checkers/xml.py
|
187
|
2044
|
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Checks WebKit style for XML files."""
from __future__ import absolute_import
from xml.parsers import expat
class XMLChecker(object):
"""Processes XML lines for checking style."""
def __init__(self, file_path, handle_style_error):
self._handle_style_error = handle_style_error
self._handle_style_error.turn_off_line_filtering()
def check(self, lines):
parser = expat.ParserCreate()
try:
for line in lines:
parser.Parse(line)
parser.Parse('\n')
parser.Parse('', True)
except expat.ExpatError, error:
self._handle_style_error(error.lineno, 'xml/syntax', 5, expat.ErrorString(error.code))
|
bsd-3-clause
|
xcstacy/kernel-N8000
|
tools/perf/scripts/python/syscall-counts.py
|
11181
|
1522
|
# system call counts
# (c) 2010, Tom Zanussi <[email protected]>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import syscall_name
usage = "perf script -s syscall-counts.py [comm]\n";
for_comm = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if for_comm is not None:
if common_comm != for_comm:
return
try:
syscalls[id] += 1
except TypeError:
syscalls[id] = 1
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"-----------"),
for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
reverse = True):
print "%-40s %10d\n" % (syscall_name(id), val),
|
gpl-2.0
|
lucasdavila/web2py-appreport
|
modules/plugin_appreport/libs/appreport/libs/pisa/libs/reportlab/src/reportlab/graphics/charts/legends.py
|
10
|
27172
|
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/charts/legends.py
__version__=''' $Id: legends.py 3723 2010-06-08 15:46:32Z juraj $ '''
__doc__="""This will be a collection of legends to be used with charts."""
import copy, operator
from reportlab.lib import colors
from reportlab.lib.validators import isNumber, OneOf, isString, isColorOrNone,\
isNumberOrNone, isListOfNumbersOrNone, isStringOrNone, isBoolean,\
EitherOr, NoneOr, AutoOr, isAuto, Auto, isBoxAnchor, SequenceOf, isInstanceOf
from reportlab.lib.attrmap import *
from reportlab.pdfbase.pdfmetrics import stringWidth, getFont
from reportlab.graphics.widgetbase import Widget, TypedPropertyCollection, PropHolder
from reportlab.graphics.shapes import Drawing, Group, String, Rect, Line, STATE_DEFAULTS
from reportlab.graphics.charts.areas import PlotArea
from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol
from reportlab.lib.utils import isSeqType, find_locals
from reportlab.graphics.shapes import _baseGFontName
def _transMax(n,A):
X = n*[0]
m = 0
for a in A:
m = max(m,len(a))
for i,x in enumerate(a):
X[i] = max(X[i],x)
X = [0] + X[:m]
for i in xrange(m):
X[i+1] += X[i]
return X
def _objStr(s):
if isinstance(s,basestring):
return s
else:
return str(s)
def _getStr(s):
if isSeqType(s):
return map(_getStr,s)
else:
return _objStr(s)
def _getLines(s):
if isSeqType(s):
return tuple([(x or '').split('\n') for x in s])
else:
return (s or '').split('\n')
def _getLineCount(s):
T = _getLines(s)
if isSeqType(s):
return max([len(x) for x in T])
else:
return len(T)
def _getWidths(i,s, fontName, fontSize, subCols):
S = []
aS = S.append
if isSeqType(s):
for j,t in enumerate(s):
sc = subCols[j,i]
fN = getattr(sc,'fontName',fontName)
fS = getattr(sc,'fontSize',fontSize)
m = [stringWidth(x, fN, fS) for x in t.split('\n')]
m = max(sc.minWidth,m and max(m) or 0)
aS(m)
aS(sc.rpad)
del S[-1]
else:
sc = subCols[0,i]
fN = getattr(sc,'fontName',fontName)
fS = getattr(sc,'fontSize',fontSize)
m = [stringWidth(x, fN, fS) for x in s.split('\n')]
aS(max(sc.minWidth,m and max(m) or 0))
return S
class SubColProperty(PropHolder):
dividerLines = 0
_attrMap = AttrMap(
minWidth = AttrMapValue(isNumber,desc="minimum width for this subcol"),
rpad = AttrMapValue(isNumber,desc="right padding for this subcol"),
align = AttrMapValue(OneOf('left','right','center','centre','numeric'),desc='alignment in subCol'),
fontName = AttrMapValue(isString, desc="Font name of the strings"),
fontSize = AttrMapValue(isNumber, desc="Font size of the strings"),
leading = AttrMapValue(isNumber, desc="leading for the strings"),
fillColor = AttrMapValue(isColorOrNone, desc="fontColor"),
underlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="underline definitions"),
overlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="overline definitions"),
dx = AttrMapValue(isNumber, desc="x offset from default position"),
dy = AttrMapValue(isNumber, desc="y offset from default position"),
)
class LegendCallout:
def _legendValues(legend,*args):
'''return a tuple of values from the first function up the stack with isinstance(self,legend)'''
L = find_locals(lambda L: L.get('self',None) is legend and L or None)
return tuple([L[a] for a in args])
_legendValues = staticmethod(_legendValues)
def _selfOrLegendValues(self,legend,*args):
L = find_locals(lambda L: L.get('self',None) is legend and L or None)
return tuple([getattr(self,a,L[a]) for a in args])
def __call__(self,legend,g,thisx,y,colName):
col, name = colName
class LegendSwatchCallout(LegendCallout):
def __call__(self,legend,g,thisx,y,i,colName,swatch):
col, name = colName
class LegendColEndCallout(LegendCallout):
def __call__(self,legend, g, x, xt, y, width, lWidth):
pass
class Legend(Widget):
"""A simple legend containing rectangular swatches and strings.
The swatches are filled rectangles whenever the respective
color object in 'colorNamePairs' is a subclass of Color in
reportlab.lib.colors. Otherwise the object passed instead is
assumed to have 'x', 'y', 'width' and 'height' attributes.
A legend then tries to set them or catches any error. This
lets you plug-in any widget you like as a replacement for
the default rectangular swatches.
Strings can be nicely aligned left or right to the swatches.
"""
_attrMap = AttrMap(
x = AttrMapValue(isNumber, desc="x-coordinate of upper-left reference point"),
y = AttrMapValue(isNumber, desc="y-coordinate of upper-left reference point"),
deltax = AttrMapValue(isNumberOrNone, desc="x-distance between neighbouring swatches"),
deltay = AttrMapValue(isNumberOrNone, desc="y-distance between neighbouring swatches"),
dxTextSpace = AttrMapValue(isNumber, desc="Distance between swatch rectangle and text"),
autoXPadding = AttrMapValue(isNumber, desc="x Padding between columns if deltax=None",advancedUsage=1),
autoYPadding = AttrMapValue(isNumber, desc="y Padding between rows if deltay=None",advancedUsage=1),
yGap = AttrMapValue(isNumber, desc="Additional gap between rows",advancedUsage=1),
dx = AttrMapValue(isNumber, desc="Width of swatch rectangle"),
dy = AttrMapValue(isNumber, desc="Height of swatch rectangle"),
columnMaximum = AttrMapValue(isNumber, desc="Max. number of items per column"),
alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text with respect to swatches"),
colorNamePairs = AttrMapValue(None, desc="List of color/name tuples (color can also be widget)"),
fontName = AttrMapValue(isString, desc="Font name of the strings"),
fontSize = AttrMapValue(isNumber, desc="Font size of the strings"),
fillColor = AttrMapValue(isColorOrNone, desc="swatches filling color"),
strokeColor = AttrMapValue(isColorOrNone, desc="Border color of the swatches"),
strokeWidth = AttrMapValue(isNumber, desc="Width of the border color of the swatches"),
swatchMarker = AttrMapValue(NoneOr(AutoOr(isSymbol)), desc="None, Auto() or makeMarker('Diamond') ...",advancedUsage=1),
callout = AttrMapValue(None, desc="a user callout(self,g,x,y,(color,text))",advancedUsage=1),
boxAnchor = AttrMapValue(isBoxAnchor,'Anchor point for the legend area'),
variColumn = AttrMapValue(isBoolean,'If true column widths may vary (default is false)',advancedUsage=1),
dividerLines = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),'If 1 we have dividers between the rows | 2 for extra top | 4 for bottom',advancedUsage=1),
dividerWidth = AttrMapValue(isNumber, desc="dividerLines width",advancedUsage=1),
dividerColor = AttrMapValue(isColorOrNone, desc="dividerLines color",advancedUsage=1),
dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.',advancedUsage=1),
dividerOffsX = AttrMapValue(SequenceOf(isNumber,emptyOK=0,lo=2,hi=2), desc='divider lines X offsets',advancedUsage=1),
dividerOffsY = AttrMapValue(isNumber, desc="dividerLines Y offset",advancedUsage=1),
colEndCallout = AttrMapValue(None, desc="a user callout(self,g, x, xt, y,width, lWidth)",advancedUsage=1),
subCols = AttrMapValue(None,desc="subColumn properties"),
swatchCallout = AttrMapValue(None, desc="a user swatch callout(self,g,x,y,i,(col,name),swatch)",advancedUsage=1),
swdx = AttrMapValue(isNumber, desc="x position adjustment for the swatch"),
swdy = AttrMapValue(isNumber, desc="y position adjustment for the swatch"),
)
def __init__(self):
# Upper-left reference point.
self.x = 0
self.y = 0
# Alginment of text with respect to swatches.
self.alignment = "left"
# x- and y-distances between neighbouring swatches.
self.deltax = 75
self.deltay = 20
self.autoXPadding = 5
self.autoYPadding = 2
# Size of swatch rectangle.
self.dx = 10
self.dy = 10
self.swdx = 0
self.swdy = 0
# Distance between swatch rectangle and text.
self.dxTextSpace = 10
# Max. number of items per column.
self.columnMaximum = 3
# Color/name pairs.
self.colorNamePairs = [ (colors.red, "red"),
(colors.blue, "blue"),
(colors.green, "green"),
(colors.pink, "pink"),
(colors.yellow, "yellow") ]
# Font name and size of the labels.
self.fontName = STATE_DEFAULTS['fontName']
self.fontSize = STATE_DEFAULTS['fontSize']
self.fillColor = STATE_DEFAULTS['fillColor']
self.strokeColor = STATE_DEFAULTS['strokeColor']
self.strokeWidth = STATE_DEFAULTS['strokeWidth']
self.swatchMarker = None
self.boxAnchor = 'nw'
self.yGap = 0
self.variColumn = 0
self.dividerLines = 0
self.dividerWidth = 0.5
self.dividerDashArray = None
self.dividerColor = colors.black
self.dividerOffsX = (0,0)
self.dividerOffsY = 0
self.colEndCallout = None
self._init_subCols()
def _init_subCols(self):
sc = self.subCols = TypedPropertyCollection(SubColProperty)
sc.rpad = 1
sc.dx = sc.dy = sc.minWidth = 0
sc.align = 'right'
sc[0].align = 'left'
def _getChartStyleName(self,chart):
for a in 'lines', 'bars', 'slices', 'strands':
if hasattr(chart,a): return a
return None
def _getChartStyle(self,chart):
return getattr(chart,self._getChartStyleName(chart),None)
def _getTexts(self,colorNamePairs):
if not isAuto(colorNamePairs):
texts = [_getStr(p[1]) for p in colorNamePairs]
else:
chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None))
texts = [chart.getSeriesName(i,'series %d' % i) for i in xrange(chart._seriesCount)]
return texts
def _calculateMaxBoundaries(self, colorNamePairs):
"Calculate the maximum width of some given strings."
fontName = self.fontName
fontSize = self.fontSize
subCols = self.subCols
M = [_getWidths(i, m, fontName, fontSize, subCols) for i,m in enumerate(self._getTexts(colorNamePairs))]
if not M:
return [0,0]
n = max([len(m) for m in M])
if self.variColumn:
columnMaximum = self.columnMaximum
return [_transMax(n,M[r:r+columnMaximum]) for r in xrange(0,len(M),self.columnMaximum)]
else:
return _transMax(n,M)
def _calcHeight(self):
dy = self.dy
yGap = self.yGap
thisy = upperlefty = self.y - dy
fontSize = self.fontSize
ascent=getFont(self.fontName).face.ascent/1000.
if ascent==0: ascent=0.718 # default (from helvetica)
ascent *= fontSize
leading = fontSize*1.2
deltay = self.deltay
if not deltay: deltay = max(dy,leading)+self.autoYPadding
columnCount = 0
count = 0
lowy = upperlefty
lim = self.columnMaximum - 1
for name in self._getTexts(self.colorNamePairs):
y0 = thisy+(dy-ascent)*0.5
y = y0 - _getLineCount(name)*leading
leadingMove = 2*y0-y-thisy
newy = thisy-max(deltay,leadingMove)-yGap
lowy = min(y,newy,lowy)
if count==lim:
count = 0
thisy = upperlefty
columnCount = columnCount + 1
else:
thisy = newy
count = count+1
return upperlefty - lowy
def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor):
return Rect(x, thisy, dx, dy,
fillColor = fillColor,
strokeColor = strokeColor,
strokeWidth = strokeWidth,
)
def draw(self):
colorNamePairs = self.colorNamePairs
autoCP = isAuto(colorNamePairs)
if autoCP:
chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None))
swatchMarker = None
autoCP = Auto(obj=chart)
n = chart._seriesCount
chartTexts = self._getTexts(colorNamePairs)
else:
swatchMarker = getattr(self,'swatchMarker',None)
if isAuto(swatchMarker):
chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None))
swatchMarker = Auto(obj=chart)
n = len(colorNamePairs)
dx = self.dx
dy = self.dy
alignment = self.alignment
columnMaximum = self.columnMaximum
deltax = self.deltax
deltay = self.deltay
dxTextSpace = self.dxTextSpace
fontName = self.fontName
fontSize = self.fontSize
fillColor = self.fillColor
strokeWidth = self.strokeWidth
strokeColor = self.strokeColor
subCols = self.subCols
leading = fontSize*1.2
yGap = self.yGap
if not deltay:
deltay = max(dy,leading)+self.autoYPadding
ba = self.boxAnchor
maxWidth = self._calculateMaxBoundaries(colorNamePairs)
nCols = int((n+columnMaximum-1)/(columnMaximum*1.0))
xW = dx+dxTextSpace+self.autoXPadding
variColumn = self.variColumn
if variColumn:
width = reduce(operator.add,[m[-1] for m in maxWidth],0)+xW*nCols
else:
deltax = max(maxWidth[-1]+xW,deltax)
width = maxWidth[-1]+nCols*deltax
maxWidth = nCols*[maxWidth]
thisx = self.x
thisy = self.y - self.dy
if ba not in ('ne','n','nw','autoy'):
height = self._calcHeight()
if ba in ('e','c','w'):
thisy += height/2.
else:
thisy += height
if ba not in ('nw','w','sw','autox'):
if ba in ('n','c','s'):
thisx -= width/2
else:
thisx -= width
upperlefty = thisy
g = Group()
ascent=getFont(fontName).face.ascent/1000.
if ascent==0: ascent=0.718 # default (from helvetica)
ascent *= fontSize # normalize
lim = columnMaximum - 1
callout = getattr(self,'callout',None)
scallout = getattr(self,'swatchCallout',None)
dividerLines = self.dividerLines
if dividerLines:
dividerWidth = self.dividerWidth
dividerColor = self.dividerColor
dividerDashArray = self.dividerDashArray
dividerOffsX = self.dividerOffsX
dividerOffsY = self.dividerOffsY
for i in xrange(n):
if autoCP:
col = autoCP
col.index = i
name = chartTexts[i]
else:
col, name = colorNamePairs[i]
if isAuto(swatchMarker):
col = swatchMarker
col.index = i
if isAuto(name):
name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i)
T = _getLines(name)
S = []
aS = S.append
j = int(i/(columnMaximum*1.0))
jOffs = maxWidth[j]
# thisy+dy/2 = y+leading/2
y = y0 = thisy+(dy-ascent)*0.5
if callout: callout(self,g,thisx,y,(col,name))
if alignment == "left":
x = thisx
xn = thisx+jOffs[-1]+dxTextSpace
elif alignment == "right":
x = thisx+dx+dxTextSpace
xn = thisx
else:
raise ValueError, "bad alignment"
if not isSeqType(name):
T = [T]
yd = y
for k,lines in enumerate(T):
y = y0
kk = k*2
x1 = x+jOffs[kk]
x2 = x+jOffs[kk+1]
sc = subCols[k,i]
anchor = sc.align
scdx = sc.dx
scdy = sc.dy
fN = getattr(sc,'fontName',fontName)
fS = getattr(sc,'fontSize',fontSize)
fC = getattr(sc,'fillColor',fillColor)
fL = getattr(sc,'leading',1.2*fontSize)
if fN==fontName:
fA = (ascent*fS)/fontSize
else:
fA = getFont(fontName).face.ascent/1000.
if fA==0: fA=0.718
fA *= fS
if anchor=='left':
anchor = 'start'
xoffs = x1
elif anchor=='right':
anchor = 'end'
xoffs = x2
elif anchor=='numeric':
xoffs = x2
else:
anchor = 'middle'
xoffs = 0.5*(x1+x2)
for t in lines:
aS(String(xoffs+scdx,y+scdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor))
y -= fL
yd = min(yd,y)
y += fL
for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')):
il = getattr(sc,a,None)
if il:
if not isinstance(il,(tuple,list)): il = (il,)
for l in il:
l = copy.copy(l)
l.y1 += iy
l.y2 += iy
l.x1 += x1
l.x2 += x2
aS(l)
x = xn
y = yd
leadingMove = 2*y0-y-thisy
if dividerLines:
xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1]
yd = thisy+dy*0.5+dividerOffsY
if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum):
g.add(Line(thisx+dividerOffsX[0],yd,xd,yd,
strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray))
if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)):
yd -= max(deltay,leadingMove)+yGap
g.add(Line(thisx+dividerOffsX[0],yd,xd,yd,
strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray))
# Make a 'normal' color swatch...
swatchX = x + getattr(self,'swdx',0)
swatchY = thisy + getattr(self,'swdy',0)
if isAuto(col):
chart = getattr(col,'chart',getattr(col,'obj',None))
c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy)
elif isinstance(col, colors.Color):
if isSymbol(swatchMarker):
c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col)
else:
c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor)
elif col is not None:
try:
c = copy.deepcopy(col)
c.x = swatchX
c.y = swatchY
c.width = dx
c.height = dy
except:
c = None
else:
c = None
if c:
g.add(c)
if scallout: scallout(self,g,thisx,y0,i,(col,name),c)
for s in S: g.add(s)
if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)):
if alignment == "left":
xt = thisx
else:
xt = thisx+dx+dxTextSpace
yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap)
self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace)
if i%columnMaximum==lim:
if variColumn:
thisx += jOffs[-1]+xW
else:
thisx = thisx+deltax
thisy = upperlefty
else:
thisy = thisy-max(deltay,leadingMove)-yGap
return g
def demo(self):
"Make sample legend."
d = Drawing(200, 100)
legend = Legend()
legend.alignment = 'left'
legend.x = 0
legend.y = 100
legend.dxTextSpace = 5
items = 'red green blue yellow pink black white'.split()
items = map(lambda i:(getattr(colors, i), i), items)
legend.colorNamePairs = items
d.add(legend, 'legend')
return d
class TotalAnnotator(LegendColEndCallout):
def __init__(self, lText='Total', rText='0.0', fontName=_baseGFontName, fontSize=10,
fillColor=colors.black, strokeWidth=0.5, strokeColor=colors.black, strokeDashArray=None,
dx=0, dy=0, dly=0, dlx=(0,0)):
self.lText = lText
self.rText = rText
self.fontName = fontName
self.fontSize = fontSize
self.fillColor = fillColor
self.dy = dy
self.dx = dx
self.dly = dly
self.dlx = dlx
self.strokeWidth = strokeWidth
self.strokeColor = strokeColor
self.strokeDashArray = strokeDashArray
def __call__(self,legend, g, x, xt, y, width, lWidth):
from reportlab.graphics.shapes import String, Line
fontSize = self.fontSize
fontName = self.fontName
fillColor = self.fillColor
strokeColor = self.strokeColor
strokeWidth = self.strokeWidth
ascent=getFont(fontName).face.ascent/1000.
if ascent==0: ascent=0.718 # default (from helvetica)
ascent *= fontSize
leading = fontSize*1.2
yt = y+self.dy-ascent*1.3
if self.lText and fillColor:
g.add(String(xt,yt,self.lText,
fontName=fontName,
fontSize=fontSize,
fillColor=fillColor,
textAnchor = "start"))
if self.rText:
g.add(String(xt+width,yt,self.rText,
fontName=fontName,
fontSize=fontSize,
fillColor=fillColor,
textAnchor = "end"))
if strokeWidth and strokeColor:
yL = y+self.dly-leading
g.add(Line(x+self.dlx[0],yL,x+self.dlx[1]+lWidth,yL,
strokeColor=strokeColor, strokeWidth=strokeWidth,
strokeDashArray=self.strokeDashArray))
class LineSwatch(Widget):
"""basically a Line with properties added so it can be used in a LineLegend"""
_attrMap = AttrMap(
x = AttrMapValue(isNumber, desc="x-coordinate for swatch line start point"),
y = AttrMapValue(isNumber, desc="y-coordinate for swatch line start point"),
width = AttrMapValue(isNumber, desc="length of swatch line"),
height = AttrMapValue(isNumber, desc="used for line strokeWidth"),
strokeColor = AttrMapValue(isColorOrNone, desc="color of swatch line"),
strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc="dash array for swatch line"),
)
def __init__(self):
from reportlab.lib.colors import red
from reportlab.graphics.shapes import Line
self.x = 0
self.y = 0
self.width = 20
self.height = 1
self.strokeColor = red
self.strokeDashArray = None
def draw(self):
l = Line(self.x,self.y,self.x+self.width,self.y)
l.strokeColor = self.strokeColor
l.strokeDashArray = self.strokeDashArray
l.strokeWidth = self.height
return l
class LineLegend(Legend):
"""A subclass of Legend for drawing legends with lines as the
swatches rather than rectangles. Useful for lineCharts and
linePlots. Should be similar in all other ways the the standard
Legend class.
"""
def __init__(self):
Legend.__init__(self)
# Size of swatch rectangle.
self.dx = 10
self.dy = 2
def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor):
l = LineSwatch()
l.x = x
l.y = thisy
l.width = dx
l.height = dy
l.strokeColor = fillColor
return l
def sample1c():
"Make sample legend."
d = Drawing(200, 100)
legend = Legend()
legend.alignment = 'right'
legend.x = 0
legend.y = 100
legend.dxTextSpace = 5
items = 'red green blue yellow pink black white'.split()
items = map(lambda i:(getattr(colors, i), i), items)
legend.colorNamePairs = items
d.add(legend, 'legend')
return d
def sample2c():
"Make sample legend."
d = Drawing(200, 100)
legend = Legend()
legend.alignment = 'right'
legend.x = 20
legend.y = 90
legend.deltax = 60
legend.dxTextSpace = 10
legend.columnMaximum = 4
items = 'red green blue yellow pink black white'.split()
items = map(lambda i:(getattr(colors, i), i), items)
legend.colorNamePairs = items
d.add(legend, 'legend')
return d
def sample3():
"Make sample legend with line swatches."
d = Drawing(200, 100)
legend = LineLegend()
legend.alignment = 'right'
legend.x = 20
legend.y = 90
legend.deltax = 60
legend.dxTextSpace = 10
legend.columnMaximum = 4
items = 'red green blue yellow pink black white'.split()
items = map(lambda i:(getattr(colors, i), i), items)
legend.colorNamePairs = items
d.add(legend, 'legend')
return d
def sample3a():
"Make sample legend with line swatches and dasharrays on the lines."
d = Drawing(200, 100)
legend = LineLegend()
legend.alignment = 'right'
legend.x = 20
legend.y = 90
legend.deltax = 60
legend.dxTextSpace = 10
legend.columnMaximum = 4
items = 'red green blue yellow pink black white'.split()
darrays = ([2,1], [2,5], [2,2,5,5], [1,2,3,4], [4,2,3,4], [1,2,3,4,5,6], [1])
cnp = []
for i in range(0, len(items)):
l = LineSwatch()
l.strokeColor = getattr(colors, items[i])
l.strokeDashArray = darrays[i]
cnp.append((l, items[i]))
legend.colorNamePairs = cnp
d.add(legend, 'legend')
return d
|
lgpl-3.0
|
rugebiker/Contrarreloj
|
src/ventanaregistro.py
|
1
|
7601
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ventanaregistro.ui'
#
# Created: Fri Jan 14 19:31:48 2011
# by: PyQt4 UI code generator 4.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_ventanaregistro(object):
def setupUi(self, ventanaregistro):
ventanaregistro.setObjectName(_fromUtf8("ventanaregistro"))
ventanaregistro.resize(727, 485)
self.verticalLayout = QtGui.QVBoxLayout(ventanaregistro)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label = QtGui.QLabel(ventanaregistro)
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
self.gridLayout = QtGui.QGridLayout()
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label_2 = QtGui.QLabel(ventanaregistro)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
self.label_3 = QtGui.QLabel(ventanaregistro)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
self.label_4 = QtGui.QLabel(ventanaregistro)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.gridLayout.addWidget(self.label_4, 3, 0, 1, 1)
self.textonumero = QtGui.QLineEdit(ventanaregistro)
self.textonumero.setReadOnly(True)
self.textonumero.setObjectName(_fromUtf8("textonumero"))
self.gridLayout.addWidget(self.textonumero, 0, 1, 1, 1)
self.textonombre = QtGui.QLineEdit(ventanaregistro)
self.textonombre.setObjectName(_fromUtf8("textonombre"))
self.gridLayout.addWidget(self.textonombre, 2, 1, 1, 1)
self.textoequipo = QtGui.QLineEdit(ventanaregistro)
self.textoequipo.setObjectName(_fromUtf8("textoequipo"))
self.gridLayout.addWidget(self.textoequipo, 3, 1, 1, 1)
self.label_5 = QtGui.QLabel(ventanaregistro)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.gridLayout.addWidget(self.label_5, 4, 0, 1, 1)
spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 0, 2, 1, 1)
spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem1, 2, 4, 1, 1)
self.textolicencia = QtGui.QLineEdit(ventanaregistro)
self.textolicencia.setObjectName(_fromUtf8("textolicencia"))
self.gridLayout.addWidget(self.textolicencia, 1, 1, 1, 1)
self.label_6 = QtGui.QLabel(ventanaregistro)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.gridLayout.addWidget(self.label_6, 1, 0, 1, 1)
self.botonretirar = QtGui.QPushButton(ventanaregistro)
self.botonretirar.setObjectName(_fromUtf8("botonretirar"))
self.gridLayout.addWidget(self.botonretirar, 3, 3, 1, 1)
self.botonagregar = QtGui.QPushButton(ventanaregistro)
self.botonagregar.setObjectName(_fromUtf8("botonagregar"))
self.gridLayout.addWidget(self.botonagregar, 1, 3, 1, 1)
self.cajacategorias = QtGui.QComboBox(ventanaregistro)
self.cajacategorias.setObjectName(_fromUtf8("cajacategorias"))
self.gridLayout.addWidget(self.cajacategorias, 4, 1, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.treearbol = QtGui.QTreeWidget(ventanaregistro)
self.treearbol.setObjectName(_fromUtf8("treearbol"))
self.verticalLayout.addWidget(self.treearbol)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem3)
self.botoncerrar = QtGui.QPushButton(ventanaregistro)
self.botoncerrar.setObjectName(_fromUtf8("botoncerrar"))
self.horizontalLayout.addWidget(self.botoncerrar)
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem4)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(ventanaregistro)
QtCore.QObject.connect(self.botoncerrar, QtCore.SIGNAL(_fromUtf8("clicked()")), ventanaregistro.close)
QtCore.QMetaObject.connectSlotsByName(ventanaregistro)
ventanaregistro.setTabOrder(self.textolicencia, self.textonombre)
ventanaregistro.setTabOrder(self.textonombre, self.textoequipo)
ventanaregistro.setTabOrder(self.textoequipo, self.cajacategorias)
ventanaregistro.setTabOrder(self.cajacategorias, self.botonagregar)
ventanaregistro.setTabOrder(self.botonagregar, self.botonretirar)
ventanaregistro.setTabOrder(self.botonretirar, self.treearbol)
ventanaregistro.setTabOrder(self.treearbol, self.botoncerrar)
ventanaregistro.setTabOrder(self.botoncerrar, self.textonumero)
def retranslateUi(self, ventanaregistro):
ventanaregistro.setWindowTitle(QtGui.QApplication.translate("ventanaregistro", "Contrarreloj - Registro", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("ventanaregistro", "<center>Registro</center>", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("ventanaregistro", "Número", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("ventanaregistro", "Nombre", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("ventanaregistro", "Equipo", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("ventanaregistro", "Categoría", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("ventanaregistro", "Licencia", None, QtGui.QApplication.UnicodeUTF8))
self.botonretirar.setText(QtGui.QApplication.translate("ventanaregistro", "Retirar el último elemento", None, QtGui.QApplication.UnicodeUTF8))
self.botonagregar.setText(QtGui.QApplication.translate("ventanaregistro", "Agregar", None, QtGui.QApplication.UnicodeUTF8))
self.treearbol.headerItem().setText(0, QtGui.QApplication.translate("ventanaregistro", "Número", None, QtGui.QApplication.UnicodeUTF8))
self.treearbol.headerItem().setText(1, QtGui.QApplication.translate("ventanaregistro", "Licencia", None, QtGui.QApplication.UnicodeUTF8))
self.treearbol.headerItem().setText(2, QtGui.QApplication.translate("ventanaregistro", "Nombre", None, QtGui.QApplication.UnicodeUTF8))
self.treearbol.headerItem().setText(3, QtGui.QApplication.translate("ventanaregistro", "Equipo", None, QtGui.QApplication.UnicodeUTF8))
self.treearbol.headerItem().setText(4, QtGui.QApplication.translate("ventanaregistro", "Categoría", None, QtGui.QApplication.UnicodeUTF8))
self.botoncerrar.setText(QtGui.QApplication.translate("ventanaregistro", "Cerrar", None, QtGui.QApplication.UnicodeUTF8))
|
gpl-3.0
|
adieu/python-openid
|
openid/test/test_extension.py
|
77
|
1293
|
from openid import extension
from openid import message
import unittest
class DummyExtension(extension.Extension):
ns_uri = 'http://an.extension/'
ns_alias = 'dummy'
def getExtensionArgs(self):
return {}
class ToMessageTest(unittest.TestCase):
def test_OpenID1(self):
oid1_msg = message.Message(message.OPENID1_NS)
ext = DummyExtension()
ext.toMessage(oid1_msg)
namespaces = oid1_msg.namespaces
self.failUnless(namespaces.isImplicit(DummyExtension.ns_uri))
self.failUnlessEqual(
DummyExtension.ns_uri,
namespaces.getNamespaceURI(DummyExtension.ns_alias))
self.failUnlessEqual(DummyExtension.ns_alias,
namespaces.getAlias(DummyExtension.ns_uri))
def test_OpenID2(self):
oid2_msg = message.Message(message.OPENID2_NS)
ext = DummyExtension()
ext.toMessage(oid2_msg)
namespaces = oid2_msg.namespaces
self.failIf(namespaces.isImplicit(DummyExtension.ns_uri))
self.failUnlessEqual(
DummyExtension.ns_uri,
namespaces.getNamespaceURI(DummyExtension.ns_alias))
self.failUnlessEqual(DummyExtension.ns_alias,
namespaces.getAlias(DummyExtension.ns_uri))
|
apache-2.0
|
adviti/melange
|
thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/utils/dateformat.py
|
39
|
5828
|
from datetime import datetime, date
import os
import time
import unittest
from django.utils.dateformat import format
from django.utils import dateformat, translation
from django.utils.tzinfo import FixedOffset, LocalTimezone
class DateFormatTests(unittest.TestCase):
def setUp(self):
self.old_TZ = os.environ.get('TZ')
os.environ['TZ'] = 'Europe/Copenhagen'
translation.activate('en-us')
try:
# Check if a timezone has been set
time.tzset()
self.tz_tests = True
except AttributeError:
# No timezone available. Don't run the tests that require a TZ
self.tz_tests = False
def tearDown(self):
if self.old_TZ is None:
del os.environ['TZ']
else:
os.environ['TZ'] = self.old_TZ
# Cleanup - force re-evaluation of TZ environment variable.
if self.tz_tests:
time.tzset()
def test_date(self):
d = date(2009, 5, 16)
self.assertEquals(date.fromtimestamp(int(format(d, 'U'))), d)
def test_naive_datetime(self):
dt = datetime(2009, 5, 16, 5, 30, 30)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt)
def test_datetime_with_local_tzinfo(self):
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=ltz)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None))
def test_datetime_with_tzinfo(self):
tz = FixedOffset(-510)
ltz = LocalTimezone(datetime.now())
dt = datetime(2009, 5, 16, 5, 30, 30, tzinfo=tz)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
self.assertEquals(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple())
def test_epoch(self):
utc = FixedOffset(0)
udt = datetime(1970, 1, 1, tzinfo=utc)
self.assertEquals(format(udt, 'U'), u'0')
def test_empty_format(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, ''), u'')
def test_am_pm(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, 'a'), u'p.m.')
def test_date_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
self.assertEquals(dateformat.format(my_birthday, 'A'), u'PM')
self.assertEquals(dateformat.format(timestamp, 'c'), u'2008-05-19T11:45:23.123456')
self.assertEquals(dateformat.format(my_birthday, 'd'), u'08')
self.assertEquals(dateformat.format(my_birthday, 'j'), u'8')
self.assertEquals(dateformat.format(my_birthday, 'l'), u'Sunday')
self.assertEquals(dateformat.format(my_birthday, 'L'), u'False')
self.assertEquals(dateformat.format(my_birthday, 'm'), u'07')
self.assertEquals(dateformat.format(my_birthday, 'M'), u'Jul')
self.assertEquals(dateformat.format(my_birthday, 'b'), u'jul')
self.assertEquals(dateformat.format(my_birthday, 'n'), u'7')
self.assertEquals(dateformat.format(my_birthday, 'N'), u'July')
def test_time_formats(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, 'P'), u'10 p.m.')
self.assertEquals(dateformat.format(my_birthday, 's'), u'00')
self.assertEquals(dateformat.format(my_birthday, 'S'), u'th')
self.assertEquals(dateformat.format(my_birthday, 't'), u'31')
self.assertEquals(dateformat.format(my_birthday, 'w'), u'0')
self.assertEquals(dateformat.format(my_birthday, 'W'), u'27')
self.assertEquals(dateformat.format(my_birthday, 'y'), u'79')
self.assertEquals(dateformat.format(my_birthday, 'Y'), u'1979')
self.assertEquals(dateformat.format(my_birthday, 'z'), u'189')
def test_dateformat(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
self.assertEquals(dateformat.format(my_birthday, r'Y z \C\E\T'), u'1979 189 CET')
self.assertEquals(dateformat.format(my_birthday, r'jS o\f F'), u'8th of July')
def test_futuredates(self):
the_future = datetime(2100, 10, 25, 0, 00)
self.assertEquals(dateformat.format(the_future, r'Y'), u'2100')
def test_timezones(self):
my_birthday = datetime(1979, 7, 8, 22, 00)
summertime = datetime(2005, 10, 30, 1, 00)
wintertime = datetime(2005, 10, 30, 4, 00)
timestamp = datetime(2008, 5, 19, 11, 45, 23, 123456)
if self.tz_tests:
self.assertEquals(dateformat.format(my_birthday, 'O'), u'+0100')
self.assertEquals(dateformat.format(my_birthday, 'r'), u'Sun, 8 Jul 1979 22:00:00 +0100')
self.assertEquals(dateformat.format(my_birthday, 'T'), u'CET')
self.assertEquals(dateformat.format(my_birthday, 'U'), u'300315600')
self.assertEquals(dateformat.format(timestamp, 'u'), u'123456')
self.assertEquals(dateformat.format(my_birthday, 'Z'), u'3600')
self.assertEquals(dateformat.format(summertime, 'I'), u'1')
self.assertEquals(dateformat.format(summertime, 'O'), u'+0200')
self.assertEquals(dateformat.format(wintertime, 'I'), u'0')
self.assertEquals(dateformat.format(wintertime, 'O'), u'+0100')
|
apache-2.0
|
ProfessionalIT/professionalit-webiste
|
sdk/google_appengine/google/appengine/ext/datastore_admin/backup_pb2.py
|
6
|
17101
|
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
import google
from google.net.proto2.python.public import descriptor as _descriptor
from google.net.proto2.python.public import message as _message
from google.net.proto2.python.public import reflection as _reflection
from google.net.proto2.python.public import symbol_database as _symbol_database
from google.net.proto2.proto import descriptor_pb2
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='apphosting/ext/datastore_admin/backup.proto',
package='apphosting.ext.datastore_admin',
syntax='proto2',
serialized_pb=_b('\n+apphosting/ext/datastore_admin/backup.proto\x12\x1e\x61pphosting.ext.datastore_admin\"\x8c\x01\n\x06\x42\x61\x63kup\x12?\n\x0b\x62\x61\x63kup_info\x18\x01 \x01(\x0b\x32*.apphosting.ext.datastore_admin.BackupInfo\x12\x41\n\tkind_info\x18\x02 \x03(\x0b\x32..apphosting.ext.datastore_admin.KindBackupInfo\"Q\n\nBackupInfo\x12\x13\n\x0b\x62\x61\x63kup_name\x18\x01 \x01(\t\x12\x17\n\x0fstart_timestamp\x18\x02 \x01(\x03\x12\x15\n\rend_timestamp\x18\x03 \x01(\x03\"\x8c\x01\n\x0eKindBackupInfo\x12\x0c\n\x04kind\x18\x01 \x02(\t\x12\x0c\n\x04\x66ile\x18\x02 \x03(\t\x12\x43\n\rentity_schema\x18\x03 \x01(\x0b\x32,.apphosting.ext.datastore_admin.EntitySchema\x12\x19\n\nis_partial\x18\x04 \x01(\x08:\x05\x66\x61lse\"\x90\x05\n\x0c\x45ntitySchema\x12\x0c\n\x04kind\x18\x01 \x01(\t\x12\x41\n\x05\x66ield\x18\x02 \x03(\x0b\x32\x32.apphosting.ext.datastore_admin.EntitySchema.Field\x1a\xb2\x01\n\x04Type\x12\x0f\n\x07is_list\x18\x01 \x01(\x08\x12R\n\x0eprimitive_type\x18\x02 \x03(\x0e\x32:.apphosting.ext.datastore_admin.EntitySchema.PrimitiveType\x12\x45\n\x0f\x65mbedded_schema\x18\x03 \x03(\x0b\x32,.apphosting.ext.datastore_admin.EntitySchema\x1aj\n\x05\x46ield\x12\x0c\n\x04name\x18\x01 \x02(\t\x12?\n\x04type\x18\x02 \x03(\x0b\x32\x31.apphosting.ext.datastore_admin.EntitySchema.Type\x12\x12\n\nfield_name\x18\x03 \x01(\t\"\x8d\x02\n\rPrimitiveType\x12\t\n\x05\x46LOAT\x10\x00\x12\x0b\n\x07INTEGER\x10\x01\x12\x0b\n\x07\x42OOLEAN\x10\x02\x12\n\n\x06STRING\x10\x03\x12\r\n\tDATE_TIME\x10\x04\x12\n\n\x06RATING\x10\x05\x12\x08\n\x04LINK\x10\x06\x12\x0c\n\x08\x43\x41TEGORY\x10\x07\x12\x10\n\x0cPHONE_NUMBER\x10\x08\x12\x12\n\x0ePOSTAL_ADDRESS\x10\t\x12\t\n\x05\x45MAIL\x10\n\x12\r\n\tIM_HANDLE\x10\x0b\x12\x0c\n\x08\x42LOB_KEY\x10\x0c\x12\x08\n\x04TEXT\x10\r\x12\x08\n\x04\x42LOB\x10\x0e\x12\x0e\n\nSHORT_BLOB\x10\x0f\x12\x08\n\x04USER\x10\x10\x12\r\n\tGEO_POINT\x10\x11\x12\r\n\tREFERENCE\x10\x12\x42\x14\x10\x02 \x02(\x02\x42\x0c\x42\x61\x63kupProtos')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_ENTITYSCHEMA_PRIMITIVETYPE = _descriptor.EnumDescriptor(
name='PrimitiveType',
full_name='apphosting.ext.datastore_admin.EntitySchema.PrimitiveType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='FLOAT', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='INTEGER', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='BOOLEAN', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='STRING', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DATE_TIME', index=4, number=4,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='RATING', index=5, number=5,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='LINK', index=6, number=6,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='CATEGORY', index=7, number=7,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='PHONE_NUMBER', index=8, number=8,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='POSTAL_ADDRESS', index=9, number=9,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='EMAIL', index=10, number=10,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='IM_HANDLE', index=11, number=11,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='BLOB_KEY', index=12, number=12,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TEXT', index=13, number=13,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='BLOB', index=14, number=14,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='SHORT_BLOB', index=15, number=15,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='USER', index=16, number=16,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='GEO_POINT', index=17, number=17,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='REFERENCE', index=18, number=18,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=836,
serialized_end=1105,
)
_sym_db.RegisterEnumDescriptor(_ENTITYSCHEMA_PRIMITIVETYPE)
_BACKUP = _descriptor.Descriptor(
name='Backup',
full_name='apphosting.ext.datastore_admin.Backup',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='backup_info', full_name='apphosting.ext.datastore_admin.Backup.backup_info', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='kind_info', full_name='apphosting.ext.datastore_admin.Backup.kind_info', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=80,
serialized_end=220,
)
_BACKUPINFO = _descriptor.Descriptor(
name='BackupInfo',
full_name='apphosting.ext.datastore_admin.BackupInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='backup_name', full_name='apphosting.ext.datastore_admin.BackupInfo.backup_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='start_timestamp', full_name='apphosting.ext.datastore_admin.BackupInfo.start_timestamp', index=1,
number=2, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='end_timestamp', full_name='apphosting.ext.datastore_admin.BackupInfo.end_timestamp', index=2,
number=3, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=222,
serialized_end=303,
)
_KINDBACKUPINFO = _descriptor.Descriptor(
name='KindBackupInfo',
full_name='apphosting.ext.datastore_admin.KindBackupInfo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='kind', full_name='apphosting.ext.datastore_admin.KindBackupInfo.kind', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='file', full_name='apphosting.ext.datastore_admin.KindBackupInfo.file', index=1,
number=2, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='entity_schema', full_name='apphosting.ext.datastore_admin.KindBackupInfo.entity_schema', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='is_partial', full_name='apphosting.ext.datastore_admin.KindBackupInfo.is_partial', index=3,
number=4, type=8, cpp_type=7, label=1,
has_default_value=True, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=306,
serialized_end=446,
)
_ENTITYSCHEMA_TYPE = _descriptor.Descriptor(
name='Type',
full_name='apphosting.ext.datastore_admin.EntitySchema.Type',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='is_list', full_name='apphosting.ext.datastore_admin.EntitySchema.Type.is_list', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='primitive_type', full_name='apphosting.ext.datastore_admin.EntitySchema.Type.primitive_type', index=1,
number=2, type=14, cpp_type=8, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='embedded_schema', full_name='apphosting.ext.datastore_admin.EntitySchema.Type.embedded_schema', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=547,
serialized_end=725,
)
_ENTITYSCHEMA_FIELD = _descriptor.Descriptor(
name='Field',
full_name='apphosting.ext.datastore_admin.EntitySchema.Field',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='name', full_name='apphosting.ext.datastore_admin.EntitySchema.Field.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='apphosting.ext.datastore_admin.EntitySchema.Field.type', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='field_name', full_name='apphosting.ext.datastore_admin.EntitySchema.Field.field_name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=727,
serialized_end=833,
)
_ENTITYSCHEMA = _descriptor.Descriptor(
name='EntitySchema',
full_name='apphosting.ext.datastore_admin.EntitySchema',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='kind', full_name='apphosting.ext.datastore_admin.EntitySchema.kind', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='field', full_name='apphosting.ext.datastore_admin.EntitySchema.field', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_ENTITYSCHEMA_TYPE, _ENTITYSCHEMA_FIELD, ],
enum_types=[
_ENTITYSCHEMA_PRIMITIVETYPE,
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=449,
serialized_end=1105,
)
_BACKUP.fields_by_name['backup_info'].message_type = _BACKUPINFO
_BACKUP.fields_by_name['kind_info'].message_type = _KINDBACKUPINFO
_KINDBACKUPINFO.fields_by_name['entity_schema'].message_type = _ENTITYSCHEMA
_ENTITYSCHEMA_TYPE.fields_by_name['primitive_type'].enum_type = _ENTITYSCHEMA_PRIMITIVETYPE
_ENTITYSCHEMA_TYPE.fields_by_name['embedded_schema'].message_type = _ENTITYSCHEMA
_ENTITYSCHEMA_TYPE.containing_type = _ENTITYSCHEMA
_ENTITYSCHEMA_FIELD.fields_by_name['type'].message_type = _ENTITYSCHEMA_TYPE
_ENTITYSCHEMA_FIELD.containing_type = _ENTITYSCHEMA
_ENTITYSCHEMA.fields_by_name['field'].message_type = _ENTITYSCHEMA_FIELD
_ENTITYSCHEMA_PRIMITIVETYPE.containing_type = _ENTITYSCHEMA
DESCRIPTOR.message_types_by_name['Backup'] = _BACKUP
DESCRIPTOR.message_types_by_name['BackupInfo'] = _BACKUPINFO
DESCRIPTOR.message_types_by_name['KindBackupInfo'] = _KINDBACKUPINFO
DESCRIPTOR.message_types_by_name['EntitySchema'] = _ENTITYSCHEMA
Backup = _reflection.GeneratedProtocolMessageType('Backup', (_message.Message,), dict(
DESCRIPTOR = _BACKUP,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
_sym_db.RegisterMessage(Backup)
BackupInfo = _reflection.GeneratedProtocolMessageType('BackupInfo', (_message.Message,), dict(
DESCRIPTOR = _BACKUPINFO,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
_sym_db.RegisterMessage(BackupInfo)
KindBackupInfo = _reflection.GeneratedProtocolMessageType('KindBackupInfo', (_message.Message,), dict(
DESCRIPTOR = _KINDBACKUPINFO,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
_sym_db.RegisterMessage(KindBackupInfo)
EntitySchema = _reflection.GeneratedProtocolMessageType('EntitySchema', (_message.Message,), dict(
Type = _reflection.GeneratedProtocolMessageType('Type', (_message.Message,), dict(
DESCRIPTOR = _ENTITYSCHEMA_TYPE,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
,
Field = _reflection.GeneratedProtocolMessageType('Field', (_message.Message,), dict(
DESCRIPTOR = _ENTITYSCHEMA_FIELD,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
,
DESCRIPTOR = _ENTITYSCHEMA,
__module__ = 'google.appengine.ext.datastore_admin.backup_pb2'
))
_sym_db.RegisterMessage(EntitySchema)
_sym_db.RegisterMessage(EntitySchema.Type)
_sym_db.RegisterMessage(EntitySchema.Field)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\020\002 \002(\002B\014BackupProtos'))
|
lgpl-3.0
|
hugovk/terroroftinytown
|
terroroftinytown/services/isgd.py
|
2
|
3885
|
# encoding=utf-8
from __future__ import unicode_literals
import re
import time
from terroroftinytown.client import errors
from terroroftinytown.client.errors import PleaseRetry
from terroroftinytown.services.base import BaseService
from terroroftinytown.services.rand import HashRandMixin
from terroroftinytown.services.status import URLStatus
from terroroftinytown.six.moves import html_parser
# __all__ = ['IsgdService']
class IsgdService(BaseService):
# NOTE: VgdService inherits from this class!
# unavailable status code: 200 410
# banned status code: 502
def __init__(self, *args, **kwargs):
BaseService.__init__(self, *args, **kwargs)
self._processing_phishing_page = False
def scrape_one(self, sequence_number):
self._processing_phishing_page = False
return BaseService.scrape_one(self, sequence_number)
def process_unavailable(self, response):
if not response.text:
return (URLStatus.unavailable, None, None)
# Catch both types encountered in the wild:
# <div id="main"><p>Rate limit exceeded - you must wait at least 1798 seconds before we'll service this request.</p></div>
# <div id="main"><p>Rate limit exceeded - please wait 1 minute before accessing more shortened URLs</p></div>
if '<div id="main"><p>Rate limit exceeded - ' in response.text:
raise PleaseRetry()
if "<div id=\"disabled\"><h2>Link Disabled</h2>" in response.text:
return self.parse_blocked(response)
if "<p>The full original link is shown below. <b>Click the link</b> if you'd like to proceed to the destination shown:" in response.text:
return self.parse_preview(response)
if '<title>Suspected phishing site | CloudFlare</title>' in response.text:
return self.process_phishing(response)
raise errors.UnexpectedNoResult("Could not find processing unavailable for %s" % self.current_shortcode)
def parse_blocked(self, response):
response.encoding = 'utf-8'
match = re.search("<p>For reference and to help those fighting spam the original destination of this URL is given below \(we strongly recommend you don't visit it since it may damage your PC\): -<br />(.*)</p><h2>is\.gd</h2><p>is\.gd is a free service used to shorten long URLs\.", response.text)
if not match:
raise errors.UnexpectedNoResult("Could not find target URL in 'Link Disabled' page")
url = match.group(1)
url = html_parser.HTMLParser().unescape(url)
if url == "":
return (URLStatus.unavailable, None, None)
return (URLStatus.ok, url, response.encoding)
def parse_preview(self, response):
response.encoding = 'utf-8'
match = re.search("<b>Click the link</b> if you'd like to proceed to the destination shown: -<br /><a href=\"(.*)\" class=\"biglink\">", response.text)
if not match:
raise errors.UnexpectedNoResult("Could not find target URL in 'Preview' page")
url = match.group(1)
return (URLStatus.ok, html_parser.HTMLParser().unescape(url), response.encoding)
def process_phishing(self, response):
if self._processing_phishing_page:
raise errors.UnexpectedNoResult("Alreadying processing phishing page for %s" % self.current_shortcode)
self._processing_phishing_page = True
time.sleep(1)
match = re.search(r'<input type="hidden" name="atok" value="([a-z0-9]+)">', response.text)
url = 'https://is.gd/cdn-cgi/phish-bypass?u=/{0}&atok={1}'.format(
self.current_shortcode, match.group(1))
response = self.fetch_url(url)
return self.process_response(response)
class Isgd6Service(HashRandMixin, IsgdService):
def get_shortcode_width(self):
return 6
|
mit
|
meierue/RNNLIB
|
utils/plot_errors.py
|
1
|
2250
|
#!/usr/bin/env python
from matplotlib.pyplot import *
import re
from optparse import OptionParser
usage = "usage: %prog log_file"
parser = OptionParser(usage)
parser.add_option("-v", "--verbose", dest="verbose", default=False, action="store_true", help="verbose plot (including error types with verboseChar)?")
parser.add_option("-c", "--verbosechar", dest="verboseChar", default="_", action="store", help="special character for verbose plots")
(options, args) = parser.parse_args()
errors = dict()
#print options
if len(args) != 1:
parser.error("incorrect number of arguments")
filename = args[0]
print "plotting errors from", filename
lines = file(filename, 'r').readlines()
errorType = ""
bestEpochs = dict()
for l in lines:
words = l.split()
if (l.find("epoch") >= 0 and l.find("took") >= 0):
epochNum = int(l.split()[1])
elif (l.find("train errors") >= 0):
errorType = "train"
elif (l.find("test errors") >= 0):
errorType = "test"
elif (l.find("validation errors") >= 0):
errorType = "validation"
elif (len(words) == 0 or l.find("best") >= 0):
errorType = ""
if l.find("best network") >= 0:
bestEpochs[l.split()[2]] = epochNum
elif l.find(".best_") >= 0:
bestEpochs['(' + l.split('.')[-2].split('_')[1] + ')'] = epochNum
elif len(words) == 2 and errorType <> "":
errWord = words[0]
if options.verbose or options.verboseChar not in errWord:
errVal = float(words[1].strip('%'))
if errWord not in errors:
errors[errWord] = dict()
if errorType in errors[words[0]]:
errors[errWord][errorType][0].append(epochNum)
errors[errWord][errorType][1].append(errVal)
else:
errors[errWord][errorType] = [[epochNum],[errVal]]
for err in errors.items():
figure()
title(filename + ' \n' + err[0])
for dataSet in err[1].items():
plot(dataSet[1][0], dataSet[1][1], linewidth=1.5, label=dataSet[0], marker='+')
axes = gca()
yRange = [axis()[2], axis()[3]]
if len(bestEpochs) > 0:
bone()
for best in bestEpochs.items():
if re.search("\(.*\)", best[0]):
lab = "best "+best[0]
else:
lab = "best network"
plot([best[1], best[1]], yRange, linestyle ='--', linewidth=1, label=lab)
legend()
legend(prop = matplotlib.font_manager.FontProperties(size = 'smaller'))
show()
|
gpl-3.0
|
imminfo/ymir
|
inference.py
|
1
|
1968
|
import os
import sys
from pyymir import *
DIRNAME = os.path.dirname(sys.argv[0])
DIRNAME = DIRNAME if DIRNAME else "./"
if __name__ == "__main__":
ap = default_ymir_ap()
ap.add_argument("-a", "--algorithm", help = "name of the algorithm for the statistical inference (default is 'em'). For a list of available algorithms with their parameters in this Ymir distribution run $python3 pyymir.py -a", default = "em", type = str)
ap.add_argument("-o", "--output", help = "path to the folder for output model folders (default is './ymir_models/')", type = str, default = "./ymir_models/")
ap.add_argument("-p", "--parameters", help = "statistical inference algorithm parameters in form '<param>=<value>,<param>=<value>'", default = "niter=10,memory-safe=0", type = str)
ap.add_argument("-w", "--workmode", help = "[NOT IMPLEMENTED YET] either build a vector of graphs once and recompute their parameters at each step ('-w time', faster execution time), or rebuild graphs at each step ('-w mem', slow execution time, but consumes almost no RAM)", default = "time", type = str)
ap = add_prealign(ap)
args = ap.parse_args()
files, input_check = parse_input(args)
model, model_check = parse_model(args)
converter, format_check = parse_format(args)
out_models, out_check = parse_output_models(files, args)
algo_params = dict(map(lambda x: x.split("="), args.parameters.split(",")))
print()
if model_check and input_check and format_check and out_check:
for i in range(len(files)):
print(i + 1, ":")
conv_file, convert_flag = convert(files[i], converter)
if convert_flag:
print()
os.system(" ".join([DIRNAME + "/build/scripts/Inference", conv_file, model, out_models[i], args.algorithm, "niter", algo_params["niter"], "memory-safe", algo_params["memory-safe"]]))
else:
print("Can't process further, too many errors for me! T_T")
|
apache-2.0
|
myles-archive/asgard-calendar
|
events/tests.py
|
2
|
1812
|
from django.test import Client
from django.core.urlresolvers import reverse
from events.models import Event
from django.test import TestCase
client = Client()
class EventsTestCase(TestCase):
fixtures = ['auth', 'events',]
def setUp(self):
self.event = Event.objects.get(pk=3)
def testEventsIndex(self):
response = client.get(reverse('events_index'))
self.assertEquals(response.status_code, 200)
def testEventDetailThoughModel(self):
response = client.get(self.event.get_absolute_url())
self.assertEquals(response.status_code, 200)
def testEventDetailThoughURL(self):
year = self.event.start_date.year
month = self.event.start_date.strftime('%b').lower()
day = self.event.start_date.day
slug = self.event.slug
response = client.get(reverse('events_event_detail', args=[year, month, day, slug,]))
self.assertEquals(response.status_code, 200)
def testEventYear(self):
year = self.event.start_date.year
response = client.get(reverse('events_year', args=[year,]))
self.assertEquals(response.status_code, 200)
def testEventMonth(self):
year = self.event.start_date.year
month = self.event.start_date.strftime('%b').lower()
response = client.get(reverse('events_month', args=[year, month,]))
self.assertEquals(response.status_code, 200)
def testEventDay(self):
year = self.event.start_date.year
month = self.event.start_date.strftime('%b').lower()
day = self.event.start_date.day
response = client.get(reverse('events_day', args=[year, month, day]))
self.assertEquals(response.status_code, 200)
def testEventsSitemap(self):
response = client.get(reverse('sitemap'))
self.assertEquals(response.status_code, 200)
def testEventsEventFeed(self):
response = client.get(reverse('events_feed'))
self.assertEquals(response.status_code, 200)
|
bsd-3-clause
|
nicholsn/ncanda-data-integration
|
scripts/reporting/xnat_extractor.py
|
2
|
12824
|
#!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
"""
NCANDA XNAT Extractor
Extract all experiment, scan, and reading data from NCANDA's XNAT server.
"""
__author__ = "Nolan Nichols <http://orcid.org/0000-0003-1099-3328>"
__modified__ = "2015-08-26"
import os
import glob
import json
import tempfile
import requests
import pandas as pd
from lxml import etree
# Verbose setting for cli
verbose = None
# Define global namespace for parsing XNAT XML files
ns = {'xnat': 'http://nrg.wustl.edu/xnat'}
# Define global format to be used in XNAT requests
return_format = '?format=csv'
def get_config(config_file):
"""
Get a json configuration in pyXNAT format
:param config_file: str
:return: dict
"""
path = os.path.abspath(config_file)
with open(path, 'rb') as fi:
config = json.load(fi)
config.update(api=config['server'] + '/data')
if verbose:
print("Getting configuration file: {0}".format(path))
return config
def get_collections(config):
"""
Get a dictionary of lambda functions that create collection URLs
:param config: dict
:return: dict
"""
server = config['api']
collections = dict(projects=lambda: server + '/projects',
subjects=lambda x: server + '/{0}/subjects'.format(x),
experiments=lambda: server + '/experiments')
if verbose:
print("Getting collections configuration...")
return collections
def get_entities(config):
"""
Get a dictionary of lambda functions that create entity URLs
:param config: dict
:return: dict
"""
server = config['api']
entities = dict(project=lambda x: server + '/projects/{0}'.format(x),
subject=lambda x: server + '/subjects/{0}'.format(x),
experiment=lambda x:
server + '/experiments/{0}'.format(x))
if verbose:
print("Getting entities configuration...")
return entities
def get_xnat_session(config):
"""
Get a requests.session instance from the config
:return: requests.session
"""
jsessionid = ''.join([config['api'], '/JSESSIONID'])
session = requests.session()
session.auth = (config['user'], config['password'])
session.get(jsessionid)
if verbose:
print("Getting an XNAT session using: {0}".format(jsessionid))
return session
def write_experiments(config, session):
"""
Write out a csv file representing all the experiments in the given XNAT
session.
:param config: dict
:param session: requests.session
:return: str
"""
experiments_filename = tempfile.mktemp()
collections = get_collections(config)
experiments = session.get(collections.get('experiments')() + return_format)
with open(experiments_filename, 'w') as fi:
fi.flush()
fi.write(experiments.text)
fi.close()
if verbose:
print("Writing list of experiment ids to temp: {0}".format(experiments_filename))
return experiments_filename
def extract_experiment_xml(config, session, experiment_dir, extract=None):
"""
Open an experiments csv file, then extract the XML representation,
and write it to disk.
:param config: dict
:param session: requests.session
:param experiment_dir: str
:param extract: int
:return: str
"""
entities = get_entities(config)
experiments_file = write_experiments(config, session)
# make sure the output directory exists and is empty
outdir = os.path.abspath(experiment_dir)
if not os.path.exists(outdir):
os.mkdir(outdir)
else:
[os.remove(f) for f in glob.glob(os.path.join(outdir, '*'))]
df_experiments = pd.read_csv(experiments_file)
if not extract:
if verbose:
print("Running XML extraction for all sessions: {0} Total".format(df_experiments.shape[0]))
extract = df_experiments.shape[0]
experiment_ids = df_experiments.ID[:extract]
experiment_files = list()
for idx, experiment_id in experiment_ids.iteritems():
experiment = session.get(entities.get('experiment')(experiment_id) + return_format)
experiment_file = os.path.join(outdir, '{0}.xml'.format(experiment_id))
experiment_files.append(experiment_file)
with open(experiment_file, 'w') as fi:
fi.flush()
fi.write(experiment.text)
fi.close()
if verbose:
num = idx + 1
print("Writing XML file {0} of {1} to: {2}".format(num, extract, experiment_file))
return experiment_files
def get_experiment_info(experiment_xml_file):
"""
Extract basic information from the experiment xml file and return a
dictionary
:param experiment_xml_file: str
:return: dict
"""
xml = etree.parse(experiment_xml_file)
root = xml.getroot()
site_experiment_id = root.attrib.get('label')
site_id = site_experiment_id[0:11]
site_experiment_date = site_experiment_id[12:20]
project = root.attrib.get('project')
experiment_id = root.attrib.get('ID')
try :
experiment_date = root.find('./xnat:date', namespaces=ns).text
subject_id = root.find('./xnat:subject_ID', namespaces=ns).text
result = dict(site_id=site_id,
subject_id=subject_id,
site_experiment_id=site_experiment_id,
site_experiment_date=site_experiment_date,
project=project,
experiment_id=experiment_id,
experiment_date=experiment_date)
if verbose:
print("Parsed experiment info for: {0}".format(result))
except :
print "ERROR: %s does not have xnat:date or xnat:subject_ID defined !" % (experiment_xml_file)
result = ""
return result
def get_experiments_dir_info(experiments_dir):
"""
Get a list of experiment dicts from all the experiment xml files in the
experiments directory
:param experiments_dir: str
:return: list
"""
results = list()
if os.path.exists(os.path.abspath(experiments_dir)):
glob_path = ''.join([os.path.abspath(experiments_dir), '/*'])
experiment_files = glob.glob(glob_path)
else:
experiment_files = list()
for path in experiment_files:
results.append(get_experiment_info(path))
return results
def get_scans_info(experiment_xml_file):
"""
Get a dict of dicts for each scan from an XNAT experiment XML document
:param experiment_xml_file: lxml.etree.Element
:return: list
"""
xml = etree.parse(experiment_xml_file)
root = xml.getroot()
experiment_id = root.attrib.get('ID')
result = list()
scans = root.findall('./xnat:scans/xnat:scan', namespaces=ns)
for scan in scans:
values = dict()
scan_id = scan.attrib.get('ID')
scan_type = scan.attrib.get('type')
# handle null finds
values.update(quality=scan.find('./xnat:quality', namespaces=ns))
values.update(series_description=scan.find(
'./xnat:series_description', namespaces=ns))
values.update(coil=scan.find('./xnat:coil', namespaces=ns))
values.update(field_strength=scan.find('./xnat:fieldStrength',
namespaces=ns))
values.update(scan_note=scan.find('./xnat:note', namespaces=ns))
for k, v in values.iteritems():
try:
values[k] = v.text
except AttributeError, e:
values[k] = None
if verbose:
print(e, "for attribute {0} in scan {1} of experiment {2}".format(k, scan_id, experiment_id))
scan_dict = dict(experiment_id=experiment_id,
scan_id=scan_id,
scan_type=scan_type,
quality=values.get('quality'),
scan_note=values.get('scan_note'),
series_description=values.get('series_description'),
coil=values.get('coil'),
field_strength=values.get('field_strength'))
result.append(scan_dict)
return result
def get_reading_info(experiment_xml_file):
"""
Get a dict of dicts for each reading from an XNAT experiment XML document
These are the visit specific information, e.g. DateToDVD, Subject ID , session notes, ....
(no individual scan info)
:param experiment_xml_file: lxml.etree.Element
:return: list
"""
xml = etree.parse(experiment_xml_file)
root = xml.getroot()
experiment_id = root.attrib.get('ID')
try:
note = root.find('./xnat:note', namespaces=ns).text
except AttributeError:
note = None
pass
result = dict(experiment_id=experiment_id,
note=note,
datetodvd=None,
findings=None,
findingsdate=None,
excludefromanalysis=None,
physioproblemoverride=None,
dtimismatchoverride=None,
phantommissingoverride=None)
values = dict()
fields = root.findall('./xnat:fields/xnat:field', namespaces=ns)
for field in fields:
name = field.attrib.get('name')
value = root.xpath('.//xnat:field[@name="{0}"]/text()'.format(name),
namespaces=ns)
# handle null finds
values[name] = value
for k, v in values.iteritems():
try:
values[k] = v[1]
except IndexError:
values[k] = None
result.update(values)
return result
def get_experiments_dir_reading_info(experiments_dir):
"""
Get a list of reading dicts from all the experiment xml files in the
experiments directory
:param experiments_dir: str
:return: list
"""
results = list()
if os.path.exists(os.path.abspath(experiments_dir)):
glob_path = ''.join([os.path.abspath(experiments_dir), '/*'])
experiment_files = glob.glob(glob_path)
else:
experiment_files = list()
for path in experiment_files:
results.append(get_reading_info(path))
return results
def get_experiments_dir_scan_info(experiments_dir):
"""
Get a list of scan dicts from all the experiment xml files in the
experiments directory
:param experiments_dir: str
:return: list
"""
results = list()
if os.path.exists(os.path.abspath(experiments_dir)):
glob_path = ''.join([os.path.abspath(experiments_dir), '/*'])
experiment_files = glob.glob(glob_path)
else:
experiment_files = list()
for path in experiment_files:
results.append(get_scans_info(path))
return results
def get_scans_by_type(scans, scan_type):
"""
Get scans based on their type
:param scans: dict
:param scan_type: str
:return:
"""
result = list()
for scan in scans:
if scan['scan_type'] == scan_type:
result.append(scan)
return result
def scans_to_dataframe(scans):
"""
Convert scan dict to a pandas.DataFrame
:param scans: dict
:return: pandas.DataFrame
"""
flat = [item for sublist in scans for item in sublist]
return pd.DataFrame(flat)
def experiments_to_dataframe(experiments):
"""
Convert a list of experiment dicts to a pandas.DataFrame
:param experiments: dict
:return: pandas.DataFrame
"""
return pd.DataFrame(experiments)
def reading_to_dataframe(reading):
"""
Convert a list of reading dicts to a pandas.DataFrame
:param reading: dict
:return: pandas.DataFrame
"""
return pd.DataFrame(reading)
def merge_experiments_scans_reading(experiments, scans, reading):
"""
Merge an experiments dataframe with a scan dataframe
:param experiments: dict
:param scans: dict
:return: pandas.DataFrame
"""
experiments_df = experiments_to_dataframe(experiments)
scans_df = scans_to_dataframe(scans)
reading_df = reading_to_dataframe(reading)
exp_scan = pd.merge(experiments_df, scans_df, how='inner')
merged = pd.merge(exp_scan, reading_df, how='inner')
# reindex using multi-index of subject, experiment, scan
result = merged.to_records(index=False)
idx = pd.MultiIndex.from_arrays([merged.subject_id.values,
merged.experiment_id.values,
merged.scan_id.values],
names=['subject_id',
'experiment_id',
'scan_id'])
return pd.DataFrame(result, index=idx)
|
bsd-3-clause
|
mbauskar/Das_Erpnext
|
erpnext/setup/doctype/backup_manager/backup_manager.py
|
23
|
3457
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.utils import get_site_path
from frappe.utils.data import convert_utc_to_user_timezone
import os
import datetime
import frappe
from frappe.model.document import Document
class BackupManager(Document):
def onload(self):
self.set_onload("files", get_files())
def get_files():
def get_time(path):
dt = os.path.getmtime(path)
return convert_utc_to_user_timezone(datetime.datetime.utcfromtimestamp(dt)).strftime('%Y-%m-%d %H:%M')
def get_size(path):
size = os.path.getsize(path)
if size > 1048576:
return "{0:.1f}M".format(float(size) / 1048576)
else:
return "{0:.1f}K".format(float(size) / 1024)
path = get_site_path('private', 'backups')
files = [x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]
files = [('/backups/' + _file,
get_time(os.path.join(path, _file)),
get_size(os.path.join(path, _file))) for _file in files]
return files
def take_backups_daily():
take_backups_if("Daily")
def take_backups_weekly():
take_backups_if("Weekly")
def take_backups_if(freq):
if frappe.db.get_value("Backup Manager", None, "send_backups_to_dropbox"):
if frappe.db.get_value("Backup Manager", None, "upload_backups_to_dropbox")==freq:
take_backups_dropbox()
# if frappe.db.get_value("Backup Manager", None, "upload_backups_to_gdrive")==freq:
# take_backups_gdrive()
@frappe.whitelist()
def take_backups_dropbox():
did_not_upload, error_log = [], []
try:
from erpnext.setup.doctype.backup_manager.backup_dropbox import backup_to_dropbox
did_not_upload, error_log = backup_to_dropbox()
if did_not_upload: raise Exception
send_email(True, "Dropbox")
except Exception:
file_and_error = [" - ".join(f) for f in zip(did_not_upload, error_log)]
error_message = ("\n".join(file_and_error) + "\n" + frappe.get_traceback())
frappe.errprint(error_message)
send_email(False, "Dropbox", error_message)
#backup to gdrive
@frappe.whitelist()
def take_backups_gdrive():
did_not_upload, error_log = [], []
try:
from erpnext.setup.doctype.backup_manager.backup_googledrive import backup_to_gdrive
did_not_upload, error_log = backup_to_gdrive()
if did_not_upload: raise Exception
send_email(True, "Google Drive")
except Exception:
file_and_error = [" - ".join(f) for f in zip(did_not_upload, error_log)]
error_message = ("\n".join(file_and_error) + "\n" + frappe.get_traceback())
frappe.errprint(error_message)
send_email(False, "Google Drive", error_message)
def send_email(success, service_name, error_status=None):
if success:
subject = "Backup Upload Successful"
message ="""<h3>Backup Uploaded Successfully</h3><p>Hi there, this is just to inform you
that your backup was successfully uploaded to your %s account. So relax!</p>
""" % service_name
else:
subject = "[Warning] Backup Upload Failed"
message ="""<h3>Backup Upload Failed</h3><p>Oops, your automated backup to %s
failed.</p>
<p>Error message: %s</p>
<p>Please contact your system manager for more information.</p>
""" % (service_name, error_status)
if not frappe.db:
frappe.connect()
recipients = frappe.db.get_value("Backup Manager", None, "send_notifications_to").split(",")
frappe.sendmail(recipients=recipients, subject=subject, message=message)
|
agpl-3.0
|
pombredanne/ctypesgen
|
test/testsuite.py
|
12
|
9617
|
#!/usr/bin/env python
# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
"""Simple test suite using unittest.
By clach04 (Chris Clark).
Calling:
python test/testsuite.py
or
cd test
./testsuite.py
Could use any unitest compatible test runner (nose, etc.)
Aims to test for regressions. Where possible use stdlib to
avoid the need to compile C code.
Known to run clean with:
* 32bit Linux (python 2.5.2, 2.6)
* 32bit Windows XP (python 2.4, 2.5, 2.6.1)
"""
import sys
import os
import ctypes
import math
import unittest
import logging
test_directory = os.path.abspath(os.path.dirname(__file__))
sys.path.append(test_directory)
sys.path.append(os.path.join(test_directory, '..'))
import ctypesgentest # TODO consider moving test() from ctypesgentest into this module
class StdlibTest(unittest.TestCase):
def setUp(self):
"""NOTE this is called once for each test* method
(it is not called once per class).
FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
"""
header_str = '#include <stdlib.h>\n'
if sys.platform == "win32":
# pick something from %windir%\system32\msvc*dll that include stdlib
libraries = ["msvcrt.dll"]
libraries = ["msvcrt"]
elif sys.platform.startswith("linux"):
libraries = ["libc.so.6"]
else:
libraries = ["libc"]
self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)
def tearDown(self):
del self.module
ctypesgentest.cleanup()
def test_getenv_returns_string(self):
"""Issue 8 - Regression for crash with 64 bit and bad strings on 32 bit.
See http://code.google.com/p/ctypesgen/issues/detail?id=8
Test that we get a valid (non-NULL, non-empty) string back
"""
module = self.module
if sys.platform == "win32":
# Check a variable that is already set
env_var_name = 'USERNAME' # this is always set (as is windir, ProgramFiles, USERPROFILE, etc.)
expect_result = os.environ[env_var_name]
self.assert_(expect_result, 'this should not be None or empty')
# reason for using an existing OS variable is that unless the
# MSVCRT dll imported is the exact same one that Python was
# built with you can't share structures, see
# http://msdn.microsoft.com/en-us/library/ms235460.aspx
# "Potential Errors Passing CRT Objects Across DLL Boundaries"
else:
env_var_name = 'HELLO'
os.environ[env_var_name] = 'WORLD' # This doesn't work under win32
expect_result = 'WORLD'
result = module.getenv(env_var_name)
self.failUnlessEqual(expect_result, result)
def test_getenv_returns_null(self):
"""Related to issue 8. Test getenv of unset variable.
"""
module = self.module
env_var_name = 'NOT SET'
expect_result = None
try:
# ensure variable is not set, ignoring not set errors
del os.environ[env_var_name]
except KeyError:
pass
result = module.getenv(env_var_name)
self.failUnlessEqual(expect_result, result)
class StdBoolTest(unittest.TestCase):
"Test correct parsing and generation of bool type"
def setUp(self):
"""NOTE this is called once for each test* method
(it is not called once per class).
FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
"""
header_str = '''
#include <stdbool.h>
struct foo
{
bool is_bar;
int a;
};
'''
self.module, _ = ctypesgentest.test(header_str)#, all_headers=True)
def tearDown(self):
del self.module
ctypesgentest.cleanup()
def test_stdbool_type(self):
"""Test is bool is correctly parsed"""
module = self.module
struct_foo = module.struct_foo
self.failUnlessEqual(struct_foo._fields_, [("is_bar", ctypes.c_bool), ("a", ctypes.c_int)])
class SimpleMacrosTest(unittest.TestCase):
"""Based on simple_macros.py
"""
def setUp(self):
"""NOTE this is called once for each test* method
(it is not called once per class).
FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
"""
header_str = '''
#define A 1
#define B(x,y) x+y
#define C(a,b,c) a?b:c
#define funny(x) "funny" #x
#define multipler_macro(x,y) x*y
#define minus_macro(x,y) x-y
#define divide_macro(x,y) x/y
#define mod_macro(x,y) x%y
'''
libraries = None
self.module, output = ctypesgentest.test(header_str)
def tearDown(self):
del self.module
ctypesgentest.cleanup()
def test_macro_constant_int(self):
"""Tests from simple_macros.py
"""
module = self.module
self.failUnlessEqual(module.A, 1)
def test_macro_addition(self):
"""Tests from simple_macros.py
"""
module = self.module
self.failUnlessEqual(module.B(2, 2), 4)
def test_macro_ternary_true(self):
"""Tests from simple_macros.py
"""
module = self.module
self.failUnlessEqual(module.C(True, 1, 2), 1)
def test_macro_ternary_false(self):
"""Tests from simple_macros.py
"""
module = self.module
self.failUnlessEqual(module.C(False, 1, 2), 2)
def test_macro_ternary_true_complex(self):
"""Test ?: with true, using values that can not be confused between True and 1
"""
module = self.module
self.failUnlessEqual(module.C(True, 99, 100), 99)
def test_macro_ternary_false_complex(self):
"""Test ?: with false, using values that can not be confused between True and 1
"""
module = self.module
self.failUnlessEqual(module.C(False, 99, 100), 100)
def test_macro_string_compose(self):
"""Tests from simple_macros.py
"""
module = self.module
self.failUnlessEqual(module.funny("bunny"), "funnybunny")
def test_macro_math_multipler(self):
module = self.module
x, y = 2, 5
self.failUnlessEqual(module.multipler_macro(x, y), x * y)
def test_macro_math_minus(self):
module = self.module
x, y = 2, 5
self.failUnlessEqual(module.minus_macro(x, y), x - y)
def test_macro_math_divide(self):
module = self.module
x, y = 2, 5
self.failUnlessEqual(module.divide_macro(x, y), x / y)
def test_macro_math_mod(self):
module = self.module
x, y = 2, 5
self.failUnlessEqual(module.mod_macro(x, y), x % y)
class StructuresTest(unittest.TestCase):
"""Based on structures.py
"""
def setUp(self):
"""NOTE this is called once for each test* method
(it is not called once per class).
FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
"""
header_str = '''
struct foo
{
int a;
int b;
int c;
};
'''
libraries = None
self.module, output = ctypesgentest.test(header_str)
def tearDown(self):
del self.module
ctypesgentest.cleanup()
def test_structures(self):
"""Tests from structures.py
"""
module = self.module
struct_foo = module.struct_foo
self.failUnlessEqual(struct_foo._fields_, [("a", ctypes.c_int), ("b", ctypes.c_int), ("c", ctypes.c_int)])
class MathTest(unittest.TestCase):
"""Based on math_functions.py"""
def setUp(self):
"""NOTE this is called once for each test* method
(it is not called once per class).
FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
"""
header_str = '#include <math.h>\n'
if sys.platform == "win32":
# pick something from %windir%\system32\msvc*dll that include stdlib
libraries = ["msvcrt.dll"]
libraries = ["msvcrt"]
elif sys.platform.startswith("linux"):
libraries = ["libm.so.6"]
else:
libraries = ["libc"]
self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True)
def tearDown(self):
del self.module
ctypesgentest.cleanup()
def test_sin(self):
"""Based on math_functions.py"""
module = self.module
self.failUnlessEqual(module.sin(2), math.sin(2))
def test_sqrt(self):
"""Based on math_functions.py"""
module = self.module
self.failUnlessEqual(module.sqrt(4), 2)
def local_test():
module.sin("foobar")
self.failUnlessRaises(ctypes.ArgumentError, local_test)
def test_bad_args_string_not_number(self):
"""Based on math_functions.py"""
module = self.module
def local_test():
module.sin("foobar")
self.failUnlessRaises(ctypes.ArgumentError, local_test)
def main(argv=None):
if argv is None:
argv = sys.argv
ctypesgentest.ctypesgencore.messages.log.setLevel(logging.CRITICAL) # do not log anything
unittest.main()
return 0
if __name__ == "__main__":
sys.exit(main())
|
bsd-3-clause
|
keptenkurk/mxpgm
|
mxrestore.py
|
2
|
10303
|
# ****************************************************************************
# * mxrestore.py
# * Mobotix camera config restore utility
#
# This script restores configfiles to (multiple) mobotix camera's
# through Mobotix API
# See http://developer.mobotix.com/paks/help_cgi-remoteconfig.html for details
# usage:
# python mxrstore.py [options]
# use option -h or --help for instructions
# See https://github.com/keptenkurk/mxpgm/blob/master/README.md for
# instructions
#
# release info
# 1.0 first release 29/8/17 Paul Merkx
# 1.1 added -s (SSL) option and -v (verbose) option, removed bar and moved
# to Python3
# 1.2 skipped version
# 1.3 Changed PyCurl to requests
# ****************************************************************************
import os
import sys
import argparse
import csv
import datetime
import time
import glob
import math
import io
import requests
from http import HTTPStatus
RELEASE = '1.3 - 1-6-2020'
TMPCONFIG = 'config.tmp'
TMPCONFIG2 = 'config2.tmp'
TIMEOUT = 120 # Timeout can be overwritten with -t parameter
# Ignore the warning that SSL CA will not be checked
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.
exceptions.InsecureRequestWarning)
def filewritable(filename):
try:
f = open(filename, 'w')
f.close()
except IOError:
print('Unable to write to ' + filename + '. It might be open ' \
'in another application.')
return False
os.remove(filename)
return True
def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
def transfer(ipaddr, username, password, commandfile):
# transfers commandfile to camera
if use_ssl:
url = 'https://' + ipaddr + '/admin/remoteconfig'
else:
url = 'http://' + ipaddr + '/admin/remoteconfig'
try:
with open(commandfile, 'rb') as payload:
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(url, auth=(username, password),
data=payload, verify=False,
headers=headers, timeout=TIMEOUT)
except requests.ConnectionError:
print('Unable to connect. ', end='')
return False, ''
except requests.Timeout:
print('Timeout. ', end='')
return False, ''
except requests.exceptions.RequestException as e:
print('Uncaught error:', str(e), end='')
return False, ''
else:
content = response.text
if response:
if (content.find('#read::') != 0):
print('Are you sure this is Mobotix? ', end='')
return False, ''
else:
return True, content
else:
print('HTTP response code: ',
HTTPStatus(response.status_code).phrase)
return False, ''
def verify_version(cfgfileversion, deviceIP, username, password):
# check if cfg to be restored has same SW version as device
versionok = False
result = False
if filewritable(TMPCONFIG2):
outfile = open(TMPCONFIG2, 'w')
outfile.write('\n')
outfile.write('helo\n')
outfile.write('view section timestamp\n')
outfile.write('quit\n')
outfile.write('\n')
outfile.close()
(result, received) = transfer(ipaddr, username, password, TMPCONFIG2)
if result:
versionpos = received.find('VERSION=')
datepos = received.find('DATE=')
deviceversion = received[versionpos+8:datepos-1]
# print('[' + deviceversion + '] - [' + cfgfileversion + ']')
if deviceversion == cfgfileversion:
versionok = True
else:
versionok = False
os.remove(TMPCONFIG2)
else:
print('ERROR: Unable to write temporary file')
sys.exit()
return result, versionok
# ***************************************************************
# *** Main program ***
# ***************************************************************
print('MxRestore ' + RELEASE + ' by (c) Simac Healthcare.')
print('Restores entire configuration of multiple ' \
'Mobotix camera\'s from disk.')
print('Disclaimer: ')
print('USE THIS SOFTWARE AT YOUR OWN RISK')
print(' ')
# *** Read arguments passed on commandline
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--deviceIP", nargs=1,
help="specify target device IP when \
programming a single camera")
parser.add_argument("-l", "--devicelist", nargs=1,
help="specify target device list in CSV when \
programming multiple camera's")
parser.add_argument("-u", "--username", nargs=1,
help="specify target device admin username")
parser.add_argument("-p", "--password", nargs=1,
help="specify target device admin password")
parser.add_argument("-o", "--override",
help="write config even if SW versions are unequal",
action="store_true")
parser.add_argument("-r", "--reboot",
help="reboots camera after restoring",
action="store_true")
parser.add_argument("-s", "--ssl",
help="use SSL to communicate (HTTPS)",
action="store_true")
args = parser.parse_args()
# *** Check validity of the arguments
if (args.deviceIP is None and args.devicelist is None) or \
(args.deviceIP and args.devicelist):
print("Either deviceIP or devicelist is required")
sys.exit()
if args.username is None:
print("Default Admin account assumed")
username = 'admin'
else:
username = args.username[0]
if args.password is None:
print("Default Admin password assumed")
password = 'meinsm'
else:
password = args.password[0]
if not args.deviceIP and not args.devicelist:
print('No devices specified. Either specify a device (-d)' \
'or devicelist (-l)')
sys.exit()
if args.deviceIP:
if not validate_ip(args.deviceIP[0]):
print("Warning: The device %s is not a valid IPv4 address!"
% (args.deviceIP[0]))
print("Continuing using %s as devicename."
% (args.deviceIP[0]))
if args.devicelist:
if not os.path.exists(args.devicelist[0]):
print("The devicelist '%s' does not exist in the current directory!"
% (args.devicelist[0]))
sys.exit()
if args.ssl:
use_ssl = True
else:
use_ssl = False
print('Starting')
# Build devicelist from devicelist file or from single parameter
# devicelist is a list of lists
devicelist = []
if args.devicelist:
print('Build devicelist...')
csv.register_dialect('semicolons', delimiter=';')
with open(args.devicelist[0], 'r') as f:
reader = csv.reader(f, dialect='semicolons')
for row in reader:
devicelist.append(row)
else:
print('Found device ' + args.deviceIP[0])
devicelist.append(['IP'])
devicelist.append([args.deviceIP[0]])
for devicenr in range(1, len(devicelist)):
# skip device if starts with comment
if devicelist[devicenr][0][0] != '#':
result = False
ipaddr = devicelist[devicenr][0]
cfgfilenamepattern = ipaddr.replace(".", "-") + "_*.cfg"
list_of_files = glob.glob(cfgfilenamepattern)
if len(list_of_files) > 0:
latest_file = max(list_of_files, key=os.path.getctime)
cfgfile = open(latest_file, 'r')
cfgfileversion = ''
for line in cfgfile.readlines():
if line.find('#:MX-') == 0:
cfgfileversion = line[2:-1]
break
(result, versionok) = verify_version(cfgfileversion, ipaddr,
username, password)
if result:
if versionok:
print('SW version matches configfile version ' \
'for device ' + ipaddr)
else:
if args.override:
print('Non matching SW versions overridden by ' \
'--override flag for device ' + ipaddr)
if versionok or args.override:
# build API commandfile to read the config
if filewritable(TMPCONFIG):
outfile = open(TMPCONFIG, 'w')
outfile.write('\n')
outfile.write('helo\n')
outfile.write('write\n')
cfgfile = open(latest_file, 'r')
for line in cfgfile:
outfile.write(line)
outfile.write('store\n')
outfile.write('update\n')
if args.reboot:
outfile.write('reboot\n')
outfile.write('quit\n')
outfile.write('\n')
outfile.close()
print('Restoring ' + ipaddr + '...(takes abt 90sec)..')
(result, received) = transfer(ipaddr, username,
password, TMPCONFIG)
if result:
print('Restoring of ' + latest_file + ' to ' +
ipaddr + ' succeeded.')
else:
print('ERROR: Restoring of ' + ipaddr + ' failed.')
os.remove(TMPCONFIG)
else:
print('SW version does not match configfile version ' \
'for device ' + ipaddr)
print('Use -o or --override flag to ignore difference ' \
'(but be aware of unexpected camera behaviour)')
else:
print('Unable to verify device SW version')
else:
print('No configfile found for device ' + ipaddr)
print('')
print("Done.")
|
mit
|
SimpleAOSP-Kernel/kernel_shamu
|
tools/perf/scripts/python/failed-syscalls-by-pid.py
|
11180
|
2058
|
# failed system call counts, by pid
# (c) 2010, Tom Zanussi <[email protected]>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide failed system call totals, broken down by pid.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_error_totals()
def raw_syscalls__sys_exit(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, ret):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
if ret < 0:
try:
syscalls[common_comm][common_pid][id][ret] += 1
except TypeError:
syscalls[common_comm][common_pid][id][ret] = 1
def print_error_totals():
if for_comm is not None:
print "\nsyscall errors for %s:\n\n" % (for_comm),
else:
print "\nsyscall errors:\n\n",
print "%-30s %10s\n" % ("comm [pid]", "count"),
print "%-30s %10s\n" % ("------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id in id_keys:
print " syscall: %-16s\n" % syscall_name(id),
ret_keys = syscalls[comm][pid][id].keys()
for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True):
print " err = %-20s %10d\n" % (strerror(ret), val),
|
gpl-2.0
|
jcbagneris/fms
|
fms/contrib/coleman/checksuccess.py
|
2
|
7398
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Checks the Success of Agent Behaviors
"""
__author__ = "Sami Nazif / Patrick Coleman"
__license__ = "BSD"
import sys
import dumbstartfms
def main():
"""
Runs a head to head competition of agent behavior types.
"""
expnum = 0
agents = []
overall = dict()
# agents = ['AvgBuySellTrader','AvgBuySellTraderD','DefectorTrader',
# 'DeflationaryTrader', 'InflationaryTrader','Mem1Trader',
# 'Mem3Trader','Mem5Trader', 'Mem5TraderD',
# 'Mem10Trader',
# 'ProbeAdjustBSTrader','ProbeAdjustTrader', 'ProbeSameTrader',
# 'RandomFixedTrader', 'RandomFixedTraderHalves','SmartMem3Trader',
# 'SmartMem5Trader', 'SmartMem5TraderD', 'SmartMem10Trader',
# 'ZeroIntelligenceBoundedTrader', 'ZeroIntelligenceTrader',
# 'ZeroIntelligenceTraderNL', 'ZigFastTrader','ZigTrader']
# overall = {'AvgBuySellTrader':0,'AvgBuySellTraderD':0,'DefectorTrader':0,
# 'DeflationaryTrader':0, 'InflationaryTrader':0,'Mem1Trader':0,
# 'Mem3Trader':0,'Mem5Trader':0, 'Mem5TraderD':0,
# 'Mem10Trader':0,
# 'ProbeAdjustBSTrader':0,'ProbeAdjustTrader':0, 'ProbeSameTrader':0,
# 'RandomFixedTrader':0, 'RandomFixedTraderHalves':0,'SmartMem3Trader':0,
# 'SmartMem5Trader':0, 'SmartMem5TraderD':0, 'SmartMem10Trader':0,
# 'ZeroIntelligenceBoundedTrader':0, 'ZeroIntelligenceTrader':0,
# 'ZeroIntelligenceTraderNL':0, 'ZigFastTrader':0,'ZigTrader':0}
#overall = {'AvgBuySellTrader':0,'DefectorTrader':0,'Mem1Trader':0,
# 'Mem3Trader':0,'Mem5Trader':0, 'Mem10Trader':0,
# 'ProbeAdjustBSTrader':0, 'ProbeSameTrader':0,
# 'RandomFixedTrader':0, 'RandomFixedTraderHalves':0,
# 'ZeroIntelligenceBoundedTrader':0,'ZeroIntelligenceTrader':0}
#agents = ['AvgBuySellTrader','Mem5Trader', 'Mem10Trader',
# 'RandomFixedTraderHalves',]
agentfile = open('agentfile.txt','r')
#This looks through the config file to pull out the agents that
#will participate in the head to head
for line in agentfile:
if line.startswith('#'):
continue
else:
agents.append(line.rstrip())
overall[line.rstrip()] = 0
#Loops through the agents, running them against each other, excluding
#identical types. The script generates experiment YAML files which are
#then run using a specific version of startfms.py (dumbstart),
#the original fms runtime.
for agenti in agents:
for agentj in agents:
if agenti == agentj:
continue
currentagent = agenti
nextagent = agentj
#print agenti
#print agentj
expname = 'exp' + str(expnum)
args = ['run', expname + '.yml']
yamltowrite = open(expname + '.yml', 'w')
linestowrite = []
linestowrite.append('--- # Experiment ' + str(expnum))
linestowrite.append('outputfilename: ' + expname + '.csv')
linestowrite.append('orderslogfilename: ' + expname + '.log')
yamltoread = open('template.yml', 'r')
for line in yamltoread:
linestowrite.append(line)
yamltoread.close()
#This is the important agent specification part
linestowrite.append('agents:')
linestowrite.append(' - classname: ' + currentagent)
linestowrite.append(' number: 100')
linestowrite.append(' money: 100000')
linestowrite.append(' stocks: 1000')
linestowrite.append(' args: [1000, 1000]')
linestowrite.append(' - classname: ' + nextagent)
linestowrite.append(' number: 100')
linestowrite.append(' money: 100000')
linestowrite.append(' stocks: 1000')
linestowrite.append(' args: [1000, 1000]')
for line in linestowrite:
yamltowrite.write(line.rstrip() + '\n')
yamltowrite.close()
dumbstartfms.main(args)
wealthresult = wealth_tester(expname)
for guy in wealthresult.keys():
overall[guy] += wealthresult[guy]
expnum += 1 #increment the exp number counter
fultimateout = open('ultimateoutput.txt', 'a')
dudes = [key for key, dummy in sorted(overall.items(), key = lambda arg: arg[1], reverse = True)]
fultimateout.write('==========================================================================' + '\n')
for dude in dudes:
fultimateout.write('Agent ' + dude + ' scored ' + str(overall[dude]) + ' overall.' + '\n')
return 0
def wealth_tester(expname):
'''
Checks the TotalWealth of each Behavior Type in the wealth file.
'''
try:
wealthfile = open(expname + 'wealth.csv', 'r')
except IOError:
print "Check the wealth file."
try:
transactionfile = open(expname + '.csv')
except IOError:
print "Error in passing the csv file"
fout = open('ultimateoutput.txt', 'a')
#find the average stockprice
#indices for readability
#time = 0
#transactionnum = 1
#price = 2
#volume = 3
#totalprice = 0
#numtrans = 0
#skipfirstlines = 0
#for line in transactionfile:
# if skipfirstlines == 0 or skipfirstlines == 1:
# skipfirstlines += 1
# continue
# splitline = line.split(';')
# totalprice = totalprice + (int(float(splitline[price])) * int(splitline[volume]))
# numtrans = numtrans + int(splitline[volume])
# avgtrans = totalprice / numtrans
avgtrans = 500 #This replaces the actual average finder
totalwealth = dict()
#indices for readability
time = 0
id = 1
behavior = 2
wealth = 3
stock = 4
for line in wealthfile:
splitline = line.split(';')
agent = splitline[behavior]
#print agent
if agent in totalwealth.keys():
#add wealth
totalwealth[agent] = totalwealth[agent] + int(splitline[wealth])
#add stock x avg transaction price
totalwealth[agent] = totalwealth[agent] + (int(splitline[stock]) * avgtrans)
else:
totalwealth[agent] = 0
#add wealth
totalwealth[agent] = totalwealth[agent] + int(splitline[wealth])
#add stock x avg transaction price
totalwealth[agent] = totalwealth[agent] + (int(splitline[stock]) * avgtrans)
#Order them top to bottom
agents = [key for key, dummy in sorted(totalwealth.items(), key = lambda arg: arg[1], reverse = True)]
#print agents
#for agent in agents:
# print totalwealth[agent]
#print totalwealth
#print type(totalwealth.keys())
print totalwealth
fout.write(expname + '\n')
fout.write('Agent1: ' + agents[0] + " has a total wealth of " + str(totalwealth[agents[0]]) + '\n')
fout.write('Agent2: ' + agents[1] + " has a total wealth of " + str(totalwealth[agents[1]]) + '\n')
wealthfile.close()
fout.close()
return totalwealth
if __name__ == "__main__":
sys.exit(main())
|
bsd-3-clause
|
turbokongen/home-assistant
|
tests/components/template/test_switch.py
|
14
|
23138
|
"""The tests for the Template switch platform."""
import pytest
from homeassistant import setup
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from homeassistant.core import CoreState, State
from homeassistant.setup import async_setup_component
from tests.common import (
assert_setup_component,
async_mock_service,
mock_component,
mock_restore_cache,
)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
async def test_template_state_text(hass):
"""Test the state text of a template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
async def test_template_state_boolean_on(hass):
"""Test the setting of the state with boolean on."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ 1 == 1 }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
async def test_template_state_boolean_off(hass):
"""Test the setting of the state with off."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ 1 == 2 }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
async def test_icon_template(hass):
"""Test icon template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
"icon_template": "{% if states.switch.test_state.state %}"
"mdi:check"
"{% endif %}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes.get("icon") == ""
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes["icon"] == "mdi:check"
async def test_entity_picture_template(hass):
"""Test entity_picture template."""
with assert_setup_component(1, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
"entity_picture_template": "{% if states.switch.test_state.state %}"
"/local/switch.png"
"{% endif %}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes.get("entity_picture") == ""
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.attributes["entity_picture"] == "/local/switch.png"
async def test_template_syntax_error(hass):
"""Test templating syntax error."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{% if rubbish %}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_invalid_name_does_not_create(hass):
"""Test invalid name."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test INVALID switch": {
"value_template": "{{ rubbish }",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_invalid_switch_does_not_create(hass):
"""Test invalid switch."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {"test_template_switch": "Invalid"},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_no_switches_does_not_create(hass):
"""Test if there are no switches no creation."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass, "switch", {"switch": {"platform": "template"}}
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_missing_on_does_not_create(hass):
"""Test missing on."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"not_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_missing_off_does_not_create(hass):
"""Test missing off."""
with assert_setup_component(0, "switch"):
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"not_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.async_all() == []
async def test_on_action(hass, calls):
"""Test on action."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {"service": "test.automation"},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
assert len(calls) == 1
async def test_on_action_optimistic(hass, calls):
"""Test on action in optimistic mode."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"turn_on": {"service": "test.automation"},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_template_switch", STATE_OFF)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
state = hass.states.get("switch.test_template_switch")
assert len(calls) == 1
assert state.state == STATE_ON
async def test_off_action(hass, calls):
"""Test off action."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ states.switch.test_state.state }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {"service": "test.automation"},
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_state", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
assert len(calls) == 1
async def test_off_action_optimistic(hass, calls):
"""Test off action in optimistic mode."""
assert await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"turn_off": {"service": "test.automation"},
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
}
},
}
},
)
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("switch.test_template_switch", STATE_ON)
await hass.async_block_till_done()
state = hass.states.get("switch.test_template_switch")
assert state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test_template_switch"},
blocking=True,
)
state = hass.states.get("switch.test_template_switch")
assert len(calls) == 1
assert state.state == STATE_OFF
async def test_restore_state(hass):
"""Test state restoration."""
mock_restore_cache(
hass,
(
State("switch.s1", STATE_ON),
State("switch.s2", STATE_OFF),
),
)
hass.state = CoreState.starting
mock_component(hass, "recorder")
await async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"s1": {
"turn_on": {"service": "test.automation"},
"turn_off": {"service": "test.automation"},
},
"s2": {
"turn_on": {"service": "test.automation"},
"turn_off": {"service": "test.automation"},
},
},
}
},
)
await hass.async_block_till_done()
state = hass.states.get("switch.s1")
assert state
assert state.state == STATE_ON
state = hass.states.get("switch.s2")
assert state
assert state.state == STATE_OFF
async def test_available_template_with_entities(hass):
"""Test availability templates with values from other entities."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ 1 == 1 }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
"availability_template": "{{ is_state('availability_state.state', 'on') }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
hass.states.async_set("availability_state.state", STATE_ON)
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state != STATE_UNAVAILABLE
hass.states.async_set("availability_state.state", STATE_OFF)
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state == STATE_UNAVAILABLE
async def test_invalid_availability_template_keeps_component_available(hass, caplog):
"""Test that an invalid availability keeps the device available."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch": {
"value_template": "{{ true }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
"availability_template": "{{ x - 12 }}",
}
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert hass.states.get("switch.test_template_switch").state != STATE_UNAVAILABLE
assert ("UndefinedError: 'x' is undefined") in caplog.text
async def test_unique_id(hass):
"""Test unique_id option only creates one switch per id."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "template",
"switches": {
"test_template_switch_01": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ true }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
},
"test_template_switch_02": {
"unique_id": "not-so-unique-anymore",
"value_template": "{{ false }}",
"turn_on": {
"service": "switch.turn_on",
"entity_id": "switch.test_state",
},
"turn_off": {
"service": "switch.turn_off",
"entity_id": "switch.test_state",
},
},
},
}
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 1
|
apache-2.0
|
Action-Committee/unstakeable
|
share/qt/extract_strings_qt.py
|
2945
|
1844
|
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
import operator
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_msgid:
msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages
files = glob.glob('src/*.cpp') + glob.glob('src/*.h')
# xgettext -n --keyword=_ $FILES
child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()
messages = parse_po(out)
f = open(OUT_CPP, 'w')
f.write("""#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
""")
f.write('static const char UNUSED *bitcoin_strings[] = {\n')
messages.sort(key=operator.itemgetter(0))
for (msgid, msgstr) in messages:
if msgid != EMPTY:
f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid)))
f.write('};')
f.close()
|
mit
|
SiCKRAGETV/SickRage
|
sickrage/libs/adba/aniDBmaper.py
|
6
|
6268
|
#!/usr/bin/env python
# coding=utf-8
#
# This file is part of aDBa.
#
# aDBa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# aDBa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with aDBa. If not, see <http://www.gnu.org/licenses/>.
from random import shuffle
class AniDBMaper:
blacklist = ('unused', 'retired', 'reserved')
def getAnimeBitsA(self, amask):
map = self.getAnimeMapA()
return self._getBitChain(map, amask)
def getAnimeCodesA(self, aBitChain):
amap = self.getAnimeMapA()
return self._getCodes(amap, aBitChain)
def getFileBitsF(self, fmask):
fmap = self.getFileMapF()
return self._getBitChain(fmap, fmask)
def getFileCodesF(self, bitChainF):
fmap = self.getFileMapF()
return self._getCodes(fmap, bitChainF)
def getFileBitsA(self, amask):
amap = self.getFileMapA()
return self._getBitChain(amap, amask)
def getFileCodesA(self, bitChainA):
amap = self.getFileMapA()
return self._getCodes(amap, bitChainA)
def _getBitChain(self, map, wanted):
"""Return an hex string with the correct bit set corresponding to the wanted fields in the map
"""
bit = 0
for index, field in enumerate(map):
if field in wanted and field not in self.blacklist:
bit ^= 1 << len(map) - index - 1
bit = str(hex(bit)).lstrip("0x").rstrip("L")
bit = ''.join(["0" for unused in range(int(len(map) / 4) - len(bit))]) + bit
return bit
@staticmethod
def _getCodes(map, bit_chain):
"""Returns a list with the corresponding fields as set in the bitChain (hex string)
"""
code_list = []
bit_chain = int(bit_chain, 16)
map_length = len(map)
for i in reversed(list(range(map_length))):
if bit_chain & (2 ** i):
code_list.append(map[map_length - i - 1])
return code_list
@staticmethod
def getAnimeMapA():
# each line is one byte
# only chnage this if the api changes
map = ['aid', 'unused', 'year', 'type', 'related_aid_list', 'related_aid_type', 'category_list', 'category_weight_list',
'romaji_name', 'kanji_name', 'english_name', 'other_name', 'short_name_list', 'synonym_list', 'retired', 'retired',
'episodes', 'highest_episode_number', 'special_ep_count', 'air_date', 'end_date', 'url', 'picname', 'category_id_list',
'rating', 'vote_count', 'temp_rating', 'temp_vote_count', 'average_review_rating', 'review_count', 'award_list', 'is_18_restricted',
'anime_planet_id', 'ANN_id', 'allcinema_id', 'AnimeNfo_id', 'unused', 'unused', 'unused', 'date_record_updated',
'character_id_list', 'creator_id_list', 'main_creator_id_list', 'main_creator_name_list', 'unused', 'unused', 'unused', 'unused',
'specials_count', 'credits_count', 'other_count', 'trailer_count', 'parody_count', 'unused', 'unused', 'unused']
return map
@staticmethod
def getFileMapF():
# each line is one byte
# only chnage this if the api changes
map = ['unused', 'aid', 'eid', 'gid', 'mylist_id', 'list_other_episodes', 'IsDeprecated', 'state',
'size', 'ed2k', 'md5', 'sha1', 'crc32', 'unused', 'unused', 'reserved',
'quality', 'source', 'audio_codec_list', 'audio_bitrate_list', 'video_codec', 'video_bitrate', 'video_resolution', 'file_type_extension',
'dub_language', 'sub_language', 'length_in_seconds', 'description', 'aired_date', 'unused', 'unused', 'anidb_file_name',
'mylist_state', 'mylist_filestate', 'mylist_viewed', 'mylist_viewdate', 'mylist_storage', 'mylist_source', 'mylist_other', 'unused']
return map
@staticmethod
def getFileMapA():
# each line is one byte
# only chnage this if the api changes
map = ['anime_total_episodes', 'highest_episode_number', 'year', 'type', 'related_aid_list', 'related_aid_type', 'category_list', 'reserved',
'romaji_name', 'kanji_name', 'english_name', 'other_name', 'short_name_list', 'synonym_list', 'retired', 'retired',
'epno', 'ep_name', 'ep_romaji_name', 'ep_kanji_name', 'episode_rating', 'episode_vote_count', 'unused', 'unused',
'group_name', 'group_short_name', 'unused', 'unused', 'unused', 'unused', 'unused', 'date_aid_record_updated']
return map
def checkMapping(self, verbos=False):
print("------")
print("File F: " + str(self.checkMapFileF(verbos)))
print("------")
print("File A: " + str(self.checkMapFileA(verbos)))
def checkMapFileF(self, verbos=False):
get_general_map = self.getFileMapF
get_bits = self.getFileBitsF
get_codes = self.getFileCodesF
return self._checkMapGeneral(get_general_map, get_bits, get_codes, verbos=verbos)
def checkMapFileA(self, verbos=False):
get_general_map = self.getFileMapA
get_bits = self.getFileBitsA
get_codes = self.getFileCodesA
return self._checkMapGeneral(get_general_map, get_bits, get_codes, verbos=verbos)
def _checkMapGeneral(self, getGeneralMap, getBits, getCodes, verbos=False):
map = getGeneralMap()
shuffle(map)
mask = [elem for elem in map if elem not in self.blacklist][:5]
bits = getBits(mask)
mask_re = getCodes(bits)
bits_re = getBits(mask_re)
if verbos:
print(mask)
print(mask_re)
print(bits)
print(bits_re)
print("bits are:" + str((bits_re == bits)))
print("map is :" + str((sorted(mask_re) == sorted(mask))))
return (bits_re == bits) and sorted(mask_re) == sorted(mask)
|
gpl-3.0
|
Bezoar/surrender-rides
|
bp_includes/external/wtforms/fields/simple.py
|
85
|
1274
|
from .. import widgets
from .core import StringField, BooleanField
__all__ = (
'BooleanField', 'TextAreaField', 'PasswordField', 'FileField',
'HiddenField', 'SubmitField', 'TextField'
)
class TextField(StringField):
"""
Legacy alias for StringField
"""
class TextAreaField(TextField):
"""
This field represents an HTML ``<textarea>`` and can be used to take
multi-line input.
"""
widget = widgets.TextArea()
class PasswordField(TextField):
"""
Represents an ``<input type="password">``.
"""
widget = widgets.PasswordInput()
class FileField(TextField):
"""
Can render a file-upload field. Will take any passed filename value, if
any is sent by the browser in the post params. This field will NOT
actually handle the file upload portion, as wtforms does not deal with
individual frameworks' file handling capabilities.
"""
widget = widgets.FileInput()
class HiddenField(TextField):
"""
Represents an ``<input type="hidden">``.
"""
widget = widgets.HiddenInput()
class SubmitField(BooleanField):
"""
Represents an ``<input type="submit">``. This allows checking if a given
submit button has been pressed.
"""
widget = widgets.SubmitInput()
|
mit
|
jonparrott/google-cloud-python
|
automl/google/cloud/automl_v1beta1/proto/operations_pb2.py
|
3
|
8501
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/automl_v1beta1/proto/operations.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
from google.cloud.automl_v1beta1.proto import model_pb2 as google_dot_cloud_dot_automl__v1beta1_dot_proto_dot_model__pb2
from google.cloud.automl_v1beta1.proto import model_evaluation_pb2 as google_dot_cloud_dot_automl__v1beta1_dot_proto_dot_model__evaluation__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2
from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/cloud/automl_v1beta1/proto/operations.proto',
package='google.cloud.automl.v1beta1',
syntax='proto3',
serialized_pb=_b('\n2google/cloud/automl_v1beta1/proto/operations.proto\x12\x1bgoogle.cloud.automl.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a-google/cloud/automl_v1beta1/proto/model.proto\x1a\x38google/cloud/automl_v1beta1/proto/model_evaluation.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\"\xa3\x02\n\x11OperationMetadata\x12Y\n\x14\x63reate_model_details\x18\n \x01(\x0b\x32\x39.google.cloud.automl.v1beta1.CreateModelOperationMetadataH\x00\x12\x18\n\x10progress_percent\x18\r \x01(\x05\x12,\n\x10partial_failures\x18\x02 \x03(\x0b\x32\x12.google.rpc.Status\x12/\n\x0b\x63reate_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\t\n\x07\x64\x65tails\"\x1e\n\x1c\x43reateModelOperationMetadataBf\n\x1f\x63om.google.cloud.automl.v1beta1P\x01ZAgoogle.golang.org/genproto/googleapis/cloud/automl/v1beta1;automlb\x06proto3')
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_cloud_dot_automl__v1beta1_dot_proto_dot_model__pb2.DESCRIPTOR,google_dot_cloud_dot_automl__v1beta1_dot_proto_dot_model__evaluation__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,google_dot_rpc_dot_status__pb2.DESCRIPTOR,])
_OPERATIONMETADATA = _descriptor.Descriptor(
name='OperationMetadata',
full_name='google.cloud.automl.v1beta1.OperationMetadata',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='create_model_details', full_name='google.cloud.automl.v1beta1.OperationMetadata.create_model_details', index=0,
number=10, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='progress_percent', full_name='google.cloud.automl.v1beta1.OperationMetadata.progress_percent', index=1,
number=13, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='partial_failures', full_name='google.cloud.automl.v1beta1.OperationMetadata.partial_failures', index=2,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='create_time', full_name='google.cloud.automl.v1beta1.OperationMetadata.create_time', index=3,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='update_time', full_name='google.cloud.automl.v1beta1.OperationMetadata.update_time', index=4,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='details', full_name='google.cloud.automl.v1beta1.OperationMetadata.details',
index=0, containing_type=None, fields=[]),
],
serialized_start=306,
serialized_end=597,
)
_CREATEMODELOPERATIONMETADATA = _descriptor.Descriptor(
name='CreateModelOperationMetadata',
full_name='google.cloud.automl.v1beta1.CreateModelOperationMetadata',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=599,
serialized_end=629,
)
_OPERATIONMETADATA.fields_by_name['create_model_details'].message_type = _CREATEMODELOPERATIONMETADATA
_OPERATIONMETADATA.fields_by_name['partial_failures'].message_type = google_dot_rpc_dot_status__pb2._STATUS
_OPERATIONMETADATA.fields_by_name['create_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_OPERATIONMETADATA.fields_by_name['update_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP
_OPERATIONMETADATA.oneofs_by_name['details'].fields.append(
_OPERATIONMETADATA.fields_by_name['create_model_details'])
_OPERATIONMETADATA.fields_by_name['create_model_details'].containing_oneof = _OPERATIONMETADATA.oneofs_by_name['details']
DESCRIPTOR.message_types_by_name['OperationMetadata'] = _OPERATIONMETADATA
DESCRIPTOR.message_types_by_name['CreateModelOperationMetadata'] = _CREATEMODELOPERATIONMETADATA
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
OperationMetadata = _reflection.GeneratedProtocolMessageType('OperationMetadata', (_message.Message,), dict(
DESCRIPTOR = _OPERATIONMETADATA,
__module__ = 'google.cloud.automl_v1beta1.proto.operations_pb2'
,
__doc__ = """Metadata used across all long running operations returned by AutoML API.
Attributes:
details:
Ouptut only. Details of specific operation. Even if this field
is empty, the presence allows to distinguish different types
of operations.
create_model_details:
Details of CreateModel operation.
progress_percent:
Output only. Progress of operation. Range: [0, 100].
partial_failures:
Output only. Partial failures encountered. E.g. single files
that couldn't be read. This field should never exceed 20
entries. Status details field will contain standard GCP error
details.
create_time:
Output only. Time when the operation was created.
update_time:
Output only. Time when the operation was updated for the last
time.
""",
# @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.OperationMetadata)
))
_sym_db.RegisterMessage(OperationMetadata)
CreateModelOperationMetadata = _reflection.GeneratedProtocolMessageType('CreateModelOperationMetadata', (_message.Message,), dict(
DESCRIPTOR = _CREATEMODELOPERATIONMETADATA,
__module__ = 'google.cloud.automl_v1beta1.proto.operations_pb2'
,
__doc__ = """Details of CreateModel operation.
""",
# @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.CreateModelOperationMetadata)
))
_sym_db.RegisterMessage(CreateModelOperationMetadata)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\037com.google.cloud.automl.v1beta1P\001ZAgoogle.golang.org/genproto/googleapis/cloud/automl/v1beta1;automl'))
# @@protoc_insertion_point(module_scope)
|
apache-2.0
|
LobsterBandit/Movie_List
|
update_db.py
|
1
|
2861
|
import sqlite3
import datetime
from config import DATABASE
def upsert_db(movie_list, database=DATABASE):
try:
db = sqlite3.connect(database)
cur = db.cursor()
for movie in movie_list:
cur.execute("""
insert or replace into Movie_List (id, Filename, Size, Path, Title,
Year, tmdb_id, Overview, imdb_id,
Rating, Runtime, Poster, Backdrop,
Release_Date, Tagline, Date_Added, Genre)
values ((select id from Movie_List where tmdb_id = ? and size = ?)
,?,?,?,?,?,?,?,?,?,?,?,?,?,?,
(select Date_Added from Movie_List where tmdb_id = ? and size = ?), ?)
""", (movie['tmdb_id'], movie['size'], movie['filename'], movie['size'], movie['root'], movie['title'],
movie['year'], movie['tmdb_id'], movie['overview'], movie['imdb_id'], movie['vote_average'],
movie['runtime'], movie['poster_path'], movie['backdrop_path'], movie['release_date'],
movie['tagline'], movie['tmdb_id'], movie['size'], movie['genres'])
)
# for genre in movie['genres']:
# cur.execute("""
# insert or replace into Genre (Id, GenreId, Source, MovieId)
# values ((select Id from Genre
# where MovieId = (select id from Movie_List where tmdb_id = ? and size = ?)
# and GenreId = ?
# and Source = ?)
# ,?, ?, (select id from Movie_List where tmdb_id = ? and size = ?))
# """, (movie['tmdb_id'], movie['size'], genre['id'], 'TMDb', genre['id'], 'TMDb', movie['tmdb_id'], movie['size'])
# )
db.commit()
except Exception as e:
db.rollback()
raise e
finally:
db.close()
def upsert_videos(video_list, database=DATABASE):
try:
db = sqlite3.connect(database)
cur = db.cursor()
for video in video_list:
cur.execute("""
insert or replace into Video (Video_ID, Type, Key, Name, Size, Site, Movie_id, Date_Added)
values ((select Video_ID from Video where Movie_id = ? and Key = ?),
?,?,?,?,?,?,
(select Date_Added from Video where Movie_id = ? and Key = ?))
""", (video['movie_id'], video['key'], video['type'], video['key'], video['name'], video['size'],
video['site'], video['movie_id'], video['movie_id'], video['key'])
)
db.commit()
except Exception as e:
db.rollback()
raise e
finally:
db.close()
|
mit
|
seanmcerlean/personal-projects
|
robotframework-imagetools/ImageTools/ImageSize.py
|
1
|
2728
|
from PIL import Image
class ImageSize():
"""
Providses size information and crop / resize tools for images
"""
def __init__(self):
pass
def _open_image_file(function):
"""
Decorator to open image file
"""
def read_image(image_file, *args):
try:
image = Image.open(image_file)
return function(image, *args)
except IOError:
return 'Error opening file'
return read_image
@staticmethod
@_open_image_file
def get_image_size(image):
"""
:param image_file: A path to an image file
:return: The size of the image as (width, height) tuple
"""
return image.size
@staticmethod
@_open_image_file
def get_image_width(image):
"""
:param image_file: A path to an image file
:return: The width of the image as a string
"""
return str(image.size[0])
@staticmethod
@_open_image_file
def get_image_height(image):
"""
:param image_file: A path to an image file
:return: The height of an image as a string
"""
return str(image.size[1])
@staticmethod
def crop_image(image_file, left, upper, right, lower):
"""
Opens an image, crops it and saves to the same location as image_cropped.ext
The top left of the image is point (0, 0)
:param image_file: Location of the image
:param left: leftmost point of crop area
:param upper: uppermost point of crop area
:param right: rightmost point of crop area
:param lower: lowest point of crop area
:return: None
"""
try:
image = Image.open(image_file)
crop_area = (int(left), int(upper), int(right), int(lower))
cropped_image = image.crop(box=crop_area)
cropped_image.save(image_file.replace('.', '_cropped.'))
except IOError:
return 'Error opening file'
@staticmethod
def resize_image(image_file, width, height):
"""
Opens an image, resizes it and saves to the same location as image_resized.ext
If enlarging the image, uses a nearest neignbour resample
:param image_file: Location of the image
:param width: width of new image
:param height: height of new image
:return: None
"""
try:
image = Image.open(image_file)
new_size = (int(width), int(height))
new_image = image.resize(size=new_size)
new_image.save(image_file.replace('.', '_resized.'))
except IOError:
return 'Error opening file'
|
gpl-3.0
|
linaro-technologies/jobserv
|
jobserv/settings.py
|
1
|
2446
|
# Copyright (C) 2017 Linaro Limited
# Author: Andy Doan <[email protected]>
import os
import hashlib
DEBUG = 1
SQLALCHEMY_TRACK_MODIFICATIONS = False
_fmt = os.environ.get('SQLALCHEMY_DATABASE_URI_FMT')
if _fmt:
SQLALCHEMY_DATABASE_URI = _fmt.format(
db_user=os.environ['DB_USER'], db_pass=os.environ['DB_PASS'])
else:
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
JOBS_DIR = os.environ.get('JOBS_DIR', '/data/ci_jobs')
WORKER_DIR = os.environ.get('WORKER_DIR', '/data/workers')
LOCAL_ARTIFACTS_DIR = os.environ.get('LOCAL_ARTIFACTS_DIR', '/data/artifacts')
GCE_BUCKET = os.environ.get('GCE_BUCKET')
STORAGE_BACKEND = os.environ.get(
'STORAGE_BACKEND', 'jobserv.storage.gce_storage')
INTERNAL_API_KEY = os.environ.get('INTERNAL_API_KEY', '').encode()
# Allow this to be deployed in a way that builds and runs can provide links
# to a custom web frontend
BUILD_URL_FMT = os.environ.get('BUILD_URL_FMT')
RUN_URL_FMT = os.environ.get('RUN_URL_FMT')
# BUILD_URL_FMT = 'https://example.com/{project}/{build}
# RUN_URL_FMT = 'https://example.com/{project}/{build}/{run}
SMTP_SERVER = os.environ.get('SMTP_SERVER', 'smtp.gmail.com')
SMTP_USER = os.environ.get('SMTP_USER')
SMTP_PASSWORD = os.environ.get('SMTP_PASSWORD')
LAVA_URLBASE = os.environ.get(
'LAVA_URLBASE', 'http://lava.linarotechnologies.org')
# every 90 seconds
GIT_POLLER_INTERVAL = int(os.environ.get('GIT_POLLER_INTERVAL', '90'))
CARBON_HOST = os.environ.get('CARBON_HOST')
if CARBON_HOST:
parts = CARBON_HOST.split(':')
if len(parts) == 1:
CARBON_HOST = (CARBON_HOST, 2003) # provide default port
elif len(parts) == 2:
CARBON_HOST = (parts[0], int(parts[1]))
else:
raise ValueError('Invalid CARBON_HOST setting: ' + CARBON_HOST)
CARBON_PREFIX = os.environ.get('CARBON_PREFIX', 'jobserv')
if CARBON_PREFIX and CARBON_PREFIX[-1] != '.':
CARBON_PREFIX += '.'
RUNNER = os.path.join(os.path.dirname(__file__),
'../runner/dist/jobserv_runner-0.1-py3-none-any.whl')
SIMULATOR_SCRIPT = os.path.join(os.path.dirname(__file__), '../simulator.py')
with open(SIMULATOR_SCRIPT, 'rb') as f:
h = hashlib.md5()
h.update(f.read())
SIMULATOR_SCRIPT_VERSION = h.hexdigest()
WORKER_SCRIPT = os.path.join(os.path.dirname(__file__), '../jobserv_worker.py')
with open(WORKER_SCRIPT, 'rb') as f:
h = hashlib.md5()
h.update(f.read())
WORKER_SCRIPT_VERSION = h.hexdigest()
|
agpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.