Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/strategies/tests/test_traverse.py
from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) from sympy.strategies.rl import rebuild from sympy.strategies.util import expr_fns from sympy import Add, Basic, Symbol, S from sympy.abc import x, y, z def zero_symbols(expression): return S.Zero if isinstance(expression, Symbol) else expression def test_sall(): zero_onelevel = sall(zero_symbols) assert zero_onelevel(Basic(x, y, Basic(x, z))) == Basic(0, 0, Basic(x, z)) def test_bottom_up(): _test_global_traversal(bottom_up) _test_stop_on_non_basics(bottom_up) def test_top_down(): _test_global_traversal(top_down) _test_stop_on_non_basics(top_down) def _test_global_traversal(trav): zero_all_symbols = trav(zero_symbols) assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ Basic(0, 0, Basic(0, 0)) def _test_stop_on_non_basics(trav): def add_one_if_can(expr): try: return expr + 1 except TypeError: return expr expr = Basic(1, 'a', Basic(2, 'b')) expected = Basic(2, 'a', Basic(3, 'b')) rl = trav(add_one_if_can) assert rl(expr) == expected class Basic2(Basic): pass rl = lambda x: Basic2(*x.args) if isinstance(x, Basic) else x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(1, 2, Basic(3, 4))) == Basic2(1, 2, Basic(3, 4)) def test_bottom_up_once(): bottom_rl = bottom_up_once(rl) assert bottom_rl(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, Basic2(3, 4)) def test_expr_fns(): expr = x + y**3 e = bottom_up(lambda v: v + 1, expr_fns)(expr) b = bottom_up(lambda v: Basic.__new__(Add, v, 1), basic_fns)(expr) assert rebuild(b) == e
1,749
22.333333
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/crypto/__init__.py
from sympy.crypto.crypto import (cycle_list, encipher_shift, encipher_affine, encipher_substitution, check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square, bifid6_square, encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6, decipher_bifid5, decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa, lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse, elgamal_private_key, elgamal_public_key, decipher_elgamal, encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key, padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5, bifid6, bifid10)
816
57.357143
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/crypto/crypto.py
# -*- coding: utf-8 -*- """ This file contains some classical ciphers and routines implementing a linear-feedback shift register (LFSR) and the Diffie-Hellman key exchange. """ from __future__ import print_function from string import whitespace, ascii_uppercase as uppercase, printable from sympy import nextprime from sympy.core import Rational, Symbol from sympy.core.numbers import igcdex, mod_inverse from sympy.core.compatibility import range from sympy.matrices import Matrix from sympy.ntheory import isprime, totient, primitive_root from sympy.polys.domains import FF from sympy.polys.polytools import gcd, Poly from sympy.utilities.misc import filldedent, translate from sympy.utilities.iterables import uniq from sympy.utilities.randtest import _randrange def AZ(s=None): """Return the letters of ``s`` in uppercase. In case more than one string is passed, each of them will be processed and a list of upper case strings will be returned. Examples ======== >>> from sympy.crypto.crypto import AZ >>> AZ('Hello, world!') 'HELLOWORLD' >>> AZ('Hello, world!'.split()) ['HELLO', 'WORLD'] See Also ======== check_and_join """ if not s: return uppercase t = type(s) is str if t: s = [s] rv = [check_and_join(i.upper().split(), uppercase, filter=True) for i in s] if t: return rv[0] return rv bifid5 = AZ().replace('J', '') bifid6 = AZ() + '0123456789' bifid10 = printable def padded_key(key, symbols, filter=True): """Return a string of the distinct characters of ``symbols`` with those of ``key`` appearing first, omitting characters in ``key`` that are not in ``symbols``. A ValueError is raised if a) there are duplicate characters in ``symbols`` or b) there are characters in ``key`` that are not in ``symbols``. Examples ======== >>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent call last): ... ValueError: duplicate characters in symbols: T """ syms = list(uniq(symbols)) if len(syms) != len(symbols): extra = ''.join(sorted(set( [i for i in symbols if symbols.count(i) > 1]))) raise ValueError('duplicate characters in symbols: %s' % extra) extra = set(key) - set(syms) if extra: raise ValueError( 'characters in key but not symbols: %s' % ''.join( sorted(extra))) key0 = ''.join(list(uniq(key))) return key0 + ''.join([i for i in syms if i not in key0]) def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of `phrase` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase: string or list of strings to be returned as a string symbols: iterable of characters allowed in ``phrase``; if ``symbols`` is None, no checking is performed Examples ======== >>> from sympy.crypto.crypto import check_and_join >>> check_and_join('a phrase') 'a phrase' >>> check_and_join('a phrase'.upper().split()) 'APHRASE' >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True) 'ARAE' >>> check_and_join('a phrase!'.upper().split(), 'ARE') Traceback (most recent call last): ... ValueError: characters in phrase but not symbols: "!HPS" """ rv = ''.join(''.join(phrase)) if symbols is not None: symbols = check_and_join(symbols) missing = ''.join(list(sorted(set(rv) - set(symbols)))) if missing: if not filter: raise ValueError( 'characters in phrase but not symbols: "%s"' % missing) rv = translate(rv, None, missing) return rv def _prep(msg, key, alp, default=None): if not alp: if not default: alp = AZ() msg = AZ(msg) key = AZ(key) else: alp = default else: alp = ''.join(alp) key = check_and_join(key, alp, filter=True) msg = check_and_join(msg, alp, filter=True) return msg, key, alp def cycle_list(k, n): """ Returns the elements of the list ``range(n)`` shifted to the left by ``k`` (so the list starts with ``k`` (mod ``n``)). Examples ======== >>> from sympy.crypto.crypto import cycle_list >>> cycle_list(3, 10) [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] """ k = k % n return list(range(k, n)) + list(range(k)) ######## shift cipher examples ############ def encipher_shift(msg, key, symbols=None): """ Performs shift cipher encryption on plaintext msg, and returns the ciphertext. Notes ===== The shift cipher is also called the Caesar cipher, after Julius Caesar, who, according to Suetonius, used it with a shift of three to protect messages of military significance. Caesar's nephew Augustus reportedly used a similar cipher, but with a right shift of 1. ALGORITHM: INPUT: ``key``: an integer (the secret key) ``msg``: plaintext of upper-case letters OUTPUT: ``ct``: ciphertext of upper-case letters STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by adding ``(k mod 26)`` to each element in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' There is also a convenience function that does this with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' """ msg, _, A = _prep(msg, '', symbols) shift = len(A) - key % len(A) key = A[shift:] + A[:shift] return translate(msg, key, A) def decipher_shift(msg, key, symbols=None): """ Return the text by shifting the characters of ``msg`` to the left by the amount given by ``key``. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' Or use this function with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' """ return encipher_shift(msg, -key, symbols) ######## affine cipher examples ############ def encipher_affine(msg, key, symbols=None, _inverse=False): r""" Performs the affine cipher encryption on plaintext ``msg``, and returns the ciphertext. Encryption is based on the map `x \rightarrow ax+b` (mod `N`) where ``N`` is the number of characters in the alphabet. Decryption is based on the map `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). In particular, for the map to be invertible, we need `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is not true. Notes ===== This is a straightforward generalization of the shift cipher with the added complexity of requiring 2 characters to be deciphered in order to recover the key. ALGORITHM: INPUT: ``msg``: string of characters that appear in ``symbols`` ``a, b``: a pair integers, with ``gcd(a, N) = 1`` (the secret key) ``symbols``: string of characters (default = uppercase letters). When no symbols are given, ``msg`` is converted to upper case letters and all other charactes are ignored. OUTPUT: ``ct``: string of characters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by replacing ``x`` by ``a*x + b (mod N)``, for each element ``x`` in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. See Also ======== decipher_affine """ msg, _, A = _prep(msg, '', symbols) N = len(A) a, b = key assert gcd(a, N) == 1 if _inverse: c = mod_inverse(a, N) d = -b*c a, b = c, d B = ''.join([A[(a*i + b) % N] for i in range(N)]) return translate(msg, A, B) def decipher_affine(msg, key, symbols=None): r""" Return the deciphered text that was made from the mapping, `x \rightarrow ax+b` (mod `N`), where ``N`` is the number of characters in the alphabet. Deciphering is done by reciphering with a new key: `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). Examples ======== >>> from sympy.crypto.crypto import encipher_affine, decipher_affine >>> msg = "GO NAVY BEAT ARMY" >>> key = (3, 1) >>> encipher_affine(msg, key) 'TROBMVENBGBALV' >>> decipher_affine(_, key) 'GONAVYBEATARMY' """ return encipher_affine(msg, key, symbols, _inverse=True) #################### substitution cipher ########################### def encipher_substitution(msg, old, new=None): """ Returns the ciphertext obtained by replacing each character that appears in ``old`` with the corresponding character in ``new``. If ``old`` is a mapping, then new is ignored and the replacements defined by ``old`` are used. Notes ===== This is a more general than the affine cipher in that the key can only be recovered by determining the mapping for each symbol. Though in practice, once a few symbols are recognized the mappings for other characters can be quickly guessed. Examples ======== >>> from sympy.crypto.crypto import encipher_substitution, AZ >>> old = 'OEYAG' >>> new = '034^6' >>> msg = AZ("go navy! beat army!") >>> ct = encipher_substitution(msg, old, new); ct '60N^V4B3^T^RM4' To decrypt a substitution, reverse the last two arguments: >>> encipher_substitution(ct, new, old) 'GONAVYBEATARMY' In the special case where ``old`` and ``new`` are a permuation of order 2 (representing a transposition of characters) their order is immaterial: >>> old = 'NAVY' >>> new = 'ANYV' >>> encipher = lambda x: encipher_substitution(x, old, new) >>> encipher('NAVY') 'ANYV' >>> encipher(_) 'NAVY' The substitution cipher, in general, is a method whereby "units" (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system. >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc'])) >>> print(encipher_substitution('abc', ords)) \97\98\99 """ return translate(msg, old, new) ###################################################################### #################### Vigenère cipher examples ######################## ###################################################################### def encipher_vigenere(msg, key, symbols=None): """ Performs the Vigenère cipher encryption on plaintext ``msg``, and returns the ciphertext. Examples ======== >>> from sympy.crypto.crypto import encipher_vigenere, AZ >>> key = "encrypt" >>> msg = "meet me on monday" >>> encipher_vigenere(msg, key) 'QRGKKTHRZQEBPR' Section 1 of the Kryptos sculpture at the CIA headquarters uses this cipher and also changes the order of the the alphabet [2]_. Here is the first line of that section of the sculpture: >>> from sympy.crypto.crypto import decipher_vigenere, padded_key >>> alp = padded_key('KRYPTOS', AZ()) >>> key = 'PALIMPSEST' >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ' >>> decipher_vigenere(msg, key, alp) 'BETWEENSUBTLESHADINGANDTHEABSENC' Notes ===== The Vigenère cipher is named after Blaise de Vigenère, a sixteenth century diplomat and cryptographer, by a historical accident. Vigenère actually invented a different and more complicated cipher. The so-called *Vigenère cipher* was actually invented by Giovan Batista Belaso in 1553. This cipher was used in the 1800's, for example, during the American Civil War. The Confederacy used a brass cipher disk to implement the Vigenère cipher (now on display in the NSA Museum in Fort Meade) [1]_. The Vigenère cipher is a generalization of the shift cipher. Whereas the shift cipher shifts each letter by the same amount (that amount being the key of the shift cipher) the Vigenère cipher shifts a letter by an amount determined by the key (which is a word or phrase known only to the sender and receiver). For example, if the key was a single letter, such as "C", then the so-called Vigenere cipher is actually a shift cipher with a shift of `2` (since "C" is the 2nd letter of the alphabet, if you start counting at `0`). If the key was a word with two letters, such as "CA", then the so-called Vigenère cipher will shift letters in even positions by `2` and letters in odd positions are left alone (shifted by `0`, since "A" is the 0th letter, if you start counting at `0`). ALGORITHM: INPUT: ``msg``: string of characters that appear in ``symbols`` (the plaintext) ``key``: a string of characters that appear in ``symbols`` (the secret key) ``symbols``: a string of letters defining the alphabet OUTPUT: ``ct``: string of characters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``key`` a list ``L1`` of corresponding integers. Let ``n1 = len(L1)``. 2. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 3. Break ``L2`` up sequencially into sublists of size ``n1``; the last sublist may be smaller than ``n1`` 4. For each of these sublists ``L`` of ``L2``, compute a new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)`` to the ``i``-th element in the sublist, for each ``i``. 5. Assemble these lists ``C`` by concatenation into a new list of length ``n2``. 6. Compute from the new list a string ``ct`` of corresponding letters. Once it is known that the key is, say, `n` characters long, frequency analysis can be applied to every `n`-th letter of the ciphertext to determine the plaintext. This method is called *Kasiski examination* (although it was first discovered by Babbage). If they key is as long as the message and is comprised of randomly selected characters -- a one-time pad -- the message is theoretically unbreakable. The cipher Vigenère actually discovered is an "auto-key" cipher described as follows. ALGORITHM: INPUT: ``key``: a string of letters (the secret key) ``msg``: string of letters (the plaintext message) OUTPUT: ``ct``: string of upper-case letters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 2. Let ``n1`` be the length of the key. Append to the string ``key`` the first ``n2 - n1`` characters of the plaintext message. Compute from this string (also of length ``n2``) a list ``L1`` of integers corresponding to the letter numbers in the first step. 3. Compute a new list ``C`` given by ``C[i] = L1[i] + L2[i] (mod N)``. 4. Compute from the new list a string ``ct`` of letters corresponding to the new integers. To decipher the auto-key ciphertext, the key is used to decipher the first ``n1`` characters and then those characters become the key to decipher the next ``n1`` characters, etc...: >>> m = AZ('go navy, beat army! yes you can'); m 'GONAVYBEATARMYYESYOUCAN' >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m) >>> auto_key = key + m[:n2 - n1]; auto_key 'GOLDBUGGONAVYBEATARMYYE' >>> ct = encipher_vigenere(m, auto_key); ct 'MCYDWSHKOGAMKZCELYFGAYR' >>> n1 = len(key) >>> pt = [] >>> while ct: ... part, ct = ct[:n1], ct[n1:] ... pt.append(decipher_vigenere(part, key)) ... key = pt[-1] ... >>> ''.join(pt) == m True References ========== .. [1] http://en.wikipedia.org/wiki/Vigenere_cipher .. [2] http://web.archive.org/web/20071116100808/ http://filebox.vt.edu/users/batman/kryptos.html (short URL: https://goo.gl/ijr22d) """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} key = [map[c] for c in key] N = len(map) k = len(key) rv = [] for i, m in enumerate(msg): rv.append(A[(map[m] + key[i % k]) % N]) rv = ''.join(rv) return rv def decipher_vigenere(msg, key, symbols=None): """ Decode using the Vigenère cipher. Examples ======== >>> from sympy.crypto.crypto import decipher_vigenere >>> key = "encrypt" >>> ct = "QRGK kt HRZQE BPR" >>> decipher_vigenere(ct, key) 'MEETMEONMONDAY' """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} N = len(A) # normally, 26 K = [map[c] for c in key] n = len(K) C = [map[c] for c in msg] rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)]) return rv #################### Hill cipher ######################## def encipher_hill(msg, key, symbols=None, pad="Q"): r""" Return the Hill cipher encryption of ``msg``. Notes ===== The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_, was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices. First, each letter is first encoded as a number starting with 0. Suppose your message `msg` consists of `n` capital letters, with no spaces. This may be regarded an `n`-tuple M of elements of `Z_{26}` (if the letters are those of the English alphabet). A key in the Hill cipher is a `k x k` matrix `K`, all of whose entries are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k` is one-to-one). ALGORITHM: INPUT: ``msg``: plaintext message of `n` upper-case letters ``key``: a `k x k` invertible matrix `K`, all of whose entries are in `Z_{26}` (or whatever number of symbols are being used). ``pad``: character (default "Q") to use to make length of text be a multiple of ``k`` OUTPUT: ``ct``: ciphertext of upper-case letters STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L`` of corresponding integers. Let ``n = len(L)``. 2. Break the list ``L`` up into ``t = ceiling(n/k)`` sublists ``L_1``, ..., ``L_t`` of size ``k`` (with the last list "padded" to ensure its size is ``k``). 3. Compute new list ``C_1``, ..., ``C_t`` given by ``C[i] = K*L_i`` (arithmetic is done mod N), for each ``i``. 4. Concatenate these into a list ``C = C_1 + ... + C_t``. 5. Compute from ``C`` a string ``ct`` of corresponding letters. This has length ``k*t``. References ========== .. [1] en.wikipedia.org/wiki/Hill_cipher .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet, The American Mathematical Monthly Vol.36, June-July 1929, pp.306-312. See Also ======== decipher_hill """ assert key.is_square assert len(pad) == 1 msg, pad, A = _prep(msg, pad, symbols) map = {c: i for i, c in enumerate(A)} P = [map[c] for c in msg] N = len(A) k = key.cols n = len(P) m, r = divmod(n, k) if r: P = P + [map[pad]]*(k - r) m += 1 rv = ''.join([A[c % N] for j in range(m) for c in list(key*Matrix(k, 1, [P[i] for i in range(k*j, k*(j + 1))]))]) return rv def decipher_hill(msg, key, symbols=None): """ Deciphering is the same as enciphering but using the inverse of the key matrix. Examples ======== >>> from sympy.crypto.crypto import encipher_hill, decipher_hill >>> from sympy import Matrix >>> key = Matrix([[1, 2], [3, 5]]) >>> encipher_hill("meet me on monday", key) 'UEQDUEODOCTCWQ' >>> decipher_hill(_, key) 'MEETMEONMONDAY' When the length of the plaintext (stripped of invalid characters) is not a multiple of the key dimension, extra characters will appear at the end of the enciphered and deciphered text. In order to decipher the text, those characters must be included in the text to be deciphered. In the following, the key has a dimension of 4 but the text is 2 short of being a multiple of 4 so two characters will be added. >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0], ... [2, 2, 3, 4], [1, 1, 0, 1]]) >>> msg = "ST" >>> encipher_hill(msg, key) 'HJEB' >>> decipher_hill(_, key) 'STQQ' >>> encipher_hill(msg, key, pad="Z") 'ISPK' >>> decipher_hill(_, key) 'STZZ' If the last two characters of the ciphertext were ignored in either case, the wrong plaintext would be recovered: >>> decipher_hill("HD", key) 'ORMV' >>> decipher_hill("IS", key) 'UIKY' """ assert key.is_square msg, _, A = _prep(msg, '', symbols) map = {c: i for i, c in enumerate(A)} C = [map[c] for c in msg] N = len(A) k = key.cols n = len(C) m, r = divmod(n, k) if r: C = C + [0]*(k - r) m += 1 key_inv = key.inv_mod(N) rv = ''.join([A[p % N] for j in range(m) for p in list(key_inv*Matrix( k, 1, [C[i] for i in range(k*j, k*(j + 1))]))]) return rv #################### Bifid cipher ######################## def encipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses an `n \times n` Polybius square. INPUT: ``msg``: plaintext string ``key``: short string for key; duplicate characters are ignored and then it is padded with the characters in ``symbols`` that were not in the short key ``symbols``: `n \times n` characters defining the alphabet (default is string.printable) OUTPUT: ciphertext (using Bifid5 cipher without spaces) See Also ======== decipher_bifid, encipher_bifid5, encipher_bifid6 """ msg, key, A = _prep(msg, key, symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the fractionalization row_col = dict([(ch, divmod(i, N)) for i, ch in enumerate(long_key)]) r, c = zip(*[row_col[x] for x in msg]) rc = r + c ch = {i: ch for ch, i in row_col.items()} rv = ''.join((ch[i] for i in zip(rc[::2], rc[1::2]))) return rv def decipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `n \times n` Polybius square. INPUT: ``msg``: ciphertext string ``key``: short string for key; duplicate characters are ignored and then it is padded with the characters in ``symbols`` that were not in the short key ``symbols``: `n \times n` characters defining the alphabet (default=string.printable, a `10 \times 10` matrix) OUTPUT: deciphered text Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid, decipher_bifid, AZ) Do an encryption using the bifid5 alphabet: >>> alp = AZ().replace('J', '') >>> ct = AZ("meet me on monday!") >>> key = AZ("gold bug") >>> encipher_bifid(ct, key, alp) 'IEILHHFSTSFQYE' When entering the text or ciphertext, spaces are ignored so it can be formatted as desired. Re-entering the ciphertext from the preceding, putting 4 characters per line and padding with an extra J, does not cause problems for the deciphering: >>> decipher_bifid(''' ... IEILH ... HFSTS ... FQYEJ''', key, alp) 'MEETMEONMONDAY' When no alphabet is given, all 100 printable characters will be used: >>> key = '' >>> encipher_bifid('hello world!', key) 'bmtwmg-bIo*w' >>> decipher_bifid(_, key) 'hello world!' If the key is changed, a different encryption is obtained: >>> key = 'gold bug' >>> encipher_bifid('hello world!', 'gold_bug') 'hg2sfuei7t}w' And if the key used to decrypt the message is not exact, the original text will not be perfectly obtained: >>> decipher_bifid(_, 'gold pug') 'heldo~wor6d!' """ msg, _, A = _prep(msg, '', symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the reverse fractionalization row_col = dict( [(ch, divmod(i, N)) for i, ch in enumerate(long_key)]) rc = [i for c in msg for i in row_col[c]] n = len(msg) rc = zip(*(rc[:n], rc[n:])) ch = {i: ch for ch, i in row_col.items()} rv = ''.join((ch[i] for i in rc)) return rv def bifid_square(key): """Return characters of ``key`` arranged in a square. Examples ======== >>> from sympy.crypto.crypto import ( ... bifid_square, AZ, padded_key, bifid5) >>> bifid_square(AZ().replace('J', '')) Matrix([ [A, B, C, D, E], [F, G, H, I, K], [L, M, N, O, P], [Q, R, S, T, U], [V, W, X, Y, Z]]) >>> bifid_square(padded_key(AZ('gold bug!'), bifid5)) Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) See Also ======== padded_key """ A = ''.join(uniq(''.join(key))) n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) n = int(n) f = lambda i, j: Symbol(A[n*i + j]) rv = Matrix(n, n, f) return rv def encipher_bifid5(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square. The letter "J" is ignored so it must be replaced with something else (traditionally an "I") before encryption. Notes ===== The Bifid cipher was invented around 1901 by Felix Delastelle. It is a *fractional substitution* cipher, where letters are replaced by pairs of symbols from a smaller alphabet. The cipher uses a `5 \times 5` square filled with some ordering of the alphabet, except that "J" is replaced with "I" (this is a so-called Polybius square; there is a `6 \times 6` analog if you add back in "J" and also append onto the usual 26 letter alphabet, the digits 0, 1, ..., 9). According to Helen Gaines' book *Cryptanalysis*, this type of cipher was used in the field by the German Army during World War I. ALGORITHM: (5x5 case) INPUT: ``msg``: plaintext string; converted to upper case and filtered of anything but all letters except J. ``key``: short string for key; non-alphabetic letters, J and duplicated characters are ignored and then, if the length is less than 25 characters, it is padded with other letters of the alphabet (in alphabetical order). OUTPUT: ciphertext (all caps, no spaces) STEPS: 0. Create the `5 \times 5` Polybius square ``S`` associated to ``key`` as follows: a) moving from left-to-right, top-to-bottom, place the letters of the key into a `5 \times 5` matrix, b) if the key has less than 25 letters, add the letters of the alphabet not in the key until the `5 \times 5` square is filled. 1. Create a list ``P`` of pairs of numbers which are the coordinates in the Polybius square of the letters in ``msg``. 2. Let ``L1`` be the list of all first coordinates of ``P`` (length of ``L1 = n``), let ``L2`` be the list of all second coordinates of ``P`` (so the length of ``L2`` is also ``n``). 3. Let ``L`` be the concatenation of ``L1`` and ``L2`` (length ``L = 2*n``), except that consecutive numbers are paired ``(L[2*i], L[2*i + 1])``. You can regard ``L`` as a list of pairs of length ``n``. 4. Let ``C`` be the list of all letters which are of the form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a string, this is the ciphertext of ``msg``. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid5, decipher_bifid5) "J" will be omitted unless it is replaced with somthing else: >>> round_trip = lambda m, k: \ ... decipher_bifid5(encipher_bifid5(m, k), k) >>> key = 'a' >>> msg = "JOSIE" >>> round_trip(msg, key) 'OSIE' >>> round_trip(msg.replace("J", "I"), key) 'IOSIE' >>> j = "QIQ" >>> round_trip(msg.replace("J", j), key).replace(j, "J") 'JOSIE' See Also ======== decipher_bifid5, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return encipher_bifid(msg, '', key) def decipher_bifid5(msg, key): r""" Return the Bifid cipher decryption of ``msg``. This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square; the letter "J" is ignored unless a ``key`` of length 25 is used. INPUT: ``msg``: ciphertext string ``key``: short string for key; duplicated characters are ignored and if the length is less then 25 characters, it will be padded with other letters from the alphabet omitting "J". Non-alphabetic characters are ignored. OUTPUT: plaintext from Bifid5 cipher (all caps, no spaces) Examples ======== >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5 >>> key = "gold bug" >>> encipher_bifid5('meet me on friday', key) 'IEILEHFSTSFXEE' >>> encipher_bifid5('meet me on monday', key) 'IEILHHFSTSFQYE' >>> decipher_bifid5(_, key) 'MEETMEONMONDAY' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return decipher_bifid(msg, '', key) def bifid5_square(key=None): r""" 5x5 Polybius square. Produce the Polybius square for the `5 \times 5` Bifid cipher. Examples ======== >>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) """ if not key: key = bifid5 else: _, key, _ = _prep('', key.upper(), None, bifid5) key = padded_key(key, bifid5) return bifid_square(key) def encipher_bifid6(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. INPUT: ``msg``: plaintext string (digits okay) ``key``: short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. OUTPUT: ciphertext from Bifid cipher (all caps, no spaces) See Also ======== decipher_bifid6, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return encipher_bifid(msg, '', key) def decipher_bifid6(msg, key): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. INPUT: ``msg``: ciphertext string (digits okay); converted to upper case ``key``: short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. All letters are converted to uppercase. OUTPUT: plaintext from Bifid cipher (all caps, no spaces) Examples ======== >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6 >>> key = "gold bug" >>> encipher_bifid6('meet me on monday at 8am', key) 'KFKLJJHF5MMMKTFRGPL' >>> decipher_bifid6(_, key) 'MEETMEONMONDAYAT8AM' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return decipher_bifid(msg, '', key) def bifid6_square(key=None): r""" 6x6 Polybius square. Produces the Polybius square for the `6 \times 6` Bifid cipher. Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9". Examples ======== >>> from sympy.crypto.crypto import bifid6_square >>> key = "gold bug" >>> bifid6_square(key) Matrix([ [G, O, L, D, B, U], [A, C, E, F, H, I], [J, K, M, N, P, Q], [R, S, T, V, W, X], [Y, Z, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]) """ if not key: key = bifid6 else: _, key, _ = _prep('', key.upper(), None, bifid6) key = padded_key(key, bifid6) return bifid_square(key) #################### RSA ############################# def rsa_public_key(p, q, e): r""" Return the RSA *public key* pair, `(n, e)`, where `n` is a product of two primes and `e` is relatively prime (coprime) to the Euler totient `\phi(n)`. False is returned if any assumption is violated. Examples ======== >>> from sympy.crypto.crypto import rsa_public_key >>> p, q, e = 3, 5, 7 >>> rsa_public_key(p, q, e) (15, 7) >>> rsa_public_key(p, q, 30) False """ n = p*q if isprime(p) and isprime(q): phi = totient(n) if gcd(e, phi) == 1: return n, e return False def rsa_private_key(p, q, e): r""" Return the RSA *private key*, `(n,d)`, where `n` is a product of two primes and `d` is the inverse of `e` (mod `\phi(n)`). False is returned if any assumption is violated. Examples ======== >>> from sympy.crypto.crypto import rsa_private_key >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) >>> rsa_private_key(p, q, 30) False """ n = p*q if isprime(p) and isprime(q): phi = totient(n) if gcd(e, phi) == 1: d = mod_inverse(e, phi) return n, d return False def encipher_rsa(i, key): """ Return encryption of ``i`` by computing `i^e` (mod `n`), where ``key`` is the public key `(n, e)`. Examples ======== >>> from sympy.crypto.crypto import encipher_rsa, rsa_public_key >>> p, q, e = 3, 5, 7 >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, puk) 3 """ n, e = key return pow(i, e, n) def decipher_rsa(i, key): """ Return decyption of ``i`` by computing `i^d` (mod `n`), where ``key`` is the private key `(n, d)`. Examples ======== >>> from sympy.crypto.crypto import decipher_rsa, rsa_private_key >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> msg = 3 >>> decipher_rsa(msg, prk) 12 """ n, d = key return pow(i, d, n) #################### kid krypto (kid RSA) ############################# def kid_rsa_public_key(a, b, A, B): r""" Kid RSA is a version of RSA useful to teach grade school children since it does not involve exponentiation. Alice wants to talk to Bob. Bob generates keys as follows. Key generation: * Select positive integers `a, b, A, B` at random. * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1)//M`. * The *public key* is `(n, e)`. Bob sends these to Alice. * The *private key* is `(n, d)`, which Bob keeps secret. Encryption: If `p` is the plaintext message then the ciphertext is `c = p e \pmod n`. Decryption: If `c` is the ciphertext message then the plaintext is `p = c d \pmod n`. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_public_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_public_key(a, b, A, B) (369, 58) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, e def kid_rsa_private_key(a, b, A, B): """ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1) / M`. The *private key* is `d`, which Bob keeps secret. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_private_key(a, b, A, B) (369, 70) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, d def encipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the public key. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_kid_rsa, kid_rsa_public_key) >>> msg = 200 >>> a, b, A, B = 3, 4, 5, 6 >>> key = kid_rsa_public_key(a, b, A, B) >>> encipher_kid_rsa(msg, key) 161 """ n, e = key return (msg*e) % n def decipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the private key. Examples ======== >>> from sympy.crypto.crypto import ( ... kid_rsa_public_key, kid_rsa_private_key, ... decipher_kid_rsa, encipher_kid_rsa) >>> a, b, A, B = 3, 4, 5, 6 >>> d = kid_rsa_private_key(a, b, A, B) >>> msg = 200 >>> pub = kid_rsa_public_key(a, b, A, B) >>> pri = kid_rsa_private_key(a, b, A, B) >>> ct = encipher_kid_rsa(msg, pub) >>> decipher_kid_rsa(ct, pri) 200 """ n, d = key return (msg*d) % n #################### Morse Code ###################################### morse_char = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "-----": "0", "----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", ".-.-.-": ".", "--..--": ",", "---...": ":", "-.-.-.": ";", "..--..": "?", "-....-": "-", "..--.-": "_", "-.--.": "(", "-.--.-": ")", ".----.": "'", "-...-": "=", ".-.-.": "+", "-..-.": "/", ".--.-.": "@", "...-..-": "$", "-.-.--": "!"} char_morse = {v: k for k, v in morse_char.items()} def encode_morse(msg, sep='|', mapping=None): """ Encodes a plaintext into popular Morse Code with letters separated by `sep` and words by a double `sep`. References ========== .. [1] http://en.wikipedia.org/wiki/Morse_code Examples ======== >>> from sympy.crypto.crypto import encode_morse >>> msg = 'ATTACK RIGHT FLANK' >>> encode_morse(msg) '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-' """ mapping = mapping or char_morse assert sep not in mapping word_sep = 2*sep mapping[" "] = word_sep suffix = msg and msg[-1] in whitespace # normalize whitespace msg = (' ' if word_sep else '').join(msg.split()) # omit unmapped chars chars = set(''.join(msg.split())) ok = set(mapping.keys()) msg = translate(msg, None, ''.join(chars - ok)) morsestring = [] words = msg.split() for word in words: morseword = [] for letter in word: morseletter = mapping[letter] morseword.append(morseletter) word = sep.join(morseword) morsestring.append(word) return word_sep.join(morsestring) + (word_sep if suffix else '') def decode_morse(msg, sep='|', mapping=None): """ Decodes a Morse Code with letters separated by `sep` (default is '|') and words by `word_sep` (default is '||) into plaintext. References ========== .. [1] http://en.wikipedia.org/wiki/Morse_code Examples ======== >>> from sympy.crypto.crypto import decode_morse >>> mc = '--|---|...-|.||.|.-|...|-' >>> decode_morse(mc) 'MOVE EAST' """ mapping = mapping or morse_char word_sep = 2*sep characterstring = [] words = msg.strip(word_sep).split(word_sep) for word in words: letters = word.split(sep) chars = [mapping[c] for c in letters] word = ''.join(chars) characterstring.append(word) rv = " ".join(characterstring) return rv #################### LFSRs ########################################## def lfsr_sequence(key, fill, n): r""" This function creates an lfsr sequence. INPUT: ``key``: a list of finite field elements, `[c_0, c_1, \ldots, c_k].` ``fill``: the list of the initial terms of the lfsr sequence, `[x_0, x_1, \ldots, x_k].` ``n``: number of terms of the sequence that the function returns. OUTPUT: The lfsr sequence defined by `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for `n \leq k`. Notes ===== S. Golomb [G]_ gives a list of three statistical properties a sequence of numbers `a = \{a_n\}_{n=1}^\infty`, `a_n \in \{0,1\}`, should display to be considered "random". Define the autocorrelation of `a` to be .. math:: C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}. In the case where `a` is periodic with period `P` then this reduces to .. math:: C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}. Assume `a` is periodic with period `P`. - balance: .. math:: \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1. - low autocorrelation: .. math:: C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right. (For sequences satisfying these first two properties, it is known that `\epsilon = -1/P` must hold.) - proportional runs property: In each period, half the runs have length `1`, one-fourth have length `2`, etc. Moreover, there are as many runs of `1`'s as there are of `0`'s. References ========== .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press, Laguna Hills, Ca, 1967 Examples ======== >>> from sympy.crypto.crypto import lfsr_sequence >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> lfsr_sequence(key, fill, 10) [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2] """ if not isinstance(key, list): raise TypeError("key must be a list") if not isinstance(fill, list): raise TypeError("fill must be a list") p = key[0].mod F = FF(p) s = fill k = len(fill) L = [] for i in range(n): s0 = s[:] L.append(s[0]) s = s[1:k] x = sum([int(key[i]*s0[i]) for i in range(k)]) s.append(F(x)) return L # use [x.to_int() for x in L] for int version def lfsr_autocorrelation(L, P, k): """ This function computes the LFSR autocorrelation function. INPUT: ``L``: is a periodic sequence of elements of `GF(2)`. ``L`` must have length larger than ``P``. ``P``: the period of ``L`` ``k``: an integer (`0 < k < p`) OUTPUT: the ``k``-th value of the autocorrelation of the LFSR ``L`` Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_autocorrelation) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_autocorrelation(s, 15, 7) -1/15 >>> lfsr_autocorrelation(s, 15, 0) 1 """ if not isinstance(L, list): raise TypeError("L (=%s) must be a list" % L) P = int(P) k = int(k) L0 = L[:P] # slices makes a copy L1 = L0 + L0[:k] L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)] tot = sum(L2) return Rational(tot, P) def lfsr_connection_polynomial(s): """ This function computes the LFSR connection polynomial. INPUT: ``s``: a sequence of elements of even length, with entries in a finite field OUTPUT: ``C(x)``: the connection polynomial of a minimal LFSR yielding ``s``. This implements the algorithm in section 3 of J. L. Massey's article [M]_. References ========== .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding." IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127, Jan 1969. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_connection_polynomial) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**4 + x + 1 >>> fill = [F(1), F(0), F(0), F(1)] >>> key = [F(1), F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(1), F(0)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x**2 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x + 1 """ # Initialization: p = s[0].mod F = FF(p) x = Symbol("x") C = 1*x**0 B = 1*x**0 m = 1 b = 1*x**0 L = 0 N = 0 while N < len(s): if L > 0: dC = Poly(C).degree() r = min(L + 1, dC + 1) coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int() for i in range(1, r)])) % p if L == 0: d = s[N].to_int()*x**0 if d == 0: m += 1 N += 1 if d > 0: if 2*L > N: C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() m += 1 N += 1 else: T = C C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() L = N + 1 - L m = 1 b = d B = T N += 1 dC = Poly(C).degree() coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] return sum([coeffsC[i] % p*x**i for i in range(dC + 1) if coeffsC[i] is not None]) #################### ElGamal ############################# def elgamal_private_key(digit=10, seed=None): """ Return three number tuple as private key. Elgamal encryption is based on the mathmatical problem called the Discrete Logarithm Problem (DLP). For example, `a^{b} \equiv c \pmod p` In general, if ``a`` and ``b`` are known, ``ct`` is easily calculated. If ``b`` is unknown, it is hard to use ``a`` and ``ct`` to get ``b``. Parameters ========== digit : minimum number of binary digits for key Returns ======= (p, r, d) : p = prime number, r = primitive root, d = random number Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.ntheory import is_primitive_root, isprime >>> a, b, _ = elgamal_private_key() >>> isprime(a) True >>> is_primitive_root(b, a) True """ randrange = _randrange(seed) p = nextprime(2**digit) return p, primitive_root(p), randrange(2, p) def elgamal_public_key(key): """ Return three number tuple as public key. Parameters ========== key : Tuple (p, r, e) generated by ``elgamal_private_key`` Returns ======= (p, r, e = r**d mod p) : d is a random number in private key. Examples ======== >>> from sympy.crypto.crypto import elgamal_public_key >>> elgamal_public_key((1031, 14, 636)) (1031, 14, 212) """ p, r, e = key return p, r, pow(r, e, p) def encipher_elgamal(i, key, seed=None): """ Encrypt message with public key ``i`` is a plaintext message expressed as an integer. ``key`` is public key (p, r, e). In order to encrypt a message, a random number ``a`` in ``range(2, p)`` is generated and the encryped message is returned as `c_{1}` and `c_{2}` where: `c_{1} \equiv r^{a} \pmod p` `c_{2} \equiv m e^{a} \pmod p` Parameters ========== msg : int of encoded message key : public key Returns ======= (c1, c2) : Encipher into two number Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6) """ p, r, e = key if i < 0 or i >= p: raise ValueError( 'Message (%s) should be in range(%s)' % (i, p)) randrange = _randrange(seed) a = randrange(2, p) return pow(r, a, p), i*pow(e, a, p) % p def decipher_elgamal(msg, key): r""" Decrypt message with private key `msg = (c_{1}, c_{2})` `key = (p, r, d)` According to extended Eucliden theorem, `u c_{1}^{d} + p n = 1` `u \equiv 1/{{c_{1}}^d} \pmod p` `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p` `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p` Examples ======== >>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True """ p, r, d = key c1, c2 = msg u = igcdex(c1**d, p)[0] return u * c2 % p ################ Diffie-Hellman Key Exchange ######################### def dh_private_key(digit=10, seed=None): """ Return three integer tuple as private key. Diffie-Hellman key exchange is based on the mathematical problem called the Discrete Logarithm Problem (see ElGamal). Diffie-Hellman key exchange is divided into the following steps: * Alice and Bob agree on a base that consist of a prime ``p`` and a primitive root of ``p`` called ``g`` * Alice choses a number ``a`` and Bob choses a number ``b`` where ``a`` and ``b`` are random numbers in range `[2, p)`. These are their private keys. * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends Alice `g^{b} \pmod p` * They both raise the received value to their secretly chosen number (``a`` or ``b``) and now have both as their shared key `g^{ab} \pmod p` Parameters ========== digit: minimum number of binary digits required in key Returns ======= (p, g, a) : p = prime number, g = primitive root of p, a = random number from 2 thru p - 1 Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.utilities.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import dh_private_key >>> from sympy.ntheory import isprime, is_primitive_root >>> p, g, _ = dh_private_key() >>> isprime(p) True >>> is_primitive_root(g, p) True >>> p, g, _ = dh_private_key(5) >>> isprime(p) True >>> is_primitive_root(g, p) True """ p = nextprime(2**digit) g = primitive_root(p) randrange = _randrange(seed) a = randrange(2, p) return p, g, a def dh_public_key(key): """ Return three number tuple as public key. This is the tuple that Alice sends to Bob. Parameters ========== key: Tuple (p, g, a) generated by ``dh_private_key`` Returns ======= (p, g, g^a mod p) : p, g and a as in Parameters Examples ======== >>> from sympy.crypto.crypto import dh_private_key, dh_public_key >>> p, g, a = dh_private_key(); >>> _p, _g, x = dh_public_key((p, g, a)) >>> p == _p and g == _g True >>> x == pow(g, a, p) True """ p, g, a = key return p, g, pow(g, a, p) def dh_shared_key(key, b): """ Return an integer that is the shared key. This is what Bob and Alice can both calculate using the public keys they received from each other and their private keys. Parameters ========== key: Tuple (p, g, x) generated by ``dh_public_key`` b: Random number in the range of 2 to p - 1 (Chosen by second key exchange member (Bob)) Returns ======= shared key (int) Examples ======== >>> from sympy.crypto.crypto import ( ... dh_private_key, dh_public_key, dh_shared_key) >>> prk = dh_private_key(); >>> p, g, x = dh_public_key(prk); >>> sk = dh_shared_key((p, g, x), 1000) >>> sk == pow(x, 1000, p) True """ p, _, x = key if 1 >= b or b >= p: raise ValueError(filldedent(''' Value of b should be greater 1 and less than prime %s.''' % p)) return pow(x, b, p)
56,916
26.90049
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/crypto/tests/test_crypto.py
from sympy.core import symbols from sympy.core.compatibility import range from sympy.crypto.crypto import (cycle_list, encipher_shift, encipher_affine, encipher_substitution, check_and_join, encipher_vigenere, decipher_vigenere, encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6, bifid5_square, bifid6_square, bifid5, bifid6, bifid10, decipher_bifid5, decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa, lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse, elgamal_private_key, elgamal_public_key, encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key, dh_shared_key, decipher_shift, decipher_affine, encipher_bifid, decipher_bifid, bifid_square, padded_key, uniq) from sympy.matrices import Matrix from sympy.ntheory import isprime, is_primitive_root from sympy.polys.domains import FF from sympy.utilities.pytest import raises, slow from random import randrange def test_cycle_list(): assert cycle_list(3, 4) == [3, 0, 1, 2] assert cycle_list(-1, 4) == [3, 0, 1, 2] assert cycle_list(1, 4) == [1, 2, 3, 0] def test_encipher_shift(): assert encipher_shift("ABC", 0) == "ABC" assert encipher_shift("ABC", 1) == "BCD" assert encipher_shift("ABC", -1) == "ZAB" assert decipher_shift("ZAB", -1) == "ABC" def test_encipher_affine(): assert encipher_affine("ABC", (1, 0)) == "ABC" assert encipher_affine("ABC", (1, 1)) == "BCD" assert encipher_affine("ABC", (-1, 0)) == "AZY" assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD" assert encipher_affine("123", (-1, 1), symbols="1234") == "214" assert encipher_affine("ABC", (3, 16)) == "QTW" assert decipher_affine("QTW", (3, 16)) == "ABC" def test_encipher_substitution(): assert encipher_substitution("ABC", "BAC", "ABC") == "BAC" assert encipher_substitution("123", "1243", "1234") == "124" def test_check_and_join(): assert check_and_join("abc") == "abc" assert check_and_join(uniq("aaabc")) == "abc" assert check_and_join("ab c".split()) == "abc" assert check_and_join("abc", "a", filter=True) == "a" raises(ValueError, lambda: check_and_join('ab', 'a')) def test_encipher_vigenere(): assert encipher_vigenere("ABC", "ABC") == "ACE" assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA" assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC" assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC" assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A" def test_decipher_vigenere(): assert decipher_vigenere("ABC", "ABC") == "AAA" assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA" assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC" assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA" assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A" def test_encipher_hill(): A = Matrix(2, 2, [1, 2, 3, 5]) assert encipher_hill("ABCD", A) == "CFIV" A = Matrix(2, 2, [1, 0, 0, 1]) assert encipher_hill("ABCD", A) == "ABCD" assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD" A = Matrix(2, 2, [1, 2, 3, 5]) assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB" assert encipher_hill("AB", A, symbols="ABCD") == "CB" # message length, n, does not need to be a multiple of k; # it is padded assert encipher_hill("ABA", A) == "CFGC" assert encipher_hill("ABA", A, pad="Z") == "CFYV" def test_decipher_hill(): A = Matrix(2, 2, [1, 2, 3, 5]) assert decipher_hill("CFIV", A) == "ABCD" A = Matrix(2, 2, [1, 0, 0, 1]) assert decipher_hill("ABCD", A) == "ABCD" assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD" A = Matrix(2, 2, [1, 2, 3, 5]) assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD" assert decipher_hill("CB", A, symbols="ABCD") == "AB" # n does not need to be a multiple of k assert decipher_hill("CFA", A) == "ABAA" def test_encipher_bifid5(): assert encipher_bifid5("AB", "AB") == "AB" assert encipher_bifid5("AB", "CD") == "CO" assert encipher_bifid5("ab", "c") == "CH" assert encipher_bifid5("a bc", "b") == "BAC" def test_bifid5_square(): A = bifid5 f = lambda i, j: symbols(A[5*i + j]) M = Matrix(5, 5, f) assert bifid5_square("") == M def test_decipher_bifid5(): assert decipher_bifid5("AB", "AB") == "AB" assert decipher_bifid5("CO", "CD") == "AB" assert decipher_bifid5("ch", "c") == "AB" assert decipher_bifid5("b ac", "b") == "ABC" def test_encipher_bifid6(): assert encipher_bifid6("AB", "AB") == "AB" assert encipher_bifid6("AB", "CD") == "CP" assert encipher_bifid6("ab", "c") == "CI" assert encipher_bifid6("a bc", "b") == "BAC" def test_decipher_bifid6(): assert decipher_bifid6("AB", "AB") == "AB" assert decipher_bifid6("CP", "CD") == "AB" assert decipher_bifid6("ci", "c") == "AB" assert decipher_bifid6("b ac", "b") == "ABC" def test_bifid6_square(): A = bifid6 f = lambda i, j: symbols(A[6*i + j]) M = Matrix(6, 6, f) assert bifid6_square("") == M def test_rsa_public_key(): assert rsa_public_key(2, 2, 1) == (4, 1) assert rsa_public_key(2, 3, 1) == (6, 1) assert rsa_public_key(5, 3, 3) == (15, 3) assert rsa_public_key(8, 8, 8) is False def test_rsa_private_key(): assert rsa_private_key(2, 2, 1) == (4, 1) assert rsa_private_key(2, 3, 1) == (6, 1) assert rsa_private_key(5, 3, 3) == (15, 3) assert rsa_private_key(23,29,5) == (667,493) assert rsa_private_key(8, 8, 8) is False def test_encipher_rsa(): puk = rsa_public_key(2, 2, 1) assert encipher_rsa(2, puk) == 2 puk = rsa_public_key(2, 3, 1) assert encipher_rsa(2, puk) == 2 puk = rsa_public_key(5, 3, 3) assert encipher_rsa(2, puk) == 8 def test_decipher_rsa(): prk = rsa_private_key(2, 2, 1) assert decipher_rsa(2, prk) == 2 prk = rsa_private_key(2, 3, 1) assert decipher_rsa(2, prk) == 2 prk = rsa_private_key(5, 3, 3) assert decipher_rsa(8, prk) == 2 def test_kid_rsa_public_key(): assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2) assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3) assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2) def test_kid_rsa_private_key(): assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3) assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3) assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4) def test_encipher_kid_rsa(): assert encipher_kid_rsa(1, (5, 2)) == 2 assert encipher_kid_rsa(1, (8, 3)) == 3 assert encipher_kid_rsa(1, (7, 2)) == 2 def test_decipher_kid_rsa(): assert decipher_kid_rsa(2, (5, 3)) == 1 assert decipher_kid_rsa(3, (8, 3)) == 1 assert decipher_kid_rsa(2, (7, 4)) == 1 def test_encode_morse(): assert encode_morse('ABC') == '.-|-...|-.-.' assert encode_morse('SMS ') == '...|--|...||' assert encode_morse('SMS\n') == '...|--|...||' assert encode_morse('') == '' assert encode_morse(' ') == '||' assert encode_morse(' ', sep='`') == '``' assert encode_morse(' ', sep='``') == '````' assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.' def test_decode_morse(): assert decode_morse('-.-|.|-.--') == 'KEY' assert decode_morse('.-.|..-|-.||') == 'RUN' raises(KeyError, lambda: decode_morse('.....----')) def test_lfsr_sequence(): raises(TypeError, lambda: lfsr_sequence(1, [1], 1)) raises(TypeError, lambda: lfsr_sequence([1], 1, 1)) F = FF(2) assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)] assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)] F = FF(3) assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)] assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)] assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)] def test_lfsr_autocorrelation(): raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3)) F = FF(2) s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5) assert lfsr_autocorrelation(s, 2, 0) == 1 assert lfsr_autocorrelation(s, 2, 1) == -1 def test_lfsr_connection_polynomial(): F = FF(2) x = symbols("x") s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5) assert lfsr_connection_polynomial(s) == x**2 + 1 s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5) assert lfsr_connection_polynomial(s) == x**2 + x + 1 def test_elgamal_private_key(): a, b, _ = elgamal_private_key(digit=100) assert isprime(a) assert is_primitive_root(b, a) assert len(bin(a)) >= 102 def test_elgamal(): dk = elgamal_private_key(5) ek = elgamal_public_key(dk) P = ek[0] assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk) raises(ValueError, lambda: encipher_elgamal(P, dk)) raises(ValueError, lambda: encipher_elgamal(-1, dk)) def test_dh_private_key(): p, g, _ = dh_private_key(digit = 100) assert isprime(p) assert is_primitive_root(g, p) assert len(bin(p)) >= 102 def test_dh_public_key(): p1, g1, a = dh_private_key(digit = 100) p2, g2, ga = dh_public_key((p1, g1, a)) assert p1 == p2 assert g1 == g2 assert ga == pow(g1, a, p1) def test_dh_shared_key(): prk = dh_private_key(digit = 100) p, _, ga = dh_public_key(prk) b = randrange(2, p) sk = dh_shared_key((p, _, ga), b) assert sk == pow(ga, b, p) raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000)) def test_padded_key(): assert padded_key('b', 'ab') == 'ba' raises(ValueError, lambda: padded_key('ab', 'ace')) raises(ValueError, lambda: padded_key('ab', 'abba')) def test_bifid(): raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde')) assert encipher_bifid('abc', 'b', 'abcd') == 'bdb' raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde')) assert encipher_bifid('bdb', 'b', 'abcd') == 'abc' raises(ValueError, lambda: bifid_square('abcde')) assert bifid5_square("B") == \ bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ') assert bifid6_square('B0') == \ bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
10,326
32.748366
92
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/crypto/tests/__init__.py
0
0
0
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/gaussopt.py
from sympy.physics.optics.gaussopt import RayTransferMatrix, FreeSpace,\ FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens,\ GeometricRay, BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\ geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams from sympy.utilities.exceptions import SymPyDeprecationWarning SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt", useinstead="sympy.physics.optics.gaussopt", deprecated_since_version="0.7.6", issue=7659).warn()
556
45.416667
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/hydrogen.py
from __future__ import print_function, division from sympy import factorial, sqrt, exp, S, assoc_laguerre, Float def R_nl(n, l, r, Z=1): """ Returns the Hydrogen radial wavefunction R_{nl}. n, l quantum numbers 'n' and 'l' r radial coordinate Z atomic number (1 for Hydrogen, 2 for Helium, ...) Everything is in Hartree atomic units. Examples ======== >>> from sympy.physics.hydrogen import R_nl >>> from sympy import var >>> var("r Z") (r, Z) >>> R_nl(1, 0, r, Z) 2*sqrt(Z**3)*exp(-Z*r) >>> R_nl(2, 0, r, Z) sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4 >>> R_nl(2, 1, r, Z) sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12 For Hydrogen atom, you can just use the default value of Z=1: >>> R_nl(1, 0, r) 2*exp(-r) >>> R_nl(2, 0, r) sqrt(2)*(-r + 2)*exp(-r/2)/4 >>> R_nl(3, 0, r) 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27 For Silver atom, you would use Z=47: >>> R_nl(1, 0, r, Z=47) 94*sqrt(47)*exp(-47*r) >>> R_nl(2, 0, r, Z=47) 47*sqrt(94)*(-47*r + 2)*exp(-47*r/2)/4 >>> R_nl(3, 0, r, Z=47) 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27 The normalization of the radial wavefunction is: >>> from sympy import integrate, oo >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo)) 1 It holds for any atomic number: >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo)) 1 >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo)) 1 """ # sympify arguments n, l, r, Z = S(n), S(l), S(r), S(Z) # radial quantum number n_r = n - l - 1 # rescaled "r" a = 1/Z # Bohr radius r0 = 2 * r / (n * a) # normalization coefficient C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l))) # This is an equivalent normalization coefficient, that can be found in # some books. Both coefficients seem to be the same fast: # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l))) return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2) def E_nl(n, Z=1): """ Returns the energy of the state (n, l) in Hartree atomic units. The energy doesn't depend on "l". Examples ======== >>> from sympy import var >>> from sympy.physics.hydrogen import E_nl >>> var("n Z") (n, Z) >>> E_nl(n, Z) -Z**2/(2*n**2) >>> E_nl(1) -1/2 >>> E_nl(2) -1/8 >>> E_nl(3) -1/18 >>> E_nl(3, 47) -2209/18 """ n, Z = S(n), S(Z) if n.is_integer and (n < 1): raise ValueError("'n' must be positive integer") return -Z**2/(2*n**2) def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")): """ Returns the relativistic energy of the state (n, l, spin) in Hartree atomic units. The energy is calculated from the Dirac equation. The rest mass energy is *not* included. n, l quantum numbers 'n' and 'l' spin_up True if the electron spin is up (default), otherwise down Z atomic number (1 for Hydrogen, 2 for Helium, ...) c speed of light in atomic units. Default value is 137.035999037, taken from: http://arxiv.org/abs/1012.3627 Examples ======== >>> from sympy.physics.hydrogen import E_nl_dirac >>> E_nl_dirac(1, 0) -0.500006656595360 >>> E_nl_dirac(2, 0) -0.125002080189006 >>> E_nl_dirac(2, 1) -0.125000416028342 >>> E_nl_dirac(2, 1, False) -0.125002080189006 >>> E_nl_dirac(3, 0) -0.0555562951740285 >>> E_nl_dirac(3, 1) -0.0555558020932949 >>> E_nl_dirac(3, 1, False) -0.0555562951740285 >>> E_nl_dirac(3, 2) -0.0555556377366884 >>> E_nl_dirac(3, 2, False) -0.0555558020932949 """ if not (l >= 0): raise ValueError("'l' must be positive or zero") if not (n > l): raise ValueError("'n' must be greater than 'l'") if (l == 0 and spin_up is False): raise ValueError("Spin must be up for l==0.") # skappa is sign*kappa, where sign contains the correct sign if spin_up: skappa = -l - 1 else: skappa = -l c = S(c) beta = sqrt(skappa**2 - Z**2/c**2) return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
4,497
24.702857
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/wigner.py
r""" Wigner, Clebsch-Gordan, Racah, and Gaunt coefficients Collection of functions for calculating Wigner 3j, 6j, 9j, Clebsch-Gordan, Racah as well as Gaunt coefficients exactly, all evaluating to a rational number times the square root of a rational number [Rasch03]_. Please see the description of the individual functions for further details and examples. References ~~~~~~~~~~ .. [Rasch03] J. Rasch and A. C. H. Yu, 'Efficient Storage Scheme for Pre-calculated Wigner 3j, 6j and Gaunt Coefficients', SIAM J. Sci. Comput. Volume 25, Issue 4, pp. 1416-1428 (2003) Credits and Copyright ~~~~~~~~~~~~~~~~~~~~~ This code was taken from Sage with the permission of all authors: https://groups.google.com/forum/#!topic/sage-devel/M4NZdu-7O38 AUTHORS: - Jens Rasch (2009-03-24): initial version for Sage - Jens Rasch (2009-05-31): updated to sage-4.0 Copyright (C) 2008 Jens Rasch <[email protected]> """ from __future__ import print_function, division from sympy import (Integer, pi, sqrt, sympify, Dummy, S, Sum, Ynm, Function) from sympy.core.compatibility import range # This list of precomputed factorials is needed to massively # accelerate future calculations of the various coefficients _Factlist = [1] def _calc_factlist(nn): r""" Function calculates a list of precomputed factorials in order to massively accelerate future calculations of the various coefficients. INPUT: - ``nn`` - integer, highest factorial to be computed OUTPUT: list of integers -- the list of precomputed factorials EXAMPLES: Calculate list of factorials:: sage: from sage.functions.wigner import _calc_factlist sage: _calc_factlist(10) [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] """ if nn >= len(_Factlist): for ii in range(len(_Factlist), int(nn + 1)): _Factlist.append(_Factlist[ii - 1] * ii) return _Factlist[:int(nn) + 1] def wigner_3j(j_1, j_2, j_3, m_1, m_2, m_3): r""" Calculate the Wigner 3j symbol `\operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3)`. INPUT: - ``j_1``, ``j_2``, ``j_3``, ``m_1``, ``m_2``, ``m_3`` - integer or half integer OUTPUT: Rational number times the square root of a rational number. Examples ======== >>> from sympy.physics.wigner import wigner_3j >>> wigner_3j(2, 6, 4, 0, 0, 0) sqrt(715)/143 >>> wigner_3j(2, 6, 4, 0, 0, 1) 0 It is an error to have arguments that are not integer or half integer values:: sage: wigner_3j(2.1, 6, 4, 0, 0, 0) Traceback (most recent call last): ... ValueError: j values must be integer or half integer sage: wigner_3j(2, 6, 4, 1, 0, -1.1) Traceback (most recent call last): ... ValueError: m values must be integer or half integer NOTES: The Wigner 3j symbol obeys the following symmetry rules: - invariant under any permutation of the columns (with the exception of a sign change where `J:=j_1+j_2+j_3`): .. math:: \begin{aligned} \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3) &=\operatorname{Wigner3j}(j_3,j_1,j_2,m_3,m_1,m_2) \\ &=\operatorname{Wigner3j}(j_2,j_3,j_1,m_2,m_3,m_1) \\ &=(-1)^J \operatorname{Wigner3j}(j_3,j_2,j_1,m_3,m_2,m_1) \\ &=(-1)^J \operatorname{Wigner3j}(j_1,j_3,j_2,m_1,m_3,m_2) \\ &=(-1)^J \operatorname{Wigner3j}(j_2,j_1,j_3,m_2,m_1,m_3) \end{aligned} - invariant under space inflection, i.e. .. math:: \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,m_3) =(-1)^J \operatorname{Wigner3j}(j_1,j_2,j_3,-m_1,-m_2,-m_3) - symmetric with respect to the 72 additional symmetries based on the work by [Regge58]_ - zero for `j_1`, `j_2`, `j_3` not fulfilling triangle relation - zero for `m_1 + m_2 + m_3 \neq 0` - zero for violating any one of the conditions `j_1 \ge |m_1|`, `j_2 \ge |m_2|`, `j_3 \ge |m_3|` ALGORITHM: This function uses the algorithm of [Edmonds74]_ to calculate the value of the 3j symbol exactly. Note that the formula contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. REFERENCES: .. [Regge58] 'Symmetry Properties of Clebsch-Gordan Coefficients', T. Regge, Nuovo Cimento, Volume 10, pp. 544 (1958) .. [Edmonds74] 'Angular Momentum in Quantum Mechanics', A. R. Edmonds, Princeton University Press (1974) AUTHORS: - Jens Rasch (2009-03-24): initial version """ if int(j_1 * 2) != j_1 * 2 or int(j_2 * 2) != j_2 * 2 or \ int(j_3 * 2) != j_3 * 2: raise ValueError("j values must be integer or half integer") if int(m_1 * 2) != m_1 * 2 or int(m_2 * 2) != m_2 * 2 or \ int(m_3 * 2) != m_3 * 2: raise ValueError("m values must be integer or half integer") if m_1 + m_2 + m_3 != 0: return 0 prefid = Integer((-1) ** int(j_1 - j_2 - m_3)) m_3 = -m_3 a1 = j_1 + j_2 - j_3 if a1 < 0: return 0 a2 = j_1 - j_2 + j_3 if a2 < 0: return 0 a3 = -j_1 + j_2 + j_3 if a3 < 0: return 0 if (abs(m_1) > j_1) or (abs(m_2) > j_2) or (abs(m_3) > j_3): return 0 maxfact = max(j_1 + j_2 + j_3 + 1, j_1 + abs(m_1), j_2 + abs(m_2), j_3 + abs(m_3)) _calc_factlist(int(maxfact)) argsqrt = Integer(_Factlist[int(j_1 + j_2 - j_3)] * _Factlist[int(j_1 - j_2 + j_3)] * _Factlist[int(-j_1 + j_2 + j_3)] * _Factlist[int(j_1 - m_1)] * _Factlist[int(j_1 + m_1)] * _Factlist[int(j_2 - m_2)] * _Factlist[int(j_2 + m_2)] * _Factlist[int(j_3 - m_3)] * _Factlist[int(j_3 + m_3)]) / \ _Factlist[int(j_1 + j_2 + j_3 + 1)] ressqrt = sqrt(argsqrt) if ressqrt.is_complex: ressqrt = ressqrt.as_real_imag()[0] imin = max(-j_3 + j_1 + m_2, -j_3 + j_2 - m_1, 0) imax = min(j_2 + m_2, j_1 - m_1, j_1 + j_2 - j_3) sumres = 0 for ii in range(int(imin), int(imax) + 1): den = _Factlist[ii] * \ _Factlist[int(ii + j_3 - j_1 - m_2)] * \ _Factlist[int(j_2 + m_2 - ii)] * \ _Factlist[int(j_1 - ii - m_1)] * \ _Factlist[int(ii + j_3 - j_2 + m_1)] * \ _Factlist[int(j_1 + j_2 - j_3 - ii)] sumres = sumres + Integer((-1) ** ii) / den res = ressqrt * sumres * prefid return res def clebsch_gordan(j_1, j_2, j_3, m_1, m_2, m_3): r""" Calculates the Clebsch-Gordan coefficient `\langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \rangle`. The reference for this function is [Edmonds74]_. INPUT: - ``j_1``, ``j_2``, ``j_3``, ``m_1``, ``m_2``, ``m_3`` - integer or half integer OUTPUT: Rational number times the square root of a rational number. EXAMPLES:: >>> from sympy import S >>> from sympy.physics.wigner import clebsch_gordan >>> clebsch_gordan(S(3)/2, S(1)/2, 2, S(3)/2, S(1)/2, 2) 1 >>> clebsch_gordan(S(3)/2, S(1)/2, 1, S(3)/2, -S(1)/2, 1) sqrt(3)/2 >>> clebsch_gordan(S(3)/2, S(1)/2, 1, -S(1)/2, S(1)/2, 0) -sqrt(2)/2 NOTES: The Clebsch-Gordan coefficient will be evaluated via its relation to Wigner 3j symbols: .. math:: \langle j_1 m_1 \; j_2 m_2 | j_3 m_3 \rangle =(-1)^{j_1-j_2+m_3} \sqrt{2j_3+1} \operatorname{Wigner3j}(j_1,j_2,j_3,m_1,m_2,-m_3) See also the documentation on Wigner 3j symbols which exhibit much higher symmetry relations than the Clebsch-Gordan coefficient. AUTHORS: - Jens Rasch (2009-03-24): initial version """ res = (-1) ** sympify(j_1 - j_2 + m_3) * sqrt(2 * j_3 + 1) * \ wigner_3j(j_1, j_2, j_3, m_1, m_2, -m_3) return res def _big_delta_coeff(aa, bb, cc, prec=None): r""" Calculates the Delta coefficient of the 3 angular momenta for Racah symbols. Also checks that the differences are of integer value. INPUT: - ``aa`` - first angular momentum, integer or half integer - ``bb`` - second angular momentum, integer or half integer - ``cc`` - third angular momentum, integer or half integer - ``prec`` - precision of the ``sqrt()`` calculation OUTPUT: double - Value of the Delta coefficient EXAMPLES:: sage: from sage.functions.wigner import _big_delta_coeff sage: _big_delta_coeff(1,1,1) 1/2*sqrt(1/6) """ if int(aa + bb - cc) != (aa + bb - cc): raise ValueError("j values must be integer or half integer and fulfill the triangle relation") if int(aa + cc - bb) != (aa + cc - bb): raise ValueError("j values must be integer or half integer and fulfill the triangle relation") if int(bb + cc - aa) != (bb + cc - aa): raise ValueError("j values must be integer or half integer and fulfill the triangle relation") if (aa + bb - cc) < 0: return 0 if (aa + cc - bb) < 0: return 0 if (bb + cc - aa) < 0: return 0 maxfact = max(aa + bb - cc, aa + cc - bb, bb + cc - aa, aa + bb + cc + 1) _calc_factlist(maxfact) argsqrt = Integer(_Factlist[int(aa + bb - cc)] * _Factlist[int(aa + cc - bb)] * _Factlist[int(bb + cc - aa)]) / \ Integer(_Factlist[int(aa + bb + cc + 1)]) ressqrt = sqrt(argsqrt) if prec: ressqrt = ressqrt.evalf(prec).as_real_imag()[0] return ressqrt def racah(aa, bb, cc, dd, ee, ff, prec=None): r""" Calculate the Racah symbol `W(a,b,c,d;e,f)`. INPUT: - ``a``, ..., ``f`` - integer or half integer - ``prec`` - precision, default: ``None``. Providing a precision can drastically speed up the calculation. OUTPUT: Rational number times the square root of a rational number (if ``prec=None``), or real number if a precision is given. Examples ======== >>> from sympy.physics.wigner import racah >>> racah(3,3,3,3,3,3) -1/14 NOTES: The Racah symbol is related to the Wigner 6j symbol: .. math:: \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6) =(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6) Please see the 6j symbol for its much richer symmetries and for additional properties. ALGORITHM: This function uses the algorithm of [Edmonds74]_ to calculate the value of the 6j symbol exactly. Note that the formula contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. AUTHORS: - Jens Rasch (2009-03-24): initial version """ prefac = _big_delta_coeff(aa, bb, ee, prec) * \ _big_delta_coeff(cc, dd, ee, prec) * \ _big_delta_coeff(aa, cc, ff, prec) * \ _big_delta_coeff(bb, dd, ff, prec) if prefac == 0: return 0 imin = max(aa + bb + ee, cc + dd + ee, aa + cc + ff, bb + dd + ff) imax = min(aa + bb + cc + dd, aa + dd + ee + ff, bb + cc + ee + ff) maxfact = max(imax + 1, aa + bb + cc + dd, aa + dd + ee + ff, bb + cc + ee + ff) _calc_factlist(maxfact) sumres = 0 for kk in range(int(imin), int(imax) + 1): den = _Factlist[int(kk - aa - bb - ee)] * \ _Factlist[int(kk - cc - dd - ee)] * \ _Factlist[int(kk - aa - cc - ff)] * \ _Factlist[int(kk - bb - dd - ff)] * \ _Factlist[int(aa + bb + cc + dd - kk)] * \ _Factlist[int(aa + dd + ee + ff - kk)] * \ _Factlist[int(bb + cc + ee + ff - kk)] sumres = sumres + Integer((-1) ** kk * _Factlist[kk + 1]) / den res = prefac * sumres * (-1) ** int(aa + bb + cc + dd) return res def wigner_6j(j_1, j_2, j_3, j_4, j_5, j_6, prec=None): r""" Calculate the Wigner 6j symbol `\operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6)`. INPUT: - ``j_1``, ..., ``j_6`` - integer or half integer - ``prec`` - precision, default: ``None``. Providing a precision can drastically speed up the calculation. OUTPUT: Rational number times the square root of a rational number (if ``prec=None``), or real number if a precision is given. Examples ======== >>> from sympy.physics.wigner import wigner_6j >>> wigner_6j(3,3,3,3,3,3) -1/14 >>> wigner_6j(5,5,5,5,5,5) 1/52 It is an error to have arguments that are not integer or half integer values or do not fulfill the triangle relation:: sage: wigner_6j(2.5,2.5,2.5,2.5,2.5,2.5) Traceback (most recent call last): ... ValueError: j values must be integer or half integer and fulfill the triangle relation sage: wigner_6j(0.5,0.5,1.1,0.5,0.5,1.1) Traceback (most recent call last): ... ValueError: j values must be integer or half integer and fulfill the triangle relation NOTES: The Wigner 6j symbol is related to the Racah symbol but exhibits more symmetries as detailed below. .. math:: \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6) =(-1)^{j_1+j_2+j_4+j_5} W(j_1,j_2,j_5,j_4,j_3,j_6) The Wigner 6j symbol obeys the following symmetry rules: - Wigner 6j symbols are left invariant under any permutation of the columns: .. math:: \begin{aligned} \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6) &=\operatorname{Wigner6j}(j_3,j_1,j_2,j_6,j_4,j_5) \\ &=\operatorname{Wigner6j}(j_2,j_3,j_1,j_5,j_6,j_4) \\ &=\operatorname{Wigner6j}(j_3,j_2,j_1,j_6,j_5,j_4) \\ &=\operatorname{Wigner6j}(j_1,j_3,j_2,j_4,j_6,j_5) \\ &=\operatorname{Wigner6j}(j_2,j_1,j_3,j_5,j_4,j_6) \end{aligned} - They are invariant under the exchange of the upper and lower arguments in each of any two columns, i.e. .. math:: \operatorname{Wigner6j}(j_1,j_2,j_3,j_4,j_5,j_6) =\operatorname{Wigner6j}(j_1,j_5,j_6,j_4,j_2,j_3) =\operatorname{Wigner6j}(j_4,j_2,j_6,j_1,j_5,j_3) =\operatorname{Wigner6j}(j_4,j_5,j_3,j_1,j_2,j_6) - additional 6 symmetries [Regge59]_ giving rise to 144 symmetries in total - only non-zero if any triple of `j`'s fulfill a triangle relation ALGORITHM: This function uses the algorithm of [Edmonds74]_ to calculate the value of the 6j symbol exactly. Note that the formula contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. REFERENCES: .. [Regge59] 'Symmetry Properties of Racah Coefficients', T. Regge, Nuovo Cimento, Volume 11, pp. 116 (1959) """ res = (-1) ** int(j_1 + j_2 + j_4 + j_5) * \ racah(j_1, j_2, j_5, j_4, j_3, j_6, prec) return res def wigner_9j(j_1, j_2, j_3, j_4, j_5, j_6, j_7, j_8, j_9, prec=None): r""" Calculate the Wigner 9j symbol `\operatorname{Wigner9j}(j_1,j_2,j_3,j_4,j_5,j_6,j_7,j_8,j_9)`. INPUT: - ``j_1``, ..., ``j_9`` - integer or half integer - ``prec`` - precision, default: ``None``. Providing a precision can drastically speed up the calculation. OUTPUT: Rational number times the square root of a rational number (if ``prec=None``), or real number if a precision is given. Examples ======== >>> from sympy.physics.wigner import wigner_9j >>> wigner_9j(1,1,1, 1,1,1, 1,1,0 ,prec=64) # ==1/18 0.05555555... It is an error to have arguments that are not integer or half integer values or do not fulfill the triangle relation:: sage: wigner_9j(0.5,0.5,0.5, 0.5,0.5,0.5, 0.5,0.5,0.5,prec=64) Traceback (most recent call last): ... ValueError: j values must be integer or half integer and fulfill the triangle relation sage: wigner_9j(1,1,1, 0.5,1,1.5, 0.5,1,2.5,prec=64) Traceback (most recent call last): ... ValueError: j values must be integer or half integer and fulfill the triangle relation ALGORITHM: This function uses the algorithm of [Edmonds74]_ to calculate the value of the 3j symbol exactly. Note that the formula contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. """ imin = 0 imax = min(j_1 + j_9, j_2 + j_6, j_4 + j_8) sumres = 0 for kk in range(imin, int(imax) + 1): sumres = sumres + (2 * kk + 1) * \ racah(j_1, j_2, j_9, j_6, j_3, kk, prec) * \ racah(j_4, j_6, j_8, j_2, j_5, kk, prec) * \ racah(j_1, j_4, j_9, j_8, j_7, kk, prec) return sumres def gaunt(l_1, l_2, l_3, m_1, m_2, m_3, prec=None): r""" Calculate the Gaunt coefficient. The Gaunt coefficient is defined as the integral over three spherical harmonics: .. math:: \begin{aligned} \operatorname{Gaunt}(l_1,l_2,l_3,m_1,m_2,m_3) &=\int Y_{l_1,m_1}(\Omega) Y_{l_2,m_2}(\Omega) Y_{l_3,m_3}(\Omega) \,d\Omega \\ &=\sqrt{\frac{(2l_1+1)(2l_2+1)(2l_3+1)}{4\pi}} \operatorname{Wigner3j}(l_1,l_2,l_3,0,0,0) \operatorname{Wigner3j}(l_1,l_2,l_3,m_1,m_2,m_3) \end{aligned} INPUT: - ``l_1``, ``l_2``, ``l_3``, ``m_1``, ``m_2``, ``m_3`` - integer - ``prec`` - precision, default: ``None``. Providing a precision can drastically speed up the calculation. OUTPUT: Rational number times the square root of a rational number (if ``prec=None``), or real number if a precision is given. Examples ======== >>> from sympy.physics.wigner import gaunt >>> gaunt(1,0,1,1,0,-1) -1/(2*sqrt(pi)) >>> gaunt(1000,1000,1200,9,3,-12).n(64) 0.00689500421922113448... It is an error to use non-integer values for `l` and `m`:: sage: gaunt(1.2,0,1.2,0,0,0) Traceback (most recent call last): ... ValueError: l values must be integer sage: gaunt(1,0,1,1.1,0,-1.1) Traceback (most recent call last): ... ValueError: m values must be integer NOTES: The Gaunt coefficient obeys the following symmetry rules: - invariant under any permutation of the columns .. math:: \begin{aligned} Y(l_1,l_2,l_3,m_1,m_2,m_3) &=Y(l_3,l_1,l_2,m_3,m_1,m_2) \\ &=Y(l_2,l_3,l_1,m_2,m_3,m_1) \\ &=Y(l_3,l_2,l_1,m_3,m_2,m_1) \\ &=Y(l_1,l_3,l_2,m_1,m_3,m_2) \\ &=Y(l_2,l_1,l_3,m_2,m_1,m_3) \end{aligned} - invariant under space inflection, i.e. .. math:: Y(l_1,l_2,l_3,m_1,m_2,m_3) =Y(l_1,l_2,l_3,-m_1,-m_2,-m_3) - symmetric with respect to the 72 Regge symmetries as inherited for the `3j` symbols [Regge58]_ - zero for `l_1`, `l_2`, `l_3` not fulfilling triangle relation - zero for violating any one of the conditions: `l_1 \ge |m_1|`, `l_2 \ge |m_2|`, `l_3 \ge |m_3|` - non-zero only for an even sum of the `l_i`, i.e. `L = l_1 + l_2 + l_3 = 2n` for `n` in `\mathbb{N}` ALGORITHM: This function uses the algorithm of [Liberatodebrito82]_ to calculate the value of the Gaunt coefficient exactly. Note that the formula contains alternating sums over large factorials and is therefore unsuitable for finite precision arithmetic and only useful for a computer algebra system [Rasch03]_. REFERENCES: .. [Liberatodebrito82] 'FORTRAN program for the integral of three spherical harmonics', A. Liberato de Brito, Comput. Phys. Commun., Volume 25, pp. 81-85 (1982) AUTHORS: - Jens Rasch (2009-03-24): initial version for Sage """ if int(l_1) != l_1 or int(l_2) != l_2 or int(l_3) != l_3: raise ValueError("l values must be integer") if int(m_1) != m_1 or int(m_2) != m_2 or int(m_3) != m_3: raise ValueError("m values must be integer") sumL = l_1 + l_2 + l_3 bigL = sumL // 2 a1 = l_1 + l_2 - l_3 if a1 < 0: return 0 a2 = l_1 - l_2 + l_3 if a2 < 0: return 0 a3 = -l_1 + l_2 + l_3 if a3 < 0: return 0 if sumL % 2: return 0 if (m_1 + m_2 + m_3) != 0: return 0 if (abs(m_1) > l_1) or (abs(m_2) > l_2) or (abs(m_3) > l_3): return 0 imin = max(-l_3 + l_1 + m_2, -l_3 + l_2 - m_1, 0) imax = min(l_2 + m_2, l_1 - m_1, l_1 + l_2 - l_3) maxfact = max(l_1 + l_2 + l_3 + 1, imax + 1) _calc_factlist(maxfact) argsqrt = (2 * l_1 + 1) * (2 * l_2 + 1) * (2 * l_3 + 1) * \ _Factlist[l_1 - m_1] * _Factlist[l_1 + m_1] * _Factlist[l_2 - m_2] * \ _Factlist[l_2 + m_2] * _Factlist[l_3 - m_3] * _Factlist[l_3 + m_3] / \ (4*pi) ressqrt = sqrt(argsqrt) prefac = Integer(_Factlist[bigL] * _Factlist[l_2 - l_1 + l_3] * _Factlist[l_1 - l_2 + l_3] * _Factlist[l_1 + l_2 - l_3])/ \ _Factlist[2 * bigL + 1]/ \ (_Factlist[bigL - l_1] * _Factlist[bigL - l_2] * _Factlist[bigL - l_3]) sumres = 0 for ii in range(int(imin), int(imax) + 1): den = _Factlist[ii] * _Factlist[ii + l_3 - l_1 - m_2] * \ _Factlist[l_2 + m_2 - ii] * _Factlist[l_1 - ii - m_1] * \ _Factlist[ii + l_3 - l_2 + m_1] * _Factlist[l_1 + l_2 - l_3 - ii] sumres = sumres + Integer((-1) ** ii) / den res = ressqrt * prefac * sumres * (-1) ** (bigL + l_3 + m_1 - m_2) if prec is not None: res = res.n(prec) return res class Wigner3j(Function): def doit(self, **hints): if all(obj.is_number for obj in self.args): return wigner_3j(*self.args) else: return self def dot_rot_grad_Ynm(j, p, l, m, theta, phi): r""" Returns dot product of rotational gradients of spherical harmonics. This function returns the right hand side of the following expression: .. math :: \vec{R}Y{_j^{p}} \cdot \vec{R}Y{_l^{m}} = (-1)^{m+p} \sum\limits_{k=|l-j|}^{l+j}Y{_k^{m+p}} * \alpha_{l,m,j,p,k} * \frac{1}{2} (k^2-j^2-l^2+k-j-l) Arguments ========= j, p, l, m .... indices in spherical harmonics (expressions or integers) theta, phi .... angle arguments in spherical harmonics Example ======= >>> from sympy import symbols >>> from sympy.physics.wigner import dot_rot_grad_Ynm >>> theta, phi = symbols("theta phi") >>> dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() 3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi)) """ j = sympify(j) p = sympify(p) l = sympify(l) m = sympify(m) theta = sympify(theta) phi = sympify(phi) k = Dummy("k") def alpha(l,m,j,p,k): return sqrt((2*l+1)*(2*j+1)*(2*k+1)/(4*pi)) * \ Wigner3j(j, l, k, S(0), S(0), S(0)) * Wigner3j(j, l, k, p, m, -m-p) return (-S(1))**(m+p) * Sum(Ynm(k, m+p, theta, phi) * alpha(l,m,j,p,k) / 2 \ *(k**2-j**2-l**2+k-j-l), (k, abs(l-j), l+j))
23,391
30.023873
102
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/pring.py
from __future__ import print_function, division from sympy import sqrt, exp, S, pi, I from sympy.physics.quantum.constants import hbar def wavefunction(n, x): """ Returns the wavefunction for particle on ring. n is the quantum number, x is the angle, here n can be positive as well as negative which can be used to describe the direction of motion of particle Examples ======== >>> from sympy.physics.pring import wavefunction, energy >>> from sympy import Symbol, integrate, pi >>> x=Symbol("x") >>> wavefunction(1, x) sqrt(2)*exp(I*x)/(2*sqrt(pi)) >>> wavefunction(2, x) sqrt(2)*exp(2*I*x)/(2*sqrt(pi)) >>> wavefunction(3, x) sqrt(2)*exp(3*I*x)/(2*sqrt(pi)) The normalization of the wavefunction is: >>> integrate(wavefunction(2, x)*wavefunction(-2, x), (x, 0, 2*pi)) 1 >>> integrate(wavefunction(4, x)*wavefunction(-4, x), (x, 0, 2*pi)) 1 References ========== .. [1] Atkins, Peter W.; Friedman, Ronald (2005). Molecular Quantum Mechanics (4th ed.). Pages 71-73. """ # sympify arguments n, x = S(n), S(x) return exp(n * I * x) / sqrt(2 * pi) def energy(n, m, r): """ Returns the energy of the state corresponding to quantum number n. E=(n**2 * (hcross)**2) / (2 * m * r**2) here n is the quantum number, m is the mass of the particle and r is the radius of circle. Examples ======== >>> from sympy.physics.pring import energy >>> from sympy import Symbol >>> m=Symbol("m") >>> r=Symbol("r") >>> energy(1, m, r) hbar**2/(2*m*r**2) >>> energy(2, m, r) 2*hbar**2/(m*r**2) >>> energy(-2, 2.0, 3.0) 0.111111111111111*hbar**2 References ========== .. [1] Atkins, Peter W.; Friedman, Ronald (2005). Molecular Quantum Mechanics (4th ed.). Pages 71-73. """ n, m, r = S(n), S(m), S(r) if n.is_integer: return (n**2 * hbar**2) / (2 * m * r**2) else: raise ValueError("'n' must be integer")
2,048
24.6125
71
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/paulialgebra.py
""" This module implements Pauli algebra by subclassing Symbol. Only algebraic properties of Pauli matrices are used (we don't use the Matrix class). See the documentation to the class Pauli for examples. References ~~~~~~~~~~ .. [1] http://en.wikipedia.org/wiki/Pauli_matrices """ from __future__ import print_function, division from sympy import Symbol, I, Mul, Pow, Add from sympy.physics.quantum import TensorProduct __all__ = ['evaluate_pauli_product'] def delta(i, j): """ Returns 1 if i == j, else 0. This is used in the multiplication of Pauli matrices. Examples ======== >>> from sympy.physics.paulialgebra import delta >>> delta(1, 1) 1 >>> delta(2, 3) 0 """ if i == j: return 1 else: return 0 def epsilon(i, j, k): """ Return 1 if i,j,k is equal to (1,2,3), (2,3,1), or (3,1,2); -1 if i,j,k is equal to (1,3,2), (3,2,1), or (2,1,3); else return 0. This is used in the multiplication of Pauli matrices. Examples ======== >>> from sympy.physics.paulialgebra import epsilon >>> epsilon(1, 2, 3) 1 >>> epsilon(1, 3, 2) -1 """ if (i, j, k) in [(1, 2, 3), (2, 3, 1), (3, 1, 2)]: return 1 elif (i, j, k) in [(1, 3, 2), (3, 2, 1), (2, 1, 3)]: return -1 else: return 0 class Pauli(Symbol): """The class representing algebraic properties of Pauli matrices If the left multiplication of symbol or number with Pauli matrix is needed, please use parentheses to separate Pauli and symbolic multiplication (for example: 2*I*(Pauli(3)*Pauli(2))) Another variant is to use evaluate_pauli_product function to evaluate the product of Pauli matrices and other symbols (with commutative multiply rules) See Also ======= evaluate_pauli_product Examples ======== >>> from sympy.physics.paulialgebra import Pauli >>> Pauli(1) sigma1 >>> Pauli(1)*Pauli(2) I*sigma3 >>> Pauli(1)*Pauli(1) 1 >>> Pauli(3)**4 1 >>> Pauli(1)*Pauli(2)*Pauli(3) I >>> from sympy import I >>> I*(Pauli(2)*Pauli(3)) -sigma1 >>> from sympy.physics.paulialgebra import evaluate_pauli_product >>> f = I*Pauli(2)*Pauli(3) >>> f I*sigma2*sigma3 >>> evaluate_pauli_product(f) -sigma1 """ __slots__ = ["i"] def __new__(cls, i): if not i in [1, 2, 3]: raise IndexError("Invalid Pauli index") obj = Symbol.__new__(cls, "sigma%d" % i, commutative=False) obj.i = i return obj def __getnewargs__(self): return (self.i,) # FIXME don't work for -I*Pauli(2)*Pauli(3) def __mul__(self, other): if isinstance(other, Pauli): j = self.i k = other.i return delta(j, k) \ + I*epsilon(j, k, 1)*Pauli(1) \ + I*epsilon(j, k, 2)*Pauli(2) \ + I*epsilon(j, k, 3)*Pauli(3) return super(Pauli, self).__mul__(other) def _eval_power(b, e): if e.is_Integer and e.is_positive: return super(Pauli, b).__pow__(int(e) % 2) def evaluate_pauli_product(arg): '''Help function to evaluate Pauli matrices product with symbolic objects Parameters ========== arg: symbolic expression that contains Paulimatrices Examples ======== >>> from sympy.physics.paulialgebra import Pauli, evaluate_pauli_product >>> from sympy import I >>> evaluate_pauli_product(I*Pauli(1)*Pauli(2)) -sigma3 >>> from sympy.abc import x,y >>> evaluate_pauli_product(x**2*Pauli(2)*Pauli(1)) -I*x**2*sigma3 ''' start = arg end = arg if isinstance(arg, Pow) and isinstance(arg.args[0], Pauli): if arg.args[1].is_odd: return arg.args[0] else: return 1 if isinstance(arg, Add): return Add(*[evaluate_pauli_product(part) for part in arg.args]) if isinstance(arg, TensorProduct): return TensorProduct(*[evaluate_pauli_product(part) for part in arg.args]) elif not(isinstance(arg, Mul)): return arg while ((not(start == end)) | ((start == arg) & (end == arg))): start = end tmp = start.as_coeff_mul() sigma_product = 1 com_product = 1 keeper = 1 for el in tmp[1]: if isinstance(el, Pauli): sigma_product *= el elif not(el.is_commutative): if isinstance(el, Pow) and isinstance(el.args[0], Pauli): if el.args[1].is_odd: sigma_product *= el.args[0] elif isinstance(el, TensorProduct): keeper = keeper*sigma_product*\ TensorProduct( *[evaluate_pauli_product(part) for part in el.args] ) sigma_product = 1 else: keeper = keeper*sigma_product*el sigma_product = 1 else: com_product *= el end = (tmp[0]*keeper*sigma_product*com_product) if end == arg: break return end
5,211
24.42439
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/unitsystems.py
""" Deprecated: use ``sympy.physics.units`` """ # DEPRECATED: use `units` from sympy.utilities.exceptions import SymPyDeprecationWarning exec("from sympy.physics.units import *") SymPyDeprecationWarning( feature ="sympy.physics.unitsystems", useinstead ="sympy.physics.units", deprecated_since_version ="1.1", issue=12856, ).warn()
351
21
62
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/matrices.py
"""Known matrices related to physics""" from __future__ import print_function, division from sympy import Matrix, I, pi, sqrt from sympy.functions import exp from sympy.core.compatibility import range def msigma(i): r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3` References ========== .. [1] http://en.wikipedia.org/wiki/Pauli_matrices Examples ======== >>> from sympy.physics.matrices import msigma >>> msigma(1) Matrix([ [0, 1], [1, 0]]) """ if i == 1: mat = ( ( (0, 1), (1, 0) ) ) elif i == 2: mat = ( ( (0, -I), (I, 0) ) ) elif i == 3: mat = ( ( (1, 0), (0, -1) ) ) else: raise IndexError("Invalid Pauli index") return Matrix(mat) def pat_matrix(m, dx, dy, dz): """Returns the Parallel Axis Theorem matrix to translate the inertia matrix a distance of `(dx, dy, dz)` for a body of mass m. Examples ======== To translate a body having a mass of 2 units a distance of 1 unit along the `x`-axis we get: >>> from sympy.physics.matrices import pat_matrix >>> pat_matrix(2, 1, 0, 0) Matrix([ [0, 0, 0], [0, 2, 0], [0, 0, 2]]) """ dxdy = -dx*dy dydz = -dy*dz dzdx = -dz*dx dxdx = dx**2 dydy = dy**2 dzdz = dz**2 mat = ((dydy + dzdz, dxdy, dzdx), (dxdy, dxdx + dzdz, dydz), (dzdx, dydz, dydy + dxdx)) return m*Matrix(mat) def mgamma(mu, lower=False): r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard (Dirac) representation. If you want `\gamma_\mu`, use ``gamma(mu, True)``. We use a convention: `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3` `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5` References ========== .. [1] http://en.wikipedia.org/wiki/Gamma_matrices Examples ======== >>> from sympy.physics.matrices import mgamma >>> mgamma(1) Matrix([ [ 0, 0, 0, 1], [ 0, 0, 1, 0], [ 0, -1, 0, 0], [-1, 0, 0, 0]]) """ if not mu in [0, 1, 2, 3, 5]: raise IndexError("Invalid Dirac index") if mu == 0: mat = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1) ) elif mu == 1: mat = ( (0, 0, 0, 1), (0, 0, 1, 0), (0, -1, 0, 0), (-1, 0, 0, 0) ) elif mu == 2: mat = ( (0, 0, 0, -I), (0, 0, I, 0), (0, I, 0, 0), (-I, 0, 0, 0) ) elif mu == 3: mat = ( (0, 0, 1, 0), (0, 0, 0, -1), (-1, 0, 0, 0), (0, 1, 0, 0) ) elif mu == 5: mat = ( (0, 0, 1, 0), (0, 0, 0, 1), (1, 0, 0, 0), (0, 1, 0, 0) ) m = Matrix(mat) if lower: if mu in [1, 2, 3, 5]: m = -m return m #Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field #Theory minkowski_tensor = Matrix( ( (1, 0, 0, 0), (0, -1, 0, 0), (0, 0, -1, 0), (0, 0, 0, -1) )) def mdft(n): r""" Returns an expression of a discrete Fourier transform as a matrix multiplication. It is an n X n matrix. References ========== .. [1] https://en.wikipedia.org/wiki/DFT_matrix Examples ======== >>> from sympy.physics.matrices import mdft >>> mdft(3) Matrix([ [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3], [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(-4*I*pi/3)/3], [sqrt(3)/3, sqrt(3)*exp(-4*I*pi/3)/3, sqrt(3)*exp(-8*I*pi/3)/3]]) """ mat = [[None for x in range(n)] for y in range(n)] base = exp(-2*pi*I/n) mat[0] = [1]*n for i in range(n): mat[i][0] = 1 for i in range(1, n): for j in range(i, n): mat[i][j] = mat[j][i] = base**(i*j) return (1/sqrt(n))*Matrix(mat)
4,140
21.263441
91
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/sho.py
from __future__ import print_function, division from sympy.core import S, pi, Rational from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2 def R_nl(n, l, nu, r): """ Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic oscillator. ``n`` the "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. n >= 0 ``l`` the quantum number for orbital angular momentum ``nu`` mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass and `omega` the frequency of the oscillator. (in atomic units nu == omega/2) ``r`` Radial coordinate Examples ======== >>> from sympy.physics.sho import R_nl >>> from sympy import var >>> var("r nu l") (r, nu, l) >>> R_nl(0, 0, 1, r) 2*2**(3/4)*exp(-r**2)/pi**(1/4) >>> R_nl(1, 0, 1, r) 4*2**(1/4)*sqrt(3)*(-2*r**2 + 3/2)*exp(-r**2)/(3*pi**(1/4)) l, nu and r may be symbolic: >>> R_nl(0, 0, nu, r) 2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4) >>> R_nl(0, l, 1, r) r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4) The normalization of the radial wavefunction is: >>> from sympy import Integral, oo >>> Integral(R_nl(0, 0, 1, r)**2 * r**2, (r, 0, oo)).n() 1.00000000000000 >>> Integral(R_nl(1, 0, 1, r)**2 * r**2, (r, 0, oo)).n() 1.00000000000000 >>> Integral(R_nl(1, 1, 1, r)**2 * r**2, (r, 0, oo)).n() 1.00000000000000 """ n, l, nu, r = map(S, [n, l, nu, r]) # formula uses n >= 1 (instead of nodal n >= 0) n = n + 1 C = sqrt( ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/ (sqrt(pi)*(factorial2(2*n + 2*l - 1))) ) return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S(1)/2, 2*nu*r**2) def E_nl(n, l, hw): """ Returns the Energy of an isotropic harmonic oscillator ``n`` the "nodal" quantum number ``l`` the orbital angular momentum ``hw`` the harmonic oscillator parameter. The unit of the returned value matches the unit of hw, since the energy is calculated as: E_nl = (2*n + l + 3/2)*hw Examples ======== >>> from sympy.physics.sho import E_nl >>> from sympy import symbols >>> x, y, z = symbols('x, y, z') >>> E_nl(x, y, z) z*(2*x + y + 3/2) """ return (2*n + l + Rational(3, 2))*hw
2,482
26.285714
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/qho_1d.py
from __future__ import print_function, division from sympy.core import S, pi, Rational from sympy.functions import hermite, sqrt, exp, factorial, Abs from sympy.physics.quantum.constants import hbar def psi_n(n, x, m, omega): """ Returns the wavefunction psi_{n} for the One-dimensional harmonic oscillator. ``n`` the "nodal" quantum number. Corresponds to the number of nodes in the wavefunction. n >= 0 ``x`` x coordinate ``m`` mass of the particle ``omega`` angular frequency of the oscillator Examples ======== >>> from sympy.physics.qho_1d import psi_n >>> from sympy import var >>> var("x m omega") (x, m, omega) >>> psi_n(0, x, m, omega) (m*omega)**(1/4)*exp(-m*omega*x**2/(2*hbar))/(hbar**(1/4)*pi**(1/4)) """ # sympify arguments n, x, m, omega = map(S, [n, x, m, omega]) nu = m * omega / hbar # normalization coefficient C = (nu/pi)**(S(1)/4) * sqrt(1/(2**n*factorial(n))) return C * exp(-nu* x**2 /2) * hermite(n, sqrt(nu)*x) def E_n(n, omega): """ Returns the Energy of the One-dimensional harmonic oscillator ``n`` the "nodal" quantum number ``omega`` the harmonic oscillator angular frequency The unit of the returned value matches the unit of hw, since the energy is calculated as: E_n = hbar * omega*(n + 1/2) Examples ======== >>> from sympy.physics.qho_1d import E_n >>> from sympy import var >>> var("x omega") (x, omega) >>> E_n(x, omega) hbar*omega*(x + 1/2) """ return hbar * omega*(n + Rational(1, 2)) def coherent_state(n, alpha): """ Returns <n|alpha> for the coherent states of 1D harmonic oscillator. See http://en.wikipedia.org/wiki/Coherent_states ``n`` the "nodal" quantum number ``alpha`` the eigen value of annihilation operator """ return exp(- Abs(alpha)**2/2)*(alpha**n)/sqrt(factorial(n))
2,003
23.144578
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/__init__.py
""" A module that helps solving problems in physics """ from . import units from .matrices import mgamma, msigma, minkowski_tensor, mdft
138
18.857143
60
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/secondquant.py
""" Second quantization operators and states for bosons. This follow the formulation of Fetter and Welecka, "Quantum Theory of Many-Particle Systems." """ from __future__ import print_function, division from collections import defaultdict from sympy import (Add, Basic, cacheit, Dummy, Expr, Function, I, KroneckerDelta, Mul, Pow, S, sqrt, Symbol, sympify, Tuple, zeros) from sympy.printing.str import StrPrinter from sympy.core.compatibility import range from sympy.utilities.iterables import has_dups from sympy.utilities import default_sort_key __all__ = [ 'Dagger', 'KroneckerDelta', 'BosonicOperator', 'AnnihilateBoson', 'CreateBoson', 'AnnihilateFermion', 'CreateFermion', 'FockState', 'FockStateBra', 'FockStateKet', 'FockStateBosonKet', 'FockStateBosonBra', 'BBra', 'BKet', 'FBra', 'FKet', 'F', 'Fd', 'B', 'Bd', 'apply_operators', 'InnerProduct', 'BosonicBasis', 'VarBosonicBasis', 'FixedBosonicBasis', 'Commutator', 'matrix_rep', 'contraction', 'wicks', 'NO', 'evaluate_deltas', 'AntiSymmetricTensor', 'substitute_dummies', 'PermutationOperator', 'simplify_index_permutations', ] class SecondQuantizationError(Exception): pass class AppliesOnlyToSymbolicIndex(SecondQuantizationError): pass class ContractionAppliesOnlyToFermions(SecondQuantizationError): pass class ViolationOfPauliPrinciple(SecondQuantizationError): pass class SubstitutionOfAmbigousOperatorFailed(SecondQuantizationError): pass class WicksTheoremDoesNotApply(SecondQuantizationError): pass class Dagger(Expr): """ Hermitian conjugate of creation/annihilation operators. Examples ======== >>> from sympy import I >>> from sympy.physics.secondquant import Dagger, B, Bd >>> Dagger(2*I) -2*I >>> Dagger(B(0)) CreateBoson(0) >>> Dagger(Bd(0)) AnnihilateBoson(0) """ def __new__(cls, arg): arg = sympify(arg) r = cls.eval(arg) if isinstance(r, Basic): return r obj = Basic.__new__(cls, arg) return obj @classmethod def eval(cls, arg): """ Evaluates the Dagger instance. Examples ======== >>> from sympy import I >>> from sympy.physics.secondquant import Dagger, B, Bd >>> Dagger(2*I) -2*I >>> Dagger(B(0)) CreateBoson(0) >>> Dagger(Bd(0)) AnnihilateBoson(0) The eval() method is called automatically. """ try: d = arg._dagger_() except AttributeError: if isinstance(arg, Basic): if arg.is_Add: return Add(*tuple(map(Dagger, arg.args))) if arg.is_Mul: return Mul(*tuple(map(Dagger, reversed(arg.args)))) if arg.is_Number: return arg if arg.is_Pow: return Pow(Dagger(arg.args[0]), arg.args[1]) if arg == I: return -arg else: return None else: return d def _dagger_(self): return self.args[0] class TensorSymbol(Expr): is_commutative = True class AntiSymmetricTensor(TensorSymbol): """Stores upper and lower indices in separate Tuple's. Each group of indices is assumed to be antisymmetric. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import AntiSymmetricTensor >>> i, j = symbols('i j', below_fermi=True) >>> a, b = symbols('a b', above_fermi=True) >>> AntiSymmetricTensor('v', (a, i), (b, j)) AntiSymmetricTensor(v, (a, i), (b, j)) >>> AntiSymmetricTensor('v', (i, a), (b, j)) -AntiSymmetricTensor(v, (a, i), (b, j)) As you can see, the indices are automatically sorted to a canonical form. """ def __new__(cls, symbol, upper, lower): try: upper, signu = _sort_anticommuting_fermions( upper, key=cls._sortkey) lower, signl = _sort_anticommuting_fermions( lower, key=cls._sortkey) except ViolationOfPauliPrinciple: return S.Zero symbol = sympify(symbol) upper = Tuple(*upper) lower = Tuple(*lower) if (signu + signl) % 2: return -TensorSymbol.__new__(cls, symbol, upper, lower) else: return TensorSymbol.__new__(cls, symbol, upper, lower) @classmethod def _sortkey(cls, index): """Key for sorting of indices. particle < hole < general FIXME: This is a bottle-neck, can we do it faster? """ h = hash(index) if isinstance(index, Dummy): if index.assumptions0.get('above_fermi'): return (20, h) elif index.assumptions0.get('below_fermi'): return (21, h) else: return (22, h) if index.assumptions0.get('above_fermi'): return (10, h) elif index.assumptions0.get('below_fermi'): return (11, h) else: return (12, h) def _latex(self, printer): return "%s^{%s}_{%s}" % ( self.symbol, "".join([ i.name for i in self.args[1]]), "".join([ i.name for i in self.args[2]]) ) @property def symbol(self): """ Returns the symbol of the tensor. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import AntiSymmetricTensor >>> i, j = symbols('i,j', below_fermi=True) >>> a, b = symbols('a,b', above_fermi=True) >>> AntiSymmetricTensor('v', (a, i), (b, j)) AntiSymmetricTensor(v, (a, i), (b, j)) >>> AntiSymmetricTensor('v', (a, i), (b, j)).symbol v """ return self.args[0] @property def upper(self): """ Returns the upper indices. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import AntiSymmetricTensor >>> i, j = symbols('i,j', below_fermi=True) >>> a, b = symbols('a,b', above_fermi=True) >>> AntiSymmetricTensor('v', (a, i), (b, j)) AntiSymmetricTensor(v, (a, i), (b, j)) >>> AntiSymmetricTensor('v', (a, i), (b, j)).upper (a, i) """ return self.args[1] @property def lower(self): """ Returns the lower indices. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import AntiSymmetricTensor >>> i, j = symbols('i,j', below_fermi=True) >>> a, b = symbols('a,b', above_fermi=True) >>> AntiSymmetricTensor('v', (a, i), (b, j)) AntiSymmetricTensor(v, (a, i), (b, j)) >>> AntiSymmetricTensor('v', (a, i), (b, j)).lower (b, j) """ return self.args[2] def __str__(self): return "%s(%s,%s)" % self.args def doit(self, **kw_args): """ Returns self. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import AntiSymmetricTensor >>> i, j = symbols('i,j', below_fermi=True) >>> a, b = symbols('a,b', above_fermi=True) >>> AntiSymmetricTensor('v', (a, i), (b, j)).doit() AntiSymmetricTensor(v, (a, i), (b, j)) """ return self class SqOperator(Expr): """ Base class for Second Quantization operators. """ op_symbol = 'sq' is_commutative = False def __new__(cls, k): obj = Basic.__new__(cls, sympify(k)) return obj @property def state(self): """ Returns the state index related to this operator. >>> from sympy import Symbol >>> from sympy.physics.secondquant import F, Fd, B, Bd >>> p = Symbol('p') >>> F(p).state p >>> Fd(p).state p >>> B(p).state p >>> Bd(p).state p """ return self.args[0] @property def is_symbolic(self): """ Returns True if the state is a symbol (as opposed to a number). >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> p = Symbol('p') >>> F(p).is_symbolic True >>> F(1).is_symbolic False """ if self.state.is_Integer: return False else: return True def doit(self, **kw_args): """ FIXME: hack to prevent crash further up... """ return self def __repr__(self): return NotImplemented def __str__(self): return "%s(%r)" % (self.op_symbol, self.state) def apply_operator(self, state): """ Applies an operator to itself. """ raise NotImplementedError('implement apply_operator in a subclass') class BosonicOperator(SqOperator): pass class Annihilator(SqOperator): pass class Creator(SqOperator): pass class AnnihilateBoson(BosonicOperator, Annihilator): """ Bosonic annihilation operator. Examples ======== >>> from sympy.physics.secondquant import B >>> from sympy.abc import x >>> B(x) AnnihilateBoson(x) """ op_symbol = 'b' def _dagger_(self): return CreateBoson(self.state) def apply_operator(self, state): """ Apply state to self if self is not symbolic and state is a FockStateKet, else multiply self by state. Examples ======== >>> from sympy.physics.secondquant import B, BKet >>> from sympy.abc import x, y, n >>> B(x).apply_operator(y) y*AnnihilateBoson(x) >>> B(0).apply_operator(BKet((n,))) sqrt(n)*FockStateBosonKet((n - 1,)) """ if not self.is_symbolic and isinstance(state, FockStateKet): element = self.state amp = sqrt(state[element]) return amp*state.down(element) else: return Mul(self, state) def __repr__(self): return "AnnihilateBoson(%s)" % self.state class CreateBoson(BosonicOperator, Creator): """ Bosonic creation operator. """ op_symbol = 'b+' def _dagger_(self): return AnnihilateBoson(self.state) def apply_operator(self, state): """ Apply state to self if self is not symbolic and state is a FockStateKet, else multiply self by state. Examples ======== >>> from sympy.physics.secondquant import B, Dagger, BKet >>> from sympy.abc import x, y, n >>> Dagger(B(x)).apply_operator(y) y*CreateBoson(x) >>> B(0).apply_operator(BKet((n,))) sqrt(n)*FockStateBosonKet((n - 1,)) """ if not self.is_symbolic and isinstance(state, FockStateKet): element = self.state amp = sqrt(state[element] + 1) return amp*state.up(element) else: return Mul(self, state) def __repr__(self): return "CreateBoson(%s)" % self.state B = AnnihilateBoson Bd = CreateBoson class FermionicOperator(SqOperator): @property def is_restricted(self): """ Is this FermionicOperator restricted with respect to fermi level? Return values: 1 : restricted to orbits above fermi 0 : no restriction -1 : restricted to orbits below fermi >>> from sympy import Symbol >>> from sympy.physics.secondquant import F, Fd >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_restricted 1 >>> Fd(a).is_restricted 1 >>> F(i).is_restricted -1 >>> Fd(i).is_restricted -1 >>> F(p).is_restricted 0 >>> Fd(p).is_restricted 0 """ ass = self.args[0].assumptions0 if ass.get("below_fermi"): return -1 if ass.get("above_fermi"): return 1 return 0 @property def is_above_fermi(self): """ Does the index of this FermionicOperator allow values above fermi? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_above_fermi True >>> F(i).is_above_fermi False >>> F(p).is_above_fermi True The same applies to creation operators Fd """ return not self.args[0].assumptions0.get("below_fermi") @property def is_below_fermi(self): """ Does the index of this FermionicOperator allow values below fermi? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_below_fermi False >>> F(i).is_below_fermi True >>> F(p).is_below_fermi True The same applies to creation operators Fd """ return not self.args[0].assumptions0.get("above_fermi") @property def is_only_below_fermi(self): """ Is the index of this FermionicOperator restricted to values below fermi? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_only_below_fermi False >>> F(i).is_only_below_fermi True >>> F(p).is_only_below_fermi False The same applies to creation operators Fd """ return self.is_below_fermi and not self.is_above_fermi @property def is_only_above_fermi(self): """ Is the index of this FermionicOperator restricted to values above fermi? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_only_above_fermi True >>> F(i).is_only_above_fermi False >>> F(p).is_only_above_fermi False The same applies to creation operators Fd """ return self.is_above_fermi and not self.is_below_fermi def _sortkey(self): h = hash(self) label = str(self.args[0]) if self.is_only_q_creator: return 1, label, h if self.is_only_q_annihilator: return 4, label, h if isinstance(self, Annihilator): return 3, label, h if isinstance(self, Creator): return 2, label, h class AnnihilateFermion(FermionicOperator, Annihilator): """ Fermionic annihilation operator. """ op_symbol = 'f' def _dagger_(self): return CreateFermion(self.state) def apply_operator(self, state): """ Apply state to self if self is not symbolic and state is a FockStateKet, else multiply self by state. Examples ======== >>> from sympy.physics.secondquant import B, Dagger, BKet >>> from sympy.abc import x, y, n >>> Dagger(B(x)).apply_operator(y) y*CreateBoson(x) >>> B(0).apply_operator(BKet((n,))) sqrt(n)*FockStateBosonKet((n - 1,)) """ if isinstance(state, FockStateFermionKet): element = self.state return state.down(element) elif isinstance(state, Mul): c_part, nc_part = state.args_cnc() if isinstance(nc_part[0], FockStateFermionKet): element = self.state return Mul(*(c_part + [nc_part[0].down(element)] + nc_part[1:])) else: return Mul(self, state) else: return Mul(self, state) @property def is_q_creator(self): """ Can we create a quasi-particle? (create hole or create particle) If so, would that be above or below the fermi surface? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_q_creator 0 >>> F(i).is_q_creator -1 >>> F(p).is_q_creator -1 """ if self.is_below_fermi: return -1 return 0 @property def is_q_annihilator(self): """ Can we destroy a quasi-particle? (annihilate hole or annihilate particle) If so, would that be above or below the fermi surface? >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=1) >>> i = Symbol('i', below_fermi=1) >>> p = Symbol('p') >>> F(a).is_q_annihilator 1 >>> F(i).is_q_annihilator 0 >>> F(p).is_q_annihilator 1 """ if self.is_above_fermi: return 1 return 0 @property def is_only_q_creator(self): """ Always create a quasi-particle? (create hole or create particle) >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_only_q_creator False >>> F(i).is_only_q_creator True >>> F(p).is_only_q_creator False """ return self.is_only_below_fermi @property def is_only_q_annihilator(self): """ Always destroy a quasi-particle? (annihilate hole or annihilate particle) >>> from sympy import Symbol >>> from sympy.physics.secondquant import F >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> F(a).is_only_q_annihilator True >>> F(i).is_only_q_annihilator False >>> F(p).is_only_q_annihilator False """ return self.is_only_above_fermi def __repr__(self): return "AnnihilateFermion(%s)" % self.state def _latex(self, printer): return "a_{%s}" % self.state.name class CreateFermion(FermionicOperator, Creator): """ Fermionic creation operator. """ op_symbol = 'f+' def _dagger_(self): return AnnihilateFermion(self.state) def apply_operator(self, state): """ Apply state to self if self is not symbolic and state is a FockStateKet, else multiply self by state. Examples ======== >>> from sympy.physics.secondquant import B, Dagger, BKet >>> from sympy.abc import x, y, n >>> Dagger(B(x)).apply_operator(y) y*CreateBoson(x) >>> B(0).apply_operator(BKet((n,))) sqrt(n)*FockStateBosonKet((n - 1,)) """ if isinstance(state, FockStateFermionKet): element = self.state return state.up(element) elif isinstance(state, Mul): c_part, nc_part = state.args_cnc() if isinstance(nc_part[0], FockStateFermionKet): element = self.state return Mul(*(c_part + [nc_part[0].up(element)] + nc_part[1:])) return Mul(self, state) @property def is_q_creator(self): """ Can we create a quasi-particle? (create hole or create particle) If so, would that be above or below the fermi surface? >>> from sympy import Symbol >>> from sympy.physics.secondquant import Fd >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> Fd(a).is_q_creator 1 >>> Fd(i).is_q_creator 0 >>> Fd(p).is_q_creator 1 """ if self.is_above_fermi: return 1 return 0 @property def is_q_annihilator(self): """ Can we destroy a quasi-particle? (annihilate hole or annihilate particle) If so, would that be above or below the fermi surface? >>> from sympy import Symbol >>> from sympy.physics.secondquant import Fd >>> a = Symbol('a', above_fermi=1) >>> i = Symbol('i', below_fermi=1) >>> p = Symbol('p') >>> Fd(a).is_q_annihilator 0 >>> Fd(i).is_q_annihilator -1 >>> Fd(p).is_q_annihilator -1 """ if self.is_below_fermi: return -1 return 0 @property def is_only_q_creator(self): """ Always create a quasi-particle? (create hole or create particle) >>> from sympy import Symbol >>> from sympy.physics.secondquant import Fd >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> Fd(a).is_only_q_creator True >>> Fd(i).is_only_q_creator False >>> Fd(p).is_only_q_creator False """ return self.is_only_above_fermi @property def is_only_q_annihilator(self): """ Always destroy a quasi-particle? (annihilate hole or annihilate particle) >>> from sympy import Symbol >>> from sympy.physics.secondquant import Fd >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> Fd(a).is_only_q_annihilator False >>> Fd(i).is_only_q_annihilator True >>> Fd(p).is_only_q_annihilator False """ return self.is_only_below_fermi def __repr__(self): return "CreateFermion(%s)" % self.state def _latex(self, printer): return "a^\\dagger_{%s}" % self.state.name Fd = CreateFermion F = AnnihilateFermion class FockState(Expr): """ Many particle Fock state with a sequence of occupation numbers. Anywhere you can have a FockState, you can also have S.Zero. All code must check for this! Base class to represent FockStates. """ is_commutative = False def __new__(cls, occupations): """ occupations is a list with two possible meanings: - For bosons it is a list of occupation numbers. Element i is the number of particles in state i. - For fermions it is a list of occupied orbits. Element 0 is the state that was occupied first, element i is the i'th occupied state. """ occupations = list(map(sympify, occupations)) obj = Basic.__new__(cls, Tuple(*occupations)) return obj def __getitem__(self, i): i = int(i) return self.args[0][i] def __repr__(self): return ("FockState(%r)") % (self.args) def __str__(self): return "%s%r%s" % (self.lbracket, self._labels(), self.rbracket) def _labels(self): return self.args[0] def __len__(self): return len(self.args[0]) class BosonState(FockState): """ Base class for FockStateBoson(Ket/Bra). """ def up(self, i): """ Performs the action of a creation operator. Examples ======== >>> from sympy.physics.secondquant import BBra >>> b = BBra([1, 2]) >>> b FockStateBosonBra((1, 2)) >>> b.up(1) FockStateBosonBra((1, 3)) """ i = int(i) new_occs = list(self.args[0]) new_occs[i] = new_occs[i] + S.One return self.__class__(new_occs) def down(self, i): """ Performs the action of an annihilation operator. Examples ======== >>> from sympy.physics.secondquant import BBra >>> b = BBra([1, 2]) >>> b FockStateBosonBra((1, 2)) >>> b.down(1) FockStateBosonBra((1, 1)) """ i = int(i) new_occs = list(self.args[0]) if new_occs[i] == S.Zero: return S.Zero else: new_occs[i] = new_occs[i] - S.One return self.__class__(new_occs) class FermionState(FockState): """ Base class for FockStateFermion(Ket/Bra). """ fermi_level = 0 def __new__(cls, occupations, fermi_level=0): occupations = list(map(sympify, occupations)) if len(occupations) > 1: try: (occupations, sign) = _sort_anticommuting_fermions( occupations, key=hash) except ViolationOfPauliPrinciple: return S.Zero else: sign = 0 cls.fermi_level = fermi_level if cls._count_holes(occupations) > fermi_level: return S.Zero if sign % 2: return S.NegativeOne*FockState.__new__(cls, occupations) else: return FockState.__new__(cls, occupations) def up(self, i): """ Performs the action of a creation operator. If below fermi we try to remove a hole, if above fermi we try to create a particle. if general index p we return Kronecker(p,i)*self where i is a new symbol with restriction above or below. >>> from sympy import Symbol >>> from sympy.physics.secondquant import FKet >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') >>> FKet([]).up(a) FockStateFermionKet((a,)) A creator acting on vacuum below fermi vanishes >>> FKet([]).up(i) 0 """ present = i in self.args[0] if self._only_above_fermi(i): if present: return S.Zero else: return self._add_orbit(i) elif self._only_below_fermi(i): if present: return self._remove_orbit(i) else: return S.Zero else: if present: hole = Dummy("i", below_fermi=True) return KroneckerDelta(i, hole)*self._remove_orbit(i) else: particle = Dummy("a", above_fermi=True) return KroneckerDelta(i, particle)*self._add_orbit(i) def down(self, i): """ Performs the action of an annihilation operator. If below fermi we try to create a hole, if above fermi we try to remove a particle. if general index p we return Kronecker(p,i)*self where i is a new symbol with restriction above or below. >>> from sympy import Symbol >>> from sympy.physics.secondquant import FKet >>> a = Symbol('a', above_fermi=True) >>> i = Symbol('i', below_fermi=True) >>> p = Symbol('p') An annihilator acting on vacuum above fermi vanishes >>> FKet([]).down(a) 0 Also below fermi, it vanishes, unless we specify a fermi level > 0 >>> FKet([]).down(i) 0 >>> FKet([],4).down(i) FockStateFermionKet((i,)) """ present = i in self.args[0] if self._only_above_fermi(i): if present: return self._remove_orbit(i) else: return S.Zero elif self._only_below_fermi(i): if present: return S.Zero else: return self._add_orbit(i) else: if present: hole = Dummy("i", below_fermi=True) return KroneckerDelta(i, hole)*self._add_orbit(i) else: particle = Dummy("a", above_fermi=True) return KroneckerDelta(i, particle)*self._remove_orbit(i) @classmethod def _only_below_fermi(cls, i): """ Tests if given orbit is only below fermi surface. If nothing can be concluded we return a conservative False. """ if i.is_number: return i <= cls.fermi_level if i.assumptions0.get('below_fermi'): return True return False @classmethod def _only_above_fermi(cls, i): """ Tests if given orbit is only above fermi surface. If fermi level has not been set we return True. If nothing can be concluded we return a conservative False. """ if i.is_number: return i > cls.fermi_level if i.assumptions0.get('above_fermi'): return True return not cls.fermi_level def _remove_orbit(self, i): """ Removes particle/fills hole in orbit i. No input tests performed here. """ new_occs = list(self.args[0]) pos = new_occs.index(i) del new_occs[pos] if (pos) % 2: return S.NegativeOne*self.__class__(new_occs, self.fermi_level) else: return self.__class__(new_occs, self.fermi_level) def _add_orbit(self, i): """ Adds particle/creates hole in orbit i. No input tests performed here. """ return self.__class__((i,) + self.args[0], self.fermi_level) @classmethod def _count_holes(cls, list): """ returns number of identified hole states in list. """ return len([i for i in list if cls._only_below_fermi(i)]) def _negate_holes(self, list): return tuple([-i if i <= self.fermi_level else i for i in list]) def __repr__(self): if self.fermi_level: return "FockStateKet(%r, fermi_level=%s)" % (self.args[0], self.fermi_level) else: return "FockStateKet(%r)" % (self.args[0],) def _labels(self): return self._negate_holes(self.args[0]) class FockStateKet(FockState): """ Representation of a ket. """ lbracket = '|' rbracket = '>' class FockStateBra(FockState): """ Representation of a bra. """ lbracket = '<' rbracket = '|' def __mul__(self, other): if isinstance(other, FockStateKet): return InnerProduct(self, other) else: return Expr.__mul__(self, other) class FockStateBosonKet(BosonState, FockStateKet): """ Many particle Fock state with a sequence of occupation numbers. Occupation numbers can be any integer >= 0. Examples ======== >>> from sympy.physics.secondquant import BKet >>> BKet([1, 2]) FockStateBosonKet((1, 2)) """ def _dagger_(self): return FockStateBosonBra(*self.args) class FockStateBosonBra(BosonState, FockStateBra): """ Describes a collection of BosonBra particles. Examples ======== >>> from sympy.physics.secondquant import BBra >>> BBra([1, 2]) FockStateBosonBra((1, 2)) """ def _dagger_(self): return FockStateBosonKet(*self.args) class FockStateFermionKet(FermionState, FockStateKet): """ Many-particle Fock state with a sequence of occupied orbits. Each state can only have one particle, so we choose to store a list of occupied orbits rather than a tuple with occupation numbers (zeros and ones). states below fermi level are holes, and are represented by negative labels in the occupation list. For symbolic state labels, the fermi_level caps the number of allowed hole- states. Examples ======== >>> from sympy.physics.secondquant import FKet >>> FKet([1, 2]) #doctest: +SKIP FockStateFermionKet((1, 2)) """ def _dagger_(self): return FockStateFermionBra(*self.args) class FockStateFermionBra(FermionState, FockStateBra): """ See Also ======== FockStateFermionKet Examples ======== >>> from sympy.physics.secondquant import FBra >>> FBra([1, 2]) #doctest: +SKIP FockStateFermionBra((1, 2)) """ def _dagger_(self): return FockStateFermionKet(*self.args) BBra = FockStateBosonBra BKet = FockStateBosonKet FBra = FockStateFermionBra FKet = FockStateFermionKet def _apply_Mul(m): """ Take a Mul instance with operators and apply them to states. This method applies all operators with integer state labels to the actual states. For symbolic state labels, nothing is done. When inner products of FockStates are encountered (like <a|b>), they are converted to instances of InnerProduct. This does not currently work on double inner products like, <a|b><c|d>. If the argument is not a Mul, it is simply returned as is. """ if not isinstance(m, Mul): return m c_part, nc_part = m.args_cnc() n_nc = len(nc_part) if n_nc == 0 or n_nc == 1: return m else: last = nc_part[-1] next_to_last = nc_part[-2] if isinstance(last, FockStateKet): if isinstance(next_to_last, SqOperator): if next_to_last.is_symbolic: return m else: result = next_to_last.apply_operator(last) if result == 0: return S.Zero else: return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result]))) elif isinstance(next_to_last, Pow): if isinstance(next_to_last.base, SqOperator) and \ next_to_last.exp.is_Integer: if next_to_last.base.is_symbolic: return m else: result = last for i in range(next_to_last.exp): result = next_to_last.base.apply_operator(result) if result == 0: break if result == 0: return S.Zero else: return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result]))) else: return m elif isinstance(next_to_last, FockStateBra): result = InnerProduct(next_to_last, last) if result == 0: return S.Zero else: return _apply_Mul(Mul(*(c_part + nc_part[:-2] + [result]))) else: return m else: return m def apply_operators(e): """ Take a sympy expression with operators and states and apply the operators. Examples ======== >>> from sympy.physics.secondquant import apply_operators >>> from sympy import sympify >>> apply_operators(sympify(3)+4) 7 """ e = e.expand() muls = e.atoms(Mul) subs_list = [(m, _apply_Mul(m)) for m in iter(muls)] return e.subs(subs_list) class InnerProduct(Basic): """ An unevaluated inner product between a bra and ket. Currently this class just reduces things to a product of Kronecker Deltas. In the future, we could introduce abstract states like ``|a>`` and ``|b>``, and leave the inner product unevaluated as ``<a|b>``. """ is_commutative = True def __new__(cls, bra, ket): if not isinstance(bra, FockStateBra): raise TypeError("must be a bra") if not isinstance(ket, FockStateKet): raise TypeError("must be a key") return cls.eval(bra, ket) @classmethod def eval(cls, bra, ket): result = S.One for i, j in zip(bra.args[0], ket.args[0]): result *= KroneckerDelta(i, j) if result == 0: break return result @property def bra(self): """Returns the bra part of the state""" return self.args[0] @property def ket(self): """Returns the ket part of the state""" return self.args[1] def __repr__(self): sbra = repr(self.bra) sket = repr(self.ket) return "%s|%s" % (sbra[:-1], sket[1:]) def __str__(self): return self.__repr__() def matrix_rep(op, basis): """ Find the representation of an operator in a basis. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis, B, matrix_rep >>> b = VarBosonicBasis(5) >>> o = B(0) >>> matrix_rep(o, b) Matrix([ [0, 1, 0, 0, 0], [0, 0, sqrt(2), 0, 0], [0, 0, 0, sqrt(3), 0], [0, 0, 0, 0, 2], [0, 0, 0, 0, 0]]) """ a = zeros(len(basis)) for i in range(len(basis)): for j in range(len(basis)): a[i, j] = apply_operators(Dagger(basis[i])*op*basis[j]) return a class BosonicBasis(object): """ Base class for a basis set of bosonic Fock states. """ pass class VarBosonicBasis(object): """ A single state, variable particle number basis set. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(5) >>> b [FockState((0,)), FockState((1,)), FockState((2,)), FockState((3,)), FockState((4,))] """ def __init__(self, n_max): self.n_max = n_max self._build_states() def _build_states(self): self.basis = [] for i in range(self.n_max): self.basis.append(FockStateBosonKet([i])) self.n_basis = len(self.basis) def index(self, state): """ Returns the index of state in basis. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(3) >>> state = b.state(1) >>> b [FockState((0,)), FockState((1,)), FockState((2,))] >>> state FockStateBosonKet((1,)) >>> b.index(state) 1 """ return self.basis.index(state) def state(self, i): """ The state of a single basis. Examples ======== >>> from sympy.physics.secondquant import VarBosonicBasis >>> b = VarBosonicBasis(5) >>> b.state(3) FockStateBosonKet((3,)) """ return self.basis[i] def __getitem__(self, i): return self.state(i) def __len__(self): return len(self.basis) def __repr__(self): return repr(self.basis) class FixedBosonicBasis(BosonicBasis): """ Fixed particle number basis set. Examples ======== >>> from sympy.physics.secondquant import FixedBosonicBasis >>> b = FixedBosonicBasis(2, 2) >>> state = b.state(1) >>> b [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))] >>> state FockStateBosonKet((1, 1)) >>> b.index(state) 1 """ def __init__(self, n_particles, n_levels): self.n_particles = n_particles self.n_levels = n_levels self._build_particle_locations() self._build_states() def _build_particle_locations(self): tup = ["i%i" % i for i in range(self.n_particles)] first_loop = "for i0 in range(%i)" % self.n_levels other_loops = '' for cur, prev in zip(tup[1:], tup): temp = "for %s in range(%s + 1) " % (cur, prev) other_loops = other_loops + temp tup_string = "(%s)" % ", ".join(tup) list_comp = "[%s %s %s]" % (tup_string, first_loop, other_loops) result = eval(list_comp) if self.n_particles == 1: result = [(item,) for item in result] self.particle_locations = result def _build_states(self): self.basis = [] for tuple_of_indices in self.particle_locations: occ_numbers = self.n_levels*[0] for level in tuple_of_indices: occ_numbers[level] += 1 self.basis.append(FockStateBosonKet(occ_numbers)) self.n_basis = len(self.basis) def index(self, state): """Returns the index of state in basis. Examples ======== >>> from sympy.physics.secondquant import FixedBosonicBasis >>> b = FixedBosonicBasis(2, 3) >>> b.index(b.state(3)) 3 """ return self.basis.index(state) def state(self, i): """Returns the state that lies at index i of the basis Examples ======== >>> from sympy.physics.secondquant import FixedBosonicBasis >>> b = FixedBosonicBasis(2, 3) >>> b.state(3) FockStateBosonKet((1, 0, 1)) """ return self.basis[i] def __getitem__(self, i): return self.state(i) def __len__(self): return len(self.basis) def __repr__(self): return repr(self.basis) class Commutator(Function): """ The Commutator: [A, B] = A*B - B*A The arguments are ordered according to .__cmp__() >>> from sympy import symbols >>> from sympy.physics.secondquant import Commutator >>> A, B = symbols('A,B', commutative=False) >>> Commutator(B, A) -Commutator(A, B) Evaluate the commutator with .doit() >>> comm = Commutator(A,B); comm Commutator(A, B) >>> comm.doit() A*B - B*A For two second quantization operators the commutator is evaluated immediately: >>> from sympy.physics.secondquant import Fd, F >>> a = symbols('a', above_fermi=True) >>> i = symbols('i', below_fermi=True) >>> p,q = symbols('p,q') >>> Commutator(Fd(a),Fd(i)) 2*NO(CreateFermion(a)*CreateFermion(i)) But for more complicated expressions, the evaluation is triggered by a call to .doit() >>> comm = Commutator(Fd(p)*Fd(q),F(i)); comm Commutator(CreateFermion(p)*CreateFermion(q), AnnihilateFermion(i)) >>> comm.doit(wicks=True) -KroneckerDelta(i, p)*CreateFermion(q) + KroneckerDelta(i, q)*CreateFermion(p) """ is_commutative = False @classmethod def eval(cls, a, b): """ The Commutator [A,B] is on canonical form if A < B. Examples ======== >>> from sympy.physics.secondquant import Commutator, F, Fd >>> from sympy.abc import x >>> c1 = Commutator(F(x), Fd(x)) >>> c2 = Commutator(Fd(x), F(x)) >>> Commutator.eval(c1, c2) 0 """ if not (a and b): return S.Zero if a == b: return S.Zero if a.is_commutative or b.is_commutative: return S.Zero # # [A+B,C] -> [A,C] + [B,C] # a = a.expand() if isinstance(a, Add): return Add(*[cls(term, b) for term in a.args]) b = b.expand() if isinstance(b, Add): return Add(*[cls(a, term) for term in b.args]) # # [xA,yB] -> xy*[A,B] # ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = list(ca) + list(cb) if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # # single second quantization operators # if isinstance(a, BosonicOperator) and isinstance(b, BosonicOperator): if isinstance(b, CreateBoson) and isinstance(a, AnnihilateBoson): return KroneckerDelta(a.state, b.state) if isinstance(a, CreateBoson) and isinstance(b, AnnihilateBoson): return S.NegativeOne*KroneckerDelta(a.state, b.state) else: return S.Zero if isinstance(a, FermionicOperator) and isinstance(b, FermionicOperator): return wicks(a*b) - wicks(b*a) # # Canonical ordering of arguments # if a.sort_key() > b.sort_key(): return S.NegativeOne*cls(b, a) def doit(self, **hints): """ Enables the computation of complex expressions. Examples ======== >>> from sympy.physics.secondquant import Commutator, F, Fd >>> from sympy import symbols >>> i, j = symbols('i,j', below_fermi=True) >>> a, b = symbols('a,b', above_fermi=True) >>> c = Commutator(Fd(a)*F(i),Fd(b)*F(j)) >>> c.doit(wicks=True) 0 """ a = self.args[0] b = self.args[1] if hints.get("wicks"): a = a.doit(**hints) b = b.doit(**hints) try: return wicks(a*b) - wicks(b*a) except ContractionAppliesOnlyToFermions: pass except WicksTheoremDoesNotApply: pass return (a*b - b*a).doit(**hints) def __repr__(self): return "Commutator(%s,%s)" % (self.args[0], self.args[1]) def __str__(self): return "[%s,%s]" % (self.args[0], self.args[1]) def _latex(self, printer): return "\\left[%s,%s\\right]" % tuple([ printer._print(arg) for arg in self.args]) class NO(Expr): """ This Object is used to represent normal ordering brackets. i.e. {abcd} sometimes written :abcd: Applying the function NO(arg) to an argument means that all operators in the argument will be assumed to anticommute, and have vanishing contractions. This allows an immediate reordering to canonical form upon object creation. >>> from sympy import symbols >>> from sympy.physics.secondquant import NO, F, Fd >>> p,q = symbols('p,q') >>> NO(Fd(p)*F(q)) NO(CreateFermion(p)*AnnihilateFermion(q)) >>> NO(F(q)*Fd(p)) -NO(CreateFermion(p)*AnnihilateFermion(q)) Note: If you want to generate a normal ordered equivalent of an expression, you should use the function wicks(). This class only indicates that all operators inside the brackets anticommute, and have vanishing contractions. Nothing more, nothing less. """ is_commutative = False def __new__(cls, arg): """ Use anticommutation to get canonical form of operators. Employ associativity of normal ordered product: {ab{cd}} = {abcd} but note that {ab}{cd} /= {abcd}. We also employ distributivity: {ab + cd} = {ab} + {cd}. Canonical form also implies expand() {ab(c+d)} = {abc} + {abd}. """ # {ab + cd} = {ab} + {cd} arg = sympify(arg) arg = arg.expand() if arg.is_Add: return Add(*[ cls(term) for term in arg.args]) if arg.is_Mul: # take coefficient outside of normal ordering brackets c_part, seq = arg.args_cnc() if c_part: coeff = Mul(*c_part) if not seq: return coeff else: coeff = S.One # {ab{cd}} = {abcd} newseq = [] foundit = False for fac in seq: if isinstance(fac, NO): newseq.extend(fac.args) foundit = True else: newseq.append(fac) if foundit: return coeff*cls(Mul(*newseq)) # We assume that the user don't mix B and F operators if isinstance(seq[0], BosonicOperator): raise NotImplementedError try: newseq, sign = _sort_anticommuting_fermions(seq) except ViolationOfPauliPrinciple: return S.Zero if sign % 2: return (S.NegativeOne*coeff)*cls(Mul(*newseq)) elif sign: return coeff*cls(Mul(*newseq)) else: pass # since sign==0, no permutations was necessary # if we couldn't do anything with Mul object, we just # mark it as normal ordered if coeff != S.One: return coeff*cls(Mul(*newseq)) return Expr.__new__(cls, Mul(*newseq)) if isinstance(arg, NO): return arg # if object was not Mul or Add, normal ordering does not apply return arg @property def has_q_creators(self): """ Return 0 if the leftmost argument of the first argument is a not a q_creator, else 1 if it is above fermi or -1 if it is below fermi. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import NO, F, Fd >>> a = symbols('a', above_fermi=True) >>> i = symbols('i', below_fermi=True) >>> NO(Fd(a)*Fd(i)).has_q_creators 1 >>> NO(F(i)*F(a)).has_q_creators -1 >>> NO(Fd(i)*F(a)).has_q_creators #doctest: +SKIP 0 """ return self.args[0].args[0].is_q_creator @property def has_q_annihilators(self): """ Return 0 if the rightmost argument of the first argument is a not a q_annihilator, else 1 if it is above fermi or -1 if it is below fermi. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import NO, F, Fd >>> a = symbols('a', above_fermi=True) >>> i = symbols('i', below_fermi=True) >>> NO(Fd(a)*Fd(i)).has_q_annihilators -1 >>> NO(F(i)*F(a)).has_q_annihilators 1 >>> NO(Fd(a)*F(i)).has_q_annihilators 0 """ return self.args[0].args[-1].is_q_annihilator def doit(self, **kw_args): """ Either removes the brackets or enables complex computations in its arguments. Examples ======== >>> from sympy.physics.secondquant import NO, Fd, F >>> from textwrap import fill >>> from sympy import symbols, Dummy >>> p,q = symbols('p,q', cls=Dummy) >>> print(fill(str(NO(Fd(p)*F(q)).doit()))) KroneckerDelta(_a, _p)*KroneckerDelta(_a, _q)*CreateFermion(_a)*AnnihilateFermion(_a) + KroneckerDelta(_a, _p)*KroneckerDelta(_i, _q)*CreateFermion(_a)*AnnihilateFermion(_i) - KroneckerDelta(_a, _q)*KroneckerDelta(_i, _p)*AnnihilateFermion(_a)*CreateFermion(_i) - KroneckerDelta(_i, _p)*KroneckerDelta(_i, _q)*AnnihilateFermion(_i)*CreateFermion(_i) """ if kw_args.get("remove_brackets", True): return self._remove_brackets() else: return self.__new__(type(self), self.args[0].doit(**kw_args)) def _remove_brackets(self): """ Returns the sorted string without normal order brackets. The returned string have the property that no nonzero contractions exist. """ # check if any creator is also an annihilator subslist = [] for i in self.iter_q_creators(): if self[i].is_q_annihilator: assume = self[i].state.assumptions0 # only operators with a dummy index can be split in two terms if isinstance(self[i].state, Dummy): # create indices with fermi restriction assume.pop("above_fermi", None) assume["below_fermi"] = True below = Dummy('i', **assume) assume.pop("below_fermi", None) assume["above_fermi"] = True above = Dummy('a', **assume) cls = type(self[i]) split = ( self[i].__new__(cls, below) * KroneckerDelta(below, self[i].state) + self[i].__new__(cls, above) * KroneckerDelta(above, self[i].state) ) subslist.append((self[i], split)) else: raise SubstitutionOfAmbigousOperatorFailed(self[i]) if subslist: result = NO(self.subs(subslist)) if isinstance(result, Add): return Add(*[term.doit() for term in result.args]) else: return self.args[0] def _expand_operators(self): """ Returns a sum of NO objects that contain no ambiguous q-operators. If an index q has range both above and below fermi, the operator F(q) is ambiguous in the sense that it can be both a q-creator and a q-annihilator. If q is dummy, it is assumed to be a summation variable and this method rewrites it into a sum of NO terms with unambiguous operators: {Fd(p)*F(q)} = {Fd(a)*F(b)} + {Fd(a)*F(i)} + {Fd(j)*F(b)} -{F(i)*Fd(j)} where a,b are above and i,j are below fermi level. """ return NO(self._remove_brackets) def __getitem__(self, i): if isinstance(i, slice): indices = i.indices(len(self)) return [self.args[0].args[i] for i in range(*indices)] else: return self.args[0].args[i] def __len__(self): return len(self.args[0].args) def iter_q_annihilators(self): """ Iterates over the annihilation operators. Examples ======== >>> from sympy import symbols >>> i, j = symbols('i j', below_fermi=True) >>> a, b = symbols('a b', above_fermi=True) >>> from sympy.physics.secondquant import NO, F, Fd >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j)) >>> no.iter_q_creators() <generator object... at 0x...> >>> list(no.iter_q_creators()) [0, 1] >>> list(no.iter_q_annihilators()) [3, 2] """ ops = self.args[0].args iter = range(len(ops) - 1, -1, -1) for i in iter: if ops[i].is_q_annihilator: yield i else: break def iter_q_creators(self): """ Iterates over the creation operators. Examples ======== >>> from sympy import symbols >>> i, j = symbols('i j', below_fermi=True) >>> a, b = symbols('a b', above_fermi=True) >>> from sympy.physics.secondquant import NO, F, Fd >>> no = NO(Fd(a)*F(i)*F(b)*Fd(j)) >>> no.iter_q_creators() <generator object... at 0x...> >>> list(no.iter_q_creators()) [0, 1] >>> list(no.iter_q_annihilators()) [3, 2] """ ops = self.args[0].args iter = range(0, len(ops)) for i in iter: if ops[i].is_q_creator: yield i else: break def get_subNO(self, i): """ Returns a NO() without FermionicOperator at index i. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import F, NO >>> p,q,r = symbols('p,q,r') >>> NO(F(p)*F(q)*F(r)).get_subNO(1) # doctest: +SKIP NO(AnnihilateFermion(p)*AnnihilateFermion(r)) """ arg0 = self.args[0] # it's a Mul by definition of how it's created mul = arg0._new_rawargs(arg0.args[:i] + arg0.args[i + 1:]) return NO(mul) def _latex(self, printer): return "\\left\\{%s\\right\\}" % printer._print(self.args[0]) def __repr__(self): return "NO(%s)" % self.args[0] def __str__(self): return ":%s:" % self.args[0] def contraction(a, b): """ Calculates contraction of Fermionic operators a and b. Examples ======== >>> from sympy import symbols >>> from sympy.physics.secondquant import F, Fd, contraction >>> p, q = symbols('p,q') >>> a, b = symbols('a,b', above_fermi=True) >>> i, j = symbols('i,j', below_fermi=True) A contraction is non-zero only if a quasi-creator is to the right of a quasi-annihilator: >>> contraction(F(a),Fd(b)) KroneckerDelta(a, b) >>> contraction(Fd(i),F(j)) KroneckerDelta(i, j) For general indices a non-zero result restricts the indices to below/above the fermi surface: >>> contraction(Fd(p),F(q)) KroneckerDelta(_i, q)*KroneckerDelta(p, q) >>> contraction(F(p),Fd(q)) KroneckerDelta(_a, q)*KroneckerDelta(p, q) Two creators or two annihilators always vanishes: >>> contraction(F(p),F(q)) 0 >>> contraction(Fd(p),Fd(q)) 0 """ if isinstance(b, FermionicOperator) and isinstance(a, FermionicOperator): if isinstance(a, AnnihilateFermion) and isinstance(b, CreateFermion): if b.state.assumptions0.get("below_fermi"): return S.Zero if a.state.assumptions0.get("below_fermi"): return S.Zero if b.state.assumptions0.get("above_fermi"): return KroneckerDelta(a.state, b.state) if a.state.assumptions0.get("above_fermi"): return KroneckerDelta(a.state, b.state) return (KroneckerDelta(a.state, b.state)* KroneckerDelta(b.state, Dummy('a', above_fermi=True))) if isinstance(b, AnnihilateFermion) and isinstance(a, CreateFermion): if b.state.assumptions0.get("above_fermi"): return S.Zero if a.state.assumptions0.get("above_fermi"): return S.Zero if b.state.assumptions0.get("below_fermi"): return KroneckerDelta(a.state, b.state) if a.state.assumptions0.get("below_fermi"): return KroneckerDelta(a.state, b.state) return (KroneckerDelta(a.state, b.state)* KroneckerDelta(b.state, Dummy('i', below_fermi=True))) # vanish if 2xAnnihilator or 2xCreator return S.Zero else: #not fermion operators t = ( isinstance(i, FermionicOperator) for i in (a, b) ) raise ContractionAppliesOnlyToFermions(*t) def _sqkey(sq_operator): """Generates key for canonical sorting of SQ operators.""" return sq_operator._sortkey() def _sort_anticommuting_fermions(string1, key=_sqkey): """Sort fermionic operators to canonical order, assuming all pairs anticommute. Uses a bidirectional bubble sort. Items in string1 are not referenced so in principle they may be any comparable objects. The sorting depends on the operators '>' and '=='. If the Pauli principle is violated, an exception is raised. Returns ======= tuple (sorted_str, sign) sorted_str: list containing the sorted operators sign: int telling how many times the sign should be changed (if sign==0 the string was already sorted) """ verified = False sign = 0 rng = list(range(len(string1) - 1)) rev = list(range(len(string1) - 3, -1, -1)) keys = list(map(key, string1)) key_val = dict(list(zip(keys, string1))) while not verified: verified = True for i in rng: left = keys[i] right = keys[i + 1] if left == right: raise ViolationOfPauliPrinciple([left, right]) if left > right: verified = False keys[i:i + 2] = [right, left] sign = sign + 1 if verified: break for i in rev: left = keys[i] right = keys[i + 1] if left == right: raise ViolationOfPauliPrinciple([left, right]) if left > right: verified = False keys[i:i + 2] = [right, left] sign = sign + 1 string1 = [ key_val[k] for k in keys ] return (string1, sign) def evaluate_deltas(e): """ We evaluate KroneckerDelta symbols in the expression assuming Einstein summation. If one index is repeated it is summed over and in effect substituted with the other one. If both indices are repeated we substitute according to what is the preferred index. this is determined by KroneckerDelta.preferred_index and KroneckerDelta.killable_index. In case there are no possible substitutions or if a substitution would imply a loss of information, nothing is done. In case an index appears in more than one KroneckerDelta, the resulting substitution depends on the order of the factors. Since the ordering is platform dependent, the literal expression resulting from this function may be hard to predict. Examples ======== We assume the following: >>> from sympy import symbols, Function, Dummy, KroneckerDelta >>> from sympy.physics.secondquant import evaluate_deltas >>> i,j = symbols('i j', below_fermi=True, cls=Dummy) >>> a,b = symbols('a b', above_fermi=True, cls=Dummy) >>> p,q = symbols('p q', cls=Dummy) >>> f = Function('f') >>> t = Function('t') The order of preference for these indices according to KroneckerDelta is (a, b, i, j, p, q). Trivial cases: >>> evaluate_deltas(KroneckerDelta(i,j)*f(i)) # d_ij f(i) -> f(j) f(_j) >>> evaluate_deltas(KroneckerDelta(i,j)*f(j)) # d_ij f(j) -> f(i) f(_i) >>> evaluate_deltas(KroneckerDelta(i,p)*f(p)) # d_ip f(p) -> f(i) f(_i) >>> evaluate_deltas(KroneckerDelta(q,p)*f(p)) # d_qp f(p) -> f(q) f(_q) >>> evaluate_deltas(KroneckerDelta(q,p)*f(q)) # d_qp f(q) -> f(p) f(_p) More interesting cases: >>> evaluate_deltas(KroneckerDelta(i,p)*t(a,i)*f(p,q)) f(_i, _q)*t(_a, _i) >>> evaluate_deltas(KroneckerDelta(a,p)*t(a,i)*f(p,q)) f(_a, _q)*t(_a, _i) >>> evaluate_deltas(KroneckerDelta(p,q)*f(p,q)) f(_p, _p) Finally, here are some cases where nothing is done, because that would imply a loss of information: >>> evaluate_deltas(KroneckerDelta(i,p)*f(q)) f(_q)*KroneckerDelta(_i, _p) >>> evaluate_deltas(KroneckerDelta(i,p)*f(i)) f(_i)*KroneckerDelta(_i, _p) """ # We treat Deltas only in mul objects # for general function objects we don't evaluate KroneckerDeltas in arguments, # but here we hard code exceptions to this rule accepted_functions = ( Add, ) if isinstance(e, accepted_functions): return e.func(*[evaluate_deltas(arg) for arg in e.args]) elif isinstance(e, Mul): # find all occurences of delta function and count each index present in # expression. deltas = [] indices = {} for i in e.args: for s in i.free_symbols: if s in indices: indices[s] += 1 else: indices[s] = 0 # geek counting simplifies logic below if isinstance(i, KroneckerDelta): deltas.append(i) for d in deltas: # If we do something, and there are more deltas, we should recurse # to treat the resulting expression properly if d.killable_index.is_Symbol and indices[d.killable_index]: e = e.subs(d.killable_index, d.preferred_index) if len(deltas) > 1: return evaluate_deltas(e) elif (d.preferred_index.is_Symbol and indices[d.preferred_index] and d.indices_contain_equal_information): e = e.subs(d.preferred_index, d.killable_index) if len(deltas) > 1: return evaluate_deltas(e) else: pass return e # nothing to do, maybe we hit a Symbol or a number else: return e def substitute_dummies(expr, new_indices=False, pretty_indices={}): """ Collect terms by substitution of dummy variables. This routine allows simplification of Add expressions containing terms which differ only due to dummy variables. The idea is to substitute all dummy variables consistently depending on the structure of the term. For each term, we obtain a sequence of all dummy variables, where the order is determined by the index range, what factors the index belongs to and its position in each factor. See _get_ordered_dummies() for more inforation about the sorting of dummies. The index sequence is then substituted consistently in each term. Examples ======== >>> from sympy import symbols, Function, Dummy >>> from sympy.physics.secondquant import substitute_dummies >>> a,b,c,d = symbols('a b c d', above_fermi=True, cls=Dummy) >>> i,j = symbols('i j', below_fermi=True, cls=Dummy) >>> f = Function('f') >>> expr = f(a,b) + f(c,d); expr f(_a, _b) + f(_c, _d) Since a, b, c and d are equivalent summation indices, the expression can be simplified to a single term (for which the dummy indices are still summed over) >>> substitute_dummies(expr) 2*f(_a, _b) Controlling output: By default the dummy symbols that are already present in the expression will be reused in a different permuation. However, if new_indices=True, new dummies will be generated and inserted. The keyword 'pretty_indices' can be used to control this generation of new symbols. By default the new dummies will be generated on the form i_1, i_2, a_1, etc. If you supply a dictionary with key:value pairs in the form: { index_group: string_of_letters } The letters will be used as labels for the new dummy symbols. The index_groups must be one of 'above', 'below' or 'general'. >>> expr = f(a,b,i,j) >>> my_dummies = { 'above':'st', 'below':'uv' } >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies) f(_s, _t, _u, _v) If we run out of letters, or if there is no keyword for some index_group the default dummy generator will be used as a fallback: >>> p,q = symbols('p q', cls=Dummy) # general indices >>> expr = f(p,q) >>> substitute_dummies(expr, new_indices=True, pretty_indices=my_dummies) f(_p_0, _p_1) """ # setup the replacing dummies if new_indices: letters_above = pretty_indices.get('above', "") letters_below = pretty_indices.get('below', "") letters_general = pretty_indices.get('general', "") len_above = len(letters_above) len_below = len(letters_below) len_general = len(letters_general) def _i(number): try: return letters_below[number] except IndexError: return 'i_' + str(number - len_below) def _a(number): try: return letters_above[number] except IndexError: return 'a_' + str(number - len_above) def _p(number): try: return letters_general[number] except IndexError: return 'p_' + str(number - len_general) aboves = [] belows = [] generals = [] dummies = expr.atoms(Dummy) if not new_indices: dummies = sorted(dummies, key=default_sort_key) # generate lists with the dummies we will insert a = i = p = 0 for d in dummies: assum = d.assumptions0 if assum.get("above_fermi"): if new_indices: sym = _a(a) a += 1 l1 = aboves elif assum.get("below_fermi"): if new_indices: sym = _i(i) i += 1 l1 = belows else: if new_indices: sym = _p(p) p += 1 l1 = generals if new_indices: l1.append(Dummy(sym, **assum)) else: l1.append(d) expr = expr.expand() terms = Add.make_args(expr) new_terms = [] for term in terms: i = iter(belows) a = iter(aboves) p = iter(generals) ordered = _get_ordered_dummies(term) subsdict = {} for d in ordered: if d.assumptions0.get('below_fermi'): subsdict[d] = next(i) elif d.assumptions0.get('above_fermi'): subsdict[d] = next(a) else: subsdict[d] = next(p) subslist = [] final_subs = [] for k, v in subsdict.items(): if k == v: continue if v in subsdict: # We check if the sequence of substitutions end quickly. In # that case, we can avoid temporary symbols if we ensure the # correct substitution order. if subsdict[v] in subsdict: # (x, y) -> (y, x), we need a temporary variable x = Dummy('x') subslist.append((k, x)) final_subs.append((x, v)) else: # (x, y) -> (y, a), x->y must be done last # but before temporary variables are resolved final_subs.insert(0, (k, v)) else: subslist.append((k, v)) subslist.extend(final_subs) new_terms.append(term.subs(subslist)) return Add(*new_terms) class KeyPrinter(StrPrinter): """Printer for which only equal objects are equal in print""" def _print_Dummy(self, expr): return "(%s_%i)" % (expr.name, expr.dummy_index) def __kprint(expr): p = KeyPrinter() return p.doprint(expr) def _get_ordered_dummies(mul, verbose=False): """Returns all dummies in the mul sorted in canonical order The purpose of the canonical ordering is that dummies can be substituted consistently across terms with the result that equivalent terms can be simplified. It is not possible to determine if two terms are equivalent based solely on the dummy order. However, a consistent substitution guided by the ordered dummies should lead to trivially (non-)equivalent terms, thereby revealing the equivalence. This also means that if two terms have identical sequences of dummies, the (non-)equivalence should already be apparent. Strategy -------- The canoncial order is given by an arbitrary sorting rule. A sort key is determined for each dummy as a tuple that depends on all factors where the index is present. The dummies are thereby sorted according to the contraction structure of the term, instead of sorting based solely on the dummy symbol itself. After all dummies in the term has been assigned a key, we check for identical keys, i.e. unorderable dummies. If any are found, we call a specialized method, _determine_ambiguous(), that will determine a unique order based on recursive calls to _get_ordered_dummies(). Key description --------------- A high level description of the sort key: 1. Range of the dummy index 2. Relation to external (non-dummy) indices 3. Position of the index in the first factor 4. Position of the index in the second factor The sort key is a tuple with the following components: 1. A single character indicating the range of the dummy (above, below or general.) 2. A list of strings with fully masked string representations of all factors where the dummy is present. By masked, we mean that dummies are represented by a symbol to indicate either below fermi, above or general. No other information is displayed about the dummies at this point. The list is sorted stringwise. 3. An integer number indicating the position of the index, in the first factor as sorted in 2. 4. An integer number indicating the position of the index, in the second factor as sorted in 2. If a factor is either of type AntiSymmetricTensor or SqOperator, the index position in items 3 and 4 is indicated as 'upper' or 'lower' only. (Creation operators are considered upper and annihilation operators lower.) If the masked factors are identical, the two factors cannot be ordered unambiguously in item 2. In this case, items 3, 4 are left out. If several indices are contracted between the unorderable factors, it will be handled by _determine_ambiguous() """ # setup dicts to avoid repeated calculations in key() args = Mul.make_args(mul) fac_dum = dict([ (fac, fac.atoms(Dummy)) for fac in args] ) fac_repr = dict([ (fac, __kprint(fac)) for fac in args] ) all_dums = set().union(*fac_dum.values()) mask = {} for d in all_dums: if d.assumptions0.get('below_fermi'): mask[d] = '0' elif d.assumptions0.get('above_fermi'): mask[d] = '1' else: mask[d] = '2' dum_repr = {d: __kprint(d) for d in all_dums} def _key(d): dumstruct = [ fac for fac in fac_dum if d in fac_dum[fac] ] other_dums = set().union(*[fac_dum[fac] for fac in dumstruct]) fac = dumstruct[-1] if other_dums is fac_dum[fac]: other_dums = fac_dum[fac].copy() other_dums.remove(d) masked_facs = [ fac_repr[fac] for fac in dumstruct ] for d2 in other_dums: masked_facs = [ fac.replace(dum_repr[d2], mask[d2]) for fac in masked_facs ] all_masked = [ fac.replace(dum_repr[d], mask[d]) for fac in masked_facs ] masked_facs = dict(list(zip(dumstruct, masked_facs))) # dummies for which the ordering cannot be determined if has_dups(all_masked): all_masked.sort() return mask[d], tuple(all_masked) # positions are ambiguous # sort factors according to fully masked strings keydict = dict(list(zip(dumstruct, all_masked))) dumstruct.sort(key=lambda x: keydict[x]) all_masked.sort() pos_val = [] for fac in dumstruct: if isinstance(fac, AntiSymmetricTensor): if d in fac.upper: pos_val.append('u') if d in fac.lower: pos_val.append('l') elif isinstance(fac, Creator): pos_val.append('u') elif isinstance(fac, Annihilator): pos_val.append('l') elif isinstance(fac, NO): ops = [ op for op in fac if op.has(d) ] for op in ops: if isinstance(op, Creator): pos_val.append('u') else: pos_val.append('l') else: # fallback to position in string representation facpos = -1 while 1: facpos = masked_facs[fac].find(dum_repr[d], facpos + 1) if facpos == -1: break pos_val.append(facpos) return (mask[d], tuple(all_masked), pos_val[0], pos_val[-1]) dumkey = dict(list(zip(all_dums, list(map(_key, all_dums))))) result = sorted(all_dums, key=lambda x: dumkey[x]) if has_dups(iter(dumkey.values())): # We have ambiguities unordered = defaultdict(set) for d, k in dumkey.items(): unordered[k].add(d) for k in [ k for k in unordered if len(unordered[k]) < 2 ]: del unordered[k] unordered = [ unordered[k] for k in sorted(unordered) ] result = _determine_ambiguous(mul, result, unordered) return result def _determine_ambiguous(term, ordered, ambiguous_groups): # We encountered a term for which the dummy substitution is ambiguous. # This happens for terms with 2 or more contractions between factors that # cannot be uniquely ordered independent of summation indices. For # example: # # Sum(p, q) v^{p, .}_{q, .}v^{q, .}_{p, .} # # Assuming that the indices represented by . are dummies with the # same range, the factors cannot be ordered, and there is no # way to determine a consistent ordering of p and q. # # The strategy employed here, is to relabel all unambiguous dummies with # non-dummy symbols and call _get_ordered_dummies again. This procedure is # applied to the entire term so there is a possibility that # _determine_ambiguous() is called again from a deeper recursion level. # break recursion if there are no ordered dummies all_ambiguous = set() for dummies in ambiguous_groups: all_ambiguous |= dummies all_ordered = set(ordered) - all_ambiguous if not all_ordered: # FIXME: If we arrive here, there are no ordered dummies. A method to # handle this needs to be implemented. In order to return something # useful nevertheless, we choose arbitrarily the first dummy and # determine the rest from this one. This method is dependent on the # actual dummy labels which violates an assumption for the canonization # procedure. A better implementation is needed. group = [ d for d in ordered if d in ambiguous_groups[0] ] d = group[0] all_ordered.add(d) ambiguous_groups[0].remove(d) stored_counter = _symbol_factory._counter subslist = [] for d in [ d for d in ordered if d in all_ordered ]: nondum = _symbol_factory._next() subslist.append((d, nondum)) newterm = term.subs(subslist) neworder = _get_ordered_dummies(newterm) _symbol_factory._set_counter(stored_counter) # update ordered list with new information for group in ambiguous_groups: ordered_group = [ d for d in neworder if d in group ] ordered_group.reverse() result = [] for d in ordered: if d in group: result.append(ordered_group.pop()) else: result.append(d) ordered = result return ordered class _SymbolFactory(object): def __init__(self, label): self._counterVar = 0 self._label = label def _set_counter(self, value): """ Sets counter to value. """ self._counterVar = value @property def _counter(self): """ What counter is currently at. """ return self._counterVar def _next(self): """ Generates the next symbols and increments counter by 1. """ s = Symbol("%s%i" % (self._label, self._counterVar)) self._counterVar += 1 return s _symbol_factory = _SymbolFactory('_]"]_') # most certainly a unique label @cacheit def _get_contractions(string1, keep_only_fully_contracted=False): """ Returns Add-object with contracted terms. Uses recursion to find all contractions. -- Internal helper function -- Will find nonzero contractions in string1 between indices given in leftrange and rightrange. """ # Should we store current level of contraction? if keep_only_fully_contracted and string1: result = [] else: result = [NO(Mul(*string1))] for i in range(len(string1) - 1): for j in range(i + 1, len(string1)): c = contraction(string1[i], string1[j]) if c: sign = (j - i + 1) % 2 if sign: coeff = S.NegativeOne*c else: coeff = c # # Call next level of recursion # ============================ # # We now need to find more contractions among operators # # oplist = string1[:i]+ string1[i+1:j] + string1[j+1:] # # To prevent overcounting, we don't allow contractions # we have already encountered. i.e. contractions between # string1[:i] <---> string1[i+1:j] # and string1[:i] <---> string1[j+1:]. # # This leaves the case: oplist = string1[i + 1:j] + string1[j + 1:] if oplist: result.append(coeff*NO( Mul(*string1[:i])*_get_contractions( oplist, keep_only_fully_contracted=keep_only_fully_contracted))) else: result.append(coeff*NO( Mul(*string1[:i]))) if keep_only_fully_contracted: break # next iteration over i leaves leftmost operator string1[0] uncontracted return Add(*result) def wicks(e, **kw_args): """ Returns the normal ordered equivalent of an expression using Wicks Theorem. Examples ======== >>> from sympy import symbols, Function, Dummy >>> from sympy.physics.secondquant import wicks, F, Fd, NO >>> p,q,r = symbols('p,q,r') >>> wicks(Fd(p)*F(q)) # doctest: +SKIP d(p, q)*d(q, _i) + NO(CreateFermion(p)*AnnihilateFermion(q)) By default, the expression is expanded: >>> wicks(F(p)*(F(q)+F(r))) # doctest: +SKIP NO(AnnihilateFermion(p)*AnnihilateFermion(q)) + NO( AnnihilateFermion(p)*AnnihilateFermion(r)) With the keyword 'keep_only_fully_contracted=True', only fully contracted terms are returned. By request, the result can be simplified in the following order: -- KroneckerDelta functions are evaluated -- Dummy variables are substituted consistently across terms >>> p, q, r = symbols('p q r', cls=Dummy) >>> wicks(Fd(p)*(F(q)+F(r)), keep_only_fully_contracted=True) # doctest: +SKIP KroneckerDelta(_i, _q)*KroneckerDelta( _p, _q) + KroneckerDelta(_i, _r)*KroneckerDelta(_p, _r) """ if not e: return S.Zero opts = { 'simplify_kronecker_deltas': False, 'expand': True, 'simplify_dummies': False, 'keep_only_fully_contracted': False } opts.update(kw_args) # check if we are already normally ordered if isinstance(e, NO): if opts['keep_only_fully_contracted']: return S.Zero else: return e elif isinstance(e, FermionicOperator): if opts['keep_only_fully_contracted']: return S.Zero else: return e # break up any NO-objects, and evaluate commutators e = e.doit(wicks=True) # make sure we have only one term to consider e = e.expand() if isinstance(e, Add): if opts['simplify_dummies']: return substitute_dummies(Add(*[ wicks(term, **kw_args) for term in e.args])) else: return Add(*[ wicks(term, **kw_args) for term in e.args]) # For Mul-objects we can actually do something if isinstance(e, Mul): # we dont want to mess around with commuting part of Mul # so we factorize it out before starting recursion c_part = [] string1 = [] for factor in e.args: if factor.is_commutative: c_part.append(factor) else: string1.append(factor) n = len(string1) # catch trivial cases if n == 0: result = e elif n == 1: if opts['keep_only_fully_contracted']: return S.Zero else: result = e else: # non-trivial if isinstance(string1[0], BosonicOperator): raise NotImplementedError string1 = tuple(string1) # recursion over higher order contractions result = _get_contractions(string1, keep_only_fully_contracted=opts['keep_only_fully_contracted'] ) result = Mul(*c_part)*result if opts['expand']: result = result.expand() if opts['simplify_kronecker_deltas']: result = evaluate_deltas(result) return result # there was nothing to do return e class PermutationOperator(Expr): """ Represents the index permutation operator P(ij). P(ij)*f(i)*g(j) = f(i)*g(j) - f(j)*g(i) """ is_commutative = True def __new__(cls, i, j): i, j = sorted(map(sympify, (i, j)), key=default_sort_key) obj = Basic.__new__(cls, i, j) return obj def get_permuted(self, expr): """ Returns -expr with permuted indices. >>> from sympy import symbols, Function >>> from sympy.physics.secondquant import PermutationOperator >>> p,q = symbols('p,q') >>> f = Function('f') >>> PermutationOperator(p,q).get_permuted(f(p,q)) -f(q, p) """ i = self.args[0] j = self.args[1] if expr.has(i) and expr.has(j): tmp = Dummy() expr = expr.subs(i, tmp) expr = expr.subs(j, i) expr = expr.subs(tmp, j) return S.NegativeOne*expr else: return expr def _latex(self, printer): return "P(%s%s)" % self.args def simplify_index_permutations(expr, permutation_operators): """ Performs simplification by introducing PermutationOperators where appropriate. Schematically: [abij] - [abji] - [baij] + [baji] -> P(ab)*P(ij)*[abij] permutation_operators is a list of PermutationOperators to consider. If permutation_operators=[P(ab),P(ij)] we will try to introduce the permutation operators P(ij) and P(ab) in the expression. If there are other possible simplifications, we ignore them. >>> from sympy import symbols, Function >>> from sympy.physics.secondquant import simplify_index_permutations >>> from sympy.physics.secondquant import PermutationOperator >>> p,q,r,s = symbols('p,q,r,s') >>> f = Function('f') >>> g = Function('g') >>> expr = f(p)*g(q) - f(q)*g(p); expr f(p)*g(q) - f(q)*g(p) >>> simplify_index_permutations(expr,[PermutationOperator(p,q)]) f(p)*g(q)*PermutationOperator(p, q) >>> PermutList = [PermutationOperator(p,q),PermutationOperator(r,s)] >>> expr = f(p,r)*g(q,s) - f(q,r)*g(p,s) + f(q,s)*g(p,r) - f(p,s)*g(q,r) >>> simplify_index_permutations(expr,PermutList) f(p, r)*g(q, s)*PermutationOperator(p, q)*PermutationOperator(r, s) """ def _get_indices(expr, ind): """ Collects indices recursively in predictable order. """ result = [] for arg in expr.args: if arg in ind: result.append(arg) else: if arg.args: result.extend(_get_indices(arg, ind)) return result def _choose_one_to_keep(a, b, ind): # we keep the one where indices in ind are in order ind[0] < ind[1] return min(a, b, key=lambda x: default_sort_key(_get_indices(x, ind))) expr = expr.expand() if isinstance(expr, Add): terms = set(expr.args) for P in permutation_operators: new_terms = set([]) on_hold = set([]) while terms: term = terms.pop() permuted = P.get_permuted(term) if permuted in terms | on_hold: try: terms.remove(permuted) except KeyError: on_hold.remove(permuted) keep = _choose_one_to_keep(term, permuted, P.args) new_terms.add(P*keep) else: # Some terms must get a second chance because the permuted # term may already have canonical dummy ordering. Then # substitute_dummies() does nothing. However, the other # term, if it exists, will be able to match with us. permuted1 = permuted permuted = substitute_dummies(permuted) if permuted1 == permuted: on_hold.add(term) elif permuted in terms | on_hold: try: terms.remove(permuted) except KeyError: on_hold.remove(permuted) keep = _choose_one_to_keep(term, permuted, P.args) new_terms.add(P*keep) else: new_terms.add(term) terms = new_terms | on_hold return Add(*terms) return expr
88,680
28.530803
92
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/identitysearch.py
from __future__ import print_function, division from collections import deque from random import randint from sympy.core.compatibility import range from sympy.external import import_module from sympy import Mul, Basic, Number, Pow, Integer from sympy.physics.quantum.represent import represent from sympy.physics.quantum.dagger import Dagger __all__ = [ # Public interfaces 'generate_gate_rules', 'generate_equivalent_ids', 'GateIdentity', 'bfs_identity_search', 'random_identity_search', # "Private" functions 'is_scalar_sparse_matrix', 'is_scalar_nonsparse_matrix', 'is_degenerate', 'is_reducible', ] np = import_module('numpy') scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11): """Checks if a given scipy.sparse matrix is a scalar matrix. A scalar matrix is such that B = bI, where B is the scalar matrix, b is some scalar multiple, and I is the identity matrix. A scalar matrix would have only the element b along it's main diagonal and zeroes elsewhere. Parameters ========== circuit : Gate tuple Sequence of quantum gates representing a quantum circuit nqubits : int Number of qubits in the circuit identity_only : bool Check for only identity matrices eps : number The tolerance value for zeroing out elements in the matrix. Values in the range [-eps, +eps] will be changed to a zero. """ if not np or not scipy: pass matrix = represent(Mul(*circuit), nqubits=nqubits, format='scipy.sparse') # In some cases, represent returns a 1D scalar value in place # of a multi-dimensional scalar matrix if (isinstance(matrix, int)): return matrix == 1 if identity_only else True # If represent returns a matrix, check if the matrix is diagonal # and if every item along the diagonal is the same else: # Due to floating pointing operations, must zero out # elements that are "very" small in the dense matrix # See parameter for default value. # Get the ndarray version of the dense matrix dense_matrix = matrix.todense().getA() # Since complex values can't be compared, must split # the matrix into real and imaginary components # Find the real values in between -eps and eps bool_real = np.logical_and(dense_matrix.real > -eps, dense_matrix.real < eps) # Find the imaginary values between -eps and eps bool_imag = np.logical_and(dense_matrix.imag > -eps, dense_matrix.imag < eps) # Replaces values between -eps and eps with 0 corrected_real = np.where(bool_real, 0.0, dense_matrix.real) corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag) # Convert the matrix with real values into imaginary values corrected_imag = corrected_imag * np.complex(1j) # Recombine the real and imaginary components corrected_dense = corrected_real + corrected_imag # Check if it's diagonal row_indices = corrected_dense.nonzero()[0] col_indices = corrected_dense.nonzero()[1] # Check if the rows indices and columns indices are the same # If they match, then matrix only contains elements along diagonal bool_indices = row_indices == col_indices is_diagonal = bool_indices.all() first_element = corrected_dense[0][0] # If the first element is a zero, then can't rescale matrix # and definitely not diagonal if (first_element == 0.0 + 0.0j): return False # The dimensions of the dense matrix should still # be 2^nqubits if there are elements all along the # the main diagonal trace_of_corrected = (corrected_dense/first_element).trace() expected_trace = pow(2, nqubits) has_correct_trace = trace_of_corrected == expected_trace # If only looking for identity matrices # first element must be a 1 real_is_one = abs(first_element.real - 1.0) < eps imag_is_zero = abs(first_element.imag) < eps is_one = real_is_one and imag_is_zero is_identity = is_one if identity_only else True return bool(is_diagonal and has_correct_trace and is_identity) def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only): """Checks if a given circuit, in matrix form, is equivalent to a scalar value. Parameters ========== circuit : Gate tuple Sequence of quantum gates representing a quantum circuit nqubits : int Number of qubits in the circuit identity_only : bool Check for only identity matrices Note: Used in situations when is_scalar_sparse_matrix has bugs """ matrix = represent(Mul(*circuit), nqubits=nqubits) # In some cases, represent returns a 1D scalar value in place # of a multi-dimensional scalar matrix if (isinstance(matrix, Number)): return matrix == 1 if identity_only else True # If represent returns a matrix, check if the matrix is diagonal # and if every item along the diagonal is the same else: # Added up the diagonal elements matrix_trace = matrix.trace() # Divide the trace by the first element in the matrix # if matrix is not required to be the identity matrix adjusted_matrix_trace = (matrix_trace/matrix[0] if not identity_only else matrix_trace) is_identity = matrix[0] == 1.0 if identity_only else True has_correct_trace = adjusted_matrix_trace == pow(2, nqubits) # The matrix is scalar if it's diagonal and the adjusted trace # value is equal to 2^nqubits return bool( matrix.is_diagonal() and has_correct_trace and is_identity) if np and scipy: is_scalar_matrix = is_scalar_sparse_matrix else: is_scalar_matrix = is_scalar_nonsparse_matrix def _get_min_qubits(a_gate): if isinstance(a_gate, Pow): return a_gate.base.min_qubits else: return a_gate.min_qubits def ll_op(left, right): """Perform a LL operation. A LL operation multiplies both left and right circuits with the dagger of the left circuit's leftmost gate, and the dagger is multiplied on the left side of both circuits. If a LL is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a LL is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a LL operation: >>> from sympy.physics.quantum.identitysearch import ll_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> ll_op((x, y, z), ()) ((Y(0), Z(0)), (X(0),)) >>> ll_op((y, z), (x,)) ((Z(0),), (Y(0), X(0))) """ if (len(left) > 0): ll_gate = left[0] ll_gate_is_unitary = is_scalar_matrix( (Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True) if (len(left) > 0 and ll_gate_is_unitary): # Get the new left side w/o the leftmost gate new_left = left[1:len(left)] # Add the leftmost gate to the left position on the right side new_right = (Dagger(ll_gate),) + right # Return the new gate rule return (new_left, new_right) return None def lr_op(left, right): """Perform a LR operation. A LR operation multiplies both left and right circuits with the dagger of the left circuit's rightmost gate, and the dagger is multiplied on the right side of both circuits. If a LR is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a LR is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a LR operation: >>> from sympy.physics.quantum.identitysearch import lr_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> lr_op((x, y, z), ()) ((X(0), Y(0)), (Z(0),)) >>> lr_op((x, y), (z,)) ((X(0),), (Z(0), Y(0))) """ if (len(left) > 0): lr_gate = left[len(left) - 1] lr_gate_is_unitary = is_scalar_matrix( (Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True) if (len(left) > 0 and lr_gate_is_unitary): # Get the new left side w/o the rightmost gate new_left = left[0:len(left) - 1] # Add the rightmost gate to the right position on the right side new_right = right + (Dagger(lr_gate),) # Return the new gate rule return (new_left, new_right) return None def rl_op(left, right): """Perform a RL operation. A RL operation multiplies both left and right circuits with the dagger of the right circuit's leftmost gate, and the dagger is multiplied on the left side of both circuits. If a RL is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a RL is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a RL operation: >>> from sympy.physics.quantum.identitysearch import rl_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> rl_op((x,), (y, z)) ((Y(0), X(0)), (Z(0),)) >>> rl_op((x, y), (z,)) ((Z(0), X(0), Y(0)), ()) """ if (len(right) > 0): rl_gate = right[0] rl_gate_is_unitary = is_scalar_matrix( (Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True) if (len(right) > 0 and rl_gate_is_unitary): # Get the new right side w/o the leftmost gate new_right = right[1:len(right)] # Add the leftmost gate to the left position on the left side new_left = (Dagger(rl_gate),) + left # Return the new gate rule return (new_left, new_right) return None def rr_op(left, right): """Perform a RR operation. A RR operation multiplies both left and right circuits with the dagger of the right circuit's rightmost gate, and the dagger is multiplied on the right side of both circuits. If a RR is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a RR is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a RR operation: >>> from sympy.physics.quantum.identitysearch import rr_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> rr_op((x, y), (z,)) ((X(0), Y(0), Z(0)), ()) >>> rr_op((x,), (y, z)) ((X(0), Z(0)), (Y(0),)) """ if (len(right) > 0): rr_gate = right[len(right) - 1] rr_gate_is_unitary = is_scalar_matrix( (Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True) if (len(right) > 0 and rr_gate_is_unitary): # Get the new right side w/o the rightmost gate new_right = right[0:len(right) - 1] # Add the rightmost gate to the right position on the right side new_left = left + (Dagger(rr_gate),) # Return the new gate rule return (new_left, new_right) return None def generate_gate_rules(gate_seq, return_as_muls=False): """Returns a set of gate rules. Each gate rules is represented as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary scalar value. This function uses the four operations (LL, LR, RL, RR) to generate the gate rules. A gate rule is an expression such as ABC = D or AB = CD, where A, B, C, and D are gates. Each value on either side of the equal sign represents a circuit. The four operations allow one to find a set of equivalent circuits from a gate identity. The letters denoting the operation tell the user what activities to perform on each expression. The first letter indicates which side of the equal sign to focus on. The second letter indicates which gate to focus on given the side. Once this information is determined, the inverse of the gate is multiplied on both circuits to create a new gate rule. For example, given the identity, ABCD = 1, a LL operation means look at the left value and multiply both left sides by the inverse of the leftmost gate A. If A is Hermitian, the inverse of A is still A. The resulting new rule is BCD = A. The following is a summary of the four operations. Assume that in the examples, all gates are Hermitian. LL : left circuit, left multiply ABCD = E -> AABCD = AE -> BCD = AE LR : left circuit, right multiply ABCD = E -> ABCDD = ED -> ABC = ED RL : right circuit, left multiply ABC = ED -> EABC = EED -> EABC = D RR : right circuit, right multiply AB = CD -> ABD = CDD -> ABD = C The number of gate rules generated is n*(n+1), where n is the number of gates in the sequence (unproven). Parameters ========== gate_seq : Gate tuple, Mul, or Number A variable length tuple or Mul of Gates whose product is equal to a scalar matrix return_as_muls : bool True to return a set of Muls; False to return a set of tuples Examples ======== Find the gate rules of the current circuit using tuples: >>> from sympy.physics.quantum.identitysearch import generate_gate_rules >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> generate_gate_rules((x, x)) {((X(0),), (X(0),)), ((X(0), X(0)), ())} >>> generate_gate_rules((x, y, z)) {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))), ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))), ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))), ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)), ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()), ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())} Find the gate rules of the current circuit using Muls: >>> generate_gate_rules(x*x, return_as_muls=True) {(1, 1)} >>> generate_gate_rules(x*y*z, return_as_muls=True) {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)), (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)), (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)), (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1), (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)), (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))} """ if isinstance(gate_seq, Number): if return_as_muls: return {(Integer(1), Integer(1))} else: return {((), ())} elif isinstance(gate_seq, Mul): gate_seq = gate_seq.args # Each item in queue is a 3-tuple: # i) first item is the left side of an equality # ii) second item is the right side of an equality # iii) third item is the number of operations performed # The argument, gate_seq, will start on the left side, and # the right side will be empty, implying the presence of an # identity. queue = deque() # A set of gate rules rules = set() # Maximum number of operations to perform max_ops = len(gate_seq) def process_new_rule(new_rule, ops): if new_rule is not None: new_left, new_right = new_rule if new_rule not in rules and (new_right, new_left) not in rules: rules.add(new_rule) # If haven't reached the max limit on operations if ops + 1 < max_ops: queue.append(new_rule + (ops + 1,)) queue.append((gate_seq, (), 0)) rules.add((gate_seq, ())) while len(queue) > 0: left, right, ops = queue.popleft() # Do a LL new_rule = ll_op(left, right) process_new_rule(new_rule, ops) # Do a LR new_rule = lr_op(left, right) process_new_rule(new_rule, ops) # Do a RL new_rule = rl_op(left, right) process_new_rule(new_rule, ops) # Do a RR new_rule = rr_op(left, right) process_new_rule(new_rule, ops) if return_as_muls: # Convert each rule as tuples into a rule as muls mul_rules = set() for rule in rules: left, right = rule mul_rules.add((Mul(*left), Mul(*right))) rules = mul_rules return rules def generate_equivalent_ids(gate_seq, return_as_muls=False): """Returns a set of equivalent gate identities. A gate identity is a quantum circuit such that the product of the gates in the circuit is equal to a scalar value. For example, XYZ = i, where X, Y, Z are the Pauli gates and i is the imaginary value, is considered a gate identity. This function uses the four operations (LL, LR, RL, RR) to generate the gate rules and, subsequently, to locate equivalent gate identities. Note that all equivalent identities are reachable in n operations from the starting gate identity, where n is the number of gates in the sequence. The max number of gate identities is 2n, where n is the number of gates in the sequence (unproven). Parameters ========== gate_seq : Gate tuple, Mul, or Number A variable length tuple or Mul of Gates whose product is equal to a scalar matrix. return_as_muls: bool True to return as Muls; False to return as tuples Examples ======== Find equivalent gate identities from the current circuit with tuples: >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> generate_equivalent_ids((x, x)) {(X(0), X(0))} >>> generate_equivalent_ids((x, y, z)) {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)), (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))} Find equivalent gate identities from the current circuit with Muls: >>> generate_equivalent_ids(x*x, return_as_muls=True) {1} >>> generate_equivalent_ids(x*y*z, return_as_muls=True) {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0), Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)} """ if isinstance(gate_seq, Number): return {Integer(1)} elif isinstance(gate_seq, Mul): gate_seq = gate_seq.args # Filter through the gate rules and keep the rules # with an empty tuple either on the left or right side # A set of equivalent gate identities eq_ids = set() gate_rules = generate_gate_rules(gate_seq) for rule in gate_rules: l, r = rule if l == (): eq_ids.add(r) elif r == (): eq_ids.add(l) if return_as_muls: convert_to_mul = lambda id_seq: Mul(*id_seq) eq_ids = set(map(convert_to_mul, eq_ids)) return eq_ids class GateIdentity(Basic): """Wrapper class for circuits that reduce to a scalar value. A gate identity is a quantum circuit such that the product of the gates in the circuit is equal to a scalar value. For example, XYZ = i, where X, Y, Z are the Pauli gates and i is the imaginary value, is considered a gate identity. Parameters ========== args : Gate tuple A variable length tuple of Gates that form an identity. Examples ======== Create a GateIdentity and look at its attributes: >>> from sympy.physics.quantum.identitysearch import GateIdentity >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> an_identity = GateIdentity(x, y, z) >>> an_identity.circuit X(0)*Y(0)*Z(0) >>> an_identity.equivalent_ids {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)), (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))} """ def __new__(cls, *args): # args should be a tuple - a variable length argument list obj = Basic.__new__(cls, *args) obj._circuit = Mul(*args) obj._rules = generate_gate_rules(args) obj._eq_ids = generate_equivalent_ids(args) return obj @property def circuit(self): return self._circuit @property def gate_rules(self): return self._rules @property def equivalent_ids(self): return self._eq_ids @property def sequence(self): return self.args def __str__(self): """Returns the string of gates in a tuple.""" return str(self.circuit) def is_degenerate(identity_set, gate_identity): """Checks if a gate identity is a permutation of another identity. Parameters ========== identity_set : set A Python set with GateIdentity objects. gate_identity : GateIdentity The GateIdentity to check for existence in the set. Examples ======== Check if the identity is a permutation of another identity: >>> from sympy.physics.quantum.identitysearch import ( ... GateIdentity, is_degenerate) >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> an_identity = GateIdentity(x, y, z) >>> id_set = {an_identity} >>> another_id = (y, z, x) >>> is_degenerate(id_set, another_id) True >>> another_id = (x, x) >>> is_degenerate(id_set, another_id) False """ # For now, just iteratively go through the set and check if the current # gate_identity is a permutation of an identity in the set for an_id in identity_set: if (gate_identity in an_id.equivalent_ids): return True return False def is_reducible(circuit, nqubits, begin, end): """Determines if a circuit is reducible by checking if its subcircuits are scalar values. Parameters ========== circuit : Gate tuple A tuple of Gates representing a circuit. The circuit to check if a gate identity is contained in a subcircuit. nqubits : int The number of qubits the circuit operates on. begin : int The leftmost gate in the circuit to include in a subcircuit. end : int The rightmost gate in the circuit to include in a subcircuit. Examples ======== Check if the circuit can be reduced: >>> from sympy.physics.quantum.identitysearch import ( ... GateIdentity, is_reducible) >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> is_reducible((x, y, z), 1, 0, 3) True Check if an interval in the circuit can be reduced: >>> is_reducible((x, y, z), 1, 1, 3) False >>> is_reducible((x, y, y), 1, 1, 3) True """ current_circuit = () # Start from the gate at "end" and go down to almost the gate at "begin" for ndx in reversed(range(begin, end)): next_gate = circuit[ndx] current_circuit = (next_gate,) + current_circuit # If a circuit as a matrix is equivalent to a scalar value if (is_scalar_matrix(current_circuit, nqubits, False)): return True return False def bfs_identity_search(gate_list, nqubits, max_depth=None, identity_only=False): """Constructs a set of gate identities from the list of possible gates. Performs a breadth first search over the space of gate identities. This allows the finding of the shortest gate identities first. Parameters ========== gate_list : list, Gate A list of Gates from which to search for gate identities. nqubits : int The number of qubits the quantum circuit operates on. max_depth : int The longest quantum circuit to construct from gate_list. identity_only : bool True to search for gate identities that reduce to identity; False to search for gate identities that reduce to a scalar. Examples ======== Find a list of gate identities: >>> from sympy.physics.quantum.identitysearch import bfs_identity_search >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> x = X(0); y = Y(0); z = Z(0) >>> bfs_identity_search([x], 1, max_depth=2) {GateIdentity(X(0), X(0))} >>> bfs_identity_search([x, y, z], 1) {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)), GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))} Find a list of identities that only equal to 1: >>> bfs_identity_search([x, y, z], 1, identity_only=True) {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)), GateIdentity(Z(0), Z(0))} """ if max_depth is None or max_depth <= 0: max_depth = len(gate_list) id_only = identity_only # Start with an empty sequence (implicitly contains an IdentityGate) queue = deque([()]) # Create an empty set of gate identities ids = set() # Begin searching for gate identities in given space. while (len(queue) > 0): current_circuit = queue.popleft() for next_gate in gate_list: new_circuit = current_circuit + (next_gate,) # Determines if a (strict) subcircuit is a scalar matrix circuit_reducible = is_reducible(new_circuit, nqubits, 1, len(new_circuit)) # In many cases when the matrix is a scalar value, # the evaluated matrix will actually be an integer if (is_scalar_matrix(new_circuit, nqubits, id_only) and not is_degenerate(ids, new_circuit) and not circuit_reducible): ids.add(GateIdentity(*new_circuit)) elif (len(new_circuit) < max_depth and not circuit_reducible): queue.append(new_circuit) return ids def random_identity_search(gate_list, numgates, nqubits): """Randomly selects numgates from gate_list and checks if it is a gate identity. If the circuit is a gate identity, the circuit is returned; Otherwise, None is returned. """ gate_size = len(gate_list) circuit = () for i in range(numgates): next_gate = gate_list[randint(0, gate_size - 1)] circuit = circuit + (next_gate,) is_scalar = is_scalar_matrix(circuit, nqubits, False) return circuit if is_scalar else None
27,458
31.266745
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/qubit.py
"""Qubits for quantum computing. Todo: * Finish implementing measurement logic. This should include POVM. * Update docstrings. * Update tests. """ from __future__ import print_function, division import math from sympy import Integer, log, Mul, Add, Pow, conjugate from sympy.core.basic import sympify from sympy.core.compatibility import string_types, range from sympy.matrices import Matrix, zeros from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.state import Ket, Bra, State from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.represent import represent from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix ) from mpmath.libmp.libintmath import bitcount __all__ = [ 'Qubit', 'QubitBra', 'IntQubit', 'IntQubitBra', 'qubit_to_matrix', 'matrix_to_qubit', 'matrix_to_density', 'measure_all', 'measure_partial', 'measure_partial_oneshot', 'measure_all_oneshot' ] #----------------------------------------------------------------------------- # Qubit Classes #----------------------------------------------------------------------------- class QubitState(State): """Base class for Qubit and QubitBra.""" #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # If we are passed a QubitState or subclass, we just take its qubit # values directly. if len(args) == 1 and isinstance(args[0], QubitState): return args[0].qubit_values # Turn strings into tuple of strings if len(args) == 1 and isinstance(args[0], string_types): args = tuple(args[0]) args = sympify(args) # Validate input (must have 0 or 1 input) for element in args: if not (element == 1 or element == 0): raise ValueError( "Qubit values must be 0 or 1, got: %r" % element) return args @classmethod def _eval_hilbert_space(cls, args): return ComplexSpace(2)**len(args) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def dimension(self): """The number of Qubits in the state.""" return len(self.qubit_values) @property def nqubits(self): return self.dimension @property def qubit_values(self): """Returns the values of the qubits as a tuple.""" return self.label #------------------------------------------------------------------------- # Special methods #------------------------------------------------------------------------- def __len__(self): return self.dimension def __getitem__(self, bit): return self.qubit_values[int(self.dimension - bit - 1)] #------------------------------------------------------------------------- # Utility methods #------------------------------------------------------------------------- def flip(self, *bits): """Flip the bit(s) given.""" newargs = list(self.qubit_values) for i in bits: bit = int(self.dimension - i - 1) if newargs[bit] == 1: newargs[bit] = 0 else: newargs[bit] = 1 return self.__class__(*tuple(newargs)) class Qubit(QubitState, Ket): """A multi-qubit ket in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). Examples ======== Create a qubit in a couple of different ways and look at their attributes: >>> from sympy.physics.quantum.qubit import Qubit >>> Qubit(0,0,0) |000> >>> q = Qubit('0101') >>> q |0101> >>> q.nqubits 4 >>> len(q) 4 >>> q.dimension 4 >>> q.qubit_values (0, 1, 0, 1) We can flip the value of an individual qubit: >>> q.flip(1) |0111> We can take the dagger of a Qubit to get a bra: >>> from sympy.physics.quantum.dagger import Dagger >>> Dagger(q) <0101| >>> type(Dagger(q)) <class 'sympy.physics.quantum.qubit.QubitBra'> Inner products work as expected: >>> ip = Dagger(q)*q >>> ip <0101|0101> >>> ip.doit() 1 """ @classmethod def dual_class(self): return QubitBra def _eval_innerproduct_QubitBra(self, bra, **hints): if self.label == bra.label: return Integer(1) else: return Integer(0) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """Represent this qubits in the computational basis (ZGate). """ format = options.get('format', 'sympy') n = 1 definite_state = 0 for it in reversed(self.qubit_values): definite_state += n*it n = n*2 result = [0]*(2**self.dimension) result[int(definite_state)] = 1 if format == 'sympy': return Matrix(result) elif format == 'numpy': import numpy as np return np.matrix(result, dtype='complex').transpose() elif format == 'scipy.sparse': from scipy import sparse return sparse.csr_matrix(result, dtype='complex').transpose() def _eval_trace(self, bra, **kwargs): indices = kwargs.get('indices', []) #sort index list to begin trace from most-significant #qubit sorted_idx = list(indices) if len(sorted_idx) == 0: sorted_idx = list(range(0, self.nqubits)) sorted_idx.sort() #trace out for each of index new_mat = self*bra for i in range(len(sorted_idx) - 1, -1, -1): # start from tracing out from leftmost qubit new_mat = self._reduced_density(new_mat, int(sorted_idx[i])) if (len(sorted_idx) == self.nqubits): #in case full trace was requested return new_mat[0] else: return matrix_to_density(new_mat) def _reduced_density(self, matrix, qubit, **options): """Compute the reduced density matrix by tracing out one qubit. The qubit argument should be of type python int, since it is used in bit operations """ def find_index_that_is_projected(j, k, qubit): bit_mask = 2**qubit - 1 return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit) old_matrix = represent(matrix, **options) old_size = old_matrix.cols #we expect the old_size to be even new_size = old_size//2 new_matrix = Matrix().zeros(new_size) for i in range(new_size): for j in range(new_size): for k in range(2): col = find_index_that_is_projected(j, k, qubit) row = find_index_that_is_projected(i, k, qubit) new_matrix[i, j] += old_matrix[row, col] return new_matrix class QubitBra(QubitState, Bra): """A multi-qubit bra in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). See also ======== Qubit: Examples using qubits """ @classmethod def dual_class(self): return Qubit class IntQubitState(QubitState): """A base class for qubits that work with binary representations.""" @classmethod def _eval_args(cls, args): # The case of a QubitState instance if len(args) == 1 and isinstance(args[0], QubitState): return QubitState._eval_args(args) # For a single argument, we construct the binary representation of # that integer with the minimal number of bits. if len(args) == 1 and args[0] > 1: #rvalues is the minimum number of bits needed to express the number rvalues = reversed(range(bitcount(abs(args[0])))) qubit_values = [(args[0] >> i) & 1 for i in rvalues] return QubitState._eval_args(qubit_values) # For two numbers, the second number is the number of bits # on which it is expressed, so IntQubit(0,5) == |00000>. elif len(args) == 2 and args[1] > 1: need = bitcount(abs(args[0])) if args[1] < need: raise ValueError( 'cannot represent %s with %s bits' % (args[0], args[1])) qubit_values = [(args[0] >> i) & 1 for i in reversed(range(args[1]))] return QubitState._eval_args(qubit_values) else: return QubitState._eval_args(args) def as_int(self): """Return the numerical value of the qubit.""" number = 0 n = 1 for i in reversed(self.qubit_values): number += n*i n = n << 1 return number def _print_label(self, printer, *args): return str(self.as_int()) def _print_label_pretty(self, printer, *args): label = self._print_label(printer, *args) return prettyForm(label) _print_label_repr = _print_label _print_label_latex = _print_label class IntQubit(IntQubitState, Qubit): """A qubit ket that store integers as binary numbers in qubit values. The differences between this class and ``Qubit`` are: * The form of the constructor. * The qubit values are printed as their corresponding integer, rather than the raw qubit values. The internal storage format of the qubit values in the same as ``Qubit``. Parameters ========== values : int, tuple If a single argument, the integer we want to represent in the qubit values. This integer will be represented using the fewest possible number of qubits. If a pair of integers, the first integer gives the integer to represent in binary form and the second integer gives the number of qubits to use. Examples ======== Create a qubit for the integer 5: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qubit import Qubit >>> q = IntQubit(5) >>> q |5> We can also create an ``IntQubit`` by passing a ``Qubit`` instance. >>> q = IntQubit(Qubit('101')) >>> q |5> >>> q.as_int() 5 >>> q.nqubits 3 >>> q.qubit_values (1, 0, 1) We can go back to the regular qubit form. >>> Qubit(q) |101> """ @classmethod def dual_class(self): return IntQubitBra def _eval_innerproduct_IntQubitBra(self, bra, **hints): return Qubit._eval_innerproduct_QubitBra(self, bra) class IntQubitBra(IntQubitState, QubitBra): """A qubit bra that store integers as binary numbers in qubit values.""" @classmethod def dual_class(self): return IntQubit #----------------------------------------------------------------------------- # Qubit <---> Matrix conversion functions #----------------------------------------------------------------------------- def matrix_to_qubit(matrix): """Convert from the matrix repr. to a sum of Qubit objects. Parameters ---------- matrix : Matrix, numpy.matrix, scipy.sparse The matrix to build the Qubit representation of. This works with sympy matrices, numpy matrices and scipy.sparse sparse matrices. Examples ======== Represent a state and then go back to its qubit form: >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit >>> from sympy.physics.quantum.gate import Z >>> from sympy.physics.quantum.represent import represent >>> q = Qubit('01') >>> matrix_to_qubit(represent(q)) |01> """ # Determine the format based on the type of the input matrix format = 'sympy' if isinstance(matrix, numpy_ndarray): format = 'numpy' if isinstance(matrix, scipy_sparse_matrix): format = 'scipy.sparse' # Make sure it is of correct dimensions for a Qubit-matrix representation. # This logic should work with sympy, numpy or scipy.sparse matrices. if matrix.shape[0] == 1: mlistlen = matrix.shape[1] nqubits = log(mlistlen, 2) ket = False cls = QubitBra elif matrix.shape[1] == 1: mlistlen = matrix.shape[0] nqubits = log(mlistlen, 2) ket = True cls = Qubit else: raise QuantumError( 'Matrix must be a row/column vector, got %r' % matrix ) if not isinstance(nqubits, Integer): raise QuantumError('Matrix must be a row/column vector of size ' '2**nqubits, got: %r' % matrix) # Go through each item in matrix, if element is non-zero, make it into a # Qubit item times the element. result = 0 for i in range(mlistlen): if ket: element = matrix[i, 0] else: element = matrix[0, i] if format == 'numpy' or format == 'scipy.sparse': element = complex(element) if element != 0.0: # Form Qubit array; 0 in bit-locations where i is 0, 1 in # bit-locations where i is 1 qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)] qubit_array.reverse() result = result + element*cls(*qubit_array) # If sympy simplified by pulling out a constant coefficient, undo that. if isinstance(result, (Mul, Add, Pow)): result = result.expand() return result def matrix_to_density(mat): """ Works by finding the eigenvectors and eigenvalues of the matrix. We know we can decompose rho by doing: sum(EigenVal*|Eigenvect><Eigenvect|) """ from sympy.physics.quantum.density import Density eigen = mat.eigenvects() args = [[matrix_to_qubit(Matrix( [vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0] if (len(args) == 0): return 0 else: return Density(*args) def qubit_to_matrix(qubit, format='sympy'): """Converts an Add/Mul of Qubit objects into it's matrix representation This function is the inverse of ``matrix_to_qubit`` and is a shorthand for ``represent(qubit)``. """ return represent(qubit, format=format) #----------------------------------------------------------------------------- # Measurement #----------------------------------------------------------------------------- def measure_all(qubit, format='sympy', normalize=True): """Perform an ensemble measurement of all qubits. Parameters ========== qubit : Qubit, Add The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_all >>> from sympy.physics.quantum.gate import H, X, Y, Z >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_all(q) [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)] """ m = qubit_to_matrix(qubit, format) if format == 'sympy': results = [] if normalize: m = m.normalized() size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size)/math.log(2)) for i in range(size): if m[i] != 0.0: results.append( (Qubit(IntQubit(i, nqubits)), m[i]*conjugate(m[i])) ) return results else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def measure_partial(qubit, bits, format='sympy', normalize=True): """Perform a partial ensemble measure on the specifed qubits. Parameters ========== qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_partial >>> from sympy.physics.quantum.gate import H, X, Y, Z >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_partial(q, (0,)) [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)] """ m = qubit_to_matrix(qubit, format) if isinstance(bits, (int, Integer)): bits = (int(bits),) if format == 'sympy': if normalize: m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function. output = [] for outcome in possible_outcomes: # Calculate probability of finding the specified bits with # given values. prob_of_outcome = 0 prob_of_outcome += (outcome.H*outcome)[0] # If the output has a chance, append it to output with found # probability. if prob_of_outcome != 0: if normalize: next_matrix = matrix_to_qubit(outcome.normalized()) else: next_matrix = matrix_to_qubit(outcome) output.append(( next_matrix, prob_of_outcome )) return output else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def measure_partial_oneshot(qubit, bits, format='sympy'): """Perform a partial oneshot measurement on the specified qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit, format) if format == 'sympy': m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function random_number = random.random() total_prob = 0 for outcome in possible_outcomes: # Calculate probability of finding the specified bits # with given values total_prob += (outcome.H*outcome)[0] if total_prob >= random_number: return matrix_to_qubit(outcome.normalized()) else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def _get_possible_outcomes(m, bits): """Get the possible states that can be produced in a measurement. Parameters ---------- m : Matrix The matrix representing the state of the system. bits : tuple, list Which bits will be measured. Returns ------- result : list The list of possible states which can occur given this measurement. These are un-normalized so we can derive the probability of finding this state by taking the inner product with itself """ # This is filled with loads of dirty binary tricks...You have been warned size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size, 2) + .1) # Number of qubits possible # Make the output states and put in output_matrices, nothing in them now. # Each state will represent a possible outcome of the measurement # Thus, output_matrices[0] is the matrix which we get when all measured # bits return 0. and output_matrices[1] is the matrix for only the 0th # bit being true output_matrices = [] for i in range(1 << len(bits)): output_matrices.append(zeros(2**nqubits, 1)) # Bitmasks will help sort how to determine possible outcomes. # When the bit mask is and-ed with a matrix-index, # it will determine which state that index belongs to bit_masks = [] for bit in bits: bit_masks.append(1 << bit) # Make possible outcome states for i in range(2**nqubits): trueness = 0 # This tells us to which output_matrix this value belongs # Find trueness for j in range(len(bit_masks)): if i & bit_masks[j]: trueness += j + 1 # Put the value in the correct output matrix output_matrices[trueness][i] = m[i] return output_matrices def measure_all_oneshot(qubit, format='sympy'): """Perform a oneshot ensemble measurement on all qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit) if format == 'sympy': m = m.normalized() random_number = random.random() total = 0 result = 0 for i in m: total += i*i.conjugate() if total > random_number: break result += 1 return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1))) else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" )
24,119
30.36541
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/cg.py
#TODO: # -Implement Clebsch-Gordan symmetries # -Improve simplification method # -Implement new simpifications """Clebsch-Gordon Coefficients.""" from __future__ import print_function, division from sympy import (Add, expand, Eq, Expr, Mul, Piecewise, Pow, sqrt, Sum, symbols, sympify, Wild) from sympy.core.compatibility import range from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j __all__ = [ 'CG', 'Wigner3j', 'Wigner6j', 'Wigner9j', 'cg_simp' ] #----------------------------------------------------------------------------- # CG Coefficients #----------------------------------------------------------------------------- class Wigner3j(Expr): """Class for the Wigner-3j symbols Wigner 3j-symbols are coefficients determined by the coupling of two angular momenta. When created, they are expressed as symbolic quantities that, for numerical parameters, can be evaluated using the ``.doit()`` method [1]_. Parameters ========== j1, m1, j2, m2, j3, m3 : Number, Symbol Terms determining the angular momentum of coupled angular momentum systems. Examples ======== Declare a Wigner-3j coefficient and calcualte its value >>> from sympy.physics.quantum.cg import Wigner3j >>> w3j = Wigner3j(6,0,4,0,2,0) >>> w3j Wigner3j(6, 0, 4, 0, 2, 0) >>> w3j.doit() sqrt(715)/143 See Also ======== CG: Clebsch-Gordan coefficients References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ is_commutative = True def __new__(cls, j1, m1, j2, m2, j3, m3): args = map(sympify, (j1, m1, j2, m2, j3, m3)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def m1(self): return self.args[1] @property def j2(self): return self.args[2] @property def m2(self): return self.args[3] @property def j3(self): return self.args[4] @property def m3(self): return self.args[5] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ((printer._print(self.j1), printer._print(self.m1)), (printer._print(self.j2), printer._print(self.m2)), (printer._print(self.j3), printer._print(self.m3))) hsep = 2 vsep = 1 maxw = [-1] * 3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(2) ]) D = None for i in range(2): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens()) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)) return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3) class CG(Wigner3j): """Class for Clebsch-Gordan coefficient Clebsch-Gordan coefficients describe the angular momentum coupling between two systems. The coefficients give the expansion of a coupled total angular momentum state and an uncoupled tensor product state. The Clebsch-Gordan coefficients are defined as [1]_: .. math :: C^{j_1,m_1}_{j_2,m_2,j_3,m_3} = \langle j_1,m_1;j_2,m_2 | j_3,m_3\\rangle Parameters ========== j1, m1, j2, m2, j3, m3 : Number, Symbol Terms determining the angular momentum of coupled angular momentum systems. Examples ======== Define a Clebsch-Gordan coefficient and evaluate its value >>> from sympy.physics.quantum.cg import CG >>> from sympy import S >>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1) >>> cg CG(3/2, 3/2, 1/2, -1/2, 1, 1) >>> cg.doit() sqrt(3)/2 See Also ======== Wigner3j: Wigner-3j symbols References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3) def _pretty(self, printer, *args): bot = printer._print_seq( (self.j1, self.m1, self.j2, self.m2), delimiter=',') top = printer._print_seq((self.j3, self.m3), delimiter=',') pad = max(top.width(), bot.width()) bot = prettyForm(*bot.left(' ')) top = prettyForm(*top.left(' ')) if not pad == bot.width(): bot = prettyForm(*bot.right(' ' * (pad - bot.width()))) if not pad == top.width(): top = prettyForm(*top.right(' ' * (pad - top.width()))) s = stringPict('C' + ' '*pad) s = prettyForm(*s.below(bot)) s = prettyForm(*s.above(top)) return s def _latex(self, printer, *args): label = map(printer._print, (self.j3, self.m3, self.j1, self.m1, self.j2, self.m2)) return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label) class Wigner6j(Expr): """Class for the Wigner-6j symbols See Also ======== Wigner3j: Wigner-3j symbols """ def __new__(cls, j1, j2, j12, j3, j, j23): args = map(sympify, (j1, j2, j12, j3, j, j23)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def j2(self): return self.args[1] @property def j12(self): return self.args[2] @property def j3(self): return self.args[3] @property def j(self): return self.args[4] @property def j23(self): return self.args[5] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ((printer._print(self.j1), printer._print(self.j3)), (printer._print(self.j2), printer._print(self.j)), (printer._print(self.j12), printer._print(self.j23))) hsep = 2 vsep = 1 maxw = [-1] * 3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(2) ]) D = None for i in range(2): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens(left='{', right='}')) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j12, self.j3, self.j, self.j23)) return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23) class Wigner9j(Expr): """Class for the Wigner-9j symbols See Also ======== Wigner3j: Wigner-3j symbols """ def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j): args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def j2(self): return self.args[1] @property def j12(self): return self.args[2] @property def j3(self): return self.args[3] @property def j4(self): return self.args[4] @property def j34(self): return self.args[5] @property def j13(self): return self.args[6] @property def j24(self): return self.args[7] @property def j(self): return self.args[8] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ( (printer._print( self.j1), printer._print(self.j3), printer._print(self.j13)), (printer._print( self.j2), printer._print(self.j4), printer._print(self.j24)), (printer._print(self.j12), printer._print(self.j34), printer._print(self.j))) hsep = 2 vsep = 1 maxw = [-1] * 3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(3) ]) D = None for i in range(3): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens(left='{', right='}')) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)) return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j) def cg_simp(e): """Simplify and combine CG coefficients This function uses various symmetry and properties of sums and products of Clebsch-Gordan coefficients to simplify statements involving these terms [1]_. Examples ======== Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to 2*a+1 >>> from sympy.physics.quantum.cg import CG, cg_simp >>> a = CG(1,1,0,0,1,1) >>> b = CG(1,0,0,0,1,0) >>> c = CG(1,-1,0,0,1,-1) >>> cg_simp(a+b+c) 3 See Also ======== CG: Clebsh-Gordan coefficients References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ if isinstance(e, Add): return _cg_simp_add(e) elif isinstance(e, Sum): return _cg_simp_sum(e) elif isinstance(e, Mul): return Mul(*[cg_simp(arg) for arg in e.args]) elif isinstance(e, Pow): return Pow(cg_simp(e.base), e.exp) else: return e def _cg_simp_add(e): #TODO: Improve simplification method """Takes a sum of terms involving Clebsch-Gordan coefficients and simplifies the terms. First, we create two lists, cg_part, which is all the terms involving CG coefficients, and other_part, which is all other terms. The cg_part list is then passed to the simplification methods, which return the new cg_part and any additional terms that are added to other_part """ cg_part = [] other_part = [] e = expand(e) for arg in e.args: if arg.has(CG): if isinstance(arg, Sum): other_part.append(_cg_simp_sum(arg)) elif isinstance(arg, Mul): terms = 1 for term in arg.args: if isinstance(term, Sum): terms *= _cg_simp_sum(term) else: terms *= term if terms.has(CG): cg_part.append(terms) else: other_part.append(terms) else: cg_part.append(arg) else: other_part.append(arg) cg_part, other = _check_varsh_871_1(cg_part) other_part.append(other) cg_part, other = _check_varsh_871_2(cg_part) other_part.append(other) cg_part, other = _check_varsh_872_9(cg_part) other_part.append(other) return Add(*cg_part) + Add(*other_part) def _check_varsh_871_1(term_list): # Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0) a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt')) expr = lt*CG(a, alpha, b, 0, a, alpha) simp = (2*a + 1)*KroneckerDelta(b, 0) sign = lt/abs(lt) build_expr = 2*a + 1 index_expr = a + alpha return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr) def _check_varsh_871_2(term_list): # Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a)) a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt')) expr = lt*CG(a, alpha, a, -alpha, c, 0) simp = sqrt(2*a + 1)*KroneckerDelta(c, 0) sign = (-1)**(a - alpha)*lt/abs(lt) build_expr = 2*a + 1 index_expr = a + alpha return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr) def _check_varsh_872_9(term_list): # Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b)) a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, ( 'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt')) # Case alpha==alphap, beta==betap # For numerical alpha,beta expr = lt*CG(a, alpha, b, beta, c, gamma)**2 simp = 1 sign = lt/abs(lt) x = abs(a - b) y = abs(alpha + beta) build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x)) index_expr = a + b - c term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr) # For symbolic alpha,beta x = abs(a - b) y = a + b build_expr = (y + 1 - x)*(x + y + 1) index_expr = (c - x)*(x + c) + c + gamma term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr) # Case alpha!=alphap or beta!=betap # Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term # For numerical alpha,alphap,beta,betap expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma) simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap) sign = sympify(1) x = abs(a - b) y = abs(alpha + beta) build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x)) index_expr = a + b - c term_list, other3 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr) # For symbolic alpha,alphap,beta,betap x = abs(a - b) y = a + b build_expr = (y + 1 - x)*(x + y + 1) index_expr = (c - x)*(x + c) + c + gamma term_list, other4 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr) return term_list, other1 + other2 + other4 def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr): """ Checks for simplifications that can be made, returning a tuple of the simplified list of terms and any terms generated by simplification. Parameters ========== expr: expression The expression with Wild terms that will be matched to the terms in the sum simp: expression The expression with Wild terms that is substituted in place of the CG terms in the case of simplification sign: expression The expression with Wild terms denoting the sign that is on expr that must match lt: expression The expression with Wild terms that gives the leading term of the matched expr term_list: list A list of all of the terms is the sum to be simplified variables: list A list of all the variables that appears in expr dep_variables: list A list of the variables that must match for all the terms in the sum, i.e. the dependant variables build_index_expr: expression Expression with Wild terms giving the number of elements in cg_index index_expr: expression Expression with Wild terms giving the index terms have when storing them to cg_index """ other_part = 0 i = 0 while i < len(term_list): sub_1 = _check_cg(term_list[i], expr, len(variables)) if sub_1 is None: i += 1 continue if not sympify(build_index_expr.subs(sub_1)).is_number: i += 1 continue sub_dep = [(x, sub_1[x]) for x in dep_variables] cg_index = [None] * build_index_expr.subs(sub_1) for j in range(i, len(term_list)): sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep))) if sub_2 is None: continue if not sympify(index_expr.subs(sub_dep).subs(sub_2)).is_number: continue cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2) if all(i is not None for i in cg_index): min_lt = min(*[ abs(term[2]) for term in cg_index ]) indicies = [ term[0] for term in cg_index] indicies.sort() indicies.reverse() [ term_list.pop(j) for j in indicies ] for term in cg_index: if abs(term[2]) > min_lt: term_list.append( (term[2] - min_lt*term[3]) * term[1] ) other_part += min_lt * (sign*simp).subs(sub_1) else: i += 1 return term_list, other_part def _check_cg(cg_term, expr, length, sign=None): """Checks whether a term matches the given expression""" # TODO: Check for symmetries matches = cg_term.match(expr) if matches is None: return if sign is not None: if not isinstance(sign, tuple): raise TypeError('sign must be a tuple') if not sign[0] == (sign[1]).subs(matches): return if len(matches) == length: return matches def _cg_simp_sum(e): e = _check_varsh_sum_871_1(e) e = _check_varsh_sum_871_2(e) e = _check_varsh_sum_872_4(e) return e def _check_varsh_sum_871_1(e): a = Wild('a') alpha = symbols('alpha') b = Wild('b') match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a))) if match is not None and len(match) == 2: return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match) return e def _check_varsh_sum_871_2(e): a = Wild('a') alpha = symbols('alpha') c = Wild('c') match = e.match( Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a))) if match is not None and len(match) == 2: return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match) return e def _check_varsh_sum_872_4(e): a = Wild('a') alpha = Wild('alpha') b = Wild('b') beta = Wild('beta') c = Wild('c') cp = Wild('cp') gamma = Wild('gamma') gammap = Wild('gammap') match1 = e.match(Sum(CG(a, alpha, b, beta, c, gamma)*CG( a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) if match1 is not None and len(match1) == 8: return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1) match2 = e.match(Sum( CG(a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) if match2 is not None and len(match2) == 6: return 1 return e def _cg_list(term): if isinstance(term, CG): return (term,), 1, 1 cg = [] coeff = 1 if not (isinstance(term, Mul) or isinstance(term, Pow)): raise NotImplementedError('term must be CG, Add, Mul or Pow') if isinstance(term, Pow) and sympify(term.exp).is_number: if sympify(term.exp).is_number: [ cg.append(term.base) for _ in range(term.exp) ] else: return (term,), 1, 1 if isinstance(term, Mul): for arg in term.args: if isinstance(arg, CG): cg.append(arg) else: coeff *= arg return cg, coeff, coeff/abs(coeff)
22,514
30.141079
185
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/sho1d.py
"""Simple Harmonic Oscillator 1-Dimension""" from __future__ import print_function, division from sympy import sqrt, I, Symbol, Integer, S from sympy.core.compatibility import range from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.state import Bra, Ket, State from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.cartesian import X, Px from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.matrixutils import matrix_zeros #------------------------------------------------------------------------------ class SHOOp(Operator): """A base class for the SHO Operators. We are limiting the number of arguments to be 1. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) == 1: return args else: raise ValueError("Too many arguments") @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) class RaisingOp(SHOOp): """The Raising Operator or a^dagger. When a^dagger acts on a state it raises the state up by one. Taking the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger can be rewritten in terms of position and momentum. We can represent a^dagger as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Raising Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns 'a': >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum import Dagger >>> ad = RaisingOp('a') >>> ad.rewrite('xp').doit() sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(ad) a Taking the commutator of a^dagger with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> N = NumberOp('N') >>> Commutator(ad, a).doit() -1 >>> Commutator(ad, N).doit() -RaisingOp(a) Apply a^dagger to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet >>> ad = RaisingOp('a') >>> k = SHOKet('k') >>> qapply(ad*k) sqrt(k + 1)*|k + 1> Matrix Representation >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum.represent import represent >>> ad = RaisingOp('a') >>> represent(ad, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [1, 0, 0, 0], [0, sqrt(2), 0, 0], [0, 0, sqrt(3), 0]]) """ def _eval_rewrite_as_xp(self, *args): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( Integer(-1)*I*Px + m*omega*X) def _eval_adjoint(self): return LoweringOp(*self.args) def _eval_commutator_LoweringOp(self, other): return Integer(-1) def _eval_commutator_NumberOp(self, other): return Integer(-1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n + Integer(1) return sqrt(temp)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format','sympy') spmatrix = options.get('spmatrix', 'csr') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i + 1, i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix #-------------------------------------------------------------------------- # Printing Methods #-------------------------------------------------------------------------- def _print_contents(self, printer, *args): arg0 = printer._print(self.args[0], *args) return '%s(%s)' % (self.__class__.__name__, arg0) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) pform = pform**prettyForm(u'\N{DAGGER}') return pform def _print_contents_latex(self, printer, *args): arg = printer._print(self.args[0]) return '%s^{\\dag}' % arg class LoweringOp(SHOOp): """The Lowering Operator or 'a'. When 'a' acts on a state it lowers the state up by one. Taking the adjoint of 'a' returns a^dagger, the Raising Operator. 'a' can be rewritten in terms of position and momentum. We can represent 'a' as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Lowering Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns a^dagger: >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum import Dagger >>> a = LoweringOp('a') >>> a.rewrite('xp').doit() sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(a) RaisingOp(a) Taking the commutator of 'a' with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> a = LoweringOp('a') >>> ad = RaisingOp('a') >>> N = NumberOp('N') >>> Commutator(a, ad).doit() 1 >>> Commutator(a, N).doit() a Apply 'a' to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet('k') >>> qapply(a*k) sqrt(k)*|k - 1> Taking 'a' of the lowest state will return 0: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet(0) >>> qapply(a*k) 0 Matrix Representation >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum.represent import represent >>> a = LoweringOp('a') >>> represent(a, basis=N, ndim=4, format='sympy') Matrix([ [0, 1, 0, 0], [0, 0, sqrt(2), 0], [0, 0, 0, sqrt(3)], [0, 0, 0, 0]]) """ def _eval_rewrite_as_xp(self, *args): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( I*Px + m*omega*X) def _eval_adjoint(self): return RaisingOp(*self.args) def _eval_commutator_RaisingOp(self, other): return Integer(1) def _eval_commutator_NumberOp(self, other): return Integer(1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n - Integer(1) if ket.n == Integer(0): return Integer(0) else: return sqrt(ket.n)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') spmatrix = options.get('spmatrix', 'csr') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i,i + 1] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class NumberOp(SHOOp): """The Number Operator is simply a^dagger*a It is often useful to write a^dagger*a as simply the Number Operator because the Number Operator commutes with the Hamiltonian. And can be expressed using the Number Operator. Also the Number Operator can be applied to states. We can represent the Number Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Number Operator and rewrite it in terms of the ladder operators, position and momentum operators, and Hamiltonian: >>> from sympy.physics.quantum.sho1d import NumberOp >>> N = NumberOp('N') >>> N.rewrite('a').doit() RaisingOp(a)*a >>> N.rewrite('xp').doit() -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega) >>> N.rewrite('H').doit() -1/2 + H/(hbar*omega) Take the Commutator of the Number Operator with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> N = NumberOp('N') >>> H = Hamiltonian('H') >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> Commutator(N,H).doit() 0 >>> Commutator(N,ad).doit() RaisingOp(a) >>> Commutator(N,a).doit() -a Apply the Number Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet >>> N = NumberOp('N') >>> k = SHOKet('k') >>> qapply(N*k) k*|k> Matrix Representation >>> from sympy.physics.quantum.sho1d import NumberOp >>> from sympy.physics.quantum.represent import represent >>> N = NumberOp('N') >>> represent(N, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) """ def _eval_rewrite_as_a(self, *args): return ad*a def _eval_rewrite_as_xp(self, *args): return (Integer(1)/(Integer(2)*m*hbar*omega))*(Px**2 + ( m*omega*X)**2) - Integer(1)/Integer(2) def _eval_rewrite_as_H(self, *args): return H/(hbar*omega) - Integer(1)/Integer(2) def _apply_operator_SHOKet(self, ket): return ket.n*ket def _eval_commutator_Hamiltonian(self, other): return Integer(0) def _eval_commutator_RaisingOp(self, other): return other def _eval_commutator_LoweringOp(self, other): return Integer(-1)*other def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') spmatrix = options.get('spmatrix', 'csr') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class Hamiltonian(SHOOp): """The Hamiltonian Operator. The Hamiltonian is used to solve the time-independent Schrodinger equation. The Hamiltonian can be expressed using the ladder operators, as well as by position and momentum. We can represent the Hamiltonian Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Hamiltonian Operator and rewrite it in terms of the ladder operators, position and momentum, and the Number Operator: >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> H = Hamiltonian('H') >>> H.rewrite('a').doit() hbar*omega*(1/2 + RaisingOp(a)*a) >>> H.rewrite('xp').doit() (m**2*omega**2*X**2 + Px**2)/(2*m) >>> H.rewrite('N').doit() hbar*omega*(1/2 + N) Take the Commutator of the Hamiltonian and the Number Operator: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp >>> H = Hamiltonian('H') >>> N = NumberOp('N') >>> Commutator(H,N).doit() 0 Apply the Hamiltonian Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet >>> H = Hamiltonian('H') >>> k = SHOKet('k') >>> qapply(H*k) hbar*k*omega*|k> + hbar*omega*|k>/2 Matrix Representation >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> from sympy.physics.quantum.represent import represent >>> H = Hamiltonian('H') >>> represent(H, basis=N, ndim=4, format='sympy') Matrix([ [hbar*omega/2, 0, 0, 0], [ 0, 3*hbar*omega/2, 0, 0], [ 0, 0, 5*hbar*omega/2, 0], [ 0, 0, 0, 7*hbar*omega/2]]) """ def _eval_rewrite_as_a(self, *args): return hbar*omega*(ad*a + Integer(1)/Integer(2)) def _eval_rewrite_as_xp(self, *args): return (Integer(1)/(Integer(2)*m))*(Px**2 + (m*omega*X)**2) def _eval_rewrite_as_N(self, *args): return hbar*omega*(N + Integer(1)/Integer(2)) def _apply_operator_SHOKet(self, ket): return (hbar*omega*(ket.n + Integer(1)/Integer(2)))*ket def _eval_commutator_NumberOp(self, other): return Integer(0) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') spmatrix = options.get('spmatrix', 'csr') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i + Integer(1)/Integer(2) if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return hbar*omega*matrix #------------------------------------------------------------------------------ class SHOState(State): """State class for SHO states""" @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) @property def n(self): return self.args[0] class SHOKet(SHOState, Ket): """1D eigenket. Inherits from SHOState and Ket. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Ket's know about their associated bra: >>> from sympy.physics.quantum.sho1d import SHOKet >>> k = SHOKet('k') >>> k.dual <k| >>> k.dual_class() <class 'sympy.physics.quantum.sho1d.SHOBra'> Take the Inner Product with a bra: >>> from sympy.physics.quantum import InnerProduct >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra >>> k = SHOKet('k') >>> b = SHOBra('b') >>> InnerProduct(b,k).doit() KroneckerDelta(b, k) Vector representation of a numerical state ket: >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp >>> from sympy.physics.quantum.represent import represent >>> k = SHOKet(3) >>> N = NumberOp('N') >>> represent(k, basis=N, ndim=4) Matrix([ [0], [0], [0], [1]]) """ @classmethod def dual_class(self): return SHOBra def _eval_innerproduct_SHOBra(self, bra, **hints): result = KroneckerDelta(self.n, bra.n) return result def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(ndim_info, 1, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") value = Integer(1) if format == 'scipy.sparse': vector[int(self.n), 0] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[int(self.n), 0] = 1.0 else: vector[self.n, 0] = Integer(1) return vector else: return ValueError("Not Numerical State") class SHOBra(SHOState, Bra): """A time-independent Bra in SHO. Inherits from SHOState and Bra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Bra's know about their associated ket: >>> from sympy.physics.quantum.sho1d import SHOBra >>> b = SHOBra('b') >>> b.dual |b> >>> b.dual_class() <class 'sympy.physics.quantum.sho1d.SHOKet'> Vector representation of a numerical state bra: >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp >>> from sympy.physics.quantum.represent import represent >>> b = SHOBra(3) >>> N = NumberOp('N') >>> represent(b, basis=N, ndim=4) Matrix([[0, 0, 0, 1]]) """ @classmethod def dual_class(self): return SHOKet def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(1, ndim_info, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[0, int(self.n)] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[0, int(self.n)] = 1.0 else: vector[0, self.n] = Integer(1) return vector else: return ValueError("Not Numerical State") ad = RaisingOp('a') a = LoweringOp('a') H = Hamiltonian('H') N = NumberOp('N') omega = Symbol('omega') m = Symbol('m')
21,085
29.782482
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tensorproduct.py
"""Abstract tensor product.""" from __future__ import print_function, division from sympy import Expr, Add, Mul, Matrix, Pow, sympify from sympy.core.compatibility import range from sympy.core.trace import Tr from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, matrix_tensor_product ) __all__ = [ 'TensorProduct', 'tensor_product_simp' ] #----------------------------------------------------------------------------- # Tensor product #----------------------------------------------------------------------------- _combined_printing = False def combined_tensor_printing(combined): """Set flag controlling whether tensor products of states should be printed as a combined bra/ket or as an explicit tensor product of different bra/kets. This is a global setting for all TensorProduct class instances. Parameters ---------- combine : bool When true, tensor product states are combined into one ket/bra, and when false explicit tensor product notation is used between each ket/bra. """ global _combined_printing _combined_printing = combined class TensorProduct(Expr): """The tensor product of two or more arguments. For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker or tensor product matrix. For other objects a symbolic ``TensorProduct`` instance is returned. The tensor product is a non-commutative multiplication that is used primarily with operators and states in quantum mechanics. Currently, the tensor product distinguishes between commutative and non- commutative arguments. Commutative arguments are assumed to be scalars and are pulled out in front of the ``TensorProduct``. Non-commutative arguments remain in the resulting ``TensorProduct``. Parameters ========== args : tuple A sequence of the objects to take the tensor product of. Examples ======== Start with a simple tensor product of sympy matrices:: >>> from sympy import I, Matrix, symbols >>> from sympy.physics.quantum import TensorProduct >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> TensorProduct(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> TensorProduct(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) We can also construct tensor products of non-commutative symbols: >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> tp = TensorProduct(A, B) >>> tp AxB We can take the dagger of a tensor product (note the order does NOT reverse like the dagger of a normal product): >>> from sympy.physics.quantum import Dagger >>> Dagger(tp) Dagger(A)xDagger(B) Expand can be used to distribute a tensor product across addition: >>> C = Symbol('C',commutative=False) >>> tp = TensorProduct(A+B,C) >>> tp (A + B)xC >>> tp.expand(tensorproduct=True) AxC + BxC """ is_commutative = False def __new__(cls, *args): if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)): return matrix_tensor_product(*args) c_part, new_args = cls.flatten(sympify(args)) c_part = Mul(*c_part) if len(new_args) == 0: return c_part elif len(new_args) == 1: return c_part * new_args[0] else: tp = Expr.__new__(cls, *new_args) return c_part * tp @classmethod def flatten(cls, args): # TODO: disallow nested TensorProducts. c_part = [] nc_parts = [] for arg in args: cp, ncp = arg.args_cnc() c_part.extend(list(cp)) nc_parts.append(Mul._from_args(ncp)) return c_part, nc_parts def _eval_adjoint(self): return TensorProduct(*[Dagger(i) for i in self.args]) def _eval_rewrite(self, pattern, rule, **hints): sargs = self.args terms = [t._eval_rewrite(pattern, rule, **hints) for t in sargs] return TensorProduct(*terms).expand(tensorproduct=True) def _sympystr(self, printer, *args): from sympy.printing.str import sstr length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Pow, Mul)): s = s + '(' s = s + sstr(self.args[i]) if isinstance(self.args[i], (Add, Pow, Mul)): s = s + ')' if i != length - 1: s = s + 'x' return s def _pretty(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print('', *args) length_i = len(self.args[i].args) for j in range(length_i): part_pform = printer._print(self.args[i].args[j], *args) next_pform = prettyForm(*next_pform.right(part_pform)) if j != length_i - 1: next_pform = prettyForm(*next_pform.right(', ')) if len(self.args[i].args) > 1: next_pform = prettyForm( *next_pform.parens(left='{', right='}')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: pform = prettyForm(*pform.right(',' + ' ')) pform = prettyForm(*pform.left(self.args[0].lbracket)) pform = prettyForm(*pform.right(self.args[0].rbracket)) return pform length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(u'\N{N-ARY CIRCLED TIMES OPERATOR}' + u' ')) else: pform = prettyForm(*pform.right('x' + ' ')) return pform def _latex(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): def _label_wrap(label, nlabels): return label if nlabels == 1 else r"\left\{%s\right\}" % label s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args), len(arg.args)) for arg in self.args]) return r"{%s%s%s}" % (self.args[0].lbracket_latex, s, self.args[0].rbracket_latex) length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Mul)): s = s + '\\left(' # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. s = s + '{' + printer._print(self.args[i], *args) + '}' if isinstance(self.args[i], (Add, Mul)): s = s + '\\right)' if i != length - 1: s = s + '\\otimes ' return s def doit(self, **hints): return TensorProduct(*[item.doit(**hints) for item in self.args]) def _eval_expand_tensorproduct(self, **hints): """Distribute TensorProducts across addition.""" args = self.args add_args = [] stop = False for i in range(len(args)): if isinstance(args[i], Add): for aa in args[i].args: tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:]) if isinstance(tp, TensorProduct): tp = tp._eval_expand_tensorproduct() add_args.append(tp) break if add_args: return Add(*add_args) else: return self def _eval_trace(self, **kwargs): indices = kwargs.get('indices', None) exp = tensor_product_simp(self) if indices is None or len(indices) == 0: return Mul(*[Tr(arg).doit() for arg in exp.args]) else: return Mul(*[Tr(value).doit() if idx in indices else value for idx, value in enumerate(exp.args)]) def tensor_product_simp_Mul(e): """Simplify a Mul with TensorProducts. Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s to a ``TensorProduct`` of ``Muls``. It currently only works for relatively simple cases where the initial ``Mul`` only has scalars and raw ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of ``TensorProduct``s. Parameters ========== e : Expr A ``Mul`` of ``TensorProduct``s to be simplified. Returns ======= e : Expr A ``TensorProduct`` of ``Mul``s. Examples ======== This is an example of the type of simplification that this function performs:: >>> from sympy.physics.quantum.tensorproduct import \ tensor_product_simp_Mul, TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp_Mul(e) (A*C)x(B*D) """ # TODO: This won't work with Muls that have other composites of # TensorProducts, like an Add, Pow, Commutator, etc. # TODO: This only works for the equivalent of single Qbit gates. if not isinstance(e, Mul): return e c_part, nc_part = e.args_cnc() n_nc = len(nc_part) if n_nc == 0 or n_nc == 1: return e elif e.has(TensorProduct): current = nc_part[0] if not isinstance(current, TensorProduct): raise TypeError('TensorProduct expected, got: %r' % current) n_terms = len(current.args) new_args = list(current.args) for next in nc_part[1:]: # TODO: check the hilbert spaces of next and current here. if isinstance(next, TensorProduct): if n_terms != len(next.args): raise QuantumError( 'TensorProducts of different lengths: %r and %r' % (current, next) ) for i in range(len(new_args)): new_args[i] = new_args[i] * next.args[i] else: # this won't quite work as we don't want next in the # TensorProduct for i in range(len(new_args)): new_args[i] = new_args[i] * next current = next return Mul(*c_part) * TensorProduct(*new_args) else: return e def tensor_product_simp(e, **hints): """Try to simplify and combine TensorProducts. In general this will try to pull expressions inside of ``TensorProducts``. It currently only works for relatively simple cases where the products have only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators`` of ``TensorProducts``. It is best to see what it does by showing examples. Examples ======== >>> from sympy.physics.quantum import tensor_product_simp >>> from sympy.physics.quantum import TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) First see what happens to products of tensor products: >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp(e) (A*C)x(B*D) This is the core logic of this function, and it works inside, powers, sums, commutators and anticommutators as well: >>> tensor_product_simp(e**2) (A*C)x(B*D)**2 """ if isinstance(e, Add): return Add(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, Pow): return tensor_product_simp(e.base) ** e.exp elif isinstance(e, Mul): return tensor_product_simp_Mul(e) elif isinstance(e, Commutator): return Commutator(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, AntiCommutator): return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args]) else: return e
13,565
33.431472
96
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/operatorset.py
""" A module for mapping operators to their corresponding eigenstates and vice versa It contains a global dictionary with eigenstate-operator pairings. If a new state-operator pair is created, this dictionary should be updated as well. It also contains functions operators_to_state and state_to_operators for mapping between the two. These can handle both classes and instances of operators and states. See the individual function descriptions for details. TODO List: - Update the dictionary with a complete list of state-operator pairs """ from __future__ import print_function, division from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet, PositionKet3D) from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.state import StateBase, BraBase, Ket from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet, JzKet) __all__ = [ 'operators_to_state', 'state_to_operators' ] #state_mapping stores the mappings between states and their associated #operators or tuples of operators. This should be updated when new #classes are written! Entries are of the form PxKet : PxOp or #something like 3DKet : (ROp, ThetaOp, PhiOp) #frozenset is used so that the reverse mapping can be made #(regular sets are not hashable because they are mutable state_mapping = { JxKet: frozenset((J2Op, JxOp)), JyKet: frozenset((J2Op, JyOp)), JzKet: frozenset((J2Op, JzOp)), Ket: Operator, PositionKet3D: frozenset((XOp, YOp, ZOp)), PxKet: PxOp, XKet: XOp } op_mapping = dict((v, k) for k, v in state_mapping.items()) def operators_to_state(operators, **options): """ Returns the eigenstate of the given operator or set of operators A global function for mapping operator classes to their associated states. It takes either an Operator or a set of operators and returns the state associated with these. This function can handle both instances of a given operator or just the class itself (i.e. both XOp() and XOp) There are multiple use cases to consider: 1) A class or set of classes is passed: First, we try to instantiate default instances for these operators. If this fails, then the class is simply returned. If we succeed in instantiating default instances, then we try to call state._operators_to_state on the operator instances. If this fails, the class is returned. Otherwise, the instance returned by _operators_to_state is returned. 2) An instance or set of instances is passed: In this case, state._operators_to_state is called on the instances passed. If this fails, a state class is returned. If the method returns an instance, that instance is returned. In both cases, if the operator class or set does not exist in the state_mapping dictionary, None is returned. Parameters ========== arg: Operator or set The class or instance of the operator or set of operators to be mapped to a state Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp >>> from sympy.physics.quantum.operatorset import operators_to_state >>> from sympy.physics.quantum.operator import Operator >>> operators_to_state(XOp) |x> >>> operators_to_state(XOp()) |x> >>> operators_to_state(PxOp) |px> >>> operators_to_state(PxOp()) |px> >>> operators_to_state(Operator) |psi> >>> operators_to_state(Operator()) |psi> """ if not (isinstance(operators, Operator) or isinstance(operators, set) or issubclass(operators, Operator)): raise NotImplementedError("Argument is not an Operator or a set!") if isinstance(operators, set): for s in operators: if not (isinstance(s, Operator) or issubclass(s, Operator)): raise NotImplementedError("Set is not all Operators!") ops = frozenset(operators) if ops in op_mapping: # ops is a list of classes in this case #Try to get an object from default instances of the #operators...if this fails, return the class try: op_instances = [op() for op in ops] ret = _get_state(op_mapping[ops], set(op_instances), **options) except NotImplementedError: ret = op_mapping[ops] return ret else: tmp = [type(o) for o in ops] classes = frozenset(tmp) if classes in op_mapping: ret = _get_state(op_mapping[classes], ops, **options) else: ret = None return ret else: if operators in op_mapping: try: op_instance = operators() ret = _get_state(op_mapping[operators], op_instance, **options) except NotImplementedError: ret = op_mapping[operators] return ret elif type(operators) in op_mapping: return _get_state(op_mapping[type(operators)], operators, **options) else: return None def state_to_operators(state, **options): """ Returns the operator or set of operators corresponding to the given eigenstate A global function for mapping state classes to their associated operators or sets of operators. It takes either a state class or instance. This function can handle both instances of a given state or just the class itself (i.e. both XKet() and XKet) There are multiple use cases to consider: 1) A state class is passed: In this case, we first try instantiating a default instance of the class. If this succeeds, then we try to call state._state_to_operators on that instance. If the creation of the default instance or if the calling of _state_to_operators fails, then either an operator class or set of operator classes is returned. Otherwise, the appropriate operator instances are returned. 2) A state instance is returned: Here, state._state_to_operators is called for the instance. If this fails, then a class or set of operator classes is returned. Otherwise, the instances are returned. In either case, if the state's class does not exist in state_mapping, None is returned. Parameters ========== arg: StateBase class or instance (or subclasses) The class or instance of the state to be mapped to an operator or set of operators Examples ======== >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra >>> from sympy.physics.quantum.operatorset import state_to_operators >>> from sympy.physics.quantum.state import Ket, Bra >>> state_to_operators(XKet) X >>> state_to_operators(XKet()) X >>> state_to_operators(PxKet) Px >>> state_to_operators(PxKet()) Px >>> state_to_operators(PxBra) Px >>> state_to_operators(XBra) X >>> state_to_operators(Ket) O >>> state_to_operators(Bra) O """ if not (isinstance(state, StateBase) or issubclass(state, StateBase)): raise NotImplementedError("Argument is not a state!") if state in state_mapping: # state is a class state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state]), **options) except (NotImplementedError, TypeError): ret = state_mapping[state] elif type(state) in state_mapping: ret = _get_ops(state, _make_set(state_mapping[type(state)]), **options) elif isinstance(state, BraBase) and state.dual_class() in state_mapping: ret = _get_ops(state, _make_set(state_mapping[state.dual_class()])) elif issubclass(state, BraBase) and state.dual_class() in state_mapping: state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state.dual_class()])) except (NotImplementedError, TypeError): ret = state_mapping[state.dual_class()] else: ret = None return _make_set(ret) def _make_default(expr): try: ret = expr() except Exception: ret = expr return ret def _get_state(state_class, ops, **options): # Try to get a state instance from the operator INSTANCES. # If this fails, get the class try: ret = state_class._operators_to_state(ops, **options) except NotImplementedError: ret = _make_default(state_class) return ret def _get_ops(state_inst, op_classes, **options): # Try to get operator instances from the state INSTANCE. # If this fails, just return the classes try: ret = state_inst._state_to_operators(op_classes, **options) except NotImplementedError: if isinstance(op_classes, (set, tuple, frozenset)): ret = tuple(_make_default(x) for x in op_classes) else: ret = _make_default(op_classes) if isinstance(ret, set) and len(ret) == 1: return ret[0] return ret def _make_set(ops): if isinstance(ops, (tuple, list, frozenset)): return set(ops) else: return ops
9,480
32.860714
80
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/anticommutator.py
"""The anti-commutator: ``{A,B} = A*B + B*A``.""" from __future__ import print_function, division from sympy import S, Expr, Mul, Integer from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.dagger import Dagger __all__ = [ 'AntiCommutator' ] #----------------------------------------------------------------------------- # Anti-commutator #----------------------------------------------------------------------------- class AntiCommutator(Expr): """The standard anticommutator, in an unevaluated state. Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``. This class returns the anticommutator in an unevaluated form. To evaluate the anticommutator, use the ``.doit()`` method. Cannonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The arguments of the anticommutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``. Parameters ========== A : Expr The first argument of the anticommutator {A,B}. B : Expr The second argument of the anticommutator {A,B}. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum import AntiCommutator >>> from sympy.physics.quantum import Operator, Dagger >>> x, y = symbols('x,y') >>> A = Operator('A') >>> B = Operator('B') Create an anticommutator and use ``doit()`` to multiply them out. >>> ac = AntiCommutator(A,B); ac {A,B} >>> ac.doit() A*B + B*A The commutator orders it arguments in canonical order: >>> ac = AntiCommutator(B,A); ac {A,B} Commutative constants are factored out: >>> AntiCommutator(3*x*A,x*y*B) 3*x**2*y*{A,B} Adjoint operations applied to the anticommutator are properly applied to the arguments: >>> Dagger(AntiCommutator(A,B)) {Dagger(A),Dagger(B)} References ========== .. [1] http://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return Integer(2)*a**2 if a.is_commutative or b.is_commutative: return Integer(2)*a*b # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments #The Commutator [A,B] is on canonical form if A < B. if a.compare(b) == 1: return cls(b, a) def doit(self, **hints): """ Evaluate anticommutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_anticommutator(B, **hints) except NotImplementedError: try: comm = B._eval_anticommutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B + B*A).doit(**hints) def _eval_adjoint(self): return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "{%s,%s}" % (self.args[0], self.args[1]) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right((prettyForm(u',')))) pform = prettyForm(*pform.right((printer._print(self.args[1], *args)))) pform = prettyForm(*pform.parens(left='{', right='}')) return pform def _latex(self, printer, *args): return "\\left\\{%s,%s\\right\\}" % tuple([ printer._print(arg, *args) for arg in self.args])
4,324
28.827586
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/density.py
from __future__ import print_function, division from itertools import product from sympy import Tuple, Add, Mul, Matrix, log, expand, Rational from sympy.core.trace import Tr from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.operator import HermitianOperator from sympy.physics.quantum.represent import represent from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy from sympy.physics.quantum.tensorproduct import TensorProduct, tensor_product_simp class Density(HermitianOperator): """Density operator for representing mixed states. TODO: Density operator support for Qubits Parameters ========== values : tuples/lists Each tuple/list should be of form (state, prob) or [state,prob] Examples ======== Create a density operator with 2 states represented by Kets. >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d 'Density'((|0>, 0.5),(|1>, 0.5)) """ @classmethod def _eval_args(cls, args): # call this to qsympify the args args = super(Density, cls)._eval_args(args) for arg in args: # Check if arg is a tuple if not (isinstance(arg, Tuple) and len(arg) == 2): raise ValueError("Each argument should be of form [state,prob]" " or ( state, prob )") return args def states(self): """Return list of all states. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.states() (|0>, |1>) """ return Tuple(*[arg[0] for arg in self.args]) def probs(self): """Return list of all probabilities. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.probs() (0.5, 0.5) """ return Tuple(*[arg[1] for arg in self.args]) def get_state(self, index): """Return specfic state by index. Parameters ========== index : index of state to be returned Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.states()[1] |1> """ state = self.args[index][0] return state def get_prob(self, index): """Return probability of specific state by index. Parameters =========== index : index of states whose probability is returned. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.probs()[1] 0.500000000000000 """ prob = self.args[index][1] return prob def apply_op(self, op): """op will operate on each individual state. Parameters ========== op : Operator Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> from sympy.physics.quantum.operator import Operator >>> A = Operator('A') >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.apply_op(A) 'Density'((A*|0>, 0.5),(A*|1>, 0.5)) """ new_args = [(op*state, prob) for (state, prob) in self.args] return Density(*new_args) def doit(self, **hints): """Expand the density operator into an outer product format. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> from sympy.physics.quantum.operator import Operator >>> A = Operator('A') >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.doit() 0.5*|0><0| + 0.5*|1><1| """ terms = [] for (state, prob) in self.args: state = state.expand() # needed to break up (a+b)*c if (isinstance(state, Add)): for arg in product(state.args, repeat=2): terms.append(prob * self._generate_outer_prod(arg[0], arg[1])) else: terms.append(prob * self._generate_outer_prod(state, state)) return Add(*terms) def _generate_outer_prod(self, arg1, arg2): c_part1, nc_part1 = arg1.args_cnc() c_part2, nc_part2 = arg2.args_cnc() if ( len(nc_part1) == 0 or len(nc_part2) == 0 ): raise ValueError('Atleast one-pair of' ' Non-commutative instance required' ' for outer product.') # Muls of Tensor Products should be expanded # before this function is called if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1 and len(nc_part2) == 1): op = tensor_product_simp(nc_part1[0] * Dagger(nc_part2[0])) else: op = Mul(*nc_part1) * Dagger(Mul(*nc_part2)) return Mul(*c_part1)*Mul(*c_part2)*op def _represent(self, **options): return represent(self.doit(), **options) def _print_operator_name_latex(self, printer, *args): return printer._print(r'\rho', *args) def _print_operator_name_pretty(self, printer, *args): return prettyForm(unichr('\N{GREEK SMALL LETTER RHO}')) def _eval_trace(self, **kwargs): indices = kwargs.get('indices', []) return Tr(self.doit(), indices).doit() def entropy(self): """ Compute the entropy of a density matrix. Refer to density.entropy() method for examples. """ return entropy(self) def entropy(density): """Compute the entropy of a matrix/density object. This computes -Tr(density*ln(density)) using the eigenvalue decomposition of density, which is given as either a Density instance or a matrix (numpy.ndarray, sympy.Matrix or scipy.sparse). Parameters ========== density : density matrix of type Density, sympy matrix, scipy.sparse or numpy.ndarray Examples ======== >>> from sympy.physics.quantum.density import Density, entropy >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.matrixutils import scipy_sparse_matrix >>> from sympy.physics.quantum.spin import JzKet, Jz >>> from sympy import S, log >>> up = JzKet(S(1)/2,S(1)/2) >>> down = JzKet(S(1)/2,-S(1)/2) >>> d = Density((up,0.5),(down,0.5)) >>> entropy(d) log(2)/2 """ if isinstance(density, Density): density = represent(density) # represent in Matrix if isinstance(density, scipy_sparse_matrix): density = to_numpy(density) if isinstance(density, Matrix): eigvals = density.eigenvals().keys() return expand(-sum(e*log(e) for e in eigvals)) elif isinstance(density, numpy_ndarray): import numpy as np eigvals = np.linalg.eigvals(density) return -np.sum(eigvals*np.log(eigvals)) else: raise ValueError( "numpy.ndarray, scipy.sparse or sympy matrix expected") def fidelity(state1, state2): """ Computes the fidelity [1]_ between two quantum states The arguments provided to this function should be a square matrix or a Density object. If it is a square matrix, it is assumed to be diagonalizable. Parameters: ========== state1, state2 : a density matrix or Matrix Examples ======== >>> from sympy import S, sqrt >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.spin import JzKet >>> from sympy.physics.quantum.density import Density, fidelity >>> from sympy.physics.quantum.represent import represent >>> >>> up = JzKet(S(1)/2,S(1)/2) >>> down = JzKet(S(1)/2,-S(1)/2) >>> amp = 1/sqrt(2) >>> updown = (amp * up) + (amp * down) >>> >>> # represent turns Kets into matrices >>> up_dm = represent(up * Dagger(up)) >>> down_dm = represent(down * Dagger(down)) >>> updown_dm = represent(updown * Dagger(updown)) >>> >>> fidelity(up_dm, up_dm) 1 >>> fidelity(up_dm, down_dm) #orthogonal states 0 >>> fidelity(up_dm, updown_dm).evalf().round(3) 0.707 References ========== .. [1] http://en.wikipedia.org/wiki/Fidelity_of_quantum_states """ state1 = represent(state1) if isinstance(state1, Density) else state1 state2 = represent(state2) if isinstance(state2, Density) else state2 if (not isinstance(state1, Matrix) or not isinstance(state2, Matrix)): raise ValueError("state1 and state2 must be of type Density or Matrix " "received type=%s for state1 and type=%s for state2" % (type(state1), type(state2))) if ( state1.shape != state2.shape and state1.is_square): raise ValueError("The dimensions of both args should be equal and the " "matrix obtained should be a square matrix") sqrt_state1 = state1**Rational(1, 2) return Tr((sqrt_state1 * state2 * sqrt_state1)**Rational(1, 2)).doit()
9,834
29.448916
90
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/constants.py
"""Constants (like hbar) related to quantum mechanics.""" from __future__ import print_function, division from sympy.core.numbers import NumberSymbol from sympy.core.singleton import Singleton from sympy.core.compatibility import with_metaclass from sympy.printing.pretty.stringpict import prettyForm import mpmath.libmp as mlib #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- __all__ = [ 'hbar' ] class HBar(with_metaclass(Singleton, NumberSymbol)): """Reduced Plank's constant in numerical and symbolic form [1]_. Examples ======== >>> from sympy.physics.quantum.constants import hbar >>> hbar.evalf() 1.05457162000000e-34 References ========== .. [1] http://en.wikipedia.org/wiki/Planck_constant """ is_real = True is_positive = True is_negative = False is_irrational = True __slots__ = [] def _as_mpf_val(self, prec): return mlib.from_float(1.05457162e-34, prec) def _sympyrepr(self, printer, *args): return 'HBar()' def _sympystr(self, printer, *args): return 'hbar' def _pretty(self, printer, *args): if printer._use_unicode: return prettyForm(u'\N{PLANCK CONSTANT OVER TWO PI}') return prettyForm('hbar') def _latex(self, printer, *args): return r'\hbar' # Create an instance for everyone to use. hbar = HBar()
1,514
23.435484
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/operatorordering.py
"""Functions for reordering operator expressions.""" import warnings from sympy import Add, Mul, Pow, Integer from sympy.core.compatibility import range from sympy.physics.quantum import Operator, Commutator, AntiCommutator from sympy.physics.quantum.boson import BosonOp from sympy.physics.quantum.fermion import FermionOp __all__ = [ 'normal_order', 'normal_ordered_form' ] def _expand_powers(factors): """ Helper function for normal_ordered_form and normal_order: Expand a power expression to a multiplication expression so that that the expression can be handled by the normal ordering functions. """ new_factors = [] for factor in factors.args: if (isinstance(factor, Pow) and isinstance(factor.args[1], Integer) and factor.args[1] > 0): for n in range(factor.args[1]): new_factors.append(factor.args[0]) else: new_factors.append(factor) return new_factors def _normal_ordered_form_factor(product, independent=False, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_ordered_form_factor: Write multiplication expression with bosonic or fermionic operators on normally ordered form, using the bosonic and fermionic commutation relations. The resulting operator expression is equivalent to the argument, but will in general be a sum of operator products instead of a simple product. """ factors = _expand_powers(product) new_factors = [] n = 0 while n < len(factors) - 1: if isinstance(factors[n], BosonOp): # boson if not isinstance(factors[n + 1], BosonOp): new_factors.append(factors[n]) elif factors[n].is_annihilation == factors[n + 1].is_annihilation: if (independent and str(factors[n].name) > str(factors[n + 1].name)): new_factors.append(factors[n + 1]) new_factors.append(factors[n]) n += 1 else: new_factors.append(factors[n]) elif not factors[n].is_annihilation: new_factors.append(factors[n]) else: if factors[n + 1].is_annihilation: new_factors.append(factors[n]) else: if factors[n].args[0] != factors[n + 1].args[0]: if independent: c = 0 else: c = Commutator(factors[n], factors[n + 1]) new_factors.append(factors[n + 1] * factors[n] + c) else: c = Commutator(factors[n], factors[n + 1]) new_factors.append( factors[n + 1] * factors[n] + c.doit()) n += 1 elif isinstance(factors[n], FermionOp): # fermion if not isinstance(factors[n + 1], FermionOp): new_factors.append(factors[n]) elif factors[n].is_annihilation == factors[n + 1].is_annihilation: if (independent and str(factors[n].name) > str(factors[n + 1].name)): new_factors.append(factors[n + 1]) new_factors.append(factors[n]) n += 1 else: new_factors.append(factors[n]) elif not factors[n].is_annihilation: new_factors.append(factors[n]) else: if factors[n + 1].is_annihilation: new_factors.append(factors[n]) else: if factors[n].args[0] != factors[n + 1].args[0]: if independent: c = 0 else: c = AntiCommutator(factors[n], factors[n + 1]) new_factors.append(-factors[n + 1] * factors[n] + c) else: c = AntiCommutator(factors[n], factors[n + 1]) new_factors.append( -factors[n + 1] * factors[n] + c.doit()) n += 1 elif isinstance(factors[n], Operator): if isinstance(factors[n + 1], (BosonOp, FermionOp)): new_factors.append(factors[n + 1]) new_factors.append(factors[n]) n += 1 else: new_factors.append(factors[n]) else: new_factors.append(factors[n]) n += 1 if n == len(factors) - 1: new_factors.append(factors[-1]) if new_factors == factors: return product else: expr = Mul(*new_factors).expand() return normal_ordered_form(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth + 1, independent=independent) def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_ordered_form: loop through each term in an addition expression and call _normal_ordered_form_factor to perform the factor to an normally ordered expression. """ new_terms = [] for term in expr.args: if isinstance(term, Mul): new_term = _normal_ordered_form_factor( term, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth, independent=independent) new_terms.append(new_term) else: new_terms.append(term) return Add(*new_terms) def normal_ordered_form(expr, independent=False, recursive_limit=10, _recursive_depth=0): """Write an expression with bosonic or fermionic operators on normal ordered form, where each term is normally ordered. Note that this normal ordered form is equivalent to the original expression. Parameters ========== expr : expression The expression write on normal ordered form. recursive_limit : int (default 10) The number of allowed recursive applications of the function. Examples ======== >>> from sympy.physics.quantum import Dagger >>> from sympy.physics.quantum.boson import BosonOp >>> from sympy.physics.quantum.operatorordering import normal_ordered_form >>> a = BosonOp("a") >>> normal_ordered_form(a * Dagger(a)) 1 + Dagger(a)*a """ if _recursive_depth > recursive_limit: warnings.warn("Too many recursions, aborting") return expr if isinstance(expr, Add): return _normal_ordered_form_terms(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth, independent=independent) elif isinstance(expr, Mul): return _normal_ordered_form_factor(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth, independent=independent) else: return expr def _normal_order_factor(product, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_order: Normal order a multiplication expression with bosonic or fermionic operators. In general the resulting operator expression will not be equivalent to original product. """ factors = _expand_powers(product) n = 0 new_factors = [] while n < len(factors) - 1: if (isinstance(factors[n], BosonOp) and factors[n].is_annihilation): # boson if not isinstance(factors[n + 1], BosonOp): new_factors.append(factors[n]) else: if factors[n + 1].is_annihilation: new_factors.append(factors[n]) else: if factors[n].args[0] != factors[n + 1].args[0]: new_factors.append(factors[n + 1] * factors[n]) else: new_factors.append(factors[n + 1] * factors[n]) n += 1 elif (isinstance(factors[n], FermionOp) and factors[n].is_annihilation): # fermion if not isinstance(factors[n + 1], FermionOp): new_factors.append(factors[n]) else: if factors[n + 1].is_annihilation: new_factors.append(factors[n]) else: if factors[n].args[0] != factors[n + 1].args[0]: new_factors.append(-factors[n + 1] * factors[n]) else: new_factors.append(-factors[n + 1] * factors[n]) n += 1 else: new_factors.append(factors[n]) n += 1 if n == len(factors) - 1: new_factors.append(factors[-1]) if new_factors == factors: return product else: expr = Mul(*new_factors).expand() return normal_order(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth + 1) def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_order: look through each term in an addition expression and call _normal_order_factor to perform the normal ordering on the factors. """ new_terms = [] for term in expr.args: if isinstance(term, Mul): new_term = _normal_order_factor(term, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth) new_terms.append(new_term) else: new_terms.append(term) return Add(*new_terms) def normal_order(expr, recursive_limit=10, _recursive_depth=0): """Normal order an expression with bosonic or fermionic operators. Note that this normal order is not equivalent to the original expression, but the creation and annihilation operators in each term in expr is reordered so that the expression becomes normal ordered. Parameters ========== expr : expression The expression to normal order. recursive_limit : int (default 10) The number of allowed recursive applications of the function. Examples ======== >>> from sympy.physics.quantum import Dagger >>> from sympy.physics.quantum.boson import BosonOp >>> from sympy.physics.quantum.operatorordering import normal_order >>> a = BosonOp("a") >>> normal_order(a * Dagger(a)) Dagger(a)*a """ if _recursive_depth > recursive_limit: warnings.warn("Too many recursions, aborting") return expr if isinstance(expr, Add): return _normal_order_terms(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth) elif isinstance(expr, Mul): return _normal_order_factor(expr, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth) else: return expr
11,547
34.207317
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/qasm.py
""" qasm.py - Functions to parse a set of qasm commands into a Sympy Circuit. Examples taken from Chuang's page: http://www.media.mit.edu/quanta/qasm2circ/ The code returns a circuit and an associated list of labels. >>> from sympy.physics.quantum.qasm import Qasm >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*H(1) >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*CNOT(0,1)*CNOT(1,0) """ __all__ = [ 'Qasm', ] from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE from sympy.physics.quantum.circuitplot import Mz def read_qasm(lines): return Qasm(*lines.splitlines()) def read_qasm_file(filename): return Qasm(*open(filename).readlines()) def prod(c): p = 1 for ci in c: p *= ci return p def flip_index(i, n): """Reorder qubit indices from largest to smallest. >>> from sympy.physics.quantum.qasm import flip_index >>> flip_index(0, 2) 1 >>> flip_index(1, 2) 0 """ return n-i-1 def trim(line): """Remove everything following comment # characters in line. >>> from sympy.physics.quantum.qasm import trim >>> trim('nothing happens here') 'nothing happens here' >>> trim('something #happens here') 'something ' """ if not '#' in line: return line return line.split('#')[0] def get_index(target, labels): """Get qubit labels from the rest of the line,and return indices >>> from sympy.physics.quantum.qasm import get_index >>> get_index('q0', ['q0', 'q1']) 1 >>> get_index('q1', ['q0', 'q1']) 0 """ nq = len(labels) return flip_index(labels.index(target), nq) def get_indices(targets, labels): return [get_index(t, labels) for t in targets] def nonblank(args): for line in args: line = trim(line) if line.isspace(): continue yield line return def fullsplit(line): words = line.split() rest = ' '.join(words[1:]) return fixcommand(words[0]), [s.strip() for s in rest.split(',')] def fixcommand(c): """Fix Qasm command names. Remove all of forbidden characters from command c, and replace 'def' with 'qdef'. """ forbidden_characters = ['-'] c = c.lower() for char in forbidden_characters: c = c.replace(char, '') if c == 'def': return 'qdef' return c def stripquotes(s): """Replace explicit quotes in a string. >>> from sympy.physics.quantum.qasm import stripquotes >>> stripquotes("'S'") == 'S' True >>> stripquotes('"S"') == 'S' True >>> stripquotes('S') == 'S' True """ s = s.replace('"', '') # Remove second set of quotes? s = s.replace("'", '') return s class Qasm(object): """Class to form objects from Qasm lines >>> from sympy.physics.quantum.qasm import Qasm >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*H(1) >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*CNOT(0,1)*CNOT(1,0) """ def __init__(self, *args, **kwargs): self.defs = {} self.circuit = [] self.labels = [] self.inits = {} self.add(*args) self.kwargs = kwargs def add(self, *lines): for line in nonblank(lines): command, rest = fullsplit(line) if self.defs.get(command): #defs come first, since you can override built-in function = self.defs.get(command) indices = self.indices(rest) if len(indices) == 1: self.circuit.append(function(indices[0])) else: self.circuit.append(function(indices[:-1], indices[-1])) elif hasattr(self, command): function = getattr(self, command) function(*rest) else: print("Function %s not defined. Skipping" % command) def get_circuit(self): return prod(reversed(self.circuit)) def get_labels(self): return list(reversed(self.labels)) def plot(self): from sympy.physics.quantum.circuitplot import CircuitPlot circuit, labels = self.get_circuit(), self.get_labels() CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits) def qubit(self, arg, init=None): self.labels.append(arg) if init: self.inits[arg] = init def indices(self, args): return get_indices(args, self.labels) def index(self, arg): return get_index(arg, self.labels) def nop(self, *args): pass def x(self, arg): self.circuit.append(X(self.index(arg))) def z(self, arg): self.circuit.append(Z(self.index(arg))) def h(self, arg): self.circuit.append(H(self.index(arg))) def s(self, arg): self.circuit.append(S(self.index(arg))) def t(self, arg): self.circuit.append(T(self.index(arg))) def measure(self, arg): self.circuit.append(Mz(self.index(arg))) def cnot(self, a1, a2): self.circuit.append(CNOT(*self.indices([a1, a2]))) def swap(self, a1, a2): self.circuit.append(SWAP(*self.indices([a1, a2]))) def cphase(self, a1, a2): self.circuit.append(CPHASE(*self.indices([a1, a2]))) def toffoli(self, a1, a2, a3): i1, i2, i3 = self.indices([a1, a2, a3]) self.circuit.append(CGateS((i1, i2), X(i3))) def cx(self, a1, a2): fi, fj = self.indices([a1, a2]) self.circuit.append(CGate(fi, X(fj))) def cz(self, a1, a2): fi, fj = self.indices([a1, a2]) self.circuit.append(CGate(fi, Z(fj))) def defbox(self, *args): print("defbox not supported yet. Skipping: ", args) def qdef(self, name, ncontrols, symbol): from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate ncontrols = int(ncontrols) command = fixcommand(name) symbol = stripquotes(symbol) if ncontrols > 0: self.defs[command] = CreateCGate(symbol) else: self.defs[command] = CreateOneQubitGate(symbol)
6,299
26.510917
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/commutator.py
"""The commutator: [A,B] = A*B - B*A.""" from __future__ import print_function, division from sympy import S, Expr, Mul, Add from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.operator import Operator __all__ = [ 'Commutator' ] #----------------------------------------------------------------------------- # Commutator #----------------------------------------------------------------------------- class Commutator(Expr): """The standard commutator, in an unevaluated state. Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This class returns the commutator in an unevaluated form. To evaluate the commutator, use the ``.doit()`` method. Cannonical ordering of a commutator is ``[A, B]`` for ``A < B``. The arguments of the commutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``. Parameters ========== A : Expr The first argument of the commutator [A,B]. B : Expr The second argument of the commutator [A,B]. Examples ======== >>> from sympy.physics.quantum import Commutator, Dagger, Operator >>> from sympy.abc import x, y >>> A = Operator('A') >>> B = Operator('B') >>> C = Operator('C') Create a commutator and use ``.doit()`` to evaluate it: >>> comm = Commutator(A, B) >>> comm [A,B] >>> comm.doit() A*B - B*A The commutator orders it arguments in canonical order: >>> comm = Commutator(B, A); comm -[A,B] Commutative constants are factored out: >>> Commutator(3*x*A, x*y*B) 3*x**2*y*[A,B] Using ``.expand(commutator=True)``, the standard commutator expansion rules can be applied: >>> Commutator(A+B, C).expand(commutator=True) [A,C] + [B,C] >>> Commutator(A, B+C).expand(commutator=True) [A,B] + [A,C] >>> Commutator(A*B, C).expand(commutator=True) [A,C]*B + A*[B,C] >>> Commutator(A, B*C).expand(commutator=True) [A,B]*C + B*[A,C] Adjoint operations applied to the commutator are properly applied to the arguments: >>> Dagger(Commutator(A, B)) -[Dagger(A),Dagger(B)] References ========== .. [1] http://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return S.Zero if a.is_commutative or b.is_commutative: return S.Zero # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments # The Commutator [A, B] is in canonical form if A < B. if a.compare(b) == 1: return S.NegativeOne*cls(b, a) def _eval_expand_commutator(self, **hints): A = self.args[0] B = self.args[1] if isinstance(A, Add): # [A + B, C] -> [A, C] + [B, C] sargs = [] for term in A.args: comm = Commutator(term, B) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(B, Add): # [A, B + C] -> [A, B] + [A, C] sargs = [] for term in B.args: comm = Commutator(A, term) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(A, Mul): # [A*B, C] -> A*[B, C] + [A, C]*B a = A.args[0] b = Mul(*A.args[1:]) c = B comm1 = Commutator(b, c) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(a, comm1) second = Mul(comm2, b) return Add(first, second) elif isinstance(B, Mul): # [A, B*C] -> [A, B]*C + B*[A, C] a = A b = B.args[0] c = Mul(*B.args[1:]) comm1 = Commutator(a, b) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(comm1, c) second = Mul(b, comm2) return Add(first, second) # No changes, so return self return self def doit(self, **hints): """ Evaluate commutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_commutator(B, **hints) except NotImplementedError: try: comm = -1*B._eval_commutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B - B*A).doit(**hints) def _eval_adjoint(self): return Commutator(Dagger(self.args[1]), Dagger(self.args[0])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "[%s,%s]" % (self.args[0], self.args[1]) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right((prettyForm(u',')))) pform = prettyForm(*pform.right((printer._print(self.args[1], *args)))) pform = prettyForm(*pform.parens(left='[', right=']')) return pform def _latex(self, printer, *args): return "\\left[%s,%s\\right]" % tuple([ printer._print(arg, *args) for arg in self.args])
6,516
29.740566
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/state.py
"""Dirac notation for states.""" from __future__ import print_function, division from sympy import (cacheit, conjugate, Expr, Function, integrate, oo, sqrt, Tuple) from sympy.core.compatibility import range from sympy.printing.pretty.stringpict import stringPict from sympy.physics.quantum.qexpr import QExpr, dispatch_method __all__ = [ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState', 'TimeDepBra', 'TimeDepKet', 'Wavefunction' ] #----------------------------------------------------------------------------- # States, bras and kets. #----------------------------------------------------------------------------- # ASCII brackets _lbracket = "<" _rbracket = ">" _straight_bracket = "|" # Unicode brackets # MATHEMATICAL ANGLE BRACKETS _lbracket_ucode = u"\N{MATHEMATICAL LEFT ANGLE BRACKET}" _rbracket_ucode = u"\N{MATHEMATICAL RIGHT ANGLE BRACKET}" # LIGHT VERTICAL BAR _straight_bracket_ucode = u"\N{LIGHT VERTICAL BAR}" # Other options for unicode printing of <, > and | for Dirac notation. # LEFT-POINTING ANGLE BRACKET # _lbracket = u"\u2329" # _rbracket = u"\u232A" # LEFT ANGLE BRACKET # _lbracket = u"\u3008" # _rbracket = u"\u3009" # VERTICAL LINE # _straight_bracket = u"\u007C" class StateBase(QExpr): """Abstract base class for general abstract states in quantum mechanics. All other state classes defined will need to inherit from this class. It carries the basic structure for all other states such as dual, _eval_adjoint and label. This is an abstract base class and you should not instantiate it directly, instead use State. """ @classmethod def _operators_to_state(self, ops, **options): """ Returns the eigenstate instance for the passed operators. This method should be overridden in subclasses. It will handle being passed either an Operator instance or set of Operator instances. It should return the corresponding state INSTANCE or simply raise a NotImplementedError. See cartesian.py for an example. """ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!") def _state_to_operators(self, op_classes, **options): """ Returns the operators which this state instance is an eigenstate of. This method should be overridden in subclasses. It will be called on state instances and be passed the operator classes that we wish to make into instances. The state instance will then transform the classes appropriately, or raise a NotImplementedError if it cannot return operator instances. See cartesian.py for examples, """ raise NotImplementedError( "Cannot map this state to operators. Method not implemented!") @property def operators(self): """Return the operator(s) that this state is an eigenstate of""" from .operatorset import state_to_operators # import internally to avoid circular import errors return state_to_operators(self) def _enumerate_state(self, num_states, **options): raise NotImplementedError("Cannot enumerate this state!") def _represent_default_basis(self, **options): return self._represent(basis=self.operators) #------------------------------------------------------------------------- # Dagger/dual #------------------------------------------------------------------------- @property def dual(self): """Return the dual state of this one.""" return self.dual_class()._new_rawargs(self.hilbert_space, *self.args) @classmethod def dual_class(self): """Return the class used to construt the dual.""" raise NotImplementedError( 'dual_class must be implemented in a subclass' ) def _eval_adjoint(self): """Compute the dagger of this state using the dual.""" return self.dual #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _pretty_brackets(self, height, use_unicode=True): # Return pretty printed brackets for the state # Ideally, this could be done by pform.parens but it does not support the angled < and > # Setup for unicode vs ascii if use_unicode: lbracket, rbracket = self.lbracket_ucode, self.rbracket_ucode slash, bslash, vert = u'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \ u'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \ u'\N{BOX DRAWINGS LIGHT VERTICAL}' else: lbracket, rbracket = self.lbracket, self.rbracket slash, bslash, vert = '/', '\\', '|' # If height is 1, just return brackets if height == 1: return stringPict(lbracket), stringPict(rbracket) # Make height even height += (height % 2) brackets = [] for bracket in lbracket, rbracket: # Create left bracket if bracket in {_lbracket, _lbracket_ucode}: bracket_args = [ ' ' * (height//2 - i - 1) + slash for i in range(height // 2)] bracket_args.extend( [ ' ' * i + bslash for i in range(height // 2)]) # Create right bracket elif bracket in {_rbracket, _rbracket_ucode}: bracket_args = [ ' ' * i + bslash for i in range(height // 2)] bracket_args.extend([ ' ' * ( height//2 - i - 1) + slash for i in range(height // 2)]) # Create straight bracket elif bracket in {_straight_bracket, _straight_bracket_ucode}: bracket_args = [vert for i in range(height)] else: raise ValueError(bracket) brackets.append( stringPict('\n'.join(bracket_args), baseline=height//2)) return brackets def _sympystr(self, printer, *args): contents = self._print_contents(printer, *args) return '%s%s%s' % (self.lbracket, contents, self.rbracket) def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm # Get brackets pform = self._print_contents_pretty(printer, *args) lbracket, rbracket = self._pretty_brackets( pform.height(), printer._use_unicode) # Put together state pform = prettyForm(*pform.left(lbracket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): contents = self._print_contents_latex(printer, *args) # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. return '{%s%s%s}' % (self.lbracket_latex, contents, self.rbracket_latex) class KetBase(StateBase): """Base class for Kets. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Ket. """ lbracket = _straight_bracket rbracket = _rbracket lbracket_ucode = _straight_bracket_ucode rbracket_ucode = _rbracket_ucode lbracket_latex = r'\left|' rbracket_latex = r'\right\rangle ' @classmethod def default_args(self): return ("psi",) @classmethod def dual_class(self): return BraBase def __mul__(self, other): """KetBase*other""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, BraBase): return OuterProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*KetBase""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, BraBase): return InnerProduct(other, self) else: return Expr.__rmul__(self, other) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_innerproduct(self, bra, **hints): """Evaluate the inner product betweeen this ket and a bra. This is called to compute <bra|ket>, where the ket is ``self``. This method will dispatch to sub-methods having the format:: ``def _eval_innerproduct_BraClass(self, **hints):`` Subclasses should define these methods (one for each BraClass) to teach the ket how to take inner products with bras. """ return dispatch_method(self, '_eval_innerproduct', bra, **hints) def _apply_operator(self, op, **options): """Apply an Operator to this Ket. This method will dispatch to methods having the format:: ``def _apply_operator_OperatorName(op, **options):`` Subclasses should define these methods (one for each OperatorName) to teach the Ket how operators act on it. Parameters ========== op : Operator The Operator that is acting on the Ket. options : dict A dict of key/value pairs that control how the operator is applied to the Ket. """ return dispatch_method(self, '_apply_operator', op, **options) class BraBase(StateBase): """Base class for Bras. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Bra. """ lbracket = _lbracket rbracket = _straight_bracket lbracket_ucode = _lbracket_ucode rbracket_ucode = _straight_bracket_ucode lbracket_latex = r'\left\langle ' rbracket_latex = r'\right|' @classmethod def _operators_to_state(self, ops, **options): state = self.dual_class().operators_to_state(ops, **options) return state.dual def _state_to_operators(self, op_classes, **options): return self.dual._state_to_operators(op_classes, **options) def _enumerate_state(self, num_states, **options): dual_states = self.dual._enumerate_state(num_states, **options) return [x.dual for x in dual_states] @classmethod def default_args(self): return self.dual_class().default_args() @classmethod def dual_class(self): return KetBase def __mul__(self, other): """BraBase*other""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, KetBase): return InnerProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*BraBase""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, KetBase): return OuterProduct(other, self) else: return Expr.__rmul__(self, other) def _represent(self, **options): """A default represent that uses the Ket's version.""" from sympy.physics.quantum.dagger import Dagger return Dagger(self.dual._represent(**options)) class State(StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class Ket(State, KetBase): """A general time-independent Ket in quantum mechanics. Inherits from State and KetBase. This class should be used as the base class for all physical, time-independent Kets in a system. This class and its subclasses will be the main classes that users will use for expressing Kets in Dirac notation [1]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Ket and looking at its properties:: >>> from sympy.physics.quantum import Ket, Bra >>> from sympy import symbols, I >>> k = Ket('psi') >>> k |psi> >>> k.hilbert_space H >>> k.is_commutative False >>> k.label (psi,) Ket's know about their associated bra:: >>> k.dual <psi| >>> k.dual_class() <class 'sympy.physics.quantum.state.Bra'> Take a linear combination of two kets:: >>> k0 = Ket(0) >>> k1 = Ket(1) >>> 2*I*k0 - 4*k1 2*I*|0> - 4*|1> Compound labels are passed as tuples:: >>> n, m = symbols('n,m') >>> k = Ket(n,m) >>> k |nm> References ========== .. [1] http://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Bra class Bra(State, BraBase): """A general time-independent Bra in quantum mechanics. Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This class and its subclasses will be the main classes that users will use for expressing Bras in Dirac notation. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Bra and look at its properties:: >>> from sympy.physics.quantum import Ket, Bra >>> from sympy import symbols, I >>> b = Bra('psi') >>> b <psi| >>> b.hilbert_space H >>> b.is_commutative False Bra's know about their dual Ket's:: >>> b.dual |psi> >>> b.dual_class() <class 'sympy.physics.quantum.state.Ket'> Like Kets, Bras can have compound labels and be manipulated in a similar manner:: >>> n, m = symbols('n,m') >>> b = Bra(n,m) - I*Bra(m,n) >>> b -I*<mn| + <nm| Symbols in a Bra can be substituted using ``.subs``:: >>> b.subs(n,m) <mm| - I*<mm| References ========== .. [1] http://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Ket #----------------------------------------------------------------------------- # Time dependent states, bras and kets. #----------------------------------------------------------------------------- class TimeDepState(StateBase): """Base class for a general time-dependent quantum state. This class is used as a base class for any time-dependent state. The main difference between this class and the time-independent state is that this class takes a second argument that is the time in addition to the usual label argument. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. """ #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def default_args(self): return ("psi", "t") #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label of the state.""" return self.args[:-1] @property def time(self): """The time of the state.""" return self.args[-1] #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print_time(self, printer, *args): return printer._print(self.time, *args) _print_time_repr = _print_time _print_time_latex = _print_time def _print_time_pretty(self, printer, *args): pform = printer._print(self.time, *args) return pform def _print_contents(self, printer, *args): label = self._print_label(printer, *args) time = self._print_time(printer, *args) return '%s;%s' % (label, time) def _print_label_repr(self, printer, *args): label = self._print_sequence(self.label, ',', printer, *args) time = self._print_time_repr(printer, *args) return '%s,%s' % (label, time) def _print_contents_pretty(self, printer, *args): label = self._print_label_pretty(printer, *args) time = self._print_time_pretty(printer, *args) return printer._print_seq((label, time), delimiter=';') def _print_contents_latex(self, printer, *args): label = self._print_sequence( self.label, self._label_separator, printer, *args) time = self._print_time_latex(printer, *args) return '%s;%s' % (label, time) class TimeDepKet(TimeDepState, KetBase): """General time-dependent Ket in quantum mechanics. This inherits from ``TimeDepState`` and ``KetBase`` and is the main class that should be used for Kets that vary with time. Its dual is a ``TimeDepBra``. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== Create a TimeDepKet and look at its attributes:: >>> from sympy.physics.quantum import TimeDepKet >>> k = TimeDepKet('psi', 't') >>> k |psi;t> >>> k.time t >>> k.label (psi,) >>> k.hilbert_space H TimeDepKets know about their dual bra:: >>> k.dual <psi;t| >>> k.dual_class() <class 'sympy.physics.quantum.state.TimeDepBra'> """ @classmethod def dual_class(self): return TimeDepBra class TimeDepBra(TimeDepState, BraBase): """General time-dependent Bra in quantum mechanics. This inherits from TimeDepState and BraBase and is the main class that should be used for Bras that vary with time. Its dual is a TimeDepBra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== >>> from sympy.physics.quantum import TimeDepBra >>> from sympy import symbols, I >>> b = TimeDepBra('psi', 't') >>> b <psi;t| >>> b.time t >>> b.label (psi,) >>> b.hilbert_space H >>> b.dual |psi;t> """ @classmethod def dual_class(self): return TimeDepKet class Wavefunction(Function): """Class for representations in continuous bases This class takes an expression and coordinates in its constructor. It can be used to easily calculate normalizations and probabilities. Parameters ========== expr : Expr The expression representing the functional form of the w.f. coords : Symbol or tuple The coordinates to be integrated over, and their bounds Examples ======== Particle in a box, specifying bounds in the more primitive way of using Piecewise: >>> from sympy import Symbol, Piecewise, pi, N >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = Symbol('x', real=True) >>> n = 1 >>> L = 1 >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) >>> f = Wavefunction(g, x) >>> f.norm 1 >>> f.is_normalized True >>> p = f.prob() >>> p(0) 0 >>> p(L) 0 >>> p(0.5) 2 >>> p(0.85*L) 2*sin(0.85*pi)**2 >>> N(p(0.85*L)) 0.412214747707527 Additionally, you can specify the bounds of the function and the indices in a more compact way: >>> from sympy import symbols, pi, diff >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> f(L+1) 0 >>> f(L-1) sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L) >>> f(-1) 0 >>> f(0.85) sqrt(2)*sin(0.85*pi*n/L)/sqrt(L) >>> f(0.85, n=1, L=1) sqrt(2)*sin(0.85*pi) >>> f.is_commutative False All arguments are automatically sympified, so you can define the variables as strings rather than symbols: >>> expr = x**2 >>> f = Wavefunction(expr, 'x') >>> type(f.variables[0]) <class 'sympy.core.symbol.Symbol'> Derivatives of Wavefunctions will return Wavefunctions: >>> diff(f, x) Wavefunction(2*x, x) """ #Any passed tuples for coordinates and their bounds need to be #converted to Tuples before Function's constructor is called, to #avoid errors from calling is_Float in the constructor def __new__(cls, *args, **options): new_args = [None for i in args] ct = 0 for arg in args: if isinstance(arg, tuple): new_args[ct] = Tuple(*arg) else: new_args[ct] = arg ct += 1 return super(Function, cls).__new__(cls, *new_args, **options) def __call__(self, *args, **options): var = self.variables if len(args) != len(var): raise NotImplementedError( "Incorrect number of arguments to function!") ct = 0 #If the passed value is outside the specified bounds, return 0 for v in var: lower, upper = self.limits[v] #Do the comparison to limits only if the passed symbol is actually #a symbol present in the limits; #Had problems with a comparison of x > L if isinstance(args[ct], Expr) and \ not (lower in args[ct].free_symbols or upper in args[ct].free_symbols): continue if (args[ct] < lower) == True or (args[ct] > upper) == True: return 0 ct += 1 expr = self.expr #Allows user to make a call like f(2, 4, m=1, n=1) for symbol in list(expr.free_symbols): if str(symbol) in options.keys(): val = options[str(symbol)] expr = expr.subs(symbol, val) return expr.subs(zip(var, args)) def _eval_derivative(self, symbol): expr = self.expr deriv = expr._eval_derivative(symbol) return Wavefunction(deriv, *self.args[1:]) def _eval_conjugate(self): return Wavefunction(conjugate(self.expr), *self.args[1:]) def _eval_transpose(self): return self @property def free_symbols(self): return self.expr.free_symbols @property def is_commutative(self): """ Override Function's is_commutative so that order is preserved in represented expressions """ return False @classmethod def eval(self, *args): return None @property def variables(self): """ Return the coordinates which the wavefunction depends on Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x,y = symbols('x,y') >>> f = Wavefunction(x*y, x, y) >>> f.variables (x, y) >>> g = Wavefunction(x*y, x) >>> g.variables (x,) """ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]] return tuple(var) @property def limits(self): """ Return the limits of the coordinates which the w.f. depends on If no limits are specified, defaults to ``(-oo, oo)``. Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, (x, 0, 1)) >>> f.limits {x: (0, 1)} >>> f = Wavefunction(x**2, x) >>> f.limits {x: (-oo, oo)} >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2)) >>> f.limits {x: (-oo, oo), y: (-1, 2)} """ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo) for g in self._args[1:]] return dict(zip(self.variables, tuple(limits))) @property def expr(self): """ Return the expression which is the functional form of the Wavefunction Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, x) >>> f.expr x**2 """ return self._args[0] @property def is_normalized(self): """ Returns true if the Wavefunction is properly normalized Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.is_normalized True """ return (self.norm == 1.0) @property @cacheit def norm(self): """ Return the normalization of the specified functional form. This function integrates over the coordinates of the Wavefunction, with the bounds specified. Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm sqrt(2)*sqrt(L)/2 """ exp = self.expr*conjugate(self.expr) var = self.variables limits = self.limits for v in var: curr_limits = limits[v] exp = integrate(exp, (v, curr_limits[0], curr_limits[1])) return sqrt(exp) def normalize(self): """ Return a normalized version of the Wavefunction Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = symbols('x', real=True) >>> L = symbols('L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.normalize() Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L)) """ const = self.norm if const == oo: raise NotImplementedError("The function is not normalizable!") else: return Wavefunction((const)**(-1)*self.expr, *self.args[1:]) def prob(self): """ Return the absolute magnitude of the w.f., `|\psi(x)|^2` Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', real=True) >>> n = symbols('n', integer=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.prob() Wavefunction(sin(pi*n*x/L)**2, x) """ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
29,156
29.498954
106
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/circuitplot.py
"""Matplotlib based plotting of quantum circuits. Todo: * Optimize printing of large circuits. * Get this to work with single gates. * Do a better job checking the form of circuits to make sure it is a Mul of Gates. * Get multi-target gates plotting. * Get initial and final states to plot. * Get measurements to plot. Might need to rethink measurement as a gate issue. * Get scale and figsize to be handled in a better way. * Write some tests/examples! """ from __future__ import print_function, division from sympy import Mul from sympy.core.compatibility import range from sympy.external import import_module from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS from sympy.core.core import BasicMeta from sympy.core.assumptions import ManagedProperties __all__ = [ 'CircuitPlot', 'circuit_plot', 'labeller', 'Mz', 'Mx', 'CreateOneQubitGate', 'CreateCGate', ] np = import_module('numpy') matplotlib = import_module( 'matplotlib', __import__kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) # This is raised in environments that have no display. if not np or not matplotlib: class CircuitPlot(object): def __init__(*args, **kwargs): raise ImportError('numpy or matplotlib not available.') def circuit_plot(*args, **kwargs): raise ImportError('numpy or matplotlib not available.') else: pyplot = matplotlib.pyplot Line2D = matplotlib.lines.Line2D Circle = matplotlib.patches.Circle #from matplotlib import rc #rc('text',usetex=True) class CircuitPlot(object): """A class for managing a circuit plot.""" scale = 1.0 fontsize = 20.0 linewidth = 1.0 control_radius = 0.05 not_radius = 0.15 swap_delta = 0.05 labels = [] inits = {} label_buffer = 0.5 def __init__(self, c, nqubits, **kwargs): self.circuit = c self.ngates = len(self.circuit.args) self.nqubits = nqubits self.update(kwargs) self._create_grid() self._create_figure() self._plot_wires() self._plot_gates() self._finish() def update(self, kwargs): """Load the kwargs into the instance dict.""" self.__dict__.update(kwargs) def _create_grid(self): """Create the grid of wires.""" scale = self.scale wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float) gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float) self._wire_grid = wire_grid self._gate_grid = gate_grid def _create_figure(self): """Create the main matplotlib figure.""" self._figure = pyplot.figure( figsize=(self.ngates*self.scale, self.nqubits*self.scale), facecolor='w', edgecolor='w' ) ax = self._figure.add_subplot( 1, 1, 1, frameon=True ) ax.set_axis_off() offset = 0.5*self.scale ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset) ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset) ax.set_aspect('equal') self._axes = ax def _plot_wires(self): """Plot the wires of the circuit diagram.""" xstart = self._gate_grid[0] xstop = self._gate_grid[-1] xdata = (xstart - self.scale, xstop + self.scale) for i in range(self.nqubits): ydata = (self._wire_grid[i], self._wire_grid[i]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) if self.labels: init_label_buffer = 0 if self.inits.get(self.labels[i]): init_label_buffer = 0.25 self._axes.text( xdata[0]-self.label_buffer-init_label_buffer,ydata[0], render_label(self.labels[i],self.inits), size=self.fontsize, color='k',ha='center',va='center') self._plot_measured_wires() def _plot_measured_wires(self): ismeasured = self._measurements() xstop = self._gate_grid[-1] dy = 0.04 # amount to shift wires when doubled # Plot doubled wires after they are measured for im in ismeasured: xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale) ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) # Also double any controlled lines off these wires for i,g in enumerate(self._gates()): if isinstance(g, CGate) or isinstance(g, CGateS): wires = g.controls + g.targets for wire in wires: if wire in ismeasured and \ self._gate_grid[i] > self._gate_grid[ismeasured[wire]]: ydata = min(wires), max(wires) xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def _gates(self): """Create a list of all gates in the circuit plot.""" gates = [] if isinstance(self.circuit, Mul): for g in reversed(self.circuit.args): if isinstance(g, Gate): gates.append(g) elif isinstance(self.circuit, Gate): gates.append(self.circuit) return gates def _plot_gates(self): """Iterate through the gates and plot each of them.""" for i, gate in enumerate(self._gates()): gate.plot_gate(self, i) def _measurements(self): """Return a dict {i:j} where i is the index of the wire that has been measured, and j is the gate where the wire is measured. """ ismeasured = {} for i,g in enumerate(self._gates()): if getattr(g,'measurement',False): for target in g.targets: if target in ismeasured: if ismeasured[target] > i: ismeasured[target] = i else: ismeasured[target] = i return ismeasured def _finish(self): # Disable clipping to make panning work well for large circuits. for o in self._figure.findobj(): o.set_clip_on(False) def one_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a single qubit gate.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] self._axes.text( x, y, t, color='k', ha='center', va='center', bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), size=self.fontsize ) def two_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a two qubit gate. Doesn't work yet. """ x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx]+0.5 print(self._gate_grid) print(self._wire_grid) obj = self._axes.text( x, y, t, color='k', ha='center', va='center', bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), size=self.fontsize ) def control_line(self, gate_idx, min_wire, max_wire): """Draw a vertical control line.""" xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx]) ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def control_point(self, gate_idx, wire_idx): """Draw a control point.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.control_radius c = Circle( (x, y), radius*self.scale, ec='k', fc='k', fill=True, lw=self.linewidth ) self._axes.add_patch(c) def not_point(self, gate_idx, wire_idx): """Draw a NOT gates as the circle with plus in the middle.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.not_radius c = Circle( (x, y), radius, ec='k', fc='w', fill=False, lw=self.linewidth ) self._axes.add_patch(c) l = Line2D( (x, x), (y - radius, y + radius), color='k', lw=self.linewidth ) self._axes.add_line(l) def swap_point(self, gate_idx, wire_idx): """Draw a swap point as a cross.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] d = self.swap_delta l1 = Line2D( (x - d, x + d), (y - d, y + d), color='k', lw=self.linewidth ) l2 = Line2D( (x - d, x + d), (y + d, y - d), color='k', lw=self.linewidth ) self._axes.add_line(l1) self._axes.add_line(l2) def circuit_plot(c, nqubits, **kwargs): """Draw the circuit diagram for the circuit with nqubits. Parameters ========== c : circuit The circuit to plot. Should be a product of Gate instances. nqubits : int The number of qubits to include in the circuit. Must be at least as big as the largest `min_qubits`` of the gates. """ return CircuitPlot(c, nqubits, **kwargs) def render_label(label, inits={}): """Slightly more flexible way to render labels. >>> from sympy.physics.quantum.circuitplot import render_label >>> render_label('q0') '$|q0\\\\rangle$' >>> render_label('q0', {'q0':'0'}) '$|q0\\\\rangle=|0\\\\rangle$' """ init = inits.get(label) if init: return r'$|%s\rangle=|%s\rangle$' % (label, init) return r'$|%s\rangle$' % label def labeller(n, symbol='q'): """Autogenerate labels for wires of quantum circuits. Parameters ========== n : int number of qubits in the circuit symbol : string A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc. >>> from sympy.physics.quantum.circuitplot import labeller >>> labeller(2) ['q_1', 'q_0'] >>> labeller(3,'j') ['j_2', 'j_1', 'j_0'] """ return ['%s_%d' % (symbol,n-i-1) for i in range(n)] class Mz(OneQubitGate): """Mock-up of a z measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mz' gate_name_latex=u'M_z' class Mx(OneQubitGate): """Mock-up of an x measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mx' gate_name_latex=u'M_x' class CreateOneQubitGate(ManagedProperties): def __new__(mcl, name, latexname=None): if not latexname: latexname = name return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,), {'gate_name': name, 'gate_name_latex': latexname}) def CreateCGate(name, latexname=None): """Use a lexical closure to make a controlled gate. """ if not latexname: latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls,target): return CGate(tuple(ctrls),onequbitgate(target)) return ControlledGate
12,934
33.310345
86
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/qft.py
"""An implementation of qubits and gates acting on them. Todo: * Update docstrings. * Update tests. * Implement apply using decompose. * Implement represent using decompose or something smarter. For this to work we first have to implement represent for SWAP. * Decide if we want upper index to be inclusive in the constructor. * Fix the printing of Rk gates in plotting. """ from __future__ import print_function, division from sympy import Expr, Matrix, exp, I, pi, Integer, Symbol from sympy.core.compatibility import range from sympy.functions import sqrt from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError, QExpr from sympy.matrices import eye from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.gate import ( Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate ) __all__ = [ 'QFT', 'IQFT', 'RkGate', 'Rk' ] #----------------------------------------------------------------------------- # Fourier stuff #----------------------------------------------------------------------------- class RkGate(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = u'Rk' gate_name_latex = u'R' def __new__(cls, *args): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates simplify to other gates, using these # substitutions give us familiar results for the QFT for small numbers # of qubits. target = args[0] k = args[1] if k == 1: return ZGate(target) elif k == 2: return PhaseGate(target) elif k == 3: return TGate(target) args = cls._eval_args(args) inst = Expr.__new__(cls, *args) inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _eval_args(cls, args): # Fall back to this, because Gate._eval_args assumes that args is # all targets and can't contain duplicates. return QExpr._eval_args(args) @property def k(self): return self.label[1] @property def targets(self): return self.label[:1] @property def gate_name_plot(self): return r'$%s_%s$' % (self.gate_name_latex, str(self.k)) def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError( 'Invalid format for the R_k gate: %r' % format) Rk = RkGate class Fourier(Gate): """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates.""" @classmethod def _eval_args(self, args): if len(args) != 2: raise QuantumError( 'QFT/IQFT only takes two arguments, got: %r' % args ) if args[0] >= args[1]: raise QuantumError("Start must be smaller than finish") return Gate._eval_args(args) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """ Represents the (I)QFT In the Z Basis """ nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) size = self.size omega = self.omega #Make a matrix that has the basic Fourier Transform Matrix arrayFT = [[omega**( i*j % size)/sqrt(size) for i in range(size)] for j in range(size)] matrixFT = Matrix(arrayFT) #Embed the FT Matrix in a higher space, if necessary if self.label[0] != 0: matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT) if self.min_qubits < nqubits: matrixFT = matrix_tensor_product( matrixFT, eye(2**(nqubits - self.min_qubits))) return matrixFT @property def targets(self): return range(self.label[0], self.label[1]) @property def min_qubits(self): return self.label[1] @property def size(self): """Size is the size of the QFT matrix""" return 2**(self.label[1] - self.label[0]) @property def omega(self): return Symbol('omega') class QFT(Fourier): """The forward quantum Fourier transform.""" gate_name = u'QFT' gate_name_latex = u'QFT' def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level)*circuit for i in range(level - start): circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit return circuit def _apply_operator_Qubit(self, qubits, **options): return qapply(self.decompose()*qubits) def _eval_inverse(self): return IQFT(*self.args) @property def omega(self): return exp(2*pi*I/self.size) class IQFT(Fourier): """The inverse quantum Fourier transform.""" gate_name = u'IQFT' gate_name_latex = u'{QFT^{-1}}' def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit for level in range(start, finish): for i in reversed(range(level - start)): circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit circuit = HadamardGate(level)*circuit return circuit def _eval_inverse(self): return QFT(*self.args) @property def omega(self): return exp(-2*pi*I/self.size)
6,297
28.568075
83
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/cartesian.py
"""Operators and states for 1D cartesian position and momentum. TODO: * Add 3D classes to mappings in operatorset.py """ from __future__ import print_function, division from sympy import DiracDelta, exp, I, Interval, pi, S, sqrt from sympy.core.compatibility import range from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import L2 from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator from sympy.physics.quantum.state import Ket, Bra, State __all__ = [ 'XOp', 'YOp', 'ZOp', 'PxOp', 'X', 'Y', 'Z', 'Px', 'XKet', 'XBra', 'PxKet', 'PxBra', 'PositionState3D', 'PositionKet3D', 'PositionBra3D' ] #------------------------------------------------------------------------- # Position operators #------------------------------------------------------------------------- class XOp(HermitianOperator): """1D cartesian position operator.""" @classmethod def default_args(self): return ("X",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _eval_commutator_PxOp(self, other): return I*hbar def _apply_operator_XKet(self, ket): return ket.position*ket def _apply_operator_PositionKet3D(self, ket): return ket.position_x*ket def _represent_PxKet(self, basis, **options): index = options.pop("index", 1) states = basis._enumerate_state(2, start_index=index) coord1 = states[0].momentum coord2 = states[1].momentum d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return I*hbar*(d*delta) class YOp(HermitianOperator): """ Y cartesian coordinate operator (for 2D or 3D systems) """ @classmethod def default_args(self): return ("Y",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_y*ket class ZOp(HermitianOperator): """ Z cartesian coordinate operator (for 3D systems) """ @classmethod def default_args(self): return ("Z",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_z*ket #------------------------------------------------------------------------- # Momentum operators #------------------------------------------------------------------------- class PxOp(HermitianOperator): """1D cartesian momentum operator.""" @classmethod def default_args(self): return ("Px",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PxKet(self, ket): return ket.momentum*ket def _represent_XKet(self, basis, **options): index = options.pop("index", 1) states = basis._enumerate_state(2, start_index=index) coord1 = states[0].position coord2 = states[1].position d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return -I*hbar*(d*delta) X = XOp('X') Y = YOp('Y') Z = ZOp('Z') Px = PxOp('Px') #------------------------------------------------------------------------- # Position eigenstates #------------------------------------------------------------------------- class XKet(Ket): """1D cartesian position eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XBra @property def position(self): """The position of the state.""" return self.label[0] def _enumerate_state(self, num_states, **options): return _enumerate_continuous_1D(self, num_states, **options) def _eval_innerproduct_XBra(self, bra, **hints): return DiracDelta(self.position - bra.position) def _eval_innerproduct_PxBra(self, bra, **hints): return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar) class XBra(Bra): """1D cartesian position eigenbra.""" @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XKet @property def position(self): """The position of the state.""" return self.label[0] class PositionState3D(State): """ Base class for 3D cartesian position eigenstates """ @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x", "y", "z") @property def position_x(self): """ The x coordinate of the state """ return self.label[0] @property def position_y(self): """ The y coordinate of the state """ return self.label[1] @property def position_z(self): """ The z coordinate of the state """ return self.label[2] class PositionKet3D(Ket, PositionState3D): """ 3D cartesian position eigenket """ def _eval_innerproduct_PositionBra3D(self, bra, **options): x_diff = self.position_x - bra.position_x y_diff = self.position_y - bra.position_y z_diff = self.position_z - bra.position_z return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff) @classmethod def dual_class(self): return PositionBra3D class PositionBra3D(Bra, PositionState3D): """ 3D cartesian position eigenbra """ @classmethod def dual_class(self): return PositionKet3D #------------------------------------------------------------------------- # Momentum eigenstates #------------------------------------------------------------------------- class PxKet(Ket): """1D cartesian momentum eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxBra @property def momentum(self): """The momentum of the state.""" return self.label[0] def _enumerate_state(self, *args, **options): return _enumerate_continuous_1D(self, *args, **options) def _eval_innerproduct_XBra(self, bra, **hints): return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar) def _eval_innerproduct_PxBra(self, bra, **hints): return DiracDelta(self.momentum - bra.momentum) class PxBra(Bra): """1D cartesian momentum eigenbra.""" @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxKet @property def momentum(self): """The momentum of the state.""" return self.label[0] #------------------------------------------------------------------------- # Global helper functions #------------------------------------------------------------------------- def _enumerate_continuous_1D(*args, **options): state = args[0] num_states = args[1] state_class = state.__class__ index_list = options.pop('index_list', []) if len(index_list) == 0: start_index = options.pop('start_index', 1) index_list = list(range(start_index, start_index + num_states)) enum_states = [0 for i in range(len(index_list))] for i, ind in enumerate(index_list): label = state.args[0] enum_states[i] = state_class(str(label) + "_" + str(ind), **options) return enum_states def _lowercase_labels(ops): if not isinstance(ops, set): ops = [ops] return [str(arg.label[0]).lower() for arg in ops] def _uppercase_labels(ops): if not isinstance(ops, set): ops = [ops] new_args = [str(arg.label[0])[0].upper() + str(arg.label[0])[1:] for arg in ops] return new_args
8,766
24.709677
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/fermion.py
"""Fermionic quantum operators.""" from sympy import Integer from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, Ket, Bra from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'FermionOp', 'FermionFockKet', 'FermionFockBra' ] class FermionOp(Operator): """A fermionic operator that satisfies {c, Dagger(c)} == 1. Parameters ========== name : str A string that labels the fermionic mode. annihilation : bool A bool that indicates if the fermionic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, AntiCommutator >>> from sympy.physics.quantum.fermion import FermionOp >>> c = FermionOp("c") >>> AntiCommutator(c, Dagger(c)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("c", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], Integer(1)) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_FermionOp(self, other, **hints): if 'independent' in hints and hints['independent']: # [c, d] = 0 return Integer(0) return None def _eval_anticommutator_FermionOp(self, other, **hints): if self.name == other.name: # {a^\dagger, a} = 1 if not self.is_annihilation and other.is_annihilation: return Integer(1) elif 'independent' in hints and hints['independent']: # {c, d} = 2 * c * d, because [c, d] = 0 for independent operators return 2 * self * other return None def _eval_anticommutator_BosonOp(self, other, **hints): # because fermions and bosons commute return 2 * self * other def _eval_commutator_BosonOp(self, other, **hints): return Integer(0) def _eval_adjoint(self): return FermionOp(str(self.name), not self.is_annihilation) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dag}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm(u'\N{DAGGER}') class FermionFockKet(Ket): """Fock state ket for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_FermionFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_operator_FermionOp(self, op, **options): if op.is_annihilation: if self.n == 1: return FermionFockKet(0) else: return Integer(0) else: if self.n == 0: return FermionFockKet(1) else: return Integer(0) class FermionFockBra(Bra): """Fock state bra for a fermionic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return FermionFockKet
4,477
24.01676
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/hilbert.py
"""Hilbert spaces for quantum mechanics. Authors: * Brian Granger * Matt Curry """ from __future__ import print_function, division from sympy import Basic, Interval, oo, sympify from sympy.core.compatibility import range from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.core.compatibility import reduce __all__ = [ 'HilbertSpaceError', 'HilbertSpace', 'ComplexSpace', 'L2', 'FockSpace' ] #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpaceError(QuantumError): pass #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpace(Basic): """An abstract Hilbert space for quantum mechanics. In short, a Hilbert space is an abstract vector space that is complete with inner products defined [1]_. Examples ======== >>> from sympy.physics.quantum.hilbert import HilbertSpace >>> hs = HilbertSpace() >>> hs H References ========== .. [1] http://en.wikipedia.org/wiki/Hilbert_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): """Return the Hilbert dimension of the space.""" raise NotImplementedError('This Hilbert space has no dimension.') def __add__(self, other): return DirectSumHilbertSpace(self, other) def __radd__(self, other): return DirectSumHilbertSpace(other, self) def __mul__(self, other): return TensorProductHilbertSpace(self, other) def __rmul__(self, other): return TensorProductHilbertSpace(other, self) def __pow__(self, other, mod=None): if mod is not None: raise ValueError('The third argument to __pow__ is not supported \ for Hilbert spaces.') return TensorPowerHilbertSpace(self, other) def __contains__(self, other): """Is the operator or state in this Hilbert space. This is checked by comparing the classes of the Hilbert spaces, not the instances. This is to allow Hilbert Spaces with symbolic dimensions. """ if other.hilbert_space.__class__ == self.__class__: return True else: return False def _sympystr(self, printer, *args): return u'H' def _pretty(self, printer, *args): ustr = u'\N{LATIN CAPITAL LETTER H}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{H}' class ComplexSpace(HilbertSpace): """Finite dimensional Hilbert space of complex vectors. The elements of this Hilbert space are n-dimensional complex valued vectors with the usual inner product that takes the complex conjugate of the vector on the right. A classic example of this type of Hilbert space is spin-1/2, which is ``ComplexSpace(2)``. Generalizing to spin-s, the space is ``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the direct product space ``ComplexSpace(2)**N``. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum.hilbert import ComplexSpace >>> c1 = ComplexSpace(2) >>> c1 C(2) >>> c1.dimension 2 >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> c2 C(n) >>> c2.dimension n """ def __new__(cls, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension) return obj @classmethod def eval(cls, dimension): if len(dimension.atoms()) == 1: if not (dimension.is_Integer and dimension > 0 or dimension is oo or dimension.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' 'be a positive integer, oo, or a Symbol: %r' % dimension) else: for dim in dimension.atoms(): if not (dim.is_Integer or dim is oo or dim.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' ' contain integers, oo, or a Symbol: %r' % dim) @property def dimension(self): return self.args[0] def _sympyrepr(self, printer, *args): return "%s(%s)" % (self.__class__.__name__, printer._print(self.dimension, *args)) def _sympystr(self, printer, *args): return "C(%s)" % printer._print(self.dimension, *args) def _pretty(self, printer, *args): ustr = u'\N{LATIN CAPITAL LETTER C}' pform_exp = printer._print(self.dimension, *args) pform_base = prettyForm(ustr) return pform_base**pform_exp def _latex(self, printer, *args): return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args) class L2(HilbertSpace): """The Hilbert space of square integrable functions on an interval. An L2 object takes in a single sympy Interval argument which represents the interval its functions (vectors) are defined on. Examples ======== >>> from sympy import Interval, oo >>> from sympy.physics.quantum.hilbert import L2 >>> hs = L2(Interval(0,oo)) >>> hs L2(Interval(0, oo)) >>> hs.dimension oo >>> hs.interval Interval(0, oo) """ def __new__(cls, interval): if not isinstance(interval, Interval): raise TypeError('L2 interval must be an Interval instance: %r' % interval) obj = Basic.__new__(cls, interval) return obj @property def dimension(self): return oo @property def interval(self): return self.args[0] def _sympyrepr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _sympystr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _pretty(self, printer, *args): pform_exp = prettyForm(u'2') pform_base = prettyForm(u'L') return pform_base**pform_exp def _latex(self, printer, *args): interval = printer._print(self.interval, *args) return r'{\mathcal{L}^2}\left( %s \right)' % interval class FockSpace(HilbertSpace): """The Hilbert space for second quantization. Technically, this Hilbert space is a infinite direct sum of direct products of single particle Hilbert spaces [1]_. This is a mess, so we have a class to represent it directly. Examples ======== >>> from sympy.physics.quantum.hilbert import FockSpace >>> hs = FockSpace() >>> hs F >>> hs.dimension oo References ========== .. [1] http://en.wikipedia.org/wiki/Fock_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): return oo def _sympyrepr(self, printer, *args): return "FockSpace()" def _sympystr(self, printer, *args): return "F" def _pretty(self, printer, *args): ustr = u'\N{LATIN CAPITAL LETTER F}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{F}' class TensorProductHilbertSpace(HilbertSpace): """A tensor product of Hilbert spaces [1]_. The tensor product between Hilbert spaces is represented by the operator ``*`` Products of the same Hilbert space will be combined into tensor powers. A ``TensorProductHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. In addition, multiplication of ``HilbertSpace`` objects will automatically return this tensor product object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c*f >>> hs C(2)*F >>> hs.dimension oo >>> hs.spaces (C(2), F) >>> c1 = ComplexSpace(2) >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> hs = c1*c2 >>> hs C(2)*C(n) >>> hs.dimension 2*n References ========== .. [1] http://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, TensorProductHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be multiplied by \ other Hilbert spaces: %r' % arg) #combine like arguments into direct powers comb_args = [] prev_arg = None for new_arg in new_args: if prev_arg is not None: if isinstance(new_arg, TensorPowerHilbertSpace) and \ isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg.base: prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp) elif isinstance(new_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg: prev_arg = prev_arg**(new_arg.exp + 1) elif isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg == prev_arg.base: prev_arg = new_arg**(prev_arg.exp + 1) elif new_arg == prev_arg: prev_arg = new_arg**2 else: comb_args.append(prev_arg) prev_arg = new_arg elif prev_arg is None: prev_arg = new_arg comb_args.append(prev_arg) if recall: return TensorProductHilbertSpace(*comb_args) elif len(comb_args) == 1: return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x*y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this tensor product.""" return self.args def _spaces_printer(self, printer, *args): spaces_strs = [] for arg in self.args: s = printer._print(arg, *args) if isinstance(arg, DirectSumHilbertSpace): s = '(%s)' % s spaces_strs.append(s) return spaces_strs def _sympyrepr(self, printer, *args): spaces_reprs = self._spaces_printer(printer, *args) return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = self._spaces_printer(printer, *args) return '*'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(u' ' + u'\N{N-ARY CIRCLED TIMES OPERATOR}' + u' ')) else: pform = prettyForm(*pform.right(' x ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\otimes ' return s class DirectSumHilbertSpace(HilbertSpace): """A direct sum of Hilbert spaces [1]_. This class uses the ``+`` operator to represent direct sums between different Hilbert spaces. A ``DirectSumHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. Also, addition of ``HilbertSpace`` objects will automatically return a direct sum object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c+f >>> hs C(2)+F >>> hs.dimension oo >>> list(hs.spaces) [C(2), F] References ========== .. [1] http://en.wikipedia.org/wiki/Hilbert_space#Direct_sums """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, DirectSumHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, HilbertSpace): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be summed with other \ Hilbert spaces: %r' % arg) if recall: return DirectSumHilbertSpace(*new_args) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x + y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this direct sum.""" return self.args def _sympyrepr(self, printer, *args): spaces_reprs = [printer._print(arg, *args) for arg in self.args] return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = [printer._print(arg, *args) for arg in self.args] return '+'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(u' \N{CIRCLED PLUS} ')) else: pform = prettyForm(*pform.right(' + ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\oplus ' return s class TensorPowerHilbertSpace(HilbertSpace): """An exponentiated Hilbert space [1]_. Tensor powers (repeated tensor products) are represented by the operator ``**`` Identical Hilbert spaces that are multiplied together will be automatically combined into a single tensor power object. Any Hilbert space, product, or sum may be raised to a tensor power. The ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the tensor power (number). Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> n = symbols('n') >>> c = ComplexSpace(2) >>> hs = c**n >>> hs C(2)**n >>> hs.dimension 2**n >>> c = ComplexSpace(2) >>> c*c C(2)**2 >>> f = FockSpace() >>> c*f*f C(2)*F**2 References ========== .. [1] http://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r return Basic.__new__(cls, *r) @classmethod def eval(cls, args): new_args = args[0], sympify(args[1]) exp = new_args[1] #simplify hs**1 -> hs if exp == 1: return args[0] #simplify hs**0 -> 1 if exp == 0: return sympify(1) #check (and allow) for hs**(x+42+y...) case if len(exp.atoms()) == 1: if not (exp.is_Integer and exp >= 0 or exp.is_Symbol): raise ValueError('Hilbert spaces can only be raised to \ positive integers or Symbols: %r' % exp) else: for power in exp.atoms(): if not (power.is_Integer or power.is_Symbol): raise ValueError('Tensor powers can only contain integers \ or Symbols: %r' % power) return new_args @property def base(self): return self.args[0] @property def exp(self): return self.args[1] @property def dimension(self): if self.base.dimension == oo: return oo else: return self.base.dimension**self.exp def _sympyrepr(self, printer, *args): return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _sympystr(self, printer, *args): return "%s**%s" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _pretty(self, printer, *args): pform_exp = printer._print(self.exp, *args) if printer._use_unicode: pform_exp = prettyForm(*pform_exp.left(prettyForm(u'\N{N-ARY CIRCLED TIMES OPERATOR}'))) else: pform_exp = prettyForm(*pform_exp.left(prettyForm('x'))) pform_base = printer._print(self.base, *args) return pform_base**pform_exp def _latex(self, printer, *args): base = printer._print(self.base, *args) exp = printer._print(self.exp, *args) return r'{%s}^{\otimes %s}' % (base, exp)
19,503
28.91411
103
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/represent.py
"""Logic for representing operators in state in various bases. TODO: * Get represent working with continuous hilbert spaces. * Document default basis functionality. """ from __future__ import print_function, division from sympy import Add, Expr, I, integrate, Mul, Pow from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.matrixutils import flatten_scalar from sympy.physics.quantum.state import KetBase, BraBase, StateBase from sympy.physics.quantum.operator import Operator, OuterProduct from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators __all__ = [ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result', 'get_basis', 'enumerate_states' ] #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def _sympy_to_scalar(e): """Convert from a sympy scalar to a Python scalar.""" if isinstance(e, Expr): if e.is_Integer: return int(e) elif e.is_Float: return float(e) elif e.is_Rational: return float(e) elif e.is_Number or e.is_NumberSymbol or e == I: return complex(e) raise TypeError('Expected number, got: %r' % e) def represent(expr, **options): """Represent the quantum expression in the given basis. In quantum mechanics abstract states and operators can be represented in various basis sets. Under this operation the follow transforms happen: * Ket -> column vector or function * Bra -> row vector of function * Operator -> matrix or differential operator This function is the top-level interface for this action. This function walks the sympy expression tree looking for ``QExpr`` instances that have a ``_represent`` method. This method is then called and the object is replaced by the representation returned by this method. By default, the ``_represent`` method will dispatch to other methods that handle the representation logic for a particular basis set. The naming convention for these methods is the following:: def _represent_FooBasis(self, e, basis, **options) This function will have the logic for representing instances of its class in the basis set having a class named ``FooBasis``. Parameters ========== expr : Expr The expression to represent. basis : Operator, basis set An object that contains the information about the basis set. If an operator is used, the basis is assumed to be the orthonormal eigenvectors of that operator. In general though, the basis argument can be any object that contains the basis set information. options : dict Key/value pairs of options that are passed to the underlying method that finds the representation. These options can be used to control how the representation is done. For example, this is where the size of the basis set would be set. Returns ======= e : Expr The SymPy expression of the represented quantum expression. Examples ======== Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator and its spin 1/2 up eigenstate. By definining the ``_represent_SzOp`` method, the ket can be represented in the z-spin basis. >>> from sympy.physics.quantum import Operator, represent, Ket >>> from sympy import Matrix >>> class SzUpKet(Ket): ... def _represent_SzOp(self, basis, **options): ... return Matrix([1,0]) ... >>> class SzOp(Operator): ... pass ... >>> sz = SzOp('Sz') >>> up = SzUpKet('up') >>> represent(up, basis=sz) Matrix([ [1], [0]]) Here we see an example of representations in a continuous basis. We see that the result of representing various combinations of cartesian position operators and kets give us continuous expressions involving DiracDelta functions. >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra >>> X = XOp() >>> x = XKet() >>> y = XBra('y') >>> represent(X*x) x*DiracDelta(x - x_2) >>> represent(X*x*y) x*DiracDelta(x - x_3)*DiracDelta(x_1 - y) """ format = options.get('format', 'sympy') if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct): options['replace_none'] = False temp_basis = get_basis(expr, **options) if temp_basis is not None: options['basis'] = temp_basis try: return expr._represent(**options) except NotImplementedError as strerr: #If no _represent_FOO method exists, map to the #appropriate basis state and try #the other methods of representation options['replace_none'] = True if isinstance(expr, (KetBase, BraBase)): try: return rep_innerproduct(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) elif isinstance(expr, Operator): try: return rep_expectation(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) else: raise NotImplementedError(strerr) elif isinstance(expr, Add): result = represent(expr.args[0], **options) for args in expr.args[1:]: # scipy.sparse doesn't support += so we use plain = here. result = result + represent(args, **options) return result elif isinstance(expr, Pow): base, exp = expr.as_base_exp() if format == 'numpy' or format == 'scipy.sparse': exp = _sympy_to_scalar(exp) return represent(base, **options)**exp elif isinstance(expr, TensorProduct): new_args = [represent(arg, **options) for arg in expr.args] return TensorProduct(*new_args) elif isinstance(expr, Dagger): return Dagger(represent(expr.args[0], **options)) elif isinstance(expr, Commutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B - B*A elif isinstance(expr, AntiCommutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B + B*A elif isinstance(expr, InnerProduct): return represent(Mul(expr.bra, expr.ket), **options) elif not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): # For numpy and scipy.sparse, we can only handle numerical prefactors. if format == 'numpy' or format == 'scipy.sparse': return _sympy_to_scalar(expr) return expr if not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): raise TypeError('Mul expected, got: %r' % expr) if "index" in options: options["index"] += 1 else: options["index"] = 1 if not "unities" in options: options["unities"] = [] result = represent(expr.args[-1], **options) last_arg = expr.args[-1] for arg in reversed(expr.args[:-1]): if isinstance(last_arg, Operator): options["index"] += 1 options["unities"].append(options["index"]) elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase): options["index"] += 1 elif isinstance(last_arg, KetBase) and isinstance(arg, Operator): options["unities"].append(options["index"]) elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase): options["unities"].append(options["index"]) result = represent(arg, **options)*result last_arg = arg # All three matrix formats create 1 by 1 matrices when inner products of # vectors are taken. In these cases, we simply return a scalar. result = flatten_scalar(result) result = integrate_result(expr, result, **options) return result def rep_innerproduct(expr, **options): """ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the given state. Attempts to calculate inner product with a bra from the specified basis. Should only be passed an instance of KetBase or BraBase Parameters ========== expr : KetBase or BraBase The expression to be represented Examples ======== >>> from sympy.physics.quantum.represent import rep_innerproduct >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> rep_innerproduct(XKet()) DiracDelta(x - x_1) >>> rep_innerproduct(XKet(), basis=PxOp()) sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi)) >>> rep_innerproduct(PxKet(), basis=XOp()) sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi)) """ if not isinstance(expr, (KetBase, BraBase)): raise TypeError("expr passed is not a Bra or Ket") basis = get_basis(expr, **options) if not isinstance(basis, StateBase): raise NotImplementedError("Can't form this representation!") if not "index" in options: options["index"] = 1 basis_kets = enumerate_states(basis, options["index"], 2) if isinstance(expr, BraBase): bra = expr ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0]) else: bra = (basis_kets[1].dual if basis_kets[0] == expr else basis_kets[0].dual) ket = expr prod = InnerProduct(bra, ket) result = prod.doit() format = options.get('format', 'sympy') return expr._format_represent(result, format) def rep_expectation(expr, **options): """ Returns an ``<x'|A|x>`` type representation for the given operator. Parameters ========== expr : Operator Operator to be represented in the specified basis Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> from sympy.physics.quantum.represent import rep_expectation >>> rep_expectation(XOp()) x_1*DiracDelta(x_1 - x_2) >>> rep_expectation(XOp(), basis=PxOp()) <px_2|*X*|px_1> >>> rep_expectation(XOp(), basis=PxKet()) <px_2|*X*|px_1> """ if not "index" in options: options["index"] = 1 if not isinstance(expr, Operator): raise TypeError("The passed expression is not an operator") basis_state = get_basis(expr, **options) if basis_state is None or not isinstance(basis_state, StateBase): raise NotImplementedError("Could not get basis kets for this operator") basis_kets = enumerate_states(basis_state, options["index"], 2) bra = basis_kets[1].dual ket = basis_kets[0] return qapply(bra*expr*ket) def integrate_result(orig_expr, result, **options): """ Returns the result of integrating over any unities ``(|x><x|)`` in the given expression. Intended for integrating over the result of representations in continuous bases. This function integrates over any unities that may have been inserted into the quantum expression and returns the result. It uses the interval of the Hilbert space of the basis state passed to it in order to figure out the limits of integration. The unities option must be specified for this to work. Note: This is mostly used internally by represent(). Examples are given merely to show the use cases. Parameters ========== orig_expr : quantum expression The original expression which was to be represented result: Expr The resulting representation that we wish to integrate over Examples ======== >>> from sympy import symbols, DiracDelta >>> from sympy.physics.quantum.represent import integrate_result >>> from sympy.physics.quantum.cartesian import XOp, XKet >>> x_ket = XKet() >>> X_op = XOp() >>> x, x_1, x_2 = symbols('x, x_1, x_2') >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2)) x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2) >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2), ... unities=[1]) x*DiracDelta(x - x_2) """ if not isinstance(result, Expr): return result options['replace_none'] = True if not "basis" in options: arg = orig_expr.args[-1] options["basis"] = get_basis(arg, **options) elif not isinstance(options["basis"], StateBase): options["basis"] = get_basis(orig_expr, **options) basis = options.pop("basis", None) if basis is None: return result unities = options.pop("unities", []) if len(unities) == 0: return result kets = enumerate_states(basis, unities) coords = [k.label[0] for k in kets] for coord in coords: if coord in result.free_symbols: #TODO: Add support for sets of operators basis_op = state_to_operators(basis) start = basis_op.hilbert_space.interval.start end = basis_op.hilbert_space.interval.end result = integrate(result, (coord, start, end)) return result def get_basis(expr, **options): """ Returns a basis state instance corresponding to the basis specified in options=s. If no basis is specified, the function tries to form a default basis state of the given expression. There are three behaviors: 1. The basis specified in options is already an instance of StateBase. If this is the case, it is simply returned. If the class is specified but not an instance, a default instance is returned. 2. The basis specified is an operator or set of operators. If this is the case, the operator_to_state mapping method is used. 3. No basis is specified. If expr is a state, then a default instance of its class is returned. If expr is an operator, then it is mapped to the corresponding state. If it is neither, then we cannot obtain the basis state. If the basis cannot be mapped, then it is not changed. This will be called from within represent, and represent will only pass QExpr's. TODO (?): Support for Muls and other types of expressions? Parameters ========== expr : Operator or StateBase Expression whose basis is sought Examples ======== >>> from sympy.physics.quantum.represent import get_basis >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> x = XKet() >>> X = XOp() >>> get_basis(x) |x> >>> get_basis(X) |x> >>> get_basis(x, basis=PxOp()) |px> >>> get_basis(x, basis=PxKet) |px> """ basis = options.pop("basis", None) replace_none = options.pop("replace_none", True) if basis is None and not replace_none: return None if basis is None: if isinstance(expr, KetBase): return _make_default(expr.__class__) elif isinstance(expr, BraBase): return _make_default((expr.dual_class())) elif isinstance(expr, Operator): state_inst = operators_to_state(expr) return (state_inst if state_inst is not None else None) else: return None elif (isinstance(basis, Operator) or (not isinstance(basis, StateBase) and issubclass(basis, Operator))): state = operators_to_state(basis) if state is None: return None elif isinstance(state, StateBase): return state else: return _make_default(state) elif isinstance(basis, StateBase): return basis elif issubclass(basis, StateBase): return _make_default(basis) else: return None def _make_default(expr): try: expr = expr() except Exception: return expr return expr def enumerate_states(*args, **options): """ Returns instances of the given state with dummy indices appended Operates in two different modes: 1. Two arguments are passed to it. The first is the base state which is to be indexed, and the second argument is a list of indices to append. 2. Three arguments are passed. The first is again the base state to be indexed. The second is the start index for counting. The final argument is the number of kets you wish to receive. Tries to call state._enumerate_state. If this fails, returns an empty list Parameters ========== args : list See list of operation modes above for explanation Examples ======== >>> from sympy.physics.quantum.cartesian import XBra, XKet >>> from sympy.physics.quantum.represent import enumerate_states >>> test = XKet('foo') >>> enumerate_states(test, 1, 3) [|foo_1>, |foo_2>, |foo_3>] >>> test2 = XBra('bar') >>> enumerate_states(test2, [4, 5, 10]) [<bar_4|, <bar_5|, <bar_10|] """ state = args[0] if not (len(args) == 2 or len(args) == 3): raise NotImplementedError("Wrong number of arguments!") if not isinstance(state, StateBase): raise TypeError("First argument is not a state!") if len(args) == 3: num_states = args[2] options['start_index'] = args[1] else: num_states = len(args[1]) options['index_list'] = args[1] try: ret = state._enumerate_state(num_states, **options) except NotImplementedError: ret = [] return ret
17,924
31.239209
84
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/qapply.py
"""Logic for applying operators to states. Todo: * Sometimes the final result needs to be expanded, we should do this by hand. """ from __future__ import print_function, division from sympy import Add, Mul, Pow, sympify, S from sympy.core.compatibility import range from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.operator import OuterProduct, Operator from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction from sympy.physics.quantum.tensorproduct import TensorProduct __all__ = [ 'qapply' ] #----------------------------------------------------------------------------- # Main code #----------------------------------------------------------------------------- def qapply(e, **options): """Apply operators to states in a quantum expression. Parameters ========== e : Expr The expression containing operators and states. This expression tree will be walked to find operators acting on states symbolically. options : dict A dict of key/value pairs that determine how the operator actions are carried out. The following options are valid: * ``dagger``: try to apply Dagger operators to the left (default: False). * ``ip_doit``: call ``.doit()`` in inner products when they are encountered (default: True). Returns ======= e : Expr The original expression, but with the operators applied to states. Examples ======== >>> from sympy.physics.quantum import qapply, Ket, Bra >>> b = Bra('b') >>> k = Ket('k') >>> A = k * b >>> A |k><b| >>> qapply(A * b.dual / (b * b.dual)) |k> >>> qapply(k.dual * A / (k.dual * k), dagger=True) <b| >>> qapply(k.dual * A / (k.dual * k)) <k|*|k><b|/<k|k> """ from sympy.physics.quantum.density import Density dagger = options.get('dagger', False) if e == 0: return S.Zero # This may be a bit aggressive but ensures that everything gets expanded # to its simplest form before trying to apply operators. This includes # things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and # TensorProducts. The only problem with this is that if we can't apply # all the Operators, we have just expanded everything. # TODO: don't expand the scalars in front of each Mul. e = e.expand(commutator=True, tensorproduct=True) # If we just have a raw ket, return it. if isinstance(e, KetBase): return e # We have an Add(a, b, c, ...) and compute # Add(qapply(a), qapply(b), ...) elif isinstance(e, Add): result = 0 for arg in e.args: result += qapply(arg, **options) return result # For a Density operator call qapply on its state elif isinstance(e, Density): new_args = [(qapply(state, **options), prob) for (state, prob) in e.args] return Density(*new_args) # For a raw TensorProduct, call qapply on its args. elif isinstance(e, TensorProduct): return TensorProduct(*[qapply(t, **options) for t in e.args]) # For a Pow, call qapply on its base. elif isinstance(e, Pow): return qapply(e.base, **options)**e.exp # We have a Mul where there might be actual operators to apply to kets. elif isinstance(e, Mul): result = qapply_Mul(e, **options) if result == e and dagger: return Dagger(qapply_Mul(Dagger(e), **options)) else: return result # In all other cases (State, Operator, Pow, Commutator, InnerProduct, # OuterProduct) we won't ever have operators to apply to kets. else: return e def qapply_Mul(e, **options): ip_doit = options.get('ip_doit', True) args = list(e.args) # If we only have 0 or 1 args, we have nothing to do and return. if len(args) <= 1 or not isinstance(e, Mul): return e rhs = args.pop() lhs = args.pop() # Make sure we have two non-commutative objects before proceeding. if (sympify(rhs).is_commutative and not isinstance(rhs, Wavefunction)) or \ (sympify(lhs).is_commutative and not isinstance(lhs, Wavefunction)): return e # For a Pow with an integer exponent, apply one of them and reduce the # exponent by one. if isinstance(lhs, Pow) and lhs.exp.is_Integer: args.append(lhs.base**(lhs.exp - 1)) lhs = lhs.base # Pull OuterProduct apart if isinstance(lhs, OuterProduct): args.append(lhs.ket) lhs = lhs.bra # Call .doit() on Commutator/AntiCommutator. if isinstance(lhs, (Commutator, AntiCommutator)): comm = lhs.doit() if isinstance(comm, Add): return qapply( e.func(*(args + [comm.args[0], rhs])) + e.func(*(args + [comm.args[1], rhs])), **options ) else: return qapply(e.func(*args)*comm*rhs, **options) # Apply tensor products of operators to states if isinstance(lhs, TensorProduct) and all([isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args]) and \ isinstance(rhs, TensorProduct) and all([isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args]) and \ len(lhs.args) == len(rhs.args): result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True) return qapply_Mul(e.func(*args), **options)*result # Now try to actually apply the operator and build an inner product. try: result = lhs._apply_operator(rhs, **options) except (NotImplementedError, AttributeError): try: result = rhs._apply_operator(lhs, **options) except (NotImplementedError, AttributeError): if isinstance(lhs, BraBase) and isinstance(rhs, KetBase): result = InnerProduct(lhs, rhs) if ip_doit: result = result.doit() else: result = None # TODO: I may need to expand before returning the final result. if result == 0: return S.Zero elif result is None: if len(args) == 0: # We had two args to begin with so args=[]. return e else: return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs elif isinstance(result, InnerProduct): return result*qapply_Mul(e.func(*args), **options) else: # result is a scalar times a Mul, Add or TensorProduct return qapply(e.func(*args)*result, **options)
6,887
33.44
136
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/matrixcache.py
"""A cache for storing small matrices in multiple formats.""" from __future__ import print_function, division from sympy import Matrix, I, Pow, Rational, exp, pi from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse ) class MatrixCache(object): """A cache for small matrices in different formats. This class takes small matrices in the standard ``sympy.Matrix`` format, and then converts these to both ``numpy.matrix`` and ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for future recovery. """ def __init__(self, dtype='complex'): self._cache = {} self.dtype = dtype def cache_matrix(self, name, m): """Cache a matrix by its name. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". m : list of lists The raw matrix data as a sympy Matrix. """ try: self._sympy_matrix(name, m) except ImportError: pass try: self._numpy_matrix(name, m) except ImportError: pass try: self._scipy_sparse_matrix(name, m) except ImportError: pass def get_matrix(self, name, format): """Get a cached matrix by name and format. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". format : str The format desired ('sympy', 'numpy', 'scipy.sparse') """ m = self._cache.get((name, format)) if m is not None: return m raise NotImplementedError( 'Matrix with name %s and format %s is not available.' % (name, format) ) def _store_matrix(self, name, format, m): self._cache[(name, format)] = m def _sympy_matrix(self, name, m): self._store_matrix(name, 'sympy', to_sympy(m)) def _numpy_matrix(self, name, m): m = to_numpy(m, dtype=self.dtype) self._store_matrix(name, 'numpy', m) def _scipy_sparse_matrix(self, name, m): # TODO: explore different sparse formats. But sparse.kron will use # coo in most cases, so we use that here. m = to_scipy_sparse(m, dtype=self.dtype) self._store_matrix(name, 'scipy.sparse', m) sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False) # Save the common matrices that we will need matrix_cache = MatrixCache() matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]])) matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1| matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0| matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0| matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1| matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]])) matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]])) matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]])) matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]])) matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]])) matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix( 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])) matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
3,519
33.174757
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/pauli.py
"""Pauli operators and states""" from sympy import I, Mul, Add, Pow, exp, Integer from sympy.physics.quantum import Operator, Ket, Bra from sympy.physics.quantum import ComplexSpace from sympy.matrices import Matrix from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'SigmaPlus', 'SigmaZKet', 'SigmaZBra', 'qsimplify_pauli' ] class SigmaOpBase(Operator): """Pauli sigma operator, base class""" @property def name(self): return self.args[0] @property def use_name(self): return bool(self.args[0]) is not False @classmethod def default_args(self): return (False,) def __new__(cls, *args, **hints): return Operator.__new__(cls, *args, **hints) def _eval_commutator_BosonOp(self, other, **hints): return Integer(0) class SigmaX(SigmaOpBase): """Pauli sigma x operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaX >>> sx = SigmaX() >>> sx SigmaX() >>> represent(sx) Matrix([ [0, 1], [1, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args, **hints) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return Integer(0) else: return 2 * I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return Integer(0) else: return - 2 * I * SigmaY(self.name) def _eval_commutator_BosonOp(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaY(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaZ(self, other, **hints): return Integer(0) def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_x^{(%s)}}' % str(self.name) else: return r'{\sigma_x}' def _print_contents(self, printer, *args): return 'SigmaX()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaX(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 1], [1, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaY(SigmaOpBase): """Pauli sigma y operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaY >>> sy = SigmaY() >>> sy SigmaY() >>> represent(sy) Matrix([ [0, -I], [I, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return Integer(0) else: return 2 * I * SigmaX(self.name) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return Integer(0) else: return - 2 * I * SigmaZ(self.name) def _eval_anticommutator_SigmaX(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaZ(self, other, **hints): return Integer(0) def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_y^{(%s)}}' % str(self.name) else: return r'{\sigma_y}' def _print_contents(self, printer, *args): return 'SigmaY()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaY(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, -I], [I, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZ(SigmaOpBase): """Pauli sigma z operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent >>> from sympy.physics.quantum.pauli import SigmaZ >>> sz = SigmaZ() >>> sz ** 3 SigmaZ() >>> represent(sz) Matrix([ [1, 0], [0, -1]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return Integer(0) else: return 2 * I * SigmaY(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return Integer(0) else: return - 2 * I * SigmaX(self.name) def _eval_anticommutator_SigmaX(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaY(self, other, **hints): return Integer(0) def _eval_adjoint(self): return self def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_z^{(%s)}}' % str(self.name) else: return r'{\sigma_z}' def _print_contents(self, printer, *args): return 'SigmaZ()' def _eval_power(self, e): if e.is_Integer and e.is_positive: return SigmaZ(self.name).__pow__(int(e) % 2) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[1, 0], [0, -1]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaMinus(SigmaOpBase): """Pauli sigma minus operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent, Dagger >>> from sympy.physics.quantum.pauli import SigmaMinus >>> sm = SigmaMinus() >>> sm SigmaMinus() >>> Dagger(sm) SigmaPlus() >>> represent(sm) Matrix([ [0, 0], [1, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return Integer(0) else: return -SigmaZ(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return Integer(0) else: return I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): return 2 * self def _eval_commutator_SigmaMinus(self, other, **hints): return SigmaZ(self.name) def _eval_anticommutator_SigmaZ(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaX(self, other, **hints): return Integer(1) def _eval_anticommutator_SigmaY(self, other, **hints): return - I * Integer(1) def _eval_anticommutator_SigmaPlus(self, other, **hints): return Integer(1) def _eval_adjoint(self): return SigmaPlus(self.name) def _eval_power(self, e): if e.is_Integer and e.is_positive: return Integer(0) def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_-^{(%s)}}' % str(self.name) else: return r'{\sigma_-}' def _print_contents(self, printer, *args): return 'SigmaMinus()' def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 0], [1, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaPlus(SigmaOpBase): """Pauli sigma plus operator Parameters ========== name : str An optional string that labels the operator. Pauli operators with different names commute. Examples ======== >>> from sympy.physics.quantum import represent, Dagger >>> from sympy.physics.quantum.pauli import SigmaPlus >>> sp = SigmaPlus() >>> sp SigmaPlus() >>> Dagger(sp) SigmaMinus() >>> represent(sp) Matrix([ [0, 1], [0, 0]]) """ def __new__(cls, *args, **hints): return SigmaOpBase.__new__(cls, *args) def _eval_commutator_SigmaX(self, other, **hints): if self.name != other.name: return Integer(0) else: return SigmaZ(self.name) def _eval_commutator_SigmaY(self, other, **hints): if self.name != other.name: return Integer(0) else: return I * SigmaZ(self.name) def _eval_commutator_SigmaZ(self, other, **hints): if self.name != other.name: return Integer(0) else: return -2 * self def _eval_commutator_SigmaMinus(self, other, **hints): return SigmaZ(self.name) def _eval_anticommutator_SigmaZ(self, other, **hints): return Integer(0) def _eval_anticommutator_SigmaX(self, other, **hints): return Integer(1) def _eval_anticommutator_SigmaY(self, other, **hints): return I * Integer(1) def _eval_anticommutator_SigmaMinus(self, other, **hints): return Integer(1) def _eval_adjoint(self): return SigmaMinus(self.name) def _eval_mul(self, other): return self * other def _eval_power(self, e): if e.is_Integer and e.is_positive: return Integer(0) def _print_contents_latex(self, printer, *args): if self.use_name: return r'{\sigma_+^{(%s)}}' % str(self.name) else: return r'{\sigma_+}' def _print_contents(self, printer, *args): return 'SigmaPlus()' def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[0, 1], [0, 0]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZKet(Ket): """Ket for a two-level system quantum system. Parameters ========== n : Number The state number (0 or 1). """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return SigmaZBra @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2) def _eval_innerproduct_SigmaZBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_operator_SigmaZ(self, op, **options): if self.n == 0: return self else: return Integer(-1) * self def _apply_operator_SigmaX(self, op, **options): return SigmaZKet(1) if self.n == 0 else SigmaZKet(0) def _apply_operator_SigmaY(self, op, **options): return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0) def _apply_operator_SigmaMinus(self, op, **options): if self.n == 0: return SigmaZKet(1) else: return Integer(0) def _apply_operator_SigmaPlus(self, op, **options): if self.n == 0: return Integer(0) else: return SigmaZKet(0) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.') class SigmaZBra(Bra): """Bra for a two-level quantum system. Parameters ========== n : Number The state number (0 or 1). """ def __new__(cls, n): if n not in [0, 1]: raise ValueError("n must be 0 or 1") return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return SigmaZKet def _qsimplify_pauli_product(a, b): """ Internal helper function for simplifying products of Pauli operators. """ if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)): return Mul(a, b) if a.name != b.name: # Pauli matrices with different labels commute; sort by name if a.name < b.name: return Mul(a, b) else: return Mul(b, a) elif isinstance(a, SigmaX): if isinstance(b, SigmaX): return Integer(1) if isinstance(b, SigmaY): return I * SigmaZ(a.name) if isinstance(b, SigmaZ): return - I * SigmaY(a.name) if isinstance(b, SigmaMinus): return (Integer(1)/2 + SigmaZ(a.name)/2) if isinstance(b, SigmaPlus): return (Integer(1)/2 - SigmaZ(a.name)/2) elif isinstance(a, SigmaY): if isinstance(b, SigmaX): return - I * SigmaZ(a.name) if isinstance(b, SigmaY): return Integer(1) if isinstance(b, SigmaZ): return I * SigmaX(a.name) if isinstance(b, SigmaMinus): return -I * (Integer(1) + SigmaZ(a.name))/2 if isinstance(b, SigmaPlus): return I * (Integer(1) - SigmaZ(a.name))/2 elif isinstance(a, SigmaZ): if isinstance(b, SigmaX): return I * SigmaY(a.name) if isinstance(b, SigmaY): return - I * SigmaX(a.name) if isinstance(b, SigmaZ): return Integer(1) if isinstance(b, SigmaMinus): return - SigmaMinus(a.name) if isinstance(b, SigmaPlus): return SigmaPlus(a.name) elif isinstance(a, SigmaMinus): if isinstance(b, SigmaX): return (Integer(1) - SigmaZ(a.name))/2 if isinstance(b, SigmaY): return - I * (Integer(1) - SigmaZ(a.name))/2 if isinstance(b, SigmaZ): # (SigmaX(a.name) - I * SigmaY(a.name))/2 return SigmaMinus(b.name) if isinstance(b, SigmaMinus): return Integer(0) if isinstance(b, SigmaPlus): return Integer(1)/2 - SigmaZ(a.name)/2 elif isinstance(a, SigmaPlus): if isinstance(b, SigmaX): return (Integer(1) + SigmaZ(a.name))/2 if isinstance(b, SigmaY): return I * (Integer(1) + SigmaZ(a.name))/2 if isinstance(b, SigmaZ): #-(SigmaX(a.name) + I * SigmaY(a.name))/2 return -SigmaPlus(a.name) if isinstance(b, SigmaMinus): return (Integer(1) + SigmaZ(a.name))/2 if isinstance(b, SigmaPlus): return Integer(0) else: return a * b def qsimplify_pauli(e): """ Simplify an expression that includes products of pauli operators. Parameters ========== e : expression An expression that contains products of Pauli operators that is to be simplified. Examples ======== >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY >>> from sympy.physics.quantum.pauli import qsimplify_pauli >>> sx, sy = SigmaX(), SigmaY() >>> sx * sy SigmaX()*SigmaY() >>> qsimplify_pauli(sx * sy) I*SigmaZ() """ if isinstance(e, Operator): return e if isinstance(e, (Add, Pow, exp)): t = type(e) return t(*(qsimplify_pauli(arg) for arg in e.args)) if isinstance(e, Mul): c, nc = e.args_cnc() nc_s = [] while nc: curr = nc.pop(0) while (len(nc) and isinstance(curr, SigmaOpBase) and isinstance(nc[0], SigmaOpBase) and curr.name == nc[0].name): x = nc.pop(0) y = _qsimplify_pauli_product(curr, x) c1, nc1 = y.args_cnc() curr = Mul(*nc1) c = c + c1 nc_s.append(curr) return Mul(*c) * Mul(*nc_s) return e
17,262
24.727273
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/operator.py
"""Quantum mechanical operators. TODO: * Fix early 0 in apply_operators. * Debug and test apply_operators. * Get cse working with classes in this file. * Doctests and documentation of special methods for InnerProduct, Commutator, AntiCommutator, represent, apply_operators. """ from __future__ import print_function, division from sympy import Derivative, Expr, Integer, oo, Mul, expand, Add from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.qexpr import QExpr, dispatch_method from sympy.matrices import eye __all__ = [ 'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator', 'OuterProduct', 'DifferentialOperator' ] #----------------------------------------------------------------------------- # Operators and outer products #----------------------------------------------------------------------------- class Operator(QExpr): """Base class for non-commuting quantum operators. An operator maps between quantum states [1]_. In quantum mechanics, observables (including, but not limited to, measured physical values) are represented as Hermitian operators [2]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== Create an operator and examine its attributes:: >>> from sympy.physics.quantum import Operator >>> from sympy import symbols, I >>> A = Operator('A') >>> A A >>> A.hilbert_space H >>> A.label (A,) >>> A.is_commutative False Create another operator and do some arithmetic operations:: >>> B = Operator('B') >>> C = 2*A*A + I*B >>> C 2*A**2 + I*B Operators don't commute:: >>> A.is_commutative False >>> B.is_commutative False >>> A*B == B*A False Polymonials of operators respect the commutation properties:: >>> e = (A+B)**3 >>> e.expand() A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3 Operator inverses are handle symbolically:: >>> A.inv() A**(-1) >>> A*A.inv() 1 References ========== .. [1] http://en.wikipedia.org/wiki/Operator_%28physics%29 .. [2] http://en.wikipedia.org/wiki/Observable """ @classmethod def default_args(self): return ("O",) #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- _label_separator = ',' def _print_operator_name(self, printer, *args): return printer._print(self.__class__.__name__, *args) _print_operator_name_latex = _print_operator_name def _print_operator_name_pretty(self, printer, *args): return prettyForm(self.__class__.__name__) def _print_contents(self, printer, *args): if len(self.label) == 1: return self._print_label(printer, *args) else: return '%s(%s)' % ( self._print_operator_name(printer, *args), self._print_label(printer, *args) ) def _print_contents_pretty(self, printer, *args): if len(self.label) == 1: return self._print_label_pretty(printer, *args) else: pform = self._print_operator_name_pretty(printer, *args) label_pform = self._print_label_pretty(printer, *args) label_pform = prettyForm( *label_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right((label_pform))) return pform def _print_contents_latex(self, printer, *args): if len(self.label) == 1: return self._print_label_latex(printer, *args) else: return r'%s\left(%s\right)' % ( self._print_operator_name_latex(printer, *args), self._print_label_latex(printer, *args) ) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_commutator(self, other, **options): """Evaluate [self, other] if known, return None if not known.""" return dispatch_method(self, '_eval_commutator', other, **options) def _eval_anticommutator(self, other, **options): """Evaluate [self, other] if known.""" return dispatch_method(self, '_eval_anticommutator', other, **options) #------------------------------------------------------------------------- # Operator application #------------------------------------------------------------------------- def _apply_operator(self, ket, **options): return dispatch_method(self, '_apply_operator', ket, **options) def matrix_element(self, *args): raise NotImplementedError('matrix_elements is not defined') def inverse(self): return self._eval_inverse() inv = inverse def _eval_inverse(self): return self**(-1) def __mul__(self, other): if isinstance(other, IdentityOperator): return self return Mul(self, other) class HermitianOperator(Operator): """A Hermitian operator that satisfies H == Dagger(H). Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== >>> from sympy.physics.quantum import Dagger, HermitianOperator >>> H = HermitianOperator('H') >>> Dagger(H) H """ is_hermitian = True def _eval_inverse(self): if isinstance(self, UnitaryOperator): return self else: return Operator._eval_inverse(self) def _eval_power(self, exp): if isinstance(self, UnitaryOperator): if exp == -1: return Operator._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Operator._eval_inverse(self)) else: return self else: return Operator._eval_power(self, exp) class UnitaryOperator(Operator): """A unitary operator that satisfies U*Dagger(U) == 1. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== >>> from sympy.physics.quantum import Dagger, UnitaryOperator >>> U = UnitaryOperator('U') >>> U*Dagger(U) 1 """ def _eval_adjoint(self): return self._eval_inverse() class IdentityOperator(Operator): """An identity operator I that satisfies op * I == I * op == op for any operator op. Parameters ========== N : Integer Optional parameter that specifies the dimension of the Hilbert space of operator. This is used when generating a matrix representation. Examples ======== >>> from sympy.physics.quantum import IdentityOperator >>> IdentityOperator() I """ @property def dimension(self): return self.N @classmethod def default_args(self): return (oo,) def __init__(self, *args, **hints): if not len(args) in [0, 1]: raise ValueError('0 or 1 parameters expected, got %s' % args) self.N = args[0] if (len(args) == 1 and args[0]) else oo def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return 2 * other def _eval_inverse(self): return self def _eval_adjoint(self): return self def _apply_operator(self, ket, **options): return ket def _eval_power(self, exp): return self def _print_contents(self, printer, *args): return 'I' def _print_contents_pretty(self, printer, *args): return prettyForm('I') def _print_contents_latex(self, printer, *args): return r'{\mathcal{I}}' def __mul__(self, other): if isinstance(other, Operator): return other return Mul(self, other) def _represent_default_basis(self, **options): if not self.N or self.N == oo: raise NotImplementedError('Cannot represent infinite dimensional' + ' identity operator as a matrix') format = options.get('format', 'sympy') if format != 'sympy': raise NotImplementedError('Representation in format ' + '%s not implemented.' % format) return eye(self.N) class OuterProduct(Operator): """An unevaluated outer product between a ket and bra. This constructs an outer product between any subclass of ``KetBase`` and ``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as operators in quantum expressions. For reference see [1]_. Parameters ========== ket : KetBase The ket on the left side of the outer product. bar : BraBase The bra on the right side of the outer product. Examples ======== Create a simple outer product by hand and take its dagger:: >>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger >>> from sympy.physics.quantum import Operator >>> k = Ket('k') >>> b = Bra('b') >>> op = OuterProduct(k, b) >>> op |k><b| >>> op.hilbert_space H >>> op.ket |k> >>> op.bra <b| >>> Dagger(op) |b><k| In simple products of kets and bras outer products will be automatically identified and created:: >>> k*b |k><b| But in more complex expressions, outer products are not automatically created:: >>> A = Operator('A') >>> A*k*b A*|k>*<b| A user can force the creation of an outer product in a complex expression by using parentheses to group the ket and bra:: >>> A*(k*b) A*|k><b| References ========== .. [1] http://en.wikipedia.org/wiki/Outer_product """ is_commutative = False def __new__(cls, *args, **old_assumptions): from sympy.physics.quantum.state import KetBase, BraBase if len(args) != 2: raise ValueError('2 parameters expected, got %d' % len(args)) ket_expr = expand(args[0]) bra_expr = expand(args[1]) if (isinstance(ket_expr, (KetBase, Mul)) and isinstance(bra_expr, (BraBase, Mul))): ket_c, kets = ket_expr.args_cnc() bra_c, bras = bra_expr.args_cnc() if len(kets) != 1 or not isinstance(kets[0], KetBase): raise TypeError('KetBase subclass expected' ', got: %r' % Mul(*kets)) if len(bras) != 1 or not isinstance(bras[0], BraBase): raise TypeError('BraBase subclass expected' ', got: %r' % Mul(*bras)) if not kets[0].dual_class() == bras[0].__class__: raise TypeError( 'ket and bra are not dual classes: %r, %r' % (kets[0].__class__, bras[0].__class__) ) # TODO: make sure the hilbert spaces of the bra and ket are # compatible obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions) obj.hilbert_space = kets[0].hilbert_space return Mul(*(ket_c + bra_c)) * obj op_terms = [] if isinstance(ket_expr, Add) and isinstance(bra_expr, Add): for ket_term in ket_expr.args: for bra_term in bra_expr.args: op_terms.append(OuterProduct(ket_term, bra_term, **old_assumptions)) elif isinstance(ket_expr, Add): for ket_term in ket_expr.args: op_terms.append(OuterProduct(ket_term, bra_expr, **old_assumptions)) elif isinstance(bra_expr, Add): for bra_term in bra_expr.args: op_terms.append(OuterProduct(ket_expr, bra_term, **old_assumptions)) else: raise TypeError( 'Expected ket and bra expression, got: %r, %r' % (ket_expr, bra_expr) ) return Add(*op_terms) @property def ket(self): """Return the ket on the left side of the outer product.""" return self.args[0] @property def bra(self): """Return the bra on the right side of the outer product.""" return self.args[1] def _eval_adjoint(self): return OuterProduct(Dagger(self.bra), Dagger(self.ket)) def _sympystr(self, printer, *args): return str(self.ket) + str(self.bra) def _sympyrepr(self, printer, *args): return '%s(%s,%s)' % (self.__class__.__name__, printer._print(self.ket, *args), printer._print(self.bra, *args)) def _pretty(self, printer, *args): pform = self.ket._pretty(printer, *args) return prettyForm(*pform.right(self.bra._pretty(printer, *args))) def _latex(self, printer, *args): k = printer._print(self.ket, *args) b = printer._print(self.bra, *args) return k + b def _represent(self, **options): k = self.ket._represent(**options) b = self.bra._represent(**options) return k*b def _eval_trace(self, **kwargs): # TODO if operands are tensorproducts this may be will be handled # differently. return self.ket._eval_trace(self.bra, **kwargs) class DifferentialOperator(Operator): """An operator for representing the differential operator, i.e. d/dx It is initialized by passing two arguments. The first is an arbitrary expression that involves a function, such as ``Derivative(f(x), x)``. The second is the function (e.g. ``f(x)``) which we are to replace with the ``Wavefunction`` that this ``DifferentialOperator`` is applied to. Parameters ========== expr : Expr The arbitrary expression which the appropriate Wavefunction is to be substituted into func : Expr A function (e.g. f(x)) which is to be replaced with the appropriate Wavefunction when this DifferentialOperator is applied Examples ======== You can define a completely arbitrary expression and specify where the Wavefunction is to be substituted >>> from sympy import Derivative, Function, Symbol >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy.physics.quantum.qapply import qapply >>> f = Function('f') >>> x = Symbol('x') >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) >>> w = Wavefunction(x**2, x) >>> d.function f(x) >>> d.variables (x,) >>> qapply(d*w) Wavefunction(2, x) """ @property def variables(self): """ Returns the variables with which the function in the specified arbitrary expression is evaluated Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Symbol, Function, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) >>> d.variables (x,) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.variables (x, y) """ return self.args[-1].args @property def function(self): """ Returns the function which is to be replaced with the Wavefunction Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Function, Symbol, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(Derivative(f(x), x), f(x)) >>> d.function f(x) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.function f(x, y) """ return self.args[-1] @property def expr(self): """ Returns the arbitary expression which is to have the Wavefunction substituted into it Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Function, Symbol, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(Derivative(f(x), x), f(x)) >>> d.expr Derivative(f(x), x) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.expr Derivative(f(x, y), x) + Derivative(f(x, y), y) """ return self.args[0] @property def free_symbols(self): """ Return the free symbols of the expression. """ return self.expr.free_symbols def _apply_operator_Wavefunction(self, func): from sympy.physics.quantum.state import Wavefunction var = self.variables wf_vars = func.args[1:] f = self.function new_expr = self.expr.subs(f, func(*var)) new_expr = new_expr.doit() return Wavefunction(new_expr, *wf_vars) def _eval_derivative(self, symbol): new_expr = Derivative(self.expr, symbol) return DifferentialOperator(new_expr, self.args[-1]) #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print(self, printer, *args): return '%s(%s)' % ( self._print_operator_name(printer, *args), self._print_label(printer, *args) ) def _print_pretty(self, printer, *args): pform = self._print_operator_name_pretty(printer, *args) label_pform = self._print_label_pretty(printer, *args) label_pform = prettyForm( *label_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right((label_pform))) return pform
19,072
28.570543
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/circuitutils.py
"""Primitive circuit operations on quantum circuits.""" from __future__ import print_function, division from sympy import Symbol, Tuple, Mul, sympify, default_sort_key from sympy.utilities import numbered_symbols from sympy.core.compatibility import reduce from sympy.physics.quantum.gate import Gate __all__ = [ 'kmp_table', 'find_subcircuit', 'replace_subcircuit', 'convert_to_symbolic_indices', 'convert_to_real_indices', 'random_reduce', 'random_insert' ] def kmp_table(word): """Build the 'partial match' table of the Knuth-Morris-Pratt algorithm. Note: This is applicable to strings or quantum circuits represented as tuples. """ # Current position in subcircuit pos = 2 # Beginning position of candidate substring that # may reappear later in word cnd = 0 # The 'partial match' table that helps one determine # the next location to start substring search table = list() table.append(-1) table.append(0) while pos < len(word): if word[pos - 1] == word[cnd]: cnd = cnd + 1 table.append(cnd) pos = pos + 1 elif cnd > 0: cnd = table[cnd] else: table.append(0) pos = pos + 1 return table def find_subcircuit(circuit, subcircuit, start=0, end=0): """Finds the subcircuit in circuit, if it exists. If the subcircuit exists, the index of the start of the subcircuit in circuit is returned; otherwise, -1 is returned. The algorithm that is implemented is the Knuth-Morris-Pratt algorithm. Parameters ========== circuit : tuple, Gate or Mul A tuple of Gates or Mul representing a quantum circuit subcircuit : tuple, Gate or Mul A tuple of Gates or Mul to find in circuit start : int The location to start looking for subcircuit. If start is the same or past end, -1 is returned. end : int The last place to look for a subcircuit. If end is less than 1 (one), then the length of circuit is taken to be end. Examples ======== Find the first instance of a subcircuit: >>> from sympy.physics.quantum.circuitutils import find_subcircuit >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> circuit = X(0)*Z(0)*Y(0)*H(0) >>> subcircuit = Z(0)*Y(0) >>> find_subcircuit(circuit, subcircuit) 1 Find the first instance starting at a specific position: >>> find_subcircuit(circuit, subcircuit, start=1) 1 >>> find_subcircuit(circuit, subcircuit, start=2) -1 >>> circuit = circuit*subcircuit >>> find_subcircuit(circuit, subcircuit, start=2) 4 Find the subcircuit within some interval: >>> find_subcircuit(circuit, subcircuit, start=2, end=2) -1 """ if isinstance(circuit, Mul): circuit = circuit.args if isinstance(subcircuit, Mul): subcircuit = subcircuit.args if len(subcircuit) == 0 or len(subcircuit) > len(circuit): return -1 if end < 1: end = len(circuit) # Location in circuit pos = start # Location in the subcircuit index = 0 # 'Partial match' table table = kmp_table(subcircuit) while (pos + index) < end: if subcircuit[index] == circuit[pos + index]: index = index + 1 else: pos = pos + index - table[index] index = table[index] if table[index] > -1 else 0 if index == len(subcircuit): return pos return -1 def replace_subcircuit(circuit, subcircuit, replace=None, pos=0): """Replaces a subcircuit with another subcircuit in circuit, if it exists. If multiple instances of subcircuit exists, the first instance is replaced. The position to being searching from (if different from 0) may be optionally given. If subcircuit can't be found, circuit is returned. Parameters ========== circuit : tuple, Gate or Mul A quantum circuit subcircuit : tuple, Gate or Mul The circuit to be replaced replace : tuple, Gate or Mul The replacement circuit pos : int The location to start search and replace subcircuit, if it exists. This may be used if it is known beforehand that multiple instances exist, and it is desirable to replace a specific instance. If a negative number is given, pos will be defaulted to 0. Examples ======== Find and remove the subcircuit: >>> from sympy.physics.quantum.circuitutils import replace_subcircuit >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0) >>> subcircuit = Z(0)*Y(0) >>> replace_subcircuit(circuit, subcircuit) (X(0), H(0), X(0), H(0), Y(0)) Remove the subcircuit given a starting search point: >>> replace_subcircuit(circuit, subcircuit, pos=1) (X(0), H(0), X(0), H(0), Y(0)) >>> replace_subcircuit(circuit, subcircuit, pos=2) (X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0)) Replace the subcircuit: >>> replacement = H(0)*Z(0) >>> replace_subcircuit(circuit, subcircuit, replace=replacement) (X(0), H(0), Z(0), H(0), X(0), H(0), Y(0)) """ if pos < 0: pos = 0 if isinstance(circuit, Mul): circuit = circuit.args if isinstance(subcircuit, Mul): subcircuit = subcircuit.args if isinstance(replace, Mul): replace = replace.args elif replace is None: replace = () # Look for the subcircuit starting at pos loc = find_subcircuit(circuit, subcircuit, start=pos) # If subcircuit was found if loc > -1: # Get the gates to the left of subcircuit left = circuit[0:loc] # Get the gates to the right of subcircuit right = circuit[loc + len(subcircuit):len(circuit)] # Recombine the left and right side gates into a circuit circuit = left + replace + right return circuit def _sympify_qubit_map(mapping): new_map = {} for key in mapping: new_map[key] = sympify(mapping[key]) return new_map def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None): """Returns the circuit with symbolic indices and the dictionary mapping symbolic indices to real indices. The mapping is 1 to 1 and onto (bijective). Parameters ========== seq : tuple, Gate/Integer/tuple or Mul A tuple of Gate, Integer, or tuple objects, or a Mul start : Symbol An optional starting symbolic index gen : object An optional numbered symbol generator qubit_map : dict An existing mapping of symbolic indices to real indices All symbolic indices have the format 'i#', where # is some number >= 0. """ if isinstance(seq, Mul): seq = seq.args # A numbered symbol generator index_gen = numbered_symbols(prefix='i', start=-1) cur_ndx = next(index_gen) # keys are symbolic indices; values are real indices ndx_map = {} def create_inverse_map(symb_to_real_map): rev_items = lambda item: tuple([item[1], item[0]]) return dict(map(rev_items, symb_to_real_map.items())) if start is not None: if not isinstance(start, Symbol): msg = 'Expected Symbol for starting index, got %r.' % start raise TypeError(msg) cur_ndx = start if gen is not None: if not isinstance(gen, numbered_symbols().__class__): msg = 'Expected a generator, got %r.' % gen raise TypeError(msg) index_gen = gen if qubit_map is not None: if not isinstance(qubit_map, dict): msg = ('Expected dict for existing map, got ' + '%r.' % qubit_map) raise TypeError(msg) ndx_map = qubit_map ndx_map = _sympify_qubit_map(ndx_map) # keys are real indices; keys are symbolic indices inv_map = create_inverse_map(ndx_map) sym_seq = () for item in seq: # Nested items, so recurse if isinstance(item, Gate): result = convert_to_symbolic_indices(item.args, qubit_map=ndx_map, start=cur_ndx, gen=index_gen) sym_item, new_map, cur_ndx, index_gen = result ndx_map.update(new_map) inv_map = create_inverse_map(ndx_map) elif isinstance(item, tuple) or isinstance(item, Tuple): result = convert_to_symbolic_indices(item, qubit_map=ndx_map, start=cur_ndx, gen=index_gen) sym_item, new_map, cur_ndx, index_gen = result ndx_map.update(new_map) inv_map = create_inverse_map(ndx_map) elif item in inv_map: sym_item = inv_map[item] else: cur_ndx = next(gen) ndx_map[cur_ndx] = item inv_map[item] = cur_ndx sym_item = cur_ndx if isinstance(item, Gate): sym_item = item.__class__(*sym_item) sym_seq = sym_seq + (sym_item,) return sym_seq, ndx_map, cur_ndx, index_gen def convert_to_real_indices(seq, qubit_map): """Returns the circuit with real indices. Parameters ========== seq : tuple, Gate/Integer/tuple or Mul A tuple of Gate, Integer, or tuple objects or a Mul qubit_map : dict A dictionary mapping symbolic indices to real indices. Examples ======== Change the symbolic indices to real integers: >>> from sympy import symbols >>> from sympy.physics.quantum.circuitutils import convert_to_real_indices >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> i0, i1 = symbols('i:2') >>> index_map = {i0 : 0, i1 : 1} >>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map) (X(0), Y(1), H(0), X(1)) """ if isinstance(seq, Mul): seq = seq.args if not isinstance(qubit_map, dict): msg = 'Expected dict for qubit_map, got %r.' % qubit_map raise TypeError(msg) qubit_map = _sympify_qubit_map(qubit_map) real_seq = () for item in seq: # Nested items, so recurse if isinstance(item, Gate): real_item = convert_to_real_indices(item.args, qubit_map) elif isinstance(item, tuple) or isinstance(item, Tuple): real_item = convert_to_real_indices(item, qubit_map) else: real_item = qubit_map[item] if isinstance(item, Gate): real_item = item.__class__(*real_item) real_seq = real_seq + (real_item,) return real_seq def random_reduce(circuit, gate_ids, seed=None): """Shorten the length of a quantum circuit. random_reduce looks for circuit identities in circuit, randomly chooses one to remove, and returns a shorter yet equivalent circuit. If no identities are found, the same circuit is returned. Parameters ========== circuit : Gate tuple of Mul A tuple of Gates representing a quantum circuit gate_ids : list, GateIdentity List of gate identities to find in circuit seed : int or list seed used for _randrange; to override the random selection, provide a list of integers: the elements of gate_ids will be tested in the order given by the list """ from sympy.utilities.randtest import _randrange if not gate_ids: return circuit if isinstance(circuit, Mul): circuit = circuit.args ids = flatten_ids(gate_ids) # Create the random integer generator with the seed randrange = _randrange(seed) # Look for an identity in the circuit while ids: i = randrange(len(ids)) id = ids.pop(i) if find_subcircuit(circuit, id) != -1: break else: # no identity was found return circuit # return circuit with the identity removed return replace_subcircuit(circuit, id) def random_insert(circuit, choices, seed=None): """Insert a circuit into another quantum circuit. random_insert randomly chooses a location in the circuit to insert a randomly selected circuit from amongst the given choices. Parameters ========== circuit : Gate tuple or Mul A tuple or Mul of Gates representing a quantum circuit choices : list Set of circuit choices seed : int or list seed used for _randrange; to override the random selections, give a list two integers, [i, j] where i is the circuit location where choice[j] will be inserted. Notes ===== Indices for insertion should be [0, n] if n is the length of the circuit. """ from sympy.utilities.randtest import _randrange if not choices: return circuit if isinstance(circuit, Mul): circuit = circuit.args # get the location in the circuit and the element to insert from choices randrange = _randrange(seed) loc = randrange(len(circuit) + 1) choice = choices[randrange(len(choices))] circuit = list(circuit) circuit[loc: loc] = choice return tuple(circuit) # Flatten the GateIdentity objects (with gate rules) into one single list def flatten_ids(ids): collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids, key=default_sort_key) ids = reduce(collapse, ids, []) ids.sort(key=default_sort_key) return ids
13,742
27.993671
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/shor.py
"""Shor's algorithm and helper functions. Todo: * Get the CMod gate working again using the new Gate API. * Fix everything. * Update docstrings and reformat. * Remove print statements. We may want to think about a better API for this. """ from __future__ import print_function, division import math import random from sympy import Mul, S from sympy import log, sqrt from sympy.core.numbers import igcd from sympy.core.compatibility import range from sympy.ntheory import continued_fraction_periodic as continued_fraction from sympy.utilities.iterables import variations from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qft import QFT from sympy.physics.quantum.qexpr import QuantumError class OrderFindingException(QuantumError): pass class CMod(Gate): """A controlled mod gate. This is black box controlled Mod function for use by shor's algorithm. TODO implement a decompose property that returns how to do this in terms of elementary gates """ @classmethod def _eval_args(cls, args): # t = args[0] # a = args[1] # N = args[2] raise NotImplementedError('The CMod gate has not been completed.') @property def t(self): """Size of 1/2 input register. First 1/2 holds output.""" return self.label[0] @property def a(self): """Base of the controlled mod function.""" return self.label[1] @property def N(self): """N is the type of modular arithmetic we are doing.""" return self.label[2] def _apply_operator_Qubit(self, qubits, **options): """ This directly calculates the controlled mod of the second half of the register and puts it in the second This will look pretty when we get Tensor Symbolically working """ n = 1 k = 0 # Determine the value stored in high memory. for i in range(self.t): k = k + n*qubits[self.t + i] n = n*2 # The value to go in low memory will be out. out = int(self.a**k % self.N) # Create array for new qbit-ket which will have high memory unaffected outarray = list(qubits.args[0][:self.t]) # Place out in low memory for i in reversed(range(self.t)): outarray.append((out >> i) & 1) return Qubit(*outarray) def shor(N): """This function implements Shor's factoring algorithm on the Integer N The algorithm starts by picking a random number (a) and seeing if it is coprime with N. If it isn't, then the gcd of the two numbers is a factor and we are done. Otherwise, it begins the period_finding subroutine which finds the period of a in modulo N arithmetic. This period, if even, can be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1. These values are returned. """ a = random.randrange(N - 2) + 2 if igcd(N, a) != 1: print("got lucky with rand") return igcd(N, a) print("a= ", a) print("N= ", N) r = period_find(a, N) print("r= ", r) if r % 2 == 1: print("r is not even, begin again") shor(N) answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N)) return answer def getr(x, y, N): fraction = continued_fraction(x, y) # Now convert into r total = ratioize(fraction, N) return total def ratioize(list, N): if list[0] > N: return S.Zero if len(list) == 1: return list[0] return list[0] + ratioize(list[1:], N) def period_find(a, N): """Finds the period of a in modulo N arithmetic This is quantum part of Shor's algorithm.It takes two registers, puts first in superposition of states with Hadamards so: ``|k>|0>`` with k being all possible choices. It then does a controlled mod and a QFT to determine the order of a. """ epsilon = .5 #picks out t's such that maintains accuracy within epsilon t = int(2*math.ceil(log(N, 2))) # make the first half of register be 0's |000...000> start = [0 for x in range(t)] #Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0> factor = 1/sqrt(2**t) qubits = 0 for arr in variations(range(2), t, repetition=True): qbitArray = arr + start qubits = qubits + Qubit(*qbitArray) circuit = (factor*qubits).expand() #Controlled second half of register so that we have: # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n> circuit = CMod(t, a, N)*circuit #will measure first half of register giving one of the a**k%N's circuit = qapply(circuit) print("controlled Mod'd") for i in range(t): circuit = measure_partial_oneshot(circuit, i) print("measured 1") #Now apply Inverse Quantum Fourier Transform on the second half of the register circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True) print("QFT'd") for i in range(t): circuit = measure_partial_oneshot(circuit, i + t) print(circuit) if isinstance(circuit, Qubit): register = circuit elif isinstance(circuit, Mul): register = circuit.args[-1] else: register = circuit.args[-1].args[-1] print(register) n = 1 answer = 0 for i in range(len(register)/2): answer += n*register[i + t] n = n << 1 if answer == 0: raise OrderFindingException( "Order finder returned 0. Happens with chance %f" % epsilon) #turn answer into r using continued fractions g = getr(answer, 2**t, N) print(g) return g
5,800
30.527174
114
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/innerproduct.py
"""Symbolic inner product.""" from __future__ import print_function, division from sympy import Expr, conjugate from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import KetBase, BraBase __all__ = [ 'InnerProduct' ] # InnerProduct is not an QExpr because it is really just a regular commutative # number. We have gone back and forth about this, but we gain a lot by having # it subclass Expr. The main challenges were getting Dagger to work # (we use _eval_conjugate) and represent (we can use atoms and subs). Having # it be an Expr, mean that there are no commutative QExpr subclasses, # which simplifies the design of everything. class InnerProduct(Expr): """An unevaluated inner product between a Bra and a Ket [1]. Parameters ========== bra : BraBase or subclass The bra on the left side of the inner product. ket : KetBase or subclass The ket on the right side of the inner product. Examples ======== Create an InnerProduct and check its properties: >>> from sympy.physics.quantum import Bra, Ket, InnerProduct >>> b = Bra('b') >>> k = Ket('k') >>> ip = b*k >>> ip <b|k> >>> ip.bra <b| >>> ip.ket |k> In simple products of kets and bras inner products will be automatically identified and created:: >>> b*k <b|k> But in more complex expressions, there is ambiguity in whether inner or outer products should be created:: >>> k*b*k*b |k><b|*|k>*<b| A user can force the creation of a inner products in a complex expression by using parentheses to group the bra and ket:: >>> k*(b*k)*b <b|k>*|k>*<b| Notice how the inner product <b|k> moved to the left of the expression because inner products are commutative complex numbers. References ========== .. [1] http://en.wikipedia.org/wiki/Inner_product """ is_complex = True def __new__(cls, bra, ket): if not isinstance(ket, KetBase): raise TypeError('KetBase subclass expected, got: %r' % ket) if not isinstance(bra, BraBase): raise TypeError('BraBase subclass expected, got: %r' % ket) obj = Expr.__new__(cls, bra, ket) return obj @property def bra(self): return self.args[0] @property def ket(self): return self.args[1] def _eval_conjugate(self): return InnerProduct(Dagger(self.ket), Dagger(self.bra)) def _sympyrepr(self, printer, *args): return '%s(%s,%s)' % (self.__class__.__name__, printer._print(self.bra, *args), printer._print(self.ket, *args)) def _sympystr(self, printer, *args): sbra = str(self.bra) sket = str(self.ket) return '%s|%s' % (sbra[:-1], sket[1:]) def _pretty(self, printer, *args): # Print state contents bra = self.bra._print_contents_pretty(printer, *args) ket = self.ket._print_contents_pretty(printer, *args) # Print brackets height = max(bra.height(), ket.height()) use_unicode = printer._use_unicode lbracket, _ = self.bra._pretty_brackets(height, use_unicode) cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode) # Build innerproduct pform = prettyForm(*bra.left(lbracket)) pform = prettyForm(*pform.right(cbracket)) pform = prettyForm(*pform.right(ket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): bra_label = self.bra._print_contents_latex(printer, *args) ket = printer._print(self.ket, *args) return r'\left\langle %s \right. %s' % (bra_label, ket) def doit(self, **hints): try: r = self.ket._eval_innerproduct(self.bra, **hints) except NotImplementedError: try: r = conjugate( self.bra.dual._eval_innerproduct(self.ket.dual, **hints) ) except NotImplementedError: r = None if r is not None: return r return self
4,261
29.661871
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/__init__.py
__all__ = [] # The following pattern is used below for importing sub-modules: # # 1. "from foo import *". This imports all the names from foo.__all__ into # this module. But, this does not put those names into the __all__ of # this module. This enables "from sympy.physics.quantum import State" to # work. # 2. "import foo; __all__.extend(foo.__all__)". This adds all the names in # foo.__all__ to the __all__ of this module. The names in __all__ # determine which names are imported when # "from sympy.physics.quantum import *" is done. from . import anticommutator from .anticommutator import * __all__.extend(anticommutator.__all__) from .qapply import __all__ as qap_all from .qapply import * __all__.extend(qap_all) from . import commutator from .commutator import * __all__.extend(commutator.__all__) from . import dagger from .dagger import * __all__.extend(dagger.__all__) from . import hilbert from .hilbert import * __all__.extend(hilbert.__all__) from . import innerproduct from .innerproduct import * __all__.extend(innerproduct.__all__) from . import operator from .operator import * __all__.extend(operator.__all__) from .represent import __all__ as rep_all from .represent import * __all__.extend(rep_all) from . import state from .state import * __all__.extend(state.__all__) from . import tensorproduct from .tensorproduct import * __all__.extend(tensorproduct.__all__) from . import constants from .constants import * __all__.extend(constants.__all__)
1,501
25.350877
75
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/gate.py
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from __future__ import print_function, division from itertools import chain import random from sympy import Add, I, Integer, Mul, Pow, sqrt, Tuple from sympy.core.numbers import Number from sympy.core.compatibility import is_sequence, unicode, range from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import (UnitaryOperator, Operator, HermitianOperator) from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye from sympy.physics.quantum.matrixcache import matrix_cache from sympy.matrices.matrices import MatrixBase from sympy.utilities import default_sort_key __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', 'CPHASE', 'CGateS', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def _max(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return max(*args, **kwargs) def _min(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return min(*args, **kwargs) def normalized(normalize): """Set flag controlling normalization of Hadamard gates by 1/sqrt(2). This is a global setting that can be used to simplify the look of various expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the 1/sqrt(2) normalization factor? When True, the Hadamard gate will have the 1/sqrt(2). When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer and not bit.is_Symbol: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(list(set(tandc))) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples ======== """ _label_separator = ',' gate_name = u'G' gate_name_latex = u'G' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Tuple(*UnitaryOperator._eval_args(args)) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.targets) + 1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError( 'get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' % (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n << 1 column = target_matrix[:, int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit in range(len(targets)): if new_qubit[targets[bit]] != (index >> bit) & 1: new_qubit = new_qubit.flip(targets[bit]) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format', 'sympy') nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _sympystr(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _pretty(self, printer, *args): a = stringPict(unicode(self.gate_name)) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples ======== """ gate_name = u'C' gate_name_latex = u'C' # The values this class controls for. control_value = Integer(1) simplify_cgate=False #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls, gate.targets)) return (Tuple(*controls), gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) + len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(_max(self.controls), _max(self.targets)) + 1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit] == self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_label(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '(%s),%s' % (controls, gate) def _pretty(self, printer, *args): controls = self._print_sequence_pretty( self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(unicode(self.gate_name)) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right((gate))) return final def _latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' % \ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == u'X': self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == u'Z': circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx) #------------------------------------------------------------------------- # Miscellaneous #------------------------------------------------------------------------- def _eval_dagger(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_dagger(self) def _eval_inverse(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_inverse(self) def _eval_power(self, exp): if isinstance(self.gate, HermitianOperator): if exp == -1: return Gate._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Gate._eval_inverse(self)) else: return self else: return Gate._eval_power(self, exp) class CGateS(CGate): """Version of CGate that allows gate simplifications. I.e. cnot looks like an oplus, cphase has dots, etc. """ simplify_cgate=True class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = u'U' gate_name_latex = u'U' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, MatrixBase): raise TypeError('Matrix expected, got: %r' % mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' % (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args[0]) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _pretty(self, printer, *args): targets = self._print_sequence_pretty( self.targets, ',', printer, *args) gate_name = stringPict(unicode(self.gate_name)) return self._print_subscript_pretty(gate_name, targets) def _latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = Integer(1) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'1' gate_name_latex = u'1' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(HermitianOperator, OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== >>> from sympy import sqrt >>> from sympy.physics.quantum.qubit import Qubit >>> from sympy.physics.quantum.gate import HadamardGate >>> from sympy.physics.quantum.qapply import qapply >>> qapply(HadamardGate(0)*Qubit('1')) sqrt(2)*|0>/2 - sqrt(2)*|1>/2 >>> # Hadamard on bell state, applied on 2 qubits. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11')) >>> qapply(HadamardGate(0)*HadamardGate(1)*psi) sqrt(2)*|00>/2 + sqrt(2)*|11>/2 """ gate_name = u'H' gate_name_latex = u'H' def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'X' gate_name_latex = u'X' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'Y' gate_name_latex = u'Y' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'Z' gate_name_latex = u'Z' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'S' gate_name_latex = u'S' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_TGate(self, other, **hints): return Integer(0) class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = u'T' gate_name_latex = u'T' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_PhaseGate(self, other, **hints): return Integer(0) # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(HermitianOperator, CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples ======== >>> from sympy.physics.quantum.gate import CNOT >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import Qubit >>> c = CNOT(1,0) >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left |11> """ gate_name = 'CNOT' gate_name_latex = u'CNOT' simplify_cgate = True #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.label) + 1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_label(self, printer, *args): return Gate._print_label(self, printer, *args) def _pretty(self, printer, *args): return Gate._pretty(self, printer, *args) def _latex(self, printer, *args): return Gate._latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples ======== """ gate_name = 'SWAP' gate_name_latex = u'SWAP' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i, j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(_min(self.targets)) max_wire = int(_max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = _min(targets) max_target = _max(targets) nqubits = options.get('nqubits', self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): product = nqubits*[eye2] product[nqubits - min_target - 1] = i product[nqubits - max_target - 1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate def CPHASE(a,b): return CGateS((a,),Z(b)) #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples ======== References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits - 1: product.append(matrix_eye(2**(nqubits - bit - 1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits - 1 - control] = op11 product2[nqubits - 1 - target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) + \ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in range(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate)) \ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] + (circuit_args[i].base**(circuit_args[i].exp % 2),) + circuit_args[i + 1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])** (Integer(circuit_args[i].exp/2)), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])** Integer(circuit_args[i].exp/2), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in range(len(circ_array) - 1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and \ isinstance(circ_array[i + 1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i + 1].as_base_exp() # Use sympy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) circuit = Mul(*new_args) circ_array = circuit.args changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) sign = Integer(-1)**(first_exp*second_exp) circuit = sign*Mul(*new_args) circ_array = circuit.args changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in range(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space, 2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
41,905
31.460108
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/spin.py
"""Quantum mechanical angular momemtum.""" from __future__ import print_function, division from sympy import (Add, binomial, cos, exp, Expr, factorial, I, Integer, Mul, pi, Rational, S, sin, simplify, sqrt, Sum, symbols, sympify, Tuple, Dummy) from sympy.core.compatibility import unicode, range from sympy.matrices import zeros from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import pretty_symbol from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.operator import (HermitianOperator, Operator, UnitaryOperator) from sympy.physics.quantum.state import Bra, Ket, State from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.cg import CG from sympy.physics.quantum.qapply import qapply __all__ = [ 'm_values', 'Jplus', 'Jminus', 'Jx', 'Jy', 'Jz', 'J2', 'Rotation', 'WignerD', 'JxKet', 'JxBra', 'JyKet', 'JyBra', 'JzKet', 'JzBra', 'JxKetCoupled', 'JxBraCoupled', 'JyKetCoupled', 'JyBraCoupled', 'JzKetCoupled', 'JzBraCoupled', 'couple', 'uncouple' ] def m_values(j): j = sympify(j) size = 2*j + 1 if not size.is_Integer or not size > 0: raise ValueError( 'Only integer or half-integer values allowed for j, got: : %r' % j ) return size, [j - i for i in range(int(2*j + 1))] #----------------------------------------------------------------------------- # Spin Operators #----------------------------------------------------------------------------- class SpinOpBase(object): """Base class for spin operators.""" @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def name(self): return self.args[0] def _print_contents(self, printer, *args): return '%s%s' % (unicode(self.name), self._coord) def _print_contents_pretty(self, printer, *args): a = stringPict(unicode(self.name)) b = stringPict(self._coord) return self._print_subscript_pretty(a, b) def _print_contents_latex(self, printer, *args): return r'%s_%s' % ((unicode(self.name), self._coord)) def _represent_base(self, basis, **options): j = options.get('j', Rational(1, 2)) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) result[p, q] = me return result def _apply_op(self, ket, orig_basis, **options): state = ket.rewrite(self.basis) # If the state has only one term if isinstance(state, State): ret = (hbar*state.m) * state # state is a linear combination of states elif isinstance(state, Sum): ret = self._apply_operator_Sum(state, **options) else: ret = qapply(self*state) if ret == self*state: raise NotImplementedError return ret.rewrite(orig_basis) def _apply_operator_JxKet(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_TensorProduct(self, tp, **options): # Uncoupling operator is only easily found for coordinate basis spin operators # TODO: add methods for uncoupling operators if not (isinstance(self, JxOp) or isinstance(self, JyOp) or isinstance(self, JzOp)): raise NotImplementedError result = [] for n in range(len(tp.args)): arg = [] arg.extend(tp.args[:n]) arg.append(self._apply_operator(tp.args[n])) arg.extend(tp.args[n + 1:]) result.append(tp.__class__(*arg)) return Add(*result).expand() # TODO: move this to qapply_Mul def _apply_operator_Sum(self, s, **options): new_func = qapply(self * s.function) if new_func == self*s.function: raise NotImplementedError return Sum(new_func, *s.limits) def _eval_trace(self, **options): #TODO: use options to use different j values #For now eval at default basis # is it efficient to represent each time # to do a trace? return self._represent_default_basis().trace() class JplusOp(SpinOpBase, Operator): """The J+ operator.""" _coord = '+' basis = 'Jz' def _eval_commutator_JminusOp(self, other): return 2*hbar*JzOp(self.name) def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One)) result *= KroneckerDelta(m, mp + 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args): return JxOp(args[0]) + I*JyOp(args[0]) class JminusOp(SpinOpBase, Operator): """The J- operator.""" _coord = '-' basis = 'Jz' def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One)) result *= KroneckerDelta(m, mp - 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args): return JxOp(args[0]) - I*JyOp(args[0]) class JxOp(SpinOpBase, HermitianOperator): """The Jx operator.""" _coord = 'x' basis = 'Jx' def _eval_commutator_JyOp(self, other): return I*hbar*JzOp(self.name) def _eval_commutator_JzOp(self, other): return -I*hbar*JyOp(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp + jm)/Integer(2) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp + jm)/Integer(2) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp + jm)/Integer(2) def _eval_rewrite_as_plusminus(self, *args): return (JplusOp(args[0]) + JminusOp(args[0]))/2 class JyOp(SpinOpBase, HermitianOperator): """The Jy operator.""" _coord = 'y' basis = 'Jy' def _eval_commutator_JzOp(self, other): return I*hbar*JxOp(self.name) def _eval_commutator_JxOp(self, other): return -I*hbar*J2Op(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp - jm)/(Integer(2)*I) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp - jm)/(Integer(2)*I) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp - jm)/(Integer(2)*I) def _eval_rewrite_as_plusminus(self, *args): return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I) class JzOp(SpinOpBase, HermitianOperator): """The Jz operator.""" _coord = 'z' basis = 'Jz' def _eval_commutator_JxOp(self, other): return I*hbar*JyOp(self.name) def _eval_commutator_JyOp(self, other): return -I*hbar*JxOp(self.name) def _eval_commutator_JplusOp(self, other): return hbar*JplusOp(self.name) def _eval_commutator_JminusOp(self, other): return -hbar*JminusOp(self.name) def matrix_element(self, j, m, jp, mp): result = hbar*mp result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) class J2Op(SpinOpBase, HermitianOperator): """The J^2 operator.""" _coord = '2' def _eval_commutator_JxOp(self, other): return S.Zero def _eval_commutator_JyOp(self, other): return S.Zero def _eval_commutator_JzOp(self, other): return S.Zero def _eval_commutator_JplusOp(self, other): return S.Zero def _eval_commutator_JminusOp(self, other): return S.Zero def _apply_operator_JxKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JxKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def matrix_element(self, j, m, jp, mp): result = (hbar**2)*j*(j + 1) result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _print_contents_pretty(self, printer, *args): a = prettyForm(unicode(self.name)) b = prettyForm(u'2') return a**b def _print_contents_latex(self, printer, *args): return r'%s^2' % str(self.name) def _eval_rewrite_as_xyz(self, *args): return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2 def _eval_rewrite_as_plusminus(self, *args): a = args[0] return JzOp(a)**2 + \ Rational(1, 2)*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a)) class Rotation(UnitaryOperator): """Wigner D operator in terms of Euler angles. Defines the rotation operator in terms of the Euler angles defined by the z-y-z convention for a passive transformation. That is the coordinate axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then this new coordinate system is rotated about the new y'-axis, giving new x''-y''-z'' axes. Then this new coordinate system is rotated about the z''-axis. Conventions follow those laid out in [1]_. Parameters ========== alpha : Number, Symbol First Euler Angle beta : Number, Symbol Second Euler angle gamma : Number, Symbol Third Euler angle Examples ======== A simple example rotation operator: >>> from sympy import pi >>> from sympy.physics.quantum.spin import Rotation >>> Rotation(pi, 0, pi/2) R(pi,0,pi/2) With symbolic Euler angles and calculating the inverse rotation operator: >>> from sympy import symbols >>> a, b, c = symbols('a b c') >>> Rotation(a, b, c) R(a,b,c) >>> Rotation(a, b, c).inverse() R(-c,-b,-a) See Also ======== WignerD: Symbolic Wigner-D function D: Wigner-D function d: Wigner small-d function References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) != 3: raise ValueError('3 Euler angles required, got: %r' % args) return args @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def alpha(self): return self.label[0] @property def beta(self): return self.label[1] @property def gamma(self): return self.label[2] def _print_operator_name(self, printer, *args): return 'R' def _print_operator_name_pretty(self, printer, *args): if printer._use_unicode: return prettyForm(u'\N{SCRIPT CAPITAL R}' + u' ') else: return prettyForm("R ") def _print_operator_name_latex(self, printer, *args): return r'\mathcal{R}' def _eval_inverse(self): return Rotation(-self.gamma, -self.beta, -self.alpha) @classmethod def D(cls, j, m, mp, alpha, beta, gamma): """Wigner D-function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> alpha, beta, gamma = symbols('alpha beta gamma') >>> Rotation.D(1, 1, 0,pi, pi/2,-pi) WignerD(1, 1, 0, pi, pi/2, -pi) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, alpha, beta, gamma) @classmethod def d(cls, j, m, mp, beta): """Wigner small-d function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters with the alpha and gamma angles given as 0. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis beta : Number, Symbol Second Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> beta = symbols('beta') >>> Rotation.d(1, 1, 0, pi/2) WignerD(1, 1, 0, 0, pi/2, 0) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, 0, beta, 0) def matrix_element(self, j, m, jp, mp): result = self.__class__.D( jp, m, mp, self.alpha, self.beta, self.gamma ) result *= KroneckerDelta(j, jp) return result def _represent_base(self, basis, **options): j = sympify(options.get('j', Rational(1, 2))) # TODO: move evaluation up to represent function/implement elsewhere evaluate = sympify(options.get('doit')) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) if evaluate: result[p, q] = me.doit() else: result[p, q] = me return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _apply_operator_uncoupled(self, state, ket, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z * state(j, mp)) return Add(*s) else: if options.pop('dummy', True): mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g) * state(j, mp), (mp, -j, j)) def _apply_operator_JxKet(self, ket, **options): return self._apply_operator_uncoupled(JxKet, ket, **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_operator_uncoupled(JyKet, ket, **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_operator_uncoupled(JzKet, ket, **options) def _apply_operator_coupled(self, state, ket, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z * state(j, mp, jn, coupling)) return Add(*s) else: if options.pop('dummy', True): mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g) * state( j, mp, jn, coupling), (mp, -j, j)) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_operator_coupled(JxKetCoupled, ket, **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_operator_coupled(JyKetCoupled, ket, **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_operator_coupled(JzKetCoupled, ket, **options) class WignerD(Expr): """Wigner-D function The Wigner D-function gives the matrix elements of the rotation operator in the jm-representation. For the Euler angles `\\alpha`, `\\beta`, `\gamma`, the D-function is defined such that: .. math :: <j,m| \mathcal{R}(\\alpha, \\beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \\alpha, \\beta, \gamma) Where the rotation operator is as defined by the Rotation class [1]_. The Wigner D-function defined in this way gives: .. math :: D(j, m, m', \\alpha, \\beta, \gamma) = e^{-i m \\alpha} d(j, m, m', \\beta) e^{-i m' \gamma} Where d is the Wigner small-d function, which is given by Rotation.d. The Wigner small-d function gives the component of the Wigner D-function that is determined by the second Euler angle. That is the Wigner D-function is: .. math :: D(j, m, m', \\alpha, \\beta, \gamma) = e^{-i m \\alpha} d(j, m, m', \\beta) e^{-i m' \gamma} Where d is the small-d function. The Wigner D-function is given by Rotation.D. Note that to evaluate the D-function, the j, m and mp parameters must be integer or half integer numbers. Parameters ========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Evaluate the Wigner-D matrix elements of a simple rotation: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0) >>> rot WignerD(1, 1, 0, pi, pi/2, 0) >>> rot.doit() sqrt(2)/2 Evaluate the Wigner-d matrix elements of a simple rotation >>> rot = Rotation.d(1, 1, 0, pi/2) >>> rot WignerD(1, 1, 0, 0, pi/2, 0) >>> rot.doit() -sqrt(2)/2 See Also ======== Rotation: Rotation operator References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ is_commutative = True def __new__(cls, *args, **hints): if not len(args) == 6: raise ValueError('6 parameters expected, got %s' % args) args = sympify(args) evaluate = hints.get('evaluate', False) if evaluate: return Expr.__new__(cls, *args)._eval_wignerd() return Expr.__new__(cls, *args) @property def j(self): return self.args[0] @property def m(self): return self.args[1] @property def mp(self): return self.args[2] @property def alpha(self): return self.args[3] @property def beta(self): return self.args[4] @property def gamma(self): return self.args[5] def _latex(self, printer, *args): if self.alpha == 0 and self.gamma == 0: return r'd^{%s}_{%s,%s}\left(%s\right)' % \ ( printer._print(self.j), printer._print( self.m), printer._print(self.mp), printer._print(self.beta) ) return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \ ( printer._print( self.j), printer._print(self.m), printer._print(self.mp), printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) ) def _pretty(self, printer, *args): top = printer._print(self.j) bot = printer._print(self.m) bot = prettyForm(*bot.right(',')) bot = prettyForm(*bot.right(printer._print(self.mp))) pad = max(top.width(), bot.width()) top = prettyForm(*top.left(' ')) bot = prettyForm(*bot.left(' ')) if pad > top.width(): top = prettyForm(*top.right(' ' * (pad - top.width()))) if pad > bot.width(): bot = prettyForm(*bot.right(' ' * (pad - bot.width()))) if self.alpha == 0 and self.gamma == 0: args = printer._print(self.beta) s = stringPict('d' + ' '*pad) else: args = printer._print(self.alpha) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.beta))) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.gamma))) s = stringPict('D' + ' '*pad) args = prettyForm(*args.parens()) s = prettyForm(*s.above(top)) s = prettyForm(*s.below(bot)) s = prettyForm(*s.right(args)) return s def doit(self, **hints): hints['evaluate'] = True return WignerD(*self.args, **hints) def _eval_wignerd(self): j = sympify(self.j) m = sympify(self.m) mp = sympify(self.mp) alpha = sympify(self.alpha) beta = sympify(self.beta) gamma = sympify(self.gamma) if not j.is_number: raise ValueError( 'j parameter must be numerical to evaluate, got %s' % j) r = 0 if beta == pi/2: # Varshalovich Equation (5), Section 4.16, page 113, setting # alpha=gamma=0. for k in range(2*j + 1): if k > j + mp or k > j - m or k < mp - m: continue r += (-S(1))**k * binomial(j + mp, k) * binomial(j - mp, k + m - mp) r *= (-S(1))**(m - mp) / 2**j * sqrt(factorial(j + m) * factorial(j - m) / (factorial(j + mp) * factorial(j - mp))) else: # Varshalovich Equation(5), Section 4.7.2, page 87, where we set # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi, # then we use the Eq. (1), Section 4.4. page 79, to simplify: # d(j, m, mp, beta+pi) = (-1)**(j-mp) * d(j, m, -mp, beta) # This happens to be almost the same as in Eq.(10), Section 4.16, # except that we need to substitute -mp for mp. size, mvals = m_values(j) for mpp in mvals: r += Rotation.d(j, m, mpp, pi/2).doit() * (cos(-mpp*beta) + I*sin(-mpp*beta)) * \ Rotation.d(j, mpp, -mp, pi/2).doit() # Empirical normalization factor so results match Varshalovich # Tables 4.3-4.12 # Note that this exact normalization does not follow from the # above equations r = r * I**(2*j - m - mp) * (-1)**(2*m) # Finally, simplify the whole expression r = simplify(r) r *= exp(-I*m*alpha)*exp(-I*mp*gamma) return r Jx = JxOp('J') Jy = JyOp('J') Jz = JzOp('J') J2 = J2Op('J') Jplus = JplusOp('J') Jminus = JminusOp('J') #----------------------------------------------------------------------------- # Spin States #----------------------------------------------------------------------------- class SpinState(State): """Base class for angular momentum states.""" _label_separator = ',' def __new__(cls, j, m): j = sympify(j) m = sympify(m) if j.is_number: if 2*j != int(2*j): raise ValueError( 'j must be integer or half-integer, got: %s' % j) if j < 0: raise ValueError('j must be >= 0, got: %s' % j) if m.is_number: if 2*m != int(2*m): raise ValueError( 'm must be integer or half-integer, got: %s' % m) if j.is_number and m.is_number: if abs(m) > j: raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m)) if int(j - m) != j - m: raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m)) return State.__new__(cls, j, m) @property def j(self): return self.label[0] @property def m(self): return self.label[1] @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2*label[0] + 1) def _represent_base(self, **options): j = self.j m = self.m alpha = sympify(options.get('alpha', 0)) beta = sympify(options.get('beta', 0)) gamma = sympify(options.get('gamma', 0)) size, mvals = m_values(j) result = zeros(size, 1) # TODO: Use KroneckerDelta if all Euler angles == 0 # breaks finding angles on L930 for p, mval in enumerate(mvals): if m.is_number: result[p, 0] = Rotation.D( self.j, mval, self.m, alpha, beta, gamma).doit() else: result[p, 0] = Rotation.D(self.j, mval, self.m, alpha, beta, gamma) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBra, **options) return self._rewrite_basis(Jx, JxKet, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBra, **options) return self._rewrite_basis(Jy, JyKet, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBra, **options) return self._rewrite_basis(Jz, JzKet, **options) def _rewrite_basis(self, basis, evect, **options): from sympy.physics.quantum.represent import represent j = self.j args = self.args[2:] if j.is_number: if isinstance(self, CoupledSpinState): if j == int(j): start = j**2 else: start = (2*j - 1)*(2*j + 1)/4 else: start = 0 vect = represent(self, basis=basis, **options) result = Add( *[vect[start + i] * evect(j, j - i, *args) for i in range(2*j + 1)]) if isinstance(self, CoupledSpinState) and options.get('coupled') is False: return uncouple(result) return result else: i = 0 mi = symbols('mi') # make sure not to introduce a symbol already in the state while self.subs(mi, 0) != self: i += 1 mi = symbols('mi%d' % i) break # TODO: better way to get angles of rotation if isinstance(self, CoupledSpinState): test_args = (0, mi, (0, 0)) else: test_args = (0, mi) if isinstance(self, Ket): angles = represent( self.__class__(*test_args), basis=basis)[0].args[3:6] else: angles = represent(self.__class__( *test_args), basis=basis)[0].args[0].args[3:6] if angles == (0, 0, 0): return self else: state = evect(j, mi, *args) lt = Rotation.D(j, mi, self.m, *angles) return Sum(lt * state, (mi, -j, j)) def _eval_innerproduct_JxBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JxOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j) * KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JyBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JyOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j) * KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JzBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JzOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j) * KroneckerDelta(self.m, bra.m) return result def _eval_trace(self, bra, **hints): # One way to implement this method is to assume the basis set k is # passed. # Then we can apply the discrete form of Trace formula here # Tr(|i><j| ) = \Sum_k <k|i><j|k> #then we do qapply() on each each inner product and sum over them. # OR # Inner product of |i><j| = Trace(Outer Product). # we could just use this unless there are cases when this is not true return (bra*self).doit() class JxKet(SpinState, Ket): """Eigenket of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxBra @classmethod def coupled_class(self): return JxKetCoupled def _represent_default_basis(self, **options): return self._represent_JxOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=3*pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(beta=pi/2, **options) class JxBra(SpinState, Bra): """Eigenbra of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxKet @classmethod def coupled_class(self): return JxBraCoupled class JyKet(SpinState, Ket): """Eigenket of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyBra @classmethod def coupled_class(self): return JyKetCoupled def _represent_default_basis(self, **options): return self._represent_JyOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_base(alpha=3*pi/2, beta=-pi/2, gamma=pi/2, **options) class JyBra(SpinState, Bra): """Eigenbra of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyKet @classmethod def coupled_class(self): return JyBraCoupled class JzKet(SpinState, Ket): """Eigenket of Jz. Spin state which is an eigenstate of the Jz operator. Uncoupled states, that is states representing the interaction of multiple separate spin states, are defined as a tensor product of states. Parameters ========== j : Number, Symbol Total spin angular momentum m : Number, Symbol Eigenvalue of the Jz spin operator Examples ======== *Normal States:* Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKet, JxKet >>> from sympy import symbols >>> JzKet(1, 0) |1,0> >>> j, m = symbols('j m') >>> JzKet(j, m) |j,m> Rewriting the JzKet in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKet's >>> JzKet(1,1).rewrite("Jx") |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx, Jz >>> represent(JzKet(1,-1), basis=Jx) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2]]) Apply innerproducts between states: >>> from sympy.physics.quantum.innerproduct import InnerProduct >>> from sympy.physics.quantum.spin import JxBra >>> i = InnerProduct(JxBra(1,1), JzKet(1,1)) >>> i <1,1|1,1> >>> i.doit() 1/2 *Uncoupled States:* Define an uncoupled state as a TensorProduct between two Jz eigenkets: >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> TensorProduct(JzKet(1,0), JzKet(1,1)) |1,0>x|1,1> >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2)) |j1,m1>x|j2,m2> A TensorProduct can be rewritten, in which case the eigenstates that make up the tensor product is rewritten to the new basis: >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz') |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2 The represent method for TensorProduct's gives the vector representation of the state. Note that the state in the product basis is the equivalent of the tensor product of the vector representation of the component eigenstates: >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1))) Matrix([ [0], [0], [0], [1], [0], [0], [0], [0], [0]]) >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2], [ 0], [ 0], [ 0], [ 0], [ 0], [ 0]]) See Also ======== JzKetCoupled: Coupled eigenstates TensorProduct: Used to specify uncoupled states uncouple: Uncouples states given coupling parameters couple: Couples uncoupled states """ @classmethod def dual_class(self): return JzBra @classmethod def coupled_class(self): return JzKetCoupled def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(beta=3*pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=3*pi/2, beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(**options) class JzBra(SpinState, Bra): """Eigenbra of Jz. See the JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JzKet @classmethod def coupled_class(self): return JzBraCoupled # Method used primarily to create coupled_n and coupled_jn by __new__ in # CoupledSpinState # This same method is also used by the uncouple method, and is separated from # the CoupledSpinState class to maintain consistency in defining coupling def _build_coupled(jcoupling, length): n_list = [ [n + 1] for n in range(length) ] coupled_jn = [] coupled_n = [] for n1, n2, j_new in jcoupling: coupled_jn.append(j_new) coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) ) n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1]) n_list[n_sort[0] - 1] = n_sort return coupled_n, coupled_jn class CoupledSpinState(SpinState): """Base class for coupled angular momentum states.""" def __new__(cls, j, m, jn, *jcoupling): # Check j and m values using SpinState SpinState(j, m) # Build and check coupling scheme from arguments if len(jcoupling) == 0: # Use default coupling scheme jcoupling = [] for n in range(2, len(jn)): jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) ) jcoupling.append( (1, len(jn), j) ) elif len(jcoupling) == 1: # Use specified coupling scheme jcoupling = jcoupling[0] else: raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) ) # Check arguments have correct form if not (isinstance(jn, list) or isinstance(jn, tuple) or isinstance(jn, Tuple)): raise TypeError('jn must be Tuple, list or tuple, got %s' % jn.__class__.__name__) if not (isinstance(jcoupling, list) or isinstance(jcoupling, tuple) or isinstance(jcoupling, Tuple)): raise TypeError('jcoupling must be Tuple, list or tuple, got %s' % jcoupling.__class__.__name__) if not all(isinstance(term, list) or isinstance(term, tuple) or isinstance(term, Tuple) for term in jcoupling): raise TypeError( 'All elements of jcoupling must be list, tuple or Tuple') if not len(jn) - 1 == len(jcoupling): raise ValueError('jcoupling must have length of %d, got %d' % (len(jn) - 1, len(jcoupling))) if not all(len(x) == 3 for x in jcoupling): raise ValueError('All elements of jcoupling must have length 3') # Build sympified args j = sympify(j) m = sympify(m) jn = Tuple( *[sympify(ji) for ji in jn] ) jcoupling = Tuple( *[Tuple(sympify( n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] ) # Check values in coupling scheme give physical state if any(2*ji != int(2*ji) for ji in jn if ji.is_number): raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn) if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling): raise ValueError('Indicies in jcoupling must be integers') if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling): raise ValueError('Indicies must be between 1 and the number of coupled spin spaces') if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number): raise ValueError('All coupled j values in coupling scheme must be integer or half-integer') coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn)) jvals = list(jn) for n, (n1, n2) in enumerate(coupled_n): j1 = jvals[min(n1) - 1] j2 = jvals[min(n2) - 1] j3 = coupled_jn[n] if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number: if j1 + j2 < j3: raise ValueError('All couplings must have j1+j2 >= j3, ' 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3)) if abs(j1 - j2) > j3: raise ValueError("All couplings must have |j1+j2| <= j3, " "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3)) if int(j1 + j2) == j1 + j2: pass jvals[min(n1 + n2) - 1] = j3 if len(jcoupling) > 0 and jcoupling[-1][2] != j: raise ValueError('Last j value coupled together must be the final j of the state') # Return state return State.__new__(cls, j, m, jn, jcoupling) def _print_label(self, printer, *args): label = [printer._print(self.j), printer._print(self.m)] for i, ji in enumerate(self.jn, start=1): label.append('j%d=%s' % ( i, printer._print(ji) )) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): label.append('j(%s)=%s' % ( ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn) )) return ','.join(label) def _print_label_pretty(self, printer, *args): label = [self.j, self.m] for i, ji in enumerate(self.jn, start=1): symb = 'j%d' % i symb = pretty_symbol(symb) symb = prettyForm(symb + '=') item = prettyForm(*symb.right(printer._print(ji))) label.append(item) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2)) symb = prettyForm('j' + n + '=') item = prettyForm(*symb.right(printer._print(jn))) label.append(item) return self._print_sequence_pretty( label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): label = [self.j, self.m] for i, ji in enumerate(self.jn, start=1): label.append('j_{%d}=%s' % (i, printer._print(ji)) ) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(str(i) for i in sorted(n1 + n2)) label.append('j_{%s}=%s' % (n, printer._print(jn)) ) return self._print_sequence( label, self._label_separator, printer, *args ) @property def jn(self): return self.label[2] @property def coupling(self): return self.label[3] @property def coupled_jn(self): return _build_coupled(self.label[3], len(self.label[2]))[1] @property def coupled_n(self): return _build_coupled(self.label[3], len(self.label[2]))[0] @classmethod def _eval_hilbert_space(cls, label): j = Add(*label[2]) if j.is_number: return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ]) else: # TODO: Need hilbert space fix, see issue 5732 # Desired behavior: #ji = symbols('ji') #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j)) # Temporary fix: return ComplexSpace(2*j + 1) def _represent_coupled_base(self, **options): evect = self.uncoupled_class() if not self.j.is_number: raise ValueError( 'State must not have symbolic j value to represent') if not self.hilbert_space.dimension.is_number: raise ValueError( 'State must not have symbolic j values to represent') result = zeros(self.hilbert_space.dimension, 1) if self.j == int(self.j): start = self.j**2 else: start = (2*self.j - 1)*(1 + 2*self.j)/4 result[start:start + 2*self.j + 1, 0] = evect( self.j, self.m)._represent_base(**options) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBraCoupled, **options) return self._rewrite_basis(Jx, JxKetCoupled, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBraCoupled, **options) return self._rewrite_basis(Jy, JyKetCoupled, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBraCoupled, **options) return self._rewrite_basis(Jz, JzKetCoupled, **options) class JxKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxBraCoupled @classmethod def uncoupled_class(self): return JxKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=3*pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(beta=pi/2, **options) class JxBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxKetCoupled @classmethod def uncoupled_class(self): return JxBra class JyKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyBraCoupled @classmethod def uncoupled_class(self): return JyKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(alpha=3*pi/2, beta=-pi/2, gamma=pi/2, **options) class JyBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyKetCoupled @classmethod def uncoupled_class(self): return JyBra class JzKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jz Spin state that is an eigenket of Jz which represents the coupling of separate spin spaces. The arguments for creating instances of JzKetCoupled are ``j``, ``m``, ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options are the total angular momentum quantum numbers, as used for normal states (e.g. JzKet). The other required parameter in ``jn``, which is a tuple defining the `j_n` angular momentum quantum numbers of the product spaces. So for example, if a state represented the coupling of the product basis state `|j_1,m_1\\rangle\\times|j_2,m_2\\rangle`, the ``jn`` for this state would be ``(j1,j2)``. The final option is ``jcoupling``, which is used to define how the spaces specified by ``jn`` are coupled, which includes both the order these spaces are coupled together and the quantum numbers that arise from these couplings. The ``jcoupling`` parameter itself is a list of lists, such that each of the sublists defines a single coupling between the spin spaces. If there are N coupled angular momentum spaces, that is ``jn`` has N elements, then there must be N-1 sublists. Each of these sublists making up the ``jcoupling`` parameter have length 3. The first two elements are the indicies of the product spaces that are considered to be coupled together. For example, if we want to couple `j_1` and `j_4`, the indicies would be 1 and 4. If a state has already been coupled, it is referenced by the smallest index that is coupled, so if `j_2` and `j_4` has already been coupled to some `j_{24}`, then this value can be coupled by referencing it with index 2. The final element of the sublist is the quantum number of the coupled state. So putting everything together, into a valid sublist for ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space with quantum number `j_{12}` with the value ``j12``, the sublist would be ``(1,2,j12)``, N-1 of these sublists are used in the list for ``jcoupling``. Note the ``jcoupling`` parameter is optional, if it is not specified, the default coupling is taken. This default value is to coupled the spaces in order and take the quantum number of the coupling to be the maximum value. For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then, `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would correspond to this is: ``((1,2,j1+j2),(1,3,j1+j2+j3))`` Parameters ========== args : tuple The arguments that must be passed are ``j``, ``m``, ``jn``, and ``jcoupling``. The ``j`` value is the total angular momentum. The ``m`` value is the eigenvalue of the Jz spin operator. The ``jn`` list are the j values of argular momentum spaces coupled together. The ``jcoupling`` parameter is an optional parameter defining how the spaces are coupled together. See the above description for how these coupling parameters are defined. Examples ======== Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKetCoupled >>> from sympy import symbols >>> JzKetCoupled(1, 0, (1, 1)) |1,0,j1=1,j2=1> >>> j, m, j1, j2 = symbols('j m j1 j2') >>> JzKetCoupled(j, m, (j1, j2)) |j,m,j1=j1,j2=j2> Defining coupled spin states for more than 2 coupled spaces with various coupling parameters: >>> JzKetCoupled(2, 1, (1, 1, 1)) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) ) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) ) |2,1,j1=1,j2=1,j3=1,j(2,3)=1> Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKetCoupled >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx") |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2 The rewrite method can be used to convert a coupled state to an uncoupled state. This is done by passing coupled=False to the rewrite function: >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False) -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx >>> from sympy import S >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx) Matrix([ [ 0], [ 1/2], [sqrt(2)/2], [ 1/2]]) See Also ======== JzKet: Normal spin eigenstates uncouple: Uncoupling of coupling spin states couple: Coupling of uncoupled spin states """ @classmethod def dual_class(self): return JzBraCoupled @classmethod def uncoupled_class(self): return JzKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(beta=3*pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=3*pi/2, beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(**options) class JzBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jz. See the JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JzKetCoupled @classmethod def uncoupled_class(self): return JzBra #----------------------------------------------------------------------------- # Coupling/uncoupling #----------------------------------------------------------------------------- def couple(expr, jcoupling_list=None): """ Couple a tensor product of spin states This function can be used to couple an uncoupled tensor product of spin states. All of the eigenstates to be coupled must be of the same class. It will return a linear combination of eigenstates that are subclasses of CoupledSpinState determined by Clebsch-Gordan angular momentum coupling coefficients. Parameters ========== expr : Expr An expression involving TensorProducts of spin states to be coupled. Each state must be a subclass of SpinState and they all must be the same class. jcoupling_list : list or tuple Elements of this list are sub-lists of length 2 specifying the order of the coupling of the spin spaces. The length of this must be N-1, where N is the number of states in the tensor product to be coupled. The elements of this sublist are the same as the first two elements of each sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this parameter is not specified, the default value is taken, which couples the first and second product basis spaces, then couples this new coupled space to the third product space, etc Examples ======== Couple a tensor product of numerical states for two spaces: >>> from sympy.physics.quantum.spin import JzKet, couple >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1))) -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2 Numerical coupling of three spaces using the default coupling method, i.e. first and second spaces couple, then this couples to the third space: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0))) sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 Perform this same coupling, but we define the coupling to first couple the first and third spaces: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) ) sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3 Couple a tensor product of symbolic states: >>> from sympy import symbols >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2))) Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2)) """ a = expr.atoms(TensorProduct) for tp in a: # Allow other tensor products to be in expression if not all([ isinstance(state, SpinState) for state in tp.args]): continue # If tensor product has all spin states, raise error for invalid tensor product state if not all([state.__class__ is tp.args[0].__class__ for state in tp.args]): raise TypeError('All states must be the same basis') expr = expr.subs(tp, _couple(tp, jcoupling_list)) return expr def _couple(tp, jcoupling_list): states = tp.args coupled_evect = states[0].coupled_class() # Define default coupling if none is specified if jcoupling_list is None: jcoupling_list = [] for n in range(1, len(states)): jcoupling_list.append( (1, n + 1) ) # Check jcoupling_list valid if not len(jcoupling_list) == len(states) - 1: raise TypeError('jcoupling_list must be length %d, got %d' % (len(states) - 1, len(jcoupling_list))) if not all( len(coupling) == 2 for coupling in jcoupling_list): raise ValueError('Each coupling must define 2 spaces') if any([n1 == n2 for n1, n2 in jcoupling_list]): raise ValueError('Spin spaces cannot couple to themselves') if all([sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list]): j_test = [0]*len(states) for n1, n2 in jcoupling_list: if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1: raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value') j_test[max(n1, n2) - 1] = -1 # j values of states to be coupled together jn = [state.j for state in states] mn = [state.m for state in states] # Create coupling_list, which defines all the couplings between all # the spaces from jcoupling_list coupling_list = [] n_list = [ [i + 1] for i in range(len(states)) ] for j_coupling in jcoupling_list: # Least n for all j_n which is coupled as first and second spaces n1, n2 = j_coupling # List of all n's coupled in first and second spaces j1_n = list(n_list[n1 - 1]) j2_n = list(n_list[n2 - 1]) coupling_list.append( (j1_n, j2_n) ) # Set new j_n to be coupling of all j_n in both first and second spaces n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n) if all(state.j.is_number and state.m.is_number for state in states): # Numerical coupling # Iterate over difference between maximum possible j value of each coupling and the actual value diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] + coupling[1] ] ) for coupling in coupling_list ] result = [] for diff in range(diff_max[-1] + 1): # Determine available configurations n = len(coupling_list) tot = binomial(diff + n - 1, diff) for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) # Skip the configuration if non-physical # This is a lazy check for physical states given the loose restrictions of diff_max if any( [ d > m for d, m in zip(diff_list, diff_max) ] ): continue # Determine term cg_terms = [] coupled_j = list(jn) jcoupling = [] for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list): j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] j3 = j1 + j2 - coupling_diff coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) # Better checks that state is physical if any([ abs(term[5]) > term[4] for term in cg_terms ]): continue if any([ term[0] + term[2] < term[4] for term in cg_terms ]): continue if any([ abs(term[0] - term[2]) > term[4] for term in cg_terms ]): continue coeff = Mul( *[ CG(*term).doit() for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) result.append(coeff*state) return Add(*result) else: # Symbolic coupling cg_terms = [] jcoupling = [] sum_terms = [] coupled_j = list(jn) for j1_n, j2_n in coupling_list: j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] if len(j1_n + j2_n) == len(states): j3 = symbols('j') else: j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n]) j3 = symbols(j3_name) coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) sum_terms.append((j3, m3, j1 + j2)) coeff = Mul( *[ CG(*term) for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) return Sum(coeff*state, *sum_terms) def uncouple(expr, jn=None, jcoupling_list=None): """ Uncouple a coupled spin state Gives the uncoupled representation of a coupled spin state. Arguments must be either a spin state that is a subclass of CoupledSpinState or a spin state that is a subclass of SpinState and an array giving the j values of the spaces that are to be coupled Parameters ========== expr : Expr The expression containing states that are to be coupled. If the states are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters must be defined. If the states are a subclass of CoupledSpinState, ``jn`` and ``jcoupling`` will be taken from the state. jn : list or tuple The list of the j-values that are coupled. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jn`` parameter of JzKetCoupled. jcoupling_list : list or tuple The list defining how the j-values are coupled together. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jcoupling`` parameter of JzKetCoupled. Examples ======== Uncouple a numerical state using a CoupledSpinState state: >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple >>> from sympy import S >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2))) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Perform the same calculation using a SpinState state: >>> from sympy.physics.quantum.spin import JzKet >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2)) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Uncouple a numerical state of three coupled spaces using a CoupledSpinState state: >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) )) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Perform the same calculation using a SpinState state: >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) ) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Uncouple a symbolic state using a CoupledSpinState state: >>> from sympy import symbols >>> j,m,j1,j2 = symbols('j m j1 j2') >>> uncouple(JzKetCoupled(j, m, (j1, j2))) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) Perform the same calculation using a SpinState state >>> uncouple(JzKet(j, m), (j1, j2)) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) """ a = expr.atoms(SpinState) for state in a: expr = expr.subs(state, _uncouple(state, jn, jcoupling_list)) return expr def _uncouple(state, jn, jcoupling_list): if isinstance(state, CoupledSpinState): jn = state.jn coupled_n = state.coupled_n coupled_jn = state.coupled_jn evect = state.uncoupled_class() elif isinstance(state, SpinState): if jn is None: raise ValueError("Must specify j-values for coupled state") if not (isinstance(jn, list) or isinstance(jn, tuple)): raise TypeError("jn must be list or tuple") if jcoupling_list is None: # Use default jcoupling_list = [] for i in range(1, len(jn)): jcoupling_list.append( (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) ) if not (isinstance(jcoupling_list, list) or isinstance(jcoupling_list, tuple)): raise TypeError("jcoupling must be a list or tuple") if not len(jcoupling_list) == len(jn) - 1: raise ValueError("Must specify 2 fewer coupling terms than the number of j values") coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn)) evect = state.__class__ else: raise TypeError("state must be a spin state") j = state.j m = state.m coupling_list = [] j_list = list(jn) # Create coupling, which defines all the couplings between all the spaces for j3, (n1, n2) in zip(coupled_jn, coupled_n): # j's which are coupled as first and second spaces j1 = j_list[n1[0] - 1] j2 = j_list[n2[0] - 1] # Build coupling list coupling_list.append( (n1, n2, j1, j2, j3) ) # Set new value in j_list j_list[min(n1 + n2) - 1] = j3 if j.is_number and m.is_number: diff_max = [ 2*x for x in jn ] diff = Add(*jn) - m n = len(jn) tot = binomial(diff + n - 1, diff) result = [] for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) if any( [ d > p for d, p in zip(diff_list, diff_max) ] ): continue cg_terms = [] for coupling in coupling_list: j1_n, j2_n, j1, j2, j3 = coupling m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] ) m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] ) state = TensorProduct( *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] ) result.append(coeff*state) return Add(*result) else: # Symbolic coupling m_str = "m1:%d" % (len(jn) + 1) mvals = symbols(m_str) cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ] cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ]) cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms]) sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ] state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] ) return Sum(cg_coeff*state, *sum_terms) def _confignum_to_difflist(config_num, diff, list_len): # Determines configuration of diffs into list_len number of slots diff_list = [] for n in range(list_len): prev_diff = diff # Number of spots after current one rem_spots = list_len - n - 1 # Number of configurations of distributing diff among the remaining spots rem_configs = binomial(diff + rem_spots - 1, diff) while config_num >= rem_configs: config_num -= rem_configs diff -= 1 rem_configs = binomial(diff + rem_spots - 1, diff) diff_list.append(prev_diff - diff) return diff_list
72,704
33.00608
131
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/piab.py
"""1D quantum particle in a box.""" from __future__ import print_function, division from sympy import Symbol, pi, sqrt, sin, Interval, S from sympy.physics.quantum.operator import HermitianOperator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.constants import hbar from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import L2 m = Symbol('m') L = Symbol('L') __all__ = [ 'PIABHamiltonian', 'PIABKet', 'PIABBra' ] class PIABHamiltonian(HermitianOperator): """Particle in a box Hamiltonian operator.""" @classmethod def _eval_hilbert_space(cls, label): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PIABKet(self, ket, **options): n = ket.label[0] return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket class PIABKet(Ket): """Particle in a box eigenket.""" @classmethod def _eval_hilbert_space(cls, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) @classmethod def dual_class(self): return PIABBra def _represent_default_basis(self, **options): return self._represent_XOp(None, **options) def _represent_XOp(self, basis, **options): x = Symbol('x') n = Symbol('n') subs_info = options.get('subs', {}) return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info) def _eval_innerproduct_PIABBra(self, bra): return KroneckerDelta(bra.label[0], self.label[0]) class PIABBra(Bra): """Particle in a box eigenbra.""" @classmethod def _eval_hilbert_space(cls, label): return L2(Interval(S.NegativeInfinity, S.Infinity)) @classmethod def dual_class(self): return PIABKet
1,756
24.1
67
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/dagger.py
"""Hermitian conjugation.""" from __future__ import print_function, division from sympy.core import Expr from sympy.functions.elementary.complexes import adjoint __all__ = [ 'Dagger' ] class Dagger(adjoint): """General Hermitian conjugate operation. Take the Hermetian conjugate of an argument [1]_. For matrices this operation is equivalent to transpose and complex conjugate [2]_. Parameters ========== arg : Expr The sympy expression that we want to take the dagger of. Examples ======== Daggering various quantum objects: >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.state import Ket, Bra >>> from sympy.physics.quantum.operator import Operator >>> Dagger(Ket('psi')) <psi| >>> Dagger(Bra('phi')) |phi> >>> Dagger(Operator('A')) Dagger(A) Inner and outer products:: >>> from sympy.physics.quantum import InnerProduct, OuterProduct >>> Dagger(InnerProduct(Bra('a'), Ket('b'))) <b|a> >>> Dagger(OuterProduct(Ket('a'), Bra('b'))) |b><a| Powers, sums and products:: >>> A = Operator('A') >>> B = Operator('B') >>> Dagger(A*B) Dagger(B)*Dagger(A) >>> Dagger(A+B) Dagger(A) + Dagger(B) >>> Dagger(A**2) Dagger(A)**2 Dagger also seamlessly handles complex numbers and matrices:: >>> from sympy import Matrix, I >>> m = Matrix([[1,I],[2,I]]) >>> m Matrix([ [1, I], [2, I]]) >>> Dagger(m) Matrix([ [ 1, 2], [-I, -I]]) References ========== .. [1] http://en.wikipedia.org/wiki/Hermitian_adjoint .. [2] http://en.wikipedia.org/wiki/Hermitian_transpose """ def __new__(cls, arg): if hasattr(arg, 'adjoint'): obj = arg.adjoint() elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'): obj = arg.conjugate().transpose() if obj is not None: return obj return Expr.__new__(cls, arg) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
2,242
23.922222
72
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/grover.py
"""Grover's algorithm and helper functions. Todo: * W gate construction (or perhaps -W gate based on Mermin's book) * Generalize the algorithm for an unknown function that returns 1 on multiple qubit states, not just one. * Implement _represent_ZGate in OracleGate """ from __future__ import print_function, division from sympy import floor, pi, sqrt, sympify, eye from sympy.core.compatibility import range from sympy.core.numbers import NegativeOne from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import UnitaryOperator from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import IntQubit __all__ = [ 'OracleGate', 'WGate', 'superposition_basis', 'grover_iteration', 'apply_grover' ] def superposition_basis(nqubits): """Creates an equal superposition of the computational basis. Parameters ========== nqubits : int The number of qubits. Returns ======= state : Qubit An equal superposition of the computational basis with nqubits. Examples ======== Create an equal superposition of 2 qubits:: >>> from sympy.physics.quantum.grover import superposition_basis >>> superposition_basis(2) |0>/2 + |1>/2 + |2>/2 + |3>/2 """ amp = 1/sqrt(2**nqubits) return sum([amp*IntQubit(n, nqubits) for n in range(2**nqubits)]) class OracleGate(Gate): """A black box gate. The gate marks the desired qubits of an unknown function by flipping the sign of the qubits. The unknown function returns true when it finds its desired qubits and false otherwise. Parameters ========== qubits : int Number of qubits. oracle : callable A callable function that returns a boolean on a computational basis. Examples ======== Apply an Oracle gate that flips the sign of ``|2>`` on different qubits:: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.grover import OracleGate >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(2, f) >>> qapply(v*IntQubit(2)) -|2> >>> qapply(v*IntQubit(3)) |3> """ gate_name = u'V' gate_name_latex = u'V' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # TODO: args[1] is not a subclass of Basic if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = (args[0],) sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) if not callable(args[1]): raise TypeError('Callable expected, got: %r' % args[1]) return (sub_args[0], args[1]) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**args[0] #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def search_function(self): """The unknown function that helps find the sought after qubits.""" return self.label[1] @property def targets(self): """A tuple of target qubits.""" return sympify(tuple(range(self.args[0]))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """Apply this operator to a Qubit subclass. Parameters ========== qubits : Qubit The qubit subclass to apply this operator to. Returns ======= state : Expr The resulting quantum state. """ if qubits.nqubits != self.nqubits: raise QuantumError( 'OracleGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # If function returns 1 on qubits # return the negative of the qubits (flip the sign) if self.search_function(qubits): return -qubits else: return qubits #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_ZGate(self, basis, **options): """ Represent the OracleGate in the computational basis. """ nbasis = 2**self.nqubits # compute it only once matrixOracle = eye(nbasis) # Flip the sign given the output of the oracle function for i in range(nbasis): if self.search_function(IntQubit(i, self.nqubits)): matrixOracle[i, i] = NegativeOne() return matrixOracle class WGate(Gate): """General n qubit W Gate in Grover's algorithm. The gate performs the operation ``2|phi><phi| - 1`` on some qubits. ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)`` Parameters ========== nqubits : int The number of qubits to operate on """ gate_name = u'W' gate_name_latex = u'W' @classmethod def _eval_args(cls, args): if len(args) != 1: raise QuantumError( 'Insufficient/excessive arguments to W gate. Please ' + 'supply the number of qubits to operate on.' ) args = UnitaryOperator._eval_args(args) if not args[0].is_Integer: raise TypeError('Integer expected, got: %r' % args[0]) return args #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): return sympify(tuple(reversed(range(self.args[0])))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """ qubits: a set of qubits (Qubit) Returns: quantum object (quantum expression - QExpr) """ if qubits.nqubits != self.nqubits: raise QuantumError( 'WGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis # state and phi is the superposition of basis states (see function # create_computational_basis above) basis_states = superposition_basis(self.nqubits) change_to_basis = (2/sqrt(2**self.nqubits))*basis_states return change_to_basis - qubits def grover_iteration(qstate, oracle): """Applies one application of the Oracle and W Gate, WV. Parameters ========== qstate : Qubit A superposition of qubits. oracle : OracleGate The black box operator that flips the sign of the desired basis qubits. Returns ======= Qubit : The qubits after applying the Oracle and W gate. Examples ======== Perform one iteration of grover's algorithm to see a phase change:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import OracleGate >>> from sympy.physics.quantum.grover import superposition_basis >>> from sympy.physics.quantum.grover import grover_iteration >>> numqubits = 2 >>> basis_states = superposition_basis(numqubits) >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(numqubits, f) >>> qapply(grover_iteration(basis_states, v)) |2> """ wgate = WGate(oracle.nqubits) return wgate*oracle*qstate def apply_grover(oracle, nqubits, iterations=None): """Applies grover's algorithm. Parameters ========== oracle : callable The unknown callable function that returns true when applied to the desired qubits and false otherwise. Returns ======= state : Expr The resulting state after Grover's algorithm has been iterated. Examples ======== Apply grover's algorithm to an even superposition of 2 qubits:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import apply_grover >>> f = lambda qubits: qubits == IntQubit(2) >>> qapply(apply_grover(f, 2)) |2> """ if nqubits <= 0: raise QuantumError( 'Grover\'s algorithm needs nqubits > 0, received %r qubits' % nqubits ) if iterations is None: iterations = floor(sqrt(2**nqubits)*(pi/4)) v = OracleGate(nqubits, oracle) iterated = superposition_basis(nqubits) for iter in range(iterations): iterated = grover_iteration(iterated, v) iterated = qapply(iterated) return iterated
9,884
29.229358
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/matrixutils.py
"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse.""" from __future__ import print_function, division from sympy import Matrix, I, Expr, Integer from sympy.core.compatibility import range from sympy.matrices import eye, zeros from sympy.external import import_module __all__ = [ 'numpy_ndarray', 'scipy_sparse_matrix', 'sympy_to_numpy', 'sympy_to_scipy_sparse', 'numpy_to_sympy', 'scipy_sparse_to_sympy', 'flatten_scalar', 'matrix_dagger', 'to_sympy', 'to_numpy', 'to_scipy_sparse', 'matrix_tensor_product', 'matrix_zeros' ] # Conditionally define the base classes for numpy and scipy.sparse arrays # for use in isinstance tests. np = import_module('numpy') if not np: class numpy_ndarray(object): pass else: numpy_ndarray = np.ndarray scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if not scipy: class scipy_sparse_matrix(object): pass sparse = None else: sparse = scipy.sparse # Try to find spmatrix. if hasattr(sparse, 'base'): # Newer versions have it under scipy.sparse.base. scipy_sparse_matrix = sparse.base.spmatrix elif hasattr(sparse, 'sparse'): # Older versions have it under scipy.sparse.sparse. scipy_sparse_matrix = sparse.sparse.spmatrix def sympy_to_numpy(m, **options): """Convert a sympy Matrix/complex number to a numpy matrix or scalar.""" if not np: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, Matrix): return np.matrix(m.tolist(), dtype=dtype) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected Matrix or complex scalar, got: %r' % m) def sympy_to_scipy_sparse(m, **options): """Convert a sympy Matrix/complex number to a numpy matrix or scalar.""" if not np or not sparse: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, Matrix): return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype)) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected Matrix or complex scalar, got: %r' % m) def scipy_sparse_to_sympy(m, **options): """Convert a scipy.sparse matrix to a sympy matrix.""" return Matrix(m.todense()) def numpy_to_sympy(m, **options): """Convert a numpy matrix to a sympy matrix.""" return Matrix(m) def to_sympy(m, **options): """Convert a numpy/scipy.sparse matrix to a sympy matrix.""" if isinstance(m, Matrix): return m elif isinstance(m, numpy_ndarray): return numpy_to_sympy(m) elif isinstance(m, scipy_sparse_matrix): return scipy_sparse_to_sympy(m) elif isinstance(m, Expr): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_numpy(m, **options): """Convert a sympy/scipy.sparse matrix to a numpy matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (Matrix, Expr)): return sympy_to_numpy(m, dtype=dtype) elif isinstance(m, numpy_ndarray): return m elif isinstance(m, scipy_sparse_matrix): return m.todense() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_scipy_sparse(m, **options): """Convert a sympy/numpy matrix to a scipy.sparse matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (Matrix, Expr)): return sympy_to_scipy_sparse(m, dtype=dtype) elif isinstance(m, numpy_ndarray): if not sparse: raise ImportError return sparse.csr_matrix(m) elif isinstance(m, scipy_sparse_matrix): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def flatten_scalar(e): """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged.""" if isinstance(e, Matrix): if e.shape == (1, 1): e = e[0] if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): if e.shape == (1, 1): e = complex(e[0, 0]) return e def matrix_dagger(e): """Return the dagger of a sympy/numpy/scipy.sparse matrix.""" if isinstance(e, Matrix): return e.H elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): return e.conjugate().transpose() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e) # TODO: Move this into sympy.matricies. def _sympy_tensor_product(*matrices): """Compute the tensor product of a sequence of sympy Matrices. This is the standard Kronecker product of matrices [1]. Parameters ========== matrices : tuple of Matrix instances The matrices to take the tensor product of. Returns ======= matrix : Matrix The tensor product matrix. Examples ======== >>> from sympy import I, Matrix, symbols >>> from sympy.physics.quantum.matrixutils import _sympy_tensor_product >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> _sympy_tensor_product(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> _sympy_tensor_product(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) References ========== [1] http://en.wikipedia.org/wiki/Kronecker_product """ # Make sure we have a sequence of Matrices if not all(isinstance(m, Matrix) for m in matrices): raise TypeError( 'Sequence of Matrices expected, got: %s' % repr(matrices) ) # Pull out the first element in the product. matrix_expansion = matrices[-1] # Do the tensor product working from right to left. for mat in reversed(matrices[:-1]): rows = mat.rows cols = mat.cols # Go through each row appending tensor product to. # running matrix_expansion. for i in range(rows): start = matrix_expansion*mat[i*cols] # Go through each column joining each item for j in range(cols - 1): start = start.row_join( matrix_expansion*mat[i*cols + j + 1] ) # If this is the first element, make it the start of the # new row. if i == 0: next = start else: next = next.col_join(start) matrix_expansion = next return matrix_expansion def _numpy_tensor_product(*product): """numpy version of tensor product of multiple arguments.""" if not np: raise ImportError answer = product[0] for item in product[1:]: answer = np.kron(answer, item) return answer def _scipy_sparse_tensor_product(*product): """scipy.sparse version of tensor product of multiple arguments.""" if not sparse: raise ImportError answer = product[0] for item in product[1:]: answer = sparse.kron(answer, item) # The final matrices will just be multiplied, so csr is a good final # sparse format. return sparse.csr_matrix(answer) def matrix_tensor_product(*product): """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices.""" if isinstance(product[0], Matrix): return _sympy_tensor_product(*product) elif isinstance(product[0], numpy_ndarray): return _numpy_tensor_product(*product) elif isinstance(product[0], scipy_sparse_matrix): return _scipy_sparse_tensor_product(*product) def _numpy_eye(n): """numpy version of complex eye.""" if not np: raise ImportError return np.matrix(np.eye(n, dtype='complex')) def _scipy_sparse_eye(n): """scipy.sparse version of complex eye.""" if not sparse: raise ImportError return sparse.eye(n, n, dtype='complex') def matrix_eye(n, **options): """Get the version of eye and tensor_product for a given format.""" format = options.get('format', 'sympy') if format == 'sympy': return eye(n) elif format == 'numpy': return _numpy_eye(n) elif format == 'scipy.sparse': return _scipy_sparse_eye(n) raise NotImplementedError('Invalid format: %r' % format) def _numpy_zeros(m, n, **options): """numpy verson of zeros.""" dtype = options.get('dtype', 'float64') if not np: raise ImportError return np.zeros((m, n), dtype=dtype) def _scipy_sparse_zeros(m, n, **options): """scipy.sparse verson of zeros.""" spmatrix = options.get('spmatrix', 'csr') dtype = options.get('dtype', 'float64') if not sparse: raise ImportError if spmatrix == 'lil': return sparse.lil_matrix((m, n), dtype=dtype) elif spmatrix == 'csr': return sparse.csr_matrix((m, n), dtype=dtype) def matrix_zeros(m, n, **options): """"Get a zeros matrix for a given format.""" format = options.get('format', 'sympy') dtype = options.get('dtype', 'float64') spmatrix = options.get('spmatrix', 'csr') if format == 'sympy': return zeros(m, n) elif format == 'numpy': return _numpy_zeros(m, n, **options) elif format == 'scipy.sparse': return _scipy_sparse_zeros(m, n, **options) raise NotImplementedError('Invaild format: %r' % format) def _numpy_matrix_to_zero(e): """Convert a numpy zero matrix to the zero scalar.""" if not np: raise ImportError test = np.zeros_like(e) if np.allclose(e, test): return 0.0 else: return e def _scipy_sparse_matrix_to_zero(e): """Convert a scipy.sparse zero matrix to the zero scalar.""" if not np: raise ImportError edense = e.todense() test = np.zeros_like(edense) if np.allclose(edense, test): return 0.0 else: return e def matrix_to_zero(e): """Convert a zero matrix to the scalar zero.""" if isinstance(e, Matrix): if zeros(*e.shape) == e: e = Integer(0) elif isinstance(e, numpy_ndarray): e = _numpy_matrix_to_zero(e) elif isinstance(e, scipy_sparse_matrix): e = _scipy_sparse_matrix_to_zero(e) return e
10,287
28.648415
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/boson.py
"""Bosonic quantum operators.""" from sympy import Mul, Integer, exp, sqrt, conjugate from sympy.physics.quantum import Operator from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator from sympy.functions.special.tensor_functions import KroneckerDelta __all__ = [ 'BosonOp', 'BosonFockKet', 'BosonFockBra', 'BosonCoherentKet', 'BosonCoherentBra' ] class BosonOp(Operator): """A bosonic operator that satisfies [a, Dagger(a)] == 1. Parameters ========== name : str A string that labels the bosonic mode. annihilation : bool A bool that indicates if the bosonic operator is an annihilation (True, default value) or creation operator (False) Examples ======== >>> from sympy.physics.quantum import Dagger, Commutator >>> from sympy.physics.quantum.boson import BosonOp >>> a = BosonOp("a") >>> Commutator(a, Dagger(a)).doit() 1 """ @property def name(self): return self.args[0] @property def is_annihilation(self): return bool(self.args[1]) @classmethod def default_args(self): return ("a", True) def __new__(cls, *args, **hints): if not len(args) in [1, 2]: raise ValueError('1 or 2 parameters expected, got %s' % args) if len(args) == 1: args = (args[0], Integer(1)) if len(args) == 2: args = (args[0], Integer(args[1])) return Operator.__new__(cls, *args) def _eval_commutator_BosonOp(self, other, **hints): if self.name == other.name: # [a^\dagger, a] = -1 if not self.is_annihilation and other.is_annihilation: return Integer(-1) elif 'independent' in hints and hints['independent']: # [a, b] = 0 return Integer(0) return None def _eval_commutator_FermionOp(self, other, **hints): return Integer(0) def _eval_anticommutator_BosonOp(self, other, **hints): if 'independent' in hints and hints['independent']: # {a, b} = 2 * a * b, because [a, b] = 0 return 2 * self * other return None def _eval_adjoint(self): return BosonOp(str(self.name), not self.is_annihilation) def __mul__(self, other): if other == IdentityOperator(2): return self if isinstance(other, Mul): args1 = tuple(arg for arg in other.args if arg.is_commutative) args2 = tuple(arg for arg in other.args if not arg.is_commutative) x = self for y in args2: x = x * y return Mul(*args1) * x return Mul(self, other) def _print_contents_latex(self, printer, *args): if self.is_annihilation: return r'{%s}' % str(self.name) else: return r'{{%s}^\dag}' % str(self.name) def _print_contents(self, printer, *args): if self.is_annihilation: return r'%s' % str(self.name) else: return r'Dagger(%s)' % str(self.name) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) if self.is_annihilation: return pform else: return pform**prettyForm(u'\N{DAGGER}') class BosonFockKet(Ket): """Fock state ket for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockBra @classmethod def _eval_hilbert_space(cls, label): return FockSpace() def _eval_innerproduct_BosonFockBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_operator_BosonOp(self, op, **options): if op.is_annihilation: return sqrt(self.n) * BosonFockKet(self.n - 1) else: return sqrt(self.n + 1) * BosonFockKet(self.n + 1) class BosonFockBra(Bra): """Fock state bra for a bosonic mode. Parameters ========== n : Number The Fock state number. """ def __new__(cls, n): return Bra.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return BosonFockKet @classmethod def _eval_hilbert_space(cls, label): return FockSpace() class BosonCoherentKet(Ket): """Coherent state ket for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Ket.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentBra @classmethod def _eval_hilbert_space(cls, label): return HilbertSpace() def _eval_innerproduct_BosonCoherentBra(self, bra, **hints): if self.alpha == bra.alpha: return Integer(1) else: return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2) def _apply_operator_BosonOp(self, op, **options): if op.is_annihilation: return self.alpha * self else: return None class BosonCoherentBra(Bra): """Coherent state bra for a bosonic mode. Parameters ========== alpha : Number, Symbol The complex amplitude of the coherent state. """ def __new__(cls, alpha): return Bra.__new__(cls, alpha) @property def alpha(self): return self.label[0] @classmethod def dual_class(self): return BosonCoherentKet def _apply_operator_BosonOp(self, op, **options): if not op.is_annihilation: return self.alpha * self else: return None
6,093
22.898039
107
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/qexpr.py
from __future__ import print_function, division from sympy import Expr, sympify, Symbol, Matrix from sympy.printing.pretty.stringpict import prettyForm from sympy.core.containers import Tuple from sympy.core.compatibility import is_sequence, string_types from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, to_sympy, to_numpy, to_scipy_sparse ) __all__ = [ 'QuantumError', 'QExpr' ] #----------------------------------------------------------------------------- # Error handling #----------------------------------------------------------------------------- class QuantumError(Exception): pass def _qsympify_sequence(seq): """Convert elements of a sequence to standard form. This is like sympify, but it performs special logic for arguments passed to QExpr. The following conversions are done: * (list, tuple, Tuple) => _qsympify_sequence each element and convert sequence to a Tuple. * basestring => Symbol * Matrix => Matrix * other => sympify Strings are passed to Symbol, not sympify to make sure that variables like 'pi' are kept as Symbols, not the SymPy built-in number subclasses. Examples ======== >>> from sympy.physics.quantum.qexpr import _qsympify_sequence >>> _qsympify_sequence((1,2,[3,4,[1,]])) (1, 2, (3, 4, (1,))) """ return tuple(__qsympify_sequence_helper(seq)) def __qsympify_sequence_helper(seq): """ Helper function for _qsympify_sequence This function does the actual work. """ #base case. If not a list, do Sympification if not is_sequence(seq): if isinstance(seq, Matrix): return seq elif isinstance(seq, string_types): return Symbol(seq) else: return sympify(seq) # base condition, when seq is QExpr and also # is iterable. if isinstance(seq, QExpr): return seq #if list, recurse on each item in the list result = [__qsympify_sequence_helper(item) for item in seq] return Tuple(*result) #----------------------------------------------------------------------------- # Basic Quantum Expression from which all objects descend #----------------------------------------------------------------------------- class QExpr(Expr): """A base class for all quantum object like operators and states.""" # In sympy, slots are for instance attributes that are computed # dynamically by the __new__ method. They are not part of args, but they # derive from args. # The Hilbert space a quantum Object belongs to. __slots__ = ['hilbert_space'] is_commutative = False # The separator used in printing the label. _label_separator = u'' @property def free_symbols(self): return {self} def __new__(cls, *args, **old_assumptions): """Construct a new quantum object. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the quantum object. For a state, this will be its symbol or its set of quantum numbers. Examples ======== >>> from sympy.physics.quantum.qexpr import QExpr >>> q = QExpr(0) >>> q 0 >>> q.label (0,) >>> q.hilbert_space H >>> q.args (0,) >>> q.is_commutative False """ # First compute args and call Expr.__new__ to create the instance args = cls._eval_args(args) if len(args) == 0: args = cls._eval_args(tuple(cls.default_args())) inst = Expr.__new__(cls, *args, **old_assumptions) # Now set the slots on the instance inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _new_rawargs(cls, hilbert_space, *args, **old_assumptions): """Create new instance of this class with hilbert_space and args. This is used to bypass the more complex logic in the ``__new__`` method in cases where you already have the exact ``hilbert_space`` and ``args``. This should be used when you are positive these arguments are valid, in their final, proper form and want to optimize the creation of the object. """ obj = Expr.__new__(cls, *args, **old_assumptions) obj.hilbert_space = hilbert_space return obj #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label is the unique set of identifiers for the object. Usually, this will include all of the information about the state *except* the time (in the case of time-dependent objects). This must be a tuple, rather than a Tuple. """ if len(self.args) == 0: # If there is no label specified, return the default return self._eval_args(list(self.default_args())) else: return self.args @property def is_symbolic(self): return True @classmethod def default_args(self): """If no arguments are specified, then this will return a default set of arguments to be run through the constructor. NOTE: Any classes that override this MUST return a tuple of arguments. Should be overidden by subclasses to specify the default arguments for kets and operators """ raise NotImplementedError("No default arguments for this class!") #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_adjoint(self): obj = Expr._eval_adjoint(self) if obj is None: obj = Expr.__new__(Dagger, self) if isinstance(obj, QExpr): obj.hilbert_space = self.hilbert_space return obj @classmethod def _eval_args(cls, args): """Process the args passed to the __new__ method. This simply runs args through _qsympify_sequence. """ return _qsympify_sequence(args) @classmethod def _eval_hilbert_space(cls, args): """Compute the Hilbert space instance from the args. """ from sympy.physics.quantum.hilbert import HilbertSpace return HilbertSpace() #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- # Utilities for printing: these operate on raw sympy objects def _print_sequence(self, seq, sep, printer, *args): result = [] for item in seq: result.append(printer._print(item, *args)) return sep.join(result) def _print_sequence_pretty(self, seq, sep, printer, *args): pform = printer._print(seq[0], *args) for item in seq[1:]: pform = prettyForm(*pform.right((sep))) pform = prettyForm(*pform.right((printer._print(item, *args)))) return pform # Utilities for printing: these operate prettyForm objects def _print_subscript_pretty(self, a, b): top = prettyForm(*b.left(' '*a.width())) bot = prettyForm(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_superscript_pretty(self, a, b): return a**b def _print_parens_pretty(self, pform, left='(', right=')'): return prettyForm(*pform.parens(left=left, right=right)) # Printing of labels (i.e. args) def _print_label(self, printer, *args): """Prints the label of the QExpr This method prints self.label, using self._label_separator to separate the elements. This method should not be overridden, instead, override _print_contents to change printing behavior. """ return self._print_sequence( self.label, self._label_separator, printer, *args ) def _print_label_repr(self, printer, *args): return self._print_sequence( self.label, ',', printer, *args ) def _print_label_pretty(self, printer, *args): return self._print_sequence_pretty( self.label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): return self._print_sequence( self.label, self._label_separator, printer, *args ) # Printing of contents (default to label) def _print_contents(self, printer, *args): """Printer for contents of QExpr Handles the printing of any unique identifying contents of a QExpr to print as its contents, such as any variables or quantum numbers. The default is to print the label, which is almost always the args. This should not include printing of any brackets or parenteses. """ return self._print_label(printer, *args) def _print_contents_pretty(self, printer, *args): return self._print_label_pretty(printer, *args) def _print_contents_latex(self, printer, *args): return self._print_label_latex(printer, *args) # Main printing methods def _sympystr(self, printer, *args): """Default printing behavior of QExpr objects Handles the default printing of a QExpr. To add other things to the printing of the object, such as an operator name to operators or brackets to states, the class should override the _print/_pretty/_latex functions directly and make calls to _print_contents where appropriate. This allows things like InnerProduct to easily control its printing the printing of contents. """ return self._print_contents(printer, *args) def _sympyrepr(self, printer, *args): classname = self.__class__.__name__ label = self._print_label_repr(printer, *args) return '%s(%s)' % (classname, label) def _pretty(self, printer, *args): pform = self._print_contents_pretty(printer, *args) return pform def _latex(self, printer, *args): return self._print_contents_latex(printer, *args) #------------------------------------------------------------------------- # Methods from Basic and Expr #------------------------------------------------------------------------- def doit(self, **kw_args): return self def _eval_rewrite(self, pattern, rule, **hints): if hints.get('deep', False): args = [ a._eval_rewrite(pattern, rule, **hints) for a in self.args ] else: args = self.args # TODO: Make Basic.rewrite use hints in evaluating # self.rule(*args, **hints), not having hints breaks spin state # (un)coupling on rewrite if pattern is None or isinstance(self, pattern): if hasattr(self, rule): rewritten = getattr(self, rule)(*args, **hints) if rewritten is not None: return rewritten return self #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): raise NotImplementedError('This object does not have a default basis') def _represent(self, **options): """Represent this object in a given basis. This method dispatches to the actual methods that perform the representation. Subclases of QExpr should define various methods to determine how the object will be represented in various bases. The format of these methods is:: def _represent_BasisName(self, basis, **options): Thus to define how a quantum object is represented in the basis of the operator Position, you would define:: def _represent_Position(self, basis, **options): Usually, basis object will be instances of Operator subclasses, but there is a chance we will relax this in the future to accomodate other types of basis sets that are not associated with an operator. If the ``format`` option is given it can be ("sympy", "numpy", "scipy.sparse"). This will ensure that any matrices that result from representing the object are returned in the appropriate matrix format. Parameters ========== basis : Operator The Operator whose basis functions will be used as the basis for representation. options : dict A dictionary of key/value pairs that give options and hints for the representation, such as the number of basis functions to be used. """ basis = options.pop('basis', None) if basis is None: result = self._represent_default_basis(**options) else: result = dispatch_method(self, '_represent', basis, **options) # If we get a matrix representation, convert it to the right format. format = options.get('format', 'sympy') result = self._format_represent(result, format) return result def _format_represent(self, result, format): if format == 'sympy' and not isinstance(result, Matrix): return to_sympy(result) elif format == 'numpy' and not isinstance(result, numpy_ndarray): return to_numpy(result) elif format == 'scipy.sparse' and \ not isinstance(result, scipy_sparse_matrix): return to_scipy_sparse(result) return result def split_commutative_parts(e): """Split into commutative and non-commutative parts.""" c_part, nc_part = e.args_cnc() c_part = list(c_part) return c_part, nc_part def split_qexpr_parts(e): """Split an expression into Expr and noncommutative QExpr parts.""" expr_part = [] qexpr_part = [] for arg in e.args: if not isinstance(arg, QExpr): expr_part.append(arg) else: qexpr_part.append(arg) return expr_part, qexpr_part def dispatch_method(self, basename, arg, **options): """Dispatch a method to the proper handlers.""" method_name = '%s_%s' % (basename, arg.__class__.__name__) if hasattr(self, method_name): f = getattr(self, method_name) # This can raise and we will allow it to propagate. result = f(arg, **options) if result is not None: return result raise NotImplementedError( "%s.%s can't handle: %r" % (self.__class__.__name__, basename, arg) )
14,915
32.9
97
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_cartesian.py
"""Tests for cartesian.py""" from sympy import S, Interval, symbols, I, DiracDelta, exp, sqrt, pi from sympy.physics.quantum import qapply, represent, L2, Dagger from sympy.physics.quantum import Commutator, hbar from sympy.physics.quantum.cartesian import ( XOp, YOp, ZOp, PxOp, X, Y, Z, Px, XKet, XBra, PxKet, PxBra, PositionKet3D, PositionBra3D ) from sympy.physics.quantum.operator import DifferentialOperator x, y, z, x_1, x_2, x_3, y_1, z_1 = symbols('x,y,z,x_1,x_2,x_3,y_1,z_1') px, py, px_1, px_2 = symbols('px py px_1 px_2') def test_x(): assert X.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity)) assert Commutator(X, Px).doit() == I*hbar assert qapply(X*XKet(x)) == x*XKet(x) assert XKet(x).dual_class() == XBra assert XBra(x).dual_class() == XKet assert (Dagger(XKet(y))*XKet(x)).doit() == DiracDelta(x - y) assert (PxBra(px)*XKet(x)).doit() == \ exp(-I*x*px/hbar)/sqrt(2*pi*hbar) assert represent(XKet(x)) == DiracDelta(x - x_1) assert represent(XBra(x)) == DiracDelta(-x + x_1) assert XBra(x).position == x assert represent(XOp()*XKet()) == x*DiracDelta(x - x_2) assert represent(XOp()*XKet()*XBra('y')) == \ x*DiracDelta(x - x_3)*DiracDelta(x_1 - y) assert represent(XBra("y")*XKet()) == DiracDelta(x - y) assert represent( XKet()*XBra()) == DiracDelta(x - x_2) * DiracDelta(x_1 - x) rep_p = represent(XOp(), basis=PxOp) assert rep_p == hbar*I*DiracDelta(px_1 - px_2)*DifferentialOperator(px_1) assert rep_p == represent(XOp(), basis=PxOp()) assert rep_p == represent(XOp(), basis=PxKet) assert rep_p == represent(XOp(), basis=PxKet()) assert represent(XOp()*PxKet(), basis=PxKet) == \ hbar*I*DiracDelta(px - px_2)*DifferentialOperator(px) def test_p(): assert Px.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity)) assert qapply(Px*PxKet(px)) == px*PxKet(px) assert PxKet(px).dual_class() == PxBra assert PxBra(x).dual_class() == PxKet assert (Dagger(PxKet(py))*PxKet(px)).doit() == DiracDelta(px - py) assert (XBra(x)*PxKet(px)).doit() == \ exp(I*x*px/hbar)/sqrt(2*pi*hbar) assert represent(PxKet(px)) == DiracDelta(px - px_1) rep_x = represent(PxOp(), basis=XOp) assert rep_x == -hbar*I*DiracDelta(x_1 - x_2)*DifferentialOperator(x_1) assert rep_x == represent(PxOp(), basis=XOp()) assert rep_x == represent(PxOp(), basis=XKet) assert rep_x == represent(PxOp(), basis=XKet()) assert represent(PxOp()*XKet(), basis=XKet) == \ -hbar*I*DiracDelta(x - x_2)*DifferentialOperator(x) assert represent(XBra("y")*PxOp()*XKet(), basis=XKet) == \ -hbar*I*DiracDelta(x - y)*DifferentialOperator(x) def test_3dpos(): assert Y.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity)) assert Z.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity)) test_ket = PositionKet3D(x, y, z) assert qapply(X*test_ket) == x*test_ket assert qapply(Y*test_ket) == y*test_ket assert qapply(Z*test_ket) == z*test_ket assert qapply(X*Y*test_ket) == x*y*test_ket assert qapply(X*Y*Z*test_ket) == x*y*z*test_ket assert qapply(Y*Z*test_ket) == y*z*test_ket assert PositionKet3D() == test_ket assert YOp() == Y assert ZOp() == Z assert PositionKet3D.dual_class() == PositionBra3D assert PositionBra3D.dual_class() == PositionKet3D other_ket = PositionKet3D(x_1, y_1, z_1) assert (Dagger(other_ket)*test_ket).doit() == \ DiracDelta(x - x_1)*DiracDelta(y - y_1)*DiracDelta(z - z_1) assert test_ket.position_x == x assert test_ket.position_y == y assert test_ket.position_z == z assert other_ket.position_x == x_1 assert other_ket.position_y == y_1 assert other_ket.position_z == z_1 # TODO: Add tests for representations
3,856
37.959596
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_represent.py
from sympy import Float, I, Integer, Matrix from sympy.external import import_module from sympy.utilities.pytest import skip from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.represent import (represent, rep_innerproduct, rep_expectation, enumerate_states) from sympy.physics.quantum.state import Bra, Ket from sympy.physics.quantum.operator import Operator, OuterProduct from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.matrixutils import (numpy_ndarray, scipy_sparse_matrix, to_numpy, to_scipy_sparse, to_sympy) from sympy.physics.quantum.cartesian import XKet, XOp, XBra from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.operatorset import operators_to_state Amat = Matrix([[1, I], [-I, 1]]) Bmat = Matrix([[1, 2], [3, 4]]) Avec = Matrix([[1], [I]]) class AKet(Ket): @classmethod def dual_class(self): return ABra def _represent_default_basis(self, **options): return self._represent_AOp(None, **options) def _represent_AOp(self, basis, **options): return Avec class ABra(Bra): @classmethod def dual_class(self): return AKet class AOp(Operator): def _represent_default_basis(self, **options): return self._represent_AOp(None, **options) def _represent_AOp(self, basis, **options): return Amat class BOp(Operator): def _represent_default_basis(self, **options): return self._represent_AOp(None, **options) def _represent_AOp(self, basis, **options): return Bmat k = AKet('a') b = ABra('a') A = AOp('A') B = BOp('B') _tests = [ # Bra (b, Dagger(Avec)), (Dagger(b), Avec), # Ket (k, Avec), (Dagger(k), Dagger(Avec)), # Operator (A, Amat), (Dagger(A), Dagger(Amat)), # OuterProduct (OuterProduct(k, b), Avec*Avec.H), # TensorProduct (TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)), # Pow (A**2, Amat**2), # Add/Mul (A*B + 2*A, Amat*Bmat + 2*Amat), # Commutator (Commutator(A, B), Amat*Bmat - Bmat*Amat), # AntiCommutator (AntiCommutator(A, B), Amat*Bmat + Bmat*Amat), # InnerProduct (InnerProduct(b, k), (Avec.H*Avec)[0]) ] def test_format_sympy(): for test in _tests: lhs = represent(test[0], basis=A, format='sympy') rhs = to_sympy(test[1]) assert lhs == rhs def test_scalar_sympy(): assert represent(Integer(1)) == Integer(1) assert represent(Float(1.0)) == Float(1.0) assert represent(1.0 + I) == 1.0 + I np = import_module('numpy') def test_format_numpy(): if not np: skip("numpy not installed.") for test in _tests: lhs = represent(test[0], basis=A, format='numpy') rhs = to_numpy(test[1]) if isinstance(lhs, numpy_ndarray): assert (lhs == rhs).all() else: assert lhs == rhs def test_scalar_numpy(): if not np: skip("numpy not installed.") assert represent(Integer(1), format='numpy') == 1 assert represent(Float(1.0), format='numpy') == 1.0 assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) def test_format_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") for test in _tests: lhs = represent(test[0], basis=A, format='scipy.sparse') rhs = to_scipy_sparse(test[1]) if isinstance(lhs, scipy_sparse_matrix): assert np.linalg.norm((lhs - rhs).todense()) == 0.0 else: assert lhs == rhs def test_scalar_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") assert represent(Integer(1), format='scipy.sparse') == 1 assert represent(Float(1.0), format='scipy.sparse') == 1.0 assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j x_ket = XKet('x') x_bra = XBra('x') x_op = XOp('X') def test_innerprod_represent(): assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit() assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit() try: rep_innerproduct(x_op) except TypeError: return True def test_operator_represent(): basis_kets = enumerate_states(operators_to_state(x_op), 1, 2) assert rep_expectation( x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0]) def test_enumerate_states(): test = XKet("foo") assert enumerate_states(test, 1, 1) == [XKet("foo_1")] assert enumerate_states( test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
5,124
26.116402
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_anticommutator.py
from sympy import symbols, Integer from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.anticommutator import AntiCommutator as AComm from sympy.physics.quantum.operator import Operator a, b, c = symbols('a,b,c') A, B, C, D = symbols('A,B,C,D', commutative=False) def test_anticommutator(): ac = AComm(A, B) assert isinstance(ac, AComm) assert ac.is_commutative is False assert ac.subs(A, C) == AComm(C, B) def test_commutator_identities(): assert AComm(a*A, b*B) == a*b*AComm(A, B) assert AComm(A, A) == 2*A**2 assert AComm(A, B) == AComm(B, A) assert AComm(a, b) == 2*a*b assert AComm(A, B).doit() == A*B + B*A def test_anticommutator_dagger(): assert Dagger(AComm(A, B)) == AComm(Dagger(A), Dagger(B)) class Foo(Operator): def _eval_anticommutator_Bar(self, bar): return Integer(0) class Bar(Operator): pass class Tam(Operator): def _eval_anticommutator_Foo(self, foo): return Integer(1) def test_eval_commutator(): F = Foo('F') B = Bar('B') T = Tam('T') assert AComm(F, B).doit() == 0 assert AComm(B, F).doit() == 0 assert AComm(F, T).doit() == 1 assert AComm(T, F).doit() == 1 assert AComm(B, T).doit() == B*T + T*B
1,262
21.553571
72
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_constants.py
from sympy import Float from sympy.physics.quantum.constants import hbar def test_hbar(): assert hbar.is_commutative is True assert hbar.is_real is True assert hbar.is_positive is True assert hbar.is_negative is False assert hbar.is_irrational is True assert hbar.evalf() == Float(1.05457162e-34)
325
22.285714
48
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_circuitplot.py
from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\ CreateCGate from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T from sympy.external import import_module from sympy.utilities.pytest import skip mpl = import_module('matplotlib') def test_render_label(): assert render_label('q0') == r'$|q0\rangle$' assert render_label('q0', {'q0': '0'}) == r'$|q0\rangle=|0\rangle$' def test_Mz(): assert str(Mz(0)) == 'Mz(0)' def test_create1(): Qgate = CreateOneQubitGate('Q') assert str(Qgate(0)) == 'Q(0)' def test_createc(): Qgate = CreateCGate('Q') assert str(Qgate([1],0)) == 'C((1),Q(0))' def test_labeller(): """Test the labeller utility""" assert labeller(2) == ['q_1', 'q_0'] assert labeller(3,'j') == ['j_2', 'j_1', 'j_0'] def test_cnot(): """Test a simple cnot circuit. Right now this only makes sure the code doesn't raise an exception, and some simple properties """ if not mpl: skip("matplotlib not installed") else: from sympy.physics.quantum.circuitplot import CircuitPlot c = CircuitPlot(CNOT(1,0),2,labels=labeller(2)) assert c.ngates == 2 assert c.nqubits == 2 assert c.labels == ['q_1', 'q_0'] c = CircuitPlot(CNOT(1,0),2) assert c.ngates == 2 assert c.nqubits == 2 assert c.labels == [] def test_ex1(): if not mpl: skip("matplotlib not installed") else: from sympy.physics.quantum.circuitplot import CircuitPlot c = CircuitPlot(CNOT(1,0)*H(1),2,labels=labeller(2)) assert c.ngates == 2 assert c.nqubits == 2 assert c.labels == ['q_1', 'q_0'] def test_ex4(): if not mpl: skip("matplotlib not installed") else: from sympy.physics.quantum.circuitplot import CircuitPlot c = CircuitPlot(SWAP(0,2)*H(0)* CGate((0,),S(1)) *H(1)*CGate((0,),T(2))\ *CGate((1,),S(2))*H(2),3,labels=labeller(3,'j')) assert c.ngates == 7 assert c.nqubits == 3 assert c.labels == ['j_2', 'j_1', 'j_0']
2,065
28.514286
94
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_density.py
from sympy import symbols, S, log from sympy.core.trace import Tr from sympy.external import import_module from sympy.physics.quantum.density import Density, entropy, fidelity from sympy.physics.quantum.state import Ket, TimeDepKet from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.represent import represent from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp from sympy.physics.quantum.spin import JzKet from sympy.physics.quantum.operator import OuterProduct from sympy.functions import sqrt from sympy.utilities.pytest import raises, slow from sympy.physics.quantum.matrixutils import scipy_sparse_matrix from sympy.physics.quantum.tensorproduct import TensorProduct def test_eval_args(): # check instance created assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density) assert isinstance(Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)]), Density) #test if Qubit object type preserved d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)]) for (state, prob) in d.args: assert isinstance(state, Qubit) # check for value error, when prob is not provided raises(ValueError, lambda: Density([Ket(0)], [Ket(1)])) def test_doit(): x, y = symbols('x y') A, B, C, D, E, F = symbols('A B C D E F', commutative=False) d = Density([XKet(), 0.5], [PxKet(), 0.5]) assert (0.5*(PxKet()*Dagger(PxKet())) + 0.5*(XKet()*Dagger(XKet()))) == d.doit() # check for kets with expr in them d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5]) assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) + 0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit() d = Density([(A + B)*C, 1.0]) assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) + 1.0*A*C*Dagger(C)*Dagger(B) + 1.0*B*C*Dagger(C)*Dagger(A) + 1.0*B*C*Dagger(C)*Dagger(B)) # With TensorProducts as args # Density with simple tensor products as args t = TensorProduct(A, B, C) d = Density([t, 1.0]) assert d.doit() == \ 1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C)) # Density with multiple Tensorproducts as states t2 = TensorProduct(A, B) t3 = TensorProduct(C, D) d = Density([t2, 0.5], [t3, 0.5]) assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) + 0.5 * TensorProduct(C*Dagger(C), D*Dagger(D))) #Density with mixed states d = Density([t2 + t3, 1.0]) assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) + 1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) + 1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) + 1.0 * TensorProduct(C*Dagger(C), D*Dagger(D))) #Density operators with spin states tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1)) d = Density([tp1, 1]) # full trace t = Tr(d) assert t.doit() == 1 #Partial trace on density operators with spin states t = Tr(d, [0]) assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1)) t = Tr(d, [1]) assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1)) # with another spin state tp2 = TensorProduct(JzKet(S(1)/2, S(1)/2), JzKet(S(1)/2, -S(1)/2)) d = Density([tp2, 1]) #full trace t = Tr(d) assert t.doit() == 1 #Partial trace on density operators with spin states t = Tr(d, [0]) assert t.doit() == JzKet(S(1)/2, -S(1)/2) * Dagger(JzKet(S(1)/2, -S(1)/2)) t = Tr(d, [1]) assert t.doit() == JzKet(S(1)/2, S(1)/2) * Dagger(JzKet(S(1)/2, S(1)/2)) def test_apply_op(): d = Density([Ket(0), 0.5], [Ket(1), 0.5]) assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5], [XOp()*Ket(1), 0.5]) def test_represent(): x, y = symbols('x y') d = Density([XKet(), 0.5], [PxKet(), 0.5]) assert (represent(0.5*(PxKet()*Dagger(PxKet()))) + represent(0.5*(XKet()*Dagger(XKet())))) == represent(d) # check for kets with expr in them d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5]) assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) + represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \ represent(d_with_sym) # check when given explicit basis assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) + represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \ represent(d, basis=PxOp()) def test_states(): d = Density([Ket(0), 0.5], [Ket(1), 0.5]) states = d.states() assert states[0] == Ket(0) and states[1] == Ket(1) def test_probs(): d = Density([Ket(0), .75], [Ket(1), 0.25]) probs = d.probs() assert probs[0] == 0.75 and probs[1] == 0.25 #probs can be symbols x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) probs = d.probs() assert probs[0] == x and probs[1] == y def test_get_state(): x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) states = (d.get_state(0), d.get_state(1)) assert states[0] == Ket(0) and states[1] == Ket(1) def test_get_prob(): x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) probs = (d.get_prob(0), d.get_prob(1)) assert probs[0] == x and probs[1] == y def test_entropy(): up = JzKet(S(1)/2, S(1)/2) down = JzKet(S(1)/2, -S(1)/2) d = Density((up, 0.5), (down, 0.5)) # test for density object ent = entropy(d) assert entropy(d) == 0.5*log(2) assert d.entropy() == 0.5*log(2) np = import_module('numpy', min_module_version='1.4.0') if np: #do this test only if 'numpy' is available on test machine np_mat = represent(d, format='numpy') ent = entropy(np_mat) assert isinstance(np_mat, np.matrixlib.defmatrix.matrix) assert ent.real == 0.69314718055994529 assert ent.imag == 0 scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if scipy and np: #do this test only if numpy and scipy are available mat = represent(d, format="scipy.sparse") assert isinstance(mat, scipy_sparse_matrix) assert ent.real == 0.69314718055994529 assert ent.imag == 0 def test_eval_trace(): up = JzKet(S(1)/2, S(1)/2) down = JzKet(S(1)/2, -S(1)/2) d = Density((up, 0.5), (down, 0.5)) t = Tr(d) assert t.doit() == 1 #test dummy time dependent states class TestTimeDepKet(TimeDepKet): def _eval_trace(self, bra, **options): return 1 x, t = symbols('x t') k1 = TestTimeDepKet(0, 0.5) k2 = TestTimeDepKet(0, 1) d = Density([k1, 0.5], [k2, 0.5]) assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) + 0.5 * OuterProduct(k2, k2.dual)) t = Tr(d) assert t.doit() == 1 @slow def test_fidelity(): #test with kets up = JzKet(S(1)/2, S(1)/2) down = JzKet(S(1)/2, -S(1)/2) updown = (S(1)/sqrt(2))*up + (S(1)/sqrt(2))*down #check with matrices up_dm = represent(up * Dagger(up)) down_dm = represent(down * Dagger(down)) updown_dm = represent(updown * Dagger(updown)) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert fidelity(up_dm, down_dm) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S(1)/sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S(1)/sqrt(2))) < 1e-3 #check with density up_dm = Density([up, 1.0]) down_dm = Density([down, 1.0]) updown_dm = Density([updown, 1.0]) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert abs(fidelity(up_dm, down_dm)) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S(1)/sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S(1)/sqrt(2))) < 1e-3 #check mixed states with density updown2 = (sqrt(3)/2)*up + (S(1)/2)*down d1 = Density([updown, 0.25], [updown2, 0.75]) d2 = Density([updown, 0.75], [updown2, 0.25]) assert abs(fidelity(d1, d2) - 0.991) < 1e-3 assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3 #using qubits/density(pure states) state1 = Qubit('0') state2 = Qubit('1') state3 = (S(1)/sqrt(2))*state1 + (S(1)/sqrt(2))*state2 state4 = (sqrt(S(2)/3))*state1 + (S(1)/sqrt(3))*state2 state1_dm = Density([state1, 1]) state2_dm = Density([state2, 1]) state3_dm = Density([state3, 1]) assert fidelity(state1_dm, state1_dm) == 1 assert fidelity(state1_dm, state2_dm) == 0 assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3 assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3 #using qubits/density(mixed states) d1 = Density([state3, 0.70], [state4, 0.30]) d2 = Density([state3, 0.20], [state4, 0.80]) assert abs(fidelity(d1, d1) - 1) < 1e-3 assert abs(fidelity(d1, d2) - 0.996) < 1e-3 assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3 #TODO: test for invalid arguments # non-square matrix mat1 = [[0, 0], [0, 0], [0, 0]] mat2 = [[0, 0], [0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unequal dimensions mat1 = [[0, 0], [0, 0]] mat2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unsupported data-type x, y = 1, 2 # random values that is not a matrix raises(ValueError, lambda: fidelity(x, y))
9,550
32.163194
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_piab.py
"""Tests for piab.py""" from sympy import Interval, pi, S, sin, sqrt, symbols from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum import L2, qapply, hbar, represent from sympy.physics.quantum.piab import PIABHamiltonian, PIABKet, PIABBra, m, L i, j, n, x = symbols('i j n x') def test_H(): assert PIABHamiltonian('H').hilbert_space == \ L2(Interval(S.NegativeInfinity, S.Infinity)) assert qapply(PIABHamiltonian('H')*PIABKet(n)) == \ (n**2*pi**2*hbar**2)/(2*m*L**2)*PIABKet(n) def test_states(): assert PIABKet(n).dual_class() == PIABBra assert PIABKet(n).hilbert_space == \ L2(Interval(S.NegativeInfinity, S.Infinity)) assert represent(PIABKet(n)) == sqrt(2/L)*sin(n*pi*x/L) assert (PIABBra(i)*PIABKet(j)).doit() == KroneckerDelta(i, j) assert PIABBra(n).dual_class() == PIABKet
881
34.28
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_matrixutils.py
from random import randint from sympy import Matrix, zeros, ones, Integer from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse, matrix_tensor_product, matrix_to_zero, matrix_zeros, numpy_ndarray, scipy_sparse_matrix ) from sympy.core.compatibility import range from sympy.external import import_module from sympy.utilities.pytest import skip m = Matrix([[1, 2], [3, 4]]) def test_sympy_to_sympy(): assert to_sympy(m) == m def test_matrix_to_zero(): assert matrix_to_zero(m) == m assert matrix_to_zero(Matrix([[0, 0], [0, 0]])) == Integer(0) np = import_module('numpy') def test_to_numpy(): if not np: skip("numpy not installed.") result = np.matrix([[1, 2], [3, 4]], dtype='complex') assert (to_numpy(m) == result).all() def test_matrix_tensor_product(): if not np: skip("numpy not installed.") l1 = zeros(4) for i in range(16): l1[i] = 2**i l2 = zeros(4) for i in range(16): l2[i] = i l3 = zeros(2) for i in range(4): l3[i] = i vec = Matrix([1, 2, 3]) #test for Matrix known 4x4 matricies numpyl1 = np.matrix(l1.tolist()) numpyl2 = np.matrix(l2.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, l2] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [l2, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for other known matrix of different dimensions numpyl2 = np.matrix(l3.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, l3] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [l3, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for non square matrix numpyl2 = np.matrix(vec.tolist()) numpy_product = np.kron(numpyl1, numpyl2) args = [l1, vec] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() numpy_product = np.kron(numpyl2, numpyl1) args = [vec, l1] sympy_product = matrix_tensor_product(*args) assert numpy_product.tolist() == sympy_product.tolist() #test for random matrix with random values that are floats random_matrix1 = np.random.rand(randint(1, 5), randint(1, 5)) random_matrix2 = np.random.rand(randint(1, 5), randint(1, 5)) numpy_product = np.kron(random_matrix1, random_matrix2) args = [Matrix(random_matrix1.tolist()), Matrix(random_matrix2.tolist())] sympy_product = matrix_tensor_product(*args) assert not (sympy_product - Matrix(numpy_product.tolist())).tolist() > \ (ones(sympy_product.rows, sympy_product.cols)*epsilon).tolist() #test for three matrix kronecker sympy_product = matrix_tensor_product(l1, vec, l2) numpy_product = np.kron(l1, np.kron(vec, l2)) assert numpy_product.tolist() == sympy_product.tolist() scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) def test_to_scipy_sparse(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") else: sparse = scipy.sparse result = sparse.csr_matrix([[1, 2], [3, 4]], dtype='complex') assert np.linalg.norm((to_scipy_sparse(m) - result).todense()) == 0.0 epsilon = .000001 def test_matrix_zeros_sympy(): sym = matrix_zeros(4, 4, format='sympy') assert isinstance(sym, Matrix) def test_matrix_zeros_numpy(): if not np: skip("numpy not installed.") num = matrix_zeros(4, 4, format='numpy') assert isinstance(num, numpy_ndarray) def test_matrix_zeros_scipy(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") sci = matrix_zeros(4, 4, format='scipy.sparse') assert isinstance(sci, scipy_sparse_matrix)
4,111
29.014599
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_fermion.py
from sympy.physics.quantum import Dagger, AntiCommutator, qapply from sympy.physics.quantum.fermion import FermionOp from sympy.physics.quantum.fermion import FermionFockKet, FermionFockBra def test_fermionoperator(): c = FermionOp('c') d = FermionOp('d') assert isinstance(c, FermionOp) assert isinstance(Dagger(c), FermionOp) assert c.is_annihilation assert not Dagger(c).is_annihilation assert FermionOp("c") == FermionOp("c") assert FermionOp("c") != FermionOp("d") assert FermionOp("c", True) != FermionOp("c", False) assert AntiCommutator(c, Dagger(c)).doit() == 1 assert AntiCommutator(c, Dagger(d)).doit() == c * Dagger(d) + Dagger(d) * c def test_fermion_states(): c = FermionOp("c") # Fock states assert (FermionFockBra(0) * FermionFockKet(1)).doit() == 0 assert (FermionFockBra(1) * FermionFockKet(1)).doit() == 1 assert qapply(c * FermionFockKet(1)) == FermionFockKet(0) assert qapply(c * FermionFockKet(0)) == 0 assert qapply(Dagger(c) * FermionFockKet(0)) == FermionFockKet(1) assert qapply(Dagger(c) * FermionFockKet(1)) == 0
1,129
29.540541
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_qasm.py
from sympy.physics.quantum.qasm import Qasm, prod, flip_index, trim,\ get_index, nonblank, fullsplit, fixcommand, stripquotes, read_qasm from sympy.physics.quantum.gate import X, Z, H, S, T from sympy.physics.quantum.gate import CNOT, SWAP, CPHASE, CGate, CGateS from sympy.physics.quantum.circuitplot import Mz, CreateOneQubitGate, CreateCGate def test_qasm_readqasm(): qasm_lines = """\ qubit q_0 qubit q_1 h q_0 cnot q_0,q_1 """ q = read_qasm(qasm_lines) assert q.get_circuit() == CNOT(1,0)*H(1) def test_qasm_ex1(): q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1') assert q.get_circuit() == CNOT(1,0)*H(1) def test_qasm_ex1_methodcalls(): q = Qasm() q.qubit('q_0') q.qubit('q_1') q.h('q_0') q.cnot('q_0', 'q_1') assert q.get_circuit() == CNOT(1,0)*H(1) def test_qasm_swap(): q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1') assert q.get_circuit() == CNOT(1,0)*CNOT(0,1)*CNOT(1,0) def test_qasm_ex2(): q = Qasm('qubit q_0', 'qubit q_1', 'qubit q_2', 'h q_1', 'cnot q_1,q_2', 'cnot q_0,q_1', 'h q_0', 'measure q_1', 'measure q_0', 'c-x q_1,q_2', 'c-z q_0,q_2') assert q.get_circuit() == CGate(2,Z(0))*CGate(1,X(0))*Mz(2)*Mz(1)*H(2)*CNOT(2,1)*CNOT(1,0)*H(1) def test_qasm_1q(): for symbol, gate in [('x', X), ('z', Z), ('h', H), ('s', S), ('t', T), ('measure', Mz)]: q = Qasm('qubit q_0', '%s q_0' % symbol) assert q.get_circuit() == gate(0) def test_qasm_2q(): for symbol, gate in [('cnot', CNOT), ('swap', SWAP), ('cphase', CPHASE)]: q = Qasm('qubit q_0', 'qubit q_1', '%s q_0,q_1' % symbol) assert q.get_circuit() == gate(1,0) def test_qasm_3q(): q = Qasm('qubit q0', 'qubit q1', 'qubit q2', 'toffoli q2,q1,q0') assert q.get_circuit() == CGateS((0,1),X(2)) def test_qasm_prod(): assert prod([1, 2, 3]) == 6 assert prod([H(0), X(1)])== H(0)*X(1) def test_qasm_flip_index(): assert flip_index(0, 2) == 1 assert flip_index(1, 2) == 0 def test_qasm_trim(): assert trim('nothing happens here') == 'nothing happens here' assert trim("Something #happens here") == "Something " def test_qasm_get_index(): assert get_index('q0', ['q0', 'q1']) == 1 assert get_index('q1', ['q0', 'q1']) == 0 def test_qasm_nonblank(): assert list(nonblank('abcd')) == list('abcd') assert list(nonblank('abc ')) == list('abc') def test_qasm_fullsplit(): assert fullsplit('g q0,q1,q2, q3') == ('g', ['q0', 'q1', 'q2', 'q3']) def test_qasm_fixcommand(): assert fixcommand('foo') == 'foo' assert fixcommand('def') == 'qdef' def test_qasm_stripquotes(): assert stripquotes("'S'") == 'S' assert stripquotes('"S"') == 'S' assert stripquotes('S') == 'S' def test_qasm_qdef(): # weaker test condition (str) since we don't have access to the actual class q = Qasm("def Q,0,Q",'qubit q0','Q q0') Qgate = CreateOneQubitGate('Q') assert str(q.get_circuit()) == 'Q(0)' q = Qasm("def CQ,1,Q", 'qubit q0', 'qubit q1', 'CQ q0,q1') Qgate = CreateCGate('Q') assert str(q.get_circuit()) == 'C((1),Q(0))'
3,176
32.442105
99
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_qft.py
from sympy import exp, I, Matrix, pi, sqrt, Symbol from sympy.core.compatibility import range from sympy.physics.quantum.qft import QFT, IQFT, RkGate from sympy.physics.quantum.gate import (ZGate, SwapGate, HadamardGate, CGate, PhaseGate, TGate) from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.represent import represent def test_RkGate(): x = Symbol('x') assert RkGate(1, x).k == x assert RkGate(1, x).targets == (1,) assert RkGate(1, 1) == ZGate(1) assert RkGate(2, 2) == PhaseGate(2) assert RkGate(3, 3) == TGate(3) assert represent( RkGate(0, x), nqubits=1) == Matrix([[1, 0], [0, exp(2*I*pi/2**x)]]) def test_quantum_fourier(): assert QFT(0, 3).decompose() == \ SwapGate(0, 2)*HadamardGate(0)*CGate((0,), PhaseGate(1)) * \ HadamardGate(1)*CGate((0,), TGate(2))*CGate((1,), PhaseGate(2)) * \ HadamardGate(2) assert IQFT(0, 3).decompose() == \ HadamardGate(2)*CGate((1,), RkGate(2, -2))*CGate((0,), RkGate(2, -3)) * \ HadamardGate(1)*CGate((0,), RkGate(1, -2))*HadamardGate(0)*SwapGate(0, 2) assert represent(QFT(0, 3), nqubits=3) == \ Matrix([[exp(2*pi*I/8)**(i*j % 8)/sqrt(8) for i in range(8)] for j in range(8)]) assert QFT(0, 4).decompose() # non-trivial decomposition assert qapply(QFT(0, 3).decompose()*Qubit(0, 0, 0)).expand() == qapply( HadamardGate(0)*HadamardGate(1)*HadamardGate(2)*Qubit(0, 0, 0) ).expand() def test_qft_represent(): c = QFT(0, 3) a = represent(c, nqubits=3) b = represent(c.decompose(), nqubits=3) assert a.evalf(prec=10) == b.evalf(prec=10)
1,732
35.104167
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_qapply.py
from sympy import I, Integer, sqrt, symbols from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.gate import H from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.spin import Jx, Jy, Jz, Jplus, Jminus, J2, JzKet from sympy.physics.quantum.state import Ket from sympy.physics.quantum.density import Density from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.boson import BosonOp, BosonFockKet, BosonFockBra from sympy.physics.quantum.tensorproduct import TensorProduct j, jp, m, mp = symbols("j j' m m'") z = JzKet(1, 0) po = JzKet(1, 1) mo = JzKet(1, -1) A = Operator('A') class Foo(Operator): def _apply_operator_JzKet(self, ket, **options): return ket def test_basic(): assert qapply(Jz*po) == hbar*po assert qapply(Jx*z) == hbar*po/sqrt(2) + hbar*mo/sqrt(2) assert qapply((Jplus + Jminus)*z/sqrt(2)) == hbar*po + hbar*mo assert qapply(Jz*(po + mo)) == hbar*po - hbar*mo assert qapply(Jz*po + Jz*mo) == hbar*po - hbar*mo assert qapply(Jminus*Jminus*po) == 2*hbar**2*mo assert qapply(Jplus**2*mo) == 2*hbar**2*po assert qapply(Jplus**2*Jminus**2*po) == 4*hbar**4*po def test_extra(): extra = z.dual*A*z assert qapply(Jz*po*extra) == hbar*po*extra assert qapply(Jx*z*extra) == (hbar*po/sqrt(2) + hbar*mo/sqrt(2))*extra assert qapply( (Jplus + Jminus)*z/sqrt(2)*extra) == hbar*po*extra + hbar*mo*extra assert qapply(Jz*(po + mo)*extra) == hbar*po*extra - hbar*mo*extra assert qapply(Jz*po*extra + Jz*mo*extra) == hbar*po*extra - hbar*mo*extra assert qapply(Jminus*Jminus*po*extra) == 2*hbar**2*mo*extra assert qapply(Jplus**2*mo*extra) == 2*hbar**2*po*extra assert qapply(Jplus**2*Jminus**2*po*extra) == 4*hbar**4*po*extra def test_innerproduct(): assert qapply(po.dual*Jz*po, ip_doit=False) == hbar*(po.dual*po) assert qapply(po.dual*Jz*po) == hbar def test_zero(): assert qapply(0) == 0 assert qapply(Integer(0)) == 0 def test_commutator(): assert qapply(Commutator(Jx, Jy)*Jz*po) == I*hbar**3*po assert qapply(Commutator(J2, Jz)*Jz*po) == 0 assert qapply(Commutator(Jz, Foo('F'))*po) == 0 assert qapply(Commutator(Foo('F'), Jz)*po) == 0 def test_anticommutator(): assert qapply(AntiCommutator(Jz, Foo('F'))*po) == 2*hbar*po assert qapply(AntiCommutator(Foo('F'), Jz)*po) == 2*hbar*po def test_outerproduct(): e = Jz*(mo*po.dual)*Jz*po assert qapply(e) == -hbar**2*mo assert qapply(e, ip_doit=False) == -hbar**2*(po.dual*po)*mo assert qapply(e).doit() == -hbar**2*mo def test_tensorproduct(): a = BosonOp("a") b = BosonOp("b") ket1 = TensorProduct(BosonFockKet(1), BosonFockKet(2)) ket2 = TensorProduct(BosonFockKet(0), BosonFockKet(0)) ket3 = TensorProduct(BosonFockKet(0), BosonFockKet(2)) bra1 = TensorProduct(BosonFockBra(0), BosonFockBra(0)) bra2 = TensorProduct(BosonFockBra(1), BosonFockBra(2)) assert qapply(TensorProduct(a, b ** 2) * ket1) == sqrt(2) * ket2 assert qapply(TensorProduct(a, Dagger(b) * b) * ket1) == 2 * ket3 assert qapply(bra1 * TensorProduct(a, b * b), dagger=True) == sqrt(2) * bra2 assert qapply(bra2 * ket1).doit() == TensorProduct(1, 1) assert qapply(TensorProduct(a, b * b) * ket1) == sqrt(2) * ket2 assert qapply(Dagger(TensorProduct(a, b * b) * ket1), dagger=True) == sqrt(2) * Dagger(ket2) def test_dagger(): lhs = Dagger(Qubit(0))*Dagger(H(0)) rhs = Dagger(Qubit(1))/sqrt(2) + Dagger(Qubit(0))/sqrt(2) assert qapply(lhs, dagger=True) == rhs def test_issue_6073(): x, y = symbols('x y', commutative=False) A = Ket(x, y) B = Operator('B') assert qapply(A) == A assert qapply(A.dual*B) == A.dual*B def test_density(): d = Density([Jz*mo, 0.5], [Jz*po, 0.5]) assert qapply(d) == Density([-hbar*mo, 0.5], [hbar*po, 0.5])
4,141
33.516667
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_qubit.py
import random from sympy import Integer, Matrix, Rational, sqrt, symbols from sympy.core.compatibility import range from sympy.physics.quantum.qubit import (measure_all, measure_partial, matrix_to_qubit, matrix_to_density, qubit_to_matrix, IntQubit, IntQubitBra, QubitBra) from sympy.physics.quantum.gate import (HadamardGate, CNOT, XGate, YGate, ZGate, PhaseGate) from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.represent import represent from sympy.physics.quantum.shor import Qubit from sympy.utilities.pytest import raises from sympy.physics.quantum.density import Density from sympy.core.trace import Tr x, y = symbols('x,y') epsilon = .000001 def test_Qubit(): array = [0, 0, 1, 1, 0] qb = Qubit('00110') assert qb.flip(0) == Qubit('00111') assert qb.flip(1) == Qubit('00100') assert qb.flip(4) == Qubit('10110') assert qb.qubit_values == (0, 0, 1, 1, 0) assert qb.dimension == 5 for i in range(5): assert qb[i] == array[4 - i] assert len(qb) == 5 qb = Qubit('110') def test_QubitBra(): qb = Qubit(0) qb_bra = QubitBra(0) assert qb.dual_class() == QubitBra assert qb_bra.dual_class() == Qubit qb = Qubit(1, 1, 0) qb_bra = QubitBra(1, 1, 0) assert represent(qb, nqubits=3).H == represent(qb_bra, nqubits=3) qb = Qubit(0, 1) qb_bra = QubitBra(1,0) assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(0) qb_bra = QubitBra(0, 1) assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(1) def test_IntQubit(): iqb = IntQubit(8) assert iqb.as_int() == 8 assert iqb.qubit_values == (1, 0, 0, 0) iqb = IntQubit(7, 4) assert iqb.qubit_values == (0, 1, 1, 1) assert IntQubit(3) == IntQubit(3, 2) #test Dual Classes iqb = IntQubit(3) iqb_bra = IntQubitBra(3) assert iqb.dual_class() == IntQubitBra assert iqb_bra.dual_class() == IntQubit iqb = IntQubit(5) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1) iqb = IntQubit(4) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0) raises(ValueError, lambda: IntQubit(4, 1)) def test_superposition_of_states(): state = 1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10') state_gate = CNOT(0, 1)*HadamardGate(0)*state state_expanded = Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2 assert qapply(state_gate).expand() == state_expanded assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded #test apply methods def test_apply_represent_equality(): gates = [HadamardGate(int(3*random.random())), XGate(int(3*random.random())), ZGate(int(3*random.random())), YGate(int(3*random.random())), ZGate(int(3*random.random())), PhaseGate(int(3*random.random()))] circuit = Qubit(int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2)) for i in range(int(random.random()*6)): circuit = gates[int(random.random()*6)]*circuit mat = represent(circuit, nqubits=6) states = qapply(circuit) state_rep = matrix_to_qubit(mat) states = states.expand() state_rep = state_rep.expand() assert state_rep == states def test_matrix_to_qubits(): qb = Qubit(0, 0, 0, 0) mat = Matrix([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert matrix_to_qubit(mat) == qb assert qubit_to_matrix(qb) == mat state = 2*sqrt(2)*(Qubit(0, 0, 0) + Qubit(0, 0, 1) + Qubit(0, 1, 0) + Qubit(0, 1, 1) + Qubit(1, 0, 0) + Qubit(1, 0, 1) + Qubit(1, 1, 0) + Qubit(1, 1, 1)) ones = sqrt(2)*2*Matrix([1, 1, 1, 1, 1, 1, 1, 1]) assert matrix_to_qubit(ones) == state.expand() assert qubit_to_matrix(state) == ones def test_measure_normalize(): a, b = symbols('a b') state = a*Qubit('110') + b*Qubit('111') assert measure_partial(state, (0,), normalize=False) == \ [(a*Qubit('110'), a*a.conjugate()), (b*Qubit('111'), b*b.conjugate())] assert measure_all(state, normalize=False) == \ [(Qubit('110'), a*a.conjugate()), (Qubit('111'), b*b.conjugate())] def test_measure_partial(): #Basic test of collapse of entangled two qubits (Bell States) state = Qubit('01') + Qubit('10') assert measure_partial(state, (0,)) == \ [(Qubit('10'), Rational(1, 2)), (Qubit('01'), Rational(1, 2))] assert measure_partial(state, (0,)) == \ measure_partial(state, (1,))[::-1] #Test of more complex collapse and probability calculation state1 = sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111') assert measure_partial(state1, (0,)) == \ [(sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111'), 1)] assert measure_partial(state1, (1, 2)) == measure_partial(state1, (3, 4)) assert measure_partial(state1, (1, 2, 3)) == \ [(Qubit('00001'), Rational(2, 3)), (Qubit('11111'), Rational(1, 3))] #test of measuring multiple bits at once state2 = Qubit('1111') + Qubit('1101') + Qubit('1011') + Qubit('1000') assert measure_partial(state2, (0, 1, 3)) == \ [(Qubit('1000'), Rational(1, 4)), (Qubit('1101'), Rational(1, 4)), (Qubit('1011')/sqrt(2) + Qubit('1111')/sqrt(2), Rational(1, 2))] assert measure_partial(state2, (0,)) == \ [(Qubit('1000'), Rational(1, 4)), (Qubit('1111')/sqrt(3) + Qubit('1101')/sqrt(3) + Qubit('1011')/sqrt(3), Rational(3, 4))] def test_measure_all(): assert measure_all(Qubit('11')) == [(Qubit('11'), 1)] state = Qubit('11') + Qubit('10') assert measure_all(state) == [(Qubit('10'), Rational(1, 2)), (Qubit('11'), Rational(1, 2))] state2 = Qubit('11')/sqrt(5) + 2*Qubit('00')/sqrt(5) assert measure_all(state2) == \ [(Qubit('00'), Rational(4, 5)), (Qubit('11'), Rational(1, 5))] def test_eval_trace(): q1 = Qubit('10110') q2 = Qubit('01010') d = Density([q1, 0.6], [q2, 0.4]) t = Tr(d) assert t.doit() == 1 # extreme bits t = Tr(d, 0) assert t.doit() == (0.4*Density([Qubit('0101'), 1]) + 0.6*Density([Qubit('1011'), 1])) t = Tr(d, 4) assert t.doit() == (0.4*Density([Qubit('1010'), 1]) + 0.6*Density([Qubit('0110'), 1])) # index somewhere in between t = Tr(d, 2) assert t.doit() == (0.4*Density([Qubit('0110'), 1]) + 0.6*Density([Qubit('1010'), 1])) #trace all indices t = Tr(d, [0, 1, 2, 3, 4]) assert t.doit() == 1 # trace some indices, initialized in # non-canonical order t = Tr(d, [2, 1, 3]) assert t.doit() == (0.4*Density([Qubit('00'), 1]) + 0.6*Density([Qubit('10'), 1])) # mixed states q = (1/sqrt(2)) * (Qubit('00') + Qubit('11')) d = Density( [q, 1.0] ) t = Tr(d, 0) assert t.doit() == (0.5*Density([Qubit('0'), 1]) + 0.5*Density([Qubit('1'), 1])) def test_matrix_to_density(): mat = Matrix([[0, 0], [0, 1]]) assert matrix_to_density(mat) == Density([Qubit('1'), 1]) mat = Matrix([[1, 0], [0, 0]]) assert matrix_to_density(mat) == Density([Qubit('0'), 1]) mat = Matrix([[0, 0], [0, 0]]) assert matrix_to_density(mat) == 0 mat = Matrix([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]) assert matrix_to_density(mat) == Density([Qubit('10'), 1]) mat = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) assert matrix_to_density(mat) == Density([Qubit('00'), 1])
7,934
33.650655
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_hilbert.py
from sympy.physics.quantum.hilbert import ( HilbertSpace, ComplexSpace, L2, FockSpace, TensorProductHilbertSpace, DirectSumHilbertSpace, TensorPowerHilbertSpace ) from sympy import Interval, oo, Symbol, sstr, srepr def test_hilbert_space(): hs = HilbertSpace() assert isinstance(hs, HilbertSpace) assert sstr(hs) == 'H' assert srepr(hs) == 'HilbertSpace()' def test_complex_space(): c1 = ComplexSpace(2) assert isinstance(c1, ComplexSpace) assert c1.dimension == 2 assert sstr(c1) == 'C(2)' assert srepr(c1) == 'ComplexSpace(Integer(2))' n = Symbol('n') c2 = ComplexSpace(n) assert isinstance(c2, ComplexSpace) assert c2.dimension == n assert sstr(c2) == 'C(n)' assert srepr(c2) == "ComplexSpace(Symbol('n'))" assert c2.subs(n, 2) == ComplexSpace(2) def test_L2(): b1 = L2(Interval(-oo, 1)) assert isinstance(b1, L2) assert b1.dimension == oo assert b1.interval == Interval(-oo, 1) x = Symbol('x', real=True) y = Symbol('y', real=True) b2 = L2(Interval(x, y)) assert b2.dimension == oo assert b2.interval == Interval(x, y) assert b2.subs(x, -1) == L2(Interval(-1, y)) def test_fock_space(): f1 = FockSpace() f2 = FockSpace() assert isinstance(f1, FockSpace) assert f1.dimension == oo assert f1 == f2 def test_tensor_product(): n = Symbol('n') hs1 = ComplexSpace(2) hs2 = ComplexSpace(n) h = hs1*hs2 assert isinstance(h, TensorProductHilbertSpace) assert h.dimension == 2*n assert h.spaces == (hs1, hs2) h = hs2*hs2 assert isinstance(h, TensorPowerHilbertSpace) assert h.base == hs2 assert h.exp == 2 assert h.dimension == n**2 f = FockSpace() h = hs1*hs2*f assert h.dimension == oo def test_tensor_power(): n = Symbol('n') hs1 = ComplexSpace(2) hs2 = ComplexSpace(n) h = hs1**2 assert isinstance(h, TensorPowerHilbertSpace) assert h.base == hs1 assert h.exp == 2 assert h.dimension == 4 h = hs2**3 assert isinstance(h, TensorPowerHilbertSpace) assert h.base == hs2 assert h.exp == 3 assert h.dimension == n**3 def test_direct_sum(): n = Symbol('n') hs1 = ComplexSpace(2) hs2 = ComplexSpace(n) h = hs1 + hs2 assert isinstance(h, DirectSumHilbertSpace) assert h.dimension == 2 + n assert h.spaces == (hs1, hs2) f = FockSpace() h = hs1 + f + hs2 assert h.dimension == oo assert h.spaces == (hs1, f, hs2)
2,513
22.495327
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_dagger.py
from sympy import I, Matrix, symbols, conjugate, Expr, Integer from sympy.physics.quantum.dagger import adjoint, Dagger from sympy.external import import_module from sympy.utilities.pytest import skip def test_scalars(): x = symbols('x', complex=True) assert Dagger(x) == conjugate(x) assert Dagger(I*x) == -I*conjugate(x) i = symbols('i', real=True) assert Dagger(i) == i p = symbols('p') assert isinstance(Dagger(p), adjoint) i = Integer(3) assert Dagger(i) == i A = symbols('A', commutative=False) assert Dagger(A).is_commutative is False def test_matrix(): x = symbols('x') m = Matrix([[I, x*I], [2, 4]]) assert Dagger(m) == m.H class Foo(Expr): def _eval_adjoint(self): return I def test_eval_adjoint(): f = Foo() d = Dagger(f) assert d == I np = import_module('numpy') def test_numpy_dagger(): if not np: skip("numpy not installed.") a = np.matrix([[1.0, 2.0j], [-1.0j, 2.0]]) adag = a.copy().transpose().conjugate() assert (Dagger(a) == adag).all() scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) def test_scipy_sparse_dagger(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") else: sparse = scipy.sparse a = sparse.csr_matrix([[1.0 + 0.0j, 2.0j], [-1.0j, 2.0 + 0.0j]]) adag = a.copy().transpose().conjugate() assert np.linalg.norm((Dagger(a) - adag).todense()) == 0.0
1,512
20.927536
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_printing.py
# -*- encoding: utf-8 -*- """ TODO: * Address Issue 2251, printing of spin states """ from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2 from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.qubit import Qubit, IntQubit from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.sho1d import RaisingOp from sympy import Derivative, Function, Interval, Matrix, Pow, S, symbols, Symbol, oo from sympy.core.compatibility import exec_ from sympy.utilities.pytest import XFAIL # Imports used in srepr strings from sympy.physics.quantum.constants import HBar from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, TensorProductHilbertSpace, TensorPowerHilbertSpace from sympy.physics.quantum.spin import JzOp, J2Op from sympy import Add, Integer, Mul, Rational, Tuple from sympy.printing import srepr from sympy.printing.pretty import pretty as xpretty from sympy.printing.latex import latex from sympy.core.compatibility import u_decode as u MutableDenseMatrix = Matrix ENV = {} exec_("from sympy import *", ENV) def sT(expr, string): """ sT := sreprTest from sympy/printing/tests/test_repr.py """ assert srepr(expr) == string assert eval(string) == expr def pretty(expr): """ASCII pretty-printing""" return xpretty(expr, use_unicode=False, wrap_line=False) def upretty(expr): """Unicode pretty-printing""" return xpretty(expr, use_unicode=True, wrap_line=False) def test_anticommutator(): A = Operator('A') B = Operator('B') ac = AntiCommutator(A, B) ac_tall = AntiCommutator(A**2, B) assert str(ac) == '{A,B}' assert pretty(ac) == '{A,B}' assert upretty(ac) == u'{A,B}' assert latex(ac) == r'\left\{A,B\right\}' sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(ac_tall) == '{A**2,B}' ascii_str = \ """\ / 2 \\\n\ <A ,B>\n\ \\ /\ """ ucode_str = \ u("""\ ⎧ 2 ⎫\n\ ⎨A ,B⎬\n\ ⎩ ⎭\ """) assert pretty(ac_tall) == ascii_str assert upretty(ac_tall) == ucode_str assert latex(ac_tall) == r'\left\{A^{2},B\right\}' sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))") def test_cg(): cg = CG(1, 2, 3, 4, 5, 6) wigner3j = Wigner3j(1, 2, 3, 4, 5, 6) wigner6j = Wigner6j(1, 2, 3, 4, 5, 6) wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9) assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ 5,6 \n\ C \n\ 1,2,3,4\ """ ucode_str = \ u("""\ 5,6 \n\ C \n\ 1,2,3,4\ """) assert pretty(cg) == ascii_str assert upretty(cg) == ucode_str assert latex(cg) == r'C^{5,6}_{1,2,3,4}' sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ /1 3 5\\\n\ | |\n\ \\2 4 6/\ """ ucode_str = \ u("""\ ⎛1 3 5⎞\n\ ⎜ ⎟\n\ ⎝2 4 6⎠\ """) assert pretty(wigner3j) == ascii_str assert upretty(wigner3j) == ucode_str assert latex(wigner3j) == \ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)' sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ /1 2 3\\\n\ < >\n\ \\4 5 6/\ """ ucode_str = \ u("""\ ⎧1 2 3⎫\n\ ⎨ ⎬\n\ ⎩4 5 6⎭\ """) assert pretty(wigner6j) == ascii_str assert upretty(wigner6j) == ucode_str assert latex(wigner6j) == \ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}' sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)' ascii_str = \ """\ /1 2 3\\\n\ | |\n\ <4 5 6>\n\ | |\n\ \\7 8 9/\ """ ucode_str = \ u("""\ ⎧1 2 3⎫\n\ ⎪ ⎪\n\ ⎨4 5 6⎬\n\ ⎪ ⎪\n\ ⎩7 8 9⎭\ """) assert pretty(wigner9j) == ascii_str assert upretty(wigner9j) == ucode_str assert latex(wigner9j) == \ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}' sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))") def test_commutator(): A = Operator('A') B = Operator('B') c = Commutator(A, B) c_tall = Commutator(A**2, B) assert str(c) == '[A,B]' assert pretty(c) == '[A,B]' assert upretty(c) == u'[A,B]' assert latex(c) == r'\left[A,B\right]' sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))") assert str(c_tall) == '[A**2,B]' ascii_str = \ """\ [ 2 ]\n\ [A ,B]\ """ ucode_str = \ u("""\ ⎡ 2 ⎤\n\ ⎣A ,B⎦\ """) assert pretty(c_tall) == ascii_str assert upretty(c_tall) == ucode_str assert latex(c_tall) == r'\left[A^{2},B\right]' sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))") def test_constants(): assert str(hbar) == 'hbar' assert pretty(hbar) == 'hbar' assert upretty(hbar) == u'ℏ' assert latex(hbar) == r'\hbar' sT(hbar, "HBar()") def test_dagger(): x = symbols('x') expr = Dagger(x) assert str(expr) == 'Dagger(x)' ascii_str = \ """\ +\n\ x \ """ ucode_str = \ u("""\ †\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert latex(expr) == r'x^{\dag}' sT(expr, "Dagger(Symbol('x'))") @XFAIL def test_gate_failing(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) g = UGate((0,), uMat) assert str(g) == 'U(0)' def test_gate(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) q = Qubit(1, 0, 1, 0, 1) g1 = IdentityGate(2) g2 = CGate((3, 0), XGate(1)) g3 = CNotGate(1, 0) g4 = UGate((0,), uMat) assert str(g1) == '1(2)' assert pretty(g1) == '1 \n 2' assert upretty(g1) == u'1 \n 2' assert latex(g1) == r'1_{2}' sT(g1, "IdentityGate(Integer(2))") assert str(g1*q) == '1(2)*|10101>' ascii_str = \ """\ 1 *|10101>\n\ 2 \ """ ucode_str = \ u("""\ 1 ⋅❘10101⟩\n\ 2 \ """) assert pretty(g1*q) == ascii_str assert upretty(g1*q) == ucode_str assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }' sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))") assert str(g2) == 'C((3,0),X(1))' ascii_str = \ """\ C /X \\\n\ 3,0\\ 1/\ """ ucode_str = \ u("""\ C ⎛X ⎞\n\ 3,0⎝ 1⎠\ """) assert pretty(g2) == ascii_str assert upretty(g2) == ucode_str assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}' sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))") assert str(g3) == 'CNOT(1,0)' ascii_str = \ """\ CNOT \n\ 1,0\ """ ucode_str = \ u("""\ CNOT \n\ 1,0\ """) assert pretty(g3) == ascii_str assert upretty(g3) == ucode_str assert latex(g3) == r'CNOT_{1,0}' sT(g3, "CNotGate(Integer(1),Integer(0))") ascii_str = \ """\ U \n\ 0\ """ ucode_str = \ u("""\ U \n\ 0\ """) assert str(g4) == \ """\ U((0,),Matrix([\n\ [a, b],\n\ [c, d]]))\ """ assert pretty(g4) == ascii_str assert upretty(g4) == ucode_str assert latex(g4) == r'U_{0}' sT(g4, "UGate(Tuple(Integer(0)),MutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))") def test_hilbert(): h1 = HilbertSpace() h2 = ComplexSpace(2) h3 = FockSpace() h4 = L2(Interval(0, oo)) assert str(h1) == 'H' assert pretty(h1) == 'H' assert upretty(h1) == u'H' assert latex(h1) == r'\mathcal{H}' sT(h1, "HilbertSpace()") assert str(h2) == 'C(2)' ascii_str = \ """\ 2\n\ C \ """ ucode_str = \ u("""\ 2\n\ C \ """) assert pretty(h2) == ascii_str assert upretty(h2) == ucode_str assert latex(h2) == r'\mathcal{C}^{2}' sT(h2, "ComplexSpace(Integer(2))") assert str(h3) == 'F' assert pretty(h3) == 'F' assert upretty(h3) == u'F' assert latex(h3) == r'\mathcal{F}' sT(h3, "FockSpace()") assert str(h4) == 'L2(Interval(0, oo))' ascii_str = \ """\ 2\n\ L \ """ ucode_str = \ u("""\ 2\n\ L \ """) assert pretty(h4) == ascii_str assert upretty(h4) == ucode_str assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)' sT(h4, "L2(Interval(Integer(0), oo, S.false, S.true))") assert str(h1 + h2) == 'H+C(2)' ascii_str = \ """\ 2\n\ H + C \ """ ucode_str = \ u("""\ 2\n\ H ⊕ C \ """) assert pretty(h1 + h2) == ascii_str assert upretty(h1 + h2) == ucode_str assert latex(h1 + h2) sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))") assert str(h1*h2) == "H*C(2)" ascii_str = \ """\ 2\n\ H x C \ """ ucode_str = \ u("""\ 2\n\ H ⨂ C \ """) assert pretty(h1*h2) == ascii_str assert upretty(h1*h2) == ucode_str assert latex(h1*h2) sT(h1*h2, "TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))") assert str(h1**2) == 'H**2' ascii_str = \ """\ x2\n\ H \ """ ucode_str = \ u("""\ ⨂2\n\ H \ """) assert pretty(h1**2) == ascii_str assert upretty(h1**2) == ucode_str assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}' sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))") def test_innerproduct(): x = symbols('x') ip1 = InnerProduct(Bra(), Ket()) ip2 = InnerProduct(TimeDepBra(), TimeDepKet()) ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1)) ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1))) ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2)) ip_tall2 = InnerProduct(Bra(x), Ket(x/2)) ip_tall3 = InnerProduct(Bra(x/2), Ket(x)) assert str(ip1) == '<psi|psi>' assert pretty(ip1) == '<psi|psi>' assert upretty(ip1) == u'⟨ψ❘ψ⟩' assert latex( ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }' sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))") assert str(ip2) == '<psi;t|psi;t>' assert pretty(ip2) == '<psi;t|psi;t>' assert upretty(ip2) == u'⟨ψ;t❘ψ;t⟩' assert latex(ip2) == \ r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }' sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))") assert str(ip3) == "<1,1|1,1>" assert pretty(ip3) == '<1,1|1,1>' assert upretty(ip3) == u'⟨1,1❘1,1⟩' assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }' sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))") assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>" assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>' assert upretty(ip4) == u'⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩' assert latex(ip4) == \ r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }' sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))") assert str(ip_tall1) == '<x/2|x/2>' ascii_str = \ """\ / | \\ \n\ / x|x \\\n\ \\ -|- /\n\ \\2|2/ \ """ ucode_str = \ u("""\ ╱ │ ╲ \n\ ╱ x│x ╲\n\ ╲ ─│─ ╱\n\ ╲2│2╱ \ """) assert pretty(ip_tall1) == ascii_str assert upretty(ip_tall1) == ucode_str assert latex(ip_tall1) == \ r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }' sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))") assert str(ip_tall2) == '<x|x/2>' ascii_str = \ """\ / | \\ \n\ / |x \\\n\ \\ x|- /\n\ \\ |2/ \ """ ucode_str = \ u("""\ ╱ │ ╲ \n\ ╱ │x ╲\n\ ╲ x│─ ╱\n\ ╲ │2╱ \ """) assert pretty(ip_tall2) == ascii_str assert upretty(ip_tall2) == ucode_str assert latex(ip_tall2) == \ r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }' sT(ip_tall2, "InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))") assert str(ip_tall3) == '<x/2|x>' ascii_str = \ """\ / | \\ \n\ / x| \\\n\ \\ -|x /\n\ \\2| / \ """ ucode_str = \ u("""\ ╱ │ ╲ \n\ ╱ x│ ╲\n\ ╲ ─│x ╱\n\ ╲2│ ╱ \ """) assert pretty(ip_tall3) == ascii_str assert upretty(ip_tall3) == ucode_str assert latex(ip_tall3) == \ r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }' sT(ip_tall3, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))") def test_operator(): a = Operator('A') b = Operator('B', Symbol('t'), S(1)/2) inv = a.inv() f = Function('f') x = symbols('x') d = DifferentialOperator(Derivative(f(x), x), f(x)) op = OuterProduct(Ket(), Bra()) assert str(a) == 'A' assert pretty(a) == 'A' assert upretty(a) == u'A' assert latex(a) == 'A' sT(a, "Operator(Symbol('A'))") assert str(inv) == 'A**(-1)' ascii_str = \ """\ -1\n\ A \ """ ucode_str = \ u("""\ -1\n\ A \ """) assert pretty(inv) == ascii_str assert upretty(inv) == ucode_str assert latex(inv) == r'A^{-1}' sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))") assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))' ascii_str = \ """\ /d \\\n\ DifferentialOperator|--(f(x)),f(x)|\n\ \\dx /\ """ ucode_str = \ u("""\ ⎛d ⎞\n\ DifferentialOperator⎜──(f(x)),f(x)⎟\n\ ⎝dx ⎠\ """) assert pretty(d) == ascii_str assert upretty(d) == ucode_str assert latex(d) == \ r'DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)' sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))") assert str(b) == 'Operator(B,t,1/2)' assert pretty(b) == 'Operator(B,t,1/2)' assert upretty(b) == u'Operator(B,t,1/2)' assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)' sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))") assert str(op) == '|psi><psi|' assert pretty(op) == '|psi><psi|' assert upretty(op) == u'❘ψ⟩⟨ψ❘' assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}' sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))") def test_qexpr(): q = QExpr('q') assert str(q) == 'q' assert pretty(q) == 'q' assert upretty(q) == u'q' assert latex(q) == r'q' sT(q, "QExpr(Symbol('q'))") def test_qubit(): q1 = Qubit('0101') q2 = IntQubit(8) assert str(q1) == '|0101>' assert pretty(q1) == '|0101>' assert upretty(q1) == u'❘0101⟩' assert latex(q1) == r'{\left|0101\right\rangle }' sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))") assert str(q2) == '|8>' assert pretty(q2) == '|8>' assert upretty(q2) == u'❘8⟩' assert latex(q2) == r'{\left|8\right\rangle }' sT(q2, "IntQubit(8)") def test_spin(): lz = JzOp('L') ket = JzKet(1, 0) bra = JzBra(1, 0) cket = JzKetCoupled(1, 0, (1, 2)) cbra = JzBraCoupled(1, 0, (1, 2)) cket_big = JzKetCoupled(1, 0, (1, 2, 3)) cbra_big = JzBraCoupled(1, 0, (1, 2, 3)) rot = Rotation(1, 2, 3) bigd = WignerD(1, 2, 3, 4, 5, 6) smalld = WignerD(1, 2, 3, 0, 4, 0) assert str(lz) == 'Lz' ascii_str = \ """\ L \n\ z\ """ ucode_str = \ u("""\ L \n\ z\ """) assert pretty(lz) == ascii_str assert upretty(lz) == ucode_str assert latex(lz) == 'L_z' sT(lz, "JzOp(Symbol('L'))") assert str(J2) == 'J2' ascii_str = \ """\ 2\n\ J \ """ ucode_str = \ u("""\ 2\n\ J \ """) assert pretty(J2) == ascii_str assert upretty(J2) == ucode_str assert latex(J2) == r'J^2' sT(J2, "J2Op(Symbol('J'))") assert str(Jz) == 'Jz' ascii_str = \ """\ J \n\ z\ """ ucode_str = \ u("""\ J \n\ z\ """) assert pretty(Jz) == ascii_str assert upretty(Jz) == ucode_str assert latex(Jz) == 'J_z' sT(Jz, "JzOp(Symbol('J'))") assert str(ket) == '|1,0>' assert pretty(ket) == '|1,0>' assert upretty(ket) == u'❘1,0⟩' assert latex(ket) == r'{\left|1,0\right\rangle }' sT(ket, "JzKet(Integer(1),Integer(0))") assert str(bra) == '<1,0|' assert pretty(bra) == '<1,0|' assert upretty(bra) == u'⟨1,0❘' assert latex(bra) == r'{\left\langle 1,0\right|}' sT(bra, "JzBra(Integer(1),Integer(0))") assert str(cket) == '|1,0,j1=1,j2=2>' assert pretty(cket) == '|1,0,j1=1,j2=2>' assert upretty(cket) == u'❘1,0,j₁=1,j₂=2⟩' assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }' sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))") assert str(cbra) == '<1,0,j1=1,j2=2|' assert pretty(cbra) == '<1,0,j1=1,j2=2|' assert upretty(cbra) == u'⟨1,0,j₁=1,j₂=2❘' assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}' sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))") assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>' # TODO: Fix non-unicode pretty printing # i.e. j1,2 -> j(1,2) assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>' assert upretty(cket_big) == u'❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩' assert latex(cket_big) == \ r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }' sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))") assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|' assert pretty(cbra_big) == u'<1,0,j1=1,j2=2,j3=3,j1,2=3|' assert upretty(cbra_big) == u'⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘' assert latex(cbra_big) == \ r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}' sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))") assert str(rot) == 'R(1,2,3)' assert pretty(rot) == 'R (1,2,3)' assert upretty(rot) == u'ℛ (1,2,3)' assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)' sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))") assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)' ascii_str = \ """\ 1 \n\ D (4,5,6)\n\ 2,3 \ """ ucode_str = \ u("""\ 1 \n\ D (4,5,6)\n\ 2,3 \ """) assert pretty(bigd) == ascii_str assert upretty(bigd) == ucode_str assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)' sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))") assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)' ascii_str = \ """\ 1 \n\ d (4)\n\ 2,3 \ """ ucode_str = \ u("""\ 1 \n\ d (4)\n\ 2,3 \ """) assert pretty(smalld) == ascii_str assert upretty(smalld) == ucode_str assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)' sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))") def test_state(): x = symbols('x') bra = Bra() ket = Ket() bra_tall = Bra(x/2) ket_tall = Ket(x/2) tbra = TimeDepBra() tket = TimeDepKet() assert str(bra) == '<psi|' assert pretty(bra) == '<psi|' assert upretty(bra) == u'⟨ψ❘' assert latex(bra) == r'{\left\langle \psi\right|}' sT(bra, "Bra(Symbol('psi'))") assert str(ket) == '|psi>' assert pretty(ket) == '|psi>' assert upretty(ket) == u'❘ψ⟩' assert latex(ket) == r'{\left|\psi\right\rangle }' sT(ket, "Ket(Symbol('psi'))") assert str(bra_tall) == '<x/2|' ascii_str = \ """\ / |\n\ / x|\n\ \\ -|\n\ \\2|\ """ ucode_str = \ u("""\ ╱ │\n\ ╱ x│\n\ ╲ ─│\n\ ╲2│\ """) assert pretty(bra_tall) == ascii_str assert upretty(bra_tall) == ucode_str assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}' sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))") assert str(ket_tall) == '|x/2>' ascii_str = \ """\ | \\ \n\ |x \\\n\ |- /\n\ |2/ \ """ ucode_str = \ u("""\ │ ╲ \n\ │x ╲\n\ │─ ╱\n\ │2╱ \ """) assert pretty(ket_tall) == ascii_str assert upretty(ket_tall) == ucode_str assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }' sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))") assert str(tbra) == '<psi;t|' assert pretty(tbra) == u'<psi;t|' assert upretty(tbra) == u'⟨ψ;t❘' assert latex(tbra) == r'{\left\langle \psi;t\right|}' sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))") assert str(tket) == '|psi;t>' assert pretty(tket) == '|psi;t>' assert upretty(tket) == u'❘ψ;t⟩' assert latex(tket) == r'{\left|\psi;t\right\rangle }' sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))") def test_tensorproduct(): tp = TensorProduct(JzKet(1, 1), JzKet(1, 0)) assert str(tp) == '|1,1>x|1,0>' assert pretty(tp) == '|1,1>x |1,0>' assert upretty(tp) == u'❘1,1⟩⨂ ❘1,0⟩' assert latex(tp) == \ r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}' sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))") def test_big_expr(): f = Function('f') x = symbols('x') e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1)) e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2)) e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1))) e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval( 0, oo)) + HilbertSpace()) assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)' ascii_str = \ """\ / 3 \\ \n\ |/ +\\ | \n\ 2 / + +\\ <| /d \\ | + +> \n\ /J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\ \\ z/ \\\\ \\dx / / / \ """ ucode_str = \ u("""\ ⎧ 3 ⎫ \n\ ⎪⎛ †⎞ ⎪ \n\ 2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\ ⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\ ⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \ """) assert pretty(e1) == ascii_str assert upretty(e1) == ucode_str assert latex(e1) == \ r'{J_z^{2}}\otimes \left({A^{\dag} + B^{\dag}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left (x \right )},f{\left (x \right )}\right)^{\dag}\right)^{3},A^{\dag} + B^{\dag}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)' sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Symbol('x')),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))") assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]' ascii_str = \ """\ [ 2 ] / -2 + +\\ [ 2 ]\n\ [/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\ [\\ z/ ] \\ / [ z]\ """ ucode_str = \ u("""\ ⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\ ⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\ ⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\ """) assert pretty(e2) == ascii_str assert upretty(e2) == ucode_str assert latex(e2) == \ r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dag} C^{\dag}\right\} \left[J^2,J_z\right]' sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))") assert str(e3) == \ "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>" ascii_str = \ """\ [ + ] / 2 \\ \n\ /1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\ | | \\ z/ \n\ \\2 4 6/ \ """ ucode_str = \ u("""\ ⎡ † ⎤ ⎛ 2 ⎞ \n\ ⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\ ⎜ ⎟ ⎝ z⎠ \n\ ⎝2 4 6⎠ \ """) assert pretty(e3) == ascii_str assert upretty(e3) == ucode_str assert latex(e3) == \ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dag} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}' sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))") assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)' ascii_str = \ """\ // 1 2\\ x2\\ / 2 \\\n\ \\\\C x C / + F / x \\L + H/\ """ ucode_str = \ u("""\ ⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\ ⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\ """) assert pretty(e4) == ascii_str assert upretty(e4) == ucode_str assert latex(e4) == \ r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)' sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, S.false, S.true)),HilbertSpace())))") def _test_sho1d(): ad = RaisingOp('a') assert pretty(ad) == u' \N{DAGGER}\na ' assert latex(ad) == 'a^{\\dag}'
29,280
31.974099
738
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_commutator.py
from sympy import symbols, Integer from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator as Comm from sympy.physics.quantum.operator import Operator a, b, c = symbols('a,b,c') A, B, C, D = symbols('A,B,C,D', commutative=False) def test_commutator(): c = Comm(A, B) assert c.is_commutative is False assert isinstance(c, Comm) assert c.subs(A, C) == Comm(C, B) def test_commutator_identities(): assert Comm(a*A, b*B) == a*b*Comm(A, B) assert Comm(A, A) == 0 assert Comm(a, b) == 0 assert Comm(A, B) == -Comm(B, A) assert Comm(A, B).doit() == A*B - B*A assert Comm(A, B*C).expand(commutator=True) == Comm(A, B)*C + B*Comm(A, C) assert Comm(A*B, C*D).expand(commutator=True) == \ A*C*Comm(B, D) + A*Comm(B, C)*D + C*Comm(A, D)*B + Comm(A, C)*D*B assert Comm(A + B, C + D).expand(commutator=True) == \ Comm(A, C) + Comm(A, D) + Comm(B, C) + Comm(B, D) assert Comm(A, B + C).expand(commutator=True) == Comm(A, B) + Comm(A, C) e = Comm(A, Comm(B, C)) + Comm(B, Comm(C, A)) + Comm(C, Comm(A, B)) assert e.doit().expand() == 0 def test_commutator_dagger(): comm = Comm(A*B, C) assert Dagger(comm).expand(commutator=True) == \ - Comm(Dagger(B), Dagger(C))*Dagger(A) - \ Dagger(B)*Comm(Dagger(A), Dagger(C)) class Foo(Operator): def _eval_commutator_Bar(self, bar): return Integer(0) class Bar(Operator): pass class Tam(Operator): def _eval_commutator_Foo(self, foo): return Integer(1) def test_eval_commutator(): F = Foo('F') B = Bar('B') T = Tam('T') assert Comm(F, B).doit() == 0 assert Comm(B, F).doit() == 0 assert Comm(F, T).doit() == -1 assert Comm(T, F).doit() == 1 assert Comm(B, T).doit() == B*T - T*B
1,830
26.328358
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_sho1d.py
"""Tests for sho1d.py""" from sympy import Integer, Symbol, sqrt, I, S from sympy.core.compatibility import range from sympy.physics.quantum import Dagger from sympy.physics.quantum.constants import hbar from sympy.physics.quantum import Commutator from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.cartesian import X, Px from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.represent import represent from sympy.external import import_module from sympy.utilities.pytest import skip from sympy.physics.quantum.sho1d import (RaisingOp, LoweringOp, SHOKet, SHOBra, Hamiltonian, NumberOp) ad = RaisingOp('a') a = LoweringOp('a') k = SHOKet('k') kz = SHOKet(0) kf = SHOKet(1) k3 = SHOKet(3) b = SHOBra('b') b3 = SHOBra(3) H = Hamiltonian('H') N = NumberOp('N') omega = Symbol('omega') m = Symbol('m') ndim = Integer(4) np = import_module('numpy') scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) ad_rep_sympy = represent(ad, basis=N, ndim=4, format='sympy') a_rep = represent(a, basis=N, ndim=4, format='sympy') N_rep = represent(N, basis=N, ndim=4, format='sympy') H_rep = represent(H, basis=N, ndim=4, format='sympy') k3_rep = represent(k3, basis=N, ndim=4, format='sympy') b3_rep = represent(b3, basis=N, ndim=4, format='sympy') def test_RaisingOp(): assert Dagger(ad) == a assert Commutator(ad, a).doit() == Integer(-1) assert Commutator(ad, N).doit() == Integer(-1)*ad assert qapply(ad*k) == (sqrt(k.n + 1)*SHOKet(k.n + 1)).expand() assert qapply(ad*kz) == (sqrt(kz.n + 1)*SHOKet(kz.n + 1)).expand() assert qapply(ad*kf) == (sqrt(kf.n + 1)*SHOKet(kf.n + 1)).expand() assert ad.rewrite('xp').doit() == \ (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*(Integer(-1)*I*Px + m*omega*X) assert ad.hilbert_space == ComplexSpace(S.Infinity) for i in range(ndim - 1): assert ad_rep_sympy[i + 1,i] == sqrt(i + 1) if not np: skip("numpy not installed.") ad_rep_numpy = represent(ad, basis=N, ndim=4, format='numpy') for i in range(ndim - 1): assert ad_rep_numpy[i + 1,i] == float(sqrt(i + 1)) if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") else: sparse = scipy.sparse ad_rep_scipy = represent(ad, basis=N, ndim=4, format='scipy.sparse', spmatrix='lil') for i in range(ndim - 1): assert ad_rep_scipy[i + 1,i] == float(sqrt(i + 1)) assert ad_rep_numpy.dtype == 'float64' assert ad_rep_scipy.dtype == 'float64' def test_LoweringOp(): assert Dagger(a) == ad assert Commutator(a, ad).doit() == Integer(1) assert Commutator(a, N).doit() == a assert qapply(a*k) == (sqrt(k.n)*SHOKet(k.n-Integer(1))).expand() assert qapply(a*kz) == Integer(0) assert qapply(a*kf) == (sqrt(kf.n)*SHOKet(kf.n-Integer(1))).expand() assert a.rewrite('xp').doit() == \ (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*(I*Px + m*omega*X) for i in range(ndim - 1): assert a_rep[i,i + 1] == sqrt(i + 1) def test_NumberOp(): assert Commutator(N, ad).doit() == ad assert Commutator(N, a).doit() == Integer(-1)*a assert Commutator(N, H).doit() == Integer(0) assert qapply(N*k) == (k.n*k).expand() assert N.rewrite('a').doit() == ad*a assert N.rewrite('xp').doit() == (Integer(1)/(Integer(2)*m*hbar*omega))*( Px**2 + (m*omega*X)**2) - Integer(1)/Integer(2) assert N.rewrite('H').doit() == H/(hbar*omega) - Integer(1)/Integer(2) for i in range(ndim): assert N_rep[i,i] == i assert N_rep == ad_rep_sympy*a_rep def test_Hamiltonian(): assert Commutator(H, N).doit() == Integer(0) assert qapply(H*k) == ((hbar*omega*(k.n + Integer(1)/Integer(2)))*k).expand() assert H.rewrite('a').doit() == hbar*omega*(ad*a + Integer(1)/Integer(2)) assert H.rewrite('xp').doit() == \ (Integer(1)/(Integer(2)*m))*(Px**2 + (m*omega*X)**2) assert H.rewrite('N').doit() == hbar*omega*(N + Integer(1)/Integer(2)) for i in range(ndim): assert H_rep[i,i] == hbar*omega*(i + Integer(1)/Integer(2)) def test_SHOKet(): assert SHOKet('k').dual_class() == SHOBra assert SHOBra('b').dual_class() == SHOKet assert InnerProduct(b,k).doit() == KroneckerDelta(k.n, b.n) assert k.hilbert_space == ComplexSpace(S.Infinity) assert k3_rep[k3.n, 0] == Integer(1) assert b3_rep[0, b3.n] == Integer(1)
4,644
37.38843
88
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_gate.py
from sympy import exp, symbols, sqrt, I, pi, Mul, Integer, Wild from sympy.core.compatibility import range from sympy.matrices import Matrix from sympy.physics.quantum.gate import (XGate, YGate, ZGate, random_circuit, CNOT, IdentityGate, H, X, Y, S, T, Z, SwapGate, gate_simp, gate_sort, CNotGate, TGate, HadamardGate, PhaseGate, UGate, CGate) from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.represent import represent from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qubit import Qubit, IntQubit, qubit_to_matrix, \ matrix_to_qubit from sympy.physics.quantum.matrixutils import matrix_to_zero from sympy.physics.quantum.matrixcache import sqrt2_inv from sympy.physics.quantum import Dagger def test_gate(): """Test a basic gate.""" h = HadamardGate(1) assert h.min_qubits == 2 assert h.nqubits == 1 i0 = Wild('i0') i1 = Wild('i1') h0_w1 = HadamardGate(i0) h0_w2 = HadamardGate(i0) h1_w1 = HadamardGate(i1) assert h0_w1 == h0_w2 assert h0_w1 != h1_w1 assert h1_w1 != h0_w2 cnot_10_w1 = CNOT(i1, i0) cnot_10_w2 = CNOT(i1, i0) cnot_01_w1 = CNOT(i0, i1) assert cnot_10_w1 == cnot_10_w2 assert cnot_10_w1 != cnot_01_w1 assert cnot_10_w2 != cnot_01_w1 def test_UGate(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) # Test basic case where gate exists in 1-qubit space u1 = UGate((0,), uMat) assert represent(u1, nqubits=1) == uMat assert qapply(u1*Qubit('0')) == a*Qubit('0') + c*Qubit('1') assert qapply(u1*Qubit('1')) == b*Qubit('0') + d*Qubit('1') # Test case where gate exists in a larger space u2 = UGate((1,), uMat) u2Rep = represent(u2, nqubits=2) for i in range(4): assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \ qubit_to_matrix(qapply(u2*IntQubit(i, 2))) def test_cgate(): """Test the general CGate.""" # Test single control functionality CNOTMatrix = Matrix( [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) assert represent(CGate(1, XGate(0)), nqubits=2) == CNOTMatrix # Test multiple control bit functionality ToffoliGate = CGate((1, 2), XGate(0)) assert represent(ToffoliGate, nqubits=3) == \ Matrix( [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) ToffoliGate = CGate((3, 0), XGate(1)) assert qapply(ToffoliGate*Qubit('1001')) == \ matrix_to_qubit(represent(ToffoliGate*Qubit('1001'), nqubits=4)) assert qapply(ToffoliGate*Qubit('0000')) == \ matrix_to_qubit(represent(ToffoliGate*Qubit('0000'), nqubits=4)) CYGate = CGate(1, YGate(0)) CYGate_matrix = Matrix( ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, -I), (0, 0, I, 0))) # Test 2 qubit controlled-Y gate decompose method. assert represent(CYGate.decompose(), nqubits=2) == CYGate_matrix CZGate = CGate(0, ZGate(1)) CZGate_matrix = Matrix( ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, -1))) assert qapply(CZGate*Qubit('11')) == -Qubit('11') assert matrix_to_qubit(represent(CZGate*Qubit('11'), nqubits=2)) == \ -Qubit('11') # Test 2 qubit controlled-Z gate decompose method. assert represent(CZGate.decompose(), nqubits=2) == CZGate_matrix CPhaseGate = CGate(0, PhaseGate(1)) assert qapply(CPhaseGate*Qubit('11')) == \ I*Qubit('11') assert matrix_to_qubit(represent(CPhaseGate*Qubit('11'), nqubits=2)) == \ I*Qubit('11') # Test that the dagger, inverse, and power of CGate is evaluated properly assert Dagger(CZGate) == CZGate assert pow(CZGate, 1) == Dagger(CZGate) assert Dagger(CZGate) == CZGate.inverse() assert Dagger(CPhaseGate) != CPhaseGate assert Dagger(CPhaseGate) == CPhaseGate.inverse() assert Dagger(CPhaseGate) == pow(CPhaseGate, -1) assert pow(CPhaseGate, -1) == CPhaseGate.inverse() def test_UGate_CGate_combo(): a, b, c, d = symbols('a,b,c,d') uMat = Matrix([[a, b], [c, d]]) cMat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, c, d]]) # Test basic case where gate exists in 1-qubit space. u1 = UGate((0,), uMat) cu1 = CGate(1, u1) assert represent(cu1, nqubits=2) == cMat assert qapply(cu1*Qubit('10')) == a*Qubit('10') + c*Qubit('11') assert qapply(cu1*Qubit('11')) == b*Qubit('10') + d*Qubit('11') assert qapply(cu1*Qubit('01')) == Qubit('01') assert qapply(cu1*Qubit('00')) == Qubit('00') # Test case where gate exists in a larger space. u2 = UGate((1,), uMat) u2Rep = represent(u2, nqubits=2) for i in range(4): assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \ qubit_to_matrix(qapply(u2*IntQubit(i, 2))) def test_represent_hadamard(): """Test the representation of the hadamard gate.""" circuit = HadamardGate(0)*Qubit('00') answer = represent(circuit, nqubits=2) # Check that the answers are same to within an epsilon. assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0]) def test_represent_xgate(): """Test the representation of the X gate.""" circuit = XGate(0)*Qubit('00') answer = represent(circuit, nqubits=2) assert Matrix([0, 1, 0, 0]) == answer def test_represent_ygate(): """Test the representation of the Y gate.""" circuit = YGate(0)*Qubit('00') answer = represent(circuit, nqubits=2) assert answer[0] == 0 and answer[1] == I and \ answer[2] == 0 and answer[3] == 0 def test_represent_zgate(): """Test the representation of the Z gate.""" circuit = ZGate(0)*Qubit('00') answer = represent(circuit, nqubits=2) assert Matrix([1, 0, 0, 0]) == answer def test_represent_phasegate(): """Test the representation of the S gate.""" circuit = PhaseGate(0)*Qubit('01') answer = represent(circuit, nqubits=2) assert Matrix([0, I, 0, 0]) == answer def test_represent_tgate(): """Test the representation of the T gate.""" circuit = TGate(0)*Qubit('01') assert Matrix([0, exp(I*pi/4), 0, 0]) == represent(circuit, nqubits=2) def test_compound_gates(): """Test a compound gate representation.""" circuit = YGate(0)*ZGate(0)*XGate(0)*HadamardGate(0)*Qubit('00') answer = represent(circuit, nqubits=2) assert Matrix([I/sqrt(2), I/sqrt(2), 0, 0]) == answer def test_cnot_gate(): """Test the CNOT gate.""" circuit = CNotGate(1, 0) assert represent(circuit, nqubits=2) == \ Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) circuit = circuit*Qubit('111') assert matrix_to_qubit(represent(circuit, nqubits=3)) == \ qapply(circuit) circuit = CNotGate(1, 0) assert Dagger(circuit) == circuit assert Dagger(Dagger(circuit)) == circuit assert circuit*circuit == 1 def test_gate_sort(): """Test gate_sort.""" for g in (X, Y, Z, H, S, T): assert gate_sort(g(2)*g(1)*g(0)) == g(0)*g(1)*g(2) e = gate_sort(X(1)*H(0)**2*CNOT(0, 1)*X(1)*X(0)) assert e == H(0)**2*CNOT(0, 1)*X(0)*X(1)**2 assert gate_sort(Z(0)*X(0)) == -X(0)*Z(0) assert gate_sort(Z(0)*X(0)**2) == X(0)**2*Z(0) assert gate_sort(Y(0)*H(0)) == -H(0)*Y(0) assert gate_sort(Y(0)*X(0)) == -X(0)*Y(0) assert gate_sort(Z(0)*Y(0)) == -Y(0)*Z(0) assert gate_sort(T(0)*S(0)) == S(0)*T(0) assert gate_sort(Z(0)*S(0)) == S(0)*Z(0) assert gate_sort(Z(0)*T(0)) == T(0)*Z(0) assert gate_sort(Z(0)*CNOT(0, 1)) == CNOT(0, 1)*Z(0) assert gate_sort(S(0)*CNOT(0, 1)) == CNOT(0, 1)*S(0) assert gate_sort(T(0)*CNOT(0, 1)) == CNOT(0, 1)*T(0) assert gate_sort(X(1)*CNOT(0, 1)) == CNOT(0, 1)*X(1) # This takes a long time and should only be uncommented once in a while. # nqubits = 5 # ngates = 10 # trials = 10 # for i in range(trials): # c = random_circuit(ngates, nqubits) # assert represent(c, nqubits=nqubits) == \ # represent(gate_sort(c), nqubits=nqubits) def test_gate_simp(): """Test gate_simp.""" e = H(0)*X(1)*H(0)**2*CNOT(0, 1)*X(1)**3*X(0)*Z(3)**2*S(4)**3 assert gate_simp(e) == H(0)*CNOT(0, 1)*S(4)*X(0)*Z(4) assert gate_simp(X(0)*X(0)) == 1 assert gate_simp(Y(0)*Y(0)) == 1 assert gate_simp(Z(0)*Z(0)) == 1 assert gate_simp(H(0)*H(0)) == 1 assert gate_simp(T(0)*T(0)) == S(0) assert gate_simp(S(0)*S(0)) == Z(0) assert gate_simp(Integer(1)) == Integer(1) assert gate_simp(X(0)**2 + Y(0)**2) == Integer(2) def test_swap_gate(): """Test the SWAP gate.""" swap_gate_matrix = Matrix( ((1, 0, 0, 0), (0, 0, 1, 0), (0, 1, 0, 0), (0, 0, 0, 1))) assert represent(SwapGate(1, 0).decompose(), nqubits=2) == swap_gate_matrix assert qapply(SwapGate(1, 3)*Qubit('0010')) == Qubit('1000') nqubits = 4 for i in range(nqubits): for j in range(i): assert represent(SwapGate(i, j), nqubits=nqubits) == \ represent(SwapGate(i, j).decompose(), nqubits=nqubits) def test_one_qubit_commutators(): """Test single qubit gate commutation relations.""" for g1 in (IdentityGate, X, Y, Z, H, T, S): for g2 in (IdentityGate, X, Y, Z, H, T, S): e = Commutator(g1(0), g2(0)) a = matrix_to_zero(represent(e, nqubits=1, format='sympy')) b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy')) assert a == b e = Commutator(g1(0), g2(1)) assert e.doit() == 0 def test_one_qubit_anticommutators(): """Test single qubit gate anticommutation relations.""" for g1 in (IdentityGate, X, Y, Z, H): for g2 in (IdentityGate, X, Y, Z, H): e = AntiCommutator(g1(0), g2(0)) a = matrix_to_zero(represent(e, nqubits=1, format='sympy')) b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy')) assert a == b e = AntiCommutator(g1(0), g2(1)) a = matrix_to_zero(represent(e, nqubits=2, format='sympy')) b = matrix_to_zero(represent(e.doit(), nqubits=2, format='sympy')) assert a == b def test_cnot_commutators(): """Test commutators of involving CNOT gates.""" assert Commutator(CNOT(0, 1), Z(0)).doit() == 0 assert Commutator(CNOT(0, 1), T(0)).doit() == 0 assert Commutator(CNOT(0, 1), S(0)).doit() == 0 assert Commutator(CNOT(0, 1), X(1)).doit() == 0 assert Commutator(CNOT(0, 1), CNOT(0, 1)).doit() == 0 assert Commutator(CNOT(0, 1), CNOT(0, 2)).doit() == 0 assert Commutator(CNOT(0, 2), CNOT(0, 1)).doit() == 0 assert Commutator(CNOT(1, 2), CNOT(1, 0)).doit() == 0 def test_random_circuit(): c = random_circuit(10, 3) assert isinstance(c, Mul) m = represent(c, nqubits=3) assert m.shape == (8, 8) assert isinstance(m, Matrix) def test_hermitian_XGate(): x = XGate(1, 2) x_dagger = Dagger(x) assert (x == x_dagger) def test_hermitian_YGate(): y = YGate(1, 2) y_dagger = Dagger(y) assert (y == y_dagger) def test_hermitian_ZGate(): z = ZGate(1, 2) z_dagger = Dagger(z) assert (z == z_dagger) def test_unitary_XGate(): x = XGate(1, 2) x_dagger = Dagger(x) assert (x*x_dagger == 1) def test_unitary_YGate(): y = YGate(1, 2) y_dagger = Dagger(y) assert (y*y_dagger == 1) def test_unitary_ZGate(): z = ZGate(1, 2) z_dagger = Dagger(z) assert (z*z_dagger == 1)
11,664
32.909884
90
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_tensorproduct.py
from sympy import I, symbols, Matrix from sympy.physics.quantum.commutator import Commutator as Comm from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.tensorproduct import TensorProduct as TP from sympy.physics.quantum.tensorproduct import tensor_product_simp from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.qubit import Qubit, QubitBra from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum.density import Density from sympy.core.trace import Tr A, B, C = symbols('A,B,C', commutative=False) x = symbols('x') mat1 = Matrix([[1, 2*I], [1 + I, 3]]) mat2 = Matrix([[2*I, 3], [4*I, 2]]) def test_tensor_product_dagger(): assert Dagger(TensorProduct(I*A, B)) == \ -I*TensorProduct(Dagger(A), Dagger(B)) assert Dagger(TensorProduct(mat1, mat2)) == \ TensorProduct(Dagger(mat1), Dagger(mat2)) def test_tensor_product_abstract(): assert TP(x*A, 2*B) == x*2*TP(A, B) assert TP(A, B) != TP(B, A) assert TP(A, B).is_commutative is False assert isinstance(TP(A, B), TP) assert TP(A, B).subs(A, C) == TP(C, B) def test_tensor_product_expand(): assert TP(A + B, B + C).expand(tensorproduct=True) == \ TP(A, B) + TP(A, C) + TP(B, B) + TP(B, C) def test_tensor_product_commutator(): assert TP(Comm(A, B), C).doit().expand(tensorproduct=True) == \ TP(A*B, C) - TP(B*A, C) assert Comm(TP(A, B), TP(B, C)).doit() == \ TP(A, B)*TP(B, C) - TP(B, C)*TP(A, B) def test_tensor_product_simp(): assert tensor_product_simp(TP(A, B)*TP(B, C)) == TP(A*B, B*C) def test_issue_5923(): # most of the issue regarding sympification of args has been handled # and is tested internally by the use of args_cnc through the quantum # module, but the following is a test from the issue that used to raise. assert TensorProduct(1, Qubit('1')*Qubit('1').dual) == \ TensorProduct(1, OuterProduct(Qubit(1), QubitBra(1))) def test_eval_trace(): # This test includes tests with dependencies between TensorProducts #and density operators. Since, the test is more to test the behavior of #TensorProducts it remains here A, B, C, D, E, F = symbols('A B C D E F', commutative=False) # Density with simple tensor products as args t = TensorProduct(A, B) d = Density([t, 1.0]) tr = Tr(d) assert tr.doit() == 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B)) ## partial trace with simple tensor products as args t = TensorProduct(A, B, C) d = Density([t, 1.0]) tr = Tr(d, [1]) assert tr.doit() == 1.0*A*Dagger(A)*Tr(B*Dagger(B))*C*Dagger(C) tr = Tr(d, [0, 2]) assert tr.doit() == 1.0*Tr(A*Dagger(A))*B*Dagger(B)*Tr(C*Dagger(C)) # Density with multiple Tensorproducts as states t2 = TensorProduct(A, B) t3 = TensorProduct(C, D) d = Density([t2, 0.5], [t3, 0.5]) t = Tr(d) assert t.doit() == (0.5*Tr(A*Dagger(A))*Tr(B*Dagger(B)) + 0.5*Tr(C*Dagger(C))*Tr(D*Dagger(D))) t = Tr(d, [0]) assert t.doit() == (0.5*Tr(A*Dagger(A))*B*Dagger(B) + 0.5*Tr(C*Dagger(C))*D*Dagger(D)) #Density with mixed states d = Density([t2 + t3, 1.0]) t = Tr(d) assert t.doit() == ( 1.0*Tr(A*Dagger(A))*Tr(B*Dagger(B)) + 1.0*Tr(A*Dagger(C))*Tr(B*Dagger(D)) + 1.0*Tr(C*Dagger(A))*Tr(D*Dagger(B)) + 1.0*Tr(C*Dagger(C))*Tr(D*Dagger(D))) t = Tr(d, [1] ) assert t.doit() == ( 1.0*A*Dagger(A)*Tr(B*Dagger(B)) + 1.0*A*Dagger(C)*Tr(B*Dagger(D)) + 1.0*C*Dagger(A)*Tr(D*Dagger(B)) + 1.0*C*Dagger(C)*Tr(D*Dagger(D)))
3,752
33.75
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_qexpr.py
from sympy import Symbol, Integer from sympy.physics.quantum.qexpr import QExpr, _qsympify_sequence from sympy.physics.quantum.hilbert import HilbertSpace from sympy.core.containers import Tuple x = Symbol('x') y = Symbol('y') def test_qexpr_new(): q = QExpr(0) assert q.label == (0,) assert q.hilbert_space == HilbertSpace() assert q.is_commutative is False q = QExpr(0, 1) assert q.label == (Integer(0), Integer(1)) q = QExpr._new_rawargs(HilbertSpace(), Integer(0), Integer(1)) assert q.label == (Integer(0), Integer(1)) assert q.hilbert_space == HilbertSpace() def test_qexpr_commutative(): q1 = QExpr(x) q2 = QExpr(y) assert q1.is_commutative is False assert q2.is_commutative is False assert q1*q2 != q2*q1 q = QExpr._new_rawargs(0, 1, HilbertSpace()) assert q.is_commutative is False def test_qexpr_commutative_free_symbols(): q1 = QExpr(x) assert q1.free_symbols.pop().is_commutative is False q2 = QExpr('q2') assert q2.free_symbols.pop().is_commutative is False def test_qexpr_subs(): q1 = QExpr(x, y) assert q1.subs(x, y) == QExpr(y, y) assert q1.subs({x: 1, y: 2}) == QExpr(1, 2) def test_qsympify(): assert _qsympify_sequence([[1, 2], [1, 3]]) == (Tuple(1, 2), Tuple(1, 3)) assert _qsympify_sequence(([1, 2, [3, 4, [2, ]], 1], 3)) == \ (Tuple(1, 2, Tuple(3, 4, Tuple(2,)), 1), 3) assert _qsympify_sequence((1,)) == (1,)
1,457
27.038462
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_operator.py
from sympy import (Derivative, diff, Function, Integer, Mul, pi, sin, Symbol, symbols) from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.hilbert import HilbertSpace from sympy.physics.quantum.operator import (Operator, UnitaryOperator, HermitianOperator, OuterProduct, DifferentialOperator, IdentityOperator) from sympy.physics.quantum.state import Ket, Bra, Wavefunction from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.represent import represent from sympy.core.trace import Tr from sympy.physics.quantum.spin import JzKet, JzBra from sympy.matrices import eye class CustomKet(Ket): @classmethod def default_args(self): return ("t",) class CustomOp(HermitianOperator): @classmethod def default_args(self): return ("T",) t_ket = CustomKet() t_op = CustomOp() def test_operator(): A = Operator('A') B = Operator('B') C = Operator('C') assert isinstance(A, Operator) assert isinstance(A, QExpr) assert A.label == (Symbol('A'),) assert A.is_commutative is False assert A.hilbert_space == HilbertSpace() assert A*B != B*A assert (A*(B + C)).expand() == A*B + A*C assert ((A + B)**2).expand() == A**2 + A*B + B*A + B**2 assert t_op.label[0] == Symbol(t_op.default_args()[0]) assert Operator() == Operator("O") assert A*IdentityOperator() == A def test_operator_inv(): A = Operator('A') assert A*A.inv() == 1 assert A.inv()*A == 1 def test_hermitian(): H = HermitianOperator('H') assert isinstance(H, HermitianOperator) assert isinstance(H, Operator) assert Dagger(H) == H assert H.inv() != H assert H.is_commutative is False assert Dagger(H).is_commutative is False def test_unitary(): U = UnitaryOperator('U') assert isinstance(U, UnitaryOperator) assert isinstance(U, Operator) assert U.inv() == Dagger(U) assert U*Dagger(U) == 1 assert Dagger(U)*U == 1 assert U.is_commutative is False assert Dagger(U).is_commutative is False def test_identity(): I = IdentityOperator() O = Operator('O') x = Symbol("x") assert isinstance(I, IdentityOperator) assert isinstance(I, Operator) assert I * O == O assert O * I == O assert isinstance(I * I, IdentityOperator) assert isinstance(3 * I, Mul) assert isinstance(I * x, Mul) assert I.inv() == I assert Dagger(I) == I assert qapply(I * O) == O assert qapply(O * I) == O for n in [2, 3, 5]: assert represent(IdentityOperator(n)) == eye(n) def test_outer_product(): k = Ket('k') b = Bra('b') op = OuterProduct(k, b) assert isinstance(op, OuterProduct) assert isinstance(op, Operator) assert op.ket == k assert op.bra == b assert op.label == (k, b) assert op.is_commutative is False op = k*b assert isinstance(op, OuterProduct) assert isinstance(op, Operator) assert op.ket == k assert op.bra == b assert op.label == (k, b) assert op.is_commutative is False op = 2*k*b assert op == Mul(Integer(2), k, b) op = 2*(k*b) assert op == Mul(Integer(2), OuterProduct(k, b)) assert Dagger(k*b) == OuterProduct(Dagger(b), Dagger(k)) assert Dagger(k*b).is_commutative is False #test the _eval_trace assert Tr(OuterProduct(JzKet(1, 1), JzBra(1, 1))).doit() == 1 # test scaled kets and bras assert OuterProduct(2 * k, b) == 2 * OuterProduct(k, b) assert OuterProduct(k, 2 * b) == 2 * OuterProduct(k, b) # test sums of kets and bras k1, k2 = Ket('k1'), Ket('k2') b1, b2 = Bra('b1'), Bra('b2') assert (OuterProduct(k1 + k2, b1) == OuterProduct(k1, b1) + OuterProduct(k2, b1)) assert (OuterProduct(k1, b1 + b2) == OuterProduct(k1, b1) + OuterProduct(k1, b2)) assert (OuterProduct(1 * k1 + 2 * k2, 3 * b1 + 4 * b2) == 3 * OuterProduct(k1, b1) + 4 * OuterProduct(k1, b2) + 6 * OuterProduct(k2, b1) + 8 * OuterProduct(k2, b2)) def test_operator_dagger(): A = Operator('A') B = Operator('B') assert Dagger(A*B) == Dagger(B)*Dagger(A) assert Dagger(A + B) == Dagger(A) + Dagger(B) assert Dagger(A**2) == Dagger(A)**2 def test_differential_operator(): x = Symbol('x') f = Function('f') d = DifferentialOperator(Derivative(f(x), x), f(x)) g = Wavefunction(x**2, x) assert qapply(d*g) == Wavefunction(2*x, x) assert d.expr == Derivative(f(x), x) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 2), f(x)) d = DifferentialOperator(Derivative(f(x), x, 2), f(x)) g = Wavefunction(x**3, x) assert qapply(d*g) == Wavefunction(6*x, x) assert d.expr == Derivative(f(x), x, 2) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == DifferentialOperator(Derivative(f(x), x, 3), f(x)) d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) assert d.expr == 1/x*Derivative(f(x), x) assert d.function == f(x) assert d.variables == (x,) assert diff(d, x) == \ DifferentialOperator(Derivative(1/x*Derivative(f(x), x), x), f(x)) assert qapply(d*g) == Wavefunction(3*x, x) # 2D cartesian Laplacian y = Symbol('y') d = DifferentialOperator(Derivative(f(x, y), x, 2) + Derivative(f(x, y), y, 2), f(x, y)) w = Wavefunction(x**3*y**2 + y**3*x**2, x, y) assert d.expr == Derivative(f(x, y), x, 2) + Derivative(f(x, y), y, 2) assert d.function == f(x, y) assert d.variables == (x, y) assert diff(d, x) == \ DifferentialOperator(Derivative(d.expr, x), f(x, y)) assert diff(d, y) == \ DifferentialOperator(Derivative(d.expr, y), f(x, y)) assert qapply(d*w) == Wavefunction(2*x**3 + 6*x*y**2 + 6*x**2*y + 2*y**3, x, y) # 2D polar Laplacian (th = theta) r, th = symbols('r th') d = DifferentialOperator(1/r*Derivative(r*Derivative(f(r, th), r), r) + 1/(r**2)*Derivative(f(r, th), th, 2), f(r, th)) w = Wavefunction(r**2*sin(th), r, (th, 0, pi)) assert d.expr == \ 1/r*Derivative(r*Derivative(f(r, th), r), r) + \ 1/(r**2)*Derivative(f(r, th), th, 2) assert d.function == f(r, th) assert d.variables == (r, th) assert diff(d, r) == \ DifferentialOperator(Derivative(d.expr, r), f(r, th)) assert diff(d, th) == \ DifferentialOperator(Derivative(d.expr, th), f(r, th)) assert qapply(d*w) == Wavefunction(3*sin(th), r, (th, 0, pi))
6,870
29.004367
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_boson.py
from sympy import sqrt, exp, S, prod from sympy.core.compatibility import range from sympy.physics.quantum import Dagger, Commutator, qapply from sympy.physics.quantum.boson import BosonOp from sympy.physics.quantum.boson import ( BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra) def test_bosonoperator(): a = BosonOp('a') b = BosonOp('b') assert isinstance(a, BosonOp) assert isinstance(Dagger(a), BosonOp) assert a.is_annihilation assert not Dagger(a).is_annihilation assert BosonOp("a") == BosonOp("a") assert BosonOp("a") != BosonOp("c") assert BosonOp("a", True) != BosonOp("a", False) assert Commutator(a, Dagger(a)).doit() == 1 assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a def test_boson_states(): a = BosonOp("a") # Fock states n = 3 assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0 assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1 assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \ == sqrt(prod(range(1, n+1))) # Coherent states alpha1, alpha2 = 1.2, 4.3 assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1 assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1 assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() - exp(-S(1) / 2 * (alpha1 - alpha2) ** 2)) < 1e-12 assert qapply(a * BosonCoherentKet(alpha1)) == \ alpha1 * BosonCoherentKet(alpha1)
1,523
32.130435
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_spin.py
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),) ))
320,440
73.712287
187
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_identitysearch.py
from sympy.external import import_module from sympy import Mul, Integer from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.gate import (X, Y, Z, H, CNOT, IdentityGate, CGate, PhaseGate, TGate) from sympy.physics.quantum.identitysearch import (generate_gate_rules, generate_equivalent_ids, GateIdentity, bfs_identity_search, is_scalar_sparse_matrix, is_scalar_nonsparse_matrix, is_degenerate, is_reducible) from sympy.utilities.pytest import skip, XFAIL def create_gate_sequence(qubit=0): gates = (X(qubit), Y(qubit), Z(qubit), H(qubit)) return gates def test_generate_gate_rules_1(): # Test with tuples (x, y, z, h) = create_gate_sequence() ph = PhaseGate(0) cgate_t = CGate(0, TGate(1)) assert generate_gate_rules((x,)) == {((x,), ())} gate_rules = set([((x, x), ()), ((x,), (x,))]) assert generate_gate_rules((x, x)) == gate_rules gate_rules = set([((x, y, x), ()), ((y, x, x), ()), ((x, x, y), ()), ((y, x), (x,)), ((x, y), (x,)), ((y,), (x, x))]) assert generate_gate_rules((x, y, x)) == gate_rules gate_rules = set([((x, y, z), ()), ((y, z, x), ()), ((z, x, y), ()), ((), (x, z, y)), ((), (y, x, z)), ((), (z, y, x)), ((x,), (z, y)), ((y, z), (x,)), ((y,), (x, z)), ((z, x), (y,)), ((z,), (y, x)), ((x, y), (z,))]) actual = generate_gate_rules((x, y, z)) assert actual == gate_rules gate_rules = set( [((), (h, z, y, x)), ((), (x, h, z, y)), ((), (y, x, h, z)), ((), (z, y, x, h)), ((h,), (z, y, x)), ((x,), (h, z, y)), ((y,), (x, h, z)), ((z,), (y, x, h)), ((h, x), (z, y)), ((x, y), (h, z)), ((y, z), (x, h)), ((z, h), (y, x)), ((h, x, y), (z,)), ((x, y, z), (h,)), ((y, z, h), (x,)), ((z, h, x), (y,)), ((h, x, y, z), ()), ((x, y, z, h), ()), ((y, z, h, x), ()), ((z, h, x, y), ())]) actual = generate_gate_rules((x, y, z, h)) assert actual == gate_rules gate_rules = set([((), (cgate_t**(-1), ph**(-1), x)), ((), (ph**(-1), x, cgate_t**(-1))), ((), (x, cgate_t**(-1), ph**(-1))), ((cgate_t,), (ph**(-1), x)), ((ph,), (x, cgate_t**(-1))), ((x,), (cgate_t**(-1), ph**(-1))), ((cgate_t, x), (ph**(-1),)), ((ph, cgate_t), (x,)), ((x, ph), (cgate_t**(-1),)), ((cgate_t, x, ph), ()), ((ph, cgate_t, x), ()), ((x, ph, cgate_t), ())]) actual = generate_gate_rules((x, ph, cgate_t)) assert actual == gate_rules gate_rules = set([(Integer(1), cgate_t**(-1)*ph**(-1)*x), (Integer(1), ph**(-1)*x*cgate_t**(-1)), (Integer(1), x*cgate_t**(-1)*ph**(-1)), (cgate_t, ph**(-1)*x), (ph, x*cgate_t**(-1)), (x, cgate_t**(-1)*ph**(-1)), (cgate_t*x, ph**(-1)), (ph*cgate_t, x), (x*ph, cgate_t**(-1)), (cgate_t*x*ph, Integer(1)), (ph*cgate_t*x, Integer(1)), (x*ph*cgate_t, Integer(1))]) actual = generate_gate_rules((x, ph, cgate_t), return_as_muls=True) assert actual == gate_rules def test_generate_gate_rules_2(): # Test with Muls (x, y, z, h) = create_gate_sequence() ph = PhaseGate(0) cgate_t = CGate(0, TGate(1)) # Note: 1 (type int) is not the same as 1 (type One) expected = {(x, Integer(1))} assert generate_gate_rules((x,), return_as_muls=True) == expected expected = {(Integer(1), Integer(1))} assert generate_gate_rules(x*x, return_as_muls=True) == expected expected = {((), ())} assert generate_gate_rules(x*x, return_as_muls=False) == expected gate_rules = set([(x*y*x, Integer(1)), (y, Integer(1)), (y*x, x), (x*y, x)]) assert generate_gate_rules(x*y*x, return_as_muls=True) == gate_rules gate_rules = set([(x*y*z, Integer(1)), (y*z*x, Integer(1)), (z*x*y, Integer(1)), (Integer(1), x*z*y), (Integer(1), y*x*z), (Integer(1), z*y*x), (x, z*y), (y*z, x), (y, x*z), (z*x, y), (z, y*x), (x*y, z)]) actual = generate_gate_rules(x*y*z, return_as_muls=True) assert actual == gate_rules gate_rules = set([(Integer(1), h*z*y*x), (Integer(1), x*h*z*y), (Integer(1), y*x*h*z), (Integer(1), z*y*x*h), (h, z*y*x), (x, h*z*y), (y, x*h*z), (z, y*x*h), (h*x, z*y), (z*h, y*x), (x*y, h*z), (y*z, x*h), (h*x*y, z), (x*y*z, h), (y*z*h, x), (z*h*x, y), (h*x*y*z, Integer(1)), (x*y*z*h, Integer(1)), (y*z*h*x, Integer(1)), (z*h*x*y, Integer(1))]) actual = generate_gate_rules(x*y*z*h, return_as_muls=True) assert actual == gate_rules gate_rules = set([(Integer(1), cgate_t**(-1)*ph**(-1)*x), (Integer(1), ph**(-1)*x*cgate_t**(-1)), (Integer(1), x*cgate_t**(-1)*ph**(-1)), (cgate_t, ph**(-1)*x), (ph, x*cgate_t**(-1)), (x, cgate_t**(-1)*ph**(-1)), (cgate_t*x, ph**(-1)), (ph*cgate_t, x), (x*ph, cgate_t**(-1)), (cgate_t*x*ph, Integer(1)), (ph*cgate_t*x, Integer(1)), (x*ph*cgate_t, Integer(1))]) actual = generate_gate_rules(x*ph*cgate_t, return_as_muls=True) assert actual == gate_rules gate_rules = set([((), (cgate_t**(-1), ph**(-1), x)), ((), (ph**(-1), x, cgate_t**(-1))), ((), (x, cgate_t**(-1), ph**(-1))), ((cgate_t,), (ph**(-1), x)), ((ph,), (x, cgate_t**(-1))), ((x,), (cgate_t**(-1), ph**(-1))), ((cgate_t, x), (ph**(-1),)), ((ph, cgate_t), (x,)), ((x, ph), (cgate_t**(-1),)), ((cgate_t, x, ph), ()), ((ph, cgate_t, x), ()), ((x, ph, cgate_t), ())]) actual = generate_gate_rules(x*ph*cgate_t) assert actual == gate_rules def test_generate_equivalent_ids_1(): # Test with tuples (x, y, z, h) = create_gate_sequence() assert generate_equivalent_ids((x,)) == {(x,)} assert generate_equivalent_ids((x, x)) == {(x, x)} assert generate_equivalent_ids((x, y)) == {(x, y), (y, x)} gate_seq = (x, y, z) gate_ids = set([(x, y, z), (y, z, x), (z, x, y), (z, y, x), (y, x, z), (x, z, y)]) assert generate_equivalent_ids(gate_seq) == gate_ids gate_ids = set([Mul(x, y, z), Mul(y, z, x), Mul(z, x, y), Mul(z, y, x), Mul(y, x, z), Mul(x, z, y)]) assert generate_equivalent_ids(gate_seq, return_as_muls=True) == gate_ids gate_seq = (x, y, z, h) gate_ids = set([(x, y, z, h), (y, z, h, x), (h, x, y, z), (h, z, y, x), (z, y, x, h), (y, x, h, z), (z, h, x, y), (x, h, z, y)]) assert generate_equivalent_ids(gate_seq) == gate_ids gate_seq = (x, y, x, y) gate_ids = {(x, y, x, y), (y, x, y, x)} assert generate_equivalent_ids(gate_seq) == gate_ids cgate_y = CGate((1,), y) gate_seq = (y, cgate_y, y, cgate_y) gate_ids = {(y, cgate_y, y, cgate_y), (cgate_y, y, cgate_y, y)} assert generate_equivalent_ids(gate_seq) == gate_ids cnot = CNOT(1, 0) cgate_z = CGate((0,), Z(1)) gate_seq = (cnot, h, cgate_z, h) gate_ids = set([(cnot, h, cgate_z, h), (h, cgate_z, h, cnot), (h, cnot, h, cgate_z), (cgate_z, h, cnot, h)]) assert generate_equivalent_ids(gate_seq) == gate_ids def test_generate_equivalent_ids_2(): # Test with Muls (x, y, z, h) = create_gate_sequence() assert generate_equivalent_ids((x,), return_as_muls=True) == {x} gate_ids = {Integer(1)} assert generate_equivalent_ids(x*x, return_as_muls=True) == gate_ids gate_ids = {x*y, y*x} assert generate_equivalent_ids(x*y, return_as_muls=True) == gate_ids gate_ids = {(x, y), (y, x)} assert generate_equivalent_ids(x*y) == gate_ids circuit = Mul(*(x, y, z)) gate_ids = set([x*y*z, y*z*x, z*x*y, z*y*x, y*x*z, x*z*y]) assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids circuit = Mul(*(x, y, z, h)) gate_ids = set([x*y*z*h, y*z*h*x, h*x*y*z, h*z*y*x, z*y*x*h, y*x*h*z, z*h*x*y, x*h*z*y]) assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids circuit = Mul(*(x, y, x, y)) gate_ids = {x*y*x*y, y*x*y*x} assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids cgate_y = CGate((1,), y) circuit = Mul(*(y, cgate_y, y, cgate_y)) gate_ids = {y*cgate_y*y*cgate_y, cgate_y*y*cgate_y*y} assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids cnot = CNOT(1, 0) cgate_z = CGate((0,), Z(1)) circuit = Mul(*(cnot, h, cgate_z, h)) gate_ids = set([cnot*h*cgate_z*h, h*cgate_z*h*cnot, h*cnot*h*cgate_z, cgate_z*h*cnot*h]) assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids def test_is_scalar_nonsparse_matrix(): numqubits = 2 id_only = False id_gate = (IdentityGate(1),) actual = is_scalar_nonsparse_matrix(id_gate, numqubits, id_only) assert actual is True x0 = X(0) xx_circuit = (x0, x0) actual = is_scalar_nonsparse_matrix(xx_circuit, numqubits, id_only) assert actual is True x1 = X(1) y1 = Y(1) xy_circuit = (x1, y1) actual = is_scalar_nonsparse_matrix(xy_circuit, numqubits, id_only) assert actual is False z1 = Z(1) xyz_circuit = (x1, y1, z1) actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only) assert actual is True cnot = CNOT(1, 0) cnot_circuit = (cnot, cnot) actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only) assert actual is True h = H(0) hh_circuit = (h, h) actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only) assert actual is True h1 = H(1) xhzh_circuit = (x1, h1, z1, h1) actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only) assert actual is True id_only = True actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only) assert actual is True actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only) assert actual is False actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only) assert actual is True actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only) assert actual is True def test_is_scalar_sparse_matrix(): np = import_module('numpy') if not np: skip("numpy not installed.") scipy = import_module('scipy', __import__kwargs={'fromlist': ['sparse']}) if not scipy: skip("scipy not installed.") numqubits = 2 id_only = False id_gate = (IdentityGate(1),) assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True x0 = X(0) xx_circuit = (x0, x0) assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True x1 = X(1) y1 = Y(1) xy_circuit = (x1, y1) assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False z1 = Z(1) xyz_circuit = (x1, y1, z1) assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True cnot = CNOT(1, 0) cnot_circuit = (cnot, cnot) assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True h = H(0) hh_circuit = (h, h) assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True # NOTE: # The elements of the sparse matrix for the following circuit # is actually 1.0000000000000002+0.0j. h1 = H(1) xhzh_circuit = (x1, h1, z1, h1) assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True id_only = True assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True def test_is_degenerate(): (x, y, z, h) = create_gate_sequence() gate_id = GateIdentity(x, y, z) ids = {gate_id} another_id = (z, y, x) assert is_degenerate(ids, another_id) is True def test_is_reducible(): nqubits = 2 (x, y, z, h) = create_gate_sequence() circuit = (x, y, y) assert is_reducible(circuit, nqubits, 1, 3) is True circuit = (x, y, x) assert is_reducible(circuit, nqubits, 1, 3) is False circuit = (x, y, y, x) assert is_reducible(circuit, nqubits, 0, 4) is True circuit = (x, y, y, x) assert is_reducible(circuit, nqubits, 1, 3) is True circuit = (x, y, z, y, y) assert is_reducible(circuit, nqubits, 1, 5) is True def test_bfs_identity_search(): assert bfs_identity_search([], 1) == set() (x, y, z, h) = create_gate_sequence() gate_list = [x] id_set = {GateIdentity(x, x)} assert bfs_identity_search(gate_list, 1, max_depth=2) == id_set # Set should not contain degenerate quantum circuits gate_list = [x, y, z] id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(x, y, z)]) assert bfs_identity_search(gate_list, 1) == id_set id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(x, y, z), GateIdentity(x, y, x, y), GateIdentity(x, z, x, z), GateIdentity(y, z, y, z)]) assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set gate_list = [x, y, z, h] id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(h, h), GateIdentity(x, y, z), GateIdentity(x, y, x, y), GateIdentity(x, z, x, z), GateIdentity(x, h, z, h), GateIdentity(y, z, y, z), GateIdentity(y, h, y, h)]) assert bfs_identity_search(gate_list, 1) == id_set id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(h, h)]) assert id_set == bfs_identity_search(gate_list, 1, max_depth=3, identity_only=True) id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(h, h), GateIdentity(x, y, z), GateIdentity(x, y, x, y), GateIdentity(x, z, x, z), GateIdentity(x, h, z, h), GateIdentity(y, z, y, z), GateIdentity(y, h, y, h), GateIdentity(x, y, h, x, h), GateIdentity(x, z, h, y, h), GateIdentity(y, z, h, z, h)]) assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set id_set = set([GateIdentity(x, x), GateIdentity(y, y), GateIdentity(z, z), GateIdentity(h, h), GateIdentity(x, h, z, h)]) assert id_set == bfs_identity_search(gate_list, 1, max_depth=4, identity_only=True) cnot = CNOT(1, 0) gate_list = [x, cnot] id_set = set([GateIdentity(x, x), GateIdentity(cnot, cnot), GateIdentity(x, cnot, x, cnot)]) assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set cgate_x = CGate((1,), x) gate_list = [x, cgate_x] id_set = set([GateIdentity(x, x), GateIdentity(cgate_x, cgate_x), GateIdentity(x, cgate_x, x, cgate_x)]) assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set cgate_z = CGate((0,), Z(1)) gate_list = [cnot, cgate_z, h] id_set = set([GateIdentity(h, h), GateIdentity(cgate_z, cgate_z), GateIdentity(cnot, cnot), GateIdentity(cnot, h, cgate_z, h)]) assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set s = PhaseGate(0) t = TGate(0) gate_list = [s, t] id_set = {GateIdentity(s, s, s, s)} assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set @XFAIL def test_bfs_identity_search_xfail(): s = PhaseGate(0) t = TGate(0) gate_list = [Dagger(s), t] id_set = {GateIdentity(Dagger(s), t, t)} assert bfs_identity_search(gate_list, 1, max_depth=3) == id_set
17,860
35.229209
77
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_operatorset.py
from sympy.physics.quantum.operatorset import ( operators_to_state, state_to_operators ) from sympy.physics.quantum.cartesian import ( XOp, XKet, PxOp, PxKet, XBra, PxBra ) from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.spin import ( JxKet, JyKet, JzKet, JxBra, JyBra, JzBra, JxOp, JyOp, JzOp, J2Op ) from sympy.utilities.pytest import raises from sympy.utilities.pytest import XFAIL @XFAIL def test_spin(): assert operators_to_state({J2Op, JxOp}) == JxKet() assert operators_to_state({J2Op, JyOp}) == JyKet() assert operators_to_state({J2Op, JzOp}) == JzKet() assert operators_to_state({J2Op(), JxOp()}) == JxKet() assert operators_to_state({J2Op(), JyOp()}) == JyKet() assert operators_to_state({J2Op(), JzOp()}) == JzKet() assert state_to_operators(JxKet) == {J2Op(), JxOp()} assert state_to_operators(JyKet) == {J2Op(), JyOp()} assert state_to_operators(JzKet) == {J2Op(), JzOp()} assert state_to_operators(JxBra) == {J2Op(), JxOp()} assert state_to_operators(JyBra) == {J2Op(), JyOp()} assert state_to_operators(JzBra) == {J2Op(), JzOp()} assert state_to_operators(JxKet()) == {J2Op(), JxOp()} assert state_to_operators(JyKet()) == {J2Op(), JyOp()} assert state_to_operators(JzKet()) == {J2Op(), JzOp()} assert state_to_operators(JxBra()) == {J2Op(), JxOp()} assert state_to_operators(JyBra()) == {J2Op(), JyOp()} assert state_to_operators(JzBra()) == {J2Op(), JzOp()} def test_op_to_state(): assert operators_to_state(XOp) == XKet() assert operators_to_state(PxOp) == PxKet() assert operators_to_state(Operator) == Ket() assert state_to_operators(operators_to_state(XOp("Q"))) == XOp("Q") assert state_to_operators(operators_to_state(XOp())) == XOp() raises(NotImplementedError, lambda: operators_to_state(XKet)) def test_state_to_op(): assert state_to_operators(XKet) == XOp() assert state_to_operators(PxKet) == PxOp() assert state_to_operators(XBra) == XOp() assert state_to_operators(PxBra) == PxOp() assert state_to_operators(Ket) == Operator() assert state_to_operators(Bra) == Operator() assert operators_to_state(state_to_operators(XKet("test"))) == XKet("test") assert operators_to_state(state_to_operators(XBra("test"))) == XKet("test") assert operators_to_state(state_to_operators(XKet())) == XKet() assert operators_to_state(state_to_operators(XBra())) == XKet() raises(NotImplementedError, lambda: state_to_operators(XOp))
2,595
36.085714
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_shor.py
from sympy.utilities.pytest import XFAIL from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.shor import CMod, getr @XFAIL def test_CMod(): assert qapply(CMod(4, 2, 2)*Qubit(0, 0, 1, 0, 0, 0, 0, 0)) == \ Qubit(0, 0, 1, 0, 0, 0, 0, 0) assert qapply(CMod(5, 5, 7)*Qubit(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)) == \ Qubit(0, 0, 1, 0, 0, 0, 0, 0, 1, 0) assert qapply(CMod(3, 2, 3)*Qubit(0, 1, 0, 0, 0, 0)) == \ Qubit(0, 1, 0, 0, 0, 1) def test_continued_frac(): assert getr(513, 1024, 10) == 2 assert getr(169, 1024, 11) == 6 assert getr(314, 4096, 16) == 13
668
29.409091
73
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/__init__.py
0
0
0
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_state.py
from sympy import (Add, conjugate, diff, I, Integer, Mul, oo, pi, Pow, Rational, sin, sqrt, Symbol, symbols, sympify) from sympy.utilities.pytest import raises from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.state import ( Ket, Bra, TimeDepKet, TimeDepBra, KetBase, BraBase, StateBase, Wavefunction ) from sympy.physics.quantum.hilbert import HilbertSpace x, y, t = symbols('x,y,t') class CustomKet(Ket): @classmethod def default_args(self): return ("test",) class CustomKetMultipleLabels(Ket): @classmethod def default_args(self): return ("r", "theta", "phi") class CustomTimeDepKet(TimeDepKet): @classmethod def default_args(self): return ("test", "t") class CustomTimeDepKetMultipleLabels(TimeDepKet): @classmethod def default_args(self): return ("r", "theta", "phi", "t") def test_ket(): k = Ket('0') assert isinstance(k, Ket) assert isinstance(k, KetBase) assert isinstance(k, StateBase) assert isinstance(k, QExpr) assert k.label == (Symbol('0'),) assert k.hilbert_space == HilbertSpace() assert k.is_commutative is False # Make sure this doesn't get converted to the number pi. k = Ket('pi') assert k.label == (Symbol('pi'),) k = Ket(x, y) assert k.label == (x, y) assert k.hilbert_space == HilbertSpace() assert k.is_commutative is False assert k.dual_class() == Bra assert k.dual == Bra(x, y) assert k.subs(x, y) == Ket(y, y) k = CustomKet() assert k == CustomKet("test") k = CustomKetMultipleLabels() assert k == CustomKetMultipleLabels("r", "theta", "phi") assert Ket() == Ket('psi') def test_bra(): b = Bra('0') assert isinstance(b, Bra) assert isinstance(b, BraBase) assert isinstance(b, StateBase) assert isinstance(b, QExpr) assert b.label == (Symbol('0'),) assert b.hilbert_space == HilbertSpace() assert b.is_commutative is False # Make sure this doesn't get converted to the number pi. b = Bra('pi') assert b.label == (Symbol('pi'),) b = Bra(x, y) assert b.label == (x, y) assert b.hilbert_space == HilbertSpace() assert b.is_commutative is False assert b.dual_class() == Ket assert b.dual == Ket(x, y) assert b.subs(x, y) == Bra(y, y) assert Bra() == Bra('psi') def test_ops(): k0 = Ket(0) k1 = Ket(1) k = 2*I*k0 - (x/sqrt(2))*k1 assert k == Add(Mul(2, I, k0), Mul(Rational(-1, 2), x, Pow(2, Rational(1, 2)), k1)) def test_time_dep_ket(): k = TimeDepKet(0, t) assert isinstance(k, TimeDepKet) assert isinstance(k, KetBase) assert isinstance(k, StateBase) assert isinstance(k, QExpr) assert k.label == (Integer(0),) assert k.args == (Integer(0), t) assert k.time == t assert k.dual_class() == TimeDepBra assert k.dual == TimeDepBra(0, t) assert k.subs(t, 2) == TimeDepKet(0, 2) k = TimeDepKet(x, 0.5) assert k.label == (x,) assert k.args == (x, sympify(0.5)) k = CustomTimeDepKet() assert k.label == (Symbol("test"),) assert k.time == Symbol("t") assert k == CustomTimeDepKet("test", "t") k = CustomTimeDepKetMultipleLabels() assert k.label == (Symbol("r"), Symbol("theta"), Symbol("phi")) assert k.time == Symbol("t") assert k == CustomTimeDepKetMultipleLabels("r", "theta", "phi", "t") assert TimeDepKet() == TimeDepKet("psi", "t") def test_time_dep_bra(): b = TimeDepBra(0, t) assert isinstance(b, TimeDepBra) assert isinstance(b, BraBase) assert isinstance(b, StateBase) assert isinstance(b, QExpr) assert b.label == (Integer(0),) assert b.args == (Integer(0), t) assert b.time == t assert b.dual_class() == TimeDepKet assert b.dual == TimeDepKet(0, t) k = TimeDepBra(x, 0.5) assert k.label == (x,) assert k.args == (x, sympify(0.5)) assert TimeDepBra() == TimeDepBra("psi", "t") def test_bra_ket_dagger(): x = symbols('x', complex=True) k = Ket('k') b = Bra('b') assert Dagger(k) == Bra('k') assert Dagger(b) == Ket('b') assert Dagger(k).is_commutative is False k2 = Ket('k2') e = 2*I*k + x*k2 assert Dagger(e) == conjugate(x)*Dagger(k2) - 2*I*Dagger(k) def test_wavefunction(): x, y = symbols('x y', real=True) L = symbols('L', positive=True) n = symbols('n', integer=True, positive=True) f = Wavefunction(x**2, x) p = f.prob() lims = f.limits assert f.is_normalized is False assert f.norm == oo assert f(10) == 100 assert p(10) == 10000 assert lims[x] == (-oo, oo) assert diff(f, x) == Wavefunction(2*x, x) raises(NotImplementedError, lambda: f.normalize()) assert conjugate(f) == Wavefunction(conjugate(f.expr), x) assert conjugate(f) == Dagger(f) g = Wavefunction(x**2*y + y**2*x, (x, 0, 1), (y, 0, 2)) lims_g = g.limits assert lims_g[x] == (0, 1) assert lims_g[y] == (0, 2) assert g.is_normalized is False assert g.norm == sqrt(42)/3 assert g(2, 4) == 0 assert g(1, 1) == 2 assert diff(diff(g, x), y) == Wavefunction(2*x + 2*y, (x, 0, 1), (y, 0, 2)) assert conjugate(g) == Wavefunction(conjugate(g.expr), *g.args[1:]) assert conjugate(g) == Dagger(g) h = Wavefunction(sqrt(5)*x**2, (x, 0, 1)) assert h.is_normalized is True assert h.normalize() == h assert conjugate(h) == Wavefunction(conjugate(h.expr), (x, 0, 1)) assert conjugate(h) == Dagger(h) piab = Wavefunction(sin(n*pi*x/L), (x, 0, L)) assert piab.norm == sqrt(L/2) assert piab(L + 1) == 0 assert piab(0.5) == sin(0.5*n*pi/L) assert piab(0.5, n=1, L=1) == sin(0.5*pi) assert piab.normalize() == \ Wavefunction(sqrt(2)/sqrt(L)*sin(n*pi*x/L), (x, 0, L)) assert conjugate(piab) == Wavefunction(conjugate(piab.expr), (x, 0, L)) assert conjugate(piab) == Dagger(piab) k = Wavefunction(x**2, 'x') assert type(k.variables[0]) == Symbol
6,087
25.585153
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_grover.py
from sympy import sqrt, Matrix from sympy.physics.quantum.represent import represent from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qubit import IntQubit from sympy.physics.quantum.grover import (apply_grover, superposition_basis, OracleGate, grover_iteration, WGate) def return_one_on_two(qubits): return qubits == IntQubit(2, qubits.nqubits) def return_one_on_one(qubits): return qubits == IntQubit(1, qubits.nqubits) def test_superposition_basis(): nbits = 2 first_half_state = IntQubit(0, nbits)/2 + IntQubit(1, nbits)/2 second_half_state = IntQubit(2, nbits)/2 + IntQubit(3, nbits)/2 assert first_half_state + second_half_state == superposition_basis(nbits) nbits = 3 firstq = (1/sqrt(8))*IntQubit(0, nbits) + (1/sqrt(8))*IntQubit(1, nbits) secondq = (1/sqrt(8))*IntQubit(2, nbits) + (1/sqrt(8))*IntQubit(3, nbits) thirdq = (1/sqrt(8))*IntQubit(4, nbits) + (1/sqrt(8))*IntQubit(5, nbits) fourthq = (1/sqrt(8))*IntQubit(6, nbits) + (1/sqrt(8))*IntQubit(7, nbits) assert firstq + secondq + thirdq + fourthq == superposition_basis(nbits) def test_OracleGate(): v = OracleGate(1, lambda qubits: qubits == IntQubit(0)) assert qapply(v*IntQubit(0)) == -IntQubit(0) assert qapply(v*IntQubit(1)) == IntQubit(1) nbits = 2 v = OracleGate(2, return_one_on_two) assert qapply(v*IntQubit(0, nbits)) == IntQubit(0, nbits) assert qapply(v*IntQubit(1, nbits)) == IntQubit(1, nbits) assert qapply(v*IntQubit(2, nbits)) == -IntQubit(2, nbits) assert qapply(v*IntQubit(3, nbits)) == IntQubit(3, nbits) # Due to a bug of IntQubit, this first assertion is buggy # assert represent(OracleGate(1, lambda qubits: qubits == IntQubit(0)), nqubits=1) == \ # Matrix([[-1/sqrt(2), 0], [0, 1/sqrt(2)]]) assert represent(v, nqubits=2) == Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]) def test_WGate(): nqubits = 2 basis_states = superposition_basis(nqubits) assert qapply(WGate(nqubits)*basis_states) == basis_states expected = ((2/sqrt(pow(2, nqubits)))*basis_states) - IntQubit(1, nqubits) assert qapply(WGate(nqubits)*IntQubit(1, nqubits)) == expected def test_grover_iteration_1(): numqubits = 2 basis_states = superposition_basis(numqubits) v = OracleGate(numqubits, return_one_on_one) expected = IntQubit(1, numqubits) assert qapply(grover_iteration(basis_states, v)) == expected def test_grover_iteration_2(): numqubits = 4 basis_states = superposition_basis(numqubits) v = OracleGate(numqubits, return_one_on_two) # After (pi/4)sqrt(pow(2, n)), IntQubit(2) should have highest prob # In this case, after around pi times (3 or 4) iterated = grover_iteration(basis_states, v) iterated = qapply(iterated) iterated = grover_iteration(iterated, v) iterated = qapply(iterated) iterated = grover_iteration(iterated, v) iterated = qapply(iterated) # In this case, probability was highest after 3 iterations # Probability of Qubit('0010') was 251/256 (3) vs 781/1024 (4) # Ask about measurement expected = (-13*basis_states)/64 + 264*IntQubit(2, numqubits)/256 assert qapply(expected) == iterated def test_grover(): nqubits = 2 assert apply_grover(return_one_on_one, nqubits) == IntQubit(1, nqubits) nqubits = 4 basis_states = superposition_basis(nqubits) expected = (-13*basis_states)/64 + 264*IntQubit(2, nqubits)/256 assert apply_grover(return_one_on_two, 4) == qapply(expected)
3,563
37.73913
103
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_innerproduct.py
from sympy import I, Integer from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import Bra, Ket, StateBase def test_innerproduct(): k = Ket('k') b = Bra('b') ip = InnerProduct(b, k) assert isinstance(ip, InnerProduct) assert ip.bra == b assert ip.ket == k assert b*k == InnerProduct(b, k) assert k*(b*k)*b == k*InnerProduct(b, k)*b assert InnerProduct(b, k).subs(b, Dagger(k)) == Dagger(k)*k def test_innerproduct_dagger(): k = Ket('k') b = Bra('b') ip = b*k assert Dagger(ip) == Dagger(k)*Dagger(b) class FooState(StateBase): pass class FooKet(Ket, FooState): @classmethod def dual_class(self): return FooBra def _eval_innerproduct_FooBra(self, bra): return Integer(1) def _eval_innerproduct_BarBra(self, bra): return I class FooBra(Bra, FooState): @classmethod def dual_class(self): return FooKet class BarState(StateBase): pass class BarKet(Ket, BarState): @classmethod def dual_class(self): return BarBra class BarBra(Bra, BarState): @classmethod def dual_class(self): return BarKet def test_doit(): f = FooKet('foo') b = BarBra('bar') assert InnerProduct(b, f).doit() == I assert InnerProduct(Dagger(f), Dagger(b)).doit() == -I assert InnerProduct(Dagger(f), f).doit() == Integer(1)
1,468
19.402778
63
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_pauli.py
from sympy import I, Mul from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply, Operator) from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ, SigmaMinus, SigmaPlus, qsimplify_pauli) from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra sx, sy, sz = SigmaX(), SigmaY(), SigmaZ() sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1) sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2) sm, sp = SigmaMinus(), SigmaPlus() A, B = Operator("A"), Operator("B") def test_pauli_operators_types(): assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX) assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY) assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ) assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus) assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus) def test_pauli_operators_commutator(): assert Commutator(sx, sy).doit() == 2 * I * sz assert Commutator(sy, sz).doit() == 2 * I * sx assert Commutator(sz, sx).doit() == 2 * I * sy def test_pauli_operators_commutator_with_labels(): assert Commutator(sx1, sy1).doit() == 2 * I * sz1 assert Commutator(sy1, sz1).doit() == 2 * I * sx1 assert Commutator(sz1, sx1).doit() == 2 * I * sy1 assert Commutator(sx2, sy2).doit() == 2 * I * sz2 assert Commutator(sy2, sz2).doit() == 2 * I * sx2 assert Commutator(sz2, sx2).doit() == 2 * I * sy2 assert Commutator(sx1, sy2).doit() == 0 assert Commutator(sy1, sz2).doit() == 0 assert Commutator(sz1, sx2).doit() == 0 def test_pauli_operators_anticommutator(): assert AntiCommutator(sy, sz).doit() == 0 assert AntiCommutator(sz, sx).doit() == 0 assert AntiCommutator(sx, sm).doit() == 1 assert AntiCommutator(sx, sp).doit() == 1 def test_pauli_operators_adjoint(): assert Dagger(sx) == sx assert Dagger(sy) == sy assert Dagger(sz) == sz def test_pauli_operators_adjoint_with_labels(): assert Dagger(sx1) == sx1 assert Dagger(sy1) == sy1 assert Dagger(sz1) == sz1 assert Dagger(sx1) != sx2 assert Dagger(sy1) != sy2 assert Dagger(sz1) != sz2 def test_pauli_operators_multiplication(): assert qsimplify_pauli(sx * sx) == 1 assert qsimplify_pauli(sy * sy) == 1 assert qsimplify_pauli(sz * sz) == 1 assert qsimplify_pauli(sx * sy) == I * sz assert qsimplify_pauli(sy * sz) == I * sx assert qsimplify_pauli(sz * sx) == I * sy assert qsimplify_pauli(sy * sx) == - I * sz assert qsimplify_pauli(sz * sy) == - I * sx assert qsimplify_pauli(sx * sz) == - I * sy def test_pauli_operators_multiplication_with_labels(): assert qsimplify_pauli(sx1 * sx1) == 1 assert qsimplify_pauli(sy1 * sy1) == 1 assert qsimplify_pauli(sz1 * sz1) == 1 assert isinstance(sx1 * sx2, Mul) assert isinstance(sy1 * sy2, Mul) assert isinstance(sz1 * sz2, Mul) assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2 assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2 def test_pauli_states(): sx, sz = SigmaX(), SigmaZ() up = SigmaZKet(0) down = SigmaZKet(1) assert qapply(sx * up) == down assert qapply(sx * down) == up assert qapply(sz * up) == up assert qapply(sz * down) == - down up = SigmaZBra(0) down = SigmaZBra(1) assert qapply(up * sx, dagger=True) == down assert qapply(down * sx, dagger=True) == up assert qapply(up * sz, dagger=True) == up assert qapply(down * sz, dagger=True) == - down assert Dagger(SigmaZKet(0)) == SigmaZBra(0) assert Dagger(SigmaZBra(1)) == SigmaZKet(1)
3,762
29.104
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_cg.py
from __future__ import division from sympy import S, sqrt, Sum, symbols from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.utilities.pytest import slow @slow def test_cg_simp_add(): j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p') # Test Varshalovich 8.7.1 Eq 1 a = CG(S(1)/2, S(1)/2, 0, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, 0, 0, S(1)/2, -S(1)/2) c = CG(1, 1, 0, 0, 1, 1) d = CG(1, 0, 0, 0, 1, 0) e = CG(1, -1, 0, 0, 1, -1) assert cg_simp(a + b) == 2 assert cg_simp(c + d + e) == 3 assert cg_simp(a + b + c + d + e) == 5 assert cg_simp(a + b + c) == 2 + c assert cg_simp(2*a + b) == 2 + a assert cg_simp(2*c + d + e) == 3 + c assert cg_simp(5*a + 5*b) == 10 assert cg_simp(5*c + 5*d + 5*e) == 15 assert cg_simp(-a - b) == -2 assert cg_simp(-c - d - e) == -3 assert cg_simp(-6*a - 6*b) == -12 assert cg_simp(-4*c - 4*d - 4*e) == -12 a = CG(S(1)/2, S(1)/2, j, 0, S(1)/2, S(1)/2) b = CG(S(1)/2, -S(1)/2, j, 0, S(1)/2, -S(1)/2) c = CG(1, 1, j, 0, 1, 1) d = CG(1, 0, j, 0, 1, 0) e = CG(1, -1, j, 0, 1, -1) assert cg_simp(a + b) == 2*KroneckerDelta(j, 0) assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0) assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0) assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0) assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0) assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0) assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0) assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0) assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0) # Test Varshalovich 8.7.1 Eq 2 a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, -1, 0, 0) d = CG(1, 0, 1, 0, 0, 0) e = CG(1, -1, 1, 1, 0, 0) assert cg_simp(a - b) == sqrt(2) assert cg_simp(c - d + e) == sqrt(3) assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3) assert cg_simp(a - b + c) == sqrt(2) + c assert cg_simp(2*a - b) == sqrt(2) + a assert cg_simp(2*c - d + e) == sqrt(3) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3) assert cg_simp(-a + b) == -sqrt(2) assert cg_simp(-c + d - e) == -sqrt(3) assert cg_simp(-6*a + 6*b) == -6*sqrt(2) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3) a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, j, 0) b = CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, j, 0) c = CG(1, 1, 1, -1, j, 0) d = CG(1, 0, 1, 0, j, 0) e = CG(1, -1, 1, 1, j, 0) assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c - d + e) == sqrt( 2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0) assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0) assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0) # Test Varshalovich 8.7.2 Eq 9 # alpha=alphap,beta=betap case # numerical a = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 1, 0)**2 b = CG(S(1)/2, S(1)/2, S(1)/2, -S(1)/2, 0, 0)**2 c = CG(1, 0, 1, 1, 1, 1)**2 d = CG(1, 0, 1, 1, 2, 1)**2 assert cg_simp(a + b) == 1 assert cg_simp(c + d) == 1 assert cg_simp(a + b + c + d) == 2 assert cg_simp(4*a + 4*b) == 4 assert cg_simp(4*c + 4*d) == 4 assert cg_simp(5*a + 3*b) == 3 + 2*a assert cg_simp(5*c + 3*d) == 3 + 2*c assert cg_simp(-a - b) == -1 assert cg_simp(-c - d) == -1 # symbolic a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)**2 b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)**2 c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)**2 d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)**2 assert cg_simp(a + b + c + d) == 1 assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4 assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d assert cg_simp(-a - b - c - d) == -1 a = CG(1, m1, 1, m2, 2, 2)**2 b = CG(1, m1, 1, m2, 2, 1)**2 c = CG(1, m1, 1, m2, 2, 0)**2 d = CG(1, m1, 1, m2, 2, -1)**2 e = CG(1, m1, 1, m2, 2, -2)**2 f = CG(1, m1, 1, m2, 1, 1)**2 g = CG(1, m1, 1, m2, 1, 0)**2 h = CG(1, m1, 1, m2, 1, -1)**2 i = CG(1, m1, 1, m2, 0, 0)**2 assert cg_simp(a + b + c + d + e + f + g + h + i) == 1 assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4 assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1 # alpha!=alphap or beta!=betap case # numerical a = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 1, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 1, 0) b = CG(S(1)/2, S( 1)/2, S(1)/2, -S(1)/2, 0, 0)*CG(S(1)/2, -S(1)/2, S(1)/2, S(1)/2, 0, 0) c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1) d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1) assert cg_simp(a + b) == 0 assert cg_simp(c + d) == 0 # symbolic a = CG(S(1)/2, m1, S(1)/2, m2, 1, 1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 1) b = CG(S(1)/2, m1, S(1)/2, m2, 1, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, 0) c = CG(S(1)/2, m1, S(1)/2, m2, 1, -1)*CG(S(1)/2, m1p, S(1)/2, m2p, 1, -1) d = CG(S(1)/2, m1, S(1)/2, m2, 0, 0)*CG(S(1)/2, m1p, S(1)/2, m2p, 0, 0) assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2) b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1) c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0) d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1) e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2) f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1) g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0) h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1) i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0) assert cg_simp( a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p) def test_cg_simp_sum(): x, a, b, c, cp, alpha, beta, gamma, gammap = symbols( 'x a b c cp alpha beta gamma gammap') # Varshalovich 8.7.1 Eq 1 assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a) )) == x*(2*a + 1)*KroneckerDelta(b, 0) assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0) assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6 # Varshalovich 8.7.1 Eq 2 assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0) assert cg_simp(3*Sum((-1)**(2 - alpha) * CG( 2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5) # Varshalovich 8.7.2 Eq 4 assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap) assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp) assert cg_simp(Sum(CG( a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1 assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap) def test_doit(): assert Wigner3j(1/2, -1/2, 1/2, 1/2, 0, 0).doit() == -sqrt(2)/2 assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105 assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105 assert Wigner9j( 2, 1, 1, S(3)/2, S(1)/2, 1, S(1)/2, S(1)/2, 0).doit() == sqrt(2)/12 assert CG(1/2, 1/2, 1/2, -1/2, 1, 0).doit() == sqrt(2)/2
8,623
47.449438
176
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_operatorordering.py
from sympy.physics.quantum import Dagger from sympy.physics.quantum.boson import BosonOp from sympy.physics.quantum.fermion import FermionOp from sympy.physics.quantum.operatorordering import (normal_order, normal_ordered_form) def test_normal_order(): a = BosonOp('a') b = BosonOp('b') c = FermionOp('c') d = FermionOp('d') assert normal_order(a * Dagger(a)) == Dagger(a) * a assert normal_order(Dagger(a) * a) == Dagger(a) * a assert normal_order(a * Dagger(a) ** 2) == Dagger(a) ** 2 * a assert normal_order(c * Dagger(c)) == - Dagger(c) * c assert normal_order(Dagger(c) * c) == Dagger(c) * c assert normal_order(c * Dagger(c) ** 2) == Dagger(c) ** 2 * c def test_normal_ordered_form(): a = BosonOp('a') b = BosonOp('b') c = FermionOp('c') d = FermionOp('d') assert normal_ordered_form(Dagger(a) * a) == Dagger(a) * a assert normal_ordered_form(a * Dagger(a)) == 1 + Dagger(a) * a assert normal_ordered_form(a ** 2 * Dagger(a)) == \ 2 * a + Dagger(a) * a ** 2 assert normal_ordered_form(a ** 3 * Dagger(a)) == \ 3 * a ** 2 + Dagger(a) * a ** 3 assert normal_ordered_form(Dagger(c) * c) == Dagger(c) * c assert normal_ordered_form(c * Dagger(c)) == 1 - Dagger(c) * c assert normal_ordered_form(c ** 2 * Dagger(c)) == Dagger(c) * c ** 2 assert normal_ordered_form(c ** 3 * Dagger(c)) == \ c ** 2 - Dagger(c) * c ** 3
1,490
33.674419
72
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/quantum/tests/test_circuitutils.py
from sympy import Symbol, Integer, Mul from sympy.utilities import numbered_symbols from sympy.physics.quantum.gate import X, Y, Z, H, CNOT, CGate from sympy.physics.quantum.identitysearch import bfs_identity_search from sympy.physics.quantum.circuitutils import (kmp_table, find_subcircuit, replace_subcircuit, convert_to_symbolic_indices, convert_to_real_indices, random_reduce, random_insert, flatten_ids) from sympy.utilities.pytest import slow def create_gate_sequence(qubit=0): gates = (X(qubit), Y(qubit), Z(qubit), H(qubit)) return gates def test_kmp_table(): word = ('a', 'b', 'c', 'd', 'a', 'b', 'd') expected_table = [-1, 0, 0, 0, 0, 1, 2] assert expected_table == kmp_table(word) word = ('P', 'A', 'R', 'T', 'I', 'C', 'I', 'P', 'A', 'T', 'E', ' ', 'I', 'N', ' ', 'P', 'A', 'R', 'A', 'C', 'H', 'U', 'T', 'E') expected_table = [-1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0] assert expected_table == kmp_table(word) x = X(0) y = Y(0) z = Z(0) h = H(0) word = (x, y, y, x, z) expected_table = [-1, 0, 0, 0, 1] assert expected_table == kmp_table(word) word = (x, x, y, h, z) expected_table = [-1, 0, 1, 0, 0] assert expected_table == kmp_table(word) def test_find_subcircuit(): x = X(0) y = Y(0) z = Z(0) h = H(0) x1 = X(1) y1 = Y(1) i0 = Symbol('i0') x_i0 = X(i0) y_i0 = Y(i0) z_i0 = Z(i0) h_i0 = H(i0) circuit = (x, y, z) assert find_subcircuit(circuit, (x,)) == 0 assert find_subcircuit(circuit, (x1,)) == -1 assert find_subcircuit(circuit, (y,)) == 1 assert find_subcircuit(circuit, (h,)) == -1 assert find_subcircuit(circuit, Mul(x, h)) == -1 assert find_subcircuit(circuit, Mul(x, y, z)) == 0 assert find_subcircuit(circuit, Mul(y, z)) == 1 assert find_subcircuit(Mul(*circuit), (x, y, z, h)) == -1 assert find_subcircuit(Mul(*circuit), (z, y, x)) == -1 assert find_subcircuit(circuit, (x,), start=2, end=1) == -1 circuit = (x, y, x, y, z) assert find_subcircuit(Mul(*circuit), Mul(x, y, z)) == 2 assert find_subcircuit(circuit, (x,), start=1) == 2 assert find_subcircuit(circuit, (x, y), start=1, end=2) == -1 assert find_subcircuit(Mul(*circuit), (x, y), start=1, end=3) == -1 assert find_subcircuit(circuit, (x, y), start=1, end=4) == 2 assert find_subcircuit(circuit, (x, y), start=2, end=4) == 2 circuit = (x, y, z, x1, x, y, z, h, x, y, x1, x, y, z, h, y1, h) assert find_subcircuit(circuit, (x, y, z, h, y1)) == 11 circuit = (x, y, x_i0, y_i0, z_i0, z) assert find_subcircuit(circuit, (x_i0, y_i0, z_i0)) == 2 circuit = (x_i0, y_i0, z_i0, x_i0, y_i0, h_i0) subcircuit = (x_i0, y_i0, z_i0) result = find_subcircuit(circuit, subcircuit) assert result == 0 def test_replace_subcircuit(): x = X(0) y = Y(0) z = Z(0) h = H(0) cnot = CNOT(1, 0) cgate_z = CGate((0,), Z(1)) # Standard cases circuit = (z, y, x, x) remove = (z, y, x) assert replace_subcircuit(circuit, Mul(*remove)) == (x,) assert replace_subcircuit(circuit, remove + (x,)) == () assert replace_subcircuit(circuit, remove, pos=1) == circuit assert replace_subcircuit(circuit, remove, pos=0) == (x,) assert replace_subcircuit(circuit, (x, x), pos=2) == (z, y) assert replace_subcircuit(circuit, (h,)) == circuit circuit = (x, y, x, y, z) remove = (x, y, z) assert replace_subcircuit(Mul(*circuit), Mul(*remove)) == (x, y) remove = (x, y, x, y) assert replace_subcircuit(circuit, remove) == (z,) circuit = (x, h, cgate_z, h, cnot) remove = (x, h, cgate_z) assert replace_subcircuit(circuit, Mul(*remove), pos=-1) == (h, cnot) assert replace_subcircuit(circuit, remove, pos=1) == circuit remove = (h, h) assert replace_subcircuit(circuit, remove) == circuit remove = (h, cgate_z, h, cnot) assert replace_subcircuit(circuit, remove) == (x,) replace = (h, x) actual = replace_subcircuit(circuit, remove, replace=replace) assert actual == (x, h, x) circuit = (x, y, h, x, y, z) remove = (x, y) replace = (cnot, cgate_z) actual = replace_subcircuit(circuit, remove, replace=Mul(*replace)) assert actual == (cnot, cgate_z, h, x, y, z) actual = replace_subcircuit(circuit, remove, replace=replace, pos=1) assert actual == (x, y, h, cnot, cgate_z, z) def test_convert_to_symbolic_indices(): (x, y, z, h) = create_gate_sequence() i0 = Symbol('i0') exp_map = {i0: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices((x,)) assert actual == (X(i0),) assert act_map == exp_map expected = (X(i0), Y(i0), Z(i0), H(i0)) exp_map = {i0: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h)) assert actual == expected assert exp_map == act_map (x1, y1, z1, h1) = create_gate_sequence(1) i1 = Symbol('i1') expected = (X(i0), Y(i0), Z(i0), H(i0)) exp_map = {i0: Integer(1)} actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, y1, z1, h1)) assert actual == expected assert act_map == exp_map expected = (X(i0), Y(i0), Z(i0), H(i0), X(i1), Y(i1), Z(i1), H(i1)) exp_map = {i0: Integer(0), i1: Integer(1)} actual, act_map, sndx, gen = convert_to_symbolic_indices((x, y, z, h, x1, y1, z1, h1)) assert actual == expected assert act_map == exp_map exp_map = {i0: Integer(1), i1: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x1, y1, z1, h1, x, y, z, h)) assert actual == expected assert act_map == exp_map expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1)) exp_map = {i0: Integer(0), i1: Integer(1)} actual, act_map, sndx, gen = convert_to_symbolic_indices(Mul(x, x1, y, y1, z, z1, h, h1)) assert actual == expected assert act_map == exp_map exp_map = {i0: Integer(1), i1: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices((x1, x, y1, y, z1, z, h1, h)) assert actual == expected assert act_map == exp_map cnot_10 = CNOT(1, 0) cnot_01 = CNOT(0, 1) cgate_z_10 = CGate(1, Z(0)) cgate_z_01 = CGate(0, Z(1)) expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1), CNOT(i1, i0), CNOT(i0, i1), CGate(i1, Z(i0)), CGate(i0, Z(i1))) exp_map = {i0: Integer(0), i1: Integer(1)} args = (x, x1, y, y1, z, z1, h, h1, cnot_10, cnot_01, cgate_z_10, cgate_z_01) actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map args = (x1, x, y1, y, z1, z, h1, h, cnot_10, cnot_01, cgate_z_10, cgate_z_01) expected = (X(i0), X(i1), Y(i0), Y(i1), Z(i0), Z(i1), H(i0), H(i1), CNOT(i0, i1), CNOT(i1, i0), CGate(i0, Z(i1)), CGate(i1, Z(i0))) exp_map = {i0: Integer(1), i1: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map args = (cnot_10, h, cgate_z_01, h) expected = (CNOT(i0, i1), H(i1), CGate(i1, Z(i0)), H(i1)) exp_map = {i0: Integer(1), i1: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map args = (cnot_01, h1, cgate_z_10, h1) exp_map = {i0: Integer(0), i1: Integer(1)} actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map args = (cnot_10, h1, cgate_z_01, h1) expected = (CNOT(i0, i1), H(i0), CGate(i1, Z(i0)), H(i0)) exp_map = {i0: Integer(1), i1: Integer(0)} actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map i2 = Symbol('i2') ccgate_z = CGate(0, CGate(1, Z(2))) ccgate_x = CGate(1, CGate(2, X(0))) args = (ccgate_z, ccgate_x) expected = (CGate(i0, CGate(i1, Z(i2))), CGate(i1, CGate(i2, X(i0)))) exp_map = {i0: Integer(0), i1: Integer(1), i2: Integer(2)} actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map ndx_map = {i0: Integer(0)} index_gen = numbered_symbols(prefix='i', start=1) actual, act_map, sndx, gen = convert_to_symbolic_indices(args, qubit_map=ndx_map, start=i0, gen=index_gen) assert actual == expected assert act_map == exp_map i3 = Symbol('i3') cgate_x0_c321 = CGate((3, 2, 1), X(0)) exp_map = {i0: Integer(3), i1: Integer(2), i2: Integer(1), i3: Integer(0)} expected = (CGate((i0, i1, i2), X(i3)),) args = (cgate_x0_c321,) actual, act_map, sndx, gen = convert_to_symbolic_indices(args) assert actual == expected assert act_map == exp_map def test_convert_to_real_indices(): i0 = Symbol('i0') i1 = Symbol('i1') (x, y, z, h) = create_gate_sequence() x_i0 = X(i0) y_i0 = Y(i0) z_i0 = Z(i0) qubit_map = {i0: 0} args = (z_i0, y_i0, x_i0) expected = (z, y, x) actual = convert_to_real_indices(args, qubit_map) assert actual == expected cnot_10 = CNOT(1, 0) cnot_01 = CNOT(0, 1) cgate_z_10 = CGate(1, Z(0)) cgate_z_01 = CGate(0, Z(1)) cnot_i1_i0 = CNOT(i1, i0) cnot_i0_i1 = CNOT(i0, i1) cgate_z_i1_i0 = CGate(i1, Z(i0)) qubit_map = {i0: 0, i1: 1} args = (cnot_i1_i0,) expected = (cnot_10,) actual = convert_to_real_indices(args, qubit_map) assert actual == expected args = (cgate_z_i1_i0,) expected = (cgate_z_10,) actual = convert_to_real_indices(args, qubit_map) assert actual == expected args = (cnot_i0_i1,) expected = (cnot_01,) actual = convert_to_real_indices(args, qubit_map) assert actual == expected qubit_map = {i0: 1, i1: 0} args = (cgate_z_i1_i0,) expected = (cgate_z_01,) actual = convert_to_real_indices(args, qubit_map) assert actual == expected i2 = Symbol('i2') ccgate_z = CGate(i0, CGate(i1, Z(i2))) ccgate_x = CGate(i1, CGate(i2, X(i0))) qubit_map = {i0: 0, i1: 1, i2: 2} args = (ccgate_z, ccgate_x) expected = (CGate(0, CGate(1, Z(2))), CGate(1, CGate(2, X(0)))) actual = convert_to_real_indices(Mul(*args), qubit_map) assert actual == expected qubit_map = {i0: 1, i2: 0, i1: 2} args = (ccgate_x, ccgate_z) expected = (CGate(2, CGate(0, X(1))), CGate(1, CGate(2, Z(0)))) actual = convert_to_real_indices(args, qubit_map) assert actual == expected @slow def test_random_reduce(): x = X(0) y = Y(0) z = Z(0) h = H(0) cnot = CNOT(1, 0) cgate_z = CGate((0,), Z(1)) gate_list = [x, y, z] ids = list(bfs_identity_search(gate_list, 1, max_depth=4)) circuit = (x, y, h, z, cnot) assert random_reduce(circuit, []) == circuit assert random_reduce(circuit, ids) == circuit seq = [2, 11, 9, 3, 5] circuit = (x, y, z, x, y, h) assert random_reduce(circuit, ids, seed=seq) == (x, y, h) circuit = (x, x, y, y, z, z) assert random_reduce(circuit, ids, seed=seq) == (x, x, y, y) seq = [14, 13, 0] assert random_reduce(circuit, ids, seed=seq) == (y, y, z, z) gate_list = [x, y, z, h, cnot, cgate_z] ids = list(bfs_identity_search(gate_list, 2, max_depth=4)) seq = [25] circuit = (x, y, z, y, h, y, h, cgate_z, h, cnot) expected = (x, y, z, cgate_z, h, cnot) assert random_reduce(circuit, ids, seed=seq) == expected circuit = Mul(*circuit) assert random_reduce(circuit, ids, seed=seq) == expected @slow def test_random_insert(): x = X(0) y = Y(0) z = Z(0) h = H(0) cnot = CNOT(1, 0) cgate_z = CGate((0,), Z(1)) choices = [(x, x)] circuit = (y, y) loc, choice = 0, 0 actual = random_insert(circuit, choices, seed=[loc, choice]) assert actual == (x, x, y, y) circuit = (x, y, z, h) choices = [(h, h), (x, y, z)] expected = (x, x, y, z, y, z, h) loc, choice = 1, 1 actual = random_insert(circuit, choices, seed=[loc, choice]) assert actual == expected gate_list = [x, y, z, h, cnot, cgate_z] ids = list(bfs_identity_search(gate_list, 2, max_depth=4)) eq_ids = flatten_ids(ids) circuit = (x, y, h, cnot, cgate_z) expected = (x, z, x, z, x, y, h, cnot, cgate_z) loc, choice = 1, 30 actual = random_insert(circuit, eq_ids, seed=[loc, choice]) assert actual == expected circuit = Mul(*circuit) actual = random_insert(circuit, eq_ids, seed=[loc, choice]) assert actual == expected
13,121
31.723192
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/rigidbody.py
# -*- encoding: utf-8 -*- from __future__ import print_function, division from sympy.core.backend import sympify from sympy.physics.vector import Point, ReferenceFrame, Dyadic __all__ = ['RigidBody'] class RigidBody(object): """An idealized rigid body. This is essentially a container which holds the various components which describe a rigid body: a name, mass, center of mass, reference frame, and inertia. All of these need to be supplied on creation, but can be changed afterwards. Attributes ========== name : string The body's name. masscenter : Point The point which represents the center of mass of the rigid body. frame : ReferenceFrame The ReferenceFrame which the rigid body is fixed in. mass : Sympifyable The body's mass. inertia : (Dyadic, Point) The body's inertia about a point; stored in a tuple as shown above. Examples ======== >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody >>> from sympy.physics.mechanics import outer >>> m = Symbol('m') >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer (A.x, A.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, A, m, inertia_tuple) >>> # Or you could change them afterwards >>> m2 = Symbol('m2') >>> B.mass = m2 """ def __init__(self, name, masscenter, frame, mass, inertia): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.masscenter = masscenter self.mass = mass self.frame = frame self.inertia = inertia self.potential_energy = 0 def __str__(self): return self._name __repr__ = __str__ @property def frame(self): return self._frame @frame.setter def frame(self, F): if not isinstance(F, ReferenceFrame): raise TypeError("RigdBody frame must be a ReferenceFrame object.") self._frame = F @property def masscenter(self): return self._masscenter @masscenter.setter def masscenter(self, p): if not isinstance(p, Point): raise TypeError("RigidBody center of mass must be a Point object.") self._masscenter = p @property def mass(self): return self._mass @mass.setter def mass(self, m): self._mass = sympify(m) @property def inertia(self): return (self._inertia, self._inertia_point) @inertia.setter def inertia(self, I): if not isinstance(I[0], Dyadic): raise TypeError("RigidBody inertia must be a Dyadic object.") if not isinstance(I[1], Point): raise TypeError("RigidBody inertia must be about a Point.") self._inertia = I[0] self._inertia_point = I[1] # have I S/O, want I S/S* # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O # I_S/S* = I_S/O - I_S*/O from sympy.physics.mechanics.functions import inertia_of_point_mass I_Ss_O = inertia_of_point_mass(self.mass, self.masscenter.pos_from(I[1]), self.frame) self._central_inertia = I[0] - I_Ss_O @property def central_inertia(self): """The body's central inertia dyadic.""" return self._central_inertia def linear_momentum(self, frame): """ Linear momentum of the rigid body. The linear momentum L, of a rigid body B, with respect to frame N is given by L = M * v* where M is the mass of the rigid body and v* is the velocity of the mass center of B in the frame, N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> M, v = dynamicsymbols('M v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (N.x, N.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, N, M, Inertia_tuple) >>> B.linear_momentum(N) M*v*N.x """ return self.mass * self.masscenter.vel(frame) def angular_momentum(self, point, frame): """Returns the angular momentum of the rigid body about a point in the given frame. The angular momentum H of a rigid body B about some point O in a frame N is given by: H = I·w + r×Mv where I is the central inertia dyadic of B, w is the angular velocity of body B in the frame, N, r is the position vector from point O to the mass center of B, and v is the velocity of the mass center in the frame, N. Parameters ========== point : Point The point about which angular momentum is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> M, v, r, omega = dynamicsymbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, 1 * N.x) >>> I = outer(b.x, b.x) >>> B = RigidBody('B', P, b, M, (I, P)) >>> B.angular_momentum(P, N) omega*b.x """ I = self.central_inertia w = self.frame.ang_vel_in(frame) m = self.mass r = self.masscenter.pos_from(point) v = self.masscenter.vel(frame) return I.dot(w) + r.cross(m * v) def kinetic_energy(self, frame): """Kinetic energy of the rigid body The kinetic energy, T, of a rigid body, B, is given by 'T = 1/2 (I omega^2 + m v^2)' where I and m are the central inertia dyadic and mass of rigid body B, respectively, omega is the body's angular velocity and v is the velocity of the body's mass center in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The RigidBody's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody >>> from sympy import symbols >>> M, v, r, omega = symbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (b.x, b.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, inertia_tuple) >>> B.kinetic_energy(N) M*v**2/2 + omega**2/2 """ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia & self.frame.ang_vel_in(frame)) / sympify(2)) translational_KE = (self.mass * (self.masscenter.vel(frame) & self.masscenter.vel(frame)) / sympify(2)) return rotational_KE + translational_KE @property def potential_energy(self): """The potential energy of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame >>> from sympy import symbols >>> M, g, h = symbols('M g h') >>> b = ReferenceFrame('b') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h >>> B.potential_energy M*g*h """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of this RigidBody. Parameters ========== scalar: Sympifyable The potential energy (a scalar) of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, outer >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame >>> from sympy import symbols >>> b = ReferenceFrame('b') >>> M, g, h = symbols('M g h') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h """ self._pe = sympify(scalar)
9,084
29.384615
87
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/system.py
from sympy.core.backend import eye, Matrix, zeros from sympy.physics.mechanics import dynamicsymbols from sympy.physics.mechanics.functions import find_dynamicsymbols __all__ = ['SymbolicSystem'] class SymbolicSystem(object): """SymbolicSystem is a class that contains all the information about a system in a symbolic format such as the equations of motions and the bodies and loads in the system. There are three ways that the equations of motion can be described for Symbolic System: [1] Explicit form where the kinematics and dynamics are combined x' = F_1(x, t, r, p) [2] Implicit form where the kinematics and dynamics are combined M_2(x, p) x' = F_2(x, t, r, p) [3] Implicit form where the kinematics and dynamics are separate M_3(q, p) u' = F_3(q, u, t, r, p) q' = G(q, u, t, r, p) where x : states, e.g. [q, u] t : time r : specified (exogenous) inputs p : constants q : generalized coordinates u : generalized speeds F_1 : right hand side of the combined equations in explicit form F_2 : right hand side of the combined equations in implicit form F_3 : right hand side of the dynamical equations in implicit form M_2 : mass matrix of the combined equations in implicit form M_3 : mass matrix of the dynamical equations in implicit form G : right hand side of the kinematical differential equations Parameters ========== coord_states : ordered iterable of functions of time This input will either be a collection of the coordinates or states of the system depending on whether or not the speeds are also given. If speeds are specified this input will be assumed to be the coordinates otherwise this input will be assumed to be the states. right_hand_side : Matrix This variable is the right hand side of the equations of motion in any of the forms. The specific form will be assumed depending on whether a mass matrix or coordinate derivatives are given. speeds : ordered iterable of functions of time, optional This is a collection of the generalized speeds of the system. If given it will be assumed that the first argument (coord_states) will represent the generalized coordinates of the system. mass_matrix : Matrix, optional The matrix of the implicit forms of the equations of motion (forms [2] and [3]). The distinction between the forms is determined by whether or not the coordinate derivatives are passed in. If they are given form [3] will be assumed otherwise form [2] is assumed. coordinate_derivatives : Matrix, optional The right hand side of the kinematical equations in explicit form. If given it will be assumed that the equations of motion are being entered in form [3]. alg_con : Iterable, optional The indexes of the rows in the equations of motion that contain algebraic constraints instead of differential equations. If the equations are input in form [3], it will be assumed the indexes are referencing the mass_matrix/right_hand_side combination and not the coordinate_derivatives. output_eqns : Dictionary, optional Any output equations that are desired to be tracked are stored in a dictionary where the key corresponds to the name given for the specific equation and the value is the equation itself in symbolic form coord_idxs : Iterable, optional If coord_states corresponds to the states rather than the coordinates this variable will tell SymbolicSystem which indexes of the states correspond to generalized coordinates. speed_idxs : Iterable, optional If coord_states corresponds to the states rather than the coordinates this variable will tell SymbolicSystem which indexes of the states correspond to generalized speeds. bodies : iterable of Body/Rigidbody objects, optional Iterable containing the bodies of the system loads : iterable of load instances (described below), optional Iterable containing the loads of the system where forces are given by (point of application, force vector) and torques are given by (reference frame acting upon, torque vector). Ex [(point, force), (ref_frame, torque)] Attributes ========== coordinates : Matrix, shape(n, 1) This is a matrix containing the generalized coordinates of the system speeds : Matrix, shape(m, 1) This is a matrix containing the generalized speeds of the system states : Matrix, shape(o, 1) This is a matrix containing the state variables of the system alg_con : List This list contains the indices of the algebraic constraints in the combined equations of motion. The presence of these constraints requires that a DAE solver be used instead of an ODE solver. If the system is given in form [3] the alg_con variable will be adjusted such that it is a representation of the combined kinematics and dynamics thus make sure it always matches the mass matrix entered. dyn_implicit_mat : Matrix, shape(m, m) This is the M matrix in form [3] of the equations of motion (the mass matrix or generalized inertia matrix of the dynamical equations of motion in implicit form). dyn_implicit_rhs : Matrix, shape(m, 1) This is the F vector in form [3] of the equations of motion (the right hand side of the dynamical equations of motion in implicit form). comb_implicit_mat : Matrix, shape(o, o) This is the M matrix in form [2] of the equations of motion. This matrix contains a block diagonal structure where the top left block (the first rows) represent the matrix in the implicit form of the kinematical equations and the bottom right block (the last rows) represent the matrix in the implicit form of the dynamical equations. comb_implicit_rhs : Matrix, shape(o, 1) This is the F vector in form [2] of the equations of motion. The top part of the vector represents the right hand side of the implicit form of the kinemaical equations and the bottom of the vector represents the right hand side of the implicit form of the dynamical equations of motion. comb_explicit_rhs : Matrix, shape(o, 1) This vector represents the right hand side of the combined equations of motion in explicit form (form [1] from above). kin_explicit_rhs : Matrix, shape(m, 1) This is the right hand side of the explicit form of the kinematical equations of motion as can be seen in form [3] (the G matrix). output_eqns : Dictionary If output equations were given they are stored in a dictionary where the key corresponds to the name given for the specific equation and the value is the equation itself in symbolic form bodies : Tuple If the bodies in the system were given they are stored in a tuple for future access loads : Tuple If the loads in the system were given they are stored in a tuple for future access. This includes forces and torques where forces are given by (point of application, force vector) and torques are given by (reference frame acted upon, torque vector). Example ======= As a simple example, the dynamics of a simple pendulum will be input into a SymbolicSystem object manually. First some imports will be needed and then symbols will be set up for the length of the pendulum (l), mass at the end of the pendulum (m), and a constant for gravity (g). :: >>> from sympy import Matrix, sin, symbols >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem >>> l, m, g = symbols('l m g') The system will be defined by an angle of theta from the vertical and a generalized speed of omega will be used where omega = theta_dot. :: >>> theta, omega = dynamicsymbols('theta omega') Now the equations of motion are ready to be formed and passed to the SymbolicSystem object. :: >>> kin_explicit_rhs = Matrix([omega]) >>> dyn_implicit_mat = Matrix([l**2 * m]) >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)]) >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega], ... dyn_implicit_mat) Notes ===== m : number of generalized speeds n : number of generalized coordinates o : number of states """ def __init__(self, coord_states, right_hand_side, speeds=None, mass_matrix=None, coordinate_derivatives=None, alg_con=None, output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None, loads=None): """Initializes a SymbolicSystem object""" # Extract information on speeds, coordinates and states if speeds is None: self._states = Matrix(coord_states) if coord_idxs is None: self._coordinates = None else: coords = [coord_states[i] for i in coord_idxs] self._coordinates = Matrix(coords) if speed_idxs is None: self._speeds = None else: speeds_inter = [coord_states[i] for i in speed_idxs] self._speeds = Matrix(speeds_inter) else: self._coordinates = Matrix(coord_states) self._speeds = Matrix(speeds) self._states = self._coordinates.col_join(self._speeds) # Extract equations of motion form if coordinate_derivatives is not None: self._kin_explicit_rhs = coordinate_derivatives self._dyn_implicit_rhs = right_hand_side self._dyn_implicit_mat = mass_matrix self._comb_implicit_rhs = None self._comb_implicit_mat = None self._comb_explicit_rhs = None elif mass_matrix is not None: self._kin_explicit_rhs = None self._dyn_implicit_rhs = None self._dyn_implicit_mat = None self._comb_implicit_rhs = right_hand_side self._comb_implicit_mat = mass_matrix self._comb_explicit_rhs = None else: self._kin_explicit_rhs = None self._dyn_implicit_rhs = None self._dyn_implicit_mat = None self._comb_implicit_rhs = None self._comb_implicit_mat = None self._comb_explicit_rhs = right_hand_side # Set the remainder of the inputs as instance attributes if alg_con is not None and coordinate_derivatives is not None: alg_con = [i + len(coordinate_derivatives) for i in alg_con] self._alg_con = alg_con self.output_eqns = output_eqns # Change the body and loads iterables to tuples if they are not tuples # already if type(bodies) != tuple and bodies is not None: bodies = tuple(bodies) if type(loads) != tuple and loads is not None: loads = tuple(loads) self._bodies = bodies self._loads = loads @property def coordinates(self): """Returns the column matrix of the generalized coordinates""" if self._coordinates is None: raise AttributeError("The coordinates were not specified.") else: return self._coordinates @property def speeds(self): """Returns the column matrix of generalized speeds""" if self._speeds is None: raise AttributeError("The speeds were not specified.") else: return self._speeds @property def states(self): """Returns the column matrix of the state variables""" return self._states @property def alg_con(self): """Returns a list with the indices of the rows containing algebraic constraints in the combined form of the equations of motion""" return self._alg_con @property def dyn_implicit_mat(self): """Returns the matrix, M, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not included""" if self._dyn_implicit_mat is None: raise AttributeError("dyn_implicit_mat is not specified for " "equations of motion form [1] or [2].") else: return self._dyn_implicit_mat @property def dyn_implicit_rhs(self): """Returns the column matrix, F, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not included""" if self._dyn_implicit_rhs is None: raise AttributeError("dyn_implicit_rhs is not specified for " "equations of motion form [1] or [2].") else: return self._dyn_implicit_rhs @property def comb_implicit_mat(self): """Returns the matrix, M, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are included""" if self._comb_implicit_mat is None: if self._dyn_implicit_mat is not None: num_kin_eqns = len(self._kin_explicit_rhs) num_dyn_eqns = len(self._dyn_implicit_rhs) zeros1 = zeros(num_kin_eqns, num_dyn_eqns) zeros2 = zeros(num_dyn_eqns, num_kin_eqns) inter1 = eye(num_kin_eqns).row_join(zeros1) inter2 = zeros2.row_join(self._dyn_implicit_mat) self._comb_implicit_mat = inter1.col_join(inter2) return self._comb_implicit_mat else: raise AttributeError("comb_implicit_mat is not specified for " "equations of motion form [1].") else: return self._comb_implicit_mat @property def comb_implicit_rhs(self): """Returns the column matrix, F, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are included""" if self._comb_implicit_rhs is None: if self._dyn_implicit_rhs is not None: kin_inter = self._kin_explicit_rhs dyn_inter = self._dyn_implicit_rhs self._comb_implicit_rhs = kin_inter.col_join(dyn_inter) return self._comb_implicit_rhs else: raise AttributeError("comb_implicit_mat is not specified for " "equations of motion in form [1].") else: return self._comb_implicit_rhs def compute_explicit_form(self): """If the explicit right hand side of the combined equations of motion is to provided upon initialization, this method will calculate it. This calculation can potentially take awhile to compute.""" if self._comb_explicit_rhs is not None: raise AttributeError("comb_explicit_rhs is already formed.") else: try: inter1 = self.kin_explicit_rhs inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs) out = inter1.col_join(inter2) except AttributeError: out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs) self._comb_explicit_rhs = out @property def comb_explicit_rhs(self): """Returns the right hand side of the equations of motion in explicit form, x' = F, where the kinematical equations are included""" if self._comb_explicit_rhs is None: raise AttributeError("Please run .combute_explicit_form before " "attempting to access comb_explicit_rhs.") else: return self._comb_explicit_rhs @property def kin_explicit_rhs(self): """Returns the right hand side of the kinematical equations in explicit form, q' = G""" if self._kin_explicit_rhs is None: raise AttributeError("kin_explicit_rhs is not specified for " "equations of motion form [1] or [2].") else: return self._kin_explicit_rhs def dynamic_symbols(self): """Returns a column matrix containing all of the symbols in the system that depend on time""" # Create a list of all of the expressions in the equations of motion if self._comb_explicit_rhs is None: eom_expressions = (self.comb_implicit_mat[:] + self.comb_implicit_rhs[:]) else: eom_expressions = (self._comb_explicit_rhs[:]) functions_of_time = set() for expr in eom_expressions: functions_of_time = functions_of_time.union( find_dynamicsymbols(expr)) functions_of_time = functions_of_time.union(self._states) return tuple(functions_of_time) def constant_symbols(self): """Returns a column matrix containing all of the symbols in the system that do not depend on time""" # Create a list of all of the expressions in the equations of motion if self._comb_explicit_rhs is None: eom_expressions = (self.comb_implicit_mat[:] + self.comb_implicit_rhs[:]) else: eom_expressions = (self._comb_explicit_rhs[:]) constants = set() for expr in eom_expressions: constants = constants.union(expr.free_symbols) constants.remove(dynamicsymbols._t) return tuple(constants) @property def bodies(self): """Returns the bodies in the system""" if self._bodies is None: raise AttributeError("bodies were not specified for the system.") else: return self._bodies @property def loads(self): """Returns the loads in the system""" if self._loads is None: raise AttributeError("loads were not specified for the system.") else: return self._loads
18,685
40.896861
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/lagrange.py
from __future__ import print_function, division from sympy.core.backend import diff, zeros, Matrix, eye, sympify from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.physics.mechanics.functions import (find_dynamicsymbols, msubs, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities import default_sort_key from sympy.utilities.iterables import iterable __all__ = ['LagrangesMethod'] class LagrangesMethod(object): """Lagrange's method object. This object generates the equations of motion in a two step procedure. The first step involves the initialization of LagrangesMethod by supplying the Lagrangian and the generalized coordinates, at the bare minimum. If there are any constraint equations, they can be supplied as keyword arguments. The Lagrange multipliers are automatically generated and are equal in number to the constraint equations. Similarly any non-conservative forces can be supplied in an iterable (as described below and also shown in the example) along with a ReferenceFrame. This is also discussed further in the __init__ method. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. bodies : iterable Iterable containing the rigid bodies and particles of the system. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the qdot's, qdoubledot's, and the lagrange multipliers (lam) forcing_full : Matrix The forcing vector for the qdot's, qdoubledot's and lagrange multipliers (lam) Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point >>> from sympy.physics.mechanics import dynamicsymbols, kinetic_energy >>> from sympy import symbols >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, qd * N.x) We need to then prepare the information as required by LagrangesMethod to generate equations of motion. First we create the Particle, which has a point attached to it. Following this the lagrangian is created from the kinetic and potential energies. Then, an iterable of nonconservative forces/torques must be constructed, where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, with the Vectors representing the nonconservative forces or torques. >>> Pa = Particle('Pa', P, m) >>> Pa.potential_energy = k * q**2 / 2.0 >>> L = Lagrangian(N, Pa) >>> fl = [(P, -b * qd * N.x)] Finally we can generate the equations of motion. First we create the LagrangesMethod object. To do this one must supply the Lagrangian, and the generalized coordinates. The constraint equations, the forcelist, and the inertial frame may also be provided, if relevant. Next we generate Lagrange's equations of motion, such that: Lagrange's equations of motion = 0. We have the equations of motion at this point. >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) >>> print(l.form_lagranges_equations()) Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), t, t)]]) We can also solve for the states using the 'rhs' method. >>> print(l.rhs()) Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) Please refer to the docstrings on each method for more details. """ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, hol_coneqs=None, nonhol_coneqs=None): """Supply the following for the initialization of LagrangesMethod Lagrangian : Sympifyable qs : array_like The generalized coordinates hol_coneqs : array_like, optional The holonomic constraint equations nonhol_coneqs : array_like, optional The nonholonomic constraint equations forcelist : iterable, optional Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. This feature is primarily to account for the nonconservative forces and/or moments. bodies : iterable, optional Takes an iterable containing the rigid bodies and particles of the system. frame : ReferenceFrame, optional Supply the inertial frame. This is used to determine the generalized forces due to non-conservative forces. """ self._L = Matrix([sympify(Lagrangian)]) self.eom = None self._m_cd = Matrix() # Mass Matrix of differentiated coneqs self._m_d = Matrix() # Mass Matrix of dynamic equations self._f_cd = Matrix() # Forcing part of the diff coneqs self._f_d = Matrix() # Forcing part of the dynamic equations self.lam_coeffs = Matrix() # The coeffecients of the multipliers forcelist = forcelist if forcelist else [] if not iterable(forcelist): raise TypeError('Force pairs must be supplied in an iterable.') self._forcelist = forcelist if frame and not isinstance(frame, ReferenceFrame): raise TypeError('frame must be a valid ReferenceFrame') self._bodies = bodies self.inertial = frame self.lam_vec = Matrix() self._term1 = Matrix() self._term2 = Matrix() self._term3 = Matrix() self._term4 = Matrix() # Creating the qs, qdots and qdoubledots if not iterable(qs): raise TypeError('Generalized coordinates must be an iterable') self._q = Matrix(qs) self._qdots = self.q.diff(dynamicsymbols._t) self._qdoubledots = self._qdots.diff(dynamicsymbols._t) mat_build = lambda x: Matrix(x) if x else Matrix() hol_coneqs = mat_build(hol_coneqs) nonhol_coneqs = mat_build(nonhol_coneqs) self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), nonhol_coneqs]) self._hol_coneqs = hol_coneqs def form_lagranges_equations(self): """Method to form Lagrange's equations of motion. Returns a vector of equations of motion using Lagrange's equations of the second kind. """ qds = self._qdots qdd_zero = dict((i, 0) for i in self._qdoubledots) n = len(self.q) # Internally we represent the EOM as four terms: # EOM = term1 - term2 - term3 - term4 = 0 # First term self._term1 = self._L.jacobian(qds) self._term1 = self._term1.diff(dynamicsymbols._t).T # Second term self._term2 = self._L.jacobian(self.q).T # Third term if self.coneqs: coneqs = self.coneqs m = len(coneqs) # Creating the multipliers self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) self.lam_coeffs = -coneqs.jacobian(qds) self._term3 = self.lam_coeffs.T * self.lam_vec # Extracting the coeffecients of the qdds from the diff coneqs diffconeqs = coneqs.diff(dynamicsymbols._t) self._m_cd = diffconeqs.jacobian(self._qdoubledots) # The remaining terms i.e. the 'forcing' terms in diff coneqs self._f_cd = -diffconeqs.subs(qdd_zero) else: self._term3 = zeros(n, 1) # Fourth term if self.forcelist: N = self.inertial self._term4 = zeros(n, 1) for i, qd in enumerate(qds): flist = zip(*_f_list_parser(self.forcelist, N)) self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) else: self._term4 = zeros(n, 1) # Form the dynamic mass and forcing matrices without_lam = self._term1 - self._term2 - self._term4 self._m_d = without_lam.jacobian(self._qdoubledots) self._f_d = -without_lam.subs(qdd_zero) # Form the EOM self.eom = without_lam - self._term3 return self.eom @property def mass_matrix(self): """Returns the mass matrix, which is augmented by the Lagrange multipliers, if necessary. If the system is described by 'n' generalized coordinates and there are no constraint equations then an n X n matrix is returned. If there are 'n' generalized coordinates and 'm' constraint equations have been supplied during initialization then an n X (n+m) matrix is returned. The (n + m - 1)th and (n + m)th columns contain the coefficients of the Lagrange multipliers. """ if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return (self._m_d).row_join(self.lam_coeffs.T) else: return self._m_d @property def mass_matrix_full(self): """Augments the coefficients of qdots to the mass_matrix.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') n = len(self.q) m = len(self.coneqs) row1 = eye(n).row_join(zeros(n, n + m)) row2 = zeros(n, n).row_join(self.mass_matrix) if self.coneqs: row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) return row1.col_join(row2).col_join(row3) else: return row1.col_join(row2) @property def forcing(self): """Returns the forcing vector from 'lagranges_equations' method.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') return self._f_d @property def forcing_full(self): """Augments qdots to the forcing vector above.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return self._qdots.col_join(self.forcing).col_join(self._f_cd) else: return self._qdots.col_join(self.forcing) def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): """Returns an instance of the Linearizer class, initiated from the data in the LagrangesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points). Parameters ========== q_ind, qd_ind : array_like, optional The independent generalized coordinates and speeds. q_dep, qd_dep : array_like, optional The dependent generalized coordinates and speeds. """ # Compose vectors t = dynamicsymbols._t q = self.q u = self._qdots ud = u.diff(t) # Get vector of lagrange multipliers lams = self.lam_vec mat_build = lambda x: Matrix(x) if x else Matrix() q_i = mat_build(q_ind) q_d = mat_build(q_dep) u_i = mat_build(qd_ind) u_d = mat_build(qd_dep) # Compose general form equations f_c = self._hol_coneqs f_v = self.coneqs f_a = f_v.diff(t) f_0 = u f_1 = -u f_2 = self._term1 f_3 = -(self._term2 + self._term4) f_4 = -self._term3 # Check that there are an appropriate number of independent and # dependent coordinates if len(q_d) != len(f_c) or len(u_d) != len(f_v): raise ValueError(("Must supply {:} dependent coordinates, and " + "{:} dependent speeds").format(len(f_c), len(f_v))) if set(Matrix([q_i, q_d])) != set(q): raise ValueError("Must partition q into q_ind and q_dep, with " + "no extra or missing symbols.") if set(Matrix([u_i, u_d])) != set(u): raise ValueError("Must partition qd into qd_ind and qd_dep, " + "with no extra or missing symbols.") # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. insyms = set(Matrix([q, u, ud, lams])) r = list(find_dynamicsymbols(f_3, insyms)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r, lams) def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, **kwargs): """Linearize the equations of motion about a symbolic operating point. If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numberic or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def solve_multipliers(self, op_point=None, sol_type='dict'): """Solves for the values of the lagrange multipliers symbolically at the specified operating point Parameters ========== op_point : dict or iterable of dicts, optional Point at which to solve at. The operating point is specified as a dictionary or iterable of dictionaries of {symbol: value}. The value may be numeric or symbolic itself. sol_type : str, optional Solution return type. Valid options are: - 'dict': A dict of {symbol : value} (default) - 'Matrix': An ordered column matrix of the solution """ # Determine number of multipliers k = len(self.lam_vec) if k == 0: raise ValueError("System has no lagrange multipliers to solve for.") # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif iterable(op_point): op_point_dict = {} for op in op_point: op_point_dict.update(op) elif op_point is None: op_point_dict = {} else: raise TypeError("op_point must be either a dictionary or an " "iterable of dictionaries.") # Compose the system to be solved mass_matrix = self.mass_matrix.col_join((-self.lam_coeffs.row_join( zeros(k, k)))) force_matrix = self.forcing.col_join(self._f_cd) # Sub in the operating point mass_matrix = msubs(mass_matrix, op_point_dict) force_matrix = msubs(force_matrix, op_point_dict) # Solve for the multipliers sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] if sol_type == 'dict': return dict(zip(self.lam_vec, sol_list)) elif sol_type == 'Matrix': return Matrix(sol_list) else: raise ValueError("Unknown sol_type {:}.".format(sol_type)) def rhs(self, inv_method=None, **kwargs): """Returns equations that can be solved numerically Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ if inv_method is None: self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) else: self._rhs = (self.mass_matrix_full.inv(inv_method, try_block_diag=True) * self.forcing_full) return self._rhs @property def q(self): return self._q @property def u(self): return self._qdots @property def bodies(self): return self._bodies @property def forcelist(self): return self._forcelist
18,077
38.3
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/functions.py
from __future__ import print_function, division from sympy.utilities import dict_merge from sympy.utilities.iterables import iterable from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, Point, dynamicsymbols) from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, init_vprinting) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy import simplify from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, tan, AppliedUndef, S) __all__ = ['inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols'] # These are functions that we've moved and renamed during extracting the # basic vector calculus code from the mechanics packages. mprint = vprint msprint = vsprint mpprint = vpprint mlatex = vlatex def mechanics_printing(**kwargs): """ Initializes time derivative printing for all SymPy objects in mechanics module. """ init_vprinting(**kwargs) mechanics_printing.__doc__ = init_vprinting.__doc__ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): """Simple way to create inertia Dyadic object. If you don't know what a Dyadic is, just treat this like the inertia tensor. Then, do the easy thing and define it in a body-fixed frame. Parameters ========== frame : ReferenceFrame The frame the inertia is defined in ixx : Sympifyable the xx element in the inertia dyadic iyy : Sympifyable the yy element in the inertia dyadic izz : Sympifyable the zz element in the inertia dyadic ixy : Sympifyable the xy element in the inertia dyadic iyz : Sympifyable the yz element in the inertia dyadic izx : Sympifyable the zx element in the inertia dyadic Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, inertia >>> N = ReferenceFrame('N') >>> inertia(N, 1, 2, 3) (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) """ if not isinstance(frame, ReferenceFrame): raise TypeError('Need to define the inertia in a frame') ol = sympify(ixx) * (frame.x | frame.x) ol += sympify(ixy) * (frame.x | frame.y) ol += sympify(izx) * (frame.x | frame.z) ol += sympify(ixy) * (frame.y | frame.x) ol += sympify(iyy) * (frame.y | frame.y) ol += sympify(iyz) * (frame.y | frame.z) ol += sympify(izx) * (frame.z | frame.x) ol += sympify(iyz) * (frame.z | frame.y) ol += sympify(izz) * (frame.z | frame.z) return ol def inertia_of_point_mass(mass, pos_vec, frame): """Inertia dyadic of a point mass relative to point O. Parameters ========== mass : Sympifyable Mass of the point mass pos_vec : Vector Position from point O to point mass frame : ReferenceFrame Reference frame to express the dyadic in Examples ======== >>> from sympy import symbols >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass >>> N = ReferenceFrame('N') >>> r, m = symbols('r m') >>> px = r * N.x >>> inertia_of_point_mass(m, px, N) m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) """ return mass * (((frame.x | frame.x) + (frame.y | frame.y) + (frame.z | frame.z)) * (pos_vec & pos_vec) - (pos_vec | pos_vec)) def linear_momentum(frame, *body): """Linear momentum of the system. This function returns the linear momentum of a system of Particle's and/or RigidBody's. The linear momentum of a system is equal to the vector sum of the linear momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The linear momentum of the system, L, is equal to the vector sum of the linear momentum of the particle, L1, and the linear momentum of the rigid body, L2, i.e. L = L1 + L2 Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose linear momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = Point('Ac') >>> Ac.set_vel(N, 25 * N.y) >>> I = outer(N.x, N.x) >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) >>> linear_momentum(N, A, Pa) 10*N.x + 500*N.y """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please specify a valid ReferenceFrame') else: linear_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): linear_momentum_sys += e.linear_momentum(frame) else: raise TypeError('*body must have only Particle or RigidBody') return linear_momentum_sys def angular_momentum(point, frame, *body): """Angular momentum of a system This function returns the angular momentum of a system of Particle's and/or RigidBody's. The angular momentum of such a system is equal to the vector sum of the angular momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The angular momentum of the system, H, is equal to the vector sum of the angular momentum of the particle, H1, and the angular momentum of the rigid body, H2, i.e. H = H1 + H2 Parameters ========== point : Point The point about which angular momentum of the system is desired. frame : ReferenceFrame The frame in which angular momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose angular momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> angular_momentum(O, N, Pa, A) 10*N.z """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') if not isinstance(point, Point): raise TypeError('Please specify a valid Point') else: angular_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): angular_momentum_sys += e.angular_momentum(point, frame) else: raise TypeError('*body must have only Particle or RigidBody') return angular_momentum_sys def kinetic_energy(frame, *body): """Kinetic energy of a multibody system. This function returns the kinetic energy of a system of Particle's and/or RigidBody's. The kinetic energy of such a system is equal to the sum of the kinetic energies of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The kinetic energy of the system, T, is equal to the vector sum of the kinetic energy of the particle, T1, and the kinetic energy of the rigid body, T2, i.e. T = T1 + T2 Kinetic energy is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose kinetic energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> kinetic_energy(N, Pa, A) 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') ke_sys = S(0) for e in body: if isinstance(e, (RigidBody, Particle)): ke_sys += e.kinetic_energy(frame) else: raise TypeError('*body must have only Particle or RigidBody') return ke_sys def potential_energy(*body): """Potential energy of a multibody system. This function returns the potential energy of a system of Particle's and/or RigidBody's. The potential energy of such a system is equal to the sum of the potential energy of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The potential energy of the system, V, is equal to the vector sum of the potential energy of the particle, V1, and the potential energy of the rigid body, V2, i.e. V = V1 + V2 Potential energy is a scalar. Parameters ========== body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose potential energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> Pa = Particle('Pa', P, m) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> a = ReferenceFrame('a') >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, M, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> potential_energy(Pa, A) M*g*h + g*h*m """ pe_sys = S(0) for e in body: if isinstance(e, (RigidBody, Particle)): pe_sys += e.potential_energy else: raise TypeError('*body must have only Particle or RigidBody') return pe_sys def Lagrangian(frame, *body): """Lagrangian of a multibody system. This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are the kinetic and potential energies of a system then it's Lagrangian, L, is defined as L = T - V The Lagrangian is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined to determine the kinetic energy. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose Lagrangian is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> Lagrangian(N, Pa, A) -M*g*h - g*h*m + 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please supply a valid ReferenceFrame') for e in body: if not isinstance(e, (RigidBody, Particle)): raise TypeError('*body must have only Particle or RigidBody') return kinetic_energy(frame, *body) - potential_energy(*body) def find_dynamicsymbols(expression, exclude=None): """Find all dynamicsymbols in expression. >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols >>> x, y = dynamicsymbols('x, y') >>> expr = x + x.diff()*y >>> find_dynamicsymbols(expr) {x(t), y(t), Derivative(x(t), t)} If the optional ``exclude`` kwarg is used, only dynamicsymbols not in the iterable ``exclude`` are returned. >>> find_dynamicsymbols(expr, [x, y]) {Derivative(x(t), t)} """ t_set = {dynamicsymbols._t} if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError("exclude kwarg must be iterable") else: exclude_set = set() return set([i for i in expression.atoms(AppliedUndef, Derivative) if i.free_symbols == t_set]) - exclude_set def msubs(expr, *sub_dicts, **kwargs): """A custom subs for use on expressions derived in physics.mechanics. Traverses the expression tree once, performing the subs found in sub_dicts. Terms inside ``Derivative`` expressions are ignored: >>> from sympy.physics.mechanics import dynamicsymbols, msubs >>> x = dynamicsymbols('x') >>> msubs(x.diff() + x, {x: 1}) Derivative(x(t), t) + 1 Note that sub_dicts can be a single dictionary, or several dictionaries: >>> x, y, z = dynamicsymbols('x, y, z') >>> sub1 = {x: 1, y: 2} >>> sub2 = {z: 3, x.diff(): 4} >>> msubs(x.diff() + x + y + z, sub1, sub2) 10 If smart=True (default False), also checks for conditions that may result in ``nan``, but if simplified would yield a valid expression. For example: >>> from sympy import sin, tan >>> (sin(x)/tan(x)).subs(x, 0) nan >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) 1 It does this by first replacing all ``tan`` with ``sin/cos``. Then each node is traversed. If the node is a fraction, subs is first evaluated on the denominator. If this results in 0, simplification of the entire fraction is attempted. Using this selective simplification, only subexpressions that result in 1/0 are targeted, resulting in faster performance. """ sub_dict = dict_merge(*sub_dicts) smart = kwargs.pop('smart', False) if smart: func = _smart_subs elif hasattr(expr, 'msubs'): return expr.msubs(sub_dict) else: func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) if isinstance(expr, (Matrix, Vector, Dyadic)): return expr.applyfunc(lambda x: func(x, sub_dict)) else: return func(expr, sub_dict) def _crawl(expr, func, *args, **kwargs): """Crawl the expression tree, and apply func to every node.""" val = func(expr, *args, **kwargs) if val is not None: return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args) def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr def _tan_repl_func(expr): """Replace tan with sin/cos.""" if isinstance(expr, tan): return sin(*expr.args) / cos(*expr.args) elif not expr.args or expr.is_Derivative: return expr def _smart_subs(expr, sub_dict): """Performs subs, checking for conditions that may result in `nan` or `oo`, and attempts to simplify them out. The expression tree is traversed twice, and the following steps are performed on each expression node: - First traverse: Replace all `tan` with `sin/cos`. - Second traverse: If node is a fraction, check if the denominator evaluates to 0. If so, attempt to simplify it out. Then if node is in sub_dict, sub in the corresponding value.""" expr = _crawl(expr, _tan_repl_func) def _recurser(expr, sub_dict): # Decompose the expression into num, den num, den = _fraction_decomp(expr) if den != 1: # If there is a non trivial denominator, we need to handle it denom_subbed = _recurser(den, sub_dict) if denom_subbed.evalf() == 0: # If denom is 0 after this, attempt to simplify the bad expr expr = simplify(expr) else: # Expression won't result in nan, find numerator num_subbed = _recurser(num, sub_dict) return num_subbed / denom_subbed # We have to crawl the tree manually, because `expr` may have been # modified in the simplify step. First, perform subs as normal: val = _sub_func(expr, sub_dict) if val is not None: return val new_args = (_recurser(arg, sub_dict) for arg in expr.args) return expr.func(*new_args) return _recurser(expr, sub_dict) def _fraction_decomp(expr): """Return num, den such that expr = num/den""" if not isinstance(expr, Mul): return expr, 1 num = [] den = [] for a in expr.args: if a.is_Pow and a.args[1] < 0: den.append(1 / a) else: num.append(a) if not den: return expr, 1 num = Mul(*num) den = Mul(*den) return num, den def _f_list_parser(fl, ref_frame): """Parses the provided forcelist composed of items of the form (obj, force). Returns a tuple containing: vel_list: The velocity (ang_vel for Frames, vel for Points) in the provided reference frame. f_list: The forces. Used internally in the KanesMethod and LagrangesMethod classes. """ def flist_iter(): for pair in fl: obj, force = pair if isinstance(obj, ReferenceFrame): yield obj.ang_vel_in(ref_frame), force elif isinstance(obj, Point): yield obj.vel(ref_frame), force else: raise TypeError('First entry in each forcelist pair must ' 'be a point or frame.') if not fl: vel_list, f_list = (), () else: unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] vel_list, f_list = unzip(list(flist_iter())) return vel_list, f_list
19,231
31.763203
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/kane.py
from __future__ import print_function, division from sympy.core.backend import zeros, Matrix, diff, eye from sympy import solve_linear_system_LU from sympy.core.compatibility import range from sympy.utilities import default_sort_key from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, partial_velocity) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod(object): """Kane's method object. This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill The attributes are for equations in the form [M] udot = forcing. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds bodylist : iterable Iterable of Point and RigidBody objects in the system. forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. auxiliary : Matrix If applicable, the set of auxiliary Kane's equations used to solve for non-contributing forces. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the u's and q's forcing_full : Matrix The "forcing vector" for the u's and q's Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized speeds and coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy import symbols >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame >>> from sympy.physics.mechanics import Point, Particle, KanesMethod >>> q, u = dynamicsymbols('q u') >>> qd, ud = dynamicsymbols('q u', 1) >>> m, c, k = symbols('m c k') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) Next we need to arrange/store information in the way that KanesMethod requires. The kinematic differential equations need to be stored in a dict. A list of forces/torques must be constructed, where each entry in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors represent the Force or Torque. Next a particle needs to be created, and it needs to have a point and mass assigned to it. Finally, a list of all bodies and particles needs to be created. >>> kd = [qd - u] >>> FL = [(P, (-k * q - c * u) * N.x)] >>> pa = Particle('pa', P, m) >>> BL = [pa] Finally we can generate the equations of motion. First we create the KanesMethod object and supply an inertial frame, coordinates, generalized speeds, and the kinematic differential equations. Additional quantities such as configuration and motion constraints, dependent coordinates and speeds, and auxiliary speeds are also supplied here (see the online documentation). Next we form FR* and FR to complete: Fr + Fr* = 0. We have the equations of motion at this point. It makes sense to rearrange them though, so we calculate the mass matrix and the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is the mass matrix, udot is a vector of the time derivatives of the generalized speeds, and forcing is a vector representing "forcing" terms. >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) >>> (fr, frstar) = KM.kanes_equations(BL, FL) >>> MM = KM.mass_matrix >>> forcing = KM.forcing >>> rhs = MM.inv() * forcing >>> rhs Matrix([[(-c*u(t) - k*q(t))/m]]) >>> KM.linearize(A_and_B=True)[0] Matrix([ [ 0, 1], [-k/m, -c/m]]) Please look at the documentation pages for more information on how to perform linearization and how to deal with dependent coordinates & speeds, and how do deal with bringing non-contributing forces into evidence. """ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, configuration_constraints=None, u_dependent=None, velocity_constraints=None, acceleration_constraints=None, u_auxiliary=None): """Please read the online documentation. """ if not isinstance(frame, ReferenceFrame): raise TypeError('An intertial ReferenceFrame must be supplied') self._inertial = frame self._fr = None self._frstar = None self._forcelist = None self._bodylist = None self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, u_auxiliary) self._initialize_kindiffeq_matrices(kd_eqs) self._initialize_constraint_matrices(configuration_constraints, velocity_constraints, acceleration_constraints) def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): """Initialize the coordinate and speed vectors.""" none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize generalized coordinates q_dep = none_handler(q_dep) if not iterable(q_ind): raise TypeError('Generalized coordinates must be an iterable.') if not iterable(q_dep): raise TypeError('Dependent coordinates must be an iterable.') q_ind = Matrix(q_ind) self._qdep = q_dep self._q = Matrix([q_ind, q_dep]) self._qdot = self.q.diff(dynamicsymbols._t) # Initialize generalized speeds u_dep = none_handler(u_dep) if not iterable(u_ind): raise TypeError('Generalized speeds must be an iterable.') if not iterable(u_dep): raise TypeError('Dependent speeds must be an iterable.') u_ind = Matrix(u_ind) self._udep = u_dep self._u = Matrix([u_ind, u_dep]) self._udot = self.u.diff(dynamicsymbols._t) self._uaux = none_handler(u_aux) def _initialize_constraint_matrices(self, config, vel, acc): """Initializes constraint matrices.""" # Define vector dimensions o = len(self.u) m = len(self._udep) p = o - m none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize configuration constraints config = none_handler(config) if len(self._qdep) != len(config): raise ValueError('There must be an equal number of dependent ' 'coordinates and configuration constraints.') self._f_h = none_handler(config) # Initialize velocity and acceleration constraints vel = none_handler(vel) acc = none_handler(acc) if len(vel) != m: raise ValueError('There must be an equal number of dependent ' 'speeds and velocity constraints.') if acc and (len(acc) != m): raise ValueError('There must be an equal number of dependent ' 'speeds and acceleration constraints.') if vel: u_zero = dict((i, 0) for i in self.u) udot_zero = dict((i, 0) for i in self._udot) # When calling kanes_equations, another class instance will be # created if auxiliary u's are present. In this case, the # computation of kinetic differential equation matrices will be # skipped as this was computed during the original KanesMethod # object, and the qd_u_map will not be available. if self._qdot_u_map is not None: vel = msubs(vel, self._qdot_u_map) self._f_nh = msubs(vel, u_zero) self._k_nh = (vel - self._f_nh).jacobian(self.u) # If no acceleration constraints given, calculate them. if not acc: self._f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + self._f_nh.diff(dynamicsymbols._t)) self._k_dnh = self._k_nh else: if self._qdot_u_map is not None: acc = msubs(acc, self._qdot_u_map) self._f_dnh = msubs(acc, udot_zero) self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) # Form of non-holonomic constraints is B*u + C = 0. # We partition B into independent and dependent columns: # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds # to independent speeds as: udep = Ars*uind, neglecting the C term. B_ind = self._k_nh[:, :p] B_dep = self._k_nh[:, p:o] self._Ars = -B_dep.LUsolve(B_ind) else: self._f_nh = Matrix() self._k_nh = Matrix() self._f_dnh = Matrix() self._k_dnh = Matrix() self._Ars = Matrix() def _initialize_kindiffeq_matrices(self, kdeqs): """Initialize the kinematic differential equation matrices.""" if kdeqs: if len(self.q) != len(kdeqs): raise ValueError('There must be an equal number of kinematic ' 'differential equations and coordinates.') kdeqs = Matrix(kdeqs) u = self.u qdot = self._qdot # Dictionaries setting things to zero u_zero = dict((i, 0) for i in u) uaux_zero = dict((i, 0) for i in self._uaux) qdot_zero = dict((i, 0) for i in qdot) f_k = msubs(kdeqs, u_zero, qdot_zero) k_ku = (msubs(kdeqs, qdot_zero) - f_k).jacobian(u) k_kqdot = (msubs(kdeqs, u_zero) - f_k).jacobian(qdot) f_k = k_kqdot.LUsolve(f_k) k_ku = k_kqdot.LUsolve(k_ku) k_kqdot = eye(len(qdot)) self._qdot_u_map = solve_linear_system_LU( Matrix([k_kqdot.T, -(k_ku * u + f_k).T]).T, qdot) self._f_k = msubs(f_k, uaux_zero) self._k_ku = msubs(k_ku, uaux_zero) self._k_kqdot = k_kqdot else: self._qdot_u_map = None self._f_k = Matrix() self._k_ku = Matrix() self._k_kqdot = Matrix() def _form_fr(self, fl): """Form the generalized active force.""" if fl != None and (len(fl) == 0 or not iterable(fl)): raise ValueError('Force pairs must be supplied in an ' 'non-empty iterable or None.') N = self._inertial # pull out relevant velocities for constructing partial velocities vel_list, f_list = _f_list_parser(fl, N) vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] # Fill Fr with dot product of partial velocities and forces o = len(self.u) b = len(f_list) FR = zeros(o, 1) partials = partial_velocity(vel_list, self.u, N) for i in range(o): FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) # In case there are dependent speeds if self._udep: p = o - len(self._udep) FRtilde = FR[:p, 0] FRold = FR[p:o, 0] FRtilde += self._Ars.T * FRold FR = FRtilde self._forcelist = fl self._fr = FR return FR def _form_frstar(self, bl): """Form the generalized inertia force.""" if not iterable(bl): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial # Dicts setting things to zero udot_zero = dict((i, 0) for i in self._udot) uaux_zero = dict((i, 0) for i in self._uaux) uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = dict((i, 0) for i in uauxdot) # Dictionary of q' and q'' to u and u' q_ddot_u_map = dict((k.diff(t), v.diff(t)) for (k, v) in self._qdot_u_map.items()) q_ddot_u_map.update(self._qdot_u_map) # Fill up the list of partials: format is a list with num elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. def get_partial_velocity(body): if isinstance(body, RigidBody): vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] elif isinstance(body, Particle): vlist = [body.point.vel(N),] else: raise TypeError('The body list may only contain either ' 'RigidBody or Particle as list elements.') v = [msubs(vel, self._qdot_u_map) for vel in vlist] return partial_velocity(v, self.u, N) partials = [get_partial_velocity(body) for body in bl] # Compute fr_star in two components: # fr_star = -(MM*u' + nonMM) o = len(self.u) MM = zeros(o, o) nonMM = zeros(o, 1) zero_uaux = lambda expr: msubs(expr, uaux_zero) zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) for i, body in enumerate(bl): if isinstance(body, RigidBody): M = zero_uaux(body.mass) I = zero_uaux(body.central_inertia) vel = zero_uaux(body.masscenter.vel(N)) omega = zero_uaux(body.frame.ang_vel_in(N)) acc = zero_udot_uaux(body.masscenter.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) inertial_torque = zero_uaux((I.dt(body.frame) & omega) + msubs(I & body.frame.ang_acc_in(N), udot_zero) + (omega ^ (I & omega))) for j in range(o): tmp_vel = zero_uaux(partials[i][0][j]) tmp_ang = zero_uaux(I & partials[i][1][j]) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] else: M = zero_uaux(body.mass) vel = zero_uaux(body.point.vel(N)) acc = zero_udot_uaux(body.point.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = zero_uaux(partials[i][0][j]) for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Compose fr_star out of MM and nonMM MM = zero_uaux(msubs(MM, q_ddot_u_map)) nonMM = msubs(msubs(nonMM, q_ddot_u_map), udot_zero, uauxdot_zero, uaux_zero) fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) # If there are dependent speeds, we need to find fr_star_tilde if self._udep: p = o - len(self._udep) fr_star_ind = fr_star[:p, 0] fr_star_dep = fr_star[p:o, 0] fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) # Apply the same to MM MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + (self._Ars.T * MMd) self._bodylist = bl self._frstar = fr_star self._k_d = MM self._f_d = -msubs(self._fr + self._frstar, udot_zero) return fr_star def to_linearizer(self): """Returns an instance of the Linearizer class, initiated from the data in the KanesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points).""" if (self._fr is None) or (self._frstar is None): raise ValueError('Need to compute Fr, Fr* first.') # Get required equation components. The Kane's method class breaks # these into pieces. Need to reassemble f_c = self._f_h if self._f_nh and self._k_nh: f_v = self._f_nh + self._k_nh*Matrix(self.u) else: f_v = Matrix() if self._f_dnh and self._k_dnh: f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) else: f_a = Matrix() # Dicts to sub to zero, for splitting up expressions u_zero = dict((i, 0) for i in self.u) ud_zero = dict((i, 0) for i in self._udot) qd_zero = dict((i, 0) for i in self._qdot) qd_u_zero = dict((i, 0) for i in Matrix([self._qdot, self.u])) # Break the kinematic differential eqs apart into f_0 and f_1 f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) # Break the dynamic differential eqs into f_2 and f_3 f_2 = msubs(self._frstar, qd_u_zero) f_3 = msubs(self._frstar, ud_zero) + self._fr f_4 = zeros(len(f_2), 1) # Get the required vector components q = self.q u = self.u if self._qdep: q_i = q[:-len(self._qdep)] else: q_i = q q_d = self._qdep if self._udep: u_i = u[:-len(self._udep)] else: u_i = u u_d = self._udep # Form dictionary to set auxiliary speeds & their derivatives to 0. uaux = self._uaux uauxdot = uaux.diff(dynamicsymbols._t) uaux_zero = dict((i, 0) for i in Matrix([uaux, uauxdot])) # Checking for dynamic symbols outside the dynamic differential # equations; throws error if there is. sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): raise ValueError('Cannot have dynamicsymbols outside dynamic \ forcing vector.') # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r) def linearize(self, **kwargs): """ Linearize the equations of motion about a symbolic operating point. If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" # TODO : Remove this after 1.1 has been released. _ = kwargs.pop('new_method', None) linearizer = self.to_linearizer() result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def kanes_equations(self, bodies, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. Returns (Fr, Fr*). In the case where auxiliary generalized speeds are present (say, s auxiliary speeds, o generalized speeds, and m motion constraints) the length of the returned vectors will be o - m + s in length. The first o - m equations will be the constrained Kane's equations, then the s auxiliary Kane's equations. These auxiliary equations can be accessed with the auxiliary_eqs(). Parameters ========== bodies : iterable An iterable of all RigidBody's and Particle's in the system. A system must have at least one body. loads : iterable Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. Must be either a non-empty iterable of tuples or None which corresponds to a system with no constraints. """ if (bodies is None and loads != None) or isinstance(bodies[0], tuple): # This switches the order if they use the old way. bodies, loads = loads, bodies SymPyDeprecationWarning(value='The API for kanes_equations() has changed such ' 'that the loads (forces and torques) are now the second argument ' 'and is optional with None being the default.', feature='The kanes_equation() argument order', useinstead='switched argument order to update your code, For example: ' 'kanes_equations(loads, bodies) > kanes_equations(bodies, loads).', issue=10945, deprecated_since_version="1.1").warn() if not self._k_kqdot: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') fr = self._form_fr(loads) frstar = self._form_frstar(bodies) if self._uaux: if not self._udep: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux) else: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux, u_dependent=self._udep, velocity_constraints=(self._k_nh * self.u + self._f_nh)) km._qdot_u_map = self._qdot_u_map self._km = km fraux = km._form_fr(loads) frstaraux = km._form_frstar(bodies) self._aux_eq = fraux + frstaraux self._fr = fr.col_join(fraux) self._frstar = frstar.col_join(frstaraux) return (self._fr, self._frstar) def rhs(self, inv_method=None): """Returns the system's equations of motion in first order form. The output is the right hand side of:: x' = |q'| =: f(q, u, r, p, t) |u'| The right hand side is what is needed by most numerical ODE integrators. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ rhs = zeros(len(self.q) + len(self.u), 1) kdes = self.kindiffdict() for i, q_i in enumerate(self.q): rhs[i] = kdes[q_i.diff()] if inv_method is None: rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) else: rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, try_block_diag=True) * self.forcing) return rhs def kindiffdict(self): """Returns a dictionary mapping q' to u.""" if not self._qdot_u_map: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') return self._qdot_u_map @property def auxiliary_eqs(self): """A matrix containing the auxiliary equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') if not self._uaux: raise ValueError('No auxiliary speeds have been declared.') return self._aux_eq @property def mass_matrix(self): """The mass matrix of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return Matrix([self._k_d, self._k_dnh]) @property def mass_matrix_full(self): """The mass matrix of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') o = len(self.u) n = len(self.q) return ((self._k_kqdot).row_join(zeros(n, o))).col_join((zeros(o, n)).row_join(self.mass_matrix)) @property def forcing(self): """The forcing vector of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return -Matrix([self._f_d, self._f_dnh]) @property def forcing_full(self): """The forcing vector of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') f1 = self._k_ku * Matrix(self.u) + self._f_k return -Matrix([f1, self._f_d, self._f_dnh]) @property def q(self): return self._q @property def u(self): return self._u @property def bodylist(self): return self._bodylist @property def forcelist(self): return self._forcelist
27,282
40.653435
91
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/linearize.py
from __future__ import print_function, division __all__ = ['Linearizer'] from sympy.core.backend import Matrix, eye, zeros from sympy import Dummy from sympy.utilities.iterables import flatten from sympy.physics.vector import dynamicsymbols from sympy.physics.mechanics.functions import msubs import collections class Linearizer(object): """This object holds the general model form for a dynamic system. This model is used for computing the linearized form of the system, while properly dealing with constraints leading to dependent coordinates and speeds. Attributes ---------- f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix Matrices holding the general system form. q, u, r : Matrix Matrices holding the generalized coordinates, speeds, and input vectors. q_i, u_i : Matrix Matrices of the independent generalized coordinates and speeds. q_d, u_d : Matrix Matrices of the dependent generalized coordinates and speeds. perm_mat : Matrix Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T """ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None): """ Parameters ---------- f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like System of equations holding the general system form. Supply empty array or Matrix if the parameter doesn't exist. q : array_like The generalized coordinates. u : array_like The generalized speeds q_i, u_i : array_like, optional The independent generalized coordinates and speeds. q_d, u_d : array_like, optional The dependent generalized coordinates and speeds. r : array_like, optional The input variables. lams : array_like, optional The lagrange multipliers """ # Generalized equation form self.f_0 = Matrix(f_0) self.f_1 = Matrix(f_1) self.f_2 = Matrix(f_2) self.f_3 = Matrix(f_3) self.f_4 = Matrix(f_4) self.f_c = Matrix(f_c) self.f_v = Matrix(f_v) self.f_a = Matrix(f_a) # Generalized equation variables self.q = Matrix(q) self.u = Matrix(u) none_handler = lambda x: Matrix(x) if x else Matrix() self.q_i = none_handler(q_i) self.q_d = none_handler(q_d) self.u_i = none_handler(u_i) self.u_d = none_handler(u_d) self.r = none_handler(r) self.lams = none_handler(lams) # Derivatives of generalized equation variables self._qd = self.q.diff(dynamicsymbols._t) self._ud = self.u.diff(dynamicsymbols._t) # If the user doesn't actually use generalized variables, and the # qd and u vectors have any intersecting variables, this can cause # problems. We'll fix this with some hackery, and Dummy variables dup_vars = set(self._qd).intersection(self.u) self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var in self._qd]) # Derive dimesion terms l = len(self.f_c) m = len(self.f_v) n = len(self.q) o = len(self.u) s = len(self.r) k = len(self.lams) dims = collections.namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k']) self._dims = dims(l, m, n, o, s, k) self._setup_done = False def _setup(self): # Calculations here only need to be run once. They are moved out of # the __init__ method to increase the speed of Linearizer creation. self._form_permutation_matrices() self._form_block_matrices() self._form_coefficient_matrices() self._setup_done = True def _form_permutation_matrices(self): """Form the permutation matrices Pq and Pu.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Compute permutation matrices if n != 0: self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d])) if l > 0: self._Pqi = self._Pq[:, :-l] self._Pqd = self._Pq[:, -l:] else: self._Pqi = self._Pq self._Pqd = Matrix() if o != 0: self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d])) if m > 0: self._Pui = self._Pu[:, :-m] self._Pud = self._Pu[:, -m:] else: self._Pui = self._Pu self._Pud = Matrix() # Compute combination permutation matrix for computing A and B P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)]) P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)]) if P_col1: if P_col2: self.perm_mat = P_col1.row_join(P_col2) else: self.perm_mat = P_col1 else: self.perm_mat = P_col2 def _form_coefficient_matrices(self): """Form the coefficient matrices C_0, C_1, and C_2.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Build up the coefficient matrices C_0, C_1, and C_2 # If there are configuration constraints (l > 0), form C_0 as normal. # If not, C_0 is I_(nxn). Note that this works even if n=0 if l > 0: f_c_jac_q = self.f_c.jacobian(self.q) self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q * self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi else: self._C_0 = eye(n) # If there are motion constraints (m > 0), form C_1 and C_2 as normal. # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if # o = 0. if m > 0: f_v_jac_u = self.f_v.jacobian(self.u) temp = f_v_jac_u * self._Pud if n != 0: f_v_jac_q = self.f_v.jacobian(self.q) self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q) else: self._C_1 = zeros(o, n) self._C_2 = (eye(o) - self._Pud * temp.LUsolve(f_v_jac_u)) * self._Pui else: self._C_1 = zeros(o, n) self._C_2 = eye(o) def _form_block_matrices(self): """Form the block matrices for composing M, A, and B.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Block Matrix Definitions. These are only defined if under certain # conditions. If undefined, an empty matrix is used instead if n != 0: self._M_qq = self.f_0.jacobian(self._qd) self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q) else: self._M_qq = Matrix() self._A_qq = Matrix() if n != 0 and m != 0: self._M_uqc = self.f_a.jacobian(self._qd_dup) self._A_uqc = -self.f_a.jacobian(self.q) else: self._M_uqc = Matrix() self._A_uqc = Matrix() if n != 0 and o - m + k != 0: self._M_uqd = self.f_3.jacobian(self._qd_dup) self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q) else: self._M_uqd = Matrix() self._A_uqd = Matrix() if o != 0 and m != 0: self._M_uuc = self.f_a.jacobian(self._ud) self._A_uuc = -self.f_a.jacobian(self.u) else: self._M_uuc = Matrix() self._A_uuc = Matrix() if o != 0 and o - m + k != 0: self._M_uud = self.f_2.jacobian(self._ud) self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u) else: self._M_uud = Matrix() self._A_uud = Matrix() if o != 0 and n != 0: self._A_qu = -self.f_1.jacobian(self.u) else: self._A_qu = Matrix() if k != 0 and o - m + k != 0: self._M_uld = self.f_4.jacobian(self.lams) else: self._M_uld = Matrix() if s != 0 and o - m + k != 0: self._B_u = -self.f_3.jacobian(self.r) else: self._B_u = Matrix() def linearize(self, op_point=None, A_and_B=False, simplify=False): """Linearize the system about the operating point. Note that q_op, u_op, qd_op, ud_op must satisfy the equations of motion. These may be either symbolic or numeric. Parameters ---------- op_point : dict or iterable of dicts, optional Dictionary or iterable of dictionaries containing the operating point conditions. These will be substituted in to the linearized system before the linearization is complete. Leave blank if you want a completely symbolic form. Note that any reduction in symbols (whether substituted for numbers or expressions with a common parameter) will result in faster runtime. A_and_B : bool, optional If A_and_B=False (default), (M, A, B) is returned for forming [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True, (A, B) is returned for forming dx = [A]x + [B]r, where x = [q_ind, u_ind]^T. simplify : bool, optional Determines if returned values are simplified before return. For large expressions this may be time consuming. Default is False. Potential Issues ---------------- Note that the process of solving with A_and_B=True is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. More values may then be substituted in to these matrices later on. The state space form can then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where P = Linearizer.perm_mat. """ # Run the setup if needed: if not self._setup_done: self._setup() # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif isinstance(op_point, collections.Iterable): op_point_dict = {} for op in op_point: op_point_dict.update(op) else: op_point_dict = {} # Extract dimension variables l, m, n, o, s, k = self._dims # Rename terms to shorten expressions M_qq = self._M_qq M_uqc = self._M_uqc M_uqd = self._M_uqd M_uuc = self._M_uuc M_uud = self._M_uud M_uld = self._M_uld A_qq = self._A_qq A_uqc = self._A_uqc A_uqd = self._A_uqd A_qu = self._A_qu A_uuc = self._A_uuc A_uud = self._A_uud B_u = self._B_u C_0 = self._C_0 C_1 = self._C_1 C_2 = self._C_2 # Build up Mass Matrix # |M_qq 0_nxo 0_nxk| # M = |M_uqc M_uuc 0_mxk| # |M_uqd M_uud M_uld| if o != 0: col2 = Matrix([zeros(n, o), M_uuc, M_uud]) if k != 0: col3 = Matrix([zeros(n + m, k), M_uld]) if n != 0: col1 = Matrix([M_qq, M_uqc, M_uqd]) if o != 0 and k != 0: M = col1.row_join(col2).row_join(col3) elif o != 0: M = col1.row_join(col2) else: M = col1 elif k != 0: M = col2.row_join(col3) else: M = col2 M_eq = msubs(M, op_point_dict) # Build up state coefficient matrix A # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2| # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2| # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2| # Col 1 is only defined if n != 0 if n != 0: r1c1 = A_qq if o != 0: r1c1 += (A_qu * C_1) r1c1 = r1c1 * C_0 if m != 0: r2c1 = A_uqc if o != 0: r2c1 += (A_uuc * C_1) r2c1 = r2c1 * C_0 else: r2c1 = Matrix() if o - m + k != 0: r3c1 = A_uqd if o != 0: r3c1 += (A_uud * C_1) r3c1 = r3c1 * C_0 else: r3c1 = Matrix() col1 = Matrix([r1c1, r2c1, r3c1]) else: col1 = Matrix() # Col 2 is only defined if o != 0 if o != 0: if n != 0: r1c2 = A_qu * C_2 else: r1c2 = Matrix() if m != 0: r2c2 = A_uuc * C_2 else: r2c2 = Matrix() if o - m + k != 0: r3c2 = A_uud * C_2 else: r3c2 = Matrix() col2 = Matrix([r1c2, r2c2, r3c2]) else: col2 = Matrix() if col1: if col2: Amat = col1.row_join(col2) else: Amat = col1 else: Amat = col2 Amat_eq = msubs(Amat, op_point_dict) # Build up the B matrix if there are forcing variables # |0_(n + m)xs| # B = |B_u | if s != 0 and o - m + k != 0: Bmat = zeros(n + m, s).col_join(B_u) Bmat_eq = msubs(Bmat, op_point_dict) else: Bmat_eq = Matrix() # kwarg A_and_B indicates to return A, B for forming the equation # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T, if A_and_B: A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq) if Bmat_eq: B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq) else: # Bmat = Matrix([]), so no need to sub B_cont = Bmat_eq if simplify: A_cont.simplify() B_cont.simplify() return A_cont, B_cont # Otherwise return M, A, B for forming the equation # [M]dx = [A]x + [B]r, where x = [q, u]^T else: if simplify: M_eq.simplify() Amat_eq.simplify() Bmat_eq.simplify() return M_eq, Amat_eq, Bmat_eq def permutation_matrix(orig_vec, per_vec): """Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ---------- orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ------- p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec). """ if not isinstance(orig_vec, (list, tuple)): orig_vec = flatten(orig_vec) if not isinstance(per_vec, (list, tuple)): per_vec = flatten(per_vec) if set(orig_vec) != set(per_vec): raise ValueError("orig_vec and per_vec must be the same length, " + "and contain the same symbols.") ind_list = [orig_vec.index(i) for i in per_vec] p_matrix = zeros(len(orig_vec)) for i, j in enumerate(ind_list): p_matrix[i, j] = 1 return p_matrix
15,371
34.915888
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """This module contains some sample symbolic models used for testing and examples.""" # Internal imports from sympy.core import backend as sm import sympy.physics.mechanics as me def multi_mass_spring_damper(n=1, apply_gravity=False, apply_external_forces=False): """Returns a system containing the symbolic equations of motion and associated variables for a simple multi-degree of freedom point mass, spring, damper system with optional gravitational and external specified forces. For example, a two mass system under the influence of gravity and external forces looks like: :: ---------------- | | | | g \ | | | V k0 / --- c0 | | | | x0, v0 --------- V | m0 | ----- --------- | | | | | \ v | | | k1 / f0 --- c1 | | | | x1, v1 --------- V | m1 | ----- --------- | f1 V Parameters ---------- n : integer The number of masses in the serial chain. apply_gravity : boolean If true, gravity will be applied to each mass. apply_external_forces : boolean If true, a time varying external force will be applied to each mass. Returns ------- kane : sympy.physics.mechanics.kane.KanesMethod A KanesMethod object. """ mass = sm.symbols('m:{}'.format(n)) stiffness = sm.symbols('k:{}'.format(n)) damping = sm.symbols('c:{}'.format(n)) acceleration_due_to_gravity = sm.symbols('g') coordinates = me.dynamicsymbols('x:{}'.format(n)) speeds = me.dynamicsymbols('v:{}'.format(n)) specifieds = me.dynamicsymbols('f:{}'.format(n)) ceiling = me.ReferenceFrame('N') origin = me.Point('origin') origin.set_vel(ceiling, 0) points = [origin] kinematic_equations = [] particles = [] forces = [] for i in range(n): center = points[-1].locatenew('center{}'.format(i), coordinates[i] * ceiling.x) center.set_vel(ceiling, points[-1].vel(ceiling) + speeds[i] * ceiling.x) points.append(center) block = me.Particle('block{}'.format(i), center, mass[i]) kinematic_equations.append(speeds[i] - coordinates[i].diff()) total_force = (-stiffness[i] * coordinates[i] - damping[i] * speeds[i]) try: total_force += (stiffness[i + 1] * coordinates[i + 1] + damping[i + 1] * speeds[i + 1]) except IndexError: # no force from below on last mass pass if apply_gravity: total_force += mass[i] * acceleration_due_to_gravity if apply_external_forces: total_force += specifieds[i] forces.append((center, total_force * ceiling.x)) particles.append(block) kane = me.KanesMethod(ceiling, q_ind=coordinates, u_ind=speeds, kd_eqs=kinematic_equations) kane.kanes_equations(particles, forces) return kane def n_link_pendulum_on_cart(n=1, cart_force=True, joint_torques=False): """Returns the system containing the symbolic first order equations of motion for a 2D n-link pendulum on a sliding cart under the influence of gravity. :: | o y v \ 0 ^ g \ | --\-|---- | \| | F-> | o --|---> x | | --------- o o Parameters ---------- n : integer The number of links in the pendulum. cart_force : boolean, default=True If true an external specified lateral force is applied to the cart. joint_torques : boolean, default=False If true joint torques will be added as specified inputs at each joint. Returns ------- kane : sympy.physics.mechanics.kane.KanesMethod A KanesMethod object. Notes ----- The degrees of freedom of the system are n + 1, i.e. one for each pendulum link and one for the lateral motion of the cart. M x' = F, where x = [u0, ..., un+1, q0, ..., qn+1] The joint angles are all defined relative to the ground where the x axis defines the ground line and the y axis points up. The joint torques are applied between each adjacent link and the between the cart and the lower link where a positive torque corresponds to positive angle. """ if n <= 0: raise ValueError('The number of links must be a positive integer.') q = me.dynamicsymbols('q:{}'.format(n + 1)) u = me.dynamicsymbols('u:{}'.format(n + 1)) if joint_torques is True: T = me.dynamicsymbols('T1:{}'.format(n + 1)) m = sm.symbols('m:{}'.format(n + 1)) l = sm.symbols('l:{}'.format(n)) g, t = sm.symbols('g t') I = me.ReferenceFrame('I') O = me.Point('O') O.set_vel(I, 0) P0 = me.Point('P0') P0.set_pos(O, q[0] * I.x) P0.set_vel(I, u[0] * I.x) Pa0 = me.Particle('Pa0', P0, m[0]) frames = [I] points = [P0] particles = [Pa0] forces = [(P0, -m[0] * g * I.y)] kindiffs = [q[0].diff(t) - u[0]] if cart_force is True or joint_torques is True: specified = [] else: specified = None for i in range(n): Bi = I.orientnew('B{}'.format(i), 'Axis', [q[i + 1], I.z]) Bi.set_ang_vel(I, u[i + 1] * I.z) frames.append(Bi) Pi = points[-1].locatenew('P{}'.format(i + 1), l[i] * Bi.y) Pi.v2pt_theory(points[-1], I, Bi) points.append(Pi) Pai = me.Particle('Pa' + str(i + 1), Pi, m[i + 1]) particles.append(Pai) forces.append((Pi, -m[i + 1] * g * I.y)) if joint_torques is True: specified.append(T[i]) if i == 0: forces.append((I, -T[i] * I.z)) if i == n - 1: forces.append((Bi, T[i] * I.z)) else: forces.append((Bi, T[i] * I.z - T[i + 1] * I.z)) kindiffs.append(q[i + 1].diff(t) - u[i + 1]) if cart_force is True: F = me.dynamicsymbols('F') forces.append((P0, F * I.x)) specified.append(F) kane = me.KanesMethod(I, q_ind=q, u_ind=u, kd_eqs=kindiffs) kane.kanes_equations(particles, forces) return kane
6,481
27.429825
76
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/__init__.py
__all__ = [] # The following pattern is used below for importing sub-modules: # # 1. "from foo import *". This imports all the names from foo.__all__ into # this module. But, this does not put those names into the __all__ of # this module. This enables "from sympy.physics.mechanics import kinematics" to # work. # 2. "import foo; __all__.extend(foo.__all__)". This adds all the names in # foo.__all__ to the __all__ of this module. The names in __all__ # determine which names are imported when # "from sympy.physics.mechanics import *" is done. from . import kane from .kane import * __all__.extend(kane.__all__) from . import rigidbody from .rigidbody import * __all__.extend(rigidbody.__all__) from . import functions from .functions import * __all__.extend(functions.__all__) from . import particle from .particle import * __all__.extend(particle.__all__) from . import lagrange from .lagrange import * __all__.extend(lagrange.__all__) from sympy.physics import vector from sympy.physics.vector import * __all__.extend(vector.__all__) from . import linearize from .linearize import * __all__.extend(linearize.__all__) from . import body from .body import * __all__.extend(body.__all__) from . import system from .system import * __all__.extend(system.__all__)
1,294
25.428571
82
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/body.py
from sympy.core.backend import Symbol from sympy.physics.mechanics import (RigidBody, Particle, ReferenceFrame, inertia) from sympy.physics.vector import Point, Vector __all__ = ['Body'] class Body(RigidBody, Particle): """ Body is a common representation of either a RigidBody or a Particle SymPy object depending on what is passed in during initialization. If a mass is passed in and central_inertia is left as None, the Particle object is created. Otherwise a RigidBody object will be created. The attributes that Body possesses will be the same as a Particle instance or a Rigid Body instance depending on which was created. Additional attributes are listed below. Attributes ========== name : string The body's name masscenter : Point The point which represents the center of mass of the rigid body frame : ReferenceFrame The reference frame which the body is fixed in mass : Sympifyable The body's mass inertia : (Dyadic, Point) The body's inertia around its center of mass. This attribute is specific to the rigid body form of Body and is left undefined for the Particle form loads : iterable This list contains information on the different loads acting on the Body. Forces are listed as a (point, vector) tuple and torques are listed as (reference frame, vector) tuples. Parameters ========== name : String Defines the name of the body. It is used as the base for defining body specific properties. masscenter : Point, optional A point that represents the center of mass of the body or particle. If no point is given, a point is generated. mass : Sympifyable, optional A Sympifyable object which represents the mass of the body. If no mass is passed, one is generated. frame : ReferenceFrame, optional The ReferenceFrame that represents the reference frame of the body. If no frame is given, a frame is generated. central_inertia : Dyadic, optional Central inertia dyadic of the body. If none is passed while creating RigidBody, a default inertia is generated. Examples ======== Default behaviour. This results in the creation of a RigidBody object for which the mass, mass center, frame and inertia attributes are given default values. :: >>> from sympy.physics.mechanics import Body >>> body = Body('name_of_body') This next example demonstrates the code required to specify all of the values of the Body object. Note this will also create a RigidBody version of the Body object. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> masscenter = Point('masscenter') >>> frame = ReferenceFrame('frame') >>> ixx = Symbol('ixx') >>> body_inertia = inertia(frame, ixx, 0, 0) >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) The minimal code required to create a Particle version of the Body object involves simply passing in a name and a mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> body = Body('name_of_body', mass=mass) The Particle version of the Body object can also receive a masscenter point and a reference frame, just not an inertia. """ def __init__(self, name, masscenter=None, mass=None, frame=None, central_inertia=None): self.name = name self.loads = [] if frame is None: frame = ReferenceFrame(name + '_frame') if masscenter is None: masscenter = Point(name + '_masscenter') if central_inertia is None and mass is None: ixx = Symbol(name + '_ixx') iyy = Symbol(name + '_iyy') izz = Symbol(name + '_izz') izx = Symbol(name + '_izx') ixy = Symbol(name + '_ixy') iyz = Symbol(name + '_iyz') _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), masscenter) else: _inertia = (central_inertia, masscenter) if mass is None: _mass = Symbol(name + '_mass') else: _mass = mass masscenter.set_vel(frame, 0) # If user passes masscenter and mass then a particle is created # otherwise a rigidbody. As a result a body may or may not have inertia. if central_inertia is None and mass is not None: self.frame = frame self.masscenter = masscenter Particle.__init__(self, name, masscenter, _mass) else: RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) def apply_force(self, vec, point=None): """ Adds a force to a point (center of mass by default) on the body. Parameters ========== vec: Vector Defines the force vector. Can be any vector w.r.t any frame or combinations of frames. point: Point, optional Defines the point on which the force is applied. Default is the Body's center of mass. Example ======= The first example applies a gravitational force in the x direction of Body's frame to the body's center of mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> g = Symbol('g') >>> body.apply_force(body.mass * g * body.frame.x) To apply force to any other point than center of mass, pass that point as well. This example applies a gravitational force to a point a distance l from the body's center of mass in the y direction. The force is again applied in the x direction. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> g = Symbol('g') >>> l = Symbol('l') >>> point = body.masscenter.locatenew('force_point', l * ... body.frame.y) >>> body.apply_force(body.mass * g * body.frame.x, point) """ if not isinstance(point, Point): if point is None: point = self.masscenter # masscenter else: raise TypeError("A Point must be supplied to apply force to.") if not isinstance(vec, Vector): raise TypeError("A Vector must be supplied to apply force.") self.loads.append((point, vec)) def apply_torque(self, vec): """ Adds a torque to the body. Parameters ========== vec: Vector Defines the torque vector. Can be any vector w.r.t any frame or combinations of frame. Example ======= This example adds a simple torque around the body's z axis. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> T = Symbol('T') >>> body.apply_torque(T * body.frame.z) """ if not isinstance(vec, Vector): raise TypeError("A Vector must be supplied to add torque.") self.loads.append((self.frame, vec))
7,676
35.042254
81
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/particle.py
from __future__ import print_function, division from sympy.core.backend import sympify from sympy.physics.vector import Point __all__ = ['Particle'] class Particle(object): """A particle. Particles have a non-zero mass and lack spatial extension; they take up no space. Values need to be supplied on initialization, but can be changed later. Parameters ========== name : str Name of particle point : Point A physics/mechanics Point which represents the position, velocity, and acceleration of this Particle mass : sympifyable A SymPy expression representing the Particle's mass Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import Symbol >>> po = Point('po') >>> m = Symbol('m') >>> pa = Particle('pa', po, m) >>> # Or you could change these later >>> pa.mass = m >>> pa.point = po """ def __init__(self, name, point, mass): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.mass = mass self.point = point self.potential_energy = 0 def __str__(self): return self._name __repr__ = __str__ @property def mass(self): """Mass of the particle.""" return self._mass @mass.setter def mass(self, value): self._mass = sympify(value) @property def point(self): """Point of the particle.""" return self._point @point.setter def point(self, p): if not isinstance(p, Point): raise TypeError("Particle point attribute must be a Point object.") self._point = p def linear_momentum(self, frame): """Linear momentum of the particle. The linear momentum L, of a particle P, with respect to frame N is given by L = m * v where m is the mass of the particle, and v is the velocity of the particle in the frame N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> m, v = dynamicsymbols('m v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> A = Particle('A', P, m) >>> P.set_vel(N, v * N.x) >>> A.linear_momentum(N) m*v*N.x """ return self.mass * self.point.vel(frame) def angular_momentum(self, point, frame): """Angular momentum of the particle about the point. The angular momentum H, about some point O of a particle, P, is given by: H = r x m * v where r is the position vector from point O to the particle P, m is the mass of the particle, and v is the velocity of the particle in the inertial frame, N. Parameters ========== point : Point The point about which angular momentum of the particle is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> m, v, r = dynamicsymbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> A = O.locatenew('A', r * N.x) >>> P = Particle('P', A, m) >>> P.point.set_vel(N, v * N.y) >>> P.angular_momentum(O, N) m*r*v*N.z """ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) def kinetic_energy(self, frame): """Kinetic energy of the particle The kinetic energy, T, of a particle, P, is given by 'T = 1/2 m v^2' where m is the mass of particle P, and v is the velocity of the particle in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The Particle's velocity is typically defined with respect to an inertial frame but any relevant frame in which the velocity is known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy import symbols >>> m, v, r = symbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.point.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 """ return (self.mass / sympify(2) * self.point.vel(frame) & self.point.vel(frame)) @property def potential_energy(self): """The potential energy of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h >>> P.potential_energy g*h*m """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of the Particle. Parameters ========== scalar : Sympifyable The potential energy (a scalar) of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h """ self._pe = sympify(scalar)
5,924
25.216814
79
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/tests/test_functions.py
from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, zeros from sympy.physics.mechanics import (Particle, Point, ReferenceFrame, RigidBody, Vector) from sympy.physics.mechanics import (angular_momentum, dynamicsymbols, inertia, inertia_of_point_mass, kinetic_energy, linear_momentum, outer, potential_energy, msubs, find_dynamicsymbols) Vector.simp = True q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5') N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = A.orientnew('B', 'Axis', [q2, A.x]) C = B.orientnew('C', 'Axis', [q3, B.y]) def test_inertia(): N = ReferenceFrame('N') ixx, iyy, izz = symbols('ixx iyy izz') ixy, iyz, izx = symbols('ixy iyz izx') assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy * (N.y | N.y) + izz * (N.z | N.z)) assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x) assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) + ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy * (N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z | N.y) + izz * (N.z | N.z)) def test_inertia_of_point_mass(): r, s, t, m = symbols('r s t m') N = ReferenceFrame('N') px = r * N.x I = inertia_of_point_mass(m, px, N) assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z) py = s * N.y I = inertia_of_point_mass(m, py, N) assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z) pz = t * N.z I = inertia_of_point_mass(m, pz, N) assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y) p = px + py + pz I = inertia_of_point_mass(m, p, N) assert I == (m * (s**2 + t**2) * (N.x | N.x) - m * r * s * (N.x | N.y) - m * r * t * (N.x | N.z) - m * r * s * (N.y | N.x) + m * (r**2 + t**2) * (N.y | N.y) - m * s * t * (N.y | N.z) - m * r * t * (N.z | N.x) - m * s * t * (N.z | N.y) + m * (r**2 + s**2) * (N.z | N.z)) def test_linear_momentum(): N = ReferenceFrame('N') Ac = Point('Ac') Ac.set_vel(N, 25 * N.y) I = outer(N.x, N.x) A = RigidBody('A', Ac, N, 20, (I, Ac)) P = Point('P') Pa = Particle('Pa', P, 1) Pa.point.set_vel(N, 10 * N.x) assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y def test_angular_momentum_and_linear_momentum(): """A rod with length 2l, centroidal inertia I, and mass M along with a particle of mass m fixed to the end of the rod rotate with an angular rate of omega about point O which is fixed to the non-particle end of the rod. The rod's reference frame is A and the inertial frame is N.""" m, M, l, I = symbols('m, M, l, I') omega = dynamicsymbols('omega') N = ReferenceFrame('N') a = ReferenceFrame('a') O = Point('O') Ac = O.locatenew('Ac', l * N.x) P = Ac.locatenew('P', l * N.x) O.set_vel(N, 0 * N.x) a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac)) expected = 2 * m * omega * l * N.y + M * l * omega * N.y assert linear_momentum(N, A, Pa) == expected expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z assert angular_momentum(O, N, A, Pa) == expected def test_kinetic_energy(): m, M, l1 = symbols('m M l1') omega = dynamicsymbols('omega') N = ReferenceFrame('N') O = Point('O') O.set_vel(N, 0 * N.x) Ac = O.locatenew('Ac', l1 * N.x) P = Ac.locatenew('P', l1 * N.x) a = ReferenceFrame('a') a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, M, (I, Ac)) assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2 + 2*l1**2*m*omega**2 + omega**2/2)).expand() def test_potential_energy(): m, M, l1, g, h, H = symbols('m M l1 g h H') omega = dynamicsymbols('omega') N = ReferenceFrame('N') O = Point('O') O.set_vel(N, 0 * N.x) Ac = O.locatenew('Ac', l1 * N.x) P = Ac.locatenew('P', l1 * N.x) a = ReferenceFrame('a') a.set_ang_vel(N, omega * N.z) Ac.v2pt_theory(O, N, a) P.v2pt_theory(O, N, a) Pa = Particle('Pa', P, m) I = outer(N.z, N.z) A = RigidBody('A', Ac, a, M, (I, Ac)) Pa.potential_energy = m * g * h A.potential_energy = M * g * H assert potential_energy(A, Pa) == m * g * h + M * g * H def test_msubs(): a, b = symbols('a, b') x, y, z = dynamicsymbols('x, y, z') # Test simple substitution expr = Matrix([[a*x + b, x*y.diff() + y], [x.diff().diff(), z + sin(z.diff())]]) sol = Matrix([[a + b, y], [x.diff().diff(), 1]]) sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0} assert msubs(expr, sd) == sol # Test smart substitution expr = cos(x + y)*tan(x + y) + b*x.diff() sd = {x: 0, y: pi/2, x.diff(): 1} assert msubs(expr, sd, smart=True) == b + 1 N = ReferenceFrame('N') v = x*N.x + y*N.y d = x*(N.x|N.x) + y*(N.y|N.y) v_sol = 1*N.y d_sol = 1*(N.y|N.y) sd = {x: 0, y: 1} assert msubs(v, sd) == v_sol assert msubs(d, sd) == d_sol def test_find_dynamicsymbols(): a, b = symbols('a, b') x, y, z = dynamicsymbols('x, y, z') expr = Matrix([[a*x + b, x*y.diff() + y], [x.diff().diff(), z + sin(z.diff())]]) # Test finding all dynamicsymbols sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()} assert find_dynamicsymbols(expr) == sol # Test finding all but those in sym_list exclude = [x, y, z] sol = {y.diff(), x.diff().diff(), z.diff()} assert find_dynamicsymbols(expr, exclude) == sol
6,013
34.169591
78
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/tests/test_lagrange.py
from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point, RigidBody, LagrangesMethod, Particle, inertia, Lagrangian) from sympy import symbols, pi, sin, cos, tan, simplify, Function, \ Derivative, Matrix def test_disc_on_an_incline_plane(): # Disc rolling on an inclined plane # First the generalized coordinates are created. The mass center of the # disc is located from top vertex of the inclined plane by the generalized # coordinate 'y'. The orientation of the disc is defined by the angle # 'theta'. The mass of the disc is 'm' and its radius is 'R'. The length of # the inclined path is 'l', the angle of inclination is 'alpha'. 'g' is the # gravitational constant. y, theta = dynamicsymbols('y theta') yd, thetad = dynamicsymbols('y theta', 1) m, g, R, l, alpha = symbols('m g R l alpha') # Next, we create the inertial reference frame 'N'. A reference frame 'A' # is attached to the inclined plane. Finally a frame is created which is attached to the disk. N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [pi/2 - alpha, N.z]) B = A.orientnew('B', 'Axis', [-theta, A.z]) # Creating the disc 'D'; we create the point that represents the mass # center of the disc and set its velocity. The inertia dyadic of the disc # is created. Finally, we create the disc. Do = Point('Do') Do.set_vel(N, yd * A.x) I = m * R**2 / 2 * B.z | B.z D = RigidBody('D', Do, B, m, (I, Do)) # To construct the Lagrangian, 'L', of the disc, we determine its kinetic # and potential energies, T and U, respectively. L is defined as the # difference between T and U. D.potential_energy = m * g * (l - y) * sin(alpha) L = Lagrangian(N, D) # We then create the list of generalized coordinates and constraint # equations. The constraint arises due to the disc rolling without slip on # on the inclined path. We then invoke the 'LagrangesMethod' class and # supply it the necessary arguments and generate the equations of motion. # The'rhs' method solves for the q_double_dots (i.e. the second derivative # with respect to time of the generalized coordinates and the lagrange # multiplers. q = [y, theta] hol_coneqs = [y - R * theta] m = LagrangesMethod(L, q, hol_coneqs=hol_coneqs) m.form_lagranges_equations() rhs = m.rhs() rhs.simplify() assert rhs[2] == 2*g*sin(alpha)/3 def test_simp_pen(): # This tests that the equations generated by LagrangesMethod are identical # to those obtained by hand calculations. The system under consideration is # the simple pendulum. # We begin by creating the generalized coordinates as per the requirements # of LagrangesMethod. Also we created the associate symbols # that characterize the system: 'm' is the mass of the bob, l is the length # of the massless rigid rod connecting the bob to a point O fixed in the # inertial frame. q, u = dynamicsymbols('q u') qd, ud = dynamicsymbols('q u ', 1) l, m, g = symbols('l m g') # We then create the inertial frame and a frame attached to the massless # string following which we define the inertial angular velocity of the # string. N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q, N.z]) A.set_ang_vel(N, qd * N.z) # Next, we create the point O and fix it in the inertial frame. We then # locate the point P to which the bob is attached. Its corresponding # velocity is then determined by the 'two point formula'. O = Point('O') O.set_vel(N, 0) P = O.locatenew('P', l * A.x) P.v2pt_theory(O, N, A) # The 'Particle' which represents the bob is then created and its # Lagrangian generated. Pa = Particle('Pa', P, m) Pa.potential_energy = - m * g * l * cos(q) L = Lagrangian(N, Pa) # The 'LagrangesMethod' class is invoked to obtain equations of motion. lm = LagrangesMethod(L, [q]) lm.form_lagranges_equations() RHS = lm.rhs() assert RHS[1] == -g*sin(q)/l def test_nonminimal_pendulum(): q1, q2 = dynamicsymbols('q1:3') q1d, q2d = dynamicsymbols('q1:3', level=1) L, m, t = symbols('L, m, t') g = 9.8 # Compose World Frame N = ReferenceFrame('N') pN = Point('N*') pN.set_vel(N, 0) # Create point P, the pendulum mass P = pN.locatenew('P1', q1*N.x + q2*N.y) P.set_vel(N, P.pos_from(pN).dt(N)) pP = Particle('pP', P, m) # Constraint Equations f_c = Matrix([q1**2 + q2**2 - L**2]) # Calculate the lagrangian, and form the equations of motion Lag = Lagrangian(N, pP) LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c, forcelist=[(P, m*g*N.x)], frame=N) LM.form_lagranges_equations() # Check solution lam1 = LM.lam_vec[0, 0] eom_sol = Matrix([[m*Derivative(q1, t, t) - 9.8*m + 2*lam1*q1], [m*Derivative(q2, t, t) + 2*lam1*q2]]) assert LM.eom == eom_sol # Check multiplier solution lam_sol = Matrix([(19.6*q1 + 2*q1d**2 + 2*q2d**2)/(4*q1**2/m + 4*q2**2/m)]) assert LM.solve_multipliers(sol_type='Matrix') == lam_sol def test_dub_pen(): # The system considered is the double pendulum. Like in the # test of the simple pendulum above, we begin by creating the generalized # coordinates and the simple generalized speeds and accelerations which # will be used later. Following this we create frames and points necessary # for the kinematics. The procedure isn't explicitly explained as this is # similar to the simple pendulum. Also this is documented on the pydy.org # website. q1, q2 = dynamicsymbols('q1 q2') q1d, q2d = dynamicsymbols('q1 q2', 1) q1dd, q2dd = dynamicsymbols('q1 q2', 2) u1, u2 = dynamicsymbols('u1 u2') u1d, u2d = dynamicsymbols('u1 u2', 1) l, m, g = symbols('l m g') N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = N.orientnew('B', 'Axis', [q2, N.z]) A.set_ang_vel(N, q1d * A.z) B.set_ang_vel(N, q2d * A.z) O = Point('O') P = O.locatenew('P', l * A.x) R = P.locatenew('R', l * B.x) O.set_vel(N, 0) P.v2pt_theory(O, N, A) R.v2pt_theory(P, N, B) ParP = Particle('ParP', P, m) ParR = Particle('ParR', R, m) ParP.potential_energy = - m * g * l * cos(q1) ParR.potential_energy = - m * g * l * cos(q1) - m * g * l * cos(q2) L = Lagrangian(N, ParP, ParR) lm = LagrangesMethod(L, [q1, q2], bodies=[ParP, ParR]) lm.form_lagranges_equations() assert simplify(l*m*(2*g*sin(q1) + l*sin(q1)*sin(q2)*q2dd + l*sin(q1)*cos(q2)*q2d**2 - l*sin(q2)*cos(q1)*q2d**2 + l*cos(q1)*cos(q2)*q2dd + 2*l*q1dd) - lm.eom[0]) == 0 assert simplify(l*m*(g*sin(q2) + l*sin(q1)*sin(q2)*q1dd - l*sin(q1)*cos(q2)*q1d**2 + l*sin(q2)*cos(q1)*q1d**2 + l*cos(q1)*cos(q2)*q1dd + l*q2dd) - lm.eom[1]) == 0 assert lm.bodies == [ParP, ParR] def test_rolling_disc(): # Rolling Disc Example # Here the rolling disc is formed from the contact point up, removing the # need to introduce generalized speeds. Only 3 configuration and 3 # speed variables are need to describe this system, along with the # disc's mass and radius, and the local gravity. q1, q2, q3 = dynamicsymbols('q1 q2 q3') q1d, q2d, q3d = dynamicsymbols('q1 q2 q3', 1) r, m, g = symbols('r m g') # The kinematics are formed by a series of simple rotations. Each simple # rotation creates a new frame, and the next rotation is defined by the new # frame's basis vectors. This example uses a 3-1-2 series of rotations, or # Z, X, Y series of rotations. Angular velocity for this is defined using # the second frame's basis (the lean frame). N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) L = Y.orientnew('L', 'Axis', [q2, Y.x]) R = L.orientnew('R', 'Axis', [q3, L.y]) # This is the translational kinematics. We create a point with no velocity # in N; this is the contact point between the disc and ground. Next we form # the position vector from the contact point to the disc's center of mass. # Finally we form the velocity and acceleration of the disc. C = Point('C') C.set_vel(N, 0) Dmc = C.locatenew('Dmc', r * L.z) Dmc.v2pt_theory(C, N, R) # Forming the inertia dyadic. I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2) BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc)) # Finally we form the equations of motion, using the same steps we did # before. Supply the Lagrangian, the generalized speeds. BodyD.potential_energy = - m * g * r * cos(q2) Lag = Lagrangian(N, BodyD) q = [q1, q2, q3] q1 = Function('q1') q2 = Function('q2') q3 = Function('q3') l = LagrangesMethod(Lag, q) l.form_lagranges_equations() RHS = l.rhs() RHS.simplify() t = symbols('t') assert (l.mass_matrix[3:6] == [0, 5*m*r**2/4, 0]) assert RHS[4].simplify() == ( (-8*g*sin(q2(t)) + r*(5*sin(2*q2(t))*Derivative(q1(t), t) + 12*cos(q2(t))*Derivative(q3(t), t))*Derivative(q1(t), t))/(10*r)) assert RHS[5] == (-5*cos(q2(t))*Derivative(q1(t), t) + 6*tan(q2(t) )*Derivative(q3(t), t) + 4*Derivative(q1(t), t)/cos(q2(t)) )*Derivative(q2(t), t)
9,394
39.847826
98
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/tests/test_kane3.py
import warnings from sympy.core.compatibility import range from sympy import evalf, symbols, pi, sin, cos, sqrt, acos, Matrix from sympy.physics.mechanics import (ReferenceFrame, dynamicsymbols, inertia, KanesMethod, RigidBody, Point, dot, msubs) from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.pytest import slow, ON_TRAVIS, skip @slow def test_bicycle(): if ON_TRAVIS: skip("Too slow for travis.") # Code to get equations of motion for a bicycle modeled as in: # J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized # dynamics equations for the balance and steer of a bicycle: a benchmark # and review. Proceedings of The Royal Society (2007) 463, 1955-1982 # doi: 10.1098/rspa.2007.1857 # Note that this code has been crudely ported from Autolev, which is the # reason for some of the unusual naming conventions. It was purposefully as # similar as possible in order to aide debugging. # Declare Coordinates & Speeds # Simple definitions for qdots - qd = u # Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame # ang. rate (spinning motion), frame ang. rate (pitching motion), steering # frame ang. rate, and front wheel ang. rate (spinning motion). # Wheel positions are ignorable coordinates, so they are not introduced. q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5') q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1) u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6') u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1) # Declare System's Parameters WFrad, WRrad, htangle, forkoffset = symbols('WFrad WRrad htangle forkoffset') forklength, framelength, forkcg1 = symbols('forklength framelength forkcg1') forkcg3, framecg1, framecg3, Iwr11 = symbols('forkcg3 framecg1 framecg3 Iwr11') Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11') Iframe22, Iframe33, Iframe31, Ifork11 = symbols('Iframe22 Iframe33 Iframe31 Ifork11') Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g') mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr') # Set up reference frames for the system # N - inertial # Y - yaw # R - roll # WR - rear wheel, rotation angle is ignorable coordinate so not oriented # Frame - bicycle frame # TempFrame - statically rotated frame for easier reference inertia definition # Fork - bicycle fork # TempFork - statically rotated frame for easier reference inertia definition # WF - front wheel, again posses a ignorable coordinate N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) R = Y.orientnew('R', 'Axis', [q2, Y.x]) Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y]) WR = ReferenceFrame('WR') TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y]) Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x]) TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y]) WF = ReferenceFrame('WF') # Kinematics of the Bicycle First block of code is forming the positions of # the relevant points # rear wheel contact -> rear wheel mass center -> frame mass center + # frame/fork connection -> fork mass center + front wheel mass center -> # front wheel contact point WR_cont = Point('WR_cont') WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z) Steer = WR_mc.locatenew('Steer', framelength * Frame.z) Frame_mc = WR_mc.locatenew('Frame_mc', - framecg1 * Frame.x + framecg3 * Frame.z) Fork_mc = Steer.locatenew('Fork_mc', - forkcg1 * Fork.x + forkcg3 * Fork.z) WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z) WF_cont = WF_mc.locatenew('WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y - Y.z).normalize()) # Set the angular velocity of each frame. # Angular accelerations end up being calculated automatically by # differentiating the angular velocities when first needed. # u1 is yaw rate # u2 is roll rate # u3 is rear wheel rate # u4 is frame pitch rate # u5 is fork steer rate # u6 is front wheel rate Y.set_ang_vel(N, u1 * Y.z) R.set_ang_vel(Y, u2 * R.x) WR.set_ang_vel(Frame, u3 * Frame.y) Frame.set_ang_vel(R, u4 * Frame.y) Fork.set_ang_vel(Frame, u5 * Fork.x) WF.set_ang_vel(Fork, u6 * Fork.y) # Form the velocities of the previously defined points, using the 2 - point # theorem (written out by hand here). Accelerations again are calculated # automatically when first needed. WR_cont.set_vel(N, 0) WR_mc.v2pt_theory(WR_cont, N, WR) Steer.v2pt_theory(WR_mc, N, Frame) Frame_mc.v2pt_theory(WR_mc, N, Frame) Fork_mc.v2pt_theory(Steer, N, Fork) WF_mc.v2pt_theory(Steer, N, Fork) WF_cont.v2pt_theory(WF_mc, N, WF) # Sets the inertias of each body. Uses the inertia frame to construct the # inertia dyadics. Wheel inertias are only defined by principle moments of # inertia, and are in fact constant in the frame and fork reference frames; # it is for this reason that the orientations of the wheels does not need # to be defined. The frame and fork inertias are defined in the 'Temp' # frames which are fixed to the appropriate body frames; this is to allow # easier input of the reference values of the benchmark paper. Note that # due to slightly different orientations, the products of inertia need to # have their signs flipped; this is done later when entering the numerical # value. Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc) Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc) WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc) WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc) # Declaration of the RigidBody containers. :: BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I) BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I) BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I) BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I) # The kinematic differential equations; they are defined quite simply. Each # entry in this list is equal to zero. kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5] # The nonholonomic constraints are the velocity of the front wheel contact # point dotted into the X, Y, and Z directions; the yaw frame is used as it # is "closer" to the front wheel (1 less DCM connecting them). These # constraints force the velocity of the front wheel contact point to be 0 # in the inertial frame; the X and Y direction constraints enforce a # "no-slip" condition, and the Z direction constraint forces the front # wheel contact point to not move away from the ground frame, essentially # replicating the holonomic constraint which does not allow the frame pitch # to change in an invalid fashion. conlist_speed = [WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z] # The holonomic constraint is that the position from the rear wheel contact # point to the front wheel contact point when dotted into the # normal-to-ground plane direction must be zero; effectively that the front # and rear wheel contact points are always touching the ground plane. This # is actually not part of the dynamic equations, but instead is necessary # for the lineraization process. conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z] # The force list; each body has the appropriate gravitational force applied # at its mass center. FL = [(Frame_mc, -mframe * g * Y.z), (Fork_mc, -mfork * g * Y.z), (WF_mc, -mwf * g * Y.z), (WR_mc, -mwr * g * Y.z)] BL = [BodyFrame, BodyFork, BodyWR, BodyWF] # The N frame is the inertial frame, coordinates are supplied in the order # of independent, dependent coordinates, as are the speeds. The kinematic # differential equation are also entered here. Here the dependent speeds # are specified, in the same order they were provided in earlier, along # with the non-holonomic constraints. The dependent coordinate is also # provided, with the holonomic constraint. Again, this is only provided # for the linearization process. KM = KanesMethod(N, q_ind=[q1, q2, q5], q_dependent=[q4], configuration_constraints=conlist_coord, u_ind=[u2, u3, u5], u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed, kd_eqs=kd) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) (fr, frstar) = KM.kanes_equations(FL, BL) # This is the start of entering in the numerical values from the benchmark # paper to validate the eigen values of the linearized equations from this # model to the reference eigen values. Look at the aforementioned paper for # more information. Some of these are intermediate values, used to # transform values from the paper into the coordinate systems used in this # model. PaperRadRear = 0.3 PaperRadFront = 0.35 HTA = evalf.N(pi / 2 - pi / 10) TrailPaper = 0.08 rake = evalf.N(-(TrailPaper*sin(HTA)-(PaperRadFront*cos(HTA)))) PaperWb = 1.02 PaperFrameCgX = 0.3 PaperFrameCgZ = 0.9 PaperForkCgX = 0.9 PaperForkCgZ = 0.7 FrameLength = evalf.N(PaperWb*sin(HTA)-(rake-(PaperRadFront-PaperRadRear)*cos(HTA))) FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear-(PaperFrameCgX/sin(HTA))*cos(HTA))*sin(HTA)) FrameCGPar = evalf.N((PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA))) tempa = evalf.N((PaperForkCgZ - PaperRadFront)) tempb = evalf.N((PaperWb-PaperForkCgX)) tempc = evalf.N(sqrt(tempa**2+tempb**2)) PaperForkL = evalf.N((PaperWb*cos(HTA)-(PaperRadFront-PaperRadRear)*sin(HTA))) ForkCGNorm = evalf.N(rake+(tempc * sin(pi/2-HTA-acos(tempa/tempc)))) ForkCGPar = evalf.N(tempc * cos((pi/2-HTA)-acos(tempa/tempc))-PaperForkL) # Here is the final assembly of the numerical values. The symbol 'v' is the # forward speed of the bicycle (a concept which only makes sense in the # upright, static equilibrium case?). These are in a dictionary which will # later be substituted in. Again the sign on the *product* of inertia # values is flipped here, due to different orientations of coordinate # systems. v = symbols('v') val_dict = {WFrad: PaperRadFront, WRrad: PaperRadRear, htangle: HTA, forkoffset: rake, forklength: PaperForkL, framelength: FrameLength, forkcg1: ForkCGPar, forkcg3: ForkCGNorm, framecg1: FrameCGNorm, framecg3: FrameCGPar, Iwr11: 0.0603, Iwr22: 0.12, Iwf11: 0.1405, Iwf22: 0.28, Ifork11: 0.05892, Ifork22: 0.06, Ifork33: 0.00708, Ifork31: 0.00756, Iframe11: 9.2, Iframe22: 11, Iframe33: 2.8, Iframe31: -2.4, mfork: 4, mframe: 85, mwf: 3, mwr: 2, g: 9.81, q1: 0, q2: 0, q4: 0, q5: 0, u1: 0, u2: 0, u3: v / PaperRadRear, u4: 0, u5: 0, u6: v / PaperRadFront} # Linearizes the forcing vector; the equations are set up as MM udot = # forcing, where MM is the mass matrix, udot is the vector representing the # time derivatives of the generalized speeds, and forcing is a vector which # contains both external forcing terms and internal forcing terms, such as # centripital or coriolis forces. This actually returns a matrix with as # many rows as *total* coordinates and speeds, but only as many columns as # independent coordinates and speeds. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) forcing_lin = KM.linearize()[0] # As mentioned above, the size of the linearized forcing terms is expanded # to include both q's and u's, so the mass matrix must have this done as # well. This will likely be changed to be part of the linearized process, # for future reference. MM_full = KM.mass_matrix_full MM_full_s = msubs(MM_full, val_dict) forcing_lin_s = msubs(forcing_lin, KM.kindiffdict(), val_dict) MM_full_s = MM_full_s.evalf() forcing_lin_s = forcing_lin_s.evalf() # Finally, we construct an "A" matrix for the form xdot = A x (x being the # state vector, although in this case, the sizes are a little off). The # following line extracts only the minimum entries required for eigenvalue # analysis, which correspond to rows and columns for lean, steer, lean # rate, and steer rate. Amat = MM_full_s.inv() * forcing_lin_s A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5]) # Precomputed for comparison Res = Matrix([[ 0, 0, 1.0, 0], [ 0, 0, 0, 1.0], [9.48977444677355, -0.891197738059089*v**2 - 0.571523173729245, -0.105522449805691*v, -0.330515398992311*v], [11.7194768719633, -1.97171508499972*v**2 + 30.9087533932407, 3.67680523332152*v, -3.08486552743311*v]]) # Actual eigenvalue comparison eps = 1.e-12 for i in range(6): error = Res.subs(v, i) - A.subs(v, i) assert all(abs(x) < eps for x in error)
14,636
48.282828
156
py
cba-pipeline-public
cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/sympy/physics/mechanics/tests/test_linearize.py
from __future__ import division import warnings from sympy.core.backend import symbols, Matrix, cos, sin, atan, sqrt from sympy import solve, simplify from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point,\ dot, cross, inertia, KanesMethod, Particle, RigidBody, Lagrangian,\ LagrangesMethod from sympy.utilities.pytest import slow from sympy.utilities.exceptions import SymPyDeprecationWarning @slow def test_linearize_rolling_disc_kane(): # Symbols for time and constant parameters t, r, m, g, v = symbols('t r m g v') # Configuration variables and their time derivatives q1, q2, q3, q4, q5, q6 = q = dynamicsymbols('q1:7') q1d, q2d, q3d, q4d, q5d, q6d = qd = [qi.diff(t) for qi in q] # Generalized speeds and their time derivatives u = dynamicsymbols('u:6') u1, u2, u3, u4, u5, u6 = u = dynamicsymbols('u1:7') u1d, u2d, u3d, u4d, u5d, u6d = [ui.diff(t) for ui in u] # Reference frames N = ReferenceFrame('N') # Inertial frame NO = Point('NO') # Inertial origin A = N.orientnew('A', 'Axis', [q1, N.z]) # Yaw intermediate frame B = A.orientnew('B', 'Axis', [q2, A.x]) # Lean intermediate frame C = B.orientnew('C', 'Axis', [q3, B.y]) # Disc fixed frame CO = NO.locatenew('CO', q4*N.x + q5*N.y + q6*N.z) # Disc center # Disc angular velocity in N expressed using time derivatives of coordinates w_c_n_qd = C.ang_vel_in(N) w_b_n_qd = B.ang_vel_in(N) # Inertial angular velocity and angular acceleration of disc fixed frame C.set_ang_vel(N, u1*B.x + u2*B.y + u3*B.z) # Disc center velocity in N expressed using time derivatives of coordinates v_co_n_qd = CO.pos_from(NO).dt(N) # Disc center velocity in N expressed using generalized speeds CO.set_vel(N, u4*C.x + u5*C.y + u6*C.z) # Disc Ground Contact Point P = CO.locatenew('P', r*B.z) P.v2pt_theory(CO, N, C) # Configuration constraint f_c = Matrix([q6 - dot(CO.pos_from(P), N.z)]) # Velocity level constraints f_v = Matrix([dot(P.vel(N), uv) for uv in C]) # Kinematic differential equations kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] + [dot(v_co_n_qd - CO.vel(N), uv) for uv in N]) qdots = solve(kindiffs, qd) # Set angular velocity of remaining frames B.set_ang_vel(N, w_b_n_qd.subs(qdots)) C.set_ang_acc(N, C.ang_vel_in(N).dt(B) + cross(B.ang_vel_in(N), C.ang_vel_in(N))) # Active forces F_CO = m*g*A.z # Create inertia dyadic of disc C about point CO I = (m * r**2) / 4 J = (m * r**2) / 2 I_C_CO = inertia(C, I, J, I) Disc = RigidBody('Disc', CO, C, m, (I_C_CO, CO)) BL = [Disc] FL = [(CO, F_CO)] KM = KanesMethod(N, [q1, q2, q3, q4, q5], [u1, u2, u3], kd_eqs=kindiffs, q_dependent=[q6], configuration_constraints=f_c, u_dependent=[u4, u5, u6], velocity_constraints=f_v) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) (fr, fr_star) = KM.kanes_equations(FL, BL) # Test generalized form equations linearizer = KM.to_linearizer() assert linearizer.f_c == f_c assert linearizer.f_v == f_v assert linearizer.f_a == f_v.diff(t) sol = solve(linearizer.f_0 + linearizer.f_1, qd) for qi in qd: assert sol[qi] == qdots[qi] assert simplify(linearizer.f_2 + linearizer.f_3 - fr - fr_star) == Matrix([0, 0, 0]) # Perform the linearization # Precomputed operating point q_op = {q6: -r*cos(q2)} u_op = {u1: 0, u2: sin(q2)*q1d + q3d, u3: cos(q2)*q1d, u4: -r*(sin(q2)*q1d + q3d)*cos(q3), u5: 0, u6: -r*(sin(q2)*q1d + q3d)*sin(q3)} qd_op = {q2d: 0, q4d: -r*(sin(q2)*q1d + q3d)*cos(q1), q5d: -r*(sin(q2)*q1d + q3d)*sin(q1), q6d: 0} ud_op = {u1d: 4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5, u2d: 0, u3d: 0, u4d: r*(sin(q2)*sin(q3)*q1d*q3d + sin(q3)*q3d**2), u5d: r*(4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5), u6d: -r*(sin(q2)*cos(q3)*q1d*q3d + cos(q3)*q3d**2)} A, B = linearizer.linearize(op_point=[q_op, u_op, qd_op, ud_op], A_and_B=True, simplify=True) upright_nominal = {q1d: 0, q2: 0, m: 1, r: 1, g: 1} # Precomputed solution A_sol = Matrix([[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [sin(q1)*q3d, 0, 0, 0, 0, -sin(q1), -cos(q1), 0], [-cos(q1)*q3d, 0, 0, 0, 0, cos(q1), -sin(q1), 0], [0, 4/5, 0, 0, 0, 0, 0, 6*q3d/5], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -2*q3d, 0, 0]]) B_sol = Matrix([]) # Check that linearization is correct assert A.subs(upright_nominal) == A_sol assert B.subs(upright_nominal) == B_sol # Check eigenvalues at critical speed are all zero: assert A.subs(upright_nominal).subs(q3d, 1/sqrt(3)).eigenvals() == {0: 8} def test_linearize_pendulum_kane_minimal(): q1 = dynamicsymbols('q1') # angle of pendulum u1 = dynamicsymbols('u1') # Angular velocity q1d = dynamicsymbols('q1', 1) # Angular velocity L, m, t = symbols('L, m, t') g = 9.8 # Compose world frame N = ReferenceFrame('N') pN = Point('N*') pN.set_vel(N, 0) # A.x is along the pendulum A = N.orientnew('A', 'axis', [q1, N.z]) A.set_ang_vel(N, u1*N.z) # Locate point P relative to the origin N* P = pN.locatenew('P', L*A.x) P.v2pt_theory(pN, N, A) pP = Particle('pP', P, m) # Create Kinematic Differential Equations kde = Matrix([q1d - u1]) # Input the force resultant at P R = m*g*N.x # Solve for eom with kanes method KM = KanesMethod(N, q_ind=[q1], u_ind=[u1], kd_eqs=kde) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) (fr, frstar) = KM.kanes_equations([(P, R)], [pP]) # Linearize A, B, inp_vec = KM.linearize(A_and_B=True, simplify=True) assert A == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]]) assert B == Matrix([]) def test_linearize_pendulum_kane_nonminimal(): # Create generalized coordinates and speeds for this non-minimal realization # q1, q2 = N.x and N.y coordinates of pendulum # u1, u2 = N.x and N.y velocities of pendulum q1, q2 = dynamicsymbols('q1:3') q1d, q2d = dynamicsymbols('q1:3', level=1) u1, u2 = dynamicsymbols('u1:3') u1d, u2d = dynamicsymbols('u1:3', level=1) L, m, t = symbols('L, m, t') g = 9.8 # Compose world frame N = ReferenceFrame('N') pN = Point('N*') pN.set_vel(N, 0) # A.x is along the pendulum theta1 = atan(q2/q1) A = N.orientnew('A', 'axis', [theta1, N.z]) # Locate the pendulum mass P = pN.locatenew('P1', q1*N.x + q2*N.y) pP = Particle('pP', P, m) # Calculate the kinematic differential equations kde = Matrix([q1d - u1, q2d - u2]) dq_dict = solve(kde, [q1d, q2d]) # Set velocity of point P P.set_vel(N, P.pos_from(pN).dt(N).subs(dq_dict)) # Configuration constraint is length of pendulum f_c = Matrix([P.pos_from(pN).magnitude() - L]) # Velocity constraint is that the velocity in the A.x direction is # always zero (the pendulum is never getting longer). f_v = Matrix([P.vel(N).express(A).dot(A.x)]) f_v.simplify() # Acceleration constraints is the time derivative of the velocity constraint f_a = f_v.diff(t) f_a.simplify() # Input the force resultant at P R = m*g*N.x # Derive the equations of motion using the KanesMethod class. KM = KanesMethod(N, q_ind=[q2], u_ind=[u2], q_dependent=[q1], u_dependent=[u1], configuration_constraints=f_c, velocity_constraints=f_v, acceleration_constraints=f_a, kd_eqs=kde) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=SymPyDeprecationWarning) (fr, frstar) = KM.kanes_equations([(P, R)], [pP]) # Set the operating point to be straight down, and non-moving q_op = {q1: L, q2: 0} u_op = {u1: 0, u2: 0} ud_op = {u1d: 0, u2d: 0} A, B, inp_vec = KM.linearize(op_point=[q_op, u_op, ud_op], A_and_B=True, simplify=True) assert A.expand() == Matrix([[0, 1], [-9.8/L, 0]]) assert B == Matrix([]) def test_linearize_pendulum_lagrange_minimal(): q1 = dynamicsymbols('q1') # angle of pendulum q1d = dynamicsymbols('q1', 1) # Angular velocity L, m, t = symbols('L, m, t') g = 9.8 # Compose world frame N = ReferenceFrame('N') pN = Point('N*') pN.set_vel(N, 0) # A.x is along the pendulum A = N.orientnew('A', 'axis', [q1, N.z]) A.set_ang_vel(N, q1d*N.z) # Locate point P relative to the origin N* P = pN.locatenew('P', L*A.x) P.v2pt_theory(pN, N, A) pP = Particle('pP', P, m) # Solve for eom with Lagranges method Lag = Lagrangian(N, pP) LM = LagrangesMethod(Lag, [q1], forcelist=[(P, m*g*N.x)], frame=N) LM.form_lagranges_equations() # Linearize A, B, inp_vec = LM.linearize([q1], [q1d], A_and_B=True) assert A == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]]) assert B == Matrix([]) def test_linearize_pendulum_lagrange_nonminimal(): q1, q2 = dynamicsymbols('q1:3') q1d, q2d = dynamicsymbols('q1:3', level=1) L, m, t = symbols('L, m, t') g = 9.8 # Compose World Frame N = ReferenceFrame('N') pN = Point('N*') pN.set_vel(N, 0) # A.x is along the pendulum theta1 = atan(q2/q1) A = N.orientnew('A', 'axis', [theta1, N.z]) # Create point P, the pendulum mass P = pN.locatenew('P1', q1*N.x + q2*N.y) P.set_vel(N, P.pos_from(pN).dt(N)) pP = Particle('pP', P, m) # Constraint Equations f_c = Matrix([q1**2 + q2**2 - L**2]) # Calculate the lagrangian, and form the equations of motion Lag = Lagrangian(N, pP) LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c, forcelist=[(P, m*g*N.x)], frame=N) LM.form_lagranges_equations() # Compose operating point op_point = {q1: L, q2: 0, q1d: 0, q2d: 0, q1d.diff(t): 0, q2d.diff(t): 0} # Solve for multiplier operating point lam_op = LM.solve_multipliers(op_point=op_point) op_point.update(lam_op) # Perform the Linearization A, B, inp_vec = LM.linearize([q2], [q2d], [q1], [q1d], op_point=op_point, A_and_B=True) assert A == Matrix([[0, 1], [-9.8/L, 0]]) assert B == Matrix([]) def test_linearize_rolling_disc_lagrange(): q1, q2, q3 = q = dynamicsymbols('q1 q2 q3') q1d, q2d, q3d = qd = dynamicsymbols('q1 q2 q3', 1) r, m, g = symbols('r m g') N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) L = Y.orientnew('L', 'Axis', [q2, Y.x]) R = L.orientnew('R', 'Axis', [q3, L.y]) C = Point('C') C.set_vel(N, 0) Dmc = C.locatenew('Dmc', r * L.z) Dmc.v2pt_theory(C, N, R) I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2) BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc)) BodyD.potential_energy = - m * g * r * cos(q2) Lag = Lagrangian(N, BodyD) l = LagrangesMethod(Lag, q) l.form_lagranges_equations() # Linearize about steady-state upright rolling op_point = {q1: 0, q2: 0, q3: 0, q1d: 0, q2d: 0, q1d.diff(): 0, q2d.diff(): 0, q3d.diff(): 0} A = l.linearize(q_ind=q, qd_ind=qd, op_point=op_point, A_and_B=True)[0] sol = Matrix([[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, -6*q3d, 0], [0, -4*g/(5*r), 0, 6*q3d/5, 0, 0], [0, 0, 0, 0, 0, 0]]) assert A == sol
12,074
34.410557
97
py