repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_gamma_matrix | def calculate_gamma_matrix(magnetic_states, Omega=1, einsteinA=None,
numeric=True):
ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
β‘ Ξ Ξ Ξ β€
β’ β β β 0 0 0 0 0 β₯
β’ 3 3 3 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ βββ 0 ββ ββ ββ 0 0 β₯
β’ 12 12 10 20 60 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ 0 βββ 0 ββ ββ ββ 0 β₯
β’ 12 12 20 15 20 β₯
β’ β₯
β’ 5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’ 0 βββ βββ 0 0 ββ ββ βββ₯
β’ 12 12 60 20 10β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ β 0 0 β β 0 0 0 β₯
β’ 2 3 6 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ β β 0 β ββ β 0 0 β₯
β’ 4 4 6 12 4 β₯
β’ β₯
β’Ξ Ξ Ξ Ξ Ξ β₯
β’ββ β ββ 0 β 0 β 0 β₯
β’12 3 12 4 4 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ 0 β β 0 0 β ββ β β₯
β’ 4 4 4 12 6 β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ 0 0 β 0 0 0 β β β₯
β’ 2 6 3 β₯
β’ β₯
β’ 0 0 0 Ξ 0 0 0 0 β₯
β’ β₯
β’ Ξ 2β
Ξ β₯
β’ 0 0 0 β βββ 0 0 0 β₯
β’ 3 3 β₯
β’ β₯
β’ Ξ 8β
Ξ 2β
Ξ β₯
β’ 0 0 0 ββ βββ βββ 0 0 β₯
β’ 15 15 5 β₯
β’ β₯
β’ Ξ 3β
Ξ Ξ β₯
β’ 0 0 0 0 β βββ β 0 β₯
β’ 5 5 5 β₯
β’ β₯
β’ 2β
Ξ 8β
Ξ Ξ β₯
β’ 0 0 0 0 0 βββ βββ βββ₯
β’ 5 15 15β₯
β’ β₯
β’ 2β
Ξ Ξ β₯
β’ 0 0 0 0 0 0 βββ β β₯
β’ 3 3 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 Ξ β¦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
β‘Ξβ€
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β£Ξβ¦
"""
Ne = len(magnetic_states)
fine_states = []
fine_map = {}
ii = 0
for ei in magnetic_states:
fine = State(ei.element, ei.isotope, ei.n, ei.l, ei.j)
if fine not in fine_states:
fine_states += [fine]
ii += 1
fine_map.update({ei: ii-1})
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
if einsteinA is not None:
iii = fine_map[ei]
jjj = fine_map[ej]
einsteinAij = einsteinA[iii, jjj]
else:
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2*ji+1)
gammaij *= (2*fi+1)
gammaij *= (2*fj+1)
if numeric:
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
else:
gammaij *= wigner_6j(ji, fi, II, fj, jj, 1)**2
gammaij *= sum([wigner_3j(fj, 1, fi, -mj, q, mi)**2
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | python | def calculate_gamma_matrix(magnetic_states, Omega=1, einsteinA=None,
numeric=True):
ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
β‘ Ξ Ξ Ξ β€
β’ β β β 0 0 0 0 0 β₯
β’ 3 3 3 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ βββ 0 ββ ββ ββ 0 0 β₯
β’ 12 12 10 20 60 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ 0 βββ 0 ββ ββ ββ 0 β₯
β’ 12 12 20 15 20 β₯
β’ β₯
β’ 5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’ 0 βββ βββ 0 0 ββ ββ βββ₯
β’ 12 12 60 20 10β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ β 0 0 β β 0 0 0 β₯
β’ 2 3 6 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ β β 0 β ββ β 0 0 β₯
β’ 4 4 6 12 4 β₯
β’ β₯
β’Ξ Ξ Ξ Ξ Ξ β₯
β’ββ β ββ 0 β 0 β 0 β₯
β’12 3 12 4 4 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ 0 β β 0 0 β ββ β β₯
β’ 4 4 4 12 6 β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ 0 0 β 0 0 0 β β β₯
β’ 2 6 3 β₯
β’ β₯
β’ 0 0 0 Ξ 0 0 0 0 β₯
β’ β₯
β’ Ξ 2β
Ξ β₯
β’ 0 0 0 β βββ 0 0 0 β₯
β’ 3 3 β₯
β’ β₯
β’ Ξ 8β
Ξ 2β
Ξ β₯
β’ 0 0 0 ββ βββ βββ 0 0 β₯
β’ 15 15 5 β₯
β’ β₯
β’ Ξ 3β
Ξ Ξ β₯
β’ 0 0 0 0 β βββ β 0 β₯
β’ 5 5 5 β₯
β’ β₯
β’ 2β
Ξ 8β
Ξ Ξ β₯
β’ 0 0 0 0 0 βββ βββ βββ₯
β’ 5 15 15β₯
β’ β₯
β’ 2β
Ξ Ξ β₯
β’ 0 0 0 0 0 0 βββ β β₯
β’ 3 3 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 Ξ β¦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
β‘Ξβ€
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β£Ξβ¦
"""
Ne = len(magnetic_states)
fine_states = []
fine_map = {}
ii = 0
for ei in magnetic_states:
fine = State(ei.element, ei.isotope, ei.n, ei.l, ei.j)
if fine not in fine_states:
fine_states += [fine]
ii += 1
fine_map.update({ei: ii-1})
II = magnetic_states[0].i
gamma = [[0.0 for j in range(Ne)] for i in range(Ne)]
for i in range(Ne):
for j in range(i):
ei = magnetic_states[i]
ej = magnetic_states[j]
if einsteinA is not None:
iii = fine_map[ei]
jjj = fine_map[ej]
einsteinAij = einsteinA[iii, jjj]
else:
einsteinAij = Transition(ei, ej).einsteinA
if einsteinAij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
gammaij = (2*ji+1)
gammaij *= (2*fi+1)
gammaij *= (2*fj+1)
if numeric:
gammaij *= float(wigner_6j(ji, fi, II, fj, jj, 1)**2)
gammaij *= sum([float(wigner_3j(fj, 1, fi, -mj, q, mi)**2)
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gammaij = float(gammaij)
else:
gammaij *= wigner_6j(ji, fi, II, fj, jj, 1)**2
gammaij *= sum([wigner_3j(fj, 1, fi, -mj, q, mi)**2
for q in [-1, 0, 1]])
gammaij *= einsteinAij/Omega
gamma[i][j] = gammaij
gamma[j][i] = -gammaij
return gamma | [
"def",
"calculate_gamma_matrix",
"(",
"magnetic_states",
",",
"Omega",
"=",
"1",
",",
"einsteinA",
"=",
"None",
",",
"numeric",
"=",
"True",
")",
":",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"fine_states",
"=",
"[",
"]",
"fine_map",
"=",
"{",
"}",
"ii",
"=",
"0",
"for",
"ei",
"in",
"magnetic_states",
":",
"fine",
"=",
"State",
"(",
"ei",
".",
"element",
",",
"ei",
".",
"isotope",
",",
"ei",
".",
"n",
",",
"ei",
".",
"l",
",",
"ei",
".",
"j",
")",
"if",
"fine",
"not",
"in",
"fine_states",
":",
"fine_states",
"+=",
"[",
"fine",
"]",
"ii",
"+=",
"1",
"fine_map",
".",
"update",
"(",
"{",
"ei",
":",
"ii",
"-",
"1",
"}",
")",
"II",
"=",
"magnetic_states",
"[",
"0",
"]",
".",
"i",
"gamma",
"=",
"[",
"[",
"0.0",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"ei",
"=",
"magnetic_states",
"[",
"i",
"]",
"ej",
"=",
"magnetic_states",
"[",
"j",
"]",
"if",
"einsteinA",
"is",
"not",
"None",
":",
"iii",
"=",
"fine_map",
"[",
"ei",
"]",
"jjj",
"=",
"fine_map",
"[",
"ej",
"]",
"einsteinAij",
"=",
"einsteinA",
"[",
"iii",
",",
"jjj",
"]",
"else",
":",
"einsteinAij",
"=",
"Transition",
"(",
"ei",
",",
"ej",
")",
".",
"einsteinA",
"if",
"einsteinAij",
"!=",
"0",
":",
"ji",
"=",
"ei",
".",
"j",
"jj",
"=",
"ej",
".",
"j",
"fi",
"=",
"ei",
".",
"f",
"fj",
"=",
"ej",
".",
"f",
"mi",
"=",
"ei",
".",
"m",
"mj",
"=",
"ej",
".",
"m",
"gammaij",
"=",
"(",
"2",
"*",
"ji",
"+",
"1",
")",
"gammaij",
"*=",
"(",
"2",
"*",
"fi",
"+",
"1",
")",
"gammaij",
"*=",
"(",
"2",
"*",
"fj",
"+",
"1",
")",
"if",
"numeric",
":",
"gammaij",
"*=",
"float",
"(",
"wigner_6j",
"(",
"ji",
",",
"fi",
",",
"II",
",",
"fj",
",",
"jj",
",",
"1",
")",
"**",
"2",
")",
"gammaij",
"*=",
"sum",
"(",
"[",
"float",
"(",
"wigner_3j",
"(",
"fj",
",",
"1",
",",
"fi",
",",
"-",
"mj",
",",
"q",
",",
"mi",
")",
"**",
"2",
")",
"for",
"q",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"]",
")",
"gammaij",
"*=",
"einsteinAij",
"/",
"Omega",
"gammaij",
"=",
"float",
"(",
"gammaij",
")",
"else",
":",
"gammaij",
"*=",
"wigner_6j",
"(",
"ji",
",",
"fi",
",",
"II",
",",
"fj",
",",
"jj",
",",
"1",
")",
"**",
"2",
"gammaij",
"*=",
"sum",
"(",
"[",
"wigner_3j",
"(",
"fj",
",",
"1",
",",
"fi",
",",
"-",
"mj",
",",
"q",
",",
"mi",
")",
"**",
"2",
"for",
"q",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"]",
")",
"gammaij",
"*=",
"einsteinAij",
"/",
"Omega",
"gamma",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"gammaij",
"gamma",
"[",
"j",
"]",
"[",
"i",
"]",
"=",
"-",
"gammaij",
"return",
"gamma"
] | ur"""Calculate the matrix of decay between states.
This function calculates the matrix :math:`\gamma_{ij}` of decay rates
between states :math:`|i\rangle` and :math:`|j\rangle` (in the units
specified by the Omega argument).
>>> import numpy as np
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> magnetic_states = make_list_of_states([g, e], "magnetic")
To return the rates in 10^6 rad /s:
>>> gamma = np.array(calculate_gamma_matrix(magnetic_states, Omega=1e6))
The :math:`5P_{3/2}, 5S_{1/2}` block of this matrix is
>>> print(gamma[8:, :8]/2/np.pi)
[[2.0217 2.0217 2.0217 0. 0. 0. 0. 0. ]
[2.5271 2.5271 0. 0.6065 0.3033 0.1011 0. 0. ]
[2.5271 0. 2.5271 0. 0.3033 0.4043 0.3033 0. ]
[0. 2.5271 2.5271 0. 0. 0.1011 0.3033 0.6065]
[3.0325 0. 0. 2.0217 1.0108 0. 0. 0. ]
[1.5163 1.5163 0. 1.0108 0.5054 1.5163 0. 0. ]
[0.5054 2.0217 0.5054 0. 1.5163 0. 1.5163 0. ]
[0. 1.5163 1.5163 0. 0. 1.5163 0.5054 1.0108]
[0. 0. 3.0325 0. 0. 0. 1.0108 2.0217]
[0. 0. 0. 6.065 0. 0. 0. 0. ]
[0. 0. 0. 2.0217 4.0433 0. 0. 0. ]
[0. 0. 0. 0.4043 3.2347 2.426 0. 0. ]
[0. 0. 0. 0. 1.213 3.639 1.213 0. ]
[0. 0. 0. 0. 0. 2.426 3.2347 0.4043]
[0. 0. 0. 0. 0. 0. 4.0433 2.0217]
[0. 0. 0. 0. 0. 0. 0. 6.065 ]]
Let us test if all D2 lines decay at the expected rate (6.065 MHz):
>>> Gamma = [sum([gamma[i][j] for j in range(i)])/2/pi
... for i in range(len(magnetic_states))][8:]
>>> for Gammai in Gamma: print("{:2.3f}".format(Gammai))
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
6.065
Let us do this symbolically
>>> from sympy import Matrix, pprint, symbols
>>> Gamma = symbols("Gamma", positive=True)
>>> einsteinA = Matrix([[0, -Gamma], [Gamma, 0]])
>>> gamma = calculate_gamma_matrix(magnetic_states, einsteinA=einsteinA,
... numeric=False)
>>> pprint(Matrix(gamma)[8:, :8])
β‘ Ξ Ξ Ξ β€
β’ β β β 0 0 0 0 0 β₯
β’ 3 3 3 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ βββ 0 ββ ββ ββ 0 0 β₯
β’ 12 12 10 20 60 β₯
β’ β₯
β’5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’βββ 0 βββ 0 ββ ββ ββ 0 β₯
β’ 12 12 20 15 20 β₯
β’ β₯
β’ 5β
Ξ 5β
Ξ Ξ Ξ Ξ β₯
β’ 0 βββ βββ 0 0 ββ ββ βββ₯
β’ 12 12 60 20 10β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ β 0 0 β β 0 0 0 β₯
β’ 2 3 6 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ β β 0 β ββ β 0 0 β₯
β’ 4 4 6 12 4 β₯
β’ β₯
β’Ξ Ξ Ξ Ξ Ξ β₯
β’ββ β ββ 0 β 0 β 0 β₯
β’12 3 12 4 4 β₯
β’ β₯
β’ Ξ Ξ Ξ Ξ Ξ β₯
β’ 0 β β 0 0 β ββ β β₯
β’ 4 4 4 12 6 β₯
β’ β₯
β’ Ξ Ξ Ξ β₯
β’ 0 0 β 0 0 0 β β β₯
β’ 2 6 3 β₯
β’ β₯
β’ 0 0 0 Ξ 0 0 0 0 β₯
β’ β₯
β’ Ξ 2β
Ξ β₯
β’ 0 0 0 β βββ 0 0 0 β₯
β’ 3 3 β₯
β’ β₯
β’ Ξ 8β
Ξ 2β
Ξ β₯
β’ 0 0 0 ββ βββ βββ 0 0 β₯
β’ 15 15 5 β₯
β’ β₯
β’ Ξ 3β
Ξ Ξ β₯
β’ 0 0 0 0 β βββ β 0 β₯
β’ 5 5 5 β₯
β’ β₯
β’ 2β
Ξ 8β
Ξ Ξ β₯
β’ 0 0 0 0 0 βββ βββ βββ₯
β’ 5 15 15β₯
β’ β₯
β’ 2β
Ξ Ξ β₯
β’ 0 0 0 0 0 0 βββ β β₯
β’ 3 3 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 Ξ β¦
>>> Gamma =Matrix([sum([gamma[i][j] for j in range(i)])
... for i in range(len(magnetic_states))][8:])
>>> pprint(Gamma)
β‘Ξβ€
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β’Ξβ₯
β’ β₯
β£Ξβ¦ | [
"ur",
"Calculate",
"the",
"matrix",
"of",
"decay",
"between",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1489-L1709 |
oscarlazoarjona/fast | fast/atomic_structure.py | reduced_matrix_element | def reduced_matrix_element(fine_statei, fine_statej, convention=1):
r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051
"""
if fine_statei == fine_statej:
return 0.0
t = Transition(fine_statei, fine_statej)
einsteinAij = t.einsteinA
omega0 = t.omega
Ji = fine_statei.j; Jj = fine_statej.j
factor = sqrt(3*Pi*hbar*c**3*epsilon0)/e
if omega0 < 0:
rij = factor*sqrt((2*Jj+1)*einsteinAij/omega0**3)/a0
else:
rij = reduced_matrix_element(fine_statej, fine_statei,
convention=convention)
rij *= (-1)**(Jj-Ji)
# We return the Brink matrix element.
if convention == 2:
if omega0 < 0:
rij = rij / sqrt(2*Ji+1)
else:
rij = rij / sqrt(2*Ji+1)
return rij | python | def reduced_matrix_element(fine_statei, fine_statej, convention=1):
r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051
"""
if fine_statei == fine_statej:
return 0.0
t = Transition(fine_statei, fine_statej)
einsteinAij = t.einsteinA
omega0 = t.omega
Ji = fine_statei.j; Jj = fine_statej.j
factor = sqrt(3*Pi*hbar*c**3*epsilon0)/e
if omega0 < 0:
rij = factor*sqrt((2*Jj+1)*einsteinAij/omega0**3)/a0
else:
rij = reduced_matrix_element(fine_statej, fine_statei,
convention=convention)
rij *= (-1)**(Jj-Ji)
# We return the Brink matrix element.
if convention == 2:
if omega0 < 0:
rij = rij / sqrt(2*Ji+1)
else:
rij = rij / sqrt(2*Ji+1)
return rij | [
"def",
"reduced_matrix_element",
"(",
"fine_statei",
",",
"fine_statej",
",",
"convention",
"=",
"1",
")",
":",
"if",
"fine_statei",
"==",
"fine_statej",
":",
"return",
"0.0",
"t",
"=",
"Transition",
"(",
"fine_statei",
",",
"fine_statej",
")",
"einsteinAij",
"=",
"t",
".",
"einsteinA",
"omega0",
"=",
"t",
".",
"omega",
"Ji",
"=",
"fine_statei",
".",
"j",
"Jj",
"=",
"fine_statej",
".",
"j",
"factor",
"=",
"sqrt",
"(",
"3",
"*",
"Pi",
"*",
"hbar",
"*",
"c",
"**",
"3",
"*",
"epsilon0",
")",
"/",
"e",
"if",
"omega0",
"<",
"0",
":",
"rij",
"=",
"factor",
"*",
"sqrt",
"(",
"(",
"2",
"*",
"Jj",
"+",
"1",
")",
"*",
"einsteinAij",
"/",
"omega0",
"**",
"3",
")",
"/",
"a0",
"else",
":",
"rij",
"=",
"reduced_matrix_element",
"(",
"fine_statej",
",",
"fine_statei",
",",
"convention",
"=",
"convention",
")",
"rij",
"*=",
"(",
"-",
"1",
")",
"**",
"(",
"Jj",
"-",
"Ji",
")",
"# We return the Brink matrix element.",
"if",
"convention",
"==",
"2",
":",
"if",
"omega0",
"<",
"0",
":",
"rij",
"=",
"rij",
"/",
"sqrt",
"(",
"2",
"*",
"Ji",
"+",
"1",
")",
"else",
":",
"rij",
"=",
"rij",
"/",
"sqrt",
"(",
"2",
"*",
"Ji",
"+",
"1",
")",
"return",
"rij"
] | r"""Return the reduced matrix element of the position operator in Bohr\
radii.
We have two available conventions for this
1.- [Racah]_ and [Edmonds74]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah}
2.- [Brink_Satchler]_
.. math::
\langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \
= (-1)^{J_i-M_i} \sqrt{2J_i+1} \
\left(\begin{matrix}J_i & k & J_j\\-M_i & q & M_j\end{matrix}\right) \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
These two definitions of the reduced matrix element are related by
.. math::
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j \
\rangle_\mathrm{Racah} = \sqrt{2J_i+1} \
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
With the Racah element being symetric under argument exchange apart from a\
sign:
.. math::
\langle \gamma_j, J_j|| (\hat{T}^k)^\dagger|| \gamma_i, J_i\rangle \
_\mathrm{Racah} = (-1)^{J_j-J_i}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Racah}
And the Brink element being asymetric under argument exchange:
.. math::
\langle \gamma_j, J_j|| \hat{T}^k|| \gamma_i, J_i\rangle \
_\mathrm{Brink} = (-1)^{J_j-J_i}\
\frac{\sqrt{2J_i +1}}{\sqrt{2J_j +1}}\
\langle \gamma_i, J_i|| \hat{T}^k|| \gamma_j, J_j\rangle \
_\mathrm{Brink}
References:
.. [Brink_Satchler] Brink, D. M. and G. R. Satchler: 1994. "Angular\
Momentum". Oxford: Oxford University Press, 3rd edn., 182 pages.
.. [Racah] Racah, G.: 1942. "Theory of complex spectra II". Phys. Rev., \
62 438-462.
.. [Edmonds74] A. R. Edmonds. Angular momentum in quantum mechanics.
Investigations in physics, 4.; Investigations in physics, no. 4.
Princeton, N.J., Princeton University Press, 1957..
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> print(reduced_matrix_element(g, e))
5.97785756147
>>> print(reduced_matrix_element(e, g))
-5.97785756146761
>>> print(reduced_matrix_element(g, e, convention=2))
4.22698361868
>>> print(reduced_matrix_element(e, g, convention=2))
-2.11349180934051 | [
"r",
"Return",
"the",
"reduced",
"matrix",
"element",
"of",
"the",
"position",
"operator",
"in",
"Bohr",
"\\",
"radii",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1712-L1810 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_reduced_matrix_elements | def calculate_reduced_matrix_elements(fine_states, convention=1):
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868
"""
reduced_matrix_elements = [[reduced_matrix_element(ei, ej,
convention=convention)
for ej in fine_states]
for ei in fine_states]
return reduced_matrix_elements | python | def calculate_reduced_matrix_elements(fine_states, convention=1):
r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868
"""
reduced_matrix_elements = [[reduced_matrix_element(ei, ej,
convention=convention)
for ej in fine_states]
for ei in fine_states]
return reduced_matrix_elements | [
"def",
"calculate_reduced_matrix_elements",
"(",
"fine_states",
",",
"convention",
"=",
"1",
")",
":",
"reduced_matrix_elements",
"=",
"[",
"[",
"reduced_matrix_element",
"(",
"ei",
",",
"ej",
",",
"convention",
"=",
"convention",
")",
"for",
"ej",
"in",
"fine_states",
"]",
"for",
"ei",
"in",
"fine_states",
"]",
"return",
"reduced_matrix_elements"
] | r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines in rubidium.
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e1 = State("Rb", 87, 5, 1, 1/Integer(2))
>>> e2 = State("Rb", 87,5 , 1, 3/Integer(2))
>>> red = calculate_reduced_matrix_elements([g, e1, e2], convention=2)
>>> print(red[0][1])
2.99207750426
>>> print(red[0][2])
4.22698361868 | [
"r",
"Calculate",
"the",
"reduced",
"matrix",
"elements",
"for",
"a",
"list",
"of",
"fine",
"states",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1813-L1841 |
oscarlazoarjona/fast | fast/atomic_structure.py | matrix_element | def matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, q=None,
numeric=True, convention=1):
r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in Rb 87.
>>> from sympy import symbols
>>> red = symbols("r", positive=True)
>>> half = 1/Integer(2)
>>> II = 3*half
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, q=1, numeric=False)
r/2
If no polarization component is specified, all are returned.
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, numeric=False)
[0, 0, r/2]
"""
if q is None:
return [matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, qi,
numeric=numeric, convention=convention)
for qi in [-1, 0, 1]]
if numeric:
from numpy import sqrt as numsqrt
sqrt = numsqrt
else:
from sympy import sqrt as symsqrt
sqrt = symsqrt
rpij = (-1)**(fi-mi)
rpij *= wigner_3j(fi, 1, fj, -mi, q, mj)
rpij *= (-1)**(fj+ji+1+II)
rpij *= sqrt(2*fj+1)
rpij *= sqrt(2*fi+1)
rpij *= wigner_6j(ji, jj, 1, fj, fi, II)
rpij *= reduced_matrix_element
if convention == 2:
rpij = rpij * sqrt(2*ji+1)
if numeric:
rpij = float(rpij)
return rpij | python | def matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, q=None,
numeric=True, convention=1):
r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in Rb 87.
>>> from sympy import symbols
>>> red = symbols("r", positive=True)
>>> half = 1/Integer(2)
>>> II = 3*half
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, q=1, numeric=False)
r/2
If no polarization component is specified, all are returned.
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, numeric=False)
[0, 0, r/2]
"""
if q is None:
return [matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, qi,
numeric=numeric, convention=convention)
for qi in [-1, 0, 1]]
if numeric:
from numpy import sqrt as numsqrt
sqrt = numsqrt
else:
from sympy import sqrt as symsqrt
sqrt = symsqrt
rpij = (-1)**(fi-mi)
rpij *= wigner_3j(fi, 1, fj, -mi, q, mj)
rpij *= (-1)**(fj+ji+1+II)
rpij *= sqrt(2*fj+1)
rpij *= sqrt(2*fi+1)
rpij *= wigner_6j(ji, jj, 1, fj, fi, II)
rpij *= reduced_matrix_element
if convention == 2:
rpij = rpij * sqrt(2*ji+1)
if numeric:
rpij = float(rpij)
return rpij | [
"def",
"matrix_element",
"(",
"ji",
",",
"fi",
",",
"mi",
",",
"jj",
",",
"fj",
",",
"mj",
",",
"II",
",",
"reduced_matrix_element",
",",
"q",
"=",
"None",
",",
"numeric",
"=",
"True",
",",
"convention",
"=",
"1",
")",
":",
"if",
"q",
"is",
"None",
":",
"return",
"[",
"matrix_element",
"(",
"ji",
",",
"fi",
",",
"mi",
",",
"jj",
",",
"fj",
",",
"mj",
",",
"II",
",",
"reduced_matrix_element",
",",
"qi",
",",
"numeric",
"=",
"numeric",
",",
"convention",
"=",
"convention",
")",
"for",
"qi",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"]",
"if",
"numeric",
":",
"from",
"numpy",
"import",
"sqrt",
"as",
"numsqrt",
"sqrt",
"=",
"numsqrt",
"else",
":",
"from",
"sympy",
"import",
"sqrt",
"as",
"symsqrt",
"sqrt",
"=",
"symsqrt",
"rpij",
"=",
"(",
"-",
"1",
")",
"**",
"(",
"fi",
"-",
"mi",
")",
"rpij",
"*=",
"wigner_3j",
"(",
"fi",
",",
"1",
",",
"fj",
",",
"-",
"mi",
",",
"q",
",",
"mj",
")",
"rpij",
"*=",
"(",
"-",
"1",
")",
"**",
"(",
"fj",
"+",
"ji",
"+",
"1",
"+",
"II",
")",
"rpij",
"*=",
"sqrt",
"(",
"2",
"*",
"fj",
"+",
"1",
")",
"rpij",
"*=",
"sqrt",
"(",
"2",
"*",
"fi",
"+",
"1",
")",
"rpij",
"*=",
"wigner_6j",
"(",
"ji",
",",
"jj",
",",
"1",
",",
"fj",
",",
"fi",
",",
"II",
")",
"rpij",
"*=",
"reduced_matrix_element",
"if",
"convention",
"==",
"2",
":",
"rpij",
"=",
"rpij",
"*",
"sqrt",
"(",
"2",
"*",
"ji",
"+",
"1",
")",
"if",
"numeric",
":",
"rpij",
"=",
"float",
"(",
"rpij",
")",
"return",
"rpij"
] | r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in Rb 87.
>>> from sympy import symbols
>>> red = symbols("r", positive=True)
>>> half = 1/Integer(2)
>>> II = 3*half
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, q=1, numeric=False)
r/2
If no polarization component is specified, all are returned.
>>> matrix_element(3*half, 3, 3, half, 2, 2, II, red, numeric=False)
[0, 0, r/2] | [
"r",
"Calculate",
"a",
"matrix",
"element",
"of",
"the",
"electric",
"dipole",
"(",
"in",
"the",
"helicity",
"basis",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1844-L1891 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_r_matrices | def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None,
numeric=True, convention=1):
ur"""Calculate the matrix elements of the electric dipole (in the helicity
basis).
We calculate all matrix elements for the D2 line in Rb 87.
>>> from sympy import symbols, pprint
>>> red = symbols("r", positive=True)
>>> reduced_matrix_elements = [[0, -red], [red, 0]]
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> fine_levels = [g, e]
>>> r = calculate_r_matrices(fine_levels, reduced_matrix_elements,
... numeric=False)
>>> pprint(r[0][8:,:8])
β‘ β3β
r β€
β’ 0 0 ββββ 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ -β15β
r β15β
r β₯
β’ 0 βββββββ 0 0 0 βββββ 0 0 β₯
β’ 12 60 β₯
β’ β₯
β’ -β15β
r β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 20 β₯
β’ β₯
β’β2β
r -β6β
r β₯
β’ββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ r -r β₯
β’ 0 β 0 0 0 βββ 0 0 β₯
β’ 4 4 β₯
β’ β₯
β’ β3β
r -r β₯
β’ 0 0 ββββ 0 0 0 βββ 0 β₯
β’ 12 4 β₯
β’ β₯
β’ -β6β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ r β₯
β’ 0 0 0 β 0 0 0 0 β₯
β’ 2 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 ββββ 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 0 0 ββββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 30 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[1][8:,:8])
β‘ -β3β
r β€
β’ 0 ββββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’β15β
r -β5β
r β₯
β’βββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 12 20 β₯
β’ β₯
β’ -β15β
r β₯
β’ 0 0 0 0 0 βββββββ 0 0 β₯
β’ 30 β₯
β’ β₯
β’ -β15β
r -β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r β3β
r β₯
β’ β 0 0 0 ββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 ββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r -β3β
r β₯
β’ 0 0 β 0 0 0 ββββββ 0 β₯
β’ 4 12 β₯
β’ β₯
β’ -β3β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 6 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 βββββ 0 0 0 β₯
β’ 15 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 0 0 βββββ 0 β₯
β’ 15 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 0 0 0 0 ββββ β₯
β’ 6 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[2][8:,:8])
β‘β3β
r β€
β’ββββ 0 0 0 0 0 0 0β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 20 β₯
β’ β₯
β’β15β
r β5β
r β₯
β’βββββ 0 0 0 ββββ 0 0 0β₯
β’ 12 20 β₯
β’ β₯
β’ β15β
r β15β
r β₯
β’ 0 βββββ 0 0 0 βββββ 0 0β₯
β’ 12 60 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 ββββ 0 0 0 0β₯
β’ 12 β₯
β’ β₯
β’β3β
r r β₯
β’ββββ 0 0 0 β 0 0 0β₯
β’ 12 4 β₯
β’ β₯
β’ r r β₯
β’ 0 β 0 0 0 β 0 0β₯
β’ 4 4 β₯
β’ β₯
β’ β2β
r β6β
r β₯
β’ 0 0 ββββ 0 0 0 ββββ 0β₯
β’ 4 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 30 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 ββββ 0 0 0β₯
β’ 10 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0β₯
β’ 10 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 0 0 ββββ 0β₯
β’ 6 β₯
β’ β₯
β’ rβ₯
β’ 0 0 0 0 0 0 0 ββ₯
β£ 2β¦
"""
magnetic_states = make_list_of_states(fine_states, 'magnetic', verbose=0)
aux = calculate_boundaries(fine_states, magnetic_states)
index_list_fine, index_list_hyperfine = aux
Ne = len(magnetic_states)
r = [[[0 for j in range(Ne)] for i in range(Ne)] for p in range(3)]
II = fine_states[0].i
for p in [-1, 0, 1]:
for i in range(Ne):
ei = magnetic_states[i]
ii = fine_index(i, index_list_fine)
for j in range(Ne):
ej = magnetic_states[j]
jj = fine_index(j, index_list_fine)
reduced_matrix_elementij = reduced_matrix_elements[ii][jj]
if reduced_matrix_elementij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
rpij = matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_elementij, p,
numeric=numeric,
convention=convention)
if q == 1:
r[p+1][i][j] = rpij*delta_lesser(i, j)
elif q == -1:
r[p+1][i][j] = rpij*delta_greater(i, j)
else:
r[p+1][i][j] = rpij
if not numeric:
r = [Matrix(ri) for ri in r]
return r | python | def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None,
numeric=True, convention=1):
ur"""Calculate the matrix elements of the electric dipole (in the helicity
basis).
We calculate all matrix elements for the D2 line in Rb 87.
>>> from sympy import symbols, pprint
>>> red = symbols("r", positive=True)
>>> reduced_matrix_elements = [[0, -red], [red, 0]]
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> fine_levels = [g, e]
>>> r = calculate_r_matrices(fine_levels, reduced_matrix_elements,
... numeric=False)
>>> pprint(r[0][8:,:8])
β‘ β3β
r β€
β’ 0 0 ββββ 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ -β15β
r β15β
r β₯
β’ 0 βββββββ 0 0 0 βββββ 0 0 β₯
β’ 12 60 β₯
β’ β₯
β’ -β15β
r β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 20 β₯
β’ β₯
β’β2β
r -β6β
r β₯
β’ββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ r -r β₯
β’ 0 β 0 0 0 βββ 0 0 β₯
β’ 4 4 β₯
β’ β₯
β’ β3β
r -r β₯
β’ 0 0 ββββ 0 0 0 βββ 0 β₯
β’ 12 4 β₯
β’ β₯
β’ -β6β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ r β₯
β’ 0 0 0 β 0 0 0 0 β₯
β’ 2 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 ββββ 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 0 0 ββββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 30 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[1][8:,:8])
β‘ -β3β
r β€
β’ 0 ββββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’β15β
r -β5β
r β₯
β’βββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 12 20 β₯
β’ β₯
β’ -β15β
r β₯
β’ 0 0 0 0 0 βββββββ 0 0 β₯
β’ 30 β₯
β’ β₯
β’ -β15β
r -β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r β3β
r β₯
β’ β 0 0 0 ββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 ββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r -β3β
r β₯
β’ 0 0 β 0 0 0 ββββββ 0 β₯
β’ 4 12 β₯
β’ β₯
β’ -β3β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 6 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 βββββ 0 0 0 β₯
β’ 15 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 0 0 βββββ 0 β₯
β’ 15 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 0 0 0 0 ββββ β₯
β’ 6 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[2][8:,:8])
β‘β3β
r β€
β’ββββ 0 0 0 0 0 0 0β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 20 β₯
β’ β₯
β’β15β
r β5β
r β₯
β’βββββ 0 0 0 ββββ 0 0 0β₯
β’ 12 20 β₯
β’ β₯
β’ β15β
r β15β
r β₯
β’ 0 βββββ 0 0 0 βββββ 0 0β₯
β’ 12 60 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 ββββ 0 0 0 0β₯
β’ 12 β₯
β’ β₯
β’β3β
r r β₯
β’ββββ 0 0 0 β 0 0 0β₯
β’ 12 4 β₯
β’ β₯
β’ r r β₯
β’ 0 β 0 0 0 β 0 0β₯
β’ 4 4 β₯
β’ β₯
β’ β2β
r β6β
r β₯
β’ 0 0 ββββ 0 0 0 ββββ 0β₯
β’ 4 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 30 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 ββββ 0 0 0β₯
β’ 10 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0β₯
β’ 10 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 0 0 ββββ 0β₯
β’ 6 β₯
β’ β₯
β’ rβ₯
β’ 0 0 0 0 0 0 0 ββ₯
β£ 2β¦
"""
magnetic_states = make_list_of_states(fine_states, 'magnetic', verbose=0)
aux = calculate_boundaries(fine_states, magnetic_states)
index_list_fine, index_list_hyperfine = aux
Ne = len(magnetic_states)
r = [[[0 for j in range(Ne)] for i in range(Ne)] for p in range(3)]
II = fine_states[0].i
for p in [-1, 0, 1]:
for i in range(Ne):
ei = magnetic_states[i]
ii = fine_index(i, index_list_fine)
for j in range(Ne):
ej = magnetic_states[j]
jj = fine_index(j, index_list_fine)
reduced_matrix_elementij = reduced_matrix_elements[ii][jj]
if reduced_matrix_elementij != 0:
ji = ei.j; jj = ej.j
fi = ei.f; fj = ej.f
mi = ei.m; mj = ej.m
rpij = matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_elementij, p,
numeric=numeric,
convention=convention)
if q == 1:
r[p+1][i][j] = rpij*delta_lesser(i, j)
elif q == -1:
r[p+1][i][j] = rpij*delta_greater(i, j)
else:
r[p+1][i][j] = rpij
if not numeric:
r = [Matrix(ri) for ri in r]
return r | [
"def",
"calculate_r_matrices",
"(",
"fine_states",
",",
"reduced_matrix_elements",
",",
"q",
"=",
"None",
",",
"numeric",
"=",
"True",
",",
"convention",
"=",
"1",
")",
":",
"magnetic_states",
"=",
"make_list_of_states",
"(",
"fine_states",
",",
"'magnetic'",
",",
"verbose",
"=",
"0",
")",
"aux",
"=",
"calculate_boundaries",
"(",
"fine_states",
",",
"magnetic_states",
")",
"index_list_fine",
",",
"index_list_hyperfine",
"=",
"aux",
"Ne",
"=",
"len",
"(",
"magnetic_states",
")",
"r",
"=",
"[",
"[",
"[",
"0",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"p",
"in",
"range",
"(",
"3",
")",
"]",
"II",
"=",
"fine_states",
"[",
"0",
"]",
".",
"i",
"for",
"p",
"in",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
":",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"ei",
"=",
"magnetic_states",
"[",
"i",
"]",
"ii",
"=",
"fine_index",
"(",
"i",
",",
"index_list_fine",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"ej",
"=",
"magnetic_states",
"[",
"j",
"]",
"jj",
"=",
"fine_index",
"(",
"j",
",",
"index_list_fine",
")",
"reduced_matrix_elementij",
"=",
"reduced_matrix_elements",
"[",
"ii",
"]",
"[",
"jj",
"]",
"if",
"reduced_matrix_elementij",
"!=",
"0",
":",
"ji",
"=",
"ei",
".",
"j",
"jj",
"=",
"ej",
".",
"j",
"fi",
"=",
"ei",
".",
"f",
"fj",
"=",
"ej",
".",
"f",
"mi",
"=",
"ei",
".",
"m",
"mj",
"=",
"ej",
".",
"m",
"rpij",
"=",
"matrix_element",
"(",
"ji",
",",
"fi",
",",
"mi",
",",
"jj",
",",
"fj",
",",
"mj",
",",
"II",
",",
"reduced_matrix_elementij",
",",
"p",
",",
"numeric",
"=",
"numeric",
",",
"convention",
"=",
"convention",
")",
"if",
"q",
"==",
"1",
":",
"r",
"[",
"p",
"+",
"1",
"]",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"rpij",
"*",
"delta_lesser",
"(",
"i",
",",
"j",
")",
"elif",
"q",
"==",
"-",
"1",
":",
"r",
"[",
"p",
"+",
"1",
"]",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"rpij",
"*",
"delta_greater",
"(",
"i",
",",
"j",
")",
"else",
":",
"r",
"[",
"p",
"+",
"1",
"]",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"rpij",
"if",
"not",
"numeric",
":",
"r",
"=",
"[",
"Matrix",
"(",
"ri",
")",
"for",
"ri",
"in",
"r",
"]",
"return",
"r"
] | ur"""Calculate the matrix elements of the electric dipole (in the helicity
basis).
We calculate all matrix elements for the D2 line in Rb 87.
>>> from sympy import symbols, pprint
>>> red = symbols("r", positive=True)
>>> reduced_matrix_elements = [[0, -red], [red, 0]]
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> fine_levels = [g, e]
>>> r = calculate_r_matrices(fine_levels, reduced_matrix_elements,
... numeric=False)
>>> pprint(r[0][8:,:8])
β‘ β3β
r β€
β’ 0 0 ββββ 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ -β15β
r β15β
r β₯
β’ 0 βββββββ 0 0 0 βββββ 0 0 β₯
β’ 12 60 β₯
β’ β₯
β’ -β15β
r β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 20 β₯
β’ β₯
β’β2β
r -β6β
r β₯
β’ββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ r -r β₯
β’ 0 β 0 0 0 βββ 0 0 β₯
β’ 4 4 β₯
β’ β₯
β’ β3β
r -r β₯
β’ 0 0 ββββ 0 0 0 βββ 0 β₯
β’ 12 4 β₯
β’ β₯
β’ -β6β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ r β₯
β’ 0 0 0 β 0 0 0 0 β₯
β’ 2 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 ββββ 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 0 0 ββββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 0 0 βββββ β₯
β’ 30 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[1][8:,:8])
β‘ -β3β
r β€
β’ 0 ββββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’β15β
r -β5β
r β₯
β’βββββ 0 0 0 ββββββ 0 0 0 β₯
β’ 12 20 β₯
β’ β₯
β’ -β15β
r β₯
β’ 0 0 0 0 0 βββββββ 0 0 β₯
β’ 30 β₯
β’ β₯
β’ -β15β
r -β5β
r β₯
β’ 0 0 βββββββ 0 0 0 ββββββ 0 β₯
β’ 12 20 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r β3β
r β₯
β’ β 0 0 0 ββββ 0 0 0 β₯
β’ 4 12 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 ββββ 0 0 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ r -β3β
r β₯
β’ 0 0 β 0 0 0 ββββββ 0 β₯
β’ 4 12 β₯
β’ β₯
β’ -β3β
r β₯
β’ 0 0 0 0 0 0 0 βββββββ₯
β’ 6 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 ββββ 0 0 0 0 β₯
β’ 6 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 βββββ 0 0 0 β₯
β’ 15 β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 0 0 βββββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30β
r β₯
β’ 0 0 0 0 0 0 βββββ 0 β₯
β’ 15 β₯
β’ β₯
β’ β3β
r β₯
β’ 0 0 0 0 0 0 0 ββββ β₯
β’ 6 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 0 β¦
>>> pprint(r[2][8:,:8])
β‘β3β
r β€
β’ββββ 0 0 0 0 0 0 0β₯
β’ 6 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 20 β₯
β’ β₯
β’β15β
r β5β
r β₯
β’βββββ 0 0 0 ββββ 0 0 0β₯
β’ 12 20 β₯
β’ β₯
β’ β15β
r β15β
r β₯
β’ 0 βββββ 0 0 0 βββββ 0 0β₯
β’ 12 60 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 ββββ 0 0 0 0β₯
β’ 12 β₯
β’ β₯
β’β3β
r r β₯
β’ββββ 0 0 0 β 0 0 0β₯
β’ 12 4 β₯
β’ β₯
β’ r r β₯
β’ 0 β 0 0 0 β 0 0β₯
β’ 4 4 β₯
β’ β₯
β’ β2β
r β6β
r β₯
β’ 0 0 ββββ 0 0 0 ββββ 0β₯
β’ 4 12 β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ 0 0 0 0 0 0 0 0β₯
β’ β₯
β’ β15β
r β₯
β’ 0 0 0 βββββ 0 0 0 0β₯
β’ 30 β₯
β’ β₯
β’ β5β
r β₯
β’ 0 0 0 0 ββββ 0 0 0β₯
β’ 10 β₯
β’ β₯
β’ β10β
r β₯
β’ 0 0 0 0 0 βββββ 0 0β₯
β’ 10 β₯
β’ β₯
β’ β6β
r β₯
β’ 0 0 0 0 0 0 ββββ 0β₯
β’ 6 β₯
β’ β₯
β’ rβ₯
β’ 0 0 0 0 0 0 0 ββ₯
β£ 2β¦ | [
"ur",
"Calculate",
"the",
"matrix",
"elements",
"of",
"the",
"electric",
"dipole",
"(",
"in",
"the",
"helicity",
"basis",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L1894-L2127 |
oscarlazoarjona/fast | fast/atomic_structure.py | calculate_matrices | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:
raise ValueError('All states must belong to the same isotope.')
# We find the fine states involved in the problem.
fine_states = find_fine_states(states)
# We find the full magnetic states. The matrices will be first calculated
# for the complete problem and later reduced to include only the states of
# interest.
full_magnetic_states = make_list_of_states(fine_states, 'magnetic',
verbose=0)
# We calculate the indices corresponding to each sub matrix of fine and
# hyperfine levels.
# We calculate the frequency differences between states.
omega_full = calculate_omega_matrix(full_magnetic_states, Omega)
# We calculate the matrix gamma.
gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)
# We calculate the reduced matrix elements
reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)
# We calculate the matrices r_-1, r_0, r_1
r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)
# Reduction to be implemented
omega = omega_full
r = r_full
gamma = gamma_full
return omega, gamma, r | python | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:
raise ValueError('All states must belong to the same isotope.')
# We find the fine states involved in the problem.
fine_states = find_fine_states(states)
# We find the full magnetic states. The matrices will be first calculated
# for the complete problem and later reduced to include only the states of
# interest.
full_magnetic_states = make_list_of_states(fine_states, 'magnetic',
verbose=0)
# We calculate the indices corresponding to each sub matrix of fine and
# hyperfine levels.
# We calculate the frequency differences between states.
omega_full = calculate_omega_matrix(full_magnetic_states, Omega)
# We calculate the matrix gamma.
gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)
# We calculate the reduced matrix elements
reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)
# We calculate the matrices r_-1, r_0, r_1
r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)
# Reduction to be implemented
omega = omega_full
r = r_full
gamma = gamma_full
return omega, gamma, r | [
"def",
"calculate_matrices",
"(",
"states",
",",
"Omega",
"=",
"1",
")",
":",
"# We check that all states belong to the same element and the same isotope.",
"iso",
"=",
"states",
"[",
"0",
"]",
".",
"isotope",
"element",
"=",
"states",
"[",
"0",
"]",
".",
"element",
"for",
"state",
"in",
"states",
"[",
"1",
":",
"]",
":",
"if",
"state",
".",
"element",
"!=",
"element",
":",
"raise",
"ValueError",
"(",
"'All states must belong to the same element.'",
")",
"if",
"state",
".",
"isotope",
"!=",
"iso",
":",
"raise",
"ValueError",
"(",
"'All states must belong to the same isotope.'",
")",
"# We find the fine states involved in the problem.",
"fine_states",
"=",
"find_fine_states",
"(",
"states",
")",
"# We find the full magnetic states. The matrices will be first calculated",
"# for the complete problem and later reduced to include only the states of",
"# interest.",
"full_magnetic_states",
"=",
"make_list_of_states",
"(",
"fine_states",
",",
"'magnetic'",
",",
"verbose",
"=",
"0",
")",
"# We calculate the indices corresponding to each sub matrix of fine and",
"# hyperfine levels.",
"# We calculate the frequency differences between states.",
"omega_full",
"=",
"calculate_omega_matrix",
"(",
"full_magnetic_states",
",",
"Omega",
")",
"# We calculate the matrix gamma.",
"gamma_full",
"=",
"calculate_gamma_matrix",
"(",
"full_magnetic_states",
",",
"Omega",
")",
"# We calculate the reduced matrix elements",
"reduced_matrix_elements",
"=",
"calculate_reduced_matrix_elements",
"(",
"fine_states",
")",
"# We calculate the matrices r_-1, r_0, r_1",
"r_full",
"=",
"calculate_r_matrices",
"(",
"fine_states",
",",
"reduced_matrix_elements",
")",
"# Reduction to be implemented",
"omega",
"=",
"omega_full",
"r",
"=",
"r_full",
"gamma",
"=",
"gamma_full",
"return",
"omega",
",",
"gamma",
",",
"r"
] | r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail. | [
"r",
"Calculate",
"the",
"matrices",
"omega_ij",
"gamma_ij",
"r_pij",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2130-L2173 |
oscarlazoarjona/fast | fast/atomic_structure.py | vapour_density | def vapour_density(Temperature, element, isotope=None):
r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natural abundances will
be returned.
This is calculated using the formulas in [SteckRb85]_, [SteckRb87]_,
[SteckCs]_.
>>> print(vapour_density(90.0 + 273.15,"Cs",133))
1.85318869181e-06
If no isotope is specified, the natural abundances are used to calculate
the density.
>>> print(vapour_density(25.0 + 273.15,"Rb"))
1.83339788085e-09
"""
atom = Atom(element, isotope)
if atom.isotope is None:
rho = 0.0
for iso in atom.isotopes:
atom = Atom(element, iso)
rho += vapour_number_density(Temperature, element) *\
atom.mass*atom.abundance
return rho
else:
return vapour_number_density(Temperature, element)*atom.mass | python | def vapour_density(Temperature, element, isotope=None):
r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natural abundances will
be returned.
This is calculated using the formulas in [SteckRb85]_, [SteckRb87]_,
[SteckCs]_.
>>> print(vapour_density(90.0 + 273.15,"Cs",133))
1.85318869181e-06
If no isotope is specified, the natural abundances are used to calculate
the density.
>>> print(vapour_density(25.0 + 273.15,"Rb"))
1.83339788085e-09
"""
atom = Atom(element, isotope)
if atom.isotope is None:
rho = 0.0
for iso in atom.isotopes:
atom = Atom(element, iso)
rho += vapour_number_density(Temperature, element) *\
atom.mass*atom.abundance
return rho
else:
return vapour_number_density(Temperature, element)*atom.mass | [
"def",
"vapour_density",
"(",
"Temperature",
",",
"element",
",",
"isotope",
"=",
"None",
")",
":",
"atom",
"=",
"Atom",
"(",
"element",
",",
"isotope",
")",
"if",
"atom",
".",
"isotope",
"is",
"None",
":",
"rho",
"=",
"0.0",
"for",
"iso",
"in",
"atom",
".",
"isotopes",
":",
"atom",
"=",
"Atom",
"(",
"element",
",",
"iso",
")",
"rho",
"+=",
"vapour_number_density",
"(",
"Temperature",
",",
"element",
")",
"*",
"atom",
".",
"mass",
"*",
"atom",
".",
"abundance",
"return",
"rho",
"else",
":",
"return",
"vapour_number_density",
"(",
"Temperature",
",",
"element",
")",
"*",
"atom",
".",
"mass"
] | r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natural abundances will
be returned.
This is calculated using the formulas in [SteckRb85]_, [SteckRb87]_,
[SteckCs]_.
>>> print(vapour_density(90.0 + 273.15,"Cs",133))
1.85318869181e-06
If no isotope is specified, the natural abundances are used to calculate
the density.
>>> print(vapour_density(25.0 + 273.15,"Rb"))
1.83339788085e-09 | [
"r",
"This",
"function",
"returns",
"the",
"density",
"in",
"a",
"rubidium",
"or",
"cesium",
"vapour",
"in",
"kg",
"/",
"m^",
"-",
"3",
".",
"It",
"receives",
"as",
"input",
"the",
"temperature",
"in",
"Kelvins",
"the",
"name",
"of",
"the",
"element",
"and",
"optionally",
"the",
"isotope",
".",
"If",
"no",
"isotope",
"is",
"specified",
"the",
"density",
"of",
"a",
"vapour",
"with",
"the",
"natural",
"abundances",
"will",
"be",
"returned",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2514-L2543 |
oscarlazoarjona/fast | fast/atomic_structure.py | doppler_width | def doppler_width(transition, Temperature):
r"""Return the Doppler width of a transition at a given temperature
(in angular frequency).
The usual Doppler FWHM of the rubidium D2 line (in MHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2)
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> t = Transition(e, g)
>>> omega = doppler_width(t, 273.15 + 22)
>>> "{:2.3f}".format(omega/2/np.pi*1e-6)
'522.477'
"""
atom = Atom(transition.e1.element, transition.e1.isotope)
m = atom.mass
omega = transition.omega
return omega*np.log(8*np.sqrt(2))*np.sqrt(k_B*Temperature/m/c**2) | python | def doppler_width(transition, Temperature):
r"""Return the Doppler width of a transition at a given temperature
(in angular frequency).
The usual Doppler FWHM of the rubidium D2 line (in MHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2)
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> t = Transition(e, g)
>>> omega = doppler_width(t, 273.15 + 22)
>>> "{:2.3f}".format(omega/2/np.pi*1e-6)
'522.477'
"""
atom = Atom(transition.e1.element, transition.e1.isotope)
m = atom.mass
omega = transition.omega
return omega*np.log(8*np.sqrt(2))*np.sqrt(k_B*Temperature/m/c**2) | [
"def",
"doppler_width",
"(",
"transition",
",",
"Temperature",
")",
":",
"atom",
"=",
"Atom",
"(",
"transition",
".",
"e1",
".",
"element",
",",
"transition",
".",
"e1",
".",
"isotope",
")",
"m",
"=",
"atom",
".",
"mass",
"omega",
"=",
"transition",
".",
"omega",
"return",
"omega",
"*",
"np",
".",
"log",
"(",
"8",
"*",
"np",
".",
"sqrt",
"(",
"2",
")",
")",
"*",
"np",
".",
"sqrt",
"(",
"k_B",
"*",
"Temperature",
"/",
"m",
"/",
"c",
"**",
"2",
")"
] | r"""Return the Doppler width of a transition at a given temperature
(in angular frequency).
The usual Doppler FWHM of the rubidium D2 line (in MHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2)
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> t = Transition(e, g)
>>> omega = doppler_width(t, 273.15 + 22)
>>> "{:2.3f}".format(omega/2/np.pi*1e-6)
'522.477' | [
"r",
"Return",
"the",
"Doppler",
"width",
"of",
"a",
"transition",
"at",
"a",
"given",
"temperature",
"(",
"in",
"angular",
"frequency",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2640-L2657 |
oscarlazoarjona/fast | fast/atomic_structure.py | thermal_state | def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833]
"""
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p | python | def thermal_state(omega_level, T, return_diagonal=False):
r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833]
"""
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p | [
"def",
"thermal_state",
"(",
"omega_level",
",",
"T",
",",
"return_diagonal",
"=",
"False",
")",
":",
"Ne",
"=",
"len",
"(",
"omega_level",
")",
"E",
"=",
"np",
".",
"array",
"(",
"[",
"hbar",
"*",
"omega_level",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
")",
"p",
"=",
"np",
".",
"exp",
"(",
"-",
"E",
"/",
"k_B",
"/",
"T",
")",
"p",
"=",
"p",
"/",
"sum",
"(",
"p",
")",
"if",
"not",
"return_diagonal",
":",
"return",
"np",
".",
"diag",
"(",
"p",
")",
"return",
"p"
] | r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([ground], "magnetic")
>>> omega_level = [ei.omega for ei in magnetic_states]
>>> T = 273.15 + 20
>>> print(thermal_state(omega_level, T, return_diagonal=True))
[0.0834 0.0834 0.0834 0.0834 0.0834 0.0833 0.0833 0.0833 0.0833 0.0833
0.0833 0.0833] | [
"r",
"Return",
"a",
"thermal",
"state",
"for",
"a",
"given",
"set",
"of",
"levels",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L2660-L2685 |
oscarlazoarjona/fast | fast/atomic_structure.py | Atom.transitions | def transitions(self, omega_min=None, omega_max=None):
r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2
"""
states = self.states()
transitions = states
transitions = []
for i in range(len(states)):
si = states[i]
for j in range(i):
sj = states[j]
t = Transition(sj, si)
if t.allowed:
transitions += [t]
if omega_min is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) >= omega_min]
if omega_max is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) <= omega_max]
return transitions | python | def transitions(self, omega_min=None, omega_max=None):
r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2
"""
states = self.states()
transitions = states
transitions = []
for i in range(len(states)):
si = states[i]
for j in range(i):
sj = states[j]
t = Transition(sj, si)
if t.allowed:
transitions += [t]
if omega_min is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) >= omega_min]
if omega_max is not None:
transitions = [ti for ti in transitions
if abs(ti.omega) <= omega_max]
return transitions | [
"def",
"transitions",
"(",
"self",
",",
"omega_min",
"=",
"None",
",",
"omega_max",
"=",
"None",
")",
":",
"states",
"=",
"self",
".",
"states",
"(",
")",
"transitions",
"=",
"states",
"transitions",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"states",
")",
")",
":",
"si",
"=",
"states",
"[",
"i",
"]",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"sj",
"=",
"states",
"[",
"j",
"]",
"t",
"=",
"Transition",
"(",
"sj",
",",
"si",
")",
"if",
"t",
".",
"allowed",
":",
"transitions",
"+=",
"[",
"t",
"]",
"if",
"omega_min",
"is",
"not",
"None",
":",
"transitions",
"=",
"[",
"ti",
"for",
"ti",
"in",
"transitions",
"if",
"abs",
"(",
"ti",
".",
"omega",
")",
">=",
"omega_min",
"]",
"if",
"omega_max",
"is",
"not",
"None",
":",
"transitions",
"=",
"[",
"ti",
"for",
"ti",
"in",
"transitions",
"if",
"abs",
"(",
"ti",
".",
"omega",
")",
"<=",
"omega_max",
"]",
"return",
"transitions"
] | r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be used to make filter out the
results.
>>> from scipy.constants import c
>>> wavelength_min=770e-9
>>> wavelength_max=790e-9
>>> omega_min=2*pi*c/wavelength_max
>>> omega_max=2*pi*c/wavelength_min
>>> easy_transitions=atom.transitions(omega_min=omega_min,
... omega_max=omega_max)
>>> for ti in easy_transitions:
... print("{} {}".format(abs(ti.wavelength)*1e9, ti))
780.241476935 85Rb 5S_1/2 -----> 85Rb 5P_3/2
776.157015322 85Rb 5P_3/2 -----> 85Rb 5D_3/2
775.978619616 85Rb 5P_3/2 -----> 85Rb 5D_5/2 | [
"r",
"Find",
"all",
"allowed",
"transitions",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/atomic_structure.py#L348-L395 |
oscarlazoarjona/fast | fast/inhomo.py | fast_doppler_terms | def fast_doppler_terms(v, detuning_knob, k, omega_level, xi, theta,
unfolding, axes=["x", "y", "z"], matrix_form=False,
file_name=None,
return_code=False):
r"""Return a fast function that returns the Doppler terms.
>>> from sympy import Matrix, symbols
>>> from scipy.constants import physical_constants
>>> from fast import PlaneWave
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> unfolding = Unfolding(Ne, True, True, True)
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [Matrix([[0, 0], [a0, 0]]),
... Matrix([[0, 0], [0, 0]]),
... Matrix([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> omega_level = [1, 2.4e15]
>>> detuning_knob = [symbols("delta1")]
>>> v = symbols("vx vy vz")
>>> laser = PlaneWave(0, 0, 0, 0, 1)
>>> k = [laser.k]
>>> doppler_terms = fast_doppler_terms(v, detuning_knob, k, omega_level,
... xi, theta, unfolding,
... matrix_form=True)
>>> detuning_knobs = [0]
>>> A, b = doppler_terms([0, 0, 167], detuning_knobs)
>>> print A/2/np.pi*1e-9
[[ 0. 0. 0. ]
[ 0. 0. 0.21277821]
[ 0. -0.21277821 0. ]]
"""
# We unpack variables.
if True:
Ne = unfolding.Ne
Nrho = unfolding.Nrho
Nl = xi.shape[0]
IJ = unfolding.IJ
Mu = unfolding.Mu
# We determine which arguments are constants.
if True:
try:
detuning_knob = np.array([float(detuning_knob[l])
for l in range(Nl)])
variable_detuning_knob = False
except:
variable_detuning_knob = True
# We establish the arguments of the output function.
if True:
code = ""
code += "def doppler_terms(v, "
if not matrix_form: code += "rho, "
if variable_detuning_knob: code += "detuning_knob, "
if code[-2:] == ", ":
code = code[:-2]
code += "):\n"
code += ' r"""A fast calculation of the Doppler terms."""\n'
# We initialize the output and auxiliaries.
if True:
# We introduce the factor that multiplies all terms.
if unfolding.real:
code += " fact = 1.0\n\n"
else:
code += " fact = 1.0j\n\n"
if matrix_form:
code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
if unfolding.normalized:
code += " b = np.zeros(("+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
else:
code += " rhs = np.zeros(("+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
# We build the degeneration simplification and is inverse (to avoid
# large combinatorics).
aux = define_simplification(omega_level, xi, Nl)
u, invu, omega_levelu, Neu, xiu = aux
# For each field we find the smallest transition frequency, and its
# simplified indices.
omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu)
#####################################
# We get the code to calculate the non degenerate detunings.
pairs = detunings_indices(Neu, Nl, xiu)
if not variable_detuning_knob:
code += " detuning_knob = np.zeros("+str(Nl)+")\n"
for l in range(Nl):
code += " detuning_knob["+str(l)+"] = " +\
str(detuning_knob[l])+"\n"
# We put in the code to calculate the Doppler shift
if True:
# Delta omega = omega_laser /c k.v
code += " # The Doppler shift\n"
dimension = len(v)
code += " c = %s\n" % c_num
for l in range(Nl):
lp1 = l+1
code += " omega_laser%s = %s" % (lp1, omega_min[l])
code += "+detuning_knob[%s]\n" % l
code += " detuning_knob[%s] = 0\n" % l
axeindices = {"x": 0, "y": 1, "z": 2}
axeindices = [axeindices[axe] for axe in axes]
for ii in axeindices[:dimension]:
code += " detuning_knob[%s] += -%s" % (l, k[l][ii])
if dimension == 1:
code += "*v/c*omega_laser%s\n" % lp1
else:
code += "*v[%s]/c*omega_laser%s\n" % (ii, lp1)
code += "\n"
code_det = detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)
code += code_det
code += "\n"
#####################################
# There is a term
# I * Theta_ij * rho_ij = I * (omega_level_j - omega_level_i
# theta_j - theta_i)
# for all i != j.
# This term can be re expressed as
# re(Theta_ij*rho_ij) = - Theta_ij * im(rho_ij)
# im(Theta_ij*rho_ij) = + Theta_ij * re(rho_ij)
_omega_level, omega, gamma = define_frequencies(Ne)
_omega_levelu, omega, gamma = define_frequencies(Neu)
E0, omega_laser = define_laser_variables(Nl)
# We build all combinations.
combs = detunings_combinations(pairs)
# We add all terms.
for mu in range(Nrho):
s, i, j = IJ(mu)
if i != j:
_Thetaij = _omega_levelu[u(j)] - _omega_levelu[u(i)]
_Thetaij += theta[j] - theta[i]
aux = (_Thetaij, combs, omega_laser,
_omega_levelu, omega_levelu, iu0, ju0)
assign = detunings_rewrite(*aux)
if assign != "":
if s == 0:
nu = mu
elif s == 1:
assign = "-(%s)" % assign
nu = Mu(-s, i, j)
elif s == -1:
assign = "+(%s)" % assign
nu = Mu(-s, i, j)
if matrix_form:
term_code = " A[%s, %s] = %s\n" % (mu, nu, assign)
else:
term_code = " rhs[%s] = (%s)*rho[%s]\n" % (mu,
assign, nu)
else:
term_code = ""
code += term_code
#####################################
# We finish the code.
if True:
if matrix_form:
if unfolding.normalized:
code += " A *= fact\n"
code += " b *= fact\n"
code += " return A, b\n"
else:
code += " A *= fact\n"
code += " return A\n"
else:
code += " rhs *= fact\n"
code += " return rhs\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
doppler_terms = code
if not return_code:
exec doppler_terms
return doppler_terms | python | def fast_doppler_terms(v, detuning_knob, k, omega_level, xi, theta,
unfolding, axes=["x", "y", "z"], matrix_form=False,
file_name=None,
return_code=False):
r"""Return a fast function that returns the Doppler terms.
>>> from sympy import Matrix, symbols
>>> from scipy.constants import physical_constants
>>> from fast import PlaneWave
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> unfolding = Unfolding(Ne, True, True, True)
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [Matrix([[0, 0], [a0, 0]]),
... Matrix([[0, 0], [0, 0]]),
... Matrix([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> omega_level = [1, 2.4e15]
>>> detuning_knob = [symbols("delta1")]
>>> v = symbols("vx vy vz")
>>> laser = PlaneWave(0, 0, 0, 0, 1)
>>> k = [laser.k]
>>> doppler_terms = fast_doppler_terms(v, detuning_knob, k, omega_level,
... xi, theta, unfolding,
... matrix_form=True)
>>> detuning_knobs = [0]
>>> A, b = doppler_terms([0, 0, 167], detuning_knobs)
>>> print A/2/np.pi*1e-9
[[ 0. 0. 0. ]
[ 0. 0. 0.21277821]
[ 0. -0.21277821 0. ]]
"""
# We unpack variables.
if True:
Ne = unfolding.Ne
Nrho = unfolding.Nrho
Nl = xi.shape[0]
IJ = unfolding.IJ
Mu = unfolding.Mu
# We determine which arguments are constants.
if True:
try:
detuning_knob = np.array([float(detuning_knob[l])
for l in range(Nl)])
variable_detuning_knob = False
except:
variable_detuning_knob = True
# We establish the arguments of the output function.
if True:
code = ""
code += "def doppler_terms(v, "
if not matrix_form: code += "rho, "
if variable_detuning_knob: code += "detuning_knob, "
if code[-2:] == ", ":
code = code[:-2]
code += "):\n"
code += ' r"""A fast calculation of the Doppler terms."""\n'
# We initialize the output and auxiliaries.
if True:
# We introduce the factor that multiplies all terms.
if unfolding.real:
code += " fact = 1.0\n\n"
else:
code += " fact = 1.0j\n\n"
if matrix_form:
code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
if unfolding.normalized:
code += " b = np.zeros(("+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
else:
code += " rhs = np.zeros(("+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
# We build the degeneration simplification and is inverse (to avoid
# large combinatorics).
aux = define_simplification(omega_level, xi, Nl)
u, invu, omega_levelu, Neu, xiu = aux
# For each field we find the smallest transition frequency, and its
# simplified indices.
omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu)
#####################################
# We get the code to calculate the non degenerate detunings.
pairs = detunings_indices(Neu, Nl, xiu)
if not variable_detuning_knob:
code += " detuning_knob = np.zeros("+str(Nl)+")\n"
for l in range(Nl):
code += " detuning_knob["+str(l)+"] = " +\
str(detuning_knob[l])+"\n"
# We put in the code to calculate the Doppler shift
if True:
# Delta omega = omega_laser /c k.v
code += " # The Doppler shift\n"
dimension = len(v)
code += " c = %s\n" % c_num
for l in range(Nl):
lp1 = l+1
code += " omega_laser%s = %s" % (lp1, omega_min[l])
code += "+detuning_knob[%s]\n" % l
code += " detuning_knob[%s] = 0\n" % l
axeindices = {"x": 0, "y": 1, "z": 2}
axeindices = [axeindices[axe] for axe in axes]
for ii in axeindices[:dimension]:
code += " detuning_knob[%s] += -%s" % (l, k[l][ii])
if dimension == 1:
code += "*v/c*omega_laser%s\n" % lp1
else:
code += "*v[%s]/c*omega_laser%s\n" % (ii, lp1)
code += "\n"
code_det = detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)
code += code_det
code += "\n"
#####################################
# There is a term
# I * Theta_ij * rho_ij = I * (omega_level_j - omega_level_i
# theta_j - theta_i)
# for all i != j.
# This term can be re expressed as
# re(Theta_ij*rho_ij) = - Theta_ij * im(rho_ij)
# im(Theta_ij*rho_ij) = + Theta_ij * re(rho_ij)
_omega_level, omega, gamma = define_frequencies(Ne)
_omega_levelu, omega, gamma = define_frequencies(Neu)
E0, omega_laser = define_laser_variables(Nl)
# We build all combinations.
combs = detunings_combinations(pairs)
# We add all terms.
for mu in range(Nrho):
s, i, j = IJ(mu)
if i != j:
_Thetaij = _omega_levelu[u(j)] - _omega_levelu[u(i)]
_Thetaij += theta[j] - theta[i]
aux = (_Thetaij, combs, omega_laser,
_omega_levelu, omega_levelu, iu0, ju0)
assign = detunings_rewrite(*aux)
if assign != "":
if s == 0:
nu = mu
elif s == 1:
assign = "-(%s)" % assign
nu = Mu(-s, i, j)
elif s == -1:
assign = "+(%s)" % assign
nu = Mu(-s, i, j)
if matrix_form:
term_code = " A[%s, %s] = %s\n" % (mu, nu, assign)
else:
term_code = " rhs[%s] = (%s)*rho[%s]\n" % (mu,
assign, nu)
else:
term_code = ""
code += term_code
#####################################
# We finish the code.
if True:
if matrix_form:
if unfolding.normalized:
code += " A *= fact\n"
code += " b *= fact\n"
code += " return A, b\n"
else:
code += " A *= fact\n"
code += " return A\n"
else:
code += " rhs *= fact\n"
code += " return rhs\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
doppler_terms = code
if not return_code:
exec doppler_terms
return doppler_terms | [
"def",
"fast_doppler_terms",
"(",
"v",
",",
"detuning_knob",
",",
"k",
",",
"omega_level",
",",
"xi",
",",
"theta",
",",
"unfolding",
",",
"axes",
"=",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"z\"",
"]",
",",
"matrix_form",
"=",
"False",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"False",
")",
":",
"# We unpack variables.",
"if",
"True",
":",
"Ne",
"=",
"unfolding",
".",
"Ne",
"Nrho",
"=",
"unfolding",
".",
"Nrho",
"Nl",
"=",
"xi",
".",
"shape",
"[",
"0",
"]",
"IJ",
"=",
"unfolding",
".",
"IJ",
"Mu",
"=",
"unfolding",
".",
"Mu",
"# We determine which arguments are constants.",
"if",
"True",
":",
"try",
":",
"detuning_knob",
"=",
"np",
".",
"array",
"(",
"[",
"float",
"(",
"detuning_knob",
"[",
"l",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"variable_detuning_knob",
"=",
"False",
"except",
":",
"variable_detuning_knob",
"=",
"True",
"# We establish the arguments of the output function.",
"if",
"True",
":",
"code",
"=",
"\"\"",
"code",
"+=",
"\"def doppler_terms(v, \"",
"if",
"not",
"matrix_form",
":",
"code",
"+=",
"\"rho, \"",
"if",
"variable_detuning_knob",
":",
"code",
"+=",
"\"detuning_knob, \"",
"if",
"code",
"[",
"-",
"2",
":",
"]",
"==",
"\", \"",
":",
"code",
"=",
"code",
"[",
":",
"-",
"2",
"]",
"code",
"+=",
"\"):\\n\"",
"code",
"+=",
"' r\"\"\"A fast calculation of the Doppler terms.\"\"\"\\n'",
"# We initialize the output and auxiliaries.",
"if",
"True",
":",
"# We introduce the factor that multiplies all terms.",
"if",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\" fact = 1.0\\n\\n\"",
"else",
":",
"code",
"+=",
"\" fact = 1.0j\\n\\n\"",
"if",
"matrix_form",
":",
"code",
"+=",
"\" A = np.zeros((\"",
"+",
"str",
"(",
"Nrho",
")",
"+",
"\", \"",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"if",
"unfolding",
".",
"normalized",
":",
"code",
"+=",
"\" b = np.zeros((\"",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"else",
":",
"code",
"+=",
"\" rhs = np.zeros((\"",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"# We build the degeneration simplification and is inverse (to avoid",
"# large combinatorics).",
"aux",
"=",
"define_simplification",
"(",
"omega_level",
",",
"xi",
",",
"Nl",
")",
"u",
",",
"invu",
",",
"omega_levelu",
",",
"Neu",
",",
"xiu",
"=",
"aux",
"# For each field we find the smallest transition frequency, and its",
"# simplified indices.",
"omega_min",
",",
"iu0",
",",
"ju0",
"=",
"find_omega_min",
"(",
"omega_levelu",
",",
"Neu",
",",
"Nl",
",",
"xiu",
")",
"#####################################",
"# We get the code to calculate the non degenerate detunings.",
"pairs",
"=",
"detunings_indices",
"(",
"Neu",
",",
"Nl",
",",
"xiu",
")",
"if",
"not",
"variable_detuning_knob",
":",
"code",
"+=",
"\" detuning_knob = np.zeros(\"",
"+",
"str",
"(",
"Nl",
")",
"+",
"\")\\n\"",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"code",
"+=",
"\" detuning_knob[\"",
"+",
"str",
"(",
"l",
")",
"+",
"\"] = \"",
"+",
"str",
"(",
"detuning_knob",
"[",
"l",
"]",
")",
"+",
"\"\\n\"",
"# We put in the code to calculate the Doppler shift",
"if",
"True",
":",
"# Delta omega = omega_laser /c k.v",
"code",
"+=",
"\" # The Doppler shift\\n\"",
"dimension",
"=",
"len",
"(",
"v",
")",
"code",
"+=",
"\" c = %s\\n\"",
"%",
"c_num",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"lp1",
"=",
"l",
"+",
"1",
"code",
"+=",
"\" omega_laser%s = %s\"",
"%",
"(",
"lp1",
",",
"omega_min",
"[",
"l",
"]",
")",
"code",
"+=",
"\"+detuning_knob[%s]\\n\"",
"%",
"l",
"code",
"+=",
"\" detuning_knob[%s] = 0\\n\"",
"%",
"l",
"axeindices",
"=",
"{",
"\"x\"",
":",
"0",
",",
"\"y\"",
":",
"1",
",",
"\"z\"",
":",
"2",
"}",
"axeindices",
"=",
"[",
"axeindices",
"[",
"axe",
"]",
"for",
"axe",
"in",
"axes",
"]",
"for",
"ii",
"in",
"axeindices",
"[",
":",
"dimension",
"]",
":",
"code",
"+=",
"\" detuning_knob[%s] += -%s\"",
"%",
"(",
"l",
",",
"k",
"[",
"l",
"]",
"[",
"ii",
"]",
")",
"if",
"dimension",
"==",
"1",
":",
"code",
"+=",
"\"*v/c*omega_laser%s\\n\"",
"%",
"lp1",
"else",
":",
"code",
"+=",
"\"*v[%s]/c*omega_laser%s\\n\"",
"%",
"(",
"ii",
",",
"lp1",
")",
"code",
"+=",
"\"\\n\"",
"code_det",
"=",
"detunings_code",
"(",
"Neu",
",",
"Nl",
",",
"pairs",
",",
"omega_levelu",
",",
"iu0",
",",
"ju0",
")",
"code",
"+=",
"code_det",
"code",
"+=",
"\"\\n\"",
"#####################################",
"# There is a term",
"# I * Theta_ij * rho_ij = I * (omega_level_j - omega_level_i",
"# theta_j - theta_i)",
"# for all i != j.",
"# This term can be re expressed as",
"# re(Theta_ij*rho_ij) = - Theta_ij * im(rho_ij)",
"# im(Theta_ij*rho_ij) = + Theta_ij * re(rho_ij)",
"_omega_level",
",",
"omega",
",",
"gamma",
"=",
"define_frequencies",
"(",
"Ne",
")",
"_omega_levelu",
",",
"omega",
",",
"gamma",
"=",
"define_frequencies",
"(",
"Neu",
")",
"E0",
",",
"omega_laser",
"=",
"define_laser_variables",
"(",
"Nl",
")",
"# We build all combinations.",
"combs",
"=",
"detunings_combinations",
"(",
"pairs",
")",
"# We add all terms.",
"for",
"mu",
"in",
"range",
"(",
"Nrho",
")",
":",
"s",
",",
"i",
",",
"j",
"=",
"IJ",
"(",
"mu",
")",
"if",
"i",
"!=",
"j",
":",
"_Thetaij",
"=",
"_omega_levelu",
"[",
"u",
"(",
"j",
")",
"]",
"-",
"_omega_levelu",
"[",
"u",
"(",
"i",
")",
"]",
"_Thetaij",
"+=",
"theta",
"[",
"j",
"]",
"-",
"theta",
"[",
"i",
"]",
"aux",
"=",
"(",
"_Thetaij",
",",
"combs",
",",
"omega_laser",
",",
"_omega_levelu",
",",
"omega_levelu",
",",
"iu0",
",",
"ju0",
")",
"assign",
"=",
"detunings_rewrite",
"(",
"*",
"aux",
")",
"if",
"assign",
"!=",
"\"\"",
":",
"if",
"s",
"==",
"0",
":",
"nu",
"=",
"mu",
"elif",
"s",
"==",
"1",
":",
"assign",
"=",
"\"-(%s)\"",
"%",
"assign",
"nu",
"=",
"Mu",
"(",
"-",
"s",
",",
"i",
",",
"j",
")",
"elif",
"s",
"==",
"-",
"1",
":",
"assign",
"=",
"\"+(%s)\"",
"%",
"assign",
"nu",
"=",
"Mu",
"(",
"-",
"s",
",",
"i",
",",
"j",
")",
"if",
"matrix_form",
":",
"term_code",
"=",
"\" A[%s, %s] = %s\\n\"",
"%",
"(",
"mu",
",",
"nu",
",",
"assign",
")",
"else",
":",
"term_code",
"=",
"\" rhs[%s] = (%s)*rho[%s]\\n\"",
"%",
"(",
"mu",
",",
"assign",
",",
"nu",
")",
"else",
":",
"term_code",
"=",
"\"\"",
"code",
"+=",
"term_code",
"#####################################",
"# We finish the code.",
"if",
"True",
":",
"if",
"matrix_form",
":",
"if",
"unfolding",
".",
"normalized",
":",
"code",
"+=",
"\" A *= fact\\n\"",
"code",
"+=",
"\" b *= fact\\n\"",
"code",
"+=",
"\" return A, b\\n\"",
"else",
":",
"code",
"+=",
"\" A *= fact\\n\"",
"code",
"+=",
"\" return A\\n\"",
"else",
":",
"code",
"+=",
"\" rhs *= fact\\n\"",
"code",
"+=",
"\" return rhs\\n\"",
"# We write the code to file if provided, and execute it.",
"if",
"True",
":",
"if",
"file_name",
"is",
"not",
"None",
":",
"f",
"=",
"file",
"(",
"file_name",
"+",
"\".py\"",
",",
"\"w\"",
")",
"f",
".",
"write",
"(",
"code",
")",
"f",
".",
"close",
"(",
")",
"doppler_terms",
"=",
"code",
"if",
"not",
"return_code",
":",
"exec",
"doppler_terms",
"return",
"doppler_terms"
] | r"""Return a fast function that returns the Doppler terms.
>>> from sympy import Matrix, symbols
>>> from scipy.constants import physical_constants
>>> from fast import PlaneWave
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> unfolding = Unfolding(Ne, True, True, True)
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [Matrix([[0, 0], [a0, 0]]),
... Matrix([[0, 0], [0, 0]]),
... Matrix([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> omega_level = [1, 2.4e15]
>>> detuning_knob = [symbols("delta1")]
>>> v = symbols("vx vy vz")
>>> laser = PlaneWave(0, 0, 0, 0, 1)
>>> k = [laser.k]
>>> doppler_terms = fast_doppler_terms(v, detuning_knob, k, omega_level,
... xi, theta, unfolding,
... matrix_form=True)
>>> detuning_knobs = [0]
>>> A, b = doppler_terms([0, 0, 167], detuning_knobs)
>>> print A/2/np.pi*1e-9
[[ 0. 0. 0. ]
[ 0. 0. 0.21277821]
[ 0. -0.21277821 0. ]] | [
"r",
"Return",
"a",
"fast",
"function",
"that",
"returns",
"the",
"Doppler",
"terms",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L241-L439 |
oscarlazoarjona/fast | fast/inhomo.py | fast_maxwell_boltzmann | def fast_maxwell_boltzmann(mass, file_name=None,
return_code=False):
r"""Return a function that returns values of a Maxwell-Boltzmann
distribution.
>>> from fast import Atom
>>> mass = Atom("Rb", 87).mass
>>> f = fast_maxwell_boltzmann(mass)
>>> print f(0, 273.15+20)
0.00238221482739
>>> import numpy as np
>>> v = np.linspace(-600, 600, 101)
>>> dist = f(v, 273.15+20)
>>> dv = v[1]-v[0]
>>> print sum(dist)*dv
0.999704711134
"""
# We get the mass of the atom.
code = ""
code = "def maxwell_boltzmann(v, T):\n"
code += ' r"""A fast calculation of the'
code += ' Maxwell-Boltzmann distribution."""\n'
code += " if hasattr(v, 'shape'):\n"
code += " d = 1\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " f = f * np.exp(-m*v**2/2/k_B_num/T)\n"
code += " return f\n"
code += " elif hasattr(v, '__len__'):\n"
code += " d = len(v)\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " vsquare = sum([v[i]**2 for i in range(d)])\n"
code += " f = f * np.exp(-m*vsquare/2/k_B_num/T)\n"
code += " return f\n"
code += " else:\n"
code += " d = 1\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " f = f * np.exp(-m*v**2/2/k_B_num/T)\n"
code += " return f\n"
# We write the code to file if provided, and execute it.
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
maxwell_boltzmann = code
if not return_code:
exec maxwell_boltzmann
return maxwell_boltzmann | python | def fast_maxwell_boltzmann(mass, file_name=None,
return_code=False):
r"""Return a function that returns values of a Maxwell-Boltzmann
distribution.
>>> from fast import Atom
>>> mass = Atom("Rb", 87).mass
>>> f = fast_maxwell_boltzmann(mass)
>>> print f(0, 273.15+20)
0.00238221482739
>>> import numpy as np
>>> v = np.linspace(-600, 600, 101)
>>> dist = f(v, 273.15+20)
>>> dv = v[1]-v[0]
>>> print sum(dist)*dv
0.999704711134
"""
# We get the mass of the atom.
code = ""
code = "def maxwell_boltzmann(v, T):\n"
code += ' r"""A fast calculation of the'
code += ' Maxwell-Boltzmann distribution."""\n'
code += " if hasattr(v, 'shape'):\n"
code += " d = 1\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " f = f * np.exp(-m*v**2/2/k_B_num/T)\n"
code += " return f\n"
code += " elif hasattr(v, '__len__'):\n"
code += " d = len(v)\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " vsquare = sum([v[i]**2 for i in range(d)])\n"
code += " f = f * np.exp(-m*vsquare/2/k_B_num/T)\n"
code += " return f\n"
code += " else:\n"
code += " d = 1\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " f = f * np.exp(-m*v**2/2/k_B_num/T)\n"
code += " return f\n"
# We write the code to file if provided, and execute it.
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
maxwell_boltzmann = code
if not return_code:
exec maxwell_boltzmann
return maxwell_boltzmann | [
"def",
"fast_maxwell_boltzmann",
"(",
"mass",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"False",
")",
":",
"# We get the mass of the atom.",
"code",
"=",
"\"\"",
"code",
"=",
"\"def maxwell_boltzmann(v, T):\\n\"",
"code",
"+=",
"' r\"\"\"A fast calculation of the'",
"code",
"+=",
"' Maxwell-Boltzmann distribution.\"\"\"\\n'",
"code",
"+=",
"\" if hasattr(v, 'shape'):\\n\"",
"code",
"+=",
"\" d = 1\\n\"",
"code",
"+=",
"\" m = %s\\n\"",
"%",
"mass",
"code",
"+=",
"\" f = np.sqrt(m/2/np.pi/k_B_num/T)**d\\n\"",
"code",
"+=",
"\" f = f * np.exp(-m*v**2/2/k_B_num/T)\\n\"",
"code",
"+=",
"\" return f\\n\"",
"code",
"+=",
"\" elif hasattr(v, '__len__'):\\n\"",
"code",
"+=",
"\" d = len(v)\\n\"",
"code",
"+=",
"\" m = %s\\n\"",
"%",
"mass",
"code",
"+=",
"\" f = np.sqrt(m/2/np.pi/k_B_num/T)**d\\n\"",
"code",
"+=",
"\" vsquare = sum([v[i]**2 for i in range(d)])\\n\"",
"code",
"+=",
"\" f = f * np.exp(-m*vsquare/2/k_B_num/T)\\n\"",
"code",
"+=",
"\" return f\\n\"",
"code",
"+=",
"\" else:\\n\"",
"code",
"+=",
"\" d = 1\\n\"",
"code",
"+=",
"\" m = %s\\n\"",
"%",
"mass",
"code",
"+=",
"\" f = np.sqrt(m/2/np.pi/k_B_num/T)**d\\n\"",
"code",
"+=",
"\" f = f * np.exp(-m*v**2/2/k_B_num/T)\\n\"",
"code",
"+=",
"\" return f\\n\"",
"# We write the code to file if provided, and execute it.",
"if",
"file_name",
"is",
"not",
"None",
":",
"f",
"=",
"file",
"(",
"file_name",
"+",
"\".py\"",
",",
"\"w\"",
")",
"f",
".",
"write",
"(",
"code",
")",
"f",
".",
"close",
"(",
")",
"maxwell_boltzmann",
"=",
"code",
"if",
"not",
"return_code",
":",
"exec",
"maxwell_boltzmann",
"return",
"maxwell_boltzmann"
] | r"""Return a function that returns values of a Maxwell-Boltzmann
distribution.
>>> from fast import Atom
>>> mass = Atom("Rb", 87).mass
>>> f = fast_maxwell_boltzmann(mass)
>>> print f(0, 273.15+20)
0.00238221482739
>>> import numpy as np
>>> v = np.linspace(-600, 600, 101)
>>> dist = f(v, 273.15+20)
>>> dv = v[1]-v[0]
>>> print sum(dist)*dv
0.999704711134 | [
"r",
"Return",
"a",
"function",
"that",
"returns",
"values",
"of",
"a",
"Maxwell",
"-",
"Boltzmann",
"distribution",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L442-L496 |
oscarlazoarjona/fast | fast/inhomo.py | fast_inhomo_bloch_equations | def fast_inhomo_bloch_equations(Ep, epsilonp, detuning_knob, T, gamma,
omega_level, rm, xi, theta,
unfolding, inhomogeneity, matrix_form=False,
file_name=None, return_code=False):
r"""Return a fast function that returns the numeric right-hand sides of \
inhomogeneous Bloch equations.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.electric_field import PlaneWave
>>> from fast.symbolic import (define_laser_variables,
... polarization_vector)
>>> from fast.atomic_structure import Atom
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
We define symbolic variables to be used as token arguments.
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
We define the Doppler broadening.
>>> shape = [9]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
>>> doppler_effect.domain
[array([-669.86784872, -502.40088654, -334.93392436, -167.46696218,
0. , 167.46696218, 334.93392436, 502.40088654,
669.86784872])]
We obtain a function to calculate the Bloch equations.
>>> T_symb = symbols("T", positive=True)
>>> aux = (Ep, epsilonp, detuning_knob, T_symb, gamma,
... omega_level, rm, xi, theta, unfolding, doppler_effect,
... True)
>>> bloch_equations = fast_inhomo_bloch_equations(*aux)
We calculate an example.
>>> detuning_knobs = [0]
>>> Eps = electric_field_amplitude_top(0, 1e-3, 1, "SI")
>>> Eps *= np.exp(1j*np.pi)
>>> Eps = [Eps]
>>> A, b = bloch_equations(Eps, detuning_knobs, T)
>>> print A[:, 2, 1]*1e-6/2/np.pi
[ 853.49268666 640.12094531 426.74705849 213.37341005 0.
-213.37317167 -426.74610495 -640.11879984 -853.49125636]
>>> print b*1e-6
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
"""
if not unfolding.lower_triangular:
mes = "It is very inefficient to solve using all components of the "
mes += "density matrix. Better set lower_triangular=True in Unfolding."
raise NotImplementedError(mes)
if matrix_form and (not unfolding.real) and (unfolding.lower_triangular):
mes = "It is not possible to express the equations in matrix form "
mes += "for complex lower triangular components only."
raise ValueError(mes)
Nl = len(Ep)
Nrho = unfolding.Nrho
# We determine which arguments are constants.
if True:
try:
Ep = np.array([complex(Ep[l]) for l in range(Nl)])
variable_Ep = False
except:
variable_Ep = True
try:
epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)])
for l in range(Nl)]
variable_epsilonp = False
except:
variable_epsilonp = True
try:
detuning_knob = np.array([float(detuning_knob[l])
for l in range(Nl)])
variable_detuning_knob = False
except:
variable_detuning_knob = True
try:
T = float(T)
variable_T = False
except:
variable_T = True
# We obtain code for the homogeneous terms.
if True:
if file_name is not None:
file_name_bloch = file_name+"_bloch"
else:
file_name_bloch = file_name
aux = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta,
unfolding, matrix_form, file_name_bloch, True)
bloch_equations = fast_bloch_equations(*aux)
code = bloch_equations+"\n\n"
# We establish the arguments of the output function.
if True:
code += "def inhomo_bloch_equations("
code_args = ""
if not matrix_form: code_args += "rho, "
if variable_Ep: code_args += "Ep, "
if variable_epsilonp: code_args += "epsilonp, "
if variable_detuning_knob: code_args += "detuning_knob, "
code += code_args
if variable_T: code += "T, "
code += "inhomogeneity=inhomogeneity, "
code += "bloch_equations=bloch_equations):\n"
code += ' r"""A fast calculation of inhomogeneous '
code += 'Bloch equations."""\n'
# We initialize the output and auxiliaries.
if True:
# We introduce the factor that multiplies all terms.
sha = str(inhomogeneity.shape)[1:-1]+" "
if matrix_form:
code += " A = np.zeros(("+sha+str(Nrho)+", "+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
if unfolding.normalized:
code += " b = np.zeros(("+sha+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
else:
code += " rhs = np.zeros(("+sha+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
# We calculate the equations for each ensemble.
if True:
if variable_T: code += " inhomogeneity.reset(T)\n"
if code_args[-2:] == ", ": code_args = code_args[:-2]
code += " homogeneous = bloch_equations("+code_args+")\n\n"
code += " terms = inhomogeneity.terms\n"
code += " shape = inhomogeneity.shape\n"
code += " domain = inhomogeneity.domain\n"
shape = inhomogeneity.shape
dimension = len(shape)
if dimension == 1:
code += " for i in range(shape[0]):\n"
code += " result = terms(domain[0][i], detuning_knob)\n"
if matrix_form:
if unfolding.normalized:
code += " A[i] = homogeneous[0]+result[0]\n"
code += " b[i] = homogeneous[1]+result[1]\n"
else:
code += " A[i] = homogeneous+result\n"
else:
code += " rhs[i] = homogeneous+result\n"
# We finish the code.
if True:
# code = rabi_code + "\n\n" + code
if matrix_form:
if unfolding.normalized:
code += " return A, b\n"
else:
code += " return A\n"
else:
code += " return rhs\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
inhomo_bloch_equations = code
if not return_code:
exec inhomo_bloch_equations
return inhomo_bloch_equations | python | def fast_inhomo_bloch_equations(Ep, epsilonp, detuning_knob, T, gamma,
omega_level, rm, xi, theta,
unfolding, inhomogeneity, matrix_form=False,
file_name=None, return_code=False):
r"""Return a fast function that returns the numeric right-hand sides of \
inhomogeneous Bloch equations.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.electric_field import PlaneWave
>>> from fast.symbolic import (define_laser_variables,
... polarization_vector)
>>> from fast.atomic_structure import Atom
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
We define symbolic variables to be used as token arguments.
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
We define the Doppler broadening.
>>> shape = [9]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
>>> doppler_effect.domain
[array([-669.86784872, -502.40088654, -334.93392436, -167.46696218,
0. , 167.46696218, 334.93392436, 502.40088654,
669.86784872])]
We obtain a function to calculate the Bloch equations.
>>> T_symb = symbols("T", positive=True)
>>> aux = (Ep, epsilonp, detuning_knob, T_symb, gamma,
... omega_level, rm, xi, theta, unfolding, doppler_effect,
... True)
>>> bloch_equations = fast_inhomo_bloch_equations(*aux)
We calculate an example.
>>> detuning_knobs = [0]
>>> Eps = electric_field_amplitude_top(0, 1e-3, 1, "SI")
>>> Eps *= np.exp(1j*np.pi)
>>> Eps = [Eps]
>>> A, b = bloch_equations(Eps, detuning_knobs, T)
>>> print A[:, 2, 1]*1e-6/2/np.pi
[ 853.49268666 640.12094531 426.74705849 213.37341005 0.
-213.37317167 -426.74610495 -640.11879984 -853.49125636]
>>> print b*1e-6
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
"""
if not unfolding.lower_triangular:
mes = "It is very inefficient to solve using all components of the "
mes += "density matrix. Better set lower_triangular=True in Unfolding."
raise NotImplementedError(mes)
if matrix_form and (not unfolding.real) and (unfolding.lower_triangular):
mes = "It is not possible to express the equations in matrix form "
mes += "for complex lower triangular components only."
raise ValueError(mes)
Nl = len(Ep)
Nrho = unfolding.Nrho
# We determine which arguments are constants.
if True:
try:
Ep = np.array([complex(Ep[l]) for l in range(Nl)])
variable_Ep = False
except:
variable_Ep = True
try:
epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)])
for l in range(Nl)]
variable_epsilonp = False
except:
variable_epsilonp = True
try:
detuning_knob = np.array([float(detuning_knob[l])
for l in range(Nl)])
variable_detuning_knob = False
except:
variable_detuning_knob = True
try:
T = float(T)
variable_T = False
except:
variable_T = True
# We obtain code for the homogeneous terms.
if True:
if file_name is not None:
file_name_bloch = file_name+"_bloch"
else:
file_name_bloch = file_name
aux = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta,
unfolding, matrix_form, file_name_bloch, True)
bloch_equations = fast_bloch_equations(*aux)
code = bloch_equations+"\n\n"
# We establish the arguments of the output function.
if True:
code += "def inhomo_bloch_equations("
code_args = ""
if not matrix_form: code_args += "rho, "
if variable_Ep: code_args += "Ep, "
if variable_epsilonp: code_args += "epsilonp, "
if variable_detuning_knob: code_args += "detuning_knob, "
code += code_args
if variable_T: code += "T, "
code += "inhomogeneity=inhomogeneity, "
code += "bloch_equations=bloch_equations):\n"
code += ' r"""A fast calculation of inhomogeneous '
code += 'Bloch equations."""\n'
# We initialize the output and auxiliaries.
if True:
# We introduce the factor that multiplies all terms.
sha = str(inhomogeneity.shape)[1:-1]+" "
if matrix_form:
code += " A = np.zeros(("+sha+str(Nrho)+", "+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
if unfolding.normalized:
code += " b = np.zeros(("+sha+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
else:
code += " rhs = np.zeros(("+sha+str(Nrho)
if not unfolding.real:
code += "), complex)\n\n"
else:
code += "))\n\n"
# We calculate the equations for each ensemble.
if True:
if variable_T: code += " inhomogeneity.reset(T)\n"
if code_args[-2:] == ", ": code_args = code_args[:-2]
code += " homogeneous = bloch_equations("+code_args+")\n\n"
code += " terms = inhomogeneity.terms\n"
code += " shape = inhomogeneity.shape\n"
code += " domain = inhomogeneity.domain\n"
shape = inhomogeneity.shape
dimension = len(shape)
if dimension == 1:
code += " for i in range(shape[0]):\n"
code += " result = terms(domain[0][i], detuning_knob)\n"
if matrix_form:
if unfolding.normalized:
code += " A[i] = homogeneous[0]+result[0]\n"
code += " b[i] = homogeneous[1]+result[1]\n"
else:
code += " A[i] = homogeneous+result\n"
else:
code += " rhs[i] = homogeneous+result\n"
# We finish the code.
if True:
# code = rabi_code + "\n\n" + code
if matrix_form:
if unfolding.normalized:
code += " return A, b\n"
else:
code += " return A\n"
else:
code += " return rhs\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
inhomo_bloch_equations = code
if not return_code:
exec inhomo_bloch_equations
return inhomo_bloch_equations | [
"def",
"fast_inhomo_bloch_equations",
"(",
"Ep",
",",
"epsilonp",
",",
"detuning_knob",
",",
"T",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"unfolding",
",",
"inhomogeneity",
",",
"matrix_form",
"=",
"False",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"False",
")",
":",
"if",
"not",
"unfolding",
".",
"lower_triangular",
":",
"mes",
"=",
"\"It is very inefficient to solve using all components of the \"",
"mes",
"+=",
"\"density matrix. Better set lower_triangular=True in Unfolding.\"",
"raise",
"NotImplementedError",
"(",
"mes",
")",
"if",
"matrix_form",
"and",
"(",
"not",
"unfolding",
".",
"real",
")",
"and",
"(",
"unfolding",
".",
"lower_triangular",
")",
":",
"mes",
"=",
"\"It is not possible to express the equations in matrix form \"",
"mes",
"+=",
"\"for complex lower triangular components only.\"",
"raise",
"ValueError",
"(",
"mes",
")",
"Nl",
"=",
"len",
"(",
"Ep",
")",
"Nrho",
"=",
"unfolding",
".",
"Nrho",
"# We determine which arguments are constants.",
"if",
"True",
":",
"try",
":",
"Ep",
"=",
"np",
".",
"array",
"(",
"[",
"complex",
"(",
"Ep",
"[",
"l",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"variable_Ep",
"=",
"False",
"except",
":",
"variable_Ep",
"=",
"True",
"try",
":",
"epsilonp",
"=",
"[",
"np",
".",
"array",
"(",
"[",
"complex",
"(",
"epsilonp",
"[",
"l",
"]",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
"variable_epsilonp",
"=",
"False",
"except",
":",
"variable_epsilonp",
"=",
"True",
"try",
":",
"detuning_knob",
"=",
"np",
".",
"array",
"(",
"[",
"float",
"(",
"detuning_knob",
"[",
"l",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"variable_detuning_knob",
"=",
"False",
"except",
":",
"variable_detuning_knob",
"=",
"True",
"try",
":",
"T",
"=",
"float",
"(",
"T",
")",
"variable_T",
"=",
"False",
"except",
":",
"variable_T",
"=",
"True",
"# We obtain code for the homogeneous terms.",
"if",
"True",
":",
"if",
"file_name",
"is",
"not",
"None",
":",
"file_name_bloch",
"=",
"file_name",
"+",
"\"_bloch\"",
"else",
":",
"file_name_bloch",
"=",
"file_name",
"aux",
"=",
"(",
"Ep",
",",
"epsilonp",
",",
"detuning_knob",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"unfolding",
",",
"matrix_form",
",",
"file_name_bloch",
",",
"True",
")",
"bloch_equations",
"=",
"fast_bloch_equations",
"(",
"*",
"aux",
")",
"code",
"=",
"bloch_equations",
"+",
"\"\\n\\n\"",
"# We establish the arguments of the output function.",
"if",
"True",
":",
"code",
"+=",
"\"def inhomo_bloch_equations(\"",
"code_args",
"=",
"\"\"",
"if",
"not",
"matrix_form",
":",
"code_args",
"+=",
"\"rho, \"",
"if",
"variable_Ep",
":",
"code_args",
"+=",
"\"Ep, \"",
"if",
"variable_epsilonp",
":",
"code_args",
"+=",
"\"epsilonp, \"",
"if",
"variable_detuning_knob",
":",
"code_args",
"+=",
"\"detuning_knob, \"",
"code",
"+=",
"code_args",
"if",
"variable_T",
":",
"code",
"+=",
"\"T, \"",
"code",
"+=",
"\"inhomogeneity=inhomogeneity, \"",
"code",
"+=",
"\"bloch_equations=bloch_equations):\\n\"",
"code",
"+=",
"' r\"\"\"A fast calculation of inhomogeneous '",
"code",
"+=",
"'Bloch equations.\"\"\"\\n'",
"# We initialize the output and auxiliaries.",
"if",
"True",
":",
"# We introduce the factor that multiplies all terms.",
"sha",
"=",
"str",
"(",
"inhomogeneity",
".",
"shape",
")",
"[",
"1",
":",
"-",
"1",
"]",
"+",
"\" \"",
"if",
"matrix_form",
":",
"code",
"+=",
"\" A = np.zeros((\"",
"+",
"sha",
"+",
"str",
"(",
"Nrho",
")",
"+",
"\", \"",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"if",
"unfolding",
".",
"normalized",
":",
"code",
"+=",
"\" b = np.zeros((\"",
"+",
"sha",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"else",
":",
"code",
"+=",
"\" rhs = np.zeros((\"",
"+",
"sha",
"+",
"str",
"(",
"Nrho",
")",
"if",
"not",
"unfolding",
".",
"real",
":",
"code",
"+=",
"\"), complex)\\n\\n\"",
"else",
":",
"code",
"+=",
"\"))\\n\\n\"",
"# We calculate the equations for each ensemble.",
"if",
"True",
":",
"if",
"variable_T",
":",
"code",
"+=",
"\" inhomogeneity.reset(T)\\n\"",
"if",
"code_args",
"[",
"-",
"2",
":",
"]",
"==",
"\", \"",
":",
"code_args",
"=",
"code_args",
"[",
":",
"-",
"2",
"]",
"code",
"+=",
"\" homogeneous = bloch_equations(\"",
"+",
"code_args",
"+",
"\")\\n\\n\"",
"code",
"+=",
"\" terms = inhomogeneity.terms\\n\"",
"code",
"+=",
"\" shape = inhomogeneity.shape\\n\"",
"code",
"+=",
"\" domain = inhomogeneity.domain\\n\"",
"shape",
"=",
"inhomogeneity",
".",
"shape",
"dimension",
"=",
"len",
"(",
"shape",
")",
"if",
"dimension",
"==",
"1",
":",
"code",
"+=",
"\" for i in range(shape[0]):\\n\"",
"code",
"+=",
"\" result = terms(domain[0][i], detuning_knob)\\n\"",
"if",
"matrix_form",
":",
"if",
"unfolding",
".",
"normalized",
":",
"code",
"+=",
"\" A[i] = homogeneous[0]+result[0]\\n\"",
"code",
"+=",
"\" b[i] = homogeneous[1]+result[1]\\n\"",
"else",
":",
"code",
"+=",
"\" A[i] = homogeneous+result\\n\"",
"else",
":",
"code",
"+=",
"\" rhs[i] = homogeneous+result\\n\"",
"# We finish the code.",
"if",
"True",
":",
"# code = rabi_code + \"\\n\\n\" + code",
"if",
"matrix_form",
":",
"if",
"unfolding",
".",
"normalized",
":",
"code",
"+=",
"\" return A, b\\n\"",
"else",
":",
"code",
"+=",
"\" return A\\n\"",
"else",
":",
"code",
"+=",
"\" return rhs\\n\"",
"# We write the code to file if provided, and execute it.",
"if",
"True",
":",
"if",
"file_name",
"is",
"not",
"None",
":",
"f",
"=",
"file",
"(",
"file_name",
"+",
"\".py\"",
",",
"\"w\"",
")",
"f",
".",
"write",
"(",
"code",
")",
"f",
".",
"close",
"(",
")",
"inhomo_bloch_equations",
"=",
"code",
"if",
"not",
"return_code",
":",
"exec",
"inhomo_bloch_equations",
"return",
"inhomo_bloch_equations"
] | r"""Return a fast function that returns the numeric right-hand sides of \
inhomogeneous Bloch equations.
We test a basic two-level system.
>>> import numpy as np
>>> from scipy.constants import physical_constants
>>> from sympy import Matrix, symbols
>>> from fast.electric_field import electric_field_amplitude_top
>>> from fast.electric_field import PlaneWave
>>> from fast.symbolic import (define_laser_variables,
... polarization_vector)
>>> from fast.atomic_structure import Atom
>>> from fast.bloch import phase_transformation
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
We define symbolic variables to be used as token arguments.
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
We define the Doppler broadening.
>>> shape = [9]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
>>> doppler_effect.domain
[array([-669.86784872, -502.40088654, -334.93392436, -167.46696218,
0. , 167.46696218, 334.93392436, 502.40088654,
669.86784872])]
We obtain a function to calculate the Bloch equations.
>>> T_symb = symbols("T", positive=True)
>>> aux = (Ep, epsilonp, detuning_knob, T_symb, gamma,
... omega_level, rm, xi, theta, unfolding, doppler_effect,
... True)
>>> bloch_equations = fast_inhomo_bloch_equations(*aux)
We calculate an example.
>>> detuning_knobs = [0]
>>> Eps = electric_field_amplitude_top(0, 1e-3, 1, "SI")
>>> Eps *= np.exp(1j*np.pi)
>>> Eps = [Eps]
>>> A, b = bloch_equations(Eps, detuning_knobs, T)
>>> print A[:, 2, 1]*1e-6/2/np.pi
[ 853.49268666 640.12094531 426.74705849 213.37341005 0.
-213.37317167 -426.74610495 -640.11879984 -853.49125636]
>>> print b*1e-6
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]] | [
"r",
"Return",
"a",
"fast",
"function",
"that",
"returns",
"the",
"numeric",
"right",
"-",
"hand",
"sides",
"of",
"\\",
"inhomogeneous",
"Bloch",
"equations",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L499-L709 |
oscarlazoarjona/fast | fast/inhomo.py | fast_inhomo_sweep_time_evolution | def fast_inhomo_sweep_time_evolution(Ep, epsilonp, gamma,
omega_level, rm, xi, theta,
inhomogeneity,
semi_analytic=True,
file_name=None, return_code=False):
r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-level system.
>>> from fast.bloch import phase_transformation
>>> from fast import PlaneWave, electric_field_amplitude_top, Atom
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
>>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")
>>> Eps = [Eps]
>>> t = np.linspace(0, 1e-6, 11)
>>> rho0 = np.array([[1, 0], [0, 0]])
>>> rho0 = unfolding(rho0)
We define the Doppler broadening.
>>> Nvz = 15
>>> shape = [Nvz]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
We get a function for the frequency sweep of time evolution.
>>> aux = (Ep, epsilonp, gamma,
... omega_level, rm, xi, theta,
... doppler_effect,
... True,
... "eqs")
>>> inhomo_time_evolution = fast_inhomo_sweep_time_evolution(*aux)
>>> amp = 1000e6*2*np.pi
>>> Ndelta = 101
>>> detuning_knobs = [[-amp, amp, Ndelta]]
>>> deltas, rhot = inhomo_time_evolution(t, rho0, Eps, detuning_knobs)
>>> print rhot.shape
(101, 11, 15, 3)
"""
# We unpack variables.
if True:
Nl = xi.shape[0]
# We determine which arguments are constants.
if True:
try:
Ep = np.array([complex(Ep[l]) for l in range(Nl)])
variable_Ep = False
except:
variable_Ep = True
try:
epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)])
for l in range(Nl)]
variable_epsilonp = False
except:
variable_epsilonp = True
# We obtain code for the time evolution.
if True:
detuning_knob = symbols("delta1:"+str(Nl))
args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta,
file_name, True)
args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi,
theta, inhomogeneity, True, file_name, True)
inhomo_time_evolution = fast_inhomo_time_evolution(*args)
code = inhomo_time_evolution+"\n\n"
# We establish the arguments of the output function.
if True:
code += "def inhomo_sweep_time_evolution(t, rho0, "
if variable_Ep: code += "Ep, "
if variable_epsilonp: code += "epsilonp, "
code += "detuning_knob, "
code += "inhomo_time_evolution=inhomo_time_evolution):\n"
code += ' r"""A fast frequency sweep of the steady state."""\n'
# Code to determine the sweep range.
if True:
code += """ sweepN = -1\n"""
code += """ for i, delta in enumerate(detuning_knob):\n"""
code += """ if hasattr(delta, "__getitem__"):\n"""
code += """ sweepN = i\n"""
code += """ delta0 = delta[0]\n"""
code += """ deltaf = delta[1]\n"""
code += """ Ndelta = delta[2]\n"""
code += """ break\n\n"""
code += """ if sweepN == -1:\n"""
code += """ s = 'One of the detuning knobs '\n"""
code += """ s += 'must be of the form '\n"""
code += """ s += '(start, stop, Nsteps)'\n"""
code += """ raise ValueError(s)\n\n"""
code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n"""
# We call time_evolution.
if True:
code += " args = [[t, rho0, "
if variable_Ep: code += "Ep, "
if variable_epsilonp: code += "epsilonp, "
code += """list(detuning_knob[:sweepN]) +\n"""
code += """ [deltas[i]] +\n"""
code += """ list(detuning_knob[sweepN+1:])]\n"""
code += """ for i in range(Ndelta)]\n\n"""
code += " rho = np.array([inhomo_time_evolution(*argsi)\n"
code += " for argsi in args])\n\n"
# We finish the code.
if True:
code += " return deltas, rho\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
inhomo_sweep_time_evolution = code
if not return_code:
exec inhomo_sweep_time_evolution
return inhomo_sweep_time_evolution | python | def fast_inhomo_sweep_time_evolution(Ep, epsilonp, gamma,
omega_level, rm, xi, theta,
inhomogeneity,
semi_analytic=True,
file_name=None, return_code=False):
r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-level system.
>>> from fast.bloch import phase_transformation
>>> from fast import PlaneWave, electric_field_amplitude_top, Atom
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
>>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")
>>> Eps = [Eps]
>>> t = np.linspace(0, 1e-6, 11)
>>> rho0 = np.array([[1, 0], [0, 0]])
>>> rho0 = unfolding(rho0)
We define the Doppler broadening.
>>> Nvz = 15
>>> shape = [Nvz]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
We get a function for the frequency sweep of time evolution.
>>> aux = (Ep, epsilonp, gamma,
... omega_level, rm, xi, theta,
... doppler_effect,
... True,
... "eqs")
>>> inhomo_time_evolution = fast_inhomo_sweep_time_evolution(*aux)
>>> amp = 1000e6*2*np.pi
>>> Ndelta = 101
>>> detuning_knobs = [[-amp, amp, Ndelta]]
>>> deltas, rhot = inhomo_time_evolution(t, rho0, Eps, detuning_knobs)
>>> print rhot.shape
(101, 11, 15, 3)
"""
# We unpack variables.
if True:
Nl = xi.shape[0]
# We determine which arguments are constants.
if True:
try:
Ep = np.array([complex(Ep[l]) for l in range(Nl)])
variable_Ep = False
except:
variable_Ep = True
try:
epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)])
for l in range(Nl)]
variable_epsilonp = False
except:
variable_epsilonp = True
# We obtain code for the time evolution.
if True:
detuning_knob = symbols("delta1:"+str(Nl))
args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta,
file_name, True)
args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi,
theta, inhomogeneity, True, file_name, True)
inhomo_time_evolution = fast_inhomo_time_evolution(*args)
code = inhomo_time_evolution+"\n\n"
# We establish the arguments of the output function.
if True:
code += "def inhomo_sweep_time_evolution(t, rho0, "
if variable_Ep: code += "Ep, "
if variable_epsilonp: code += "epsilonp, "
code += "detuning_knob, "
code += "inhomo_time_evolution=inhomo_time_evolution):\n"
code += ' r"""A fast frequency sweep of the steady state."""\n'
# Code to determine the sweep range.
if True:
code += """ sweepN = -1\n"""
code += """ for i, delta in enumerate(detuning_knob):\n"""
code += """ if hasattr(delta, "__getitem__"):\n"""
code += """ sweepN = i\n"""
code += """ delta0 = delta[0]\n"""
code += """ deltaf = delta[1]\n"""
code += """ Ndelta = delta[2]\n"""
code += """ break\n\n"""
code += """ if sweepN == -1:\n"""
code += """ s = 'One of the detuning knobs '\n"""
code += """ s += 'must be of the form '\n"""
code += """ s += '(start, stop, Nsteps)'\n"""
code += """ raise ValueError(s)\n\n"""
code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n"""
# We call time_evolution.
if True:
code += " args = [[t, rho0, "
if variable_Ep: code += "Ep, "
if variable_epsilonp: code += "epsilonp, "
code += """list(detuning_knob[:sweepN]) +\n"""
code += """ [deltas[i]] +\n"""
code += """ list(detuning_knob[sweepN+1:])]\n"""
code += """ for i in range(Ndelta)]\n\n"""
code += " rho = np.array([inhomo_time_evolution(*argsi)\n"
code += " for argsi in args])\n\n"
# We finish the code.
if True:
code += " return deltas, rho\n"
# We write the code to file if provided, and execute it.
if True:
if file_name is not None:
f = file(file_name+".py", "w")
f.write(code)
f.close()
inhomo_sweep_time_evolution = code
if not return_code:
exec inhomo_sweep_time_evolution
return inhomo_sweep_time_evolution | [
"def",
"fast_inhomo_sweep_time_evolution",
"(",
"Ep",
",",
"epsilonp",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"inhomogeneity",
",",
"semi_analytic",
"=",
"True",
",",
"file_name",
"=",
"None",
",",
"return_code",
"=",
"False",
")",
":",
"# We unpack variables.",
"if",
"True",
":",
"Nl",
"=",
"xi",
".",
"shape",
"[",
"0",
"]",
"# We determine which arguments are constants.",
"if",
"True",
":",
"try",
":",
"Ep",
"=",
"np",
".",
"array",
"(",
"[",
"complex",
"(",
"Ep",
"[",
"l",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"variable_Ep",
"=",
"False",
"except",
":",
"variable_Ep",
"=",
"True",
"try",
":",
"epsilonp",
"=",
"[",
"np",
".",
"array",
"(",
"[",
"complex",
"(",
"epsilonp",
"[",
"l",
"]",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
"variable_epsilonp",
"=",
"False",
"except",
":",
"variable_epsilonp",
"=",
"True",
"# We obtain code for the time evolution.",
"if",
"True",
":",
"detuning_knob",
"=",
"symbols",
"(",
"\"delta1:\"",
"+",
"str",
"(",
"Nl",
")",
")",
"args",
"=",
"(",
"Ep",
",",
"epsilonp",
",",
"detuning_knob",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"file_name",
",",
"True",
")",
"args",
"=",
"(",
"Ep",
",",
"epsilonp",
",",
"detuning_knob",
",",
"gamma",
",",
"omega_level",
",",
"rm",
",",
"xi",
",",
"theta",
",",
"inhomogeneity",
",",
"True",
",",
"file_name",
",",
"True",
")",
"inhomo_time_evolution",
"=",
"fast_inhomo_time_evolution",
"(",
"*",
"args",
")",
"code",
"=",
"inhomo_time_evolution",
"+",
"\"\\n\\n\"",
"# We establish the arguments of the output function.",
"if",
"True",
":",
"code",
"+=",
"\"def inhomo_sweep_time_evolution(t, rho0, \"",
"if",
"variable_Ep",
":",
"code",
"+=",
"\"Ep, \"",
"if",
"variable_epsilonp",
":",
"code",
"+=",
"\"epsilonp, \"",
"code",
"+=",
"\"detuning_knob, \"",
"code",
"+=",
"\"inhomo_time_evolution=inhomo_time_evolution):\\n\"",
"code",
"+=",
"' r\"\"\"A fast frequency sweep of the steady state.\"\"\"\\n'",
"# Code to determine the sweep range.",
"if",
"True",
":",
"code",
"+=",
"\"\"\" sweepN = -1\\n\"\"\"",
"code",
"+=",
"\"\"\" for i, delta in enumerate(detuning_knob):\\n\"\"\"",
"code",
"+=",
"\"\"\" if hasattr(delta, \"__getitem__\"):\\n\"\"\"",
"code",
"+=",
"\"\"\" sweepN = i\\n\"\"\"",
"code",
"+=",
"\"\"\" delta0 = delta[0]\\n\"\"\"",
"code",
"+=",
"\"\"\" deltaf = delta[1]\\n\"\"\"",
"code",
"+=",
"\"\"\" Ndelta = delta[2]\\n\"\"\"",
"code",
"+=",
"\"\"\" break\\n\\n\"\"\"",
"code",
"+=",
"\"\"\" if sweepN == -1:\\n\"\"\"",
"code",
"+=",
"\"\"\" s = 'One of the detuning knobs '\\n\"\"\"",
"code",
"+=",
"\"\"\" s += 'must be of the form '\\n\"\"\"",
"code",
"+=",
"\"\"\" s += '(start, stop, Nsteps)'\\n\"\"\"",
"code",
"+=",
"\"\"\" raise ValueError(s)\\n\\n\"\"\"",
"code",
"+=",
"\"\"\" deltas = np.linspace(delta0, deltaf, Ndelta)\\n\\n\"\"\"",
"# We call time_evolution.",
"if",
"True",
":",
"code",
"+=",
"\" args = [[t, rho0, \"",
"if",
"variable_Ep",
":",
"code",
"+=",
"\"Ep, \"",
"if",
"variable_epsilonp",
":",
"code",
"+=",
"\"epsilonp, \"",
"code",
"+=",
"\"\"\"list(detuning_knob[:sweepN]) +\\n\"\"\"",
"code",
"+=",
"\"\"\" [deltas[i]] +\\n\"\"\"",
"code",
"+=",
"\"\"\" list(detuning_knob[sweepN+1:])]\\n\"\"\"",
"code",
"+=",
"\"\"\" for i in range(Ndelta)]\\n\\n\"\"\"",
"code",
"+=",
"\" rho = np.array([inhomo_time_evolution(*argsi)\\n\"",
"code",
"+=",
"\" for argsi in args])\\n\\n\"",
"# We finish the code.",
"if",
"True",
":",
"code",
"+=",
"\" return deltas, rho\\n\"",
"# We write the code to file if provided, and execute it.",
"if",
"True",
":",
"if",
"file_name",
"is",
"not",
"None",
":",
"f",
"=",
"file",
"(",
"file_name",
"+",
"\".py\"",
",",
"\"w\"",
")",
"f",
".",
"write",
"(",
"code",
")",
"f",
".",
"close",
"(",
")",
"inhomo_sweep_time_evolution",
"=",
"code",
"if",
"not",
"return_code",
":",
"exec",
"inhomo_sweep_time_evolution",
"return",
"inhomo_sweep_time_evolution"
] | r"""Return a spectrum of time evolutions of the density matrix.
We test a basic two-level system.
>>> from fast.bloch import phase_transformation
>>> from fast import PlaneWave, electric_field_amplitude_top, Atom
>>> Ne = 2
>>> Nl = 1
>>> a0 = physical_constants["Bohr radius"][0]
>>> rm = [np.array([[0, 0], [a0, 0]]),
... np.array([[0, 0], [0, 0]]),
... np.array([[0, 0], [0, 0]])]
>>> xi = np.array([[[0, 1], [1, 0]]])
>>> omega_level = [0, 2.4e15]
>>> gamma21 = 2*np.pi*6e6
>>> gamma = np.array([[0, -gamma21], [gamma21, 0]])
>>> theta = phase_transformation(Ne, Nl, rm, xi)
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> laser = PlaneWave(0, 0, 0, 0)
>>> epsilonp = [laser.epsilonp]
>>> k = [laser.k]
>>> detuning_knob = [symbols("delta1", real=True)]
A map to unfold the density matrix.
>>> unfolding = Unfolding(Ne, True, True, True)
>>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")
>>> Eps = [Eps]
>>> t = np.linspace(0, 1e-6, 11)
>>> rho0 = np.array([[1, 0], [0, 0]])
>>> rho0 = unfolding(rho0)
We define the Doppler broadening.
>>> Nvz = 15
>>> shape = [Nvz]
>>> stds = [[-4, 4]]
>>> T = 273.15+20
>>> mass = Atom("Rb", 87).mass
>>> aux = (shape, stds, T, mass, detuning_knob, k,
... omega_level, xi, theta, unfolding, ["z", "x", "y"],
... True)
>>> doppler_effect = DopplerBroadening(*aux)
We get a function for the frequency sweep of time evolution.
>>> aux = (Ep, epsilonp, gamma,
... omega_level, rm, xi, theta,
... doppler_effect,
... True,
... "eqs")
>>> inhomo_time_evolution = fast_inhomo_sweep_time_evolution(*aux)
>>> amp = 1000e6*2*np.pi
>>> Ndelta = 101
>>> detuning_knobs = [[-amp, amp, Ndelta]]
>>> deltas, rhot = inhomo_time_evolution(t, rho0, Eps, detuning_knobs)
>>> print rhot.shape
(101, 11, 15, 3) | [
"r",
"Return",
"a",
"spectrum",
"of",
"time",
"evolutions",
"of",
"the",
"density",
"matrix",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L985-L1129 |
oscarlazoarjona/fast | fast/inhomo.py | Inhomogeneity.average | def average(self, rho):
r"""Return the average density matrix of an inhomogeneous ensemble."""
def marginal(f, rho):
remaining = len(f.shape)
if remaining == 0:
return rho
rho = sum([f[i]*rho[i] for i in range(rho.shape[0])])
f = np.sum(f, 0)
return marginal(f, rho)
return marginal(self.distribution, rho) | python | def average(self, rho):
r"""Return the average density matrix of an inhomogeneous ensemble."""
def marginal(f, rho):
remaining = len(f.shape)
if remaining == 0:
return rho
rho = sum([f[i]*rho[i] for i in range(rho.shape[0])])
f = np.sum(f, 0)
return marginal(f, rho)
return marginal(self.distribution, rho) | [
"def",
"average",
"(",
"self",
",",
"rho",
")",
":",
"def",
"marginal",
"(",
"f",
",",
"rho",
")",
":",
"remaining",
"=",
"len",
"(",
"f",
".",
"shape",
")",
"if",
"remaining",
"==",
"0",
":",
"return",
"rho",
"rho",
"=",
"sum",
"(",
"[",
"f",
"[",
"i",
"]",
"*",
"rho",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"rho",
".",
"shape",
"[",
"0",
"]",
")",
"]",
")",
"f",
"=",
"np",
".",
"sum",
"(",
"f",
",",
"0",
")",
"return",
"marginal",
"(",
"f",
",",
"rho",
")",
"return",
"marginal",
"(",
"self",
".",
"distribution",
",",
"rho",
")"
] | r"""Return the average density matrix of an inhomogeneous ensemble. | [
"r",
"Return",
"the",
"average",
"density",
"matrix",
"of",
"an",
"inhomogeneous",
"ensemble",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L104-L114 |
oscarlazoarjona/fast | fast/inhomo.py | DopplerBroadening.reset | def reset(self, T):
r"""Recalculate the doppler broadening for a given temperature."""
self.__init__(self.shape, self.stds, T,
self.mass, self.detuning_knob, self.k,
self.omega_level, self.xi, self.theta, self.unfolding,
self.axes,
self.matrix_form) | python | def reset(self, T):
r"""Recalculate the doppler broadening for a given temperature."""
self.__init__(self.shape, self.stds, T,
self.mass, self.detuning_knob, self.k,
self.omega_level, self.xi, self.theta, self.unfolding,
self.axes,
self.matrix_form) | [
"def",
"reset",
"(",
"self",
",",
"T",
")",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"shape",
",",
"self",
".",
"stds",
",",
"T",
",",
"self",
".",
"mass",
",",
"self",
".",
"detuning_knob",
",",
"self",
".",
"k",
",",
"self",
".",
"omega_level",
",",
"self",
".",
"xi",
",",
"self",
".",
"theta",
",",
"self",
".",
"unfolding",
",",
"self",
".",
"axes",
",",
"self",
".",
"matrix_form",
")"
] | r"""Recalculate the doppler broadening for a given temperature. | [
"r",
"Recalculate",
"the",
"doppler",
"broadening",
"for",
"a",
"given",
"temperature",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/inhomo.py#L232-L238 |
tdsmith/ijroi | ijroi/ijroi.py | read_roi | def read_roi(fileobj):
'''
points = read_roi(fileobj)
Read ImageJ's ROI format. Points are returned in a nx2 array. Each row
is in [row, column] -- that is, (y,x) -- order.
'''
# This is based on:
# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html
# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiEncoder.java.html
SPLINE_FIT = 1
DOUBLE_HEADED = 2
OUTLINE = 4
OVERLAY_LABELS = 8
OVERLAY_NAMES = 16
OVERLAY_BACKGROUNDS = 32
OVERLAY_BOLD = 64
SUB_PIXEL_RESOLUTION = 128
DRAW_OFFSET = 256
class RoiType:
POLYGON = 0
RECT = 1
OVAL = 2
LINE = 3
FREELINE = 4
POLYLINE = 5
NOROI = 6
FREEHAND = 7
TRACED = 8
ANGLE = 9
POINT = 10
def get8():
s = fileobj.read(1)
if not s:
raise IOError('readroi: Unexpected EOF')
return ord(s)
def get16():
b0 = get8()
b1 = get8()
return (b0 << 8) | b1
def get32():
s0 = get16()
s1 = get16()
return (s0 << 16) | s1
def getfloat():
v = np.int32(get32())
return v.view(np.float32)
#===========================================================================
#Read Header data
magic = fileobj.read(4)
if magic != b'Iout':
raise ValueError('Magic number not found')
version = get16()
# It seems that the roi type field occupies 2 Bytes, but only one is used
roi_type = get8()
# Discard second Byte:
get8()
top = get16()
left = get16()
bottom = get16()
right = get16()
n_coordinates = get16()
x1 = getfloat()
y1 = getfloat()
x2 = getfloat()
y2 = getfloat()
stroke_width = get16()
shape_roi_size = get32()
stroke_color = get32()
fill_color = get32()
subtype = get16()
options = get16()
arrow_style = get8()
arrow_head_size = get8()
rect_arc_size = get16()
position = get32()
header2offset = get32()
# End Header data
#===========================================================================
#RoiDecoder.java checks the version when setting sub-pixel resolution, therefore so do we
subPixelResolution = ((options&SUB_PIXEL_RESOLUTION)!=0) and (version>=222)
# Check exceptions
if roi_type not in [RoiType.FREEHAND, RoiType.TRACED, RoiType.POLYGON, RoiType.RECT, RoiType.POINT]:
raise NotImplementedError('roireader: ROI type %s not supported' % roi_type)
if subtype != 0:
raise NotImplementedError('roireader: ROI subtype %s not supported (!= 0)' % subtype)
if roi_type == RoiType.RECT:
if subPixelResolution:
return np.array(
[[y1, x1], [y1, x1+x2], [y1+y2, x1+x2], [y1+y2, x1]],
dtype=np.float32)
else:
return np.array(
[[top, left], [top, right], [bottom, right], [bottom, left]],
dtype=np.int16)
if subPixelResolution:
getc = getfloat
points = np.empty((n_coordinates, 2), dtype=np.float32)
fileobj.seek(4*n_coordinates, 1)
else:
getc = get16
points = np.empty((n_coordinates, 2), dtype=np.int16)
points[:, 1] = [getc() for i in range(n_coordinates)]
points[:, 0] = [getc() for i in range(n_coordinates)]
if not subPixelResolution:
points[:, 1] += left
points[:, 0] += top
return points | python | def read_roi(fileobj):
'''
points = read_roi(fileobj)
Read ImageJ's ROI format. Points are returned in a nx2 array. Each row
is in [row, column] -- that is, (y,x) -- order.
'''
# This is based on:
# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html
# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiEncoder.java.html
SPLINE_FIT = 1
DOUBLE_HEADED = 2
OUTLINE = 4
OVERLAY_LABELS = 8
OVERLAY_NAMES = 16
OVERLAY_BACKGROUNDS = 32
OVERLAY_BOLD = 64
SUB_PIXEL_RESOLUTION = 128
DRAW_OFFSET = 256
class RoiType:
POLYGON = 0
RECT = 1
OVAL = 2
LINE = 3
FREELINE = 4
POLYLINE = 5
NOROI = 6
FREEHAND = 7
TRACED = 8
ANGLE = 9
POINT = 10
def get8():
s = fileobj.read(1)
if not s:
raise IOError('readroi: Unexpected EOF')
return ord(s)
def get16():
b0 = get8()
b1 = get8()
return (b0 << 8) | b1
def get32():
s0 = get16()
s1 = get16()
return (s0 << 16) | s1
def getfloat():
v = np.int32(get32())
return v.view(np.float32)
#===========================================================================
#Read Header data
magic = fileobj.read(4)
if magic != b'Iout':
raise ValueError('Magic number not found')
version = get16()
# It seems that the roi type field occupies 2 Bytes, but only one is used
roi_type = get8()
# Discard second Byte:
get8()
top = get16()
left = get16()
bottom = get16()
right = get16()
n_coordinates = get16()
x1 = getfloat()
y1 = getfloat()
x2 = getfloat()
y2 = getfloat()
stroke_width = get16()
shape_roi_size = get32()
stroke_color = get32()
fill_color = get32()
subtype = get16()
options = get16()
arrow_style = get8()
arrow_head_size = get8()
rect_arc_size = get16()
position = get32()
header2offset = get32()
# End Header data
#===========================================================================
#RoiDecoder.java checks the version when setting sub-pixel resolution, therefore so do we
subPixelResolution = ((options&SUB_PIXEL_RESOLUTION)!=0) and (version>=222)
# Check exceptions
if roi_type not in [RoiType.FREEHAND, RoiType.TRACED, RoiType.POLYGON, RoiType.RECT, RoiType.POINT]:
raise NotImplementedError('roireader: ROI type %s not supported' % roi_type)
if subtype != 0:
raise NotImplementedError('roireader: ROI subtype %s not supported (!= 0)' % subtype)
if roi_type == RoiType.RECT:
if subPixelResolution:
return np.array(
[[y1, x1], [y1, x1+x2], [y1+y2, x1+x2], [y1+y2, x1]],
dtype=np.float32)
else:
return np.array(
[[top, left], [top, right], [bottom, right], [bottom, left]],
dtype=np.int16)
if subPixelResolution:
getc = getfloat
points = np.empty((n_coordinates, 2), dtype=np.float32)
fileobj.seek(4*n_coordinates, 1)
else:
getc = get16
points = np.empty((n_coordinates, 2), dtype=np.int16)
points[:, 1] = [getc() for i in range(n_coordinates)]
points[:, 0] = [getc() for i in range(n_coordinates)]
if not subPixelResolution:
points[:, 1] += left
points[:, 0] += top
return points | [
"def",
"read_roi",
"(",
"fileobj",
")",
":",
"# This is based on:",
"# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html",
"# http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiEncoder.java.html",
"SPLINE_FIT",
"=",
"1",
"DOUBLE_HEADED",
"=",
"2",
"OUTLINE",
"=",
"4",
"OVERLAY_LABELS",
"=",
"8",
"OVERLAY_NAMES",
"=",
"16",
"OVERLAY_BACKGROUNDS",
"=",
"32",
"OVERLAY_BOLD",
"=",
"64",
"SUB_PIXEL_RESOLUTION",
"=",
"128",
"DRAW_OFFSET",
"=",
"256",
"class",
"RoiType",
":",
"POLYGON",
"=",
"0",
"RECT",
"=",
"1",
"OVAL",
"=",
"2",
"LINE",
"=",
"3",
"FREELINE",
"=",
"4",
"POLYLINE",
"=",
"5",
"NOROI",
"=",
"6",
"FREEHAND",
"=",
"7",
"TRACED",
"=",
"8",
"ANGLE",
"=",
"9",
"POINT",
"=",
"10",
"def",
"get8",
"(",
")",
":",
"s",
"=",
"fileobj",
".",
"read",
"(",
"1",
")",
"if",
"not",
"s",
":",
"raise",
"IOError",
"(",
"'readroi: Unexpected EOF'",
")",
"return",
"ord",
"(",
"s",
")",
"def",
"get16",
"(",
")",
":",
"b0",
"=",
"get8",
"(",
")",
"b1",
"=",
"get8",
"(",
")",
"return",
"(",
"b0",
"<<",
"8",
")",
"|",
"b1",
"def",
"get32",
"(",
")",
":",
"s0",
"=",
"get16",
"(",
")",
"s1",
"=",
"get16",
"(",
")",
"return",
"(",
"s0",
"<<",
"16",
")",
"|",
"s1",
"def",
"getfloat",
"(",
")",
":",
"v",
"=",
"np",
".",
"int32",
"(",
"get32",
"(",
")",
")",
"return",
"v",
".",
"view",
"(",
"np",
".",
"float32",
")",
"#===========================================================================",
"#Read Header data",
"magic",
"=",
"fileobj",
".",
"read",
"(",
"4",
")",
"if",
"magic",
"!=",
"b'Iout'",
":",
"raise",
"ValueError",
"(",
"'Magic number not found'",
")",
"version",
"=",
"get16",
"(",
")",
"# It seems that the roi type field occupies 2 Bytes, but only one is used",
"roi_type",
"=",
"get8",
"(",
")",
"# Discard second Byte:",
"get8",
"(",
")",
"top",
"=",
"get16",
"(",
")",
"left",
"=",
"get16",
"(",
")",
"bottom",
"=",
"get16",
"(",
")",
"right",
"=",
"get16",
"(",
")",
"n_coordinates",
"=",
"get16",
"(",
")",
"x1",
"=",
"getfloat",
"(",
")",
"y1",
"=",
"getfloat",
"(",
")",
"x2",
"=",
"getfloat",
"(",
")",
"y2",
"=",
"getfloat",
"(",
")",
"stroke_width",
"=",
"get16",
"(",
")",
"shape_roi_size",
"=",
"get32",
"(",
")",
"stroke_color",
"=",
"get32",
"(",
")",
"fill_color",
"=",
"get32",
"(",
")",
"subtype",
"=",
"get16",
"(",
")",
"options",
"=",
"get16",
"(",
")",
"arrow_style",
"=",
"get8",
"(",
")",
"arrow_head_size",
"=",
"get8",
"(",
")",
"rect_arc_size",
"=",
"get16",
"(",
")",
"position",
"=",
"get32",
"(",
")",
"header2offset",
"=",
"get32",
"(",
")",
"# End Header data",
"#===========================================================================",
"#RoiDecoder.java checks the version when setting sub-pixel resolution, therefore so do we",
"subPixelResolution",
"=",
"(",
"(",
"options",
"&",
"SUB_PIXEL_RESOLUTION",
")",
"!=",
"0",
")",
"and",
"(",
"version",
">=",
"222",
")",
"# Check exceptions",
"if",
"roi_type",
"not",
"in",
"[",
"RoiType",
".",
"FREEHAND",
",",
"RoiType",
".",
"TRACED",
",",
"RoiType",
".",
"POLYGON",
",",
"RoiType",
".",
"RECT",
",",
"RoiType",
".",
"POINT",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'roireader: ROI type %s not supported'",
"%",
"roi_type",
")",
"if",
"subtype",
"!=",
"0",
":",
"raise",
"NotImplementedError",
"(",
"'roireader: ROI subtype %s not supported (!= 0)'",
"%",
"subtype",
")",
"if",
"roi_type",
"==",
"RoiType",
".",
"RECT",
":",
"if",
"subPixelResolution",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"y1",
",",
"x1",
"]",
",",
"[",
"y1",
",",
"x1",
"+",
"x2",
"]",
",",
"[",
"y1",
"+",
"y2",
",",
"x1",
"+",
"x2",
"]",
",",
"[",
"y1",
"+",
"y2",
",",
"x1",
"]",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"else",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"top",
",",
"left",
"]",
",",
"[",
"top",
",",
"right",
"]",
",",
"[",
"bottom",
",",
"right",
"]",
",",
"[",
"bottom",
",",
"left",
"]",
"]",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"if",
"subPixelResolution",
":",
"getc",
"=",
"getfloat",
"points",
"=",
"np",
".",
"empty",
"(",
"(",
"n_coordinates",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"fileobj",
".",
"seek",
"(",
"4",
"*",
"n_coordinates",
",",
"1",
")",
"else",
":",
"getc",
"=",
"get16",
"points",
"=",
"np",
".",
"empty",
"(",
"(",
"n_coordinates",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"points",
"[",
":",
",",
"1",
"]",
"=",
"[",
"getc",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n_coordinates",
")",
"]",
"points",
"[",
":",
",",
"0",
"]",
"=",
"[",
"getc",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n_coordinates",
")",
"]",
"if",
"not",
"subPixelResolution",
":",
"points",
"[",
":",
",",
"1",
"]",
"+=",
"left",
"points",
"[",
":",
",",
"0",
"]",
"+=",
"top",
"return",
"points"
] | points = read_roi(fileobj)
Read ImageJ's ROI format. Points are returned in a nx2 array. Each row
is in [row, column] -- that is, (y,x) -- order. | [
"points",
"=",
"read_roi",
"(",
"fileobj",
")"
] | train | https://github.com/tdsmith/ijroi/blob/611a220286788ff1447d79343da51cb2bb69a984/ijroi/ijroi.py#L11-L139 |
oscarlazoarjona/fast | fast/angular_momentum.py | perm_j | def perm_j(j1, j2):
r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2]
"""
jmin = abs(j1-j2)
jmax = j1+j2
return [jmin + i for i in range(jmax-jmin+1)] | python | def perm_j(j1, j2):
r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2]
"""
jmin = abs(j1-j2)
jmax = j1+j2
return [jmin + i for i in range(jmax-jmin+1)] | [
"def",
"perm_j",
"(",
"j1",
",",
"j2",
")",
":",
"jmin",
"=",
"abs",
"(",
"j1",
"-",
"j2",
")",
"jmax",
"=",
"j1",
"+",
"j2",
"return",
"[",
"jmin",
"+",
"i",
"for",
"i",
"in",
"range",
"(",
"jmax",
"-",
"jmin",
"+",
"1",
")",
"]"
] | r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2] | [
"r",
"Calculate",
"the",
"allowed",
"total",
"angular",
"momenta",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L31-L43 |
oscarlazoarjona/fast | fast/angular_momentum.py | coupling_matrix_2j | def coupling_matrix_2j(j1, j2):
ur"""For angular momenta $j_1, j_2$ the unitary transformation from the \
uncoupled basis into the $j = j_1 \oplus j_2$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘1 0β€
β’ β₯
β£0 1β¦
>>> L = 1
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘ -β6 β3 β€
β’0 ββββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ -β3 β6 β₯
β’0 0 0 ββββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β’1 0 0 0 0 0β₯
β’ β₯
β’ β3 β6 β₯
β’0 ββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ β6 β3 β₯
β’0 0 0 ββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β£0 0 0 0 0 1β¦
"""
# We calculate the quantum numbers for the uncoupled basis.
M1 = [-j1 + i for i in range(2*j1+1)]
M2 = [-j2 + i for i in range(2*j2+1)]
j1j2nums = [(j1, m1, j2, m2) for m1 in M1 for m2 in M2]
# We calculate the quantum numbers for the coupled basis.
Jper = perm_j(j1, j2)
jmjnums = [(J, MJ-J) for J in Jper for MJ in range(2*J+1)]
# We build the transformation matrix.
U = zeros((2*j1+1)*(2*j2+1))
for ii, numj in enumerate(jmjnums):
j, mj = numj
for jj, numi in enumerate(j1j2nums):
j1, m1, j2, m2 = numi
U[ii, jj] = clebsch_gordan(j1, j2, j, m1, m2, mj)
return U | python | def coupling_matrix_2j(j1, j2):
ur"""For angular momenta $j_1, j_2$ the unitary transformation from the \
uncoupled basis into the $j = j_1 \oplus j_2$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘1 0β€
β’ β₯
β£0 1β¦
>>> L = 1
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘ -β6 β3 β€
β’0 ββββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ -β3 β6 β₯
β’0 0 0 ββββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β’1 0 0 0 0 0β₯
β’ β₯
β’ β3 β6 β₯
β’0 ββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ β6 β3 β₯
β’0 0 0 ββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β£0 0 0 0 0 1β¦
"""
# We calculate the quantum numbers for the uncoupled basis.
M1 = [-j1 + i for i in range(2*j1+1)]
M2 = [-j2 + i for i in range(2*j2+1)]
j1j2nums = [(j1, m1, j2, m2) for m1 in M1 for m2 in M2]
# We calculate the quantum numbers for the coupled basis.
Jper = perm_j(j1, j2)
jmjnums = [(J, MJ-J) for J in Jper for MJ in range(2*J+1)]
# We build the transformation matrix.
U = zeros((2*j1+1)*(2*j2+1))
for ii, numj in enumerate(jmjnums):
j, mj = numj
for jj, numi in enumerate(j1j2nums):
j1, m1, j2, m2 = numi
U[ii, jj] = clebsch_gordan(j1, j2, j, m1, m2, mj)
return U | [
"def",
"coupling_matrix_2j",
"(",
"j1",
",",
"j2",
")",
":",
"# We calculate the quantum numbers for the uncoupled basis.",
"M1",
"=",
"[",
"-",
"j1",
"+",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"j1",
"+",
"1",
")",
"]",
"M2",
"=",
"[",
"-",
"j2",
"+",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"j2",
"+",
"1",
")",
"]",
"j1j2nums",
"=",
"[",
"(",
"j1",
",",
"m1",
",",
"j2",
",",
"m2",
")",
"for",
"m1",
"in",
"M1",
"for",
"m2",
"in",
"M2",
"]",
"# We calculate the quantum numbers for the coupled basis.",
"Jper",
"=",
"perm_j",
"(",
"j1",
",",
"j2",
")",
"jmjnums",
"=",
"[",
"(",
"J",
",",
"MJ",
"-",
"J",
")",
"for",
"J",
"in",
"Jper",
"for",
"MJ",
"in",
"range",
"(",
"2",
"*",
"J",
"+",
"1",
")",
"]",
"# We build the transformation matrix.",
"U",
"=",
"zeros",
"(",
"(",
"2",
"*",
"j1",
"+",
"1",
")",
"*",
"(",
"2",
"*",
"j2",
"+",
"1",
")",
")",
"for",
"ii",
",",
"numj",
"in",
"enumerate",
"(",
"jmjnums",
")",
":",
"j",
",",
"mj",
"=",
"numj",
"for",
"jj",
",",
"numi",
"in",
"enumerate",
"(",
"j1j2nums",
")",
":",
"j1",
",",
"m1",
",",
"j2",
",",
"m2",
"=",
"numi",
"U",
"[",
"ii",
",",
"jj",
"]",
"=",
"clebsch_gordan",
"(",
"j1",
",",
"j2",
",",
"j",
",",
"m1",
",",
"m2",
",",
"mj",
")",
"return",
"U"
] | ur"""For angular momenta $j_1, j_2$ the unitary transformation from the \
uncoupled basis into the $j = j_1 \oplus j_2$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘1 0β€
β’ β₯
β£0 1β¦
>>> L = 1
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
β‘ -β6 β3 β€
β’0 ββββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ -β3 β6 β₯
β’0 0 0 ββββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β’1 0 0 0 0 0β₯
β’ β₯
β’ β3 β6 β₯
β’0 ββ ββ 0 0 0β₯
β’ 3 3 β₯
β’ β₯
β’ β6 β3 β₯
β’0 0 0 ββ ββ 0β₯
β’ 3 3 β₯
β’ β₯
β£0 0 0 0 0 1β¦ | [
"ur",
"For",
"angular",
"momenta",
"$j_1",
"j_2$",
"the",
"unitary",
"transformation",
"from",
"the",
"\\",
"uncoupled",
"basis",
"into",
"the",
"$j",
"=",
"j_1",
"\\",
"oplus",
"j_2$",
"coupled",
"basis",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L61-L113 |
oscarlazoarjona/fast | fast/angular_momentum.py | coupling_matrix_3j | def coupling_matrix_3j(j1, j2, j3):
ur"""For angular momenta $j_1, j_2, j_3$ the unitary transformation from the \
uncoupled basis into the $j = (j_1 \oplus j_2)\oplus j_3$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> II = 3/Integer(2)
>>> pprint(coupling_matrix_3j(L, S, II))
β‘ β3 β€
β’0 -1/2 0 0 ββ 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ -β2 β2 β₯
β’0 0 ββββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ -β3 β₯
β’0 0 0 ββββ 0 0 1/2 0β₯
β’ 2 β₯
β’ β₯
β’1 0 0 0 0 0 0 0β₯
β’ β₯
β’ β3 β₯
β’0 ββ 0 0 1/2 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ β2 β2 β₯
β’0 0 ββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ β3 β₯
β’0 0 0 1/2 0 0 ββ 0β₯
β’ 2 β₯
β’ β₯
β£0 0 0 0 0 0 0 1β¦
"""
idj3 = eye(2*j3+1)
Jper = perm_j(j1, j2)
U_Jj3_list = [coupling_matrix_2j(J, j3) for J in Jper]
size = sum([U_Jj3_list[i].shape[0] for i in range(len(Jper))])
U_Jj3 = zeros(size, size)
ind0 = 0
for i, U_Jj3i in enumerate(U_Jj3_list):
sizeJ = U_Jj3i.shape[0]
indf = ind0 + sizeJ
U_Jj3[ind0: indf, ind0: indf] = U_Jj3_list[i]
ind0 = indf
return U_Jj3*TensorProduct(coupling_matrix_2j(j1, j2), idj3) | python | def coupling_matrix_3j(j1, j2, j3):
ur"""For angular momenta $j_1, j_2, j_3$ the unitary transformation from the \
uncoupled basis into the $j = (j_1 \oplus j_2)\oplus j_3$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> II = 3/Integer(2)
>>> pprint(coupling_matrix_3j(L, S, II))
β‘ β3 β€
β’0 -1/2 0 0 ββ 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ -β2 β2 β₯
β’0 0 ββββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ -β3 β₯
β’0 0 0 ββββ 0 0 1/2 0β₯
β’ 2 β₯
β’ β₯
β’1 0 0 0 0 0 0 0β₯
β’ β₯
β’ β3 β₯
β’0 ββ 0 0 1/2 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ β2 β2 β₯
β’0 0 ββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ β3 β₯
β’0 0 0 1/2 0 0 ββ 0β₯
β’ 2 β₯
β’ β₯
β£0 0 0 0 0 0 0 1β¦
"""
idj3 = eye(2*j3+1)
Jper = perm_j(j1, j2)
U_Jj3_list = [coupling_matrix_2j(J, j3) for J in Jper]
size = sum([U_Jj3_list[i].shape[0] for i in range(len(Jper))])
U_Jj3 = zeros(size, size)
ind0 = 0
for i, U_Jj3i in enumerate(U_Jj3_list):
sizeJ = U_Jj3i.shape[0]
indf = ind0 + sizeJ
U_Jj3[ind0: indf, ind0: indf] = U_Jj3_list[i]
ind0 = indf
return U_Jj3*TensorProduct(coupling_matrix_2j(j1, j2), idj3) | [
"def",
"coupling_matrix_3j",
"(",
"j1",
",",
"j2",
",",
"j3",
")",
":",
"idj3",
"=",
"eye",
"(",
"2",
"*",
"j3",
"+",
"1",
")",
"Jper",
"=",
"perm_j",
"(",
"j1",
",",
"j2",
")",
"U_Jj3_list",
"=",
"[",
"coupling_matrix_2j",
"(",
"J",
",",
"j3",
")",
"for",
"J",
"in",
"Jper",
"]",
"size",
"=",
"sum",
"(",
"[",
"U_Jj3_list",
"[",
"i",
"]",
".",
"shape",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"Jper",
")",
")",
"]",
")",
"U_Jj3",
"=",
"zeros",
"(",
"size",
",",
"size",
")",
"ind0",
"=",
"0",
"for",
"i",
",",
"U_Jj3i",
"in",
"enumerate",
"(",
"U_Jj3_list",
")",
":",
"sizeJ",
"=",
"U_Jj3i",
".",
"shape",
"[",
"0",
"]",
"indf",
"=",
"ind0",
"+",
"sizeJ",
"U_Jj3",
"[",
"ind0",
":",
"indf",
",",
"ind0",
":",
"indf",
"]",
"=",
"U_Jj3_list",
"[",
"i",
"]",
"ind0",
"=",
"indf",
"return",
"U_Jj3",
"*",
"TensorProduct",
"(",
"coupling_matrix_2j",
"(",
"j1",
",",
"j2",
")",
",",
"idj3",
")"
] | ur"""For angular momenta $j_1, j_2, j_3$ the unitary transformation from the \
uncoupled basis into the $j = (j_1 \oplus j_2)\oplus j_3$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> II = 3/Integer(2)
>>> pprint(coupling_matrix_3j(L, S, II))
β‘ β3 β€
β’0 -1/2 0 0 ββ 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ -β2 β2 β₯
β’0 0 ββββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ -β3 β₯
β’0 0 0 ββββ 0 0 1/2 0β₯
β’ 2 β₯
β’ β₯
β’1 0 0 0 0 0 0 0β₯
β’ β₯
β’ β3 β₯
β’0 ββ 0 0 1/2 0 0 0β₯
β’ 2 β₯
β’ β₯
β’ β2 β2 β₯
β’0 0 ββ 0 0 ββ 0 0β₯
β’ 2 2 β₯
β’ β₯
β’ β3 β₯
β’0 0 0 1/2 0 0 ββ 0β₯
β’ 2 β₯
β’ β₯
β£0 0 0 0 0 0 0 1β¦ | [
"ur",
"For",
"angular",
"momenta",
"$j_1",
"j_2",
"j_3$",
"the",
"unitary",
"transformation",
"from",
"the",
"\\",
"uncoupled",
"basis",
"into",
"the",
"$j",
"=",
"(",
"j_1",
"\\",
"oplus",
"j_2",
")",
"\\",
"oplus",
"j_3$",
"coupled",
"basis",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L116-L166 |
oscarlazoarjona/fast | fast/angular_momentum.py | angular_momentum_matrix | def angular_momentum_matrix(J, ind="z"):
ur"""Return the angular momentum operator matrix (divided by hbar) for a\
given J angular momentum.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
OUTPUT:
- matrix forms of angular momentum operators in the basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
>>> from sympy import Integer, pprint
>>> pprint(angular_momentum_matrix(1/Integer(2)))
β‘-1/2 0 β€
β’ β₯
β£ 0 1/2β¦
>>> pprint(angular_momentum_matrix(1/Integer(2), "all"))
β β‘ β
β€ β
β β’ 0 ββ₯ β
ββ‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β
ββ’ β₯, β’ β₯, β’ β₯β
ββ£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β
β β’βββ 0β₯ β
β β£ 2 β¦ β
>>> pprint(angular_momentum_matrix(1, "all"))
ββ‘ β2 β€ β‘ β2β
β
β€ β
ββ’0 ββ 0 β₯ β’ 0 ββββ 0 β₯ β
ββ’ 2 β₯ β’ 2 β₯ β
ββ’ β₯ β’ β₯ β‘-1 0 0β€β
ββ’β2 β2β₯ β’-β2β
β
β2β
β
β₯ β’ β₯β
ββ’ββ 0 βββ₯, β’ββββββ 0 βββββ₯, β’0 0 0β₯β
ββ’2 2 β₯ β’ 2 2 β₯ β’ β₯β
ββ’ β₯ β’ β₯ β£0 0 1β¦β
ββ’ β2 β₯ β’ -β2β
β
β₯ β
ββ’0 ββ 0 β₯ β’ 0 ββββββ 0 β₯ β
ββ£ 2 β¦ β£ 2 β¦ β
"""
MJ = [-J+i for i in range(2*J+1)]
if ind == "x":
JX = Matrix([[sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
for mj in MJ] for mi in MJ])
JX += Matrix([[sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
for mj in MJ] for mi in MJ])
return JX
elif ind == "y":
JY = Matrix([[-I*sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
for mj in MJ] for mi in MJ])
JY += Matrix([[+I*sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
for mj in MJ] for mi in MJ])
return JY
elif ind == "z":
JZ = Matrix([[mi*KroneckerDelta(mi, mj) for mj in MJ] for mi in MJ])
return JZ
elif ind == "all":
JX = angular_momentum_matrix(J, "x")
JY = angular_momentum_matrix(J, "y")
JZ = angular_momentum_matrix(J, "z")
return JX, JY, JZ | python | def angular_momentum_matrix(J, ind="z"):
ur"""Return the angular momentum operator matrix (divided by hbar) for a\
given J angular momentum.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
OUTPUT:
- matrix forms of angular momentum operators in the basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
>>> from sympy import Integer, pprint
>>> pprint(angular_momentum_matrix(1/Integer(2)))
β‘-1/2 0 β€
β’ β₯
β£ 0 1/2β¦
>>> pprint(angular_momentum_matrix(1/Integer(2), "all"))
β β‘ β
β€ β
β β’ 0 ββ₯ β
ββ‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β
ββ’ β₯, β’ β₯, β’ β₯β
ββ£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β
β β’βββ 0β₯ β
β β£ 2 β¦ β
>>> pprint(angular_momentum_matrix(1, "all"))
ββ‘ β2 β€ β‘ β2β
β
β€ β
ββ’0 ββ 0 β₯ β’ 0 ββββ 0 β₯ β
ββ’ 2 β₯ β’ 2 β₯ β
ββ’ β₯ β’ β₯ β‘-1 0 0β€β
ββ’β2 β2β₯ β’-β2β
β
β2β
β
β₯ β’ β₯β
ββ’ββ 0 βββ₯, β’ββββββ 0 βββββ₯, β’0 0 0β₯β
ββ’2 2 β₯ β’ 2 2 β₯ β’ β₯β
ββ’ β₯ β’ β₯ β£0 0 1β¦β
ββ’ β2 β₯ β’ -β2β
β
β₯ β
ββ’0 ββ 0 β₯ β’ 0 ββββββ 0 β₯ β
ββ£ 2 β¦ β£ 2 β¦ β
"""
MJ = [-J+i for i in range(2*J+1)]
if ind == "x":
JX = Matrix([[sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
for mj in MJ] for mi in MJ])
JX += Matrix([[sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
for mj in MJ] for mi in MJ])
return JX
elif ind == "y":
JY = Matrix([[-I*sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
for mj in MJ] for mi in MJ])
JY += Matrix([[+I*sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
for mj in MJ] for mi in MJ])
return JY
elif ind == "z":
JZ = Matrix([[mi*KroneckerDelta(mi, mj) for mj in MJ] for mi in MJ])
return JZ
elif ind == "all":
JX = angular_momentum_matrix(J, "x")
JY = angular_momentum_matrix(J, "y")
JZ = angular_momentum_matrix(J, "z")
return JX, JY, JZ | [
"def",
"angular_momentum_matrix",
"(",
"J",
",",
"ind",
"=",
"\"z\"",
")",
":",
"MJ",
"=",
"[",
"-",
"J",
"+",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"J",
"+",
"1",
")",
"]",
"if",
"ind",
"==",
"\"x\"",
":",
"JX",
"=",
"Matrix",
"(",
"[",
"[",
"sqrt",
"(",
"(",
"J",
"-",
"mj",
")",
"*",
"(",
"J",
"+",
"mj",
"+",
"1",
")",
")",
"/",
"2",
"*",
"KroneckerDelta",
"(",
"mi",
"-",
"1",
",",
"mj",
")",
"for",
"mj",
"in",
"MJ",
"]",
"for",
"mi",
"in",
"MJ",
"]",
")",
"JX",
"+=",
"Matrix",
"(",
"[",
"[",
"sqrt",
"(",
"(",
"J",
"+",
"mj",
")",
"*",
"(",
"J",
"-",
"mj",
"+",
"1",
")",
")",
"/",
"2",
"*",
"KroneckerDelta",
"(",
"mi",
"+",
"1",
",",
"mj",
")",
"for",
"mj",
"in",
"MJ",
"]",
"for",
"mi",
"in",
"MJ",
"]",
")",
"return",
"JX",
"elif",
"ind",
"==",
"\"y\"",
":",
"JY",
"=",
"Matrix",
"(",
"[",
"[",
"-",
"I",
"*",
"sqrt",
"(",
"(",
"J",
"-",
"mj",
")",
"*",
"(",
"J",
"+",
"mj",
"+",
"1",
")",
")",
"/",
"2",
"*",
"KroneckerDelta",
"(",
"mi",
"-",
"1",
",",
"mj",
")",
"for",
"mj",
"in",
"MJ",
"]",
"for",
"mi",
"in",
"MJ",
"]",
")",
"JY",
"+=",
"Matrix",
"(",
"[",
"[",
"+",
"I",
"*",
"sqrt",
"(",
"(",
"J",
"+",
"mj",
")",
"*",
"(",
"J",
"-",
"mj",
"+",
"1",
")",
")",
"/",
"2",
"*",
"KroneckerDelta",
"(",
"mi",
"+",
"1",
",",
"mj",
")",
"for",
"mj",
"in",
"MJ",
"]",
"for",
"mi",
"in",
"MJ",
"]",
")",
"return",
"JY",
"elif",
"ind",
"==",
"\"z\"",
":",
"JZ",
"=",
"Matrix",
"(",
"[",
"[",
"mi",
"*",
"KroneckerDelta",
"(",
"mi",
",",
"mj",
")",
"for",
"mj",
"in",
"MJ",
"]",
"for",
"mi",
"in",
"MJ",
"]",
")",
"return",
"JZ",
"elif",
"ind",
"==",
"\"all\"",
":",
"JX",
"=",
"angular_momentum_matrix",
"(",
"J",
",",
"\"x\"",
")",
"JY",
"=",
"angular_momentum_matrix",
"(",
"J",
",",
"\"y\"",
")",
"JZ",
"=",
"angular_momentum_matrix",
"(",
"J",
",",
"\"z\"",
")",
"return",
"JX",
",",
"JY",
",",
"JZ"
] | ur"""Return the angular momentum operator matrix (divided by hbar) for a\
given J angular momentum.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
OUTPUT:
- matrix forms of angular momentum operators in the basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
>>> from sympy import Integer, pprint
>>> pprint(angular_momentum_matrix(1/Integer(2)))
β‘-1/2 0 β€
β’ β₯
β£ 0 1/2β¦
>>> pprint(angular_momentum_matrix(1/Integer(2), "all"))
β β‘ β
β€ β
β β’ 0 ββ₯ β
ββ‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β
ββ’ β₯, β’ β₯, β’ β₯β
ββ£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β
β β’βββ 0β₯ β
β β£ 2 β¦ β
>>> pprint(angular_momentum_matrix(1, "all"))
ββ‘ β2 β€ β‘ β2β
β
β€ β
ββ’0 ββ 0 β₯ β’ 0 ββββ 0 β₯ β
ββ’ 2 β₯ β’ 2 β₯ β
ββ’ β₯ β’ β₯ β‘-1 0 0β€β
ββ’β2 β2β₯ β’-β2β
β
β2β
β
β₯ β’ β₯β
ββ’ββ 0 βββ₯, β’ββββββ 0 βββββ₯, β’0 0 0β₯β
ββ’2 2 β₯ β’ 2 2 β₯ β’ β₯β
ββ’ β₯ β’ β₯ β£0 0 1β¦β
ββ’ β2 β₯ β’ -β2β
β
β₯ β
ββ’0 ββ 0 β₯ β’ 0 ββββββ 0 β₯ β
ββ£ 2 β¦ β£ 2 β¦ β | [
"ur",
"Return",
"the",
"angular",
"momentum",
"operator",
"matrix",
"(",
"divided",
"by",
"hbar",
")",
"for",
"a",
"\\",
"given",
"J",
"angular",
"momentum",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L169-L233 |
oscarlazoarjona/fast | fast/angular_momentum.py | orbital_spin_nuclear_matrices | def orbital_spin_nuclear_matrices(L, S, II, ind="z"):
ur"""Return the matrix representation of the orbita, electron-spin, and \
nuclear-spin angular momentum operators \
:math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
>>> from sympy import Integer, pprint
>>> half = 1/Integer(2)
>>> Lz, Sz, Iz = orbital_spin_nuclear_matrices(0, half, 3*half)
>>> pprint(Lz)
β‘0 0 0 0 0 0 0 0β€
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β£0 0 0 0 0 0 0 0β¦
>>> pprint(Sz)
β‘ β3 β€
β’1/4 0 0 0 ββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 1/2 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 -1/4 0 0 0 ββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -1/2 0 0 0 0 β₯
β’ β₯
β’β3 β₯
β’ββ 0 0 0 -1/4 0 0 0 β₯
β’4 β₯
β’ β₯
β’ 0 1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 ββ 0 0 0 1/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 1/2β¦
>>> pprint(Iz)
β‘ -β3 β€
β’-5/4 0 0 0 ββββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 -1/2 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 5/4 0 0 0 ββββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -3/2 0 0 0 0 β₯
β’ β₯
β’-β3 β₯
β’ββββ 0 0 0 -3/4 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 -1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 ββββ 0 0 0 3/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 3/2β¦
>>> Lvec, Svec, Ivec = orbital_spin_nuclear_matrices(0, half, 0, "all")
>>> pprint(Lvec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦
>>> pprint(Svec)
β‘ β‘ β
β€ β€
β’ β’ 0 ββ₯ β₯
β’β‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β₯
β’β’ β₯, β’ β₯, β’ β₯β₯
β’β£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β₯
β’ β’βββ 0β₯ β₯
β£ β£ 2 β¦ β¦
>>> pprint(Ivec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦
"""
if ind == "all":
LSIx = orbital_spin_nuclear_matrices(L, S, II, "x")
LSIy = orbital_spin_nuclear_matrices(L, S, II, "y")
LSIz = orbital_spin_nuclear_matrices(L, S, II, "z")
return [[LSIx[i], LSIy[i], LSIz[i]] for i in range(3)]
L0 = eye(2*L+1)
S0 = eye(2*S+1)
I0 = eye(2*II+1)
Lind = angular_momentum_matrix(L, ind=ind)
Sind = angular_momentum_matrix(S, ind=ind)
Iind = angular_momentum_matrix(II, ind=ind)
Lind = TensorProduct(TensorProduct(Lind, S0), I0)
Sind = TensorProduct(TensorProduct(L0, Sind), I0)
Iind = TensorProduct(TensorProduct(L0, S0), Iind)
U_LSI = coupling_matrix_3j(L, S, II)
Lind = U_LSI*Lind*U_LSI.adjoint()
Sind = U_LSI*Sind*U_LSI.adjoint()
Iind = U_LSI*Iind*U_LSI.adjoint()
return Lind, Sind, Iind | python | def orbital_spin_nuclear_matrices(L, S, II, ind="z"):
ur"""Return the matrix representation of the orbita, electron-spin, and \
nuclear-spin angular momentum operators \
:math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
>>> from sympy import Integer, pprint
>>> half = 1/Integer(2)
>>> Lz, Sz, Iz = orbital_spin_nuclear_matrices(0, half, 3*half)
>>> pprint(Lz)
β‘0 0 0 0 0 0 0 0β€
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β£0 0 0 0 0 0 0 0β¦
>>> pprint(Sz)
β‘ β3 β€
β’1/4 0 0 0 ββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 1/2 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 -1/4 0 0 0 ββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -1/2 0 0 0 0 β₯
β’ β₯
β’β3 β₯
β’ββ 0 0 0 -1/4 0 0 0 β₯
β’4 β₯
β’ β₯
β’ 0 1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 ββ 0 0 0 1/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 1/2β¦
>>> pprint(Iz)
β‘ -β3 β€
β’-5/4 0 0 0 ββββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 -1/2 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 5/4 0 0 0 ββββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -3/2 0 0 0 0 β₯
β’ β₯
β’-β3 β₯
β’ββββ 0 0 0 -3/4 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 -1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 ββββ 0 0 0 3/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 3/2β¦
>>> Lvec, Svec, Ivec = orbital_spin_nuclear_matrices(0, half, 0, "all")
>>> pprint(Lvec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦
>>> pprint(Svec)
β‘ β‘ β
β€ β€
β’ β’ 0 ββ₯ β₯
β’β‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β₯
β’β’ β₯, β’ β₯, β’ β₯β₯
β’β£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β₯
β’ β’βββ 0β₯ β₯
β£ β£ 2 β¦ β¦
>>> pprint(Ivec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦
"""
if ind == "all":
LSIx = orbital_spin_nuclear_matrices(L, S, II, "x")
LSIy = orbital_spin_nuclear_matrices(L, S, II, "y")
LSIz = orbital_spin_nuclear_matrices(L, S, II, "z")
return [[LSIx[i], LSIy[i], LSIz[i]] for i in range(3)]
L0 = eye(2*L+1)
S0 = eye(2*S+1)
I0 = eye(2*II+1)
Lind = angular_momentum_matrix(L, ind=ind)
Sind = angular_momentum_matrix(S, ind=ind)
Iind = angular_momentum_matrix(II, ind=ind)
Lind = TensorProduct(TensorProduct(Lind, S0), I0)
Sind = TensorProduct(TensorProduct(L0, Sind), I0)
Iind = TensorProduct(TensorProduct(L0, S0), Iind)
U_LSI = coupling_matrix_3j(L, S, II)
Lind = U_LSI*Lind*U_LSI.adjoint()
Sind = U_LSI*Sind*U_LSI.adjoint()
Iind = U_LSI*Iind*U_LSI.adjoint()
return Lind, Sind, Iind | [
"def",
"orbital_spin_nuclear_matrices",
"(",
"L",
",",
"S",
",",
"II",
",",
"ind",
"=",
"\"z\"",
")",
":",
"if",
"ind",
"==",
"\"all\"",
":",
"LSIx",
"=",
"orbital_spin_nuclear_matrices",
"(",
"L",
",",
"S",
",",
"II",
",",
"\"x\"",
")",
"LSIy",
"=",
"orbital_spin_nuclear_matrices",
"(",
"L",
",",
"S",
",",
"II",
",",
"\"y\"",
")",
"LSIz",
"=",
"orbital_spin_nuclear_matrices",
"(",
"L",
",",
"S",
",",
"II",
",",
"\"z\"",
")",
"return",
"[",
"[",
"LSIx",
"[",
"i",
"]",
",",
"LSIy",
"[",
"i",
"]",
",",
"LSIz",
"[",
"i",
"]",
"]",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
"L0",
"=",
"eye",
"(",
"2",
"*",
"L",
"+",
"1",
")",
"S0",
"=",
"eye",
"(",
"2",
"*",
"S",
"+",
"1",
")",
"I0",
"=",
"eye",
"(",
"2",
"*",
"II",
"+",
"1",
")",
"Lind",
"=",
"angular_momentum_matrix",
"(",
"L",
",",
"ind",
"=",
"ind",
")",
"Sind",
"=",
"angular_momentum_matrix",
"(",
"S",
",",
"ind",
"=",
"ind",
")",
"Iind",
"=",
"angular_momentum_matrix",
"(",
"II",
",",
"ind",
"=",
"ind",
")",
"Lind",
"=",
"TensorProduct",
"(",
"TensorProduct",
"(",
"Lind",
",",
"S0",
")",
",",
"I0",
")",
"Sind",
"=",
"TensorProduct",
"(",
"TensorProduct",
"(",
"L0",
",",
"Sind",
")",
",",
"I0",
")",
"Iind",
"=",
"TensorProduct",
"(",
"TensorProduct",
"(",
"L0",
",",
"S0",
")",
",",
"Iind",
")",
"U_LSI",
"=",
"coupling_matrix_3j",
"(",
"L",
",",
"S",
",",
"II",
")",
"Lind",
"=",
"U_LSI",
"*",
"Lind",
"*",
"U_LSI",
".",
"adjoint",
"(",
")",
"Sind",
"=",
"U_LSI",
"*",
"Sind",
"*",
"U_LSI",
".",
"adjoint",
"(",
")",
"Iind",
"=",
"U_LSI",
"*",
"Iind",
"*",
"U_LSI",
".",
"adjoint",
"(",
")",
"return",
"Lind",
",",
"Sind",
",",
"Iind"
] | ur"""Return the matrix representation of the orbita, electron-spin, and \
nuclear-spin angular momentum operators \
:math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \
:math:`[|J, -J\rangle, \cdot, |J, J\rangle]`.
INPUT:
- ``ind`` - A string ("x", "y", "z", "all") indicating which direction \
to calculate, or to return them all as :math:`(J_x, J_y, J_z)`.
>>> from sympy import Integer, pprint
>>> half = 1/Integer(2)
>>> Lz, Sz, Iz = orbital_spin_nuclear_matrices(0, half, 3*half)
>>> pprint(Lz)
β‘0 0 0 0 0 0 0 0β€
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β’0 0 0 0 0 0 0 0β₯
β’ β₯
β£0 0 0 0 0 0 0 0β¦
>>> pprint(Sz)
β‘ β3 β€
β’1/4 0 0 0 ββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 1/2 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 -1/4 0 0 0 ββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -1/2 0 0 0 0 β₯
β’ β₯
β’β3 β₯
β’ββ 0 0 0 -1/4 0 0 0 β₯
β’4 β₯
β’ β₯
β’ 0 1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ β3 β₯
β’ 0 0 ββ 0 0 0 1/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 1/2β¦
>>> pprint(Iz)
β‘ -β3 β€
β’-5/4 0 0 0 ββββ 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 0 0 -1/2 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 5/4 0 0 0 ββββ 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 0 0 -3/2 0 0 0 0 β₯
β’ β₯
β’-β3 β₯
β’ββββ 0 0 0 -3/4 0 0 0 β₯
β’ 4 β₯
β’ β₯
β’ 0 -1/2 0 0 0 0 0 0 β₯
β’ β₯
β’ -β3 β₯
β’ 0 0 ββββ 0 0 0 3/4 0 β₯
β’ 4 β₯
β’ β₯
β£ 0 0 0 0 0 0 0 3/2β¦
>>> Lvec, Svec, Ivec = orbital_spin_nuclear_matrices(0, half, 0, "all")
>>> pprint(Lvec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦
>>> pprint(Svec)
β‘ β‘ β
β€ β€
β’ β’ 0 ββ₯ β₯
β’β‘ 0 1/2β€ β’ 2β₯ β‘-1/2 0 β€β₯
β’β’ β₯, β’ β₯, β’ β₯β₯
β’β£1/2 0 β¦ β’-β
β₯ β£ 0 1/2β¦β₯
β’ β’βββ 0β₯ β₯
β£ β£ 2 β¦ β¦
>>> pprint(Ivec)
β‘β‘0 0β€ β‘0 0β€ β‘0 0β€β€
β’β’ β₯, β’ β₯, β’ β₯β₯
β£β£0 0β¦ β£0 0β¦ β£0 0β¦β¦ | [
"ur",
"Return",
"the",
"matrix",
"representation",
"of",
"the",
"orbita",
"electron",
"-",
"spin",
"and",
"\\",
"nuclear",
"-",
"spin",
"angular",
"momentum",
"operators",
"\\",
":",
"math",
":",
"\\",
"hat",
"{",
"\\",
"vec",
"{",
"L",
"}}",
"\\",
"hat",
"{",
"\\",
"vec",
"{",
"L",
"}}",
"\\",
"hat",
"{",
"\\",
"vec",
"{",
"L",
"}}",
"in",
"the",
"coupled",
"basis",
"\\",
":",
"math",
":",
"[",
"|J",
"-",
"J",
"\\",
"rangle",
"\\",
"cdot",
"|J",
"J",
"\\",
"rangle",
"]",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L236-L362 |
oscarlazoarjona/fast | fast/angular_momentum.py | spherical_tensor | def spherical_tensor(Ji, Jj, K, Q):
ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
β‘-β2 β€
β’ββββ 0 0 β₯
β’ 2 β₯
β’ β₯
β’ 0 0 0 β₯
β’ β₯
β’ β2β₯
β’ 0 0 βββ₯
β£ 2 β¦
>>> pprint(spherical_tensor(1, 2, 1, -1))
β‘ β10 β€
β’0 0 βββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30 β₯
β’0 0 0 βββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β₯
β’0 0 0 0 ββββ₯
β£ 5 β¦
"""
keti = {(Ji, Mi): Matrix([KroneckerDelta(i, j)
for j in range(2*Ji+1)])
for i, Mi in enumerate(perm_m(Ji))}
braj = {(Jj, Mj): Matrix([KroneckerDelta(i, j)
for j in range(2*Jj+1)]).adjoint()
for i, Mj in enumerate(perm_m(Jj))}
if K not in perm_j(Ji, Jj):
raise ValueError("K value is not allowed.")
if Q not in perm_m(K):
raise ValueError("Q value is not allowed.")
Ni = 2*Ji+1
Nj = 2*Jj+1
T = zeros(Ni, Nj)
for i, Mi in enumerate(perm_m(Ji)):
for j, Mj in enumerate(perm_m(Jj)):
T += (-1)**(Jj-Mj)*clebsch_gordan(Ji, Jj, K, Mi, -Mj, Q) * \
keti[(Ji, Mi)]*braj[(Jj, Mj)]
return T | python | def spherical_tensor(Ji, Jj, K, Q):
ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
β‘-β2 β€
β’ββββ 0 0 β₯
β’ 2 β₯
β’ β₯
β’ 0 0 0 β₯
β’ β₯
β’ β2β₯
β’ 0 0 βββ₯
β£ 2 β¦
>>> pprint(spherical_tensor(1, 2, 1, -1))
β‘ β10 β€
β’0 0 βββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30 β₯
β’0 0 0 βββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β₯
β’0 0 0 0 ββββ₯
β£ 5 β¦
"""
keti = {(Ji, Mi): Matrix([KroneckerDelta(i, j)
for j in range(2*Ji+1)])
for i, Mi in enumerate(perm_m(Ji))}
braj = {(Jj, Mj): Matrix([KroneckerDelta(i, j)
for j in range(2*Jj+1)]).adjoint()
for i, Mj in enumerate(perm_m(Jj))}
if K not in perm_j(Ji, Jj):
raise ValueError("K value is not allowed.")
if Q not in perm_m(K):
raise ValueError("Q value is not allowed.")
Ni = 2*Ji+1
Nj = 2*Jj+1
T = zeros(Ni, Nj)
for i, Mi in enumerate(perm_m(Ji)):
for j, Mj in enumerate(perm_m(Jj)):
T += (-1)**(Jj-Mj)*clebsch_gordan(Ji, Jj, K, Mi, -Mj, Q) * \
keti[(Ji, Mi)]*braj[(Jj, Mj)]
return T | [
"def",
"spherical_tensor",
"(",
"Ji",
",",
"Jj",
",",
"K",
",",
"Q",
")",
":",
"keti",
"=",
"{",
"(",
"Ji",
",",
"Mi",
")",
":",
"Matrix",
"(",
"[",
"KroneckerDelta",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"2",
"*",
"Ji",
"+",
"1",
")",
"]",
")",
"for",
"i",
",",
"Mi",
"in",
"enumerate",
"(",
"perm_m",
"(",
"Ji",
")",
")",
"}",
"braj",
"=",
"{",
"(",
"Jj",
",",
"Mj",
")",
":",
"Matrix",
"(",
"[",
"KroneckerDelta",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"2",
"*",
"Jj",
"+",
"1",
")",
"]",
")",
".",
"adjoint",
"(",
")",
"for",
"i",
",",
"Mj",
"in",
"enumerate",
"(",
"perm_m",
"(",
"Jj",
")",
")",
"}",
"if",
"K",
"not",
"in",
"perm_j",
"(",
"Ji",
",",
"Jj",
")",
":",
"raise",
"ValueError",
"(",
"\"K value is not allowed.\"",
")",
"if",
"Q",
"not",
"in",
"perm_m",
"(",
"K",
")",
":",
"raise",
"ValueError",
"(",
"\"Q value is not allowed.\"",
")",
"Ni",
"=",
"2",
"*",
"Ji",
"+",
"1",
"Nj",
"=",
"2",
"*",
"Jj",
"+",
"1",
"T",
"=",
"zeros",
"(",
"Ni",
",",
"Nj",
")",
"for",
"i",
",",
"Mi",
"in",
"enumerate",
"(",
"perm_m",
"(",
"Ji",
")",
")",
":",
"for",
"j",
",",
"Mj",
"in",
"enumerate",
"(",
"perm_m",
"(",
"Jj",
")",
")",
":",
"T",
"+=",
"(",
"-",
"1",
")",
"**",
"(",
"Jj",
"-",
"Mj",
")",
"*",
"clebsch_gordan",
"(",
"Ji",
",",
"Jj",
",",
"K",
",",
"Mi",
",",
"-",
"Mj",
",",
"Q",
")",
"*",
"keti",
"[",
"(",
"Ji",
",",
"Mi",
")",
"]",
"*",
"braj",
"[",
"(",
"Jj",
",",
"Mj",
")",
"]",
"return",
"T"
] | ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
β‘-β2 β€
β’ββββ 0 0 β₯
β’ 2 β₯
β’ β₯
β’ 0 0 0 β₯
β’ β₯
β’ β2β₯
β’ 0 0 βββ₯
β£ 2 β¦
>>> pprint(spherical_tensor(1, 2, 1, -1))
β‘ β10 β€
β’0 0 βββ 0 0 β₯
β’ 10 β₯
β’ β₯
β’ β30 β₯
β’0 0 0 βββ 0 β₯
β’ 10 β₯
β’ β₯
β’ β15β₯
β’0 0 0 0 ββββ₯
β£ 5 β¦ | [
"ur",
"Return",
"a",
"matrix",
"representation",
"of",
"the",
"spherical",
"tensor",
"with",
"quantum",
"numbers",
"$J_i",
"J_j",
"K",
"Q$",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L365-L416 |
oscarlazoarjona/fast | fast/angular_momentum.py | wigner_d_small | def wigner_d_small(J, beta):
u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
β‘ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β€
β’ cos βββ β2β
sinββββ
cosβββ sin βββ β₯
β’ β2β β2β β2β β2β β₯
β’ β₯
β’ βΞ²β βΞ²β 2βΞ²β 2βΞ²β βΞ²β βΞ²ββ₯
β’-β2β
sinββββ
cosβββ - sin βββ + cos βββ β2β
sinββββ
cosββββ₯
β’ β2β β2β β2β β2β β2β β2β β₯
β’ β₯
β’ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β₯
β’ sin βββ -β2β
sinββββ
cosβββ cos βββ β₯
β£ β2β β2β β2β β2β β¦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]])
"""
def prod(x):
p = 1
for i, xi in enumerate(x): p = p*xi
return p
M = [J-i for i in range(2*J+1)]
d = []
for Mi in M:
row = []
for Mj in M:
# We get the maximum and minimum value of sigma.
sigmamax = max([-Mi-Mj, J-Mj])
sigmamin = min([0, J-Mi])
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
factorial(J+Mj)/factorial(J-Mj))
terms = [[(-1)**(J-Mi-s),
binomial(J+Mj, J-Mi-s),
binomial(J-Mj, s),
cos(beta/2)**(2*s+Mi+Mj),
sin(beta/2)**(2*J-2*s-Mj-Mi)]
for s in range(sigmamin, sigmamax+1)]
terms = [prod(term) if 0 not in term else 0 for term in terms]
dij = dij*sum(terms)
row += [dij]
d += [row]
return Matrix(d) | python | def wigner_d_small(J, beta):
u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
β‘ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β€
β’ cos βββ β2β
sinββββ
cosβββ sin βββ β₯
β’ β2β β2β β2β β2β β₯
β’ β₯
β’ βΞ²β βΞ²β 2βΞ²β 2βΞ²β βΞ²β βΞ²ββ₯
β’-β2β
sinββββ
cosβββ - sin βββ + cos βββ β2β
sinββββ
cosββββ₯
β’ β2β β2β β2β β2β β2β β2β β₯
β’ β₯
β’ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β₯
β’ sin βββ -β2β
sinββββ
cosβββ cos βββ β₯
β£ β2β β2β β2β β2β β¦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]])
"""
def prod(x):
p = 1
for i, xi in enumerate(x): p = p*xi
return p
M = [J-i for i in range(2*J+1)]
d = []
for Mi in M:
row = []
for Mj in M:
# We get the maximum and minimum value of sigma.
sigmamax = max([-Mi-Mj, J-Mj])
sigmamin = min([0, J-Mi])
dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
factorial(J+Mj)/factorial(J-Mj))
terms = [[(-1)**(J-Mi-s),
binomial(J+Mj, J-Mi-s),
binomial(J-Mj, s),
cos(beta/2)**(2*s+Mi+Mj),
sin(beta/2)**(2*J-2*s-Mj-Mi)]
for s in range(sigmamin, sigmamax+1)]
terms = [prod(term) if 0 not in term else 0 for term in terms]
dij = dij*sum(terms)
row += [dij]
d += [row]
return Matrix(d) | [
"def",
"wigner_d_small",
"(",
"J",
",",
"beta",
")",
":",
"def",
"prod",
"(",
"x",
")",
":",
"p",
"=",
"1",
"for",
"i",
",",
"xi",
"in",
"enumerate",
"(",
"x",
")",
":",
"p",
"=",
"p",
"*",
"xi",
"return",
"p",
"M",
"=",
"[",
"J",
"-",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"J",
"+",
"1",
")",
"]",
"d",
"=",
"[",
"]",
"for",
"Mi",
"in",
"M",
":",
"row",
"=",
"[",
"]",
"for",
"Mj",
"in",
"M",
":",
"# We get the maximum and minimum value of sigma.",
"sigmamax",
"=",
"max",
"(",
"[",
"-",
"Mi",
"-",
"Mj",
",",
"J",
"-",
"Mj",
"]",
")",
"sigmamin",
"=",
"min",
"(",
"[",
"0",
",",
"J",
"-",
"Mi",
"]",
")",
"dij",
"=",
"sqrt",
"(",
"factorial",
"(",
"J",
"+",
"Mi",
")",
"*",
"factorial",
"(",
"J",
"-",
"Mi",
")",
"/",
"factorial",
"(",
"J",
"+",
"Mj",
")",
"/",
"factorial",
"(",
"J",
"-",
"Mj",
")",
")",
"terms",
"=",
"[",
"[",
"(",
"-",
"1",
")",
"**",
"(",
"J",
"-",
"Mi",
"-",
"s",
")",
",",
"binomial",
"(",
"J",
"+",
"Mj",
",",
"J",
"-",
"Mi",
"-",
"s",
")",
",",
"binomial",
"(",
"J",
"-",
"Mj",
",",
"s",
")",
",",
"cos",
"(",
"beta",
"/",
"2",
")",
"**",
"(",
"2",
"*",
"s",
"+",
"Mi",
"+",
"Mj",
")",
",",
"sin",
"(",
"beta",
"/",
"2",
")",
"**",
"(",
"2",
"*",
"J",
"-",
"2",
"*",
"s",
"-",
"Mj",
"-",
"Mi",
")",
"]",
"for",
"s",
"in",
"range",
"(",
"sigmamin",
",",
"sigmamax",
"+",
"1",
")",
"]",
"terms",
"=",
"[",
"prod",
"(",
"term",
")",
"if",
"0",
"not",
"in",
"term",
"else",
"0",
"for",
"term",
"in",
"terms",
"]",
"dij",
"=",
"dij",
"*",
"sum",
"(",
"terms",
")",
"row",
"+=",
"[",
"dij",
"]",
"d",
"+=",
"[",
"row",
"]",
"return",
"Matrix",
"(",
"d",
")"
] | u"""Return the small Wigner d matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.15.
Some examples form [Edmonds74]_:
>>> from sympy import Integer, symbols, pi
>>> half = 1/Integer(2)
>>> beta = symbols("beta", real=True)
>>> wigner_d_small(half, beta)
Matrix([
[ cos(beta/2), sin(beta/2)],
[-sin(beta/2), cos(beta/2)]])
>>> from sympy import pprint
>>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
β‘ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β€
β’ cos βββ β2β
sinββββ
cosβββ sin βββ β₯
β’ β2β β2β β2β β2β β₯
β’ β₯
β’ βΞ²β βΞ²β 2βΞ²β 2βΞ²β βΞ²β βΞ²ββ₯
β’-β2β
sinββββ
cosβββ - sin βββ + cos βββ β2β
sinββββ
cosββββ₯
β’ β2β β2β β2β β2β β2β β2β β₯
β’ β₯
β’ 2βΞ²β βΞ²β βΞ²β 2βΞ²β β₯
β’ sin βββ -β2β
sinββββ
cosβββ cos βββ β₯
β£ β2β β2β β2β β2β β¦
From table 4 in [Edmonds74]_
>>> wigner_d_small(half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/2, sqrt(2)/2],
[-sqrt(2)/2, sqrt(2)/2]])
>>> wigner_d_small(2*half, beta).subs({beta:pi/2})
Matrix([
[ 1/2, sqrt(2)/2, 1/2],
[-sqrt(2)/2, 0, sqrt(2)/2],
[ 1/2, -sqrt(2)/2, 1/2]])
>>> wigner_d_small(3*half, beta).subs({beta:pi/2})
Matrix([
[ sqrt(2)/4, sqrt(6)/4, sqrt(6)/4, sqrt(2)/4],
[-sqrt(6)/4, -sqrt(2)/4, sqrt(2)/4, sqrt(6)/4],
[ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
[-sqrt(2)/4, sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])
>>> wigner_d_small(4*half, beta).subs({beta:pi/2})
Matrix([
[ 1/4, 1/2, sqrt(6)/4, 1/2, 1/4],
[ -1/2, -1/2, 0, 1/2, 1/2],
[sqrt(6)/4, 0, -1/2, 0, sqrt(6)/4],
[ -1/2, 1/2, 0, -1/2, 1/2],
[ 1/4, -1/2, sqrt(6)/4, -1/2, 1/4]]) | [
"u",
"Return",
"the",
"small",
"Wigner",
"d",
"matrix",
"for",
"angular",
"momentum",
"J",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L419-L507 |
oscarlazoarjona/fast | fast/angular_momentum.py | wigner_d | def wigner_d(J, alpha, beta, gamma):
u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
β‘ β
β
Ξ± β
β
Ξ³ β
β
Ξ± -β
β
Ξ³ β€
β’ βββ βββ βββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²β β₯
β’ β― β
β― β
cosβββ β― β
β― β
sinβββ β₯
β’ β2β β2β β₯
β’ β₯
β’ -β
β
Ξ± β
β
Ξ³ -β
β
Ξ± -β
β
Ξ³ β₯
β’ βββββ βββ βββββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²ββ₯
β’-β― β
β― β
sinβββ β― β
β― β
cosββββ₯
β£ β2β β2β β¦
"""
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return Matrix(D) | python | def wigner_d(J, alpha, beta, gamma):
u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
β‘ β
β
Ξ± β
β
Ξ³ β
β
Ξ± -β
β
Ξ³ β€
β’ βββ βββ βββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²β β₯
β’ β― β
β― β
cosβββ β― β
β― β
sinβββ β₯
β’ β2β β2β β₯
β’ β₯
β’ -β
β
Ξ± β
β
Ξ³ -β
β
Ξ± -β
β
Ξ³ β₯
β’ βββββ βββ βββββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²ββ₯
β’-β― β
β― β
sinβββ β― β
β― β
cosββββ₯
β£ β2β β2β β¦
"""
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return Matrix(D) | [
"def",
"wigner_d",
"(",
"J",
",",
"alpha",
",",
"beta",
",",
"gamma",
")",
":",
"d",
"=",
"wigner_d_small",
"(",
"J",
",",
"beta",
")",
"M",
"=",
"[",
"J",
"-",
"i",
"for",
"i",
"in",
"range",
"(",
"2",
"*",
"J",
"+",
"1",
")",
"]",
"D",
"=",
"[",
"[",
"exp",
"(",
"I",
"*",
"Mi",
"*",
"alpha",
")",
"*",
"d",
"[",
"i",
",",
"j",
"]",
"*",
"exp",
"(",
"I",
"*",
"Mj",
"*",
"gamma",
")",
"for",
"j",
",",
"Mj",
"in",
"enumerate",
"(",
"M",
")",
"]",
"for",
"i",
",",
"Mi",
"in",
"enumerate",
"(",
"M",
")",
"]",
"return",
"Matrix",
"(",
"D",
")"
] | u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
β‘ β
β
Ξ± β
β
Ξ³ β
β
Ξ± -β
β
Ξ³ β€
β’ βββ βββ βββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²β β₯
β’ β― β
β― β
cosβββ β― β
β― β
sinβββ β₯
β’ β2β β2β β₯
β’ β₯
β’ -β
β
Ξ± β
β
Ξ³ -β
β
Ξ± -β
β
Ξ³ β₯
β’ βββββ βββ βββββ βββββ β₯
β’ 2 2 βΞ²β 2 2 βΞ²ββ₯
β’-β― β
β― β
sinβββ β― β
β― β
cosββββ₯
β£ β2β β2β β¦ | [
"u",
"Return",
"the",
"Wigner",
"D",
"matrix",
"for",
"angular",
"momentum",
"J",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L510-L538 |
oscarlazoarjona/fast | fast/angular_momentum.py | density_matrix_rotation | def density_matrix_rotation(J_values, alpha, beta, gamma):
r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]])
"""
size = sum([2*J+1 for J in J_values])
D = zeros(size, size)
ind0 = 0
for J in J_values:
DJ = wigner_d(J, alpha, beta, gamma)
sizeJ = 2*J+1
indf = ind0 + sizeJ
D[ind0: indf, ind0: indf] = DJ
ind0 += sizeJ
return D | python | def density_matrix_rotation(J_values, alpha, beta, gamma):
r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]])
"""
size = sum([2*J+1 for J in J_values])
D = zeros(size, size)
ind0 = 0
for J in J_values:
DJ = wigner_d(J, alpha, beta, gamma)
sizeJ = 2*J+1
indf = ind0 + sizeJ
D[ind0: indf, ind0: indf] = DJ
ind0 += sizeJ
return D | [
"def",
"density_matrix_rotation",
"(",
"J_values",
",",
"alpha",
",",
"beta",
",",
"gamma",
")",
":",
"size",
"=",
"sum",
"(",
"[",
"2",
"*",
"J",
"+",
"1",
"for",
"J",
"in",
"J_values",
"]",
")",
"D",
"=",
"zeros",
"(",
"size",
",",
"size",
")",
"ind0",
"=",
"0",
"for",
"J",
"in",
"J_values",
":",
"DJ",
"=",
"wigner_d",
"(",
"J",
",",
"alpha",
",",
"beta",
",",
"gamma",
")",
"sizeJ",
"=",
"2",
"*",
"J",
"+",
"1",
"indf",
"=",
"ind0",
"+",
"sizeJ",
"D",
"[",
"ind0",
":",
"indf",
",",
"ind0",
":",
"indf",
"]",
"=",
"DJ",
"ind0",
"+=",
"sizeJ",
"return",
"D"
] | r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, 0, pi/2, 0)
Matrix([
[ 1/2, sqrt(2)/2, 1/2, 0],
[-sqrt(2)/2, 0, sqrt(2)/2, 0],
[ 1/2, -sqrt(2)/2, 1/2, 0],
[ 0, 0, 0, 1]]) | [
"r",
"Return",
"a",
"block",
"-",
"wise",
"diagonal",
"Wigner",
"D",
"matrix",
"for",
"that",
"rotates",
"a",
"density",
"matrix",
"of",
"an",
"ensemble",
"of",
"particles",
"in",
"definite",
"total",
"angular",
"momentum",
"states",
"given",
"by",
"J_values",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/angular_momentum.py#L541-L567 |
alexwlchan/specktre | src/specktre/tilings.py | generate_unit_squares | def generate_unit_squares(image_width, image_height):
"""Generate coordinates for a tiling of unit squares."""
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | |
# | |
# | |
# (x, y + 1) +-----+ (x + 1, y + 1)
#
for x in range(image_width):
for y in range(image_height):
yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)] | python | def generate_unit_squares(image_width, image_height):
"""Generate coordinates for a tiling of unit squares."""
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | |
# | |
# | |
# (x, y + 1) +-----+ (x + 1, y + 1)
#
for x in range(image_width):
for y in range(image_height):
yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)] | [
"def",
"generate_unit_squares",
"(",
"image_width",
",",
"image_height",
")",
":",
"# Iterate over the required rows and cells. The for loops (x, y)",
"# give the coordinates of the top left-hand corner of each square:",
"#",
"# (x, y) +-----+ (x + 1, y)",
"# | |",
"# | |",
"# | |",
"# (x, y + 1) +-----+ (x + 1, y + 1)",
"#",
"for",
"x",
"in",
"range",
"(",
"image_width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"image_height",
")",
":",
"yield",
"[",
"(",
"x",
",",
"y",
")",
",",
"(",
"x",
"+",
"1",
",",
"y",
")",
",",
"(",
"x",
"+",
"1",
",",
"y",
"+",
"1",
")",
",",
"(",
"x",
",",
"y",
"+",
"1",
")",
"]"
] | Generate coordinates for a tiling of unit squares. | [
"Generate",
"coordinates",
"for",
"a",
"tiling",
"of",
"unit",
"squares",
"."
] | train | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/tilings.py#L23-L36 |
alexwlchan/specktre | src/specktre/tilings.py | generate_unit_triangles | def generate_unit_triangles(image_width, image_height):
"""Generate coordinates for a tiling of unit triangles."""
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top left-hand corner
# of a pair of triangles:
#
# (x, y) +-----+ (x + 1, y)
# \ / \
# \ / \
# (x + 1/2, y + h) +-----+ (x + 3/2, y + h)
#
# where h = sin(60Β°) is the height of an equilateral triangle with
# side length 1.
#
# On odd-numbered rows, we translate by (s/2, 0) to make the triangles
# line up with the even-numbered rows.
#
# To avoid blank spaces on the edge of the canvas, the first pair of
# triangles on each row starts at (-1, 0) -- one width before the edge
# of the canvas.
h = math.sin(math.pi / 3)
for x in range(-1, image_width):
for y in range(int(image_height / h)):
# Add a horizontal offset on odd numbered rows
x_ = x if (y % 2 == 0) else x + 0.5
yield [(x_, y * h), (x_ + 1, y * h), (x_ + 0.5, (y + 1) * h)]
yield [(x_ + 1, y * h), (x_ + 1.5, (y + 1) * h),
(x_ + 0.5, (y + 1) * h)] | python | def generate_unit_triangles(image_width, image_height):
"""Generate coordinates for a tiling of unit triangles."""
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top left-hand corner
# of a pair of triangles:
#
# (x, y) +-----+ (x + 1, y)
# \ / \
# \ / \
# (x + 1/2, y + h) +-----+ (x + 3/2, y + h)
#
# where h = sin(60Β°) is the height of an equilateral triangle with
# side length 1.
#
# On odd-numbered rows, we translate by (s/2, 0) to make the triangles
# line up with the even-numbered rows.
#
# To avoid blank spaces on the edge of the canvas, the first pair of
# triangles on each row starts at (-1, 0) -- one width before the edge
# of the canvas.
h = math.sin(math.pi / 3)
for x in range(-1, image_width):
for y in range(int(image_height / h)):
# Add a horizontal offset on odd numbered rows
x_ = x if (y % 2 == 0) else x + 0.5
yield [(x_, y * h), (x_ + 1, y * h), (x_ + 0.5, (y + 1) * h)]
yield [(x_ + 1, y * h), (x_ + 1.5, (y + 1) * h),
(x_ + 0.5, (y + 1) * h)] | [
"def",
"generate_unit_triangles",
"(",
"image_width",
",",
"image_height",
")",
":",
"# Our triangles lie with one side parallel to the x-axis. Let s be",
"# the length of one side, and h the height of the triangle.",
"#",
"# The for loops (x, y) gives the coordinates of the top left-hand corner",
"# of a pair of triangles:",
"#",
"# (x, y) +-----+ (x + 1, y)",
"# \\ / \\",
"# \\ / \\",
"# (x + 1/2, y + h) +-----+ (x + 3/2, y + h)",
"#",
"# where h = sin(60Β°) is the height of an equilateral triangle with",
"# side length 1.",
"#",
"# On odd-numbered rows, we translate by (s/2, 0) to make the triangles",
"# line up with the even-numbered rows.",
"#",
"# To avoid blank spaces on the edge of the canvas, the first pair of",
"# triangles on each row starts at (-1, 0) -- one width before the edge",
"# of the canvas.",
"h",
"=",
"math",
".",
"sin",
"(",
"math",
".",
"pi",
"/",
"3",
")",
"for",
"x",
"in",
"range",
"(",
"-",
"1",
",",
"image_width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"int",
"(",
"image_height",
"/",
"h",
")",
")",
":",
"# Add a horizontal offset on odd numbered rows",
"x_",
"=",
"x",
"if",
"(",
"y",
"%",
"2",
"==",
"0",
")",
"else",
"x",
"+",
"0.5",
"yield",
"[",
"(",
"x_",
",",
"y",
"*",
"h",
")",
",",
"(",
"x_",
"+",
"1",
",",
"y",
"*",
"h",
")",
",",
"(",
"x_",
"+",
"0.5",
",",
"(",
"y",
"+",
"1",
")",
"*",
"h",
")",
"]",
"yield",
"[",
"(",
"x_",
"+",
"1",
",",
"y",
"*",
"h",
")",
",",
"(",
"x_",
"+",
"1.5",
",",
"(",
"y",
"+",
"1",
")",
"*",
"h",
")",
",",
"(",
"x_",
"+",
"0.5",
",",
"(",
"y",
"+",
"1",
")",
"*",
"h",
")",
"]"
] | Generate coordinates for a tiling of unit triangles. | [
"Generate",
"coordinates",
"for",
"a",
"tiling",
"of",
"unit",
"triangles",
"."
] | train | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/tilings.py#L44-L76 |
hammerlab/stancache | stancache/config.py | restore_default_settings | def restore_default_settings():
""" Restore settings to default values.
"""
global __DEFAULTS
__DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
__DEFAULTS.SET_SEED = defaults.SET_SEED
__DEFAULTS.SEED = defaults.SEED
logging.info('Settings reverted to their default values.') | python | def restore_default_settings():
""" Restore settings to default values.
"""
global __DEFAULTS
__DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
__DEFAULTS.SET_SEED = defaults.SET_SEED
__DEFAULTS.SEED = defaults.SEED
logging.info('Settings reverted to their default values.') | [
"def",
"restore_default_settings",
"(",
")",
":",
"global",
"__DEFAULTS",
"__DEFAULTS",
".",
"CACHE_DIR",
"=",
"defaults",
".",
"CACHE_DIR",
"__DEFAULTS",
".",
"SET_SEED",
"=",
"defaults",
".",
"SET_SEED",
"__DEFAULTS",
".",
"SEED",
"=",
"defaults",
".",
"SEED",
"logging",
".",
"info",
"(",
"'Settings reverted to their default values.'",
")"
] | Restore settings to default values. | [
"Restore",
"settings",
"to",
"default",
"values",
"."
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/config.py#L19-L26 |
hammerlab/stancache | stancache/config.py | load_config | def load_config(config_file='~/.stancache.ini'):
""" Load config file into default settings
"""
if not os.path.exists(config_file):
logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
return
## get user-level config in *.ini format
config = configparser.ConfigParser()
config.read(config_file)
if not config.has_section('main'):
raise ValueError('Config file {} has no section "main"'.format(config_file))
for (key, val) in config.items('main'):
_set_value(key.upper(), val)
return | python | def load_config(config_file='~/.stancache.ini'):
""" Load config file into default settings
"""
if not os.path.exists(config_file):
logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
return
## get user-level config in *.ini format
config = configparser.ConfigParser()
config.read(config_file)
if not config.has_section('main'):
raise ValueError('Config file {} has no section "main"'.format(config_file))
for (key, val) in config.items('main'):
_set_value(key.upper(), val)
return | [
"def",
"load_config",
"(",
"config_file",
"=",
"'~/.stancache.ini'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"logging",
".",
"warning",
"(",
"'Config file does not exist: {}. Using default settings.'",
".",
"format",
"(",
"config_file",
")",
")",
"return",
"## get user-level config in *.ini format",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read",
"(",
"config_file",
")",
"if",
"not",
"config",
".",
"has_section",
"(",
"'main'",
")",
":",
"raise",
"ValueError",
"(",
"'Config file {} has no section \"main\"'",
".",
"format",
"(",
"config_file",
")",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"config",
".",
"items",
"(",
"'main'",
")",
":",
"_set_value",
"(",
"key",
".",
"upper",
"(",
")",
",",
"val",
")",
"return"
] | Load config file into default settings | [
"Load",
"config",
"file",
"into",
"default",
"settings"
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/config.py#L29-L42 |
deployed/django-emailtemplates | emailtemplates/shortcuts.py | send_email | def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(send_to=send_to, **kwargs) | python | def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(send_to=send_to, **kwargs) | [
"def",
"send_email",
"(",
"name",
",",
"ctx_dict",
",",
"send_to",
"=",
"None",
",",
"subject",
"=",
"u'Subject'",
",",
"*",
"*",
"kwargs",
")",
":",
"eft",
"=",
"EmailFromTemplate",
"(",
"name",
"=",
"name",
")",
"eft",
".",
"subject",
"=",
"subject",
"eft",
".",
"context",
"=",
"ctx_dict",
"eft",
".",
"get_object",
"(",
")",
"eft",
".",
"render_message",
"(",
")",
"eft",
".",
"send_email",
"(",
"send_to",
"=",
"send_to",
",",
"*",
"*",
"kwargs",
")"
] | Shortcut function for EmailFromTemplate class
@return: None | [
"Shortcut",
"function",
"for",
"EmailFromTemplate",
"class"
] | train | https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/shortcuts.py#L5-L17 |
abn/cafeteria | cafeteria/logging/__init__.py | LoggingManager.set_level | def set_level(cls, level):
"""
:raises: ValueError
"""
level = (
level
if not is_str(level)
else int(LOGGING_LEVELS.get(level.upper(), level))
)
for handler in root.handlers:
handler.setLevel(level)
root.setLevel(level) | python | def set_level(cls, level):
"""
:raises: ValueError
"""
level = (
level
if not is_str(level)
else int(LOGGING_LEVELS.get(level.upper(), level))
)
for handler in root.handlers:
handler.setLevel(level)
root.setLevel(level) | [
"def",
"set_level",
"(",
"cls",
",",
"level",
")",
":",
"level",
"=",
"(",
"level",
"if",
"not",
"is_str",
"(",
"level",
")",
"else",
"int",
"(",
"LOGGING_LEVELS",
".",
"get",
"(",
"level",
".",
"upper",
"(",
")",
",",
"level",
")",
")",
")",
"for",
"handler",
"in",
"root",
".",
"handlers",
":",
"handler",
".",
"setLevel",
"(",
"level",
")",
"root",
".",
"setLevel",
"(",
"level",
")"
] | :raises: ValueError | [
":",
"raises",
":",
"ValueError"
] | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/logging/__init__.py#L17-L30 |
abn/cafeteria | cafeteria/logging/__init__.py | LoggingManager.load_config | def load_config(cls, configfile="logging.yaml"):
"""
:raises: ValueError
"""
configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile)
if isfile(configfile):
with open(configfile, "r") as cf:
# noinspection PyBroadException
try:
dictConfig(load(cf))
except ValueError:
debug("Learn to config foooo! Improper config at %s", configfile)
except Exception:
exception("Something went wrong while reading %s.", configfile)
else:
raise ValueError("Invalid configfile specified: {}".format(configfile)) | python | def load_config(cls, configfile="logging.yaml"):
"""
:raises: ValueError
"""
configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile)
if isfile(configfile):
with open(configfile, "r") as cf:
# noinspection PyBroadException
try:
dictConfig(load(cf))
except ValueError:
debug("Learn to config foooo! Improper config at %s", configfile)
except Exception:
exception("Something went wrong while reading %s.", configfile)
else:
raise ValueError("Invalid configfile specified: {}".format(configfile)) | [
"def",
"load_config",
"(",
"cls",
",",
"configfile",
"=",
"\"logging.yaml\"",
")",
":",
"configfile",
"=",
"getenv",
"(",
"cls",
".",
"CONFIGFILE_ENV_KEY",
",",
"configfile",
")",
"if",
"isfile",
"(",
"configfile",
")",
":",
"with",
"open",
"(",
"configfile",
",",
"\"r\"",
")",
"as",
"cf",
":",
"# noinspection PyBroadException",
"try",
":",
"dictConfig",
"(",
"load",
"(",
"cf",
")",
")",
"except",
"ValueError",
":",
"debug",
"(",
"\"Learn to config foooo! Improper config at %s\"",
",",
"configfile",
")",
"except",
"Exception",
":",
"exception",
"(",
"\"Something went wrong while reading %s.\"",
",",
"configfile",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid configfile specified: {}\"",
".",
"format",
"(",
"configfile",
")",
")"
] | :raises: ValueError | [
":",
"raises",
":",
"ValueError"
] | train | https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/logging/__init__.py#L33-L48 |
daddyd/dewiki | dewiki/parser.py | Parser.__parse | def __parse(self, string=''):
'''
Parse a string to remove and replace all wiki markup tags
'''
self.string = string
self.string = self.wiki_re.sub('', self.string)
# search for lists
self.listmatch = re.search('^(\*+)', self.string)
if self.listmatch:
self.string = self.__list(self.listmatch) + re.sub('^(\*+)', \
'', self.string)
return self.string | python | def __parse(self, string=''):
'''
Parse a string to remove and replace all wiki markup tags
'''
self.string = string
self.string = self.wiki_re.sub('', self.string)
# search for lists
self.listmatch = re.search('^(\*+)', self.string)
if self.listmatch:
self.string = self.__list(self.listmatch) + re.sub('^(\*+)', \
'', self.string)
return self.string | [
"def",
"__parse",
"(",
"self",
",",
"string",
"=",
"''",
")",
":",
"self",
".",
"string",
"=",
"string",
"self",
".",
"string",
"=",
"self",
".",
"wiki_re",
".",
"sub",
"(",
"''",
",",
"self",
".",
"string",
")",
"# search for lists",
"self",
".",
"listmatch",
"=",
"re",
".",
"search",
"(",
"'^(\\*+)'",
",",
"self",
".",
"string",
")",
"if",
"self",
".",
"listmatch",
":",
"self",
".",
"string",
"=",
"self",
".",
"__list",
"(",
"self",
".",
"listmatch",
")",
"+",
"re",
".",
"sub",
"(",
"'^(\\*+)'",
",",
"''",
",",
"self",
".",
"string",
")",
"return",
"self",
".",
"string"
] | Parse a string to remove and replace all wiki markup tags | [
"Parse",
"a",
"string",
"to",
"remove",
"and",
"replace",
"all",
"wiki",
"markup",
"tags"
] | train | https://github.com/daddyd/dewiki/blob/84214bb9537326e036fa65e70d7a9ce7c6659c26/dewiki/parser.py#L32-L43 |
daddyd/dewiki | dewiki/parser.py | Parser.parse_string | def parse_string(self, string=''):
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings) | python | def parse_string(self, string=''):
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings) | [
"def",
"parse_string",
"(",
"self",
",",
"string",
"=",
"''",
")",
":",
"self",
".",
"strings",
"=",
"string",
".",
"splitlines",
"(",
"1",
")",
"self",
".",
"strings",
"=",
"[",
"self",
".",
"__parse",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"strings",
"]",
"return",
"''",
".",
"join",
"(",
"self",
".",
"strings",
")"
] | Parse a string object to de-wikified text | [
"Parse",
"a",
"string",
"object",
"to",
"de",
"-",
"wikified",
"text"
] | train | https://github.com/daddyd/dewiki/blob/84214bb9537326e036fa65e70d7a9ce7c6659c26/dewiki/parser.py#L45-L51 |
oscarlazoarjona/fast | fast/evolution.py | run_evolution | def run_evolution(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
rho0=None,print_steps=False,
integrate=False,
save_systems=False,save_eigenvalues=False,rk4=False,use_netcdf=True):
"""This function runs the Runge-Kutta method compiled in path+name..."""
def py2f_bool(bool_var):
if bool_var:
return ".true.\n"
else:
return ".false.\n"
if rk4:
return run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=spectrum_of_laser,N_delta=N_delta,
frequency_step=frequency_step, frequency_end=frequency_end,
rho0=rho0,print_steps=print_steps,
integrate=integrate,save_systems=save_systems)
t0=time()
params =str(N_iter)+'\n'
params+=str(dt)+'\n'
#We give the flag on wether to print each time step.
params+=py2f_bool(print_steps)
#We give the initial value of rho
N_vars=N_states*(N_states+1)/2-1
if rho0==None:
params+=''.join(['(0.0,0.0) ' for i in range(N_states**2-1)])
elif len(rho0)==N_states-1:
if sage_included:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
params+=''.join(['(0.0,0.0) ' for i in range( N_states**2 -N_states)])
elif len(rho0)==N_vars:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
raise ValueError,'rho0 had an invalid number of elements.'
params+='\n'
#We give the amplitude of the electrical fields.
params+=''.join([str(i)+' ' for i in E0])+'\n'
#We give the detuning of each laser (taken from the lowest frequency transition).
params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'
#We give the flag on wether to calculate spectrums or time evolution.
if spectrum_of_laser==None:
params+='.false.\n'
params+=py2f_bool(save_systems)
params+=py2f_bool(save_eigenvalues)
params+=py2f_bool(use_netcdf)
params+=py2f_bool(integrate)
else:
if frequency_end !=None:
if frequency_step !=None:
raise ValueError,'both frequency_end and frequency_step were specified.'
if N_delta==1:
frequency_step=0.0
else:
frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)
#frequency_step=frequency_end
params+='.true.\n'
params+=py2f_bool(save_systems)
params+=py2f_bool(save_eigenvalues)
params+=py2f_bool(use_netcdf)
params+=py2f_bool(integrate)
params+=str(spectrum_of_laser)+'\n'
params+=str(N_delta)+'\n'
params+=str(frequency_step)
#print params
f=file(path+name+'_params.dat','w')
f.write(params)
f.close()
os.system(path+name)
return time()-t0 | python | def run_evolution(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
rho0=None,print_steps=False,
integrate=False,
save_systems=False,save_eigenvalues=False,rk4=False,use_netcdf=True):
"""This function runs the Runge-Kutta method compiled in path+name..."""
def py2f_bool(bool_var):
if bool_var:
return ".true.\n"
else:
return ".false.\n"
if rk4:
return run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=spectrum_of_laser,N_delta=N_delta,
frequency_step=frequency_step, frequency_end=frequency_end,
rho0=rho0,print_steps=print_steps,
integrate=integrate,save_systems=save_systems)
t0=time()
params =str(N_iter)+'\n'
params+=str(dt)+'\n'
#We give the flag on wether to print each time step.
params+=py2f_bool(print_steps)
#We give the initial value of rho
N_vars=N_states*(N_states+1)/2-1
if rho0==None:
params+=''.join(['(0.0,0.0) ' for i in range(N_states**2-1)])
elif len(rho0)==N_states-1:
if sage_included:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
params+=''.join(['(0.0,0.0) ' for i in range( N_states**2 -N_states)])
elif len(rho0)==N_vars:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
raise ValueError,'rho0 had an invalid number of elements.'
params+='\n'
#We give the amplitude of the electrical fields.
params+=''.join([str(i)+' ' for i in E0])+'\n'
#We give the detuning of each laser (taken from the lowest frequency transition).
params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'
#We give the flag on wether to calculate spectrums or time evolution.
if spectrum_of_laser==None:
params+='.false.\n'
params+=py2f_bool(save_systems)
params+=py2f_bool(save_eigenvalues)
params+=py2f_bool(use_netcdf)
params+=py2f_bool(integrate)
else:
if frequency_end !=None:
if frequency_step !=None:
raise ValueError,'both frequency_end and frequency_step were specified.'
if N_delta==1:
frequency_step=0.0
else:
frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)
#frequency_step=frequency_end
params+='.true.\n'
params+=py2f_bool(save_systems)
params+=py2f_bool(save_eigenvalues)
params+=py2f_bool(use_netcdf)
params+=py2f_bool(integrate)
params+=str(spectrum_of_laser)+'\n'
params+=str(N_delta)+'\n'
params+=str(frequency_step)
#print params
f=file(path+name+'_params.dat','w')
f.write(params)
f.close()
os.system(path+name)
return time()-t0 | [
"def",
"run_evolution",
"(",
"path",
",",
"name",
",",
"E0",
",",
"laser_frequencies",
",",
"N_iter",
",",
"dt",
",",
"N_states",
",",
"spectrum_of_laser",
"=",
"None",
",",
"N_delta",
"=",
"None",
",",
"frequency_step",
"=",
"None",
",",
"frequency_end",
"=",
"None",
",",
"rho0",
"=",
"None",
",",
"print_steps",
"=",
"False",
",",
"integrate",
"=",
"False",
",",
"save_systems",
"=",
"False",
",",
"save_eigenvalues",
"=",
"False",
",",
"rk4",
"=",
"False",
",",
"use_netcdf",
"=",
"True",
")",
":",
"def",
"py2f_bool",
"(",
"bool_var",
")",
":",
"if",
"bool_var",
":",
"return",
"\".true.\\n\"",
"else",
":",
"return",
"\".false.\\n\"",
"if",
"rk4",
":",
"return",
"run_rk4",
"(",
"path",
",",
"name",
",",
"E0",
",",
"laser_frequencies",
",",
"N_iter",
",",
"dt",
",",
"N_states",
",",
"spectrum_of_laser",
"=",
"spectrum_of_laser",
",",
"N_delta",
"=",
"N_delta",
",",
"frequency_step",
"=",
"frequency_step",
",",
"frequency_end",
"=",
"frequency_end",
",",
"rho0",
"=",
"rho0",
",",
"print_steps",
"=",
"print_steps",
",",
"integrate",
"=",
"integrate",
",",
"save_systems",
"=",
"save_systems",
")",
"t0",
"=",
"time",
"(",
")",
"params",
"=",
"str",
"(",
"N_iter",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"dt",
")",
"+",
"'\\n'",
"#We give the flag on wether to print each time step.",
"params",
"+=",
"py2f_bool",
"(",
"print_steps",
")",
"#We give the initial value of rho",
"N_vars",
"=",
"N_states",
"*",
"(",
"N_states",
"+",
"1",
")",
"/",
"2",
"-",
"1",
"if",
"rho0",
"==",
"None",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'(0.0,0.0) '",
"for",
"i",
"in",
"range",
"(",
"N_states",
"**",
"2",
"-",
"1",
")",
"]",
")",
"elif",
"len",
"(",
"rho0",
")",
"==",
"N_states",
"-",
"1",
":",
"if",
"sage_included",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"real",
"(",
"i",
")",
")",
"+",
"','",
"+",
"str",
"(",
"imag",
"(",
"i",
")",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"else",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"i",
".",
"real",
")",
"+",
"','",
"+",
"str",
"(",
"i",
".",
"imag",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'(0.0,0.0) '",
"for",
"i",
"in",
"range",
"(",
"N_states",
"**",
"2",
"-",
"N_states",
")",
"]",
")",
"elif",
"len",
"(",
"rho0",
")",
"==",
"N_vars",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"real",
"(",
"i",
")",
")",
"+",
"','",
"+",
"str",
"(",
"imag",
"(",
"i",
")",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"else",
":",
"raise",
"ValueError",
",",
"'rho0 had an invalid number of elements.'",
"params",
"+=",
"'\\n'",
"#We give the amplitude of the electrical fields.",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"+",
"' '",
"for",
"i",
"in",
"E0",
"]",
")",
"+",
"'\\n'",
"#We give the detuning of each laser (taken from the lowest frequency transition).",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"+",
"' '",
"for",
"i",
"in",
"laser_frequencies",
"]",
")",
"+",
"'\\n'",
"#We give the flag on wether to calculate spectrums or time evolution.",
"if",
"spectrum_of_laser",
"==",
"None",
":",
"params",
"+=",
"'.false.\\n'",
"params",
"+=",
"py2f_bool",
"(",
"save_systems",
")",
"params",
"+=",
"py2f_bool",
"(",
"save_eigenvalues",
")",
"params",
"+=",
"py2f_bool",
"(",
"use_netcdf",
")",
"params",
"+=",
"py2f_bool",
"(",
"integrate",
")",
"else",
":",
"if",
"frequency_end",
"!=",
"None",
":",
"if",
"frequency_step",
"!=",
"None",
":",
"raise",
"ValueError",
",",
"'both frequency_end and frequency_step were specified.'",
"if",
"N_delta",
"==",
"1",
":",
"frequency_step",
"=",
"0.0",
"else",
":",
"frequency_step",
"=",
"(",
"frequency_end",
"-",
"laser_frequencies",
"[",
"spectrum_of_laser",
"-",
"1",
"]",
")",
"/",
"(",
"N_delta",
"-",
"1",
")",
"#frequency_step=frequency_end",
"params",
"+=",
"'.true.\\n'",
"params",
"+=",
"py2f_bool",
"(",
"save_systems",
")",
"params",
"+=",
"py2f_bool",
"(",
"save_eigenvalues",
")",
"params",
"+=",
"py2f_bool",
"(",
"use_netcdf",
")",
"params",
"+=",
"py2f_bool",
"(",
"integrate",
")",
"params",
"+=",
"str",
"(",
"spectrum_of_laser",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"N_delta",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"frequency_step",
")",
"#print params",
"f",
"=",
"file",
"(",
"path",
"+",
"name",
"+",
"'_params.dat'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"params",
")",
"f",
".",
"close",
"(",
")",
"os",
".",
"system",
"(",
"path",
"+",
"name",
")",
"return",
"time",
"(",
")",
"-",
"t0"
] | This function runs the Runge-Kutta method compiled in path+name... | [
"This",
"function",
"runs",
"the",
"Runge",
"-",
"Kutta",
"method",
"compiled",
"in",
"path",
"+",
"name",
"..."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/evolution.py#L477-L558 |
oscarlazoarjona/fast | fast/evolution.py | characteristic_times | def characteristic_times(path,name,Omega=1):
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_lives_N**2-1]``.
'''
re,im=get_eigenvalues(path,name)
log12=log(0.5)
Nr=len(re[0]); Nd=len(re)
half_lives=[]; oscillation_periods=[]
for i in range(Nr):
col_half=[]
col_osci=[]
for j in range(Nd):
if re[j][i]>=0.0 and i!=0:
raise ValueError,'an eigenvalue was greater or equall to zero:'+str(re[j][i])+'.'
else:
col_half+=[log12/re[j][i]/Omega]
if im[j][i]==0.0 and i!=0:
col_osci+=[float('inf')]
else:
col_osci+=[abs(2*pi/im[j][i])/Omega]
half_lives+=[col_half]
oscillation_periods+=[col_osci]
return oscillation_periods+half_lives[1:] | python | def characteristic_times(path,name,Omega=1):
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_lives_N**2-1]``.
'''
re,im=get_eigenvalues(path,name)
log12=log(0.5)
Nr=len(re[0]); Nd=len(re)
half_lives=[]; oscillation_periods=[]
for i in range(Nr):
col_half=[]
col_osci=[]
for j in range(Nd):
if re[j][i]>=0.0 and i!=0:
raise ValueError,'an eigenvalue was greater or equall to zero:'+str(re[j][i])+'.'
else:
col_half+=[log12/re[j][i]/Omega]
if im[j][i]==0.0 and i!=0:
col_osci+=[float('inf')]
else:
col_osci+=[abs(2*pi/im[j][i])/Omega]
half_lives+=[col_half]
oscillation_periods+=[col_osci]
return oscillation_periods+half_lives[1:] | [
"def",
"characteristic_times",
"(",
"path",
",",
"name",
",",
"Omega",
"=",
"1",
")",
":",
"re",
",",
"im",
"=",
"get_eigenvalues",
"(",
"path",
",",
"name",
")",
"log12",
"=",
"log",
"(",
"0.5",
")",
"Nr",
"=",
"len",
"(",
"re",
"[",
"0",
"]",
")",
"Nd",
"=",
"len",
"(",
"re",
")",
"half_lives",
"=",
"[",
"]",
"oscillation_periods",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Nr",
")",
":",
"col_half",
"=",
"[",
"]",
"col_osci",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"Nd",
")",
":",
"if",
"re",
"[",
"j",
"]",
"[",
"i",
"]",
">=",
"0.0",
"and",
"i",
"!=",
"0",
":",
"raise",
"ValueError",
",",
"'an eigenvalue was greater or equall to zero:'",
"+",
"str",
"(",
"re",
"[",
"j",
"]",
"[",
"i",
"]",
")",
"+",
"'.'",
"else",
":",
"col_half",
"+=",
"[",
"log12",
"/",
"re",
"[",
"j",
"]",
"[",
"i",
"]",
"/",
"Omega",
"]",
"if",
"im",
"[",
"j",
"]",
"[",
"i",
"]",
"==",
"0.0",
"and",
"i",
"!=",
"0",
":",
"col_osci",
"+=",
"[",
"float",
"(",
"'inf'",
")",
"]",
"else",
":",
"col_osci",
"+=",
"[",
"abs",
"(",
"2",
"*",
"pi",
"/",
"im",
"[",
"j",
"]",
"[",
"i",
"]",
")",
"/",
"Omega",
"]",
"half_lives",
"+=",
"[",
"col_half",
"]",
"oscillation_periods",
"+=",
"[",
"col_osci",
"]",
"return",
"oscillation_periods",
"+",
"half_lives",
"[",
"1",
":",
"]"
] | r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_lives_N**2-1]``. | [
"r",
"This",
"function",
"can",
"be",
"called",
"after",
"calling",
"run_diagonalization",
"if",
"the",
"option",
"save_eigenvalues",
"is",
"set",
"to",
"True",
".",
"It",
"will",
"return",
"the",
"oscillation",
"periods",
"and",
"the",
"shortest",
"and",
"half",
"lives",
".",
"The",
"results",
"are",
"lists",
"ordered",
"as",
":",
"[",
"detunings",
"oscillation_periods_1",
"oscillation_periods_N",
"**",
"2",
"-",
"1",
"half_lives_1",
"half_lives_N",
"**",
"2",
"-",
"1",
"]",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/evolution.py#L569-L595 |
oscarlazoarjona/fast | fast/evolution.py | analyze_eigenvalues | def analyze_eigenvalues(path,name,Ne):
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and
longest half life. The results are lists ordered as:
``[detunings, shortest_oscillations, longest_oscillations, shortest_half_lifes, longest_half_lifes]``.
The shortest oscillation period can be interpreted as a suggested size for the time step needed for a
fine-grained picture of time evolution (an order of magnitude smaller is likely to be optimal).
The longest half life can be interpreted as a suggested time for the stationary state to be reached
(an order of magnitude larger is likely to be optimal).
'''
times=characteristic_times(path,name)
min_osci=min([min(times[1+i]) for i in range(Ne**2-1)])
max_osci=max([max(times[1+i]) for i in range(Ne**2-1)])
min_half=min([min(times[1+Ne**2-1+i]) for i in range(Ne**2-1)])
max_half=max([max(times[1+Ne**2-1+i]) for i in range(Ne**2-1)])
return min_osci,max_osci,min_half,max_half | python | def analyze_eigenvalues(path,name,Ne):
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and
longest half life. The results are lists ordered as:
``[detunings, shortest_oscillations, longest_oscillations, shortest_half_lifes, longest_half_lifes]``.
The shortest oscillation period can be interpreted as a suggested size for the time step needed for a
fine-grained picture of time evolution (an order of magnitude smaller is likely to be optimal).
The longest half life can be interpreted as a suggested time for the stationary state to be reached
(an order of magnitude larger is likely to be optimal).
'''
times=characteristic_times(path,name)
min_osci=min([min(times[1+i]) for i in range(Ne**2-1)])
max_osci=max([max(times[1+i]) for i in range(Ne**2-1)])
min_half=min([min(times[1+Ne**2-1+i]) for i in range(Ne**2-1)])
max_half=max([max(times[1+Ne**2-1+i]) for i in range(Ne**2-1)])
return min_osci,max_osci,min_half,max_half | [
"def",
"analyze_eigenvalues",
"(",
"path",
",",
"name",
",",
"Ne",
")",
":",
"times",
"=",
"characteristic_times",
"(",
"path",
",",
"name",
")",
"min_osci",
"=",
"min",
"(",
"[",
"min",
"(",
"times",
"[",
"1",
"+",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
"**",
"2",
"-",
"1",
")",
"]",
")",
"max_osci",
"=",
"max",
"(",
"[",
"max",
"(",
"times",
"[",
"1",
"+",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
"**",
"2",
"-",
"1",
")",
"]",
")",
"min_half",
"=",
"min",
"(",
"[",
"min",
"(",
"times",
"[",
"1",
"+",
"Ne",
"**",
"2",
"-",
"1",
"+",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
"**",
"2",
"-",
"1",
")",
"]",
")",
"max_half",
"=",
"max",
"(",
"[",
"max",
"(",
"times",
"[",
"1",
"+",
"Ne",
"**",
"2",
"-",
"1",
"+",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
"**",
"2",
"-",
"1",
")",
"]",
")",
"return",
"min_osci",
",",
"max_osci",
",",
"min_half",
",",
"max_half"
] | r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and
longest half life. The results are lists ordered as:
``[detunings, shortest_oscillations, longest_oscillations, shortest_half_lifes, longest_half_lifes]``.
The shortest oscillation period can be interpreted as a suggested size for the time step needed for a
fine-grained picture of time evolution (an order of magnitude smaller is likely to be optimal).
The longest half life can be interpreted as a suggested time for the stationary state to be reached
(an order of magnitude larger is likely to be optimal). | [
"r",
"This",
"function",
"can",
"be",
"called",
"after",
"calling",
"run_diagonalization",
"if",
"the",
"option",
"save_eigenvalues",
"is",
"set",
"to",
"True",
".",
"It",
"will",
"return",
"the",
"shortest",
"and",
"longest",
"oscillation",
"period",
"and",
"the",
"shortest",
"and",
"longest",
"half",
"life",
".",
"The",
"results",
"are",
"lists",
"ordered",
"as",
":",
"[",
"detunings",
"shortest_oscillations",
"longest_oscillations",
"shortest_half_lifes",
"longest_half_lifes",
"]",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/evolution.py#L597-L616 |
oscarlazoarjona/fast | build/lib/fast/electric_field.py | electric_field_amplitude_intensity | def electric_field_amplitude_intensity(s0,Omega=1.0e6):
'''This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light.'''
e0=hbar*Omega/(e*a0) #This is the electric field scale.
I0=2.50399 #mW/cm^2
I0=1.66889451102868 #mW/cm^2
I0=I0/1000*(100**2) #W/m^2
r_ciclic=4.226983616875483 #a0
gamma_D2=2*Pi*6.065e6/Omega # The decay frequency of the D2 line.
E0_sat=gamma_D2/r_ciclic/sqrt(2.0)
E0_sat=E0_sat*e0
I0=E0_sat**2/2/c/mu0
#return sqrt(c*mu0*s0*I0/2)/e0
#return sqrt(c*mu0*s0*I0)/e0
return sqrt(2*c*mu0*s0*I0)/e0 | python | def electric_field_amplitude_intensity(s0,Omega=1.0e6):
'''This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light.'''
e0=hbar*Omega/(e*a0) #This is the electric field scale.
I0=2.50399 #mW/cm^2
I0=1.66889451102868 #mW/cm^2
I0=I0/1000*(100**2) #W/m^2
r_ciclic=4.226983616875483 #a0
gamma_D2=2*Pi*6.065e6/Omega # The decay frequency of the D2 line.
E0_sat=gamma_D2/r_ciclic/sqrt(2.0)
E0_sat=E0_sat*e0
I0=E0_sat**2/2/c/mu0
#return sqrt(c*mu0*s0*I0/2)/e0
#return sqrt(c*mu0*s0*I0)/e0
return sqrt(2*c*mu0*s0*I0)/e0 | [
"def",
"electric_field_amplitude_intensity",
"(",
"s0",
",",
"Omega",
"=",
"1.0e6",
")",
":",
"e0",
"=",
"hbar",
"*",
"Omega",
"/",
"(",
"e",
"*",
"a0",
")",
"#This is the electric field scale.\r",
"I0",
"=",
"2.50399",
"#mW/cm^2\r",
"I0",
"=",
"1.66889451102868",
"#mW/cm^2\r",
"I0",
"=",
"I0",
"/",
"1000",
"*",
"(",
"100",
"**",
"2",
")",
"#W/m^2\r",
"r_ciclic",
"=",
"4.226983616875483",
"#a0\r",
"gamma_D2",
"=",
"2",
"*",
"Pi",
"*",
"6.065e6",
"/",
"Omega",
"# The decay frequency of the D2 line.\r",
"E0_sat",
"=",
"gamma_D2",
"/",
"r_ciclic",
"/",
"sqrt",
"(",
"2.0",
")",
"E0_sat",
"=",
"E0_sat",
"*",
"e0",
"I0",
"=",
"E0_sat",
"**",
"2",
"/",
"2",
"/",
"c",
"/",
"mu0",
"#return sqrt(c*mu0*s0*I0/2)/e0\r",
"#return sqrt(c*mu0*s0*I0)/e0\r",
"return",
"sqrt",
"(",
"2",
"*",
"c",
"*",
"mu0",
"*",
"s0",
"*",
"I0",
")",
"/",
"e0"
] | This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light. | [
"This",
"function",
"returns",
"the",
"value",
"of",
"E0",
"(",
"the",
"amplitude",
"of",
"the",
"electric",
"field",
")",
"at",
"a",
"given",
"saturation",
"parameter",
"s0",
"=",
"I",
"/",
"I0",
"where",
"I0",
"=",
"2",
".",
"50399",
"mW",
"/",
"cm^2",
"is",
"the",
"saturation",
"intensity",
"of",
"the",
"D2",
"line",
"of",
"Rubidium",
"for",
"linearly",
"polarized",
"light",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/electric_field.py#L374-L393 |
tilde-lab/tilde | tilde/parsers/__init__.py | Output.get_checksum | def get_checksum(self):
'''
Retrieve unique hash in a cross-platform manner:
this is how calculation identity is determined
'''
if self._checksum:
return self._checksum
if not self._filename:
raise RuntimeError('Source calc file is required in order to properly save the data!')
calc_checksum = hashlib.sha224()
struc_repr = ""
for ase_obj in self.structures:
struc_repr += "%3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f " % tuple(map(abs, [ase_obj.cell[0][0], ase_obj.cell[0][1], ase_obj.cell[0][2], ase_obj.cell[1][0], ase_obj.cell[1][1], ase_obj.cell[1][2], ase_obj.cell[2][0], ase_obj.cell[2][1], ase_obj.cell[2][2]])) # NB beware of length & minus zeros
for atom in ase_obj:
struc_repr += "%s %3.6f %3.6f %3.6f " % tuple(map(abs, [chemical_symbols.index(atom.symbol), atom.x, atom.y, atom.z])) # NB beware of length & minus zeros
if self.info["energy"] is None:
energy = str(None)
else:
energy = str(round(self.info['energy'], 11 - int(math.log10(math.fabs(self.info['energy'])))))
calc_checksum.update((
struc_repr + "\n" +
energy + "\n" +
self.info['prog'] + "\n" +
str(self.info['input']) + "\n" +
str(sum([2**x for x in self.info['calctypes']]))
).encode('ascii')) # NB this is fixed and should not be changed
result = base64.b32encode(calc_checksum.digest()).decode('ascii')
result = result[:result.index('=')] + 'CI'
return result | python | def get_checksum(self):
'''
Retrieve unique hash in a cross-platform manner:
this is how calculation identity is determined
'''
if self._checksum:
return self._checksum
if not self._filename:
raise RuntimeError('Source calc file is required in order to properly save the data!')
calc_checksum = hashlib.sha224()
struc_repr = ""
for ase_obj in self.structures:
struc_repr += "%3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f " % tuple(map(abs, [ase_obj.cell[0][0], ase_obj.cell[0][1], ase_obj.cell[0][2], ase_obj.cell[1][0], ase_obj.cell[1][1], ase_obj.cell[1][2], ase_obj.cell[2][0], ase_obj.cell[2][1], ase_obj.cell[2][2]])) # NB beware of length & minus zeros
for atom in ase_obj:
struc_repr += "%s %3.6f %3.6f %3.6f " % tuple(map(abs, [chemical_symbols.index(atom.symbol), atom.x, atom.y, atom.z])) # NB beware of length & minus zeros
if self.info["energy"] is None:
energy = str(None)
else:
energy = str(round(self.info['energy'], 11 - int(math.log10(math.fabs(self.info['energy'])))))
calc_checksum.update((
struc_repr + "\n" +
energy + "\n" +
self.info['prog'] + "\n" +
str(self.info['input']) + "\n" +
str(sum([2**x for x in self.info['calctypes']]))
).encode('ascii')) # NB this is fixed and should not be changed
result = base64.b32encode(calc_checksum.digest()).decode('ascii')
result = result[:result.index('=')] + 'CI'
return result | [
"def",
"get_checksum",
"(",
"self",
")",
":",
"if",
"self",
".",
"_checksum",
":",
"return",
"self",
".",
"_checksum",
"if",
"not",
"self",
".",
"_filename",
":",
"raise",
"RuntimeError",
"(",
"'Source calc file is required in order to properly save the data!'",
")",
"calc_checksum",
"=",
"hashlib",
".",
"sha224",
"(",
")",
"struc_repr",
"=",
"\"\"",
"for",
"ase_obj",
"in",
"self",
".",
"structures",
":",
"struc_repr",
"+=",
"\"%3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f \"",
"%",
"tuple",
"(",
"map",
"(",
"abs",
",",
"[",
"ase_obj",
".",
"cell",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"0",
"]",
"[",
"2",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"1",
"]",
"[",
"1",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"1",
"]",
"[",
"2",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"2",
"]",
"[",
"0",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"2",
"]",
"[",
"1",
"]",
",",
"ase_obj",
".",
"cell",
"[",
"2",
"]",
"[",
"2",
"]",
"]",
")",
")",
"# NB beware of length & minus zeros",
"for",
"atom",
"in",
"ase_obj",
":",
"struc_repr",
"+=",
"\"%s %3.6f %3.6f %3.6f \"",
"%",
"tuple",
"(",
"map",
"(",
"abs",
",",
"[",
"chemical_symbols",
".",
"index",
"(",
"atom",
".",
"symbol",
")",
",",
"atom",
".",
"x",
",",
"atom",
".",
"y",
",",
"atom",
".",
"z",
"]",
")",
")",
"# NB beware of length & minus zeros",
"if",
"self",
".",
"info",
"[",
"\"energy\"",
"]",
"is",
"None",
":",
"energy",
"=",
"str",
"(",
"None",
")",
"else",
":",
"energy",
"=",
"str",
"(",
"round",
"(",
"self",
".",
"info",
"[",
"'energy'",
"]",
",",
"11",
"-",
"int",
"(",
"math",
".",
"log10",
"(",
"math",
".",
"fabs",
"(",
"self",
".",
"info",
"[",
"'energy'",
"]",
")",
")",
")",
")",
")",
"calc_checksum",
".",
"update",
"(",
"(",
"struc_repr",
"+",
"\"\\n\"",
"+",
"energy",
"+",
"\"\\n\"",
"+",
"self",
".",
"info",
"[",
"'prog'",
"]",
"+",
"\"\\n\"",
"+",
"str",
"(",
"self",
".",
"info",
"[",
"'input'",
"]",
")",
"+",
"\"\\n\"",
"+",
"str",
"(",
"sum",
"(",
"[",
"2",
"**",
"x",
"for",
"x",
"in",
"self",
".",
"info",
"[",
"'calctypes'",
"]",
"]",
")",
")",
")",
".",
"encode",
"(",
"'ascii'",
")",
")",
"# NB this is fixed and should not be changed",
"result",
"=",
"base64",
".",
"b32encode",
"(",
"calc_checksum",
".",
"digest",
"(",
")",
")",
".",
"decode",
"(",
"'ascii'",
")",
"result",
"=",
"result",
"[",
":",
"result",
".",
"index",
"(",
"'='",
")",
"]",
"+",
"'CI'",
"return",
"result"
] | Retrieve unique hash in a cross-platform manner:
this is how calculation identity is determined | [
"Retrieve",
"unique",
"hash",
"in",
"a",
"cross",
"-",
"platform",
"manner",
":",
"this",
"is",
"how",
"calculation",
"identity",
"is",
"determined"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/parsers/__init__.py#L145-L179 |
tilde-lab/tilde | tilde/core/symmetry.py | SymmetryFinder.refine_cell | def refine_cell(self, tilde_obj):
'''
NB only used for perovskite_tilting app
'''
try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = 'Symmetry finder error: %s' % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell)) | python | def refine_cell(self, tilde_obj):
'''
NB only used for perovskite_tilting app
'''
try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = 'Symmetry finder error: %s' % ex
else:
self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell)) | [
"def",
"refine_cell",
"(",
"self",
",",
"tilde_obj",
")",
":",
"try",
":",
"lattice",
",",
"positions",
",",
"numbers",
"=",
"spg",
".",
"refine_cell",
"(",
"tilde_obj",
"[",
"'structures'",
"]",
"[",
"-",
"1",
"]",
",",
"symprec",
"=",
"self",
".",
"accuracy",
",",
"angle_tolerance",
"=",
"self",
".",
"angle_tolerance",
")",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"error",
"=",
"'Symmetry finder error: %s'",
"%",
"ex",
"else",
":",
"self",
".",
"refinedcell",
"=",
"Atoms",
"(",
"numbers",
"=",
"numbers",
",",
"cell",
"=",
"lattice",
",",
"scaled_positions",
"=",
"positions",
",",
"pbc",
"=",
"tilde_obj",
"[",
"'structures'",
"]",
"[",
"-",
"1",
"]",
".",
"get_pbc",
"(",
")",
")",
"self",
".",
"refinedcell",
".",
"periodicity",
"=",
"sum",
"(",
"self",
".",
"refinedcell",
".",
"get_pbc",
"(",
")",
")",
"self",
".",
"refinedcell",
".",
"dims",
"=",
"abs",
"(",
"det",
"(",
"tilde_obj",
"[",
"'structures'",
"]",
"[",
"-",
"1",
"]",
".",
"cell",
")",
")"
] | NB only used for perovskite_tilting app | [
"NB",
"only",
"used",
"for",
"perovskite_tilting",
"app"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/symmetry.py#L36-L46 |
myth/pepper8 | pepper8/parser.py | Parser.parse | def parse(self):
"""
Reads all lines from the current data source and yields each FileResult objects
"""
if self.data is None:
raise ValueError('No input data provided, unable to parse')
for line in self.data:
parts = line.strip().split()
try:
path = parts[0]
code = parts[1]
path, line, char = path.split(':')[:3]
if not re.match(POSITION, line):
continue
if not re.match(POSITION, char):
continue
if not re.match(ERROR_CODE, code):
continue
if not re.match(FILEPATH, path):
continue
# For parts mismatch
except IndexError:
continue
# For unpack mismatch
except ValueError:
continue
yield path, code, line, char, ' '.join(parts[2:]) | python | def parse(self):
"""
Reads all lines from the current data source and yields each FileResult objects
"""
if self.data is None:
raise ValueError('No input data provided, unable to parse')
for line in self.data:
parts = line.strip().split()
try:
path = parts[0]
code = parts[1]
path, line, char = path.split(':')[:3]
if not re.match(POSITION, line):
continue
if not re.match(POSITION, char):
continue
if not re.match(ERROR_CODE, code):
continue
if not re.match(FILEPATH, path):
continue
# For parts mismatch
except IndexError:
continue
# For unpack mismatch
except ValueError:
continue
yield path, code, line, char, ' '.join(parts[2:]) | [
"def",
"parse",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'No input data provided, unable to parse'",
")",
"for",
"line",
"in",
"self",
".",
"data",
":",
"parts",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"try",
":",
"path",
"=",
"parts",
"[",
"0",
"]",
"code",
"=",
"parts",
"[",
"1",
"]",
"path",
",",
"line",
",",
"char",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"[",
":",
"3",
"]",
"if",
"not",
"re",
".",
"match",
"(",
"POSITION",
",",
"line",
")",
":",
"continue",
"if",
"not",
"re",
".",
"match",
"(",
"POSITION",
",",
"char",
")",
":",
"continue",
"if",
"not",
"re",
".",
"match",
"(",
"ERROR_CODE",
",",
"code",
")",
":",
"continue",
"if",
"not",
"re",
".",
"match",
"(",
"FILEPATH",
",",
"path",
")",
":",
"continue",
"# For parts mismatch",
"except",
"IndexError",
":",
"continue",
"# For unpack mismatch",
"except",
"ValueError",
":",
"continue",
"yield",
"path",
",",
"code",
",",
"line",
",",
"char",
",",
"' '",
".",
"join",
"(",
"parts",
"[",
"2",
":",
"]",
")"
] | Reads all lines from the current data source and yields each FileResult objects | [
"Reads",
"all",
"lines",
"from",
"the",
"current",
"data",
"source",
"and",
"yields",
"each",
"FileResult",
"objects"
] | train | https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/parser.py#L26-L57 |
rshipp/python-dshield | dshield.py | _get | def _get(function, return_format=None):
"""Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data.
"""
if return_format:
return requests.get(''.join([__BASE_URL, function, return_format])).text
return requests.get(''.join([__BASE_URL, function, JSON])).json() | python | def _get(function, return_format=None):
"""Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data.
"""
if return_format:
return requests.get(''.join([__BASE_URL, function, return_format])).text
return requests.get(''.join([__BASE_URL, function, JSON])).json() | [
"def",
"_get",
"(",
"function",
",",
"return_format",
"=",
"None",
")",
":",
"if",
"return_format",
":",
"return",
"requests",
".",
"get",
"(",
"''",
".",
"join",
"(",
"[",
"__BASE_URL",
",",
"function",
",",
"return_format",
"]",
")",
")",
".",
"text",
"return",
"requests",
".",
"get",
"(",
"''",
".",
"join",
"(",
"[",
"__BASE_URL",
",",
"function",
",",
"JSON",
"]",
")",
")",
".",
"json",
"(",
")"
] | Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data. | [
"Get",
"and",
"return",
"data",
"from",
"the",
"API",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L20-L27 |
rshipp/python-dshield | dshield.py | backscatter | def backscatter(date=None, rows=None, return_format=None):
"""Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data.
"""
uri = 'backscatter'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if rows:
uri = '/'.join([uri, str(rows)])
return _get(uri, return_format) | python | def backscatter(date=None, rows=None, return_format=None):
"""Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data.
"""
uri = 'backscatter'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if rows:
uri = '/'.join([uri, str(rows)])
return _get(uri, return_format) | [
"def",
"backscatter",
"(",
"date",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'backscatter'",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"if",
"rows",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"str",
"(",
"rows",
")",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data. | [
"Returns",
"possible",
"backscatter",
"data",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L30-L47 |
rshipp/python-dshield | dshield.py | ip | def ip(ip_address, return_format=None):
"""Returns a summary of the information our database holds for a
particular IP address (similar to /ipinfo.html).
In the returned data:
Count: (also reports or records) total number of packets blocked from
this IP.
Attacks: (also targets) number of unique destination IP addresses for
these packets.
:param ip_address: a valid IP address
"""
response = _get('ip/{address}'.format(address=ip_address), return_format)
if 'bad IP address' in str(response):
raise Error('Bad IP address, {address}'.format(address=ip_address))
else:
return response | python | def ip(ip_address, return_format=None):
"""Returns a summary of the information our database holds for a
particular IP address (similar to /ipinfo.html).
In the returned data:
Count: (also reports or records) total number of packets blocked from
this IP.
Attacks: (also targets) number of unique destination IP addresses for
these packets.
:param ip_address: a valid IP address
"""
response = _get('ip/{address}'.format(address=ip_address), return_format)
if 'bad IP address' in str(response):
raise Error('Bad IP address, {address}'.format(address=ip_address))
else:
return response | [
"def",
"ip",
"(",
"ip_address",
",",
"return_format",
"=",
"None",
")",
":",
"response",
"=",
"_get",
"(",
"'ip/{address}'",
".",
"format",
"(",
"address",
"=",
"ip_address",
")",
",",
"return_format",
")",
"if",
"'bad IP address'",
"in",
"str",
"(",
"response",
")",
":",
"raise",
"Error",
"(",
"'Bad IP address, {address}'",
".",
"format",
"(",
"address",
"=",
"ip_address",
")",
")",
"else",
":",
"return",
"response"
] | Returns a summary of the information our database holds for a
particular IP address (similar to /ipinfo.html).
In the returned data:
Count: (also reports or records) total number of packets blocked from
this IP.
Attacks: (also targets) number of unique destination IP addresses for
these packets.
:param ip_address: a valid IP address | [
"Returns",
"a",
"summary",
"of",
"the",
"information",
"our",
"database",
"holds",
"for",
"a",
"particular",
"IP",
"address",
"(",
"similar",
"to",
"/",
"ipinfo",
".",
"html",
")",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L57-L74 |
rshipp/python-dshield | dshield.py | port | def port(port_number, return_format=None):
"""Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number
"""
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | python | def port(port_number, return_format=None):
"""Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number
"""
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | [
"def",
"port",
"(",
"port_number",
",",
"return_format",
"=",
"None",
")",
":",
"response",
"=",
"_get",
"(",
"'port/{number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
",",
"return_format",
")",
"if",
"'bad port number'",
"in",
"str",
"(",
"response",
")",
":",
"raise",
"Error",
"(",
"'Bad port number, {number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
")",
"else",
":",
"return",
"response"
] | Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number | [
"Summary",
"information",
"about",
"a",
"particular",
"port",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L76-L91 |
rshipp/python-dshield | dshield.py | portdate | def portdate(port_number, date=None, return_format=None):
"""Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = 'portdate/{number}'.format(number=port_number)
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | python | def portdate(port_number, date=None, return_format=None):
"""Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = 'portdate/{number}'.format(number=port_number)
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | [
"def",
"portdate",
"(",
"port_number",
",",
"date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'portdate/{number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"response",
"=",
"_get",
"(",
"uri",
",",
"return_format",
")",
"if",
"'bad port number'",
"in",
"str",
"(",
"response",
")",
":",
"raise",
"Error",
"(",
"'Bad port number, {number}'",
".",
"format",
"(",
"number",
"=",
"port_number",
")",
")",
"else",
":",
"return",
"response"
] | Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object | [
"Information",
"about",
"a",
"particular",
"port",
"at",
"a",
"particular",
"date",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L93-L111 |
rshipp/python-dshield | dshield.py | topports | def topports(sort_by='records', limit=10, date=None, return_format=None):
"""Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = '/'.join(['topports', sort_by, str(limit)])
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | python | def topports(sort_by='records', limit=10, date=None, return_format=None):
"""Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object
"""
uri = '/'.join(['topports', sort_by, str(limit)])
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | [
"def",
"topports",
"(",
"sort_by",
"=",
"'records'",
",",
"limit",
"=",
"10",
",",
"date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"'topports'",
",",
"sort_by",
",",
"str",
"(",
"limit",
")",
"]",
")",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object | [
"Information",
"about",
"top",
"ports",
"for",
"a",
"particular",
"date",
"with",
"return",
"limit",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L113-L126 |
rshipp/python-dshield | dshield.py | porthistory | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today
"""
uri = 'porthistory/{port}'.format(port=port_number)
if not start_date:
# default 30 days ago
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port, {port}'.format(port=port_number))
else:
return response | python | def porthistory(port_number, start_date=None, end_date=None, return_format=None):
"""Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today
"""
uri = 'porthistory/{port}'.format(port=port_number)
if not start_date:
# default 30 days ago
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Error('Bad port, {port}'.format(port=port_number))
else:
return response | [
"def",
"porthistory",
"(",
"port_number",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'porthistory/{port}'",
".",
"format",
"(",
"port",
"=",
"port_number",
")",
"if",
"not",
"start_date",
":",
"# default 30 days ago",
"start_date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"30",
")",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"start_date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"start_date",
"]",
")",
"if",
"end_date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"end_date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"end_date",
"]",
")",
"response",
"=",
"_get",
"(",
"uri",
",",
"return_format",
")",
"if",
"'bad port number'",
"in",
"str",
"(",
"response",
")",
":",
"raise",
"Error",
"(",
"'Bad port, {port}'",
".",
"format",
"(",
"port",
"=",
"port_number",
")",
")",
"else",
":",
"return",
"response"
] | Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or datetime.date(), default is 30 days ago
:param end_date: string or datetime.date(), default is today | [
"Returns",
"port",
"data",
"for",
"a",
"range",
"of",
"dates",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L159-L191 |
rshipp/python-dshield | dshield.py | asnum | def asnum(number, limit=None, return_format=None):
"""Returns a summary of the information our database holds for a
particular ASNUM (similar to /asdetailsascii.html) with return limit.
:param limit: number of records to be returned (max 2000)
"""
uri = 'asnum/{number}'.format(number=number)
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | python | def asnum(number, limit=None, return_format=None):
"""Returns a summary of the information our database holds for a
particular ASNUM (similar to /asdetailsascii.html) with return limit.
:param limit: number of records to be returned (max 2000)
"""
uri = 'asnum/{number}'.format(number=number)
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | [
"def",
"asnum",
"(",
"number",
",",
"limit",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'asnum/{number}'",
".",
"format",
"(",
"number",
"=",
"number",
")",
"if",
"limit",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"str",
"(",
"limit",
")",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Returns a summary of the information our database holds for a
particular ASNUM (similar to /asdetailsascii.html) with return limit.
:param limit: number of records to be returned (max 2000) | [
"Returns",
"a",
"summary",
"of",
"the",
"information",
"our",
"database",
"holds",
"for",
"a",
"particular",
"ASNUM",
"(",
"similar",
"to",
"/",
"asdetailsascii",
".",
"html",
")",
"with",
"return",
"limit",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L193-L202 |
rshipp/python-dshield | dshield.py | dailysummary | def dailysummary(start_date=None, end_date=None, return_format=None):
"""Returns daily summary totals of targets, attacks and sources. Limit to
30 days at a time. (Query 2002-01-01 to present)
In the return data:
Sources: Distinct source IP addresses the packets originate from.
Targets: Distinct target IP addresses the packets were sent to.
Reports: Number of packets reported.
:param start_date: string or datetime.date(), default is today
:param end_date: string or datetime.date(), default is today
"""
uri = 'dailysummary'
if not start_date:
# default today
start_date = datetime.datetime.now()
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
return _get(uri, return_format) | python | def dailysummary(start_date=None, end_date=None, return_format=None):
"""Returns daily summary totals of targets, attacks and sources. Limit to
30 days at a time. (Query 2002-01-01 to present)
In the return data:
Sources: Distinct source IP addresses the packets originate from.
Targets: Distinct target IP addresses the packets were sent to.
Reports: Number of packets reported.
:param start_date: string or datetime.date(), default is today
:param end_date: string or datetime.date(), default is today
"""
uri = 'dailysummary'
if not start_date:
# default today
start_date = datetime.datetime.now()
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, end_date])
return _get(uri, return_format) | [
"def",
"dailysummary",
"(",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'dailysummary'",
"if",
"not",
"start_date",
":",
"# default today",
"start_date",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"start_date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"start_date",
"]",
")",
"if",
"end_date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"end_date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"end_date",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Returns daily summary totals of targets, attacks and sources. Limit to
30 days at a time. (Query 2002-01-01 to present)
In the return data:
Sources: Distinct source IP addresses the packets originate from.
Targets: Distinct target IP addresses the packets were sent to.
Reports: Number of packets reported.
:param start_date: string or datetime.date(), default is today
:param end_date: string or datetime.date(), default is today | [
"Returns",
"daily",
"summary",
"totals",
"of",
"targets",
"attacks",
"and",
"sources",
".",
"Limit",
"to",
"30",
"days",
"at",
"a",
"time",
".",
"(",
"Query",
"2002",
"-",
"01",
"-",
"01",
"to",
"present",
")"
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L204-L232 |
rshipp/python-dshield | dshield.py | daily404summary | def daily404summary(date, return_format=None):
"""Returns daily summary information of submitted 404 Error Page
Information.
:param date: string or datetime.date() (required)
"""
uri = 'daily404summary'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | python | def daily404summary(date, return_format=None):
"""Returns daily summary information of submitted 404 Error Page
Information.
:param date: string or datetime.date() (required)
"""
uri = 'daily404summary'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | [
"def",
"daily404summary",
"(",
"date",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'daily404summary'",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Returns daily summary information of submitted 404 Error Page
Information.
:param date: string or datetime.date() (required) | [
"Returns",
"daily",
"summary",
"information",
"of",
"submitted",
"404",
"Error",
"Page",
"Information",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L234-L246 |
rshipp/python-dshield | dshield.py | daily404detail | def daily404detail(date, limit=None, return_format=None):
"""Returns detail information of submitted 404 Error Page Information.
:param date: string or datetime.date() (required)
:param limit: string or int, limit for number of returned items
"""
uri = 'daily404detail'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | python | def daily404detail(date, limit=None, return_format=None):
"""Returns detail information of submitted 404 Error Page Information.
:param date: string or datetime.date() (required)
:param limit: string or int, limit for number of returned items
"""
uri = 'daily404detail'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | [
"def",
"daily404detail",
"(",
"date",
",",
"limit",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'daily404detail'",
"if",
"date",
":",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"if",
"limit",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"str",
"(",
"limit",
")",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | Returns detail information of submitted 404 Error Page Information.
:param date: string or datetime.date() (required)
:param limit: string or int, limit for number of returned items | [
"Returns",
"detail",
"information",
"of",
"submitted",
"404",
"Error",
"Page",
"Information",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L248-L262 |
rshipp/python-dshield | dshield.py | glossary | def glossary(term=None, return_format=None):
"""List of glossary terms and definitions.
:param term: a whole or parital word to "search" in the API
"""
uri = 'glossary'
if term:
uri = '/'.join([uri, term])
return _get(uri, return_format) | python | def glossary(term=None, return_format=None):
"""List of glossary terms and definitions.
:param term: a whole or parital word to "search" in the API
"""
uri = 'glossary'
if term:
uri = '/'.join([uri, term])
return _get(uri, return_format) | [
"def",
"glossary",
"(",
"term",
"=",
"None",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'glossary'",
"if",
"term",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"term",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | List of glossary terms and definitions.
:param term: a whole or parital word to "search" in the API | [
"List",
"of",
"glossary",
"terms",
"and",
"definitions",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L264-L272 |
rshipp/python-dshield | dshield.py | webhoneypotsummary | def webhoneypotsummary(date, return_format=None):
"""API data for `Webhoneypot: Web Server Log Project
<https://dshield.org/webhoneypot/>`_.
:param date: string or datetime.date() (required)
"""
uri = 'webhoneypotsummary'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | python | def webhoneypotsummary(date, return_format=None):
"""API data for `Webhoneypot: Web Server Log Project
<https://dshield.org/webhoneypot/>`_.
:param date: string or datetime.date() (required)
"""
uri = 'webhoneypotsummary'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | [
"def",
"webhoneypotsummary",
"(",
"date",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'webhoneypotsummary'",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | API data for `Webhoneypot: Web Server Log Project
<https://dshield.org/webhoneypot/>`_.
:param date: string or datetime.date() (required) | [
"API",
"data",
"for",
"Webhoneypot",
":",
"Web",
"Server",
"Log",
"Project",
"<https",
":",
"//",
"dshield",
".",
"org",
"/",
"webhoneypot",
"/",
">",
"_",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L274-L285 |
rshipp/python-dshield | dshield.py | webhoneypotbytype | def webhoneypotbytype(date, return_format=None):
"""API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
:param date: string or datetime.date() (required)
"""
uri = 'webhoneypotbytype'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | python | def webhoneypotbytype(date, return_format=None):
"""API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
:param date: string or datetime.date() (required)
"""
uri = 'webhoneypotbytype'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | [
"def",
"webhoneypotbytype",
"(",
"date",
",",
"return_format",
"=",
"None",
")",
":",
"uri",
"=",
"'webhoneypotbytype'",
"try",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"]",
")",
"except",
"AttributeError",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"uri",
",",
"date",
"]",
")",
"return",
"_get",
"(",
"uri",
",",
"return_format",
")"
] | API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
:param date: string or datetime.date() (required) | [
"API",
"data",
"for",
"Webhoneypot",
":",
"Attack",
"By",
"Type",
"<https",
":",
"//",
"isc",
".",
"sans",
".",
"edu",
"/",
"webhoneypot",
"/",
"types",
".",
"html",
">",
"_",
".",
"We",
"currently",
"use",
"a",
"set",
"of",
"regular",
"expressions",
"to",
"determine",
"the",
"type",
"of",
"attack",
"used",
"to",
"attack",
"the",
"honeypot",
".",
"Output",
"is",
"the",
"top",
"30",
"attacks",
"for",
"the",
"last",
"month",
"."
] | train | https://github.com/rshipp/python-dshield/blob/1b003d0dfac0bc2ee8b86ca5f1a44b765b8cc6e0/dshield.py#L287-L300 |
albertyw/syspath | syspath/syspath.py | _append_path | def _append_path(new_path): # type: (str) -> None
""" Given a path string, append it to sys.path """
for path in sys.path:
path = os.path.abspath(path)
if new_path == path:
return
sys.path.append(new_path) | python | def _append_path(new_path): # type: (str) -> None
""" Given a path string, append it to sys.path """
for path in sys.path:
path = os.path.abspath(path)
if new_path == path:
return
sys.path.append(new_path) | [
"def",
"_append_path",
"(",
"new_path",
")",
":",
"# type: (str) -> None",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"new_path",
"==",
"path",
":",
"return",
"sys",
".",
"path",
".",
"append",
"(",
"new_path",
")"
] | Given a path string, append it to sys.path | [
"Given",
"a",
"path",
"string",
"append",
"it",
"to",
"sys",
".",
"path"
] | train | https://github.com/albertyw/syspath/blob/af219aecfecb1ef3130165121dcad6d2e1a269b7/syspath/syspath.py#L6-L12 |
albertyw/syspath | syspath/syspath.py | _caller_path | def _caller_path(index): # type: (int) -> str
"""
Get the caller's file path, by the index of the stack,
does not work when the caller is stdin through a CLI python
"""
module = None
stack = inspect.stack()
while not module:
if index >= len(stack):
raise RuntimeError("Cannot find import path")
frame = stack[index]
module = inspect.getmodule(frame[0])
index += 1
filename = module.__file__
path = os.path.dirname(os.path.realpath(filename))
return path | python | def _caller_path(index): # type: (int) -> str
"""
Get the caller's file path, by the index of the stack,
does not work when the caller is stdin through a CLI python
"""
module = None
stack = inspect.stack()
while not module:
if index >= len(stack):
raise RuntimeError("Cannot find import path")
frame = stack[index]
module = inspect.getmodule(frame[0])
index += 1
filename = module.__file__
path = os.path.dirname(os.path.realpath(filename))
return path | [
"def",
"_caller_path",
"(",
"index",
")",
":",
"# type: (int) -> str",
"module",
"=",
"None",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"while",
"not",
"module",
":",
"if",
"index",
">=",
"len",
"(",
"stack",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot find import path\"",
")",
"frame",
"=",
"stack",
"[",
"index",
"]",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"index",
"+=",
"1",
"filename",
"=",
"module",
".",
"__file__",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"filename",
")",
")",
"return",
"path"
] | Get the caller's file path, by the index of the stack,
does not work when the caller is stdin through a CLI python | [
"Get",
"the",
"caller",
"s",
"file",
"path",
"by",
"the",
"index",
"of",
"the",
"stack",
"does",
"not",
"work",
"when",
"the",
"caller",
"is",
"stdin",
"through",
"a",
"CLI",
"python"
] | train | https://github.com/albertyw/syspath/blob/af219aecfecb1ef3130165121dcad6d2e1a269b7/syspath/syspath.py#L15-L30 |
albertyw/syspath | syspath/syspath.py | get_current_path | def get_current_path(index=2): # type: (int) -> str
"""
Get the caller's path to sys.path
If the caller is a CLI through stdin, the current working directory is used
"""
try:
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
return path | python | def get_current_path(index=2): # type: (int) -> str
"""
Get the caller's path to sys.path
If the caller is a CLI through stdin, the current working directory is used
"""
try:
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
return path | [
"def",
"get_current_path",
"(",
"index",
"=",
"2",
")",
":",
"# type: (int) -> str",
"try",
":",
"path",
"=",
"_caller_path",
"(",
"index",
")",
"except",
"RuntimeError",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"return",
"path"
] | Get the caller's path to sys.path
If the caller is a CLI through stdin, the current working directory is used | [
"Get",
"the",
"caller",
"s",
"path",
"to",
"sys",
".",
"path",
"If",
"the",
"caller",
"is",
"a",
"CLI",
"through",
"stdin",
"the",
"current",
"working",
"directory",
"is",
"used"
] | train | https://github.com/albertyw/syspath/blob/af219aecfecb1ef3130165121dcad6d2e1a269b7/syspath/syspath.py#L33-L42 |
albertyw/syspath | syspath/syspath.py | get_git_root | def get_git_root(index=3): # type: (int) -> str
"""
Get the path of the git root directory of the caller's file
Raises a RuntimeError if a git repository cannot be found
"""
path = get_current_path(index=index)
while True:
git_path = os.path.join(path, '.git')
if os.path.isdir(git_path):
return path
if os.path.dirname(path) == path:
raise RuntimeError("Cannot find git root")
path = os.path.split(path)[0] | python | def get_git_root(index=3): # type: (int) -> str
"""
Get the path of the git root directory of the caller's file
Raises a RuntimeError if a git repository cannot be found
"""
path = get_current_path(index=index)
while True:
git_path = os.path.join(path, '.git')
if os.path.isdir(git_path):
return path
if os.path.dirname(path) == path:
raise RuntimeError("Cannot find git root")
path = os.path.split(path)[0] | [
"def",
"get_git_root",
"(",
"index",
"=",
"3",
")",
":",
"# type: (int) -> str",
"path",
"=",
"get_current_path",
"(",
"index",
"=",
"index",
")",
"while",
"True",
":",
"git_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"git_path",
")",
":",
"return",
"path",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"==",
"path",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot find git root\"",
")",
"path",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"0",
"]"
] | Get the path of the git root directory of the caller's file
Raises a RuntimeError if a git repository cannot be found | [
"Get",
"the",
"path",
"of",
"the",
"git",
"root",
"directory",
"of",
"the",
"caller",
"s",
"file",
"Raises",
"a",
"RuntimeError",
"if",
"a",
"git",
"repository",
"cannot",
"be",
"found"
] | train | https://github.com/albertyw/syspath/blob/af219aecfecb1ef3130165121dcad6d2e1a269b7/syspath/syspath.py#L55-L67 |
albertyw/syspath | syspath/syspath.py | get_parent_path | def get_parent_path(index=2): # type: (int) -> str
"""
Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used
"""
try:
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
path = os.path.abspath(os.path.join(path, os.pardir))
return path | python | def get_parent_path(index=2): # type: (int) -> str
"""
Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used
"""
try:
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
path = os.path.abspath(os.path.join(path, os.pardir))
return path | [
"def",
"get_parent_path",
"(",
"index",
"=",
"2",
")",
":",
"# type: (int) -> str",
"try",
":",
"path",
"=",
"_caller_path",
"(",
"index",
")",
"except",
"RuntimeError",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"os",
".",
"pardir",
")",
")",
"return",
"path"
] | Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used | [
"Get",
"the",
"caller",
"s",
"parent",
"path",
"to",
"sys",
".",
"path",
"If",
"the",
"caller",
"is",
"a",
"CLI",
"through",
"stdin",
"the",
"parent",
"of",
"the",
"current",
"working",
"directory",
"is",
"used"
] | train | https://github.com/albertyw/syspath/blob/af219aecfecb1ef3130165121dcad6d2e1a269b7/syspath/syspath.py#L80-L91 |
oscarlazoarjona/fast | build/lib/fast/rk4.py | write_rk4 | def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1):
r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all files will be stored. It must end with ``/``.
- ``name`` - A string with the name of the experiment. All files produced will begin with this name.
- ``laser`` - A list of Laser objects (see the Laser class).
- ``omega`` - A matrix or list of lists containing the frequency differences `\omega_{ij}`.
- ``gamma`` - A matrix or list of lists containing the spontaneous decay frequencies `\gamma_{ij}`.
- ``r`` - A list of three matrices or lists of lists containing the components of the position operator `r_{-1ij},r_{0ij},r_{1ij}`.
- ``Lij`` - A list with elements of the form ``[i,j,[l1,l2,...]]`` representing the sets `L_{ij}` of which lasers excite wich transitions. It does not need to contain an element for all ``i,j`` pairs, but only those which have a laser that excites them.
- ``Omega`` - A floating point number indicating the frequency scale for the equations. The frequencies ``omega`` and ``gamma`` are divided by this number. If ``None`` the equations and the input are taken in SI units.
OUTPUT:
- A file ``name.f90`` is created in ``path``.
"""
global omega_rescaled
t0=time()
Ne=len(omega[0])
Nl=len(laser)
if states==None: states=range(1,Ne+1)
#We make some checks
for i in range(Ne):
for j in range(Ne):
b1=not ('.' in str(omega[i][j]) or 'e' in str(omega[i][j]))
if b1: raise ValueError,'omega must be composed of floating point numbers.'
b2=not ('.' in str(gamma[i][j]) or 'e' in str(gamma[i][j]))
if b2: raise ValueError,'gamma must be composed of floating point numbers.'
#We rescale the frequencies as requested.
#~ if Omega != None:
#~ omega_rescaled=[[omega[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
#~ #gamma=[[gamma[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
#~ else:
#~ omega_rescaled=omega[:]
omega_rescaled=omega[:]
#We determine wether it is possible to eliminate explicit time-dependance
theta=find_phase_transformation(Ne,Nl,r,Lij)
#We find the detunings if required
#We construct the correspondence i <-> I between degenerate and non-degenerate indices.
i_d,I_nd,Nnd=calculate_iI_correspondence(omega)
#We get wich transitions each laser induces
detunings,detuningsij=laser_detunings(Lij,Nl,i_d,I_nd,Nnd)
#We get how many transitions each laser induces
detuning_indices=[len(detunings[i]) for i in range(Nl)]
#The number of detunings
Nd=sum([len(detunings[l]) for l in range(Nl)])
combinations=detuning_combinations(detuning_indices)
code0='''program evolution_rk4
implicit none
complex*16, dimension('''+str(Ne*(Ne+1)/2-1)+') :: x,k1,k2,k3,k4\n'
code0+=''' real*8 :: dt,t,ddelta,delta,delta0
integer :: i,j,n,ldelta,ndelta,detuning_index,n_aprox,n_mod
logical :: print_steps,run_spectrum\n'''
code0+=' real*8, dimension('+str(Nl)+') :: E0,detuning_knob\n'
code0+=' real*8, dimension('+str(Nd)+') :: detuning\n\n'
code0+=" open(unit=1,file='"+path+name+".dat',status='unknown')\n\n"
code0+=' n_aprox=1500\n'
code0+=' !We load the parameters\n'
code0+=" open(unit=2,file='"+path+name+"_params.dat',status='unknown')\n"
code0+=''' read(2,*) n
read(2,*) dt
read(2,*) print_steps
read(2,*) x
read(2,*) E0\n'''
code0+=' read(2,*) detuning_knob\n'
code0+=' read(2,*) run_spectrum\n\n'
code0+=''' if (run_spectrum) then
read(2,*) ldelta
read(2,*) ndelta
read(2,*) ddelta
close(2)
delta0=detuning_knob(ldelta)
n_mod=ndelta/n_aprox
else
ldelta=1; ndelta=1; ddelta=0; delta=0
close(2)
n_mod=n/n_aprox
end if
if (n_mod==0) n_mod=1\n\n\n'''
#We add the code to caculate all the initial detunings for each laser.
code0+=' !We calculate the initial detunings.\n'
#We find the minimal frequency corresponding to each laser.
omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)
det_index=1
for l in range(Nl):
omega0=omega_min[l]
for p in detuningsij[l]:
code0+=' detuning('+str(det_index)+')='
code0+=format_double(omega0-omega_rescaled[p[0]][p[1]])+'+detuning_knob('+str(l+1)+')\n'
det_index+=1
code0+='\n'
code0+=''' t=0
if (.not. run_spectrum) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))\n'''
code0+=''' !We start the detuning variation\n'''
code0+=' delta=detuning_knob(ldelta)\n'
code0+=''' do j=1,ndelta
!We run the Runge Kutta method
t=0.0
do i=1,n-1\n'''
code0+=' call f(x , t , k1, E0, detuning, detuning_knob)\n'
code0+=' call f(x+0.5*k1*dt, t+dt*0.5, k2, E0, detuning, detuning_knob)\n'
code0+=' call f(x+0.5*k2*dt, t+dt*0.5, k3, E0, detuning, detuning_knob)\n'
code0+=' call f(x +k3*dt, t+dt , k4, E0, detuning, detuning_knob)\n'
code0+=''' x= x+(k1+2*k2+2*k3+k4)*dt/6
if (print_steps.and. .not. run_spectrum) print*,'t=',t,'delta=',delta
t= t+ dt
if (isnan(real(x(1)))) stop 1
if (.not. run_spectrum .and. mod(i,n_mod)==0) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))
end do
if (print_steps) print*, 'delta=',delta,'percentage=',100*(delta-delta0)/(ddelta*ndelta)
!We recalculate the detunings
if (run_spectrum) then
if (mod(j,n_mod)==0) WRITE(1,*) delta,real(x),imag(x('''+str(Ne)+''':))
delta=delta+ddelta
detuning_knob(ldelta)=detuning_knob(ldelta)+ddelta\n'''
#We add the code to caculate all detunings for each laser
#This way of assigining a global index ll to the detunings ammounts to
# ll= number_of_previous_detunings
# + number_of_detuning_ordered_by_row_and_from_left_to_right_column
#like this
#->
#-> ->
#-> -> ->
#for each l
#We find the minimal frequency corresponding to each laser
omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)
det_index=1
for l in range(Nl):
omega0=omega_min[l]
code0+=' if (ldelta=='+str(l+1)+') then\n'
for p in detuningsij[l]:
code0+=' detuning('+str(det_index)+')=detuning('+str(det_index)+')'
#code0+='+('+str(omega0-omega_rescaled[p[0]][p[1]])+'+ddelta\n'
code0+='+ddelta\n'
det_index+=1
code0+=' end if\n'
code0+=''' end if
end do
close(1)
end program\n\n'''
code0+='subroutine f(x,t,y, E0, detuning,detuning_knob)\n'
code0+=''' implicit none
real*8, intent(in) :: t\n'''
code0+=' complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(in) :: x\n'
code0+=' complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(out) :: y\n'
code0+=' real*8, dimension('+str(Nl)+'), intent(in) :: E0,detuning_knob\n'
code0+=' real*8, dimension('+str(Nd)+'), intent(in) :: detuning\n\n'
code0+=' complex*16 :: I,fact,aux\n'
code0+=' real*8 :: rho11\n\n'
code0+=' I=(0,1D0)\n'
#We establish the scaling of the equations
#~ if Omega==None:
#~ h =1.054571726e-34; e=1.602176565e-19
#~ code0+=' fact=I*'+str(e/h)+'\n'
#~ else:
#~ #code0+=' fact=I*'+str(float(Omega/sqrt(2)))+'\n'
#~ code0+=' fact=I*'+str(float(1/sqrt(2)))+'\n'
#~ #code0+=' fact=I*'+str(float(1/(sqrt(2)*Omega)))+'\n'
code0+=' fact=I*'+format_double(float(1/sqrt(2)))+'\n'
#We give the code to calculate rho11
code0+=' rho11=1\n'
for i in range(1,Ne):
code0+=' rho11=rho11 -x('+str(i)+')\n'
code0+='\n\n'
####################################################################
#We produce the code for the first order equations.
####################################################################
if len(theta)>0:
code=''
for mu in range(1,Ne*(Ne+1)/2):
i,j,s=IJ(mu,Ne)
#print 'ecuacion mu=',mu,',i,j=',i,j
eqmu=' y('+str(mu)+')= 0\n'
####################################################################
#We add the terms associated with the effective hamiltonian
#other than those associated with the phase transformation.
for k in range(1,Ne+1):
#Case 1
if k>=j:
for l in Lij[i-1][k-1]:
if k>i:
#print 'E0^',l,-1,'r',i,k,'rho',k,j,'case 1.1'
eqmu+=add_line(Ne,mu,'+',laser,l,-1, r,i,k, k,j)
elif k<i:
#print 'E0^',l, 1,'r',i,k,'rho',k,j,'case 1.2'
eqmu+=add_line(Ne,mu,'+',laser,l, 1, r,i,k, k,j)
#Case 2
elif k<j:
for l in Lij[i-1][k-1]:
if k>i:
#print 'E0^',l,-1,'r',i,k,'rhoa',j,k,'case 2.1'
eqmu+=add_line(Ne,mu,'+',laser,l,-1, r,i,k, j,k,True)
elif k<i:
#print 'E0^',l, 1,'r',i,k,'rhoa',j,k,'case 2.2'
eqmu+=add_line(Ne,mu,'+',laser,l, 1, r,i,k, j,k,True)
#Case 3
if k<=i:
for l in Lij[k-1][j-1]:
if k<j:
#print 'E0^',l,-1,'r',k,j,'rho',i,k,'case 3.1'
eqmu+=add_line(Ne,mu,'-',laser,l,-1, r,k,j, i,k)
elif k>j:
#print 'E0^',l, 1,'r',k,j,'rho',i,k,'case 3.2'
eqmu+=add_line(Ne,mu,'-',laser,l, 1, r,k,j, i,k)
#Case 4
elif k>i:
for l in Lij[k-1][j-1]:
if k<j:
#print 'E0^',l,-1,'r',k,j,'rhoa',k,i,'case 4.1'
eqmu+=add_line(Ne,mu,'-',laser,l,-1, r,k,j, k,i,True)
elif k>j:
#print 'E0^',l, 1,'r',k,j,'rhoa',k,i,'case 4.2'
eqmu+=add_line(Ne,mu,'-',laser,l, 1, r,k,j, k,i,True)
eqmu+=' y('+str(mu)+')=y('+str(mu)+')*fact\n'
####################################################################
#We add the terms associated with the phase transformation.
extra=Theta(i,j,theta,omega_rescaled,omega_min,detunings,detuningsij,
combinations,detuning_indices,Lij,i_d,I_nd,Nnd,
verbose=verbose,states=states)
if extra!='':
eqmu+=' y('+str(mu)+')=y('+str(mu)+') + I*('+extra+')*x('+str(mu)+')\n'
####################################################################
#~ if i==j:
#~ for k in range(1,Ne+1):
#~ if k < i:
#~ muii=Mu(i,i,s=1,N=Ne)
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(muii)+')\n'
#~ elif k > i:
#~ mukk=Mu(k,k,s=1,N=Ne)
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(mukk)+')\n'
#~ eqmu+='\n'
#~ else:
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][j-1]/2)+')*x('+str(mu)+')\n'
#~
####################################################################
code+=eqmu+'\n'
#We add the terms associated with spontaneous decay.
#First for populations.
for i in range(2,Ne+1):
mu=Mu(i,i,1,Ne)
for k in range(1,Ne+1):
gams=0
if k<i:
gams+=gamma[i-1][k-1]
elif k>i:
nu=Mu(k,k,1,Ne)
ga=gamma[i-1][k-1]
if ga != 0:
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(ga)+')*x('+str(nu)+')\n'
if gams!=0:
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#And now for coherences
for i in range(1,Ne+1):
for j in range(1,i):
gams=gamma[i-1][j-1]/2
if gams!=0:
for a in range(i+1,Ne+1):
mu=Mu(a,i,+1,Ne)
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#~ mu=Mu(a,i,-1,Ne)
#~ code+=' y('+str(mu)+')=y('+str(mu)+')'
#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
for b in range(1,i):
mu=Mu(i,b,+1,Ne)
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#~ mu=Mu(i,b,-1,Ne)
#~ code+=' y('+str(mu)+')=y('+str(mu)+')'
#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
####################################################################
####################################################################
####################################################################
#code+=' y=y/'+str(Omega)+'\n'
f=file(path+name+'.f90','w')
code=code0+code+'end subroutine\n'
f.write(code)
f.close()
return time()-t0
else:
print 'There was no phase transformation capable of eliminating explicit time dependance.' | python | def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1):
r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all files will be stored. It must end with ``/``.
- ``name`` - A string with the name of the experiment. All files produced will begin with this name.
- ``laser`` - A list of Laser objects (see the Laser class).
- ``omega`` - A matrix or list of lists containing the frequency differences `\omega_{ij}`.
- ``gamma`` - A matrix or list of lists containing the spontaneous decay frequencies `\gamma_{ij}`.
- ``r`` - A list of three matrices or lists of lists containing the components of the position operator `r_{-1ij},r_{0ij},r_{1ij}`.
- ``Lij`` - A list with elements of the form ``[i,j,[l1,l2,...]]`` representing the sets `L_{ij}` of which lasers excite wich transitions. It does not need to contain an element for all ``i,j`` pairs, but only those which have a laser that excites them.
- ``Omega`` - A floating point number indicating the frequency scale for the equations. The frequencies ``omega`` and ``gamma`` are divided by this number. If ``None`` the equations and the input are taken in SI units.
OUTPUT:
- A file ``name.f90`` is created in ``path``.
"""
global omega_rescaled
t0=time()
Ne=len(omega[0])
Nl=len(laser)
if states==None: states=range(1,Ne+1)
#We make some checks
for i in range(Ne):
for j in range(Ne):
b1=not ('.' in str(omega[i][j]) or 'e' in str(omega[i][j]))
if b1: raise ValueError,'omega must be composed of floating point numbers.'
b2=not ('.' in str(gamma[i][j]) or 'e' in str(gamma[i][j]))
if b2: raise ValueError,'gamma must be composed of floating point numbers.'
#We rescale the frequencies as requested.
#~ if Omega != None:
#~ omega_rescaled=[[omega[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
#~ #gamma=[[gamma[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
#~ else:
#~ omega_rescaled=omega[:]
omega_rescaled=omega[:]
#We determine wether it is possible to eliminate explicit time-dependance
theta=find_phase_transformation(Ne,Nl,r,Lij)
#We find the detunings if required
#We construct the correspondence i <-> I between degenerate and non-degenerate indices.
i_d,I_nd,Nnd=calculate_iI_correspondence(omega)
#We get wich transitions each laser induces
detunings,detuningsij=laser_detunings(Lij,Nl,i_d,I_nd,Nnd)
#We get how many transitions each laser induces
detuning_indices=[len(detunings[i]) for i in range(Nl)]
#The number of detunings
Nd=sum([len(detunings[l]) for l in range(Nl)])
combinations=detuning_combinations(detuning_indices)
code0='''program evolution_rk4
implicit none
complex*16, dimension('''+str(Ne*(Ne+1)/2-1)+') :: x,k1,k2,k3,k4\n'
code0+=''' real*8 :: dt,t,ddelta,delta,delta0
integer :: i,j,n,ldelta,ndelta,detuning_index,n_aprox,n_mod
logical :: print_steps,run_spectrum\n'''
code0+=' real*8, dimension('+str(Nl)+') :: E0,detuning_knob\n'
code0+=' real*8, dimension('+str(Nd)+') :: detuning\n\n'
code0+=" open(unit=1,file='"+path+name+".dat',status='unknown')\n\n"
code0+=' n_aprox=1500\n'
code0+=' !We load the parameters\n'
code0+=" open(unit=2,file='"+path+name+"_params.dat',status='unknown')\n"
code0+=''' read(2,*) n
read(2,*) dt
read(2,*) print_steps
read(2,*) x
read(2,*) E0\n'''
code0+=' read(2,*) detuning_knob\n'
code0+=' read(2,*) run_spectrum\n\n'
code0+=''' if (run_spectrum) then
read(2,*) ldelta
read(2,*) ndelta
read(2,*) ddelta
close(2)
delta0=detuning_knob(ldelta)
n_mod=ndelta/n_aprox
else
ldelta=1; ndelta=1; ddelta=0; delta=0
close(2)
n_mod=n/n_aprox
end if
if (n_mod==0) n_mod=1\n\n\n'''
#We add the code to caculate all the initial detunings for each laser.
code0+=' !We calculate the initial detunings.\n'
#We find the minimal frequency corresponding to each laser.
omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)
det_index=1
for l in range(Nl):
omega0=omega_min[l]
for p in detuningsij[l]:
code0+=' detuning('+str(det_index)+')='
code0+=format_double(omega0-omega_rescaled[p[0]][p[1]])+'+detuning_knob('+str(l+1)+')\n'
det_index+=1
code0+='\n'
code0+=''' t=0
if (.not. run_spectrum) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))\n'''
code0+=''' !We start the detuning variation\n'''
code0+=' delta=detuning_knob(ldelta)\n'
code0+=''' do j=1,ndelta
!We run the Runge Kutta method
t=0.0
do i=1,n-1\n'''
code0+=' call f(x , t , k1, E0, detuning, detuning_knob)\n'
code0+=' call f(x+0.5*k1*dt, t+dt*0.5, k2, E0, detuning, detuning_knob)\n'
code0+=' call f(x+0.5*k2*dt, t+dt*0.5, k3, E0, detuning, detuning_knob)\n'
code0+=' call f(x +k3*dt, t+dt , k4, E0, detuning, detuning_knob)\n'
code0+=''' x= x+(k1+2*k2+2*k3+k4)*dt/6
if (print_steps.and. .not. run_spectrum) print*,'t=',t,'delta=',delta
t= t+ dt
if (isnan(real(x(1)))) stop 1
if (.not. run_spectrum .and. mod(i,n_mod)==0) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))
end do
if (print_steps) print*, 'delta=',delta,'percentage=',100*(delta-delta0)/(ddelta*ndelta)
!We recalculate the detunings
if (run_spectrum) then
if (mod(j,n_mod)==0) WRITE(1,*) delta,real(x),imag(x('''+str(Ne)+''':))
delta=delta+ddelta
detuning_knob(ldelta)=detuning_knob(ldelta)+ddelta\n'''
#We add the code to caculate all detunings for each laser
#This way of assigining a global index ll to the detunings ammounts to
# ll= number_of_previous_detunings
# + number_of_detuning_ordered_by_row_and_from_left_to_right_column
#like this
#->
#-> ->
#-> -> ->
#for each l
#We find the minimal frequency corresponding to each laser
omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)
det_index=1
for l in range(Nl):
omega0=omega_min[l]
code0+=' if (ldelta=='+str(l+1)+') then\n'
for p in detuningsij[l]:
code0+=' detuning('+str(det_index)+')=detuning('+str(det_index)+')'
#code0+='+('+str(omega0-omega_rescaled[p[0]][p[1]])+'+ddelta\n'
code0+='+ddelta\n'
det_index+=1
code0+=' end if\n'
code0+=''' end if
end do
close(1)
end program\n\n'''
code0+='subroutine f(x,t,y, E0, detuning,detuning_knob)\n'
code0+=''' implicit none
real*8, intent(in) :: t\n'''
code0+=' complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(in) :: x\n'
code0+=' complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(out) :: y\n'
code0+=' real*8, dimension('+str(Nl)+'), intent(in) :: E0,detuning_knob\n'
code0+=' real*8, dimension('+str(Nd)+'), intent(in) :: detuning\n\n'
code0+=' complex*16 :: I,fact,aux\n'
code0+=' real*8 :: rho11\n\n'
code0+=' I=(0,1D0)\n'
#We establish the scaling of the equations
#~ if Omega==None:
#~ h =1.054571726e-34; e=1.602176565e-19
#~ code0+=' fact=I*'+str(e/h)+'\n'
#~ else:
#~ #code0+=' fact=I*'+str(float(Omega/sqrt(2)))+'\n'
#~ code0+=' fact=I*'+str(float(1/sqrt(2)))+'\n'
#~ #code0+=' fact=I*'+str(float(1/(sqrt(2)*Omega)))+'\n'
code0+=' fact=I*'+format_double(float(1/sqrt(2)))+'\n'
#We give the code to calculate rho11
code0+=' rho11=1\n'
for i in range(1,Ne):
code0+=' rho11=rho11 -x('+str(i)+')\n'
code0+='\n\n'
####################################################################
#We produce the code for the first order equations.
####################################################################
if len(theta)>0:
code=''
for mu in range(1,Ne*(Ne+1)/2):
i,j,s=IJ(mu,Ne)
#print 'ecuacion mu=',mu,',i,j=',i,j
eqmu=' y('+str(mu)+')= 0\n'
####################################################################
#We add the terms associated with the effective hamiltonian
#other than those associated with the phase transformation.
for k in range(1,Ne+1):
#Case 1
if k>=j:
for l in Lij[i-1][k-1]:
if k>i:
#print 'E0^',l,-1,'r',i,k,'rho',k,j,'case 1.1'
eqmu+=add_line(Ne,mu,'+',laser,l,-1, r,i,k, k,j)
elif k<i:
#print 'E0^',l, 1,'r',i,k,'rho',k,j,'case 1.2'
eqmu+=add_line(Ne,mu,'+',laser,l, 1, r,i,k, k,j)
#Case 2
elif k<j:
for l in Lij[i-1][k-1]:
if k>i:
#print 'E0^',l,-1,'r',i,k,'rhoa',j,k,'case 2.1'
eqmu+=add_line(Ne,mu,'+',laser,l,-1, r,i,k, j,k,True)
elif k<i:
#print 'E0^',l, 1,'r',i,k,'rhoa',j,k,'case 2.2'
eqmu+=add_line(Ne,mu,'+',laser,l, 1, r,i,k, j,k,True)
#Case 3
if k<=i:
for l in Lij[k-1][j-1]:
if k<j:
#print 'E0^',l,-1,'r',k,j,'rho',i,k,'case 3.1'
eqmu+=add_line(Ne,mu,'-',laser,l,-1, r,k,j, i,k)
elif k>j:
#print 'E0^',l, 1,'r',k,j,'rho',i,k,'case 3.2'
eqmu+=add_line(Ne,mu,'-',laser,l, 1, r,k,j, i,k)
#Case 4
elif k>i:
for l in Lij[k-1][j-1]:
if k<j:
#print 'E0^',l,-1,'r',k,j,'rhoa',k,i,'case 4.1'
eqmu+=add_line(Ne,mu,'-',laser,l,-1, r,k,j, k,i,True)
elif k>j:
#print 'E0^',l, 1,'r',k,j,'rhoa',k,i,'case 4.2'
eqmu+=add_line(Ne,mu,'-',laser,l, 1, r,k,j, k,i,True)
eqmu+=' y('+str(mu)+')=y('+str(mu)+')*fact\n'
####################################################################
#We add the terms associated with the phase transformation.
extra=Theta(i,j,theta,omega_rescaled,omega_min,detunings,detuningsij,
combinations,detuning_indices,Lij,i_d,I_nd,Nnd,
verbose=verbose,states=states)
if extra!='':
eqmu+=' y('+str(mu)+')=y('+str(mu)+') + I*('+extra+')*x('+str(mu)+')\n'
####################################################################
#~ if i==j:
#~ for k in range(1,Ne+1):
#~ if k < i:
#~ muii=Mu(i,i,s=1,N=Ne)
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(muii)+')\n'
#~ elif k > i:
#~ mukk=Mu(k,k,s=1,N=Ne)
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(mukk)+')\n'
#~ eqmu+='\n'
#~ else:
#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][j-1]/2)+')*x('+str(mu)+')\n'
#~
####################################################################
code+=eqmu+'\n'
#We add the terms associated with spontaneous decay.
#First for populations.
for i in range(2,Ne+1):
mu=Mu(i,i,1,Ne)
for k in range(1,Ne+1):
gams=0
if k<i:
gams+=gamma[i-1][k-1]
elif k>i:
nu=Mu(k,k,1,Ne)
ga=gamma[i-1][k-1]
if ga != 0:
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(ga)+')*x('+str(nu)+')\n'
if gams!=0:
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#And now for coherences
for i in range(1,Ne+1):
for j in range(1,i):
gams=gamma[i-1][j-1]/2
if gams!=0:
for a in range(i+1,Ne+1):
mu=Mu(a,i,+1,Ne)
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#~ mu=Mu(a,i,-1,Ne)
#~ code+=' y('+str(mu)+')=y('+str(mu)+')'
#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
for b in range(1,i):
mu=Mu(i,b,+1,Ne)
code+=' y('+str(mu)+')=y('+str(mu)+')'
code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
#~ mu=Mu(i,b,-1,Ne)
#~ code+=' y('+str(mu)+')=y('+str(mu)+')'
#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'
####################################################################
####################################################################
####################################################################
#code+=' y=y/'+str(Omega)+'\n'
f=file(path+name+'.f90','w')
code=code0+code+'end subroutine\n'
f.write(code)
f.close()
return time()-t0
else:
print 'There was no phase transformation capable of eliminating explicit time dependance.' | [
"def",
"write_rk4",
"(",
"path",
",",
"name",
",",
"laser",
",",
"omega",
",",
"gamma",
",",
"r",
",",
"Lij",
",",
"states",
"=",
"None",
",",
"verbose",
"=",
"1",
")",
":",
"global",
"omega_rescaled",
"t0",
"=",
"time",
"(",
")",
"Ne",
"=",
"len",
"(",
"omega",
"[",
"0",
"]",
")",
"Nl",
"=",
"len",
"(",
"laser",
")",
"if",
"states",
"==",
"None",
":",
"states",
"=",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
"#We make some checks",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"b1",
"=",
"not",
"(",
"'.'",
"in",
"str",
"(",
"omega",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"or",
"'e'",
"in",
"str",
"(",
"omega",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
"if",
"b1",
":",
"raise",
"ValueError",
",",
"'omega must be composed of floating point numbers.'",
"b2",
"=",
"not",
"(",
"'.'",
"in",
"str",
"(",
"gamma",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"or",
"'e'",
"in",
"str",
"(",
"gamma",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
"if",
"b2",
":",
"raise",
"ValueError",
",",
"'gamma must be composed of floating point numbers.'",
"#We rescale the frequencies as requested.",
"#~ if Omega != None:",
"#~ omega_rescaled=[[omega[i][j]/Omega for j in range(Ne)] for i in range(Ne)]",
"#~ #gamma=[[gamma[i][j]/Omega for j in range(Ne)] for i in range(Ne)]",
"#~ else:",
"#~ omega_rescaled=omega[:]",
"omega_rescaled",
"=",
"omega",
"[",
":",
"]",
"#We determine wether it is possible to eliminate explicit time-dependance",
"theta",
"=",
"find_phase_transformation",
"(",
"Ne",
",",
"Nl",
",",
"r",
",",
"Lij",
")",
"#We find the detunings if required",
"#We construct the correspondence i <-> I between degenerate and non-degenerate indices.",
"i_d",
",",
"I_nd",
",",
"Nnd",
"=",
"calculate_iI_correspondence",
"(",
"omega",
")",
"#We get wich transitions each laser induces",
"detunings",
",",
"detuningsij",
"=",
"laser_detunings",
"(",
"Lij",
",",
"Nl",
",",
"i_d",
",",
"I_nd",
",",
"Nnd",
")",
"#We get how many transitions each laser induces",
"detuning_indices",
"=",
"[",
"len",
"(",
"detunings",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Nl",
")",
"]",
"#The number of detunings",
"Nd",
"=",
"sum",
"(",
"[",
"len",
"(",
"detunings",
"[",
"l",
"]",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"combinations",
"=",
"detuning_combinations",
"(",
"detuning_indices",
")",
"code0",
"=",
"'''program evolution_rk4\n\timplicit none\n\tcomplex*16, dimension('''",
"+",
"str",
"(",
"Ne",
"*",
"(",
"Ne",
"+",
"1",
")",
"/",
"2",
"-",
"1",
")",
"+",
"') :: x,k1,k2,k3,k4\\n'",
"code0",
"+=",
"''' real*8 :: dt,t,ddelta,delta,delta0\n\tinteger :: i,j,n,ldelta,ndelta,detuning_index,n_aprox,n_mod\n\n\tlogical :: print_steps,run_spectrum\\n'''",
"code0",
"+=",
"' real*8, dimension('",
"+",
"str",
"(",
"Nl",
")",
"+",
"') :: E0,detuning_knob\\n'",
"code0",
"+=",
"' real*8, dimension('",
"+",
"str",
"(",
"Nd",
")",
"+",
"') :: detuning\\n\\n'",
"code0",
"+=",
"\" open(unit=1,file='\"",
"+",
"path",
"+",
"name",
"+",
"\".dat',status='unknown')\\n\\n\"",
"code0",
"+=",
"' n_aprox=1500\\n'",
"code0",
"+=",
"' !We load the parameters\\n'",
"code0",
"+=",
"\" open(unit=2,file='\"",
"+",
"path",
"+",
"name",
"+",
"\"_params.dat',status='unknown')\\n\"",
"code0",
"+=",
"''' read(2,*) n\n read(2,*) dt\n read(2,*) print_steps\n read(2,*) x\n read(2,*) E0\\n'''",
"code0",
"+=",
"' read(2,*) detuning_knob\\n'",
"code0",
"+=",
"' read(2,*) run_spectrum\\n\\n'",
"code0",
"+=",
"''' if (run_spectrum) then\n\t\tread(2,*) ldelta\n\t\tread(2,*) ndelta\n\t\tread(2,*) ddelta\n\t\tclose(2)\n\t\tdelta0=detuning_knob(ldelta)\n\t\tn_mod=ndelta/n_aprox\n else\n\t\tldelta=1; ndelta=1; ddelta=0; delta=0\n\t\tclose(2)\n\t\tn_mod=n/n_aprox\n end if\n if (n_mod==0) n_mod=1\\n\\n\\n'''",
"#We add the code to caculate all the initial detunings for each laser.",
"code0",
"+=",
"'\t!We calculate the initial detunings.\\n'",
"#We find the minimal frequency corresponding to each laser.",
"omega_min",
",",
"omega_min_indices",
"=",
"find_omega_min",
"(",
"omega_rescaled",
",",
"Nl",
",",
"detuningsij",
",",
"i_d",
",",
"I_nd",
")",
"det_index",
"=",
"1",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"omega0",
"=",
"omega_min",
"[",
"l",
"]",
"for",
"p",
"in",
"detuningsij",
"[",
"l",
"]",
":",
"code0",
"+=",
"'\tdetuning('",
"+",
"str",
"(",
"det_index",
")",
"+",
"')='",
"code0",
"+=",
"format_double",
"(",
"omega0",
"-",
"omega_rescaled",
"[",
"p",
"[",
"0",
"]",
"]",
"[",
"p",
"[",
"1",
"]",
"]",
")",
"+",
"'+detuning_knob('",
"+",
"str",
"(",
"l",
"+",
"1",
")",
"+",
"')\\n'",
"det_index",
"+=",
"1",
"code0",
"+=",
"'\\n'",
"code0",
"+=",
"'''\tt=0\n\tif (.not. run_spectrum) WRITE(1,*) t,real(x),imag(x('''",
"+",
"str",
"(",
"Ne",
")",
"+",
"''':))\\n'''",
"code0",
"+=",
"'''\t!We start the detuning variation\\n'''",
"code0",
"+=",
"'\tdelta=detuning_knob(ldelta)\\n'",
"code0",
"+=",
"''' do j=1,ndelta\n\t\t!We run the Runge Kutta method\n\t\tt=0.0\n\t\tdo i=1,n-1\\n'''",
"code0",
"+=",
"' call f(x , t , k1, E0, detuning, detuning_knob)\\n'",
"code0",
"+=",
"' call f(x+0.5*k1*dt, t+dt*0.5, k2, E0, detuning, detuning_knob)\\n'",
"code0",
"+=",
"' call f(x+0.5*k2*dt, t+dt*0.5, k3, E0, detuning, detuning_knob)\\n'",
"code0",
"+=",
"' call f(x +k3*dt, t+dt , k4, E0, detuning, detuning_knob)\\n'",
"code0",
"+=",
"'''\t\t\tx= x+(k1+2*k2+2*k3+k4)*dt/6\n\t\t\tif (print_steps.and. .not. run_spectrum) print*,'t=',t,'delta=',delta\n\t\t\tt= t+ dt\n\t\t\t\n\t\t\tif (isnan(real(x(1)))) stop 1\n\t\t\tif (.not. run_spectrum .and. mod(i,n_mod)==0) WRITE(1,*) t,real(x),imag(x('''",
"+",
"str",
"(",
"Ne",
")",
"+",
"''':))\n\t\tend do\n\t\tif (print_steps) print*, 'delta=',delta,'percentage=',100*(delta-delta0)/(ddelta*ndelta)\n\t\t\n\t\t!We recalculate the detunings\n\t\tif (run_spectrum) then\n\t\t\tif (mod(j,n_mod)==0) WRITE(1,*) delta,real(x),imag(x('''",
"+",
"str",
"(",
"Ne",
")",
"+",
"''':))\n\t\t\tdelta=delta+ddelta\n\t\t\tdetuning_knob(ldelta)=detuning_knob(ldelta)+ddelta\\n'''",
"#We add the code to caculate all detunings for each laser",
"#This way of assigining a global index ll to the detunings ammounts to",
"# ll= number_of_previous_detunings ",
"# + number_of_detuning_ordered_by_row_and_from_left_to_right_column",
"#like this",
"#->",
"#-> ->",
"#-> -> ->",
"#for each l",
"#We find the minimal frequency corresponding to each laser\t\t",
"omega_min",
",",
"omega_min_indices",
"=",
"find_omega_min",
"(",
"omega_rescaled",
",",
"Nl",
",",
"detuningsij",
",",
"i_d",
",",
"I_nd",
")",
"det_index",
"=",
"1",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"omega0",
"=",
"omega_min",
"[",
"l",
"]",
"code0",
"+=",
"'\t\t\tif (ldelta=='",
"+",
"str",
"(",
"l",
"+",
"1",
")",
"+",
"') then\\n'",
"for",
"p",
"in",
"detuningsij",
"[",
"l",
"]",
":",
"code0",
"+=",
"'\t\t\t\tdetuning('",
"+",
"str",
"(",
"det_index",
")",
"+",
"')=detuning('",
"+",
"str",
"(",
"det_index",
")",
"+",
"')'",
"#code0+='+('+str(omega0-omega_rescaled[p[0]][p[1]])+'+ddelta\\n'",
"code0",
"+=",
"'+ddelta\\n'",
"det_index",
"+=",
"1",
"code0",
"+=",
"'\t\t\tend if\\n'",
"code0",
"+=",
"'''\t\tend if\n\t\n\t\n\tend do\n\t\n close(1)\n \nend program\\n\\n'''",
"code0",
"+=",
"'subroutine f(x,t,y, E0, detuning,detuning_knob)\\n'",
"code0",
"+=",
"''' implicit none\n real*8, intent(in) :: t\\n'''",
"code0",
"+=",
"' complex*16, dimension('",
"+",
"str",
"(",
"Ne",
"*",
"(",
"Ne",
"+",
"1",
")",
"/",
"2",
"-",
"1",
")",
"+",
"'), intent(in) :: x\\n'",
"code0",
"+=",
"' complex*16, dimension('",
"+",
"str",
"(",
"Ne",
"*",
"(",
"Ne",
"+",
"1",
")",
"/",
"2",
"-",
"1",
")",
"+",
"'), intent(out) :: y\\n'",
"code0",
"+=",
"' real*8, dimension('",
"+",
"str",
"(",
"Nl",
")",
"+",
"'), intent(in) :: E0,detuning_knob\\n'",
"code0",
"+=",
"' real*8, dimension('",
"+",
"str",
"(",
"Nd",
")",
"+",
"'), intent(in) :: detuning\\n\\n'",
"code0",
"+=",
"' complex*16 :: I,fact,aux\\n'",
"code0",
"+=",
"' real*8 :: rho11\\n\\n'",
"code0",
"+=",
"' I=(0,1D0)\\n'",
"#We establish the scaling of the equations",
"#~ if Omega==None:",
"#~ h =1.054571726e-34; e=1.602176565e-19",
"#~ code0+=' fact=I*'+str(e/h)+'\\n'",
"#~ else:",
"#~ #code0+=' fact=I*'+str(float(Omega/sqrt(2)))+'\\n'",
"#~ code0+=' fact=I*'+str(float(1/sqrt(2)))+'\\n'",
"#~ #code0+=' fact=I*'+str(float(1/(sqrt(2)*Omega)))+'\\n'",
"code0",
"+=",
"' fact=I*'",
"+",
"format_double",
"(",
"float",
"(",
"1",
"/",
"sqrt",
"(",
"2",
")",
")",
")",
"+",
"'\\n'",
"#We give the code to calculate rho11",
"code0",
"+=",
"' rho11=1\\n'",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"Ne",
")",
":",
"code0",
"+=",
"' rho11=rho11 -x('",
"+",
"str",
"(",
"i",
")",
"+",
"')\\n'",
"code0",
"+=",
"'\\n\\n'",
"####################################################################",
"#We produce the code for the first order equations.",
"####################################################################",
"if",
"len",
"(",
"theta",
")",
">",
"0",
":",
"code",
"=",
"''",
"for",
"mu",
"in",
"range",
"(",
"1",
",",
"Ne",
"*",
"(",
"Ne",
"+",
"1",
")",
"/",
"2",
")",
":",
"i",
",",
"j",
",",
"s",
"=",
"IJ",
"(",
"mu",
",",
"Ne",
")",
"#print 'ecuacion mu=',mu,',i,j=',i,j",
"eqmu",
"=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')= 0\\n'",
"####################################################################",
"#We add the terms associated with the effective hamiltonian",
"#other than those associated with the phase transformation.",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"#Case 1",
"if",
"k",
">=",
"j",
":",
"for",
"l",
"in",
"Lij",
"[",
"i",
"-",
"1",
"]",
"[",
"k",
"-",
"1",
"]",
":",
"if",
"k",
">",
"i",
":",
"#print 'E0^',l,-1,'r',i,k,'rho',k,j,'case 1.1'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'+'",
",",
"laser",
",",
"l",
",",
"-",
"1",
",",
"r",
",",
"i",
",",
"k",
",",
"k",
",",
"j",
")",
"elif",
"k",
"<",
"i",
":",
"#print 'E0^',l, 1,'r',i,k,'rho',k,j,'case 1.2'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'+'",
",",
"laser",
",",
"l",
",",
"1",
",",
"r",
",",
"i",
",",
"k",
",",
"k",
",",
"j",
")",
"#Case 2",
"elif",
"k",
"<",
"j",
":",
"for",
"l",
"in",
"Lij",
"[",
"i",
"-",
"1",
"]",
"[",
"k",
"-",
"1",
"]",
":",
"if",
"k",
">",
"i",
":",
"#print 'E0^',l,-1,'r',i,k,'rhoa',j,k,'case 2.1'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'+'",
",",
"laser",
",",
"l",
",",
"-",
"1",
",",
"r",
",",
"i",
",",
"k",
",",
"j",
",",
"k",
",",
"True",
")",
"elif",
"k",
"<",
"i",
":",
"#print 'E0^',l, 1,'r',i,k,'rhoa',j,k,'case 2.2'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'+'",
",",
"laser",
",",
"l",
",",
"1",
",",
"r",
",",
"i",
",",
"k",
",",
"j",
",",
"k",
",",
"True",
")",
"#Case 3",
"if",
"k",
"<=",
"i",
":",
"for",
"l",
"in",
"Lij",
"[",
"k",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
":",
"if",
"k",
"<",
"j",
":",
"#print 'E0^',l,-1,'r',k,j,'rho',i,k,'case 3.1'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'-'",
",",
"laser",
",",
"l",
",",
"-",
"1",
",",
"r",
",",
"k",
",",
"j",
",",
"i",
",",
"k",
")",
"elif",
"k",
">",
"j",
":",
"#print 'E0^',l, 1,'r',k,j,'rho',i,k,'case 3.2'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'-'",
",",
"laser",
",",
"l",
",",
"1",
",",
"r",
",",
"k",
",",
"j",
",",
"i",
",",
"k",
")",
"#Case 4",
"elif",
"k",
">",
"i",
":",
"for",
"l",
"in",
"Lij",
"[",
"k",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
":",
"if",
"k",
"<",
"j",
":",
"#print 'E0^',l,-1,'r',k,j,'rhoa',k,i,'case 4.1'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'-'",
",",
"laser",
",",
"l",
",",
"-",
"1",
",",
"r",
",",
"k",
",",
"j",
",",
"k",
",",
"i",
",",
"True",
")",
"elif",
"k",
">",
"j",
":",
"#print 'E0^',l, 1,'r',k,j,'rhoa',k,i,'case 4.2'",
"eqmu",
"+=",
"add_line",
"(",
"Ne",
",",
"mu",
",",
"'-'",
",",
"laser",
",",
"l",
",",
"1",
",",
"r",
",",
"k",
",",
"j",
",",
"k",
",",
"i",
",",
"True",
")",
"eqmu",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')*fact\\n'",
"####################################################################",
"#We add the terms associated with the phase transformation.",
"extra",
"=",
"Theta",
"(",
"i",
",",
"j",
",",
"theta",
",",
"omega_rescaled",
",",
"omega_min",
",",
"detunings",
",",
"detuningsij",
",",
"combinations",
",",
"detuning_indices",
",",
"Lij",
",",
"i_d",
",",
"I_nd",
",",
"Nnd",
",",
"verbose",
"=",
"verbose",
",",
"states",
"=",
"states",
")",
"if",
"extra",
"!=",
"''",
":",
"eqmu",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"') + I*('",
"+",
"extra",
"+",
"')*x('",
"+",
"str",
"(",
"mu",
")",
"+",
"')\\n'",
"####################################################################",
"#~ if i==j:",
"#~ for k in range(1,Ne+1):",
"#~ if k < i:",
"#~ muii=Mu(i,i,s=1,N=Ne)",
"#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(muii)+')\\n'",
"#~ elif k > i:",
"#~ mukk=Mu(k,k,s=1,N=Ne)",
"#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(mukk)+')\\n'",
"#~ eqmu+='\\n'",
"#~ else:",
"#~ eqmu+=' y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][j-1]/2)+')*x('+str(mu)+')\\n'",
"#~ ",
"####################################################################",
"code",
"+=",
"eqmu",
"+",
"'\\n'",
"#We add the terms associated with spontaneous decay.\t\t",
"#First for populations.",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"Ne",
"+",
"1",
")",
":",
"mu",
"=",
"Mu",
"(",
"i",
",",
"i",
",",
"1",
",",
"Ne",
")",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"gams",
"=",
"0",
"if",
"k",
"<",
"i",
":",
"gams",
"+=",
"gamma",
"[",
"i",
"-",
"1",
"]",
"[",
"k",
"-",
"1",
"]",
"elif",
"k",
">",
"i",
":",
"nu",
"=",
"Mu",
"(",
"k",
",",
"k",
",",
"1",
",",
"Ne",
")",
"ga",
"=",
"gamma",
"[",
"i",
"-",
"1",
"]",
"[",
"k",
"-",
"1",
"]",
"if",
"ga",
"!=",
"0",
":",
"code",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')'",
"code",
"+=",
"'-('",
"+",
"format_double",
"(",
"ga",
")",
"+",
"')*x('",
"+",
"str",
"(",
"nu",
")",
"+",
"')\\n'",
"if",
"gams",
"!=",
"0",
":",
"code",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')'",
"code",
"+=",
"'-('",
"+",
"format_double",
"(",
"gams",
")",
"+",
"')*x('",
"+",
"str",
"(",
"mu",
")",
"+",
"')\\n'",
"#And now for coherences\t",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"i",
")",
":",
"gams",
"=",
"gamma",
"[",
"i",
"-",
"1",
"]",
"[",
"j",
"-",
"1",
"]",
"/",
"2",
"if",
"gams",
"!=",
"0",
":",
"for",
"a",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"mu",
"=",
"Mu",
"(",
"a",
",",
"i",
",",
"+",
"1",
",",
"Ne",
")",
"code",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')'",
"code",
"+=",
"'-('",
"+",
"format_double",
"(",
"gams",
")",
"+",
"')*x('",
"+",
"str",
"(",
"mu",
")",
"+",
"')\\n'",
"#~ mu=Mu(a,i,-1,Ne)",
"#~ code+=' y('+str(mu)+')=y('+str(mu)+')'",
"#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\\n'",
"for",
"b",
"in",
"range",
"(",
"1",
",",
"i",
")",
":",
"mu",
"=",
"Mu",
"(",
"i",
",",
"b",
",",
"+",
"1",
",",
"Ne",
")",
"code",
"+=",
"' y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')=y('",
"+",
"str",
"(",
"mu",
")",
"+",
"')'",
"code",
"+=",
"'-('",
"+",
"format_double",
"(",
"gams",
")",
"+",
"')*x('",
"+",
"str",
"(",
"mu",
")",
"+",
"')\\n'",
"#~ mu=Mu(i,b,-1,Ne)",
"#~ code+=' y('+str(mu)+')=y('+str(mu)+')'",
"#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\\n'",
"####################################################################",
"####################################################################",
"####################################################################",
"#code+=' y=y/'+str(Omega)+'\\n'",
"f",
"=",
"file",
"(",
"path",
"+",
"name",
"+",
"'.f90'",
",",
"'w'",
")",
"code",
"=",
"code0",
"+",
"code",
"+",
"'end subroutine\\n'",
"f",
".",
"write",
"(",
"code",
")",
"f",
".",
"close",
"(",
")",
"return",
"time",
"(",
")",
"-",
"t0",
"else",
":",
"print",
"'There was no phase transformation capable of eliminating explicit time dependance.'"
] | r"""
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements
`\rho_{ij}` using the Runge-Kutta method of order 4.
INPUT:
- ``path`` - A string with the working directory where all files will be stored. It must end with ``/``.
- ``name`` - A string with the name of the experiment. All files produced will begin with this name.
- ``laser`` - A list of Laser objects (see the Laser class).
- ``omega`` - A matrix or list of lists containing the frequency differences `\omega_{ij}`.
- ``gamma`` - A matrix or list of lists containing the spontaneous decay frequencies `\gamma_{ij}`.
- ``r`` - A list of three matrices or lists of lists containing the components of the position operator `r_{-1ij},r_{0ij},r_{1ij}`.
- ``Lij`` - A list with elements of the form ``[i,j,[l1,l2,...]]`` representing the sets `L_{ij}` of which lasers excite wich transitions. It does not need to contain an element for all ``i,j`` pairs, but only those which have a laser that excites them.
- ``Omega`` - A floating point number indicating the frequency scale for the equations. The frequencies ``omega`` and ``gamma`` are divided by this number. If ``None`` the equations and the input are taken in SI units.
OUTPUT:
- A file ``name.f90`` is created in ``path``. | [
"r",
"This",
"function",
"writes",
"the",
"Fortran",
"code",
"needed",
"to",
"calculate",
"the",
"time",
"evolution",
"of",
"the",
"density",
"matrix",
"elements",
"\\",
"rho_",
"{",
"ij",
"}",
"using",
"the",
"Runge",
"-",
"Kutta",
"method",
"of",
"order",
"4",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/rk4.py#L56-L411 |
oscarlazoarjona/fast | build/lib/fast/rk4.py | run_rk4 | def run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
rho0=None,print_steps=False,integrate=False,
save_systems=False):
"""This function runs the Runge-Kutta method compiled in path+name..."""
t0=time()
params =str(N_iter)+'\n'
params+=str(dt)+'\n'
#We give the flag on wether to print each time step.
if print_steps:
params+='.true.\n'
else:
params+='.false.\n'
#We give the initial value of rho
N_vars=N_states*(N_states+1)/2-1
if rho0==None:
params+=''.join(['(0.0,0.0) ' for i in range(N_vars)])
elif len(rho0)==N_states-1:
if sage_included:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
params+=''.join(['(0.0,0.0) ' for i in range(N_vars-N_states+1)])
elif len(rho0)==N_vars:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
params+='\n'
#We give the amplitude of the electrical fields.
params+=''.join([str(i)+' ' for i in E0])+'\n'
#We give the detuning of each laser (taken from the lowest frequency transition).
params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'
#We give the flag on wether to calculate spectrums or time evolution.
if spectrum_of_laser==None:
params+='.false.'
else:
if frequency_end !=None:
if frequency_step !=None:
raise ValueError,'both frequency_end and frequency_step were specified.'
if N_delta==1:
frequency_step=0.0
else:
frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)
#frequency_step=frequency_end
params+='.true.\n'
params+=str(spectrum_of_laser)+'\n'
params+=str(N_delta)+'\n'
params+=str(frequency_step)
#print params
f=file(path+name+'_params.dat','w')
f.write(params)
f.close()
os.system(path+name)
return time()-t0 | python | def run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
rho0=None,print_steps=False,integrate=False,
save_systems=False):
"""This function runs the Runge-Kutta method compiled in path+name..."""
t0=time()
params =str(N_iter)+'\n'
params+=str(dt)+'\n'
#We give the flag on wether to print each time step.
if print_steps:
params+='.true.\n'
else:
params+='.false.\n'
#We give the initial value of rho
N_vars=N_states*(N_states+1)/2-1
if rho0==None:
params+=''.join(['(0.0,0.0) ' for i in range(N_vars)])
elif len(rho0)==N_states-1:
if sage_included:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
else:
params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
params+=''.join(['(0.0,0.0) ' for i in range(N_vars-N_states+1)])
elif len(rho0)==N_vars:
params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
params+='\n'
#We give the amplitude of the electrical fields.
params+=''.join([str(i)+' ' for i in E0])+'\n'
#We give the detuning of each laser (taken from the lowest frequency transition).
params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'
#We give the flag on wether to calculate spectrums or time evolution.
if spectrum_of_laser==None:
params+='.false.'
else:
if frequency_end !=None:
if frequency_step !=None:
raise ValueError,'both frequency_end and frequency_step were specified.'
if N_delta==1:
frequency_step=0.0
else:
frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)
#frequency_step=frequency_end
params+='.true.\n'
params+=str(spectrum_of_laser)+'\n'
params+=str(N_delta)+'\n'
params+=str(frequency_step)
#print params
f=file(path+name+'_params.dat','w')
f.write(params)
f.close()
os.system(path+name)
return time()-t0 | [
"def",
"run_rk4",
"(",
"path",
",",
"name",
",",
"E0",
",",
"laser_frequencies",
",",
"N_iter",
",",
"dt",
",",
"N_states",
",",
"spectrum_of_laser",
"=",
"None",
",",
"N_delta",
"=",
"None",
",",
"frequency_step",
"=",
"None",
",",
"frequency_end",
"=",
"None",
",",
"rho0",
"=",
"None",
",",
"print_steps",
"=",
"False",
",",
"integrate",
"=",
"False",
",",
"save_systems",
"=",
"False",
")",
":",
"t0",
"=",
"time",
"(",
")",
"params",
"=",
"str",
"(",
"N_iter",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"dt",
")",
"+",
"'\\n'",
"#We give the flag on wether to print each time step.",
"if",
"print_steps",
":",
"params",
"+=",
"'.true.\\n'",
"else",
":",
"params",
"+=",
"'.false.\\n'",
"#We give the initial value of rho",
"N_vars",
"=",
"N_states",
"*",
"(",
"N_states",
"+",
"1",
")",
"/",
"2",
"-",
"1",
"if",
"rho0",
"==",
"None",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'(0.0,0.0) '",
"for",
"i",
"in",
"range",
"(",
"N_vars",
")",
"]",
")",
"elif",
"len",
"(",
"rho0",
")",
"==",
"N_states",
"-",
"1",
":",
"if",
"sage_included",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"real",
"(",
"i",
")",
")",
"+",
"','",
"+",
"str",
"(",
"imag",
"(",
"i",
")",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"else",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"i",
".",
"real",
")",
"+",
"','",
"+",
"str",
"(",
"i",
".",
"imag",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'(0.0,0.0) '",
"for",
"i",
"in",
"range",
"(",
"N_vars",
"-",
"N_states",
"+",
"1",
")",
"]",
")",
"elif",
"len",
"(",
"rho0",
")",
"==",
"N_vars",
":",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"'('",
"+",
"str",
"(",
"real",
"(",
"i",
")",
")",
"+",
"','",
"+",
"str",
"(",
"imag",
"(",
"i",
")",
")",
"+",
"') '",
"for",
"i",
"in",
"rho0",
"]",
")",
"params",
"+=",
"'\\n'",
"#We give the amplitude of the electrical fields.",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"+",
"' '",
"for",
"i",
"in",
"E0",
"]",
")",
"+",
"'\\n'",
"#We give the detuning of each laser (taken from the lowest frequency transition).",
"params",
"+=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"+",
"' '",
"for",
"i",
"in",
"laser_frequencies",
"]",
")",
"+",
"'\\n'",
"#We give the flag on wether to calculate spectrums or time evolution.",
"if",
"spectrum_of_laser",
"==",
"None",
":",
"params",
"+=",
"'.false.'",
"else",
":",
"if",
"frequency_end",
"!=",
"None",
":",
"if",
"frequency_step",
"!=",
"None",
":",
"raise",
"ValueError",
",",
"'both frequency_end and frequency_step were specified.'",
"if",
"N_delta",
"==",
"1",
":",
"frequency_step",
"=",
"0.0",
"else",
":",
"frequency_step",
"=",
"(",
"frequency_end",
"-",
"laser_frequencies",
"[",
"spectrum_of_laser",
"-",
"1",
"]",
")",
"/",
"(",
"N_delta",
"-",
"1",
")",
"#frequency_step=frequency_end",
"params",
"+=",
"'.true.\\n'",
"params",
"+=",
"str",
"(",
"spectrum_of_laser",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"N_delta",
")",
"+",
"'\\n'",
"params",
"+=",
"str",
"(",
"frequency_step",
")",
"#print params",
"f",
"=",
"file",
"(",
"path",
"+",
"name",
"+",
"'_params.dat'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"params",
")",
"f",
".",
"close",
"(",
")",
"os",
".",
"system",
"(",
"path",
"+",
"name",
")",
"return",
"time",
"(",
")",
"-",
"t0"
] | This function runs the Runge-Kutta method compiled in path+name... | [
"This",
"function",
"runs",
"the",
"Runge",
"-",
"Kutta",
"method",
"compiled",
"in",
"path",
"+",
"name",
"..."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/rk4.py#L413-L473 |
deployed/django-emailtemplates | emailtemplates/email.py | EmailFromTemplate.send_email | def send_email(self, send_to, attachment_paths=None, fail_silently=True, *args, **kwargs):
"""
Sends email to recipient based on self object parameters.
@param fail_silently: When itβs False, msg.send() will raise an smtplib.SMTPException if an error occurs.
@param send_to: recipient email
@param args: additional args passed to EmailMessage
@param kwargs: kwargs passed to EmailMessage
@param attachment_paths: paths to attachments as received by django EmailMessage.attach_file(path) method
@return: number of sent messages
"""
msg = self.get_message_object(send_to, attachment_paths, *args, **kwargs)
msg.content_subtype = self.content_subtype
try:
self.sent = msg.send()
except SMTPException, e:
if not fail_silently:
raise
logger.error(u'Problem sending email to %s: %s', send_to, e)
return self.sent | python | def send_email(self, send_to, attachment_paths=None, fail_silently=True, *args, **kwargs):
"""
Sends email to recipient based on self object parameters.
@param fail_silently: When itβs False, msg.send() will raise an smtplib.SMTPException if an error occurs.
@param send_to: recipient email
@param args: additional args passed to EmailMessage
@param kwargs: kwargs passed to EmailMessage
@param attachment_paths: paths to attachments as received by django EmailMessage.attach_file(path) method
@return: number of sent messages
"""
msg = self.get_message_object(send_to, attachment_paths, *args, **kwargs)
msg.content_subtype = self.content_subtype
try:
self.sent = msg.send()
except SMTPException, e:
if not fail_silently:
raise
logger.error(u'Problem sending email to %s: %s', send_to, e)
return self.sent | [
"def",
"send_email",
"(",
"self",
",",
"send_to",
",",
"attachment_paths",
"=",
"None",
",",
"fail_silently",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"self",
".",
"get_message_object",
"(",
"send_to",
",",
"attachment_paths",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"msg",
".",
"content_subtype",
"=",
"self",
".",
"content_subtype",
"try",
":",
"self",
".",
"sent",
"=",
"msg",
".",
"send",
"(",
")",
"except",
"SMTPException",
",",
"e",
":",
"if",
"not",
"fail_silently",
":",
"raise",
"logger",
".",
"error",
"(",
"u'Problem sending email to %s: %s'",
",",
"send_to",
",",
"e",
")",
"return",
"self",
".",
"sent"
] | Sends email to recipient based on self object parameters.
@param fail_silently: When itβs False, msg.send() will raise an smtplib.SMTPException if an error occurs.
@param send_to: recipient email
@param args: additional args passed to EmailMessage
@param kwargs: kwargs passed to EmailMessage
@param attachment_paths: paths to attachments as received by django EmailMessage.attach_file(path) method
@return: number of sent messages | [
"Sends",
"email",
"to",
"recipient",
"based",
"on",
"self",
"object",
"parameters",
"."
] | train | https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/email.py#L127-L148 |
deployed/django-emailtemplates | emailtemplates/email.py | EmailFromTemplate.send | def send(self, to, attachment_paths=None, *args, **kwargs):
"""This function does all the operations on eft object, that are necessary to send email.
Usually one would use eft object like this:
eft = EmailFromTemplate(name='sth/sth.html')
eft.get_object()
eft.render_message()
eft.send_email(['email@example.com'])
return eft.sent
"""
self.get_object()
self.render_message()
self.send_email(to, attachment_paths, *args, **kwargs)
if self.sent:
logger.info(u"Mail has been sent to: %s ", to)
return self.sent | python | def send(self, to, attachment_paths=None, *args, **kwargs):
"""This function does all the operations on eft object, that are necessary to send email.
Usually one would use eft object like this:
eft = EmailFromTemplate(name='sth/sth.html')
eft.get_object()
eft.render_message()
eft.send_email(['email@example.com'])
return eft.sent
"""
self.get_object()
self.render_message()
self.send_email(to, attachment_paths, *args, **kwargs)
if self.sent:
logger.info(u"Mail has been sent to: %s ", to)
return self.sent | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"attachment_paths",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"get_object",
"(",
")",
"self",
".",
"render_message",
"(",
")",
"self",
".",
"send_email",
"(",
"to",
",",
"attachment_paths",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"sent",
":",
"logger",
".",
"info",
"(",
"u\"Mail has been sent to: %s \"",
",",
"to",
")",
"return",
"self",
".",
"sent"
] | This function does all the operations on eft object, that are necessary to send email.
Usually one would use eft object like this:
eft = EmailFromTemplate(name='sth/sth.html')
eft.get_object()
eft.render_message()
eft.send_email(['email@example.com'])
return eft.sent | [
"This",
"function",
"does",
"all",
"the",
"operations",
"on",
"eft",
"object",
"that",
"are",
"necessary",
"to",
"send",
"email",
".",
"Usually",
"one",
"would",
"use",
"eft",
"object",
"like",
"this",
":",
"eft",
"=",
"EmailFromTemplate",
"(",
"name",
"=",
"sth",
"/",
"sth",
".",
"html",
")",
"eft",
".",
"get_object",
"()",
"eft",
".",
"render_message",
"()",
"eft",
".",
"send_email",
"(",
"[",
"email"
] | train | https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/email.py#L150-L164 |
commontk/ctk-cli | ctk_cli/module.py | _tag | def _tag(element):
"""Return element.tag with xmlns stripped away."""
tag = element.tag
if tag[0] == "{":
uri, tag = tag[1:].split("}")
return tag | python | def _tag(element):
"""Return element.tag with xmlns stripped away."""
tag = element.tag
if tag[0] == "{":
uri, tag = tag[1:].split("}")
return tag | [
"def",
"_tag",
"(",
"element",
")",
":",
"tag",
"=",
"element",
".",
"tag",
"if",
"tag",
"[",
"0",
"]",
"==",
"\"{\"",
":",
"uri",
",",
"tag",
"=",
"tag",
"[",
"1",
":",
"]",
".",
"split",
"(",
"\"}\"",
")",
"return",
"tag"
] | Return element.tag with xmlns stripped away. | [
"Return",
"element",
".",
"tag",
"with",
"xmlns",
"stripped",
"away",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L23-L28 |
commontk/ctk-cli | ctk_cli/module.py | _uriPrefix | def _uriPrefix(element):
"""Return xmlns prefix of the given element."""
i = element.tag.find('}')
if i < 0:
return ""
return element.tag[:i+1] | python | def _uriPrefix(element):
"""Return xmlns prefix of the given element."""
i = element.tag.find('}')
if i < 0:
return ""
return element.tag[:i+1] | [
"def",
"_uriPrefix",
"(",
"element",
")",
":",
"i",
"=",
"element",
".",
"tag",
".",
"find",
"(",
"'}'",
")",
"if",
"i",
"<",
"0",
":",
"return",
"\"\"",
"return",
"element",
".",
"tag",
"[",
":",
"i",
"+",
"1",
"]"
] | Return xmlns prefix of the given element. | [
"Return",
"xmlns",
"prefix",
"of",
"the",
"given",
"element",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L30-L35 |
commontk/ctk-cli | ctk_cli/module.py | _parseElements | def _parseElements(self, elementTree, expectedTag = None):
"""Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns
the rest of the children. Every read child element's text
value will be filled into an attribute of the same name,
i.e. <description>Test</description> will lead to 'Test' being
assigned to self.description. Missing REQUIRED_ELEMENTS
result in warnings."""
xmlns = _uriPrefix(elementTree)
if expectedTag is not None:
assert _tag(elementTree) == expectedTag, 'expected <%s>, got <%s>' % (expectedTag, _tag(elementTree))
parsed = []
for tagName in self.REQUIRED_ELEMENTS + self.OPTIONAL_ELEMENTS:
tags = elementTree.findall(xmlns + tagName)
if tags:
parsed.extend(tags)
tagValue = tags[0].text
tagValue = tagValue.strip() if tagValue else ""
if len(tags) > 1:
logger.warning("More than one <%s> found within %r (using only first)" % (tagName, _tag(elementTree)))
else:
tagValue = None
if tagName in self.REQUIRED_ELEMENTS:
logger.warning("Required element %r not found within %r" % (tagName, _tag(elementTree)))
setattr(self, _tagToIdentifier(tagName), tagValue)
return [tag for tag in elementTree if tag not in parsed] | python | def _parseElements(self, elementTree, expectedTag = None):
"""Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns
the rest of the children. Every read child element's text
value will be filled into an attribute of the same name,
i.e. <description>Test</description> will lead to 'Test' being
assigned to self.description. Missing REQUIRED_ELEMENTS
result in warnings."""
xmlns = _uriPrefix(elementTree)
if expectedTag is not None:
assert _tag(elementTree) == expectedTag, 'expected <%s>, got <%s>' % (expectedTag, _tag(elementTree))
parsed = []
for tagName in self.REQUIRED_ELEMENTS + self.OPTIONAL_ELEMENTS:
tags = elementTree.findall(xmlns + tagName)
if tags:
parsed.extend(tags)
tagValue = tags[0].text
tagValue = tagValue.strip() if tagValue else ""
if len(tags) > 1:
logger.warning("More than one <%s> found within %r (using only first)" % (tagName, _tag(elementTree)))
else:
tagValue = None
if tagName in self.REQUIRED_ELEMENTS:
logger.warning("Required element %r not found within %r" % (tagName, _tag(elementTree)))
setattr(self, _tagToIdentifier(tagName), tagValue)
return [tag for tag in elementTree if tag not in parsed] | [
"def",
"_parseElements",
"(",
"self",
",",
"elementTree",
",",
"expectedTag",
"=",
"None",
")",
":",
"xmlns",
"=",
"_uriPrefix",
"(",
"elementTree",
")",
"if",
"expectedTag",
"is",
"not",
"None",
":",
"assert",
"_tag",
"(",
"elementTree",
")",
"==",
"expectedTag",
",",
"'expected <%s>, got <%s>'",
"%",
"(",
"expectedTag",
",",
"_tag",
"(",
"elementTree",
")",
")",
"parsed",
"=",
"[",
"]",
"for",
"tagName",
"in",
"self",
".",
"REQUIRED_ELEMENTS",
"+",
"self",
".",
"OPTIONAL_ELEMENTS",
":",
"tags",
"=",
"elementTree",
".",
"findall",
"(",
"xmlns",
"+",
"tagName",
")",
"if",
"tags",
":",
"parsed",
".",
"extend",
"(",
"tags",
")",
"tagValue",
"=",
"tags",
"[",
"0",
"]",
".",
"text",
"tagValue",
"=",
"tagValue",
".",
"strip",
"(",
")",
"if",
"tagValue",
"else",
"\"\"",
"if",
"len",
"(",
"tags",
")",
">",
"1",
":",
"logger",
".",
"warning",
"(",
"\"More than one <%s> found within %r (using only first)\"",
"%",
"(",
"tagName",
",",
"_tag",
"(",
"elementTree",
")",
")",
")",
"else",
":",
"tagValue",
"=",
"None",
"if",
"tagName",
"in",
"self",
".",
"REQUIRED_ELEMENTS",
":",
"logger",
".",
"warning",
"(",
"\"Required element %r not found within %r\"",
"%",
"(",
"tagName",
",",
"_tag",
"(",
"elementTree",
")",
")",
")",
"setattr",
"(",
"self",
",",
"_tagToIdentifier",
"(",
"tagName",
")",
",",
"tagValue",
")",
"return",
"[",
"tag",
"for",
"tag",
"in",
"elementTree",
"if",
"tag",
"not",
"in",
"parsed",
"]"
] | Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns
the rest of the children. Every read child element's text
value will be filled into an attribute of the same name,
i.e. <description>Test</description> will lead to 'Test' being
assigned to self.description. Missing REQUIRED_ELEMENTS
result in warnings. | [
"Read",
"REQUIRED_ELEMENTS",
"and",
"OPTIONAL_ELEMENTS",
"and",
"returns",
"the",
"rest",
"of",
"the",
"children",
".",
"Every",
"read",
"child",
"element",
"s",
"text",
"value",
"will",
"be",
"filled",
"into",
"an",
"attribute",
"of",
"the",
"same",
"name",
"i",
".",
"e",
".",
"<description",
">",
"Test<",
"/",
"description",
">",
"will",
"lead",
"to",
"Test",
"being",
"assigned",
"to",
"self",
".",
"description",
".",
"Missing",
"REQUIRED_ELEMENTS",
"result",
"in",
"warnings",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L38-L67 |
commontk/ctk-cli | ctk_cli/module.py | CLIModule.classifyParameters | def classifyParameters(self):
"""Return (arguments, options, outputs) tuple. Together, the
three lists contain all parameters (recursively fetched from
all parameter groups), classified into optional parameters,
required ones (with an index), and simple output parameters
(that would get written to a file using
--returnparameterfile). `arguments` contains the required
arguments, already sorted by index."""
arguments = []
options = []
outputs = []
for parameter in self.parameters():
if parameter.channel == 'output' and not parameter.isExternalType():
outputs.append(parameter)
elif parameter.index is not None:
arguments.append(parameter)
if parameter.flag is not None or parameter.longflag is not None:
logger.warning("Parameter '%s' has both index=%d and flag set." % (
parameter.identifier(), parameter.index))
elif parameter.flag or parameter.longflag:
options.append(parameter)
else:
logger.warning("Parameter '%s' cannot be passed (missing flag, longflag, or index)!" % parameter.name)
arguments.sort(key = lambda parameter: parameter.index)
return (arguments, options, outputs) | python | def classifyParameters(self):
"""Return (arguments, options, outputs) tuple. Together, the
three lists contain all parameters (recursively fetched from
all parameter groups), classified into optional parameters,
required ones (with an index), and simple output parameters
(that would get written to a file using
--returnparameterfile). `arguments` contains the required
arguments, already sorted by index."""
arguments = []
options = []
outputs = []
for parameter in self.parameters():
if parameter.channel == 'output' and not parameter.isExternalType():
outputs.append(parameter)
elif parameter.index is not None:
arguments.append(parameter)
if parameter.flag is not None or parameter.longflag is not None:
logger.warning("Parameter '%s' has both index=%d and flag set." % (
parameter.identifier(), parameter.index))
elif parameter.flag or parameter.longflag:
options.append(parameter)
else:
logger.warning("Parameter '%s' cannot be passed (missing flag, longflag, or index)!" % parameter.name)
arguments.sort(key = lambda parameter: parameter.index)
return (arguments, options, outputs) | [
"def",
"classifyParameters",
"(",
"self",
")",
":",
"arguments",
"=",
"[",
"]",
"options",
"=",
"[",
"]",
"outputs",
"=",
"[",
"]",
"for",
"parameter",
"in",
"self",
".",
"parameters",
"(",
")",
":",
"if",
"parameter",
".",
"channel",
"==",
"'output'",
"and",
"not",
"parameter",
".",
"isExternalType",
"(",
")",
":",
"outputs",
".",
"append",
"(",
"parameter",
")",
"elif",
"parameter",
".",
"index",
"is",
"not",
"None",
":",
"arguments",
".",
"append",
"(",
"parameter",
")",
"if",
"parameter",
".",
"flag",
"is",
"not",
"None",
"or",
"parameter",
".",
"longflag",
"is",
"not",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Parameter '%s' has both index=%d and flag set.\"",
"%",
"(",
"parameter",
".",
"identifier",
"(",
")",
",",
"parameter",
".",
"index",
")",
")",
"elif",
"parameter",
".",
"flag",
"or",
"parameter",
".",
"longflag",
":",
"options",
".",
"append",
"(",
"parameter",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Parameter '%s' cannot be passed (missing flag, longflag, or index)!\"",
"%",
"parameter",
".",
"name",
")",
"arguments",
".",
"sort",
"(",
"key",
"=",
"lambda",
"parameter",
":",
"parameter",
".",
"index",
")",
"return",
"(",
"arguments",
",",
"options",
",",
"outputs",
")"
] | Return (arguments, options, outputs) tuple. Together, the
three lists contain all parameters (recursively fetched from
all parameter groups), classified into optional parameters,
required ones (with an index), and simple output parameters
(that would get written to a file using
--returnparameterfile). `arguments` contains the required
arguments, already sorted by index. | [
"Return",
"(",
"arguments",
"options",
"outputs",
")",
"tuple",
".",
"Together",
"the",
"three",
"lists",
"contain",
"all",
"parameters",
"(",
"recursively",
"fetched",
"from",
"all",
"parameter",
"groups",
")",
"classified",
"into",
"optional",
"parameters",
"required",
"ones",
"(",
"with",
"an",
"index",
")",
"and",
"simple",
"output",
"parameters",
"(",
"that",
"would",
"get",
"written",
"to",
"a",
"file",
"using",
"--",
"returnparameterfile",
")",
".",
"arguments",
"contains",
"the",
"required",
"arguments",
"already",
"sorted",
"by",
"index",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L134-L159 |
commontk/ctk-cli | ctk_cli/module.py | CLIParameter.parseValue | def parseValue(self, value):
"""Parse the given value and return result."""
if self.isVector():
return list(map(self._pythonType, value.split(',')))
if self.typ == 'boolean':
return _parseBool(value)
return self._pythonType(value) | python | def parseValue(self, value):
"""Parse the given value and return result."""
if self.isVector():
return list(map(self._pythonType, value.split(',')))
if self.typ == 'boolean':
return _parseBool(value)
return self._pythonType(value) | [
"def",
"parseValue",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"isVector",
"(",
")",
":",
"return",
"list",
"(",
"map",
"(",
"self",
".",
"_pythonType",
",",
"value",
".",
"split",
"(",
"','",
")",
")",
")",
"if",
"self",
".",
"typ",
"==",
"'boolean'",
":",
"return",
"_parseBool",
"(",
"value",
")",
"return",
"self",
".",
"_pythonType",
"(",
"value",
")"
] | Parse the given value and return result. | [
"Parse",
"the",
"given",
"value",
"and",
"return",
"result",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L259-L265 |
commontk/ctk-cli | ctk_cli/module.py | CLIParameter.defaultExtension | def defaultExtension(self):
"""Return default extension for this parameter type, checked
against supported fileExtensions. If the default extension is
not within `fileExtensions`, return the first supported
extension."""
result = self.EXTERNAL_TYPES[self.typ]
if not self.fileExtensions:
return result
if result in self.fileExtensions:
return result
return self.fileExtensions[0] | python | def defaultExtension(self):
"""Return default extension for this parameter type, checked
against supported fileExtensions. If the default extension is
not within `fileExtensions`, return the first supported
extension."""
result = self.EXTERNAL_TYPES[self.typ]
if not self.fileExtensions:
return result
if result in self.fileExtensions:
return result
return self.fileExtensions[0] | [
"def",
"defaultExtension",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"EXTERNAL_TYPES",
"[",
"self",
".",
"typ",
"]",
"if",
"not",
"self",
".",
"fileExtensions",
":",
"return",
"result",
"if",
"result",
"in",
"self",
".",
"fileExtensions",
":",
"return",
"result",
"return",
"self",
".",
"fileExtensions",
"[",
"0",
"]"
] | Return default extension for this parameter type, checked
against supported fileExtensions. If the default extension is
not within `fileExtensions`, return the first supported
extension. | [
"Return",
"default",
"extension",
"for",
"this",
"parameter",
"type",
"checked",
"against",
"supported",
"fileExtensions",
".",
"If",
"the",
"default",
"extension",
"is",
"not",
"within",
"fileExtensions",
"return",
"the",
"first",
"supported",
"extension",
"."
] | train | https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/module.py#L291-L301 |
kpdyer/libfte | fte/encoder.py | DfaEncoderObject.encode | def encode(self, X, seed=None):
"""Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n``
is the the maximum number of bytes that can be unranked w.r.t. the
capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input
``dfa``.
"""
if not X:
return ''
if not isinstance(X, str):
raise InvalidInputException('Input must be of type string.')
if seed is not None and len(seed) != 8:
raise InvalidSeedLength('The seed is not 8 bytes long, seed length: '+str(len(seed)))
ciphertext = self._encrypter.encrypt(X)
maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))
unrank_payload_len = (
maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT)
unrank_payload_len = min(len(ciphertext), unrank_payload_len)
if unrank_payload_len <= 0:
raise InsufficientCapacityException('Language doesn\'t have enough capacity')
msg_len_header = fte.bit_ops.long_to_bytes(unrank_payload_len)
msg_len_header = string.rjust(
msg_len_header, DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT, '\x00')
random_bytes = seed if seed is not None else fte.bit_ops.random_bytes(8)
msg_len_header = random_bytes + msg_len_header
msg_len_header = self._encrypter.encryptOneBlock(msg_len_header)
unrank_payload = msg_len_header + \
ciphertext[:maximumBytesToRank -
DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT]
random_padding_bytes = maximumBytesToRank - len(unrank_payload)
if random_padding_bytes > 0:
unrank_payload += fte.bit_ops.random_bytes(random_padding_bytes)
unrank_payload = fte.bit_ops.bytes_to_long(unrank_payload)
formatted_covertext_header = self._dfa.unrank(unrank_payload)
unformatted_covertext_body = ciphertext[
maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT:]
covertext = formatted_covertext_header + unformatted_covertext_body
return covertext | python | def encode(self, X, seed=None):
"""Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n``
is the the maximum number of bytes that can be unranked w.r.t. the
capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input
``dfa``.
"""
if not X:
return ''
if not isinstance(X, str):
raise InvalidInputException('Input must be of type string.')
if seed is not None and len(seed) != 8:
raise InvalidSeedLength('The seed is not 8 bytes long, seed length: '+str(len(seed)))
ciphertext = self._encrypter.encrypt(X)
maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))
unrank_payload_len = (
maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT)
unrank_payload_len = min(len(ciphertext), unrank_payload_len)
if unrank_payload_len <= 0:
raise InsufficientCapacityException('Language doesn\'t have enough capacity')
msg_len_header = fte.bit_ops.long_to_bytes(unrank_payload_len)
msg_len_header = string.rjust(
msg_len_header, DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT, '\x00')
random_bytes = seed if seed is not None else fte.bit_ops.random_bytes(8)
msg_len_header = random_bytes + msg_len_header
msg_len_header = self._encrypter.encryptOneBlock(msg_len_header)
unrank_payload = msg_len_header + \
ciphertext[:maximumBytesToRank -
DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT]
random_padding_bytes = maximumBytesToRank - len(unrank_payload)
if random_padding_bytes > 0:
unrank_payload += fte.bit_ops.random_bytes(random_padding_bytes)
unrank_payload = fte.bit_ops.bytes_to_long(unrank_payload)
formatted_covertext_header = self._dfa.unrank(unrank_payload)
unformatted_covertext_body = ciphertext[
maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT:]
covertext = formatted_covertext_header + unformatted_covertext_body
return covertext | [
"def",
"encode",
"(",
"self",
",",
"X",
",",
"seed",
"=",
"None",
")",
":",
"if",
"not",
"X",
":",
"return",
"''",
"if",
"not",
"isinstance",
"(",
"X",
",",
"str",
")",
":",
"raise",
"InvalidInputException",
"(",
"'Input must be of type string.'",
")",
"if",
"seed",
"is",
"not",
"None",
"and",
"len",
"(",
"seed",
")",
"!=",
"8",
":",
"raise",
"InvalidSeedLength",
"(",
"'The seed is not 8 bytes long, seed length: '",
"+",
"str",
"(",
"len",
"(",
"seed",
")",
")",
")",
"ciphertext",
"=",
"self",
".",
"_encrypter",
".",
"encrypt",
"(",
"X",
")",
"maximumBytesToRank",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"getCapacity",
"(",
")",
"/",
"8.0",
")",
")",
"unrank_payload_len",
"=",
"(",
"maximumBytesToRank",
"-",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_CIPHERTTEXT",
")",
"unrank_payload_len",
"=",
"min",
"(",
"len",
"(",
"ciphertext",
")",
",",
"unrank_payload_len",
")",
"if",
"unrank_payload_len",
"<=",
"0",
":",
"raise",
"InsufficientCapacityException",
"(",
"'Language doesn\\'t have enough capacity'",
")",
"msg_len_header",
"=",
"fte",
".",
"bit_ops",
".",
"long_to_bytes",
"(",
"unrank_payload_len",
")",
"msg_len_header",
"=",
"string",
".",
"rjust",
"(",
"msg_len_header",
",",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_PLAINTEXT",
",",
"'\\x00'",
")",
"random_bytes",
"=",
"seed",
"if",
"seed",
"is",
"not",
"None",
"else",
"fte",
".",
"bit_ops",
".",
"random_bytes",
"(",
"8",
")",
"msg_len_header",
"=",
"random_bytes",
"+",
"msg_len_header",
"msg_len_header",
"=",
"self",
".",
"_encrypter",
".",
"encryptOneBlock",
"(",
"msg_len_header",
")",
"unrank_payload",
"=",
"msg_len_header",
"+",
"ciphertext",
"[",
":",
"maximumBytesToRank",
"-",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_CIPHERTTEXT",
"]",
"random_padding_bytes",
"=",
"maximumBytesToRank",
"-",
"len",
"(",
"unrank_payload",
")",
"if",
"random_padding_bytes",
">",
"0",
":",
"unrank_payload",
"+=",
"fte",
".",
"bit_ops",
".",
"random_bytes",
"(",
"random_padding_bytes",
")",
"unrank_payload",
"=",
"fte",
".",
"bit_ops",
".",
"bytes_to_long",
"(",
"unrank_payload",
")",
"formatted_covertext_header",
"=",
"self",
".",
"_dfa",
".",
"unrank",
"(",
"unrank_payload",
")",
"unformatted_covertext_body",
"=",
"ciphertext",
"[",
"maximumBytesToRank",
"-",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_CIPHERTTEXT",
":",
"]",
"covertext",
"=",
"formatted_covertext_header",
"+",
"unformatted_covertext_body",
"return",
"covertext"
] | Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n``
is the the maximum number of bytes that can be unranked w.r.t. the
capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input
``dfa``. | [
"Given",
"a",
"string",
"X",
"returns",
"unrank",
"(",
"X",
"[",
":",
"n",
"]",
")",
"||",
"X",
"[",
"n",
":",
"]",
"where",
"n",
"is",
"the",
"the",
"maximum",
"number",
"of",
"bytes",
"that",
"can",
"be",
"unranked",
"w",
".",
"r",
".",
"t",
".",
"the",
"capacity",
"of",
"the",
"input",
"dfa",
"and",
"unrank",
"is",
"w",
".",
"r",
".",
"t",
".",
"to",
"the",
"input",
"dfa",
"."
] | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encoder.py#L84-L133 |
kpdyer/libfte | fte/encoder.py | DfaEncoderObject.decode | def decode(self, covertext):
"""Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``.
"""
if not isinstance(covertext, str):
raise InvalidInputException('Input must be of type string.')
insufficient = (len(covertext) < self._fixed_slice)
if insufficient:
raise DecodeFailureError(
"Covertext is shorter than self._fixed_slice, can't decode.")
maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))
rank_payload = self._dfa.rank(covertext[:self._fixed_slice])
X = fte.bit_ops.long_to_bytes(rank_payload)
X = string.rjust(X, maximumBytesToRank, '\x00')
msg_len_header = self._encrypter.decryptOneBlock(
X[:DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT])
msg_len_header = msg_len_header[8:16]
msg_len = fte.bit_ops.bytes_to_long(
msg_len_header[:DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT])
retval = X[16:16 + msg_len]
retval += covertext[self._fixed_slice:]
ctxt_len = self._encrypter.getCiphertextLen(retval)
remaining_buffer = retval[ctxt_len:]
retval = retval[:ctxt_len]
retval = self._encrypter.decrypt(retval)
return retval, remaining_buffer | python | def decode(self, covertext):
"""Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``.
"""
if not isinstance(covertext, str):
raise InvalidInputException('Input must be of type string.')
insufficient = (len(covertext) < self._fixed_slice)
if insufficient:
raise DecodeFailureError(
"Covertext is shorter than self._fixed_slice, can't decode.")
maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))
rank_payload = self._dfa.rank(covertext[:self._fixed_slice])
X = fte.bit_ops.long_to_bytes(rank_payload)
X = string.rjust(X, maximumBytesToRank, '\x00')
msg_len_header = self._encrypter.decryptOneBlock(
X[:DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT])
msg_len_header = msg_len_header[8:16]
msg_len = fte.bit_ops.bytes_to_long(
msg_len_header[:DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT])
retval = X[16:16 + msg_len]
retval += covertext[self._fixed_slice:]
ctxt_len = self._encrypter.getCiphertextLen(retval)
remaining_buffer = retval[ctxt_len:]
retval = retval[:ctxt_len]
retval = self._encrypter.decrypt(retval)
return retval, remaining_buffer | [
"def",
"decode",
"(",
"self",
",",
"covertext",
")",
":",
"if",
"not",
"isinstance",
"(",
"covertext",
",",
"str",
")",
":",
"raise",
"InvalidInputException",
"(",
"'Input must be of type string.'",
")",
"insufficient",
"=",
"(",
"len",
"(",
"covertext",
")",
"<",
"self",
".",
"_fixed_slice",
")",
"if",
"insufficient",
":",
"raise",
"DecodeFailureError",
"(",
"\"Covertext is shorter than self._fixed_slice, can't decode.\"",
")",
"maximumBytesToRank",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"getCapacity",
"(",
")",
"/",
"8.0",
")",
")",
"rank_payload",
"=",
"self",
".",
"_dfa",
".",
"rank",
"(",
"covertext",
"[",
":",
"self",
".",
"_fixed_slice",
"]",
")",
"X",
"=",
"fte",
".",
"bit_ops",
".",
"long_to_bytes",
"(",
"rank_payload",
")",
"X",
"=",
"string",
".",
"rjust",
"(",
"X",
",",
"maximumBytesToRank",
",",
"'\\x00'",
")",
"msg_len_header",
"=",
"self",
".",
"_encrypter",
".",
"decryptOneBlock",
"(",
"X",
"[",
":",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_CIPHERTTEXT",
"]",
")",
"msg_len_header",
"=",
"msg_len_header",
"[",
"8",
":",
"16",
"]",
"msg_len",
"=",
"fte",
".",
"bit_ops",
".",
"bytes_to_long",
"(",
"msg_len_header",
"[",
":",
"DfaEncoderObject",
".",
"_COVERTEXT_HEADER_LEN_PLAINTEXT",
"]",
")",
"retval",
"=",
"X",
"[",
"16",
":",
"16",
"+",
"msg_len",
"]",
"retval",
"+=",
"covertext",
"[",
"self",
".",
"_fixed_slice",
":",
"]",
"ctxt_len",
"=",
"self",
".",
"_encrypter",
".",
"getCiphertextLen",
"(",
"retval",
")",
"remaining_buffer",
"=",
"retval",
"[",
"ctxt_len",
":",
"]",
"retval",
"=",
"retval",
"[",
":",
"ctxt_len",
"]",
"retval",
"=",
"self",
".",
"_encrypter",
".",
"decrypt",
"(",
"retval",
")",
"return",
"retval",
",",
"remaining_buffer"
] | Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. | [
"Given",
"an",
"input",
"string",
"unrank",
"(",
"X",
"[",
":",
"n",
"]",
")",
"||",
"X",
"[",
"n",
":",
"]",
"returns",
"X",
"."
] | train | https://github.com/kpdyer/libfte/blob/74ed6ad197b6e72d1b9709c4dbc04041e05eb9b7/fte/encoder.py#L135-L166 |
oscarlazoarjona/fast | fast/symbolic.py | define_symbol | def define_symbol(name, open_brace, comma, i, j,
close_brace, variables, **kwds):
r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""
>>> close_brace = ""
>>> i = 0
>>> j = 1
>>> f = define_symbol(name, open_brace, comma, i, j, close_brace,
... variables, positive=True)
>>> print f
rho12(t, x, y, z)
"""
if variables is None:
return Symbol(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)
else:
return Function(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)(*variables) | python | def define_symbol(name, open_brace, comma, i, j,
close_brace, variables, **kwds):
r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""
>>> close_brace = ""
>>> i = 0
>>> j = 1
>>> f = define_symbol(name, open_brace, comma, i, j, close_brace,
... variables, positive=True)
>>> print f
rho12(t, x, y, z)
"""
if variables is None:
return Symbol(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)
else:
return Function(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)(*variables) | [
"def",
"define_symbol",
"(",
"name",
",",
"open_brace",
",",
"comma",
",",
"i",
",",
"j",
",",
"close_brace",
",",
"variables",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"variables",
"is",
"None",
":",
"return",
"Symbol",
"(",
"name",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"*",
"*",
"kwds",
")",
"else",
":",
"return",
"Function",
"(",
"name",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"*",
"*",
"kwds",
")",
"(",
"*",
"variables",
")"
] | r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""
>>> close_brace = ""
>>> i = 0
>>> j = 1
>>> f = define_symbol(name, open_brace, comma, i, j, close_brace,
... variables, positive=True)
>>> print f
rho12(t, x, y, z) | [
"r",
"Define",
"a",
"nice",
"symbol",
"with",
"matrix",
"indices",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L59-L83 |
oscarlazoarjona/fast | fast/symbolic.py | polarization_vector | def polarization_vector(phi, theta, alpha, beta, p,
numeric=False, abstract=False):
"""This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - The spherical coordinates polar angle of the wave vector k.
- ``alpha`` - The rotation of a half-wave plate.
- ``beta`` - The rotation of a quarter-wave plate.
- ``p`` - either 1 or -1 to indicate whether to return epsilon^(+) or\
epsilon^(-) respectively.
If alpha and beta are zero, the result will be linearly polarized light
along some fast axis. alpha and beta are measured from that fast axis.
Propagation towards y, linear polarization (for pi transitions):
>>> from sympy import pi
>>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1)
Matrix([
[0],
[0],
[1]])
Propagation towards +z, circular polarization (for sigma + transitions):
>>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Propagation towards -z, circular polarization for sigma + transitions:
>>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Components + and - are complex conjugates of each other
>>> from sympy import symbols
>>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True)
>>> ep = polarization_vector(phi,theta,alpha,beta, 1)
>>> em = polarization_vector(phi,theta,alpha,beta,-1)
>>> ep-em.conjugate()
Matrix([
[0],
[0],
[0]])
We can also define abstract polarization vectors without explicit \
components
>>> polarization_vector(0, 0, 0, 0, 1, abstract=True)
epsilonp
>>> polarization_vector(0, 0, 0, 0, -1, abstract=True)
epsilonm
"""
if abstract:
Nl = symbols("N_l", integer=True)
if p == 1:
epsilon = Vector3D(IndexedBase("epsilonp", shape=(Nl,)))
else:
epsilon = Vector3D(IndexedBase("epsilonm", shape=(Nl,)))
return epsilon
epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0])
R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0],
[sin(2*alpha), cos(2*alpha), 0],
[0, 0, 1]])
R2 = Matrix([[cos(theta), 0, sin(theta)],
[0, 1, 0],
[-sin(theta), 0, cos(theta)]])
R3 = Matrix([[cos(phi), -sin(phi), 0],
[sin(phi), cos(phi), 0],
[0, 0, 1]])
epsilon = R3*R2*R1*epsilon
if numeric:
epsilon = nparray([complex(epsilon[i]) for i in range(3)])
return epsilon | python | def polarization_vector(phi, theta, alpha, beta, p,
numeric=False, abstract=False):
"""This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - The spherical coordinates polar angle of the wave vector k.
- ``alpha`` - The rotation of a half-wave plate.
- ``beta`` - The rotation of a quarter-wave plate.
- ``p`` - either 1 or -1 to indicate whether to return epsilon^(+) or\
epsilon^(-) respectively.
If alpha and beta are zero, the result will be linearly polarized light
along some fast axis. alpha and beta are measured from that fast axis.
Propagation towards y, linear polarization (for pi transitions):
>>> from sympy import pi
>>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1)
Matrix([
[0],
[0],
[1]])
Propagation towards +z, circular polarization (for sigma + transitions):
>>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Propagation towards -z, circular polarization for sigma + transitions:
>>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Components + and - are complex conjugates of each other
>>> from sympy import symbols
>>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True)
>>> ep = polarization_vector(phi,theta,alpha,beta, 1)
>>> em = polarization_vector(phi,theta,alpha,beta,-1)
>>> ep-em.conjugate()
Matrix([
[0],
[0],
[0]])
We can also define abstract polarization vectors without explicit \
components
>>> polarization_vector(0, 0, 0, 0, 1, abstract=True)
epsilonp
>>> polarization_vector(0, 0, 0, 0, -1, abstract=True)
epsilonm
"""
if abstract:
Nl = symbols("N_l", integer=True)
if p == 1:
epsilon = Vector3D(IndexedBase("epsilonp", shape=(Nl,)))
else:
epsilon = Vector3D(IndexedBase("epsilonm", shape=(Nl,)))
return epsilon
epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0])
R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0],
[sin(2*alpha), cos(2*alpha), 0],
[0, 0, 1]])
R2 = Matrix([[cos(theta), 0, sin(theta)],
[0, 1, 0],
[-sin(theta), 0, cos(theta)]])
R3 = Matrix([[cos(phi), -sin(phi), 0],
[sin(phi), cos(phi), 0],
[0, 0, 1]])
epsilon = R3*R2*R1*epsilon
if numeric:
epsilon = nparray([complex(epsilon[i]) for i in range(3)])
return epsilon | [
"def",
"polarization_vector",
"(",
"phi",
",",
"theta",
",",
"alpha",
",",
"beta",
",",
"p",
",",
"numeric",
"=",
"False",
",",
"abstract",
"=",
"False",
")",
":",
"if",
"abstract",
":",
"Nl",
"=",
"symbols",
"(",
"\"N_l\"",
",",
"integer",
"=",
"True",
")",
"if",
"p",
"==",
"1",
":",
"epsilon",
"=",
"Vector3D",
"(",
"IndexedBase",
"(",
"\"epsilonp\"",
",",
"shape",
"=",
"(",
"Nl",
",",
")",
")",
")",
"else",
":",
"epsilon",
"=",
"Vector3D",
"(",
"IndexedBase",
"(",
"\"epsilonm\"",
",",
"shape",
"=",
"(",
"Nl",
",",
")",
")",
")",
"return",
"epsilon",
"epsilon",
"=",
"Matrix",
"(",
"[",
"cos",
"(",
"2",
"*",
"beta",
")",
",",
"p",
"*",
"I",
"*",
"sin",
"(",
"2",
"*",
"beta",
")",
",",
"0",
"]",
")",
"R1",
"=",
"Matrix",
"(",
"[",
"[",
"cos",
"(",
"2",
"*",
"alpha",
")",
",",
"-",
"sin",
"(",
"2",
"*",
"alpha",
")",
",",
"0",
"]",
",",
"[",
"sin",
"(",
"2",
"*",
"alpha",
")",
",",
"cos",
"(",
"2",
"*",
"alpha",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"R2",
"=",
"Matrix",
"(",
"[",
"[",
"cos",
"(",
"theta",
")",
",",
"0",
",",
"sin",
"(",
"theta",
")",
"]",
",",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"[",
"-",
"sin",
"(",
"theta",
")",
",",
"0",
",",
"cos",
"(",
"theta",
")",
"]",
"]",
")",
"R3",
"=",
"Matrix",
"(",
"[",
"[",
"cos",
"(",
"phi",
")",
",",
"-",
"sin",
"(",
"phi",
")",
",",
"0",
"]",
",",
"[",
"sin",
"(",
"phi",
")",
",",
"cos",
"(",
"phi",
")",
",",
"0",
"]",
",",
"[",
"0",
",",
"0",
",",
"1",
"]",
"]",
")",
"epsilon",
"=",
"R3",
"*",
"R2",
"*",
"R1",
"*",
"epsilon",
"if",
"numeric",
":",
"epsilon",
"=",
"nparray",
"(",
"[",
"complex",
"(",
"epsilon",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
"]",
")",
"return",
"epsilon"
] | This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - The spherical coordinates polar angle of the wave vector k.
- ``alpha`` - The rotation of a half-wave plate.
- ``beta`` - The rotation of a quarter-wave plate.
- ``p`` - either 1 or -1 to indicate whether to return epsilon^(+) or\
epsilon^(-) respectively.
If alpha and beta are zero, the result will be linearly polarized light
along some fast axis. alpha and beta are measured from that fast axis.
Propagation towards y, linear polarization (for pi transitions):
>>> from sympy import pi
>>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1)
Matrix([
[0],
[0],
[1]])
Propagation towards +z, circular polarization (for sigma + transitions):
>>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Propagation towards -z, circular polarization for sigma + transitions:
>>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1)
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
Components + and - are complex conjugates of each other
>>> from sympy import symbols
>>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True)
>>> ep = polarization_vector(phi,theta,alpha,beta, 1)
>>> em = polarization_vector(phi,theta,alpha,beta,-1)
>>> ep-em.conjugate()
Matrix([
[0],
[0],
[0]])
We can also define abstract polarization vectors without explicit \
components
>>> polarization_vector(0, 0, 0, 0, 1, abstract=True)
epsilonp
>>> polarization_vector(0, 0, 0, 0, -1, abstract=True)
epsilonm | [
"This",
"function",
"returns",
"a",
"unitary",
"vector",
"describing",
"the",
"polarization",
"of",
"plane",
"waves",
".",
":"
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L208-L297 |
oscarlazoarjona/fast | fast/symbolic.py | cartesian_to_helicity | def cartesian_to_helicity(vector, numeric=False):
r"""This function takes vectors from the cartesian basis to the helicity basis.
For instance, we can check what are the vectors of the helicity basis.
>>> from sympy import pi
>>> em=polarization_vector(phi=0, theta= 0, alpha=0, beta=-pi/8,p= 1)
>>> em
Matrix([
[ sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(em)
Matrix([
[ 0],
[ 0],
[-1]])
>>> e0=polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta=0,p=1)
>>> e0
Matrix([
[0],
[0],
[1]])
>>> cartesian_to_helicity(e0)
Matrix([
[0],
[1],
[0]])
>>> ep=polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p= 1)
>>> ep
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(ep)
Matrix([
[-1],
[ 0],
[ 0]])
Note that vectors in the helicity basis are built in a weird way by
convention:
.. math::
\vec{a} = -a_{+1}\vec{e}_{-1} +a_0\vec{e}_0 -a_{-1}\vec{e}_{+1}
>>> from sympy import symbols
>>> am,a0,ap = symbols("am a0 ap")
>>> a=-ap*em +a0*e0 -am*ep
>>> a
Matrix([
[ sqrt(2)*am/2 - sqrt(2)*ap/2],
[sqrt(2)*I*am/2 + sqrt(2)*I*ap/2],
[ a0]])
>>> cartesian_to_helicity(a).expand()
Matrix([
[am],
[a0],
[ap]])
We can also convert a numeric array
>>> r =[[[0.0, 1.0],
... [1.0, 0.0]],
... [[0.0, -1j],
... [ 1j, 0.0]],
... [[1.0, 0.0],
... [0.0,-1.0]]]
>>> cartesian_to_helicity(r, numeric=True)
array([[[ 0. +0.j, 0. +0.j],
[ 1.4142+0.j, 0. +0.j]],
<BLANKLINE>
[[ 1. +0.j, 0. +0.j],
[ 0. +0.j, -1. +0.j]],
<BLANKLINE>
[[-0. +0.j, -1.4142+0.j],
[-0. +0.j, -0. +0.j]]])
"""
if numeric:
vector = list(vector)
vector[0] = nparray(vector[0])
vector[1] = nparray(vector[1])
vector[2] = nparray(vector[2])
v = [(vector[0]-1j*vector[1])/npsqrt(2),
vector[2],
-(vector[0]+1j*vector[1])/npsqrt(2)]
v = nparray(v)
else:
v = [(vector[0]-I*vector[1])/sqrt(2),
vector[2],
-(vector[0]+I*vector[1])/sqrt(2)]
if type(vector[0]) in [type(Matrix([1, 0])), type(nparray([1, 0]))]:
return v
else:
return Matrix(v) | python | def cartesian_to_helicity(vector, numeric=False):
r"""This function takes vectors from the cartesian basis to the helicity basis.
For instance, we can check what are the vectors of the helicity basis.
>>> from sympy import pi
>>> em=polarization_vector(phi=0, theta= 0, alpha=0, beta=-pi/8,p= 1)
>>> em
Matrix([
[ sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(em)
Matrix([
[ 0],
[ 0],
[-1]])
>>> e0=polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta=0,p=1)
>>> e0
Matrix([
[0],
[0],
[1]])
>>> cartesian_to_helicity(e0)
Matrix([
[0],
[1],
[0]])
>>> ep=polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p= 1)
>>> ep
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(ep)
Matrix([
[-1],
[ 0],
[ 0]])
Note that vectors in the helicity basis are built in a weird way by
convention:
.. math::
\vec{a} = -a_{+1}\vec{e}_{-1} +a_0\vec{e}_0 -a_{-1}\vec{e}_{+1}
>>> from sympy import symbols
>>> am,a0,ap = symbols("am a0 ap")
>>> a=-ap*em +a0*e0 -am*ep
>>> a
Matrix([
[ sqrt(2)*am/2 - sqrt(2)*ap/2],
[sqrt(2)*I*am/2 + sqrt(2)*I*ap/2],
[ a0]])
>>> cartesian_to_helicity(a).expand()
Matrix([
[am],
[a0],
[ap]])
We can also convert a numeric array
>>> r =[[[0.0, 1.0],
... [1.0, 0.0]],
... [[0.0, -1j],
... [ 1j, 0.0]],
... [[1.0, 0.0],
... [0.0,-1.0]]]
>>> cartesian_to_helicity(r, numeric=True)
array([[[ 0. +0.j, 0. +0.j],
[ 1.4142+0.j, 0. +0.j]],
<BLANKLINE>
[[ 1. +0.j, 0. +0.j],
[ 0. +0.j, -1. +0.j]],
<BLANKLINE>
[[-0. +0.j, -1.4142+0.j],
[-0. +0.j, -0. +0.j]]])
"""
if numeric:
vector = list(vector)
vector[0] = nparray(vector[0])
vector[1] = nparray(vector[1])
vector[2] = nparray(vector[2])
v = [(vector[0]-1j*vector[1])/npsqrt(2),
vector[2],
-(vector[0]+1j*vector[1])/npsqrt(2)]
v = nparray(v)
else:
v = [(vector[0]-I*vector[1])/sqrt(2),
vector[2],
-(vector[0]+I*vector[1])/sqrt(2)]
if type(vector[0]) in [type(Matrix([1, 0])), type(nparray([1, 0]))]:
return v
else:
return Matrix(v) | [
"def",
"cartesian_to_helicity",
"(",
"vector",
",",
"numeric",
"=",
"False",
")",
":",
"if",
"numeric",
":",
"vector",
"=",
"list",
"(",
"vector",
")",
"vector",
"[",
"0",
"]",
"=",
"nparray",
"(",
"vector",
"[",
"0",
"]",
")",
"vector",
"[",
"1",
"]",
"=",
"nparray",
"(",
"vector",
"[",
"1",
"]",
")",
"vector",
"[",
"2",
"]",
"=",
"nparray",
"(",
"vector",
"[",
"2",
"]",
")",
"v",
"=",
"[",
"(",
"vector",
"[",
"0",
"]",
"-",
"1j",
"*",
"vector",
"[",
"1",
"]",
")",
"/",
"npsqrt",
"(",
"2",
")",
",",
"vector",
"[",
"2",
"]",
",",
"-",
"(",
"vector",
"[",
"0",
"]",
"+",
"1j",
"*",
"vector",
"[",
"1",
"]",
")",
"/",
"npsqrt",
"(",
"2",
")",
"]",
"v",
"=",
"nparray",
"(",
"v",
")",
"else",
":",
"v",
"=",
"[",
"(",
"vector",
"[",
"0",
"]",
"-",
"I",
"*",
"vector",
"[",
"1",
"]",
")",
"/",
"sqrt",
"(",
"2",
")",
",",
"vector",
"[",
"2",
"]",
",",
"-",
"(",
"vector",
"[",
"0",
"]",
"+",
"I",
"*",
"vector",
"[",
"1",
"]",
")",
"/",
"sqrt",
"(",
"2",
")",
"]",
"if",
"type",
"(",
"vector",
"[",
"0",
"]",
")",
"in",
"[",
"type",
"(",
"Matrix",
"(",
"[",
"1",
",",
"0",
"]",
")",
")",
",",
"type",
"(",
"nparray",
"(",
"[",
"1",
",",
"0",
"]",
")",
")",
"]",
":",
"return",
"v",
"else",
":",
"return",
"Matrix",
"(",
"v",
")"
] | r"""This function takes vectors from the cartesian basis to the helicity basis.
For instance, we can check what are the vectors of the helicity basis.
>>> from sympy import pi
>>> em=polarization_vector(phi=0, theta= 0, alpha=0, beta=-pi/8,p= 1)
>>> em
Matrix([
[ sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(em)
Matrix([
[ 0],
[ 0],
[-1]])
>>> e0=polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta=0,p=1)
>>> e0
Matrix([
[0],
[0],
[1]])
>>> cartesian_to_helicity(e0)
Matrix([
[0],
[1],
[0]])
>>> ep=polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p= 1)
>>> ep
Matrix([
[ -sqrt(2)/2],
[-sqrt(2)*I/2],
[ 0]])
>>> cartesian_to_helicity(ep)
Matrix([
[-1],
[ 0],
[ 0]])
Note that vectors in the helicity basis are built in a weird way by
convention:
.. math::
\vec{a} = -a_{+1}\vec{e}_{-1} +a_0\vec{e}_0 -a_{-1}\vec{e}_{+1}
>>> from sympy import symbols
>>> am,a0,ap = symbols("am a0 ap")
>>> a=-ap*em +a0*e0 -am*ep
>>> a
Matrix([
[ sqrt(2)*am/2 - sqrt(2)*ap/2],
[sqrt(2)*I*am/2 + sqrt(2)*I*ap/2],
[ a0]])
>>> cartesian_to_helicity(a).expand()
Matrix([
[am],
[a0],
[ap]])
We can also convert a numeric array
>>> r =[[[0.0, 1.0],
... [1.0, 0.0]],
... [[0.0, -1j],
... [ 1j, 0.0]],
... [[1.0, 0.0],
... [0.0,-1.0]]]
>>> cartesian_to_helicity(r, numeric=True)
array([[[ 0. +0.j, 0. +0.j],
[ 1.4142+0.j, 0. +0.j]],
<BLANKLINE>
[[ 1. +0.j, 0. +0.j],
[ 0. +0.j, -1. +0.j]],
<BLANKLINE>
[[-0. +0.j, -1.4142+0.j],
[-0. +0.j, -0. +0.j]]]) | [
"r",
"This",
"function",
"takes",
"vectors",
"from",
"the",
"cartesian",
"basis",
"to",
"the",
"helicity",
"basis",
".",
"For",
"instance",
"we",
"can",
"check",
"what",
"are",
"the",
"vectors",
"of",
"the",
"helicity",
"basis",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L300-L400 |
oscarlazoarjona/fast | fast/symbolic.py | define_r_components | def define_r_components(Ne, xi=None, explicitly_hermitian=False,
helicity=False, real=True, p=None):
r"""Define the components of the position operators.
In general, these are representations of the position operators x, y, z
>>> define_r_components(2)
[Matrix([
[ 0, x_{12}],
[x_{21}, 0]]), Matrix([
[ 0, y_{12}],
[y_{21}, 0]]), Matrix([
[ 0, z_{12}],
[z_{21}, 0]])]
We can make these operators explicitly hermitian
>>> define_r_components(2, explicitly_hermitian=True)
[Matrix([
[ 0, x_{21}],
[x_{21}, 0]]), Matrix([
[ 0, y_{21}],
[y_{21}, 0]]), Matrix([
[ 0, z_{21}],
[z_{21}, 0]])]
Make them real
>>> r = define_r_components(2, real=True, explicitly_hermitian=True)
>>> print [r[p]-r[p].transpose() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])]
We can get the components of the operator in the helicity basis
>>> define_r_components(2, helicity=True)
[Matrix([
[ 0, r_{-1;12}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;12}],
[r_{0;21}, 0]]), Matrix([
[ 0, r_{+1;12}],
[r_{+1;21}, 0]])]
And combinations thereof. For instance, let us check that the components
in the helicity basis produce hermitian operators in the cartesian basis.
>>> r_helicity = define_r_components(2, helicity=True,
... explicitly_hermitian=True)
[Matrix([
[ 0, -r_{+1;21}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;21}],
[r_{0;21}, 0]]), Matrix([
[ 0, -r_{-1;21}],
[r_{+1;21}, 0]])]
>>> r_cartesian = helicity_to_cartesian(r_helicity)
>>> r_cartesian[0]
Matrix([
[ 0, sqrt(2)*(-r_{+1;21} + r_{-1;21})/2],
[sqrt(2)*(-r_{+1;21} + r_{-1;21})/2, 0]])
>>> [(r_cartesian[p]-r_cartesian[p].adjoint()).expand() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])]
"""
frequency_sign = p
if Ne > 9: comma = ","
else: comma = ""
if helicity:
names = ["r_{-1;", "r_{0;", "r_{+1;"]
else:
names = ["x", "y", "z"]
r = []
if helicity:
for p in range(3):
r_comp = []
for i in range(Ne):
r_row = []
for j in range(Ne):
if i == j:
r_row += [0]
elif i > j:
r_row += [Symbol(names[p]+str(i+1)+comma+str(j+1)+"}",
real=real)]
elif explicitly_hermitian:
sign = int((-1)**(p-1))
r_row += [sign*conjugate(Symbol(names[2-p]+str(j+1) +
comma+str(i+1)+"}",
real=real))]
else:
r_row += [Symbol(names[p]+str(i+1)+comma+str(j+1)+"}",
real=real)]
r_comp += [r_row]
r_comp = Matrix(r_comp)
r += [r_comp]
else:
for p in range(3):
r_comp = []
for i in range(Ne):
r_row = []
for j in range(Ne):
if i == j:
r_row += [0]
elif i > j:
r_row += [Symbol(names[p]+r"_{"+str(i+1) +
comma+str(j+1)+"}", real=real)]
elif explicitly_hermitian:
r_row += [conjugate(Symbol(names[p]+r"_{"+str(j+1) +
comma+str(i+1)+"}",
real=real))]
else:
r_row += [Symbol(names[p]+r"_{"+str(i+1) +
comma+str(j+1)+"}", real=real)]
r_comp += [r_row]
r_comp = Matrix(r_comp)
r += [r_comp]
# We select only the upper diagonal or lower diagonal components according
# to the sign r^(+) or r^(-) provided.
if frequency_sign == 1:
r = [Matrix([[r[p][i, j]*delta_lesser(i, j)
for j in range(Ne)] for i in range(Ne)])
for p in range(3)]
elif frequency_sign == -1:
r = [Matrix([[r[p][i, j]*delta_greater(i, j)
for j in range(Ne)] for i in range(Ne)])
for p in range(3)]
if xi is not None:
Nl = len(xi)
for p in range(3):
for i in range(Ne):
for j in range(Ne):
zero = True
for l in range(Nl):
if xi[l][i, j] != 0:
zero = False
if zero:
r[p][i, j] = 0
return r | python | def define_r_components(Ne, xi=None, explicitly_hermitian=False,
helicity=False, real=True, p=None):
r"""Define the components of the position operators.
In general, these are representations of the position operators x, y, z
>>> define_r_components(2)
[Matrix([
[ 0, x_{12}],
[x_{21}, 0]]), Matrix([
[ 0, y_{12}],
[y_{21}, 0]]), Matrix([
[ 0, z_{12}],
[z_{21}, 0]])]
We can make these operators explicitly hermitian
>>> define_r_components(2, explicitly_hermitian=True)
[Matrix([
[ 0, x_{21}],
[x_{21}, 0]]), Matrix([
[ 0, y_{21}],
[y_{21}, 0]]), Matrix([
[ 0, z_{21}],
[z_{21}, 0]])]
Make them real
>>> r = define_r_components(2, real=True, explicitly_hermitian=True)
>>> print [r[p]-r[p].transpose() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])]
We can get the components of the operator in the helicity basis
>>> define_r_components(2, helicity=True)
[Matrix([
[ 0, r_{-1;12}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;12}],
[r_{0;21}, 0]]), Matrix([
[ 0, r_{+1;12}],
[r_{+1;21}, 0]])]
And combinations thereof. For instance, let us check that the components
in the helicity basis produce hermitian operators in the cartesian basis.
>>> r_helicity = define_r_components(2, helicity=True,
... explicitly_hermitian=True)
[Matrix([
[ 0, -r_{+1;21}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;21}],
[r_{0;21}, 0]]), Matrix([
[ 0, -r_{-1;21}],
[r_{+1;21}, 0]])]
>>> r_cartesian = helicity_to_cartesian(r_helicity)
>>> r_cartesian[0]
Matrix([
[ 0, sqrt(2)*(-r_{+1;21} + r_{-1;21})/2],
[sqrt(2)*(-r_{+1;21} + r_{-1;21})/2, 0]])
>>> [(r_cartesian[p]-r_cartesian[p].adjoint()).expand() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])]
"""
frequency_sign = p
if Ne > 9: comma = ","
else: comma = ""
if helicity:
names = ["r_{-1;", "r_{0;", "r_{+1;"]
else:
names = ["x", "y", "z"]
r = []
if helicity:
for p in range(3):
r_comp = []
for i in range(Ne):
r_row = []
for j in range(Ne):
if i == j:
r_row += [0]
elif i > j:
r_row += [Symbol(names[p]+str(i+1)+comma+str(j+1)+"}",
real=real)]
elif explicitly_hermitian:
sign = int((-1)**(p-1))
r_row += [sign*conjugate(Symbol(names[2-p]+str(j+1) +
comma+str(i+1)+"}",
real=real))]
else:
r_row += [Symbol(names[p]+str(i+1)+comma+str(j+1)+"}",
real=real)]
r_comp += [r_row]
r_comp = Matrix(r_comp)
r += [r_comp]
else:
for p in range(3):
r_comp = []
for i in range(Ne):
r_row = []
for j in range(Ne):
if i == j:
r_row += [0]
elif i > j:
r_row += [Symbol(names[p]+r"_{"+str(i+1) +
comma+str(j+1)+"}", real=real)]
elif explicitly_hermitian:
r_row += [conjugate(Symbol(names[p]+r"_{"+str(j+1) +
comma+str(i+1)+"}",
real=real))]
else:
r_row += [Symbol(names[p]+r"_{"+str(i+1) +
comma+str(j+1)+"}", real=real)]
r_comp += [r_row]
r_comp = Matrix(r_comp)
r += [r_comp]
# We select only the upper diagonal or lower diagonal components according
# to the sign r^(+) or r^(-) provided.
if frequency_sign == 1:
r = [Matrix([[r[p][i, j]*delta_lesser(i, j)
for j in range(Ne)] for i in range(Ne)])
for p in range(3)]
elif frequency_sign == -1:
r = [Matrix([[r[p][i, j]*delta_greater(i, j)
for j in range(Ne)] for i in range(Ne)])
for p in range(3)]
if xi is not None:
Nl = len(xi)
for p in range(3):
for i in range(Ne):
for j in range(Ne):
zero = True
for l in range(Nl):
if xi[l][i, j] != 0:
zero = False
if zero:
r[p][i, j] = 0
return r | [
"def",
"define_r_components",
"(",
"Ne",
",",
"xi",
"=",
"None",
",",
"explicitly_hermitian",
"=",
"False",
",",
"helicity",
"=",
"False",
",",
"real",
"=",
"True",
",",
"p",
"=",
"None",
")",
":",
"frequency_sign",
"=",
"p",
"if",
"Ne",
">",
"9",
":",
"comma",
"=",
"\",\"",
"else",
":",
"comma",
"=",
"\"\"",
"if",
"helicity",
":",
"names",
"=",
"[",
"\"r_{-1;\"",
",",
"\"r_{0;\"",
",",
"\"r_{+1;\"",
"]",
"else",
":",
"names",
"=",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"z\"",
"]",
"r",
"=",
"[",
"]",
"if",
"helicity",
":",
"for",
"p",
"in",
"range",
"(",
"3",
")",
":",
"r_comp",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"r_row",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"if",
"i",
"==",
"j",
":",
"r_row",
"+=",
"[",
"0",
"]",
"elif",
"i",
">",
"j",
":",
"r_row",
"+=",
"[",
"Symbol",
"(",
"names",
"[",
"p",
"]",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
"]",
"elif",
"explicitly_hermitian",
":",
"sign",
"=",
"int",
"(",
"(",
"-",
"1",
")",
"**",
"(",
"p",
"-",
"1",
")",
")",
"r_row",
"+=",
"[",
"sign",
"*",
"conjugate",
"(",
"Symbol",
"(",
"names",
"[",
"2",
"-",
"p",
"]",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
")",
"]",
"else",
":",
"r_row",
"+=",
"[",
"Symbol",
"(",
"names",
"[",
"p",
"]",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
"]",
"r_comp",
"+=",
"[",
"r_row",
"]",
"r_comp",
"=",
"Matrix",
"(",
"r_comp",
")",
"r",
"+=",
"[",
"r_comp",
"]",
"else",
":",
"for",
"p",
"in",
"range",
"(",
"3",
")",
":",
"r_comp",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"r_row",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"if",
"i",
"==",
"j",
":",
"r_row",
"+=",
"[",
"0",
"]",
"elif",
"i",
">",
"j",
":",
"r_row",
"+=",
"[",
"Symbol",
"(",
"names",
"[",
"p",
"]",
"+",
"r\"_{\"",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
"]",
"elif",
"explicitly_hermitian",
":",
"r_row",
"+=",
"[",
"conjugate",
"(",
"Symbol",
"(",
"names",
"[",
"p",
"]",
"+",
"r\"_{\"",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
")",
"]",
"else",
":",
"r_row",
"+=",
"[",
"Symbol",
"(",
"names",
"[",
"p",
"]",
"+",
"r\"_{\"",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"\"}\"",
",",
"real",
"=",
"real",
")",
"]",
"r_comp",
"+=",
"[",
"r_row",
"]",
"r_comp",
"=",
"Matrix",
"(",
"r_comp",
")",
"r",
"+=",
"[",
"r_comp",
"]",
"# We select only the upper diagonal or lower diagonal components according",
"# to the sign r^(+) or r^(-) provided.",
"if",
"frequency_sign",
"==",
"1",
":",
"r",
"=",
"[",
"Matrix",
"(",
"[",
"[",
"r",
"[",
"p",
"]",
"[",
"i",
",",
"j",
"]",
"*",
"delta_lesser",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
")",
"for",
"p",
"in",
"range",
"(",
"3",
")",
"]",
"elif",
"frequency_sign",
"==",
"-",
"1",
":",
"r",
"=",
"[",
"Matrix",
"(",
"[",
"[",
"r",
"[",
"p",
"]",
"[",
"i",
",",
"j",
"]",
"*",
"delta_greater",
"(",
"i",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
")",
"for",
"p",
"in",
"range",
"(",
"3",
")",
"]",
"if",
"xi",
"is",
"not",
"None",
":",
"Nl",
"=",
"len",
"(",
"xi",
")",
"for",
"p",
"in",
"range",
"(",
"3",
")",
":",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"zero",
"=",
"True",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"if",
"xi",
"[",
"l",
"]",
"[",
"i",
",",
"j",
"]",
"!=",
"0",
":",
"zero",
"=",
"False",
"if",
"zero",
":",
"r",
"[",
"p",
"]",
"[",
"i",
",",
"j",
"]",
"=",
"0",
"return",
"r"
] | r"""Define the components of the position operators.
In general, these are representations of the position operators x, y, z
>>> define_r_components(2)
[Matrix([
[ 0, x_{12}],
[x_{21}, 0]]), Matrix([
[ 0, y_{12}],
[y_{21}, 0]]), Matrix([
[ 0, z_{12}],
[z_{21}, 0]])]
We can make these operators explicitly hermitian
>>> define_r_components(2, explicitly_hermitian=True)
[Matrix([
[ 0, x_{21}],
[x_{21}, 0]]), Matrix([
[ 0, y_{21}],
[y_{21}, 0]]), Matrix([
[ 0, z_{21}],
[z_{21}, 0]])]
Make them real
>>> r = define_r_components(2, real=True, explicitly_hermitian=True)
>>> print [r[p]-r[p].transpose() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])]
We can get the components of the operator in the helicity basis
>>> define_r_components(2, helicity=True)
[Matrix([
[ 0, r_{-1;12}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;12}],
[r_{0;21}, 0]]), Matrix([
[ 0, r_{+1;12}],
[r_{+1;21}, 0]])]
And combinations thereof. For instance, let us check that the components
in the helicity basis produce hermitian operators in the cartesian basis.
>>> r_helicity = define_r_components(2, helicity=True,
... explicitly_hermitian=True)
[Matrix([
[ 0, -r_{+1;21}],
[r_{-1;21}, 0]]), Matrix([
[ 0, r_{0;21}],
[r_{0;21}, 0]]), Matrix([
[ 0, -r_{-1;21}],
[r_{+1;21}, 0]])]
>>> r_cartesian = helicity_to_cartesian(r_helicity)
>>> r_cartesian[0]
Matrix([
[ 0, sqrt(2)*(-r_{+1;21} + r_{-1;21})/2],
[sqrt(2)*(-r_{+1;21} + r_{-1;21})/2, 0]])
>>> [(r_cartesian[p]-r_cartesian[p].adjoint()).expand() for p in range(3)]
[Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]]), Matrix([
[0, 0],
[0, 0]])] | [
"r",
"Define",
"the",
"components",
"of",
"the",
"position",
"operators",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L530-L687 |
oscarlazoarjona/fast | fast/symbolic.py | vector_element | def vector_element(r, i, j):
r"""Extract an matrix element of a vector operator.
>>> r = define_r_components(2)
>>> vector_element(r, 1, 0)
Matrix([
[x_{21}],
[y_{21}],
[z_{21}]])
"""
return Matrix([r[p][i, j] for p in range(3)]) | python | def vector_element(r, i, j):
r"""Extract an matrix element of a vector operator.
>>> r = define_r_components(2)
>>> vector_element(r, 1, 0)
Matrix([
[x_{21}],
[y_{21}],
[z_{21}]])
"""
return Matrix([r[p][i, j] for p in range(3)]) | [
"def",
"vector_element",
"(",
"r",
",",
"i",
",",
"j",
")",
":",
"return",
"Matrix",
"(",
"[",
"r",
"[",
"p",
"]",
"[",
"i",
",",
"j",
"]",
"for",
"p",
"in",
"range",
"(",
"3",
")",
"]",
")"
] | r"""Extract an matrix element of a vector operator.
>>> r = define_r_components(2)
>>> vector_element(r, 1, 0)
Matrix([
[x_{21}],
[y_{21}],
[z_{21}]]) | [
"r",
"Extract",
"an",
"matrix",
"element",
"of",
"a",
"vector",
"operator",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L690-L701 |
oscarlazoarjona/fast | fast/symbolic.py | define_frequencies | def define_frequencies(Ne, explicitly_antisymmetric=False):
u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
β β‘ 0 Οβββ€ β‘ 0 Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
We can make these matrices explicitly antisymmetric.
>>> pprint(define_frequencies(2, explicitly_antisymmetric=True),
... use_unicode=True)
β β‘ 0 -Οβββ€ β‘ 0 -Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
"""
omega_level = [Symbol('omega_'+str(i+1), real=True) for i in range(Ne)]
if Ne > 9:
opening = "\\"
comma = ","
open_brace = "{"
close_brace = "}"
else:
opening = r""
comma = ""
open_brace = ""
close_brace = ""
omega = []; gamma = []
for i in range(Ne):
row_omega = []; row_gamma = []
for j in range(Ne):
if i == j:
om = 0; ga = 0
elif i > j:
om = Symbol(opening+r"omega_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
ga = Symbol(opening+r"gamma_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
elif explicitly_antisymmetric:
om = -Symbol(opening+r"omega_" +
open_brace+str(j+1)+comma+str(i+1) +
close_brace, real=True)
ga = -Symbol(opening+r"gamma_" +
open_brace+str(j+1)+comma+str(i+1) +
close_brace, real=True)
else:
om = Symbol(opening+r"omega_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
ga = Symbol(opening+r"gamma_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
row_omega += [om]
row_gamma += [ga]
omega += [row_omega]
gamma += [row_gamma]
omega = Matrix(omega)
gamma = Matrix(gamma)
return omega_level, omega, gamma | python | def define_frequencies(Ne, explicitly_antisymmetric=False):
u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
β β‘ 0 Οβββ€ β‘ 0 Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
We can make these matrices explicitly antisymmetric.
>>> pprint(define_frequencies(2, explicitly_antisymmetric=True),
... use_unicode=True)
β β‘ 0 -Οβββ€ β‘ 0 -Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
"""
omega_level = [Symbol('omega_'+str(i+1), real=True) for i in range(Ne)]
if Ne > 9:
opening = "\\"
comma = ","
open_brace = "{"
close_brace = "}"
else:
opening = r""
comma = ""
open_brace = ""
close_brace = ""
omega = []; gamma = []
for i in range(Ne):
row_omega = []; row_gamma = []
for j in range(Ne):
if i == j:
om = 0; ga = 0
elif i > j:
om = Symbol(opening+r"omega_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
ga = Symbol(opening+r"gamma_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
elif explicitly_antisymmetric:
om = -Symbol(opening+r"omega_" +
open_brace+str(j+1)+comma+str(i+1) +
close_brace, real=True)
ga = -Symbol(opening+r"gamma_" +
open_brace+str(j+1)+comma+str(i+1) +
close_brace, real=True)
else:
om = Symbol(opening+r"omega_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
ga = Symbol(opening+r"gamma_" +
open_brace+str(i+1)+comma+str(j+1) +
close_brace, real=True)
row_omega += [om]
row_gamma += [ga]
omega += [row_omega]
gamma += [row_gamma]
omega = Matrix(omega)
gamma = Matrix(gamma)
return omega_level, omega, gamma | [
"def",
"define_frequencies",
"(",
"Ne",
",",
"explicitly_antisymmetric",
"=",
"False",
")",
":",
"omega_level",
"=",
"[",
"Symbol",
"(",
"'omega_'",
"+",
"str",
"(",
"i",
"+",
"1",
")",
",",
"real",
"=",
"True",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"]",
"if",
"Ne",
">",
"9",
":",
"opening",
"=",
"\"\\\\\"",
"comma",
"=",
"\",\"",
"open_brace",
"=",
"\"{\"",
"close_brace",
"=",
"\"}\"",
"else",
":",
"opening",
"=",
"r\"\"",
"comma",
"=",
"\"\"",
"open_brace",
"=",
"\"\"",
"close_brace",
"=",
"\"\"",
"omega",
"=",
"[",
"]",
"gamma",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"row_omega",
"=",
"[",
"]",
"row_gamma",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"if",
"i",
"==",
"j",
":",
"om",
"=",
"0",
"ga",
"=",
"0",
"elif",
"i",
">",
"j",
":",
"om",
"=",
"Symbol",
"(",
"opening",
"+",
"r\"omega_\"",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"ga",
"=",
"Symbol",
"(",
"opening",
"+",
"r\"gamma_\"",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"elif",
"explicitly_antisymmetric",
":",
"om",
"=",
"-",
"Symbol",
"(",
"opening",
"+",
"r\"omega_\"",
"+",
"open_brace",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"ga",
"=",
"-",
"Symbol",
"(",
"opening",
"+",
"r\"gamma_\"",
"+",
"open_brace",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"else",
":",
"om",
"=",
"Symbol",
"(",
"opening",
"+",
"r\"omega_\"",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"ga",
"=",
"Symbol",
"(",
"opening",
"+",
"r\"gamma_\"",
"+",
"open_brace",
"+",
"str",
"(",
"i",
"+",
"1",
")",
"+",
"comma",
"+",
"str",
"(",
"j",
"+",
"1",
")",
"+",
"close_brace",
",",
"real",
"=",
"True",
")",
"row_omega",
"+=",
"[",
"om",
"]",
"row_gamma",
"+=",
"[",
"ga",
"]",
"omega",
"+=",
"[",
"row_omega",
"]",
"gamma",
"+=",
"[",
"row_gamma",
"]",
"omega",
"=",
"Matrix",
"(",
"omega",
")",
"gamma",
"=",
"Matrix",
"(",
"gamma",
")",
"return",
"omega_level",
",",
"omega",
",",
"gamma"
] | u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
β β‘ 0 Οβββ€ β‘ 0 Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β
We can make these matrices explicitly antisymmetric.
>>> pprint(define_frequencies(2, explicitly_antisymmetric=True),
... use_unicode=True)
β β‘ 0 -Οβββ€ β‘ 0 -Ξ³βββ€β
β[Οβ, Οβ], β’ β₯, β’ β₯β
β β£Οββ 0 β¦ β£Ξ³ββ 0 β¦β | [
"u",
"Define",
"all",
"frequencies",
"omega_level",
"omega",
"gamma",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L704-L772 |
oscarlazoarjona/fast | fast/symbolic.py | bra | def bra(i, Ne):
r"""This function returns the transpose of the i-th element of the
canonical basis of a Hilbert space of dimension Ne (in the form of a
row vector).
>>> bra(2,4)
Matrix([[0, 1, 0, 0]])
This will return an error if i is not in [1 .. Ne]:
>>> bra(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne].
"""
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]).transpose() | python | def bra(i, Ne):
r"""This function returns the transpose of the i-th element of the
canonical basis of a Hilbert space of dimension Ne (in the form of a
row vector).
>>> bra(2,4)
Matrix([[0, 1, 0, 0]])
This will return an error if i is not in [1 .. Ne]:
>>> bra(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne].
"""
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]).transpose() | [
"def",
"bra",
"(",
"i",
",",
"Ne",
")",
":",
"if",
"i",
"not",
"in",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"i must be in [1 .. Ne].\"",
")",
"return",
"Matrix",
"(",
"[",
"KroneckerDelta",
"(",
"i",
"-",
"1",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
")",
".",
"transpose",
"(",
")"
] | r"""This function returns the transpose of the i-th element of the
canonical basis of a Hilbert space of dimension Ne (in the form of a
row vector).
>>> bra(2,4)
Matrix([[0, 1, 0, 0]])
This will return an error if i is not in [1 .. Ne]:
>>> bra(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne]. | [
"r",
"This",
"function",
"returns",
"the",
"transpose",
"of",
"the",
"i",
"-",
"th",
"element",
"of",
"the",
"canonical",
"basis",
"of",
"a",
"Hilbert",
"space",
"of",
"dimension",
"Ne",
"(",
"in",
"the",
"form",
"of",
"a",
"row",
"vector",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L801-L819 |
oscarlazoarjona/fast | fast/symbolic.py | ket | def ket(i, Ne):
r"""This function returns the i-th element of the canonical basis
of a Hilbert space of dimension Ne (in the form of a column vector).
>>> ket(2,4)
Matrix([
[0],
[1],
[0],
[0]])
This will return an error if i is not in [1 .. Ne]:
>>> ket(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne].
"""
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]) | python | def ket(i, Ne):
r"""This function returns the i-th element of the canonical basis
of a Hilbert space of dimension Ne (in the form of a column vector).
>>> ket(2,4)
Matrix([
[0],
[1],
[0],
[0]])
This will return an error if i is not in [1 .. Ne]:
>>> ket(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne].
"""
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]) | [
"def",
"ket",
"(",
"i",
",",
"Ne",
")",
":",
"if",
"i",
"not",
"in",
"range",
"(",
"1",
",",
"Ne",
"+",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"i must be in [1 .. Ne].\"",
")",
"return",
"Matrix",
"(",
"[",
"KroneckerDelta",
"(",
"i",
"-",
"1",
",",
"j",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"]",
")"
] | r"""This function returns the i-th element of the canonical basis
of a Hilbert space of dimension Ne (in the form of a column vector).
>>> ket(2,4)
Matrix([
[0],
[1],
[0],
[0]])
This will return an error if i is not in [1 .. Ne]:
>>> ket(5,3)
Traceback (most recent call last):
...
ValueError: i must be in [1 .. Ne]. | [
"r",
"This",
"function",
"returns",
"the",
"i",
"-",
"th",
"element",
"of",
"the",
"canonical",
"basis",
"of",
"a",
"Hilbert",
"space",
"of",
"dimension",
"Ne",
"(",
"in",
"the",
"form",
"of",
"a",
"column",
"vector",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L822-L843 |
oscarlazoarjona/fast | fast/symbolic.py | ketbra | def ketbra(i, j, Ne):
"""This function returns the outer product :math:`|i><j|` where\
:math:`|i>` and :math:`|j>` are elements of the canonical basis of an\
Ne-dimensional Hilbert space (in matrix form).
>>> ketbra(2, 3, 3)
Matrix([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]])
"""
return ket(i, Ne)*bra(j, Ne) | python | def ketbra(i, j, Ne):
"""This function returns the outer product :math:`|i><j|` where\
:math:`|i>` and :math:`|j>` are elements of the canonical basis of an\
Ne-dimensional Hilbert space (in matrix form).
>>> ketbra(2, 3, 3)
Matrix([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]])
"""
return ket(i, Ne)*bra(j, Ne) | [
"def",
"ketbra",
"(",
"i",
",",
"j",
",",
"Ne",
")",
":",
"return",
"ket",
"(",
"i",
",",
"Ne",
")",
"*",
"bra",
"(",
"j",
",",
"Ne",
")"
] | This function returns the outer product :math:`|i><j|` where\
:math:`|i>` and :math:`|j>` are elements of the canonical basis of an\
Ne-dimensional Hilbert space (in matrix form).
>>> ketbra(2, 3, 3)
Matrix([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]) | [
"This",
"function",
"returns",
"the",
"outer",
"product",
":",
"math",
":",
"|i",
">",
"<j|",
"where",
"\\",
":",
"math",
":",
"|i",
">",
"and",
":",
"math",
":",
"|j",
">",
"are",
"elements",
"of",
"the",
"canonical",
"basis",
"of",
"an",
"\\",
"Ne",
"-",
"dimensional",
"Hilbert",
"space",
"(",
"in",
"matrix",
"form",
")",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L846-L858 |
oscarlazoarjona/fast | fast/symbolic.py | sigma_operator_indices | def sigma_operator_indices(A):
r"""If A is an outer-product type operator |a><b| return a, b.
>>> sig = ket(2, 3)*bra(1, 3)
>>> sigma_operator_indices(sig)
(1, 0)
>>> sigma_operator_indices(sig+sig.adjoint())
(None, None)
"""
Ne = A.shape[0]
band = True
if sum(A) != 1:
band = False
a = None; b = None
for i in range(Ne):
for j in range(Ne):
if A[i, j] == 1:
a = i; b = j
elif A[i, j] != 0:
band = False
if band:
return a, b
else:
return None, None | python | def sigma_operator_indices(A):
r"""If A is an outer-product type operator |a><b| return a, b.
>>> sig = ket(2, 3)*bra(1, 3)
>>> sigma_operator_indices(sig)
(1, 0)
>>> sigma_operator_indices(sig+sig.adjoint())
(None, None)
"""
Ne = A.shape[0]
band = True
if sum(A) != 1:
band = False
a = None; b = None
for i in range(Ne):
for j in range(Ne):
if A[i, j] == 1:
a = i; b = j
elif A[i, j] != 0:
band = False
if band:
return a, b
else:
return None, None | [
"def",
"sigma_operator_indices",
"(",
"A",
")",
":",
"Ne",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
"band",
"=",
"True",
"if",
"sum",
"(",
"A",
")",
"!=",
"1",
":",
"band",
"=",
"False",
"a",
"=",
"None",
"b",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"if",
"A",
"[",
"i",
",",
"j",
"]",
"==",
"1",
":",
"a",
"=",
"i",
"b",
"=",
"j",
"elif",
"A",
"[",
"i",
",",
"j",
"]",
"!=",
"0",
":",
"band",
"=",
"False",
"if",
"band",
":",
"return",
"a",
",",
"b",
"else",
":",
"return",
"None",
",",
"None"
] | r"""If A is an outer-product type operator |a><b| return a, b.
>>> sig = ket(2, 3)*bra(1, 3)
>>> sigma_operator_indices(sig)
(1, 0)
>>> sigma_operator_indices(sig+sig.adjoint())
(None, None) | [
"r",
"If",
"A",
"is",
"an",
"outer",
"-",
"product",
"type",
"operator",
"|a",
">",
"<b|",
"return",
"a",
"b",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L861-L886 |
oscarlazoarjona/fast | fast/symbolic.py | lindblad_operator | def lindblad_operator(A, rho):
r"""This function returns the action of a Lindblad operator A on a density\
matrix rho. This is defined as :
.. math::
\mathcal{L}(A, \rho) = A \rho A^\dagger -
(A^\dagger A \rho + \rho A^\dagger A)/2.
>>> rho=define_density_matrix(3)
>>> lindblad_operator( ketbra(1,2,3) ,rho )
Matrix([
[ rho22, -rho12/2, 0],
[-rho21/2, -rho22, -rho23/2],
[ 0, -rho32/2, 0]])
"""
a, b = sigma_operator_indices(A)
# print(111, a, b)
if a is not None and b is not None:
Ne = A.shape[0]
L = zeros(Ne, Ne)
L[a, a] += rho[b, b]
for j in range(Ne):
L[b, j] += -rho[b, j]/2
for i in range(Ne):
L[i, b] += -rho[i, b]/2
return L
else:
return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2 | python | def lindblad_operator(A, rho):
r"""This function returns the action of a Lindblad operator A on a density\
matrix rho. This is defined as :
.. math::
\mathcal{L}(A, \rho) = A \rho A^\dagger -
(A^\dagger A \rho + \rho A^\dagger A)/2.
>>> rho=define_density_matrix(3)
>>> lindblad_operator( ketbra(1,2,3) ,rho )
Matrix([
[ rho22, -rho12/2, 0],
[-rho21/2, -rho22, -rho23/2],
[ 0, -rho32/2, 0]])
"""
a, b = sigma_operator_indices(A)
# print(111, a, b)
if a is not None and b is not None:
Ne = A.shape[0]
L = zeros(Ne, Ne)
L[a, a] += rho[b, b]
for j in range(Ne):
L[b, j] += -rho[b, j]/2
for i in range(Ne):
L[i, b] += -rho[i, b]/2
return L
else:
return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2 | [
"def",
"lindblad_operator",
"(",
"A",
",",
"rho",
")",
":",
"a",
",",
"b",
"=",
"sigma_operator_indices",
"(",
"A",
")",
"# print(111, a, b)",
"if",
"a",
"is",
"not",
"None",
"and",
"b",
"is",
"not",
"None",
":",
"Ne",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
"L",
"=",
"zeros",
"(",
"Ne",
",",
"Ne",
")",
"L",
"[",
"a",
",",
"a",
"]",
"+=",
"rho",
"[",
"b",
",",
"b",
"]",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"L",
"[",
"b",
",",
"j",
"]",
"+=",
"-",
"rho",
"[",
"b",
",",
"j",
"]",
"/",
"2",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"L",
"[",
"i",
",",
"b",
"]",
"+=",
"-",
"rho",
"[",
"i",
",",
"b",
"]",
"/",
"2",
"return",
"L",
"else",
":",
"return",
"A",
"*",
"rho",
"*",
"A",
".",
"adjoint",
"(",
")",
"-",
"(",
"A",
".",
"adjoint",
"(",
")",
"*",
"A",
"*",
"rho",
"+",
"rho",
"*",
"A",
".",
"adjoint",
"(",
")",
"*",
"A",
")",
"/",
"2"
] | r"""This function returns the action of a Lindblad operator A on a density\
matrix rho. This is defined as :
.. math::
\mathcal{L}(A, \rho) = A \rho A^\dagger -
(A^\dagger A \rho + \rho A^\dagger A)/2.
>>> rho=define_density_matrix(3)
>>> lindblad_operator( ketbra(1,2,3) ,rho )
Matrix([
[ rho22, -rho12/2, 0],
[-rho21/2, -rho22, -rho23/2],
[ 0, -rho32/2, 0]]) | [
"r",
"This",
"function",
"returns",
"the",
"action",
"of",
"a",
"Lindblad",
"operator",
"A",
"on",
"a",
"density",
"\\",
"matrix",
"rho",
".",
"This",
"is",
"defined",
"as",
":"
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L889-L920 |
oscarlazoarjona/fast | fast/symbolic.py | lindblad_terms | def lindblad_terms(gamma, rho, Ne, verbose=1):
u"""Return the Lindblad terms for decays gamma in matrix form.
>>> from sympy import pprint
>>> aux = define_frequencies(4, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3, 1]:0})
>>> pprint(gamma, use_unicode=True)
β‘ 0 -Ξ³ββ 0 0 β€
β’ β₯
β’Ξ³ββ 0 -Ξ³ββ 0 β₯
β’ β₯
β’ 0 Ξ³ββ 0 -Ξ³βββ₯
β’ β₯
β£ 0 0 Ξ³ββ 0 β¦
>>> rho = define_density_matrix(4)
>>> pprint(lindblad_terms(gamma, rho, 4), use_unicode=True)
β‘ -Ξ³βββ
Οββ -Ξ³βββ
Οββ -Ξ³βββ
Οββ β€
β’ Ξ³βββ
Οββ βββββββββ βββββββββ βββββββββ β₯
β’ 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - βββββββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ β₯
β’βββββββββ - βββββββ - βββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ β₯
β£ 2 2 2 2 2 β¦
Notice that there are more terms than simply adding a decay
gamma_ij*rho_ij/2 for each coherence.
"""
# We count the necessary Lindblad operators.
Nterms = 0
for i in range(Ne):
for j in range(i):
if gamma[i, j] != 0:
Nterms += 1
L = zeros(Ne)
counter = 0
t0 = time()
for i in range(Ne):
for j in range(i):
if gamma[i, j] != 0:
counter += 1
sig = ket(j+1, Ne)*bra(i+1, Ne)
L += gamma[i, j]*lindblad_operator(sig, rho)
tn = time()
if tn-t0 > 1:
aux = "Calculated up to i={}, j={}, or {}/{} = {:2.2f} %."
if verbose > 0:
print(aux.format(i, j, counter, Nterms,
float(counter+1)/Nterms*100))
t0 = tn
return L | python | def lindblad_terms(gamma, rho, Ne, verbose=1):
u"""Return the Lindblad terms for decays gamma in matrix form.
>>> from sympy import pprint
>>> aux = define_frequencies(4, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3, 1]:0})
>>> pprint(gamma, use_unicode=True)
β‘ 0 -Ξ³ββ 0 0 β€
β’ β₯
β’Ξ³ββ 0 -Ξ³ββ 0 β₯
β’ β₯
β’ 0 Ξ³ββ 0 -Ξ³βββ₯
β’ β₯
β£ 0 0 Ξ³ββ 0 β¦
>>> rho = define_density_matrix(4)
>>> pprint(lindblad_terms(gamma, rho, 4), use_unicode=True)
β‘ -Ξ³βββ
Οββ -Ξ³βββ
Οββ -Ξ³βββ
Οββ β€
β’ Ξ³βββ
Οββ βββββββββ βββββββββ βββββββββ β₯
β’ 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - βββββββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ β₯
β’βββββββββ - βββββββ - βββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ β₯
β£ 2 2 2 2 2 β¦
Notice that there are more terms than simply adding a decay
gamma_ij*rho_ij/2 for each coherence.
"""
# We count the necessary Lindblad operators.
Nterms = 0
for i in range(Ne):
for j in range(i):
if gamma[i, j] != 0:
Nterms += 1
L = zeros(Ne)
counter = 0
t0 = time()
for i in range(Ne):
for j in range(i):
if gamma[i, j] != 0:
counter += 1
sig = ket(j+1, Ne)*bra(i+1, Ne)
L += gamma[i, j]*lindblad_operator(sig, rho)
tn = time()
if tn-t0 > 1:
aux = "Calculated up to i={}, j={}, or {}/{} = {:2.2f} %."
if verbose > 0:
print(aux.format(i, j, counter, Nterms,
float(counter+1)/Nterms*100))
t0 = tn
return L | [
"def",
"lindblad_terms",
"(",
"gamma",
",",
"rho",
",",
"Ne",
",",
"verbose",
"=",
"1",
")",
":",
"# We count the necessary Lindblad operators.",
"Nterms",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"if",
"gamma",
"[",
"i",
",",
"j",
"]",
"!=",
"0",
":",
"Nterms",
"+=",
"1",
"L",
"=",
"zeros",
"(",
"Ne",
")",
"counter",
"=",
"0",
"t0",
"=",
"time",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
")",
":",
"if",
"gamma",
"[",
"i",
",",
"j",
"]",
"!=",
"0",
":",
"counter",
"+=",
"1",
"sig",
"=",
"ket",
"(",
"j",
"+",
"1",
",",
"Ne",
")",
"*",
"bra",
"(",
"i",
"+",
"1",
",",
"Ne",
")",
"L",
"+=",
"gamma",
"[",
"i",
",",
"j",
"]",
"*",
"lindblad_operator",
"(",
"sig",
",",
"rho",
")",
"tn",
"=",
"time",
"(",
")",
"if",
"tn",
"-",
"t0",
">",
"1",
":",
"aux",
"=",
"\"Calculated up to i={}, j={}, or {}/{} = {:2.2f} %.\"",
"if",
"verbose",
">",
"0",
":",
"print",
"(",
"aux",
".",
"format",
"(",
"i",
",",
"j",
",",
"counter",
",",
"Nterms",
",",
"float",
"(",
"counter",
"+",
"1",
")",
"/",
"Nterms",
"*",
"100",
")",
")",
"t0",
"=",
"tn",
"return",
"L"
] | u"""Return the Lindblad terms for decays gamma in matrix form.
>>> from sympy import pprint
>>> aux = define_frequencies(4, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3, 1]:0})
>>> pprint(gamma, use_unicode=True)
β‘ 0 -Ξ³ββ 0 0 β€
β’ β₯
β’Ξ³ββ 0 -Ξ³ββ 0 β₯
β’ β₯
β’ 0 Ξ³ββ 0 -Ξ³βββ₯
β’ β₯
β£ 0 0 Ξ³ββ 0 β¦
>>> rho = define_density_matrix(4)
>>> pprint(lindblad_terms(gamma, rho, 4), use_unicode=True)
β‘ -Ξ³βββ
Οββ -Ξ³βββ
Οββ -Ξ³βββ
Οββ β€
β’ Ξ³βββ
Οββ βββββββββ βββββββββ βββββββββ β₯
β’ 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - βββββββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οβββ₯
β’βββββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ + Ξ³βββ
Οββ - βββββββ - ββββββββ₯
β’ 2 2 2 2 2 β₯
β’ β₯
β’-Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ Ξ³βββ
Οββ β₯
β’βββββββββ - βββββββ - βββββββ - βββββββ - βββββββ -Ξ³βββ
Οββ β₯
β£ 2 2 2 2 2 β¦
Notice that there are more terms than simply adding a decay
gamma_ij*rho_ij/2 for each coherence. | [
"u",
"Return",
"the",
"Lindblad",
"terms",
"for",
"decays",
"gamma",
"in",
"matrix",
"form",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L923-L983 |
oscarlazoarjona/fast | fast/symbolic.py | define_rho_vector | def define_rho_vector(rho, Ne):
u"""Define the vectorized density matrix.
>>> from sympy import pprint
>>> rho = define_density_matrix(3)
>>> pprint(define_rho_vector(rho, 3), use_unicode=True)
β‘ Οββ β€
β’ β₯
β’ Οββ β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β£im(Οββ)β¦
"""
rho_vect = []
for mu in range(1, Ne**2):
i, j, s = IJ(mu, Ne)
i = i-1; j = j-1
rho_vect += [part_symbolic(rho[i, j], s)]
return Matrix(rho_vect) | python | def define_rho_vector(rho, Ne):
u"""Define the vectorized density matrix.
>>> from sympy import pprint
>>> rho = define_density_matrix(3)
>>> pprint(define_rho_vector(rho, 3), use_unicode=True)
β‘ Οββ β€
β’ β₯
β’ Οββ β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β£im(Οββ)β¦
"""
rho_vect = []
for mu in range(1, Ne**2):
i, j, s = IJ(mu, Ne)
i = i-1; j = j-1
rho_vect += [part_symbolic(rho[i, j], s)]
return Matrix(rho_vect) | [
"def",
"define_rho_vector",
"(",
"rho",
",",
"Ne",
")",
":",
"rho_vect",
"=",
"[",
"]",
"for",
"mu",
"in",
"range",
"(",
"1",
",",
"Ne",
"**",
"2",
")",
":",
"i",
",",
"j",
",",
"s",
"=",
"IJ",
"(",
"mu",
",",
"Ne",
")",
"i",
"=",
"i",
"-",
"1",
"j",
"=",
"j",
"-",
"1",
"rho_vect",
"+=",
"[",
"part_symbolic",
"(",
"rho",
"[",
"i",
",",
"j",
"]",
",",
"s",
")",
"]",
"return",
"Matrix",
"(",
"rho_vect",
")"
] | u"""Define the vectorized density matrix.
>>> from sympy import pprint
>>> rho = define_density_matrix(3)
>>> pprint(define_rho_vector(rho, 3), use_unicode=True)
β‘ Οββ β€
β’ β₯
β’ Οββ β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’re(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β’im(Οββ)β₯
β’ β₯
β£im(Οββ)β¦ | [
"u",
"Define",
"the",
"vectorized",
"density",
"matrix",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1021-L1049 |
oscarlazoarjona/fast | fast/symbolic.py | calculate_A_b | def calculate_A_b(eqs, unfolding, verbose=0):
u"""Calculate the equations in matrix form.
>>> from sympy import symbols, pprint, I
>>> rho = define_density_matrix(2, explicitly_hermitian=True,
... normalized=True)
>>> Omega = symbols("Omega")
>>> delta = symbols("delta", real=True)
>>> hbar = symbols("hbar", positive=True)
>>> H = hbar*Matrix([[0, Omega.conjugate()/2], [Omega/2, -delta]])
>>> Ne = 2
>>> aux = define_frequencies(Ne, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> eqs = I/hbar*(rho*H-H*rho) + lindblad_terms(gamma, rho, 2)
>>> from fast import Unfolding
>>> unfolding = Unfolding(Ne, True, True, True)
>>> A, b = calculate_A_b(eqs, unfolding)
>>> pprint(A, use_unicode=True)
β‘ -Ξ³ββ im(Ξ©) -re(Ξ©)β€
β’ β₯
β’ -Ξ³ββ β₯
β’-im(Ξ©) βββββ -Ξ΄ β₯
β’ 2 β₯
β’ β₯
β’ -Ξ³ββ β₯
β’re(Ξ©) Ξ΄ βββββ β₯
β£ 2 β¦
>>> pprint(b, use_unicode=True)
β‘ 0 β€
β’ β₯
β’-im(Ξ©) β₯
β’ββββββββ₯
β’ 2 β₯
β’ β₯
β’ re(Ξ©) β₯
β’ βββββ β₯
β£ 2 β¦
"""
Ne = unfolding.Ne
Nrho = unfolding.Nrho
lower_triangular = unfolding.lower_triangular
rho = define_density_matrix(Ne, explicitly_hermitian=lower_triangular,
normalized=unfolding.normalized)
rho_vect = unfolding(rho)
if unfolding.real:
ss_comp = {rho[i, j]: re(rho[i, j])+I*im(rho[i, j])
for j in range(Ne) for i in range(Ne)}
A = []; b = []
for mu in range(Nrho):
s, i, j = unfolding.IJ(mu)
if verbose > 0: print mu
eq = part_symbolic(eqs[i, j].subs(ss_comp), s)
eq_new = 0
row = []
for nu in range(Nrho):
variable = rho_vect[nu]
coefficient = Derivative(eq, variable).doit()
row += [coefficient]
eq_new += coefficient*variable
b += [-(eq-eq_new).expand()]
A += [row]
A = Matrix(A); b = Matrix(b)
return A, b | python | def calculate_A_b(eqs, unfolding, verbose=0):
u"""Calculate the equations in matrix form.
>>> from sympy import symbols, pprint, I
>>> rho = define_density_matrix(2, explicitly_hermitian=True,
... normalized=True)
>>> Omega = symbols("Omega")
>>> delta = symbols("delta", real=True)
>>> hbar = symbols("hbar", positive=True)
>>> H = hbar*Matrix([[0, Omega.conjugate()/2], [Omega/2, -delta]])
>>> Ne = 2
>>> aux = define_frequencies(Ne, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> eqs = I/hbar*(rho*H-H*rho) + lindblad_terms(gamma, rho, 2)
>>> from fast import Unfolding
>>> unfolding = Unfolding(Ne, True, True, True)
>>> A, b = calculate_A_b(eqs, unfolding)
>>> pprint(A, use_unicode=True)
β‘ -Ξ³ββ im(Ξ©) -re(Ξ©)β€
β’ β₯
β’ -Ξ³ββ β₯
β’-im(Ξ©) βββββ -Ξ΄ β₯
β’ 2 β₯
β’ β₯
β’ -Ξ³ββ β₯
β’re(Ξ©) Ξ΄ βββββ β₯
β£ 2 β¦
>>> pprint(b, use_unicode=True)
β‘ 0 β€
β’ β₯
β’-im(Ξ©) β₯
β’ββββββββ₯
β’ 2 β₯
β’ β₯
β’ re(Ξ©) β₯
β’ βββββ β₯
β£ 2 β¦
"""
Ne = unfolding.Ne
Nrho = unfolding.Nrho
lower_triangular = unfolding.lower_triangular
rho = define_density_matrix(Ne, explicitly_hermitian=lower_triangular,
normalized=unfolding.normalized)
rho_vect = unfolding(rho)
if unfolding.real:
ss_comp = {rho[i, j]: re(rho[i, j])+I*im(rho[i, j])
for j in range(Ne) for i in range(Ne)}
A = []; b = []
for mu in range(Nrho):
s, i, j = unfolding.IJ(mu)
if verbose > 0: print mu
eq = part_symbolic(eqs[i, j].subs(ss_comp), s)
eq_new = 0
row = []
for nu in range(Nrho):
variable = rho_vect[nu]
coefficient = Derivative(eq, variable).doit()
row += [coefficient]
eq_new += coefficient*variable
b += [-(eq-eq_new).expand()]
A += [row]
A = Matrix(A); b = Matrix(b)
return A, b | [
"def",
"calculate_A_b",
"(",
"eqs",
",",
"unfolding",
",",
"verbose",
"=",
"0",
")",
":",
"Ne",
"=",
"unfolding",
".",
"Ne",
"Nrho",
"=",
"unfolding",
".",
"Nrho",
"lower_triangular",
"=",
"unfolding",
".",
"lower_triangular",
"rho",
"=",
"define_density_matrix",
"(",
"Ne",
",",
"explicitly_hermitian",
"=",
"lower_triangular",
",",
"normalized",
"=",
"unfolding",
".",
"normalized",
")",
"rho_vect",
"=",
"unfolding",
"(",
"rho",
")",
"if",
"unfolding",
".",
"real",
":",
"ss_comp",
"=",
"{",
"rho",
"[",
"i",
",",
"j",
"]",
":",
"re",
"(",
"rho",
"[",
"i",
",",
"j",
"]",
")",
"+",
"I",
"*",
"im",
"(",
"rho",
"[",
"i",
",",
"j",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"}",
"A",
"=",
"[",
"]",
"b",
"=",
"[",
"]",
"for",
"mu",
"in",
"range",
"(",
"Nrho",
")",
":",
"s",
",",
"i",
",",
"j",
"=",
"unfolding",
".",
"IJ",
"(",
"mu",
")",
"if",
"verbose",
">",
"0",
":",
"print",
"mu",
"eq",
"=",
"part_symbolic",
"(",
"eqs",
"[",
"i",
",",
"j",
"]",
".",
"subs",
"(",
"ss_comp",
")",
",",
"s",
")",
"eq_new",
"=",
"0",
"row",
"=",
"[",
"]",
"for",
"nu",
"in",
"range",
"(",
"Nrho",
")",
":",
"variable",
"=",
"rho_vect",
"[",
"nu",
"]",
"coefficient",
"=",
"Derivative",
"(",
"eq",
",",
"variable",
")",
".",
"doit",
"(",
")",
"row",
"+=",
"[",
"coefficient",
"]",
"eq_new",
"+=",
"coefficient",
"*",
"variable",
"b",
"+=",
"[",
"-",
"(",
"eq",
"-",
"eq_new",
")",
".",
"expand",
"(",
")",
"]",
"A",
"+=",
"[",
"row",
"]",
"A",
"=",
"Matrix",
"(",
"A",
")",
"b",
"=",
"Matrix",
"(",
"b",
")",
"return",
"A",
",",
"b"
] | u"""Calculate the equations in matrix form.
>>> from sympy import symbols, pprint, I
>>> rho = define_density_matrix(2, explicitly_hermitian=True,
... normalized=True)
>>> Omega = symbols("Omega")
>>> delta = symbols("delta", real=True)
>>> hbar = symbols("hbar", positive=True)
>>> H = hbar*Matrix([[0, Omega.conjugate()/2], [Omega/2, -delta]])
>>> Ne = 2
>>> aux = define_frequencies(Ne, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> eqs = I/hbar*(rho*H-H*rho) + lindblad_terms(gamma, rho, 2)
>>> from fast import Unfolding
>>> unfolding = Unfolding(Ne, True, True, True)
>>> A, b = calculate_A_b(eqs, unfolding)
>>> pprint(A, use_unicode=True)
β‘ -Ξ³ββ im(Ξ©) -re(Ξ©)β€
β’ β₯
β’ -Ξ³ββ β₯
β’-im(Ξ©) βββββ -Ξ΄ β₯
β’ 2 β₯
β’ β₯
β’ -Ξ³ββ β₯
β’re(Ξ©) Ξ΄ βββββ β₯
β£ 2 β¦
>>> pprint(b, use_unicode=True)
β‘ 0 β€
β’ β₯
β’-im(Ξ©) β₯
β’ββββββββ₯
β’ 2 β₯
β’ β₯
β’ re(Ξ©) β₯
β’ βββββ β₯
β£ 2 β¦ | [
"u",
"Calculate",
"the",
"equations",
"in",
"matrix",
"form",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1052-L1124 |
oscarlazoarjona/fast | fast/symbolic.py | phase_transformation | def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase):
r"""Obtain a phase transformation to eliminate explicit time dependence.
>>> Ne = 2
"""
ph = find_phase_transformation(Ne, Nl, r, Lij)
return {phase[i]: sum([ph[i][j]*omega_laser[j] for j in range(Nl)])
for i in range(Ne)} | python | def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase):
r"""Obtain a phase transformation to eliminate explicit time dependence.
>>> Ne = 2
"""
ph = find_phase_transformation(Ne, Nl, r, Lij)
return {phase[i]: sum([ph[i][j]*omega_laser[j] for j in range(Nl)])
for i in range(Ne)} | [
"def",
"phase_transformation",
"(",
"Ne",
",",
"Nl",
",",
"r",
",",
"Lij",
",",
"omega_laser",
",",
"phase",
")",
":",
"ph",
"=",
"find_phase_transformation",
"(",
"Ne",
",",
"Nl",
",",
"r",
",",
"Lij",
")",
"return",
"{",
"phase",
"[",
"i",
"]",
":",
"sum",
"(",
"[",
"ph",
"[",
"i",
"]",
"[",
"j",
"]",
"*",
"omega_laser",
"[",
"j",
"]",
"for",
"j",
"in",
"range",
"(",
"Nl",
")",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
"}"
] | r"""Obtain a phase transformation to eliminate explicit time dependence.
>>> Ne = 2 | [
"r",
"Obtain",
"a",
"phase",
"transformation",
"to",
"eliminate",
"explicit",
"time",
"dependence",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1127-L1136 |
oscarlazoarjona/fast | fast/symbolic.py | hamiltonian | def hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, omega_laser, xi,
RWA=True, RF=True):
r"""Return symbolic Hamiltonian.
>>> from sympy import zeros, pi, pprint, symbols
>>> Ne = 3
>>> Nl = 2
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> epsilonp = [polarization_vector(0, -pi/2, 0, 0, 1) for l in range(Nl)]
>>> detuning_knob = symbols("delta1 delta2", real=True)
>>> xi = [zeros(Ne, Ne) for l in range(Nl)]
>>> coup = [[(1, 0)], [(2, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... xi[l][pair[0], pair[1]] = 1
... xi[l][pair[1], pair[0]] = 1
>>> rm = define_r_components(Ne, xi, explicitly_hermitian=True,
... helicity=True, p=-1)
>>> rm = helicity_to_cartesian(rm)
>>> omega_level, omega, gamma = define_frequencies(Ne, True)
>>> H = hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level,
... omega_laser, xi, RWA=True, RF=False)
>>> print H[1, 0]
-E_{01}*e*r_{0;21}*exp(-I*t*varpi_1)/2
>>> print H[2, 0]
-E_{02}*e*r_{0;31}*exp(-I*t*varpi_2)/2
>>> print H[2, 2]
hbar*omega_3
"""
# We check what RF is.
if type(RF) == list:
theta = RF[:]
RF = True
elif type(RF) == Matrix:
theta = [RF[i, 0] for i in range(RF.shape[0])]
RF = True
elif RF:
# theta should be calculate here!
s = "We are still missing automatic calculation of phase "
s += "transformations."
raise ValueError(s)
if not RWA and RF:
s = "The rotating frame does not exist without the rotating wave \
approximation, as far as I know."
raise ValueError(s)
# We check that the epsilonp is a list of vectors.
if not isinstance(epsilonp, list):
raise ValueError("epsilonp must be a list of polarization vectors.")
if not isinstance(epsilonp[0], Matrix):
raise ValueError("epsilonp must be a list of polarization vectors.")
Ne = len(omega_level)
Nl = len(omega_laser)
H = zeros(Ne, Ne)
hbar, e = symbols("hbar e", positive=True)
t = symbols("t", real=True)
for i in range(Ne):
for j in range(Ne):
rmij = vector_element(rm, i, j)
rpij = vector_element(rm, j, i).conjugate()
for l in range(Nl):
epsilonpl = epsilonp[l]
epsilonml = epsilonpl.conjugate()
if RF:
Epl = xi[l][i, j]*Ep[l]
Epl *= exp(-I*(theta[j]-theta[i]-t*omega_laser[l]))
Eml = xi[l][i, j]*Ep[l].conjugate()
Eml *= exp(-I*(theta[j]-theta[i]+t*omega_laser[l]))
else:
Epl = Ep[l]*xi[l][i, j]*exp(-I*omega_laser[l]*t)
Eml = Epl.conjugate()
# The E^(+)r^(-) term
H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rmij)
# The E^(-)r^(+) term
H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rpij)
if not RWA:
# The E^(+)r^(+) term
H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rpij)
# The E^(-)r^(-) term
H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rmij)
if i == j:
if RF:
H[i, j] += hbar*(omega_level[i]+diff(theta[i], t))
else:
H[i, j] += hbar*omega_level[i]
return H | python | def hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, omega_laser, xi,
RWA=True, RF=True):
r"""Return symbolic Hamiltonian.
>>> from sympy import zeros, pi, pprint, symbols
>>> Ne = 3
>>> Nl = 2
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> epsilonp = [polarization_vector(0, -pi/2, 0, 0, 1) for l in range(Nl)]
>>> detuning_knob = symbols("delta1 delta2", real=True)
>>> xi = [zeros(Ne, Ne) for l in range(Nl)]
>>> coup = [[(1, 0)], [(2, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... xi[l][pair[0], pair[1]] = 1
... xi[l][pair[1], pair[0]] = 1
>>> rm = define_r_components(Ne, xi, explicitly_hermitian=True,
... helicity=True, p=-1)
>>> rm = helicity_to_cartesian(rm)
>>> omega_level, omega, gamma = define_frequencies(Ne, True)
>>> H = hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level,
... omega_laser, xi, RWA=True, RF=False)
>>> print H[1, 0]
-E_{01}*e*r_{0;21}*exp(-I*t*varpi_1)/2
>>> print H[2, 0]
-E_{02}*e*r_{0;31}*exp(-I*t*varpi_2)/2
>>> print H[2, 2]
hbar*omega_3
"""
# We check what RF is.
if type(RF) == list:
theta = RF[:]
RF = True
elif type(RF) == Matrix:
theta = [RF[i, 0] for i in range(RF.shape[0])]
RF = True
elif RF:
# theta should be calculate here!
s = "We are still missing automatic calculation of phase "
s += "transformations."
raise ValueError(s)
if not RWA and RF:
s = "The rotating frame does not exist without the rotating wave \
approximation, as far as I know."
raise ValueError(s)
# We check that the epsilonp is a list of vectors.
if not isinstance(epsilonp, list):
raise ValueError("epsilonp must be a list of polarization vectors.")
if not isinstance(epsilonp[0], Matrix):
raise ValueError("epsilonp must be a list of polarization vectors.")
Ne = len(omega_level)
Nl = len(omega_laser)
H = zeros(Ne, Ne)
hbar, e = symbols("hbar e", positive=True)
t = symbols("t", real=True)
for i in range(Ne):
for j in range(Ne):
rmij = vector_element(rm, i, j)
rpij = vector_element(rm, j, i).conjugate()
for l in range(Nl):
epsilonpl = epsilonp[l]
epsilonml = epsilonpl.conjugate()
if RF:
Epl = xi[l][i, j]*Ep[l]
Epl *= exp(-I*(theta[j]-theta[i]-t*omega_laser[l]))
Eml = xi[l][i, j]*Ep[l].conjugate()
Eml *= exp(-I*(theta[j]-theta[i]+t*omega_laser[l]))
else:
Epl = Ep[l]*xi[l][i, j]*exp(-I*omega_laser[l]*t)
Eml = Epl.conjugate()
# The E^(+)r^(-) term
H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rmij)
# The E^(-)r^(+) term
H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rpij)
if not RWA:
# The E^(+)r^(+) term
H[i, j] += -e*Epl/2*cartesian_dot_product(epsilonpl, rpij)
# The E^(-)r^(-) term
H[i, j] += -e*Eml/2*cartesian_dot_product(epsilonml, rmij)
if i == j:
if RF:
H[i, j] += hbar*(omega_level[i]+diff(theta[i], t))
else:
H[i, j] += hbar*omega_level[i]
return H | [
"def",
"hamiltonian",
"(",
"Ep",
",",
"epsilonp",
",",
"detuning_knob",
",",
"rm",
",",
"omega_level",
",",
"omega_laser",
",",
"xi",
",",
"RWA",
"=",
"True",
",",
"RF",
"=",
"True",
")",
":",
"# We check what RF is.",
"if",
"type",
"(",
"RF",
")",
"==",
"list",
":",
"theta",
"=",
"RF",
"[",
":",
"]",
"RF",
"=",
"True",
"elif",
"type",
"(",
"RF",
")",
"==",
"Matrix",
":",
"theta",
"=",
"[",
"RF",
"[",
"i",
",",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"RF",
".",
"shape",
"[",
"0",
"]",
")",
"]",
"RF",
"=",
"True",
"elif",
"RF",
":",
"# theta should be calculate here!",
"s",
"=",
"\"We are still missing automatic calculation of phase \"",
"s",
"+=",
"\"transformations.\"",
"raise",
"ValueError",
"(",
"s",
")",
"if",
"not",
"RWA",
"and",
"RF",
":",
"s",
"=",
"\"The rotating frame does not exist without the rotating wave \\\napproximation, as far as I know.\"",
"raise",
"ValueError",
"(",
"s",
")",
"# We check that the epsilonp is a list of vectors.",
"if",
"not",
"isinstance",
"(",
"epsilonp",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"epsilonp must be a list of polarization vectors.\"",
")",
"if",
"not",
"isinstance",
"(",
"epsilonp",
"[",
"0",
"]",
",",
"Matrix",
")",
":",
"raise",
"ValueError",
"(",
"\"epsilonp must be a list of polarization vectors.\"",
")",
"Ne",
"=",
"len",
"(",
"omega_level",
")",
"Nl",
"=",
"len",
"(",
"omega_laser",
")",
"H",
"=",
"zeros",
"(",
"Ne",
",",
"Ne",
")",
"hbar",
",",
"e",
"=",
"symbols",
"(",
"\"hbar e\"",
",",
"positive",
"=",
"True",
")",
"t",
"=",
"symbols",
"(",
"\"t\"",
",",
"real",
"=",
"True",
")",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Ne",
")",
":",
"rmij",
"=",
"vector_element",
"(",
"rm",
",",
"i",
",",
"j",
")",
"rpij",
"=",
"vector_element",
"(",
"rm",
",",
"j",
",",
"i",
")",
".",
"conjugate",
"(",
")",
"for",
"l",
"in",
"range",
"(",
"Nl",
")",
":",
"epsilonpl",
"=",
"epsilonp",
"[",
"l",
"]",
"epsilonml",
"=",
"epsilonpl",
".",
"conjugate",
"(",
")",
"if",
"RF",
":",
"Epl",
"=",
"xi",
"[",
"l",
"]",
"[",
"i",
",",
"j",
"]",
"*",
"Ep",
"[",
"l",
"]",
"Epl",
"*=",
"exp",
"(",
"-",
"I",
"*",
"(",
"theta",
"[",
"j",
"]",
"-",
"theta",
"[",
"i",
"]",
"-",
"t",
"*",
"omega_laser",
"[",
"l",
"]",
")",
")",
"Eml",
"=",
"xi",
"[",
"l",
"]",
"[",
"i",
",",
"j",
"]",
"*",
"Ep",
"[",
"l",
"]",
".",
"conjugate",
"(",
")",
"Eml",
"*=",
"exp",
"(",
"-",
"I",
"*",
"(",
"theta",
"[",
"j",
"]",
"-",
"theta",
"[",
"i",
"]",
"+",
"t",
"*",
"omega_laser",
"[",
"l",
"]",
")",
")",
"else",
":",
"Epl",
"=",
"Ep",
"[",
"l",
"]",
"*",
"xi",
"[",
"l",
"]",
"[",
"i",
",",
"j",
"]",
"*",
"exp",
"(",
"-",
"I",
"*",
"omega_laser",
"[",
"l",
"]",
"*",
"t",
")",
"Eml",
"=",
"Epl",
".",
"conjugate",
"(",
")",
"# The E^(+)r^(-) term",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"-",
"e",
"*",
"Epl",
"/",
"2",
"*",
"cartesian_dot_product",
"(",
"epsilonpl",
",",
"rmij",
")",
"# The E^(-)r^(+) term",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"-",
"e",
"*",
"Eml",
"/",
"2",
"*",
"cartesian_dot_product",
"(",
"epsilonml",
",",
"rpij",
")",
"if",
"not",
"RWA",
":",
"# The E^(+)r^(+) term",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"-",
"e",
"*",
"Epl",
"/",
"2",
"*",
"cartesian_dot_product",
"(",
"epsilonpl",
",",
"rpij",
")",
"# The E^(-)r^(-) term",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"-",
"e",
"*",
"Eml",
"/",
"2",
"*",
"cartesian_dot_product",
"(",
"epsilonml",
",",
"rmij",
")",
"if",
"i",
"==",
"j",
":",
"if",
"RF",
":",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"hbar",
"*",
"(",
"omega_level",
"[",
"i",
"]",
"+",
"diff",
"(",
"theta",
"[",
"i",
"]",
",",
"t",
")",
")",
"else",
":",
"H",
"[",
"i",
",",
"j",
"]",
"+=",
"hbar",
"*",
"omega_level",
"[",
"i",
"]",
"return",
"H"
] | r"""Return symbolic Hamiltonian.
>>> from sympy import zeros, pi, pprint, symbols
>>> Ne = 3
>>> Nl = 2
>>> Ep, omega_laser = define_laser_variables(Nl)
>>> epsilonp = [polarization_vector(0, -pi/2, 0, 0, 1) for l in range(Nl)]
>>> detuning_knob = symbols("delta1 delta2", real=True)
>>> xi = [zeros(Ne, Ne) for l in range(Nl)]
>>> coup = [[(1, 0)], [(2, 0)]]
>>> for l in range(Nl):
... for pair in coup[l]:
... xi[l][pair[0], pair[1]] = 1
... xi[l][pair[1], pair[0]] = 1
>>> rm = define_r_components(Ne, xi, explicitly_hermitian=True,
... helicity=True, p=-1)
>>> rm = helicity_to_cartesian(rm)
>>> omega_level, omega, gamma = define_frequencies(Ne, True)
>>> H = hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level,
... omega_laser, xi, RWA=True, RF=False)
>>> print H[1, 0]
-E_{01}*e*r_{0;21}*exp(-I*t*varpi_1)/2
>>> print H[2, 0]
-E_{02}*e*r_{0;31}*exp(-I*t*varpi_2)/2
>>> print H[2, 2]
hbar*omega_3 | [
"r",
"Return",
"symbolic",
"Hamiltonian",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1163-L1262 |
oscarlazoarjona/fast | fast/symbolic.py | dot | def dot(a, b):
r"""Dot product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
acoef = Mul(*acoef)
return acoef*dot(avect, b)
if isinstance(b, Mul):
b = b.expand()
bvect = 1
bivect = -1
for bi, fact in enumerate(b.args):
if isinstance(fact, Vector3D):
bvect = fact
bivect = bi
break
bcoef = b.args[:bivect] + b.args[bivect+1:]
bcoef = Mul(*bcoef)
return bcoef*dot(a, bvect)
if isinstance(a, Vector3D) and isinstance(b, Vector3D):
return DotProduct(a, b)
if hasattr(a, "shape") and hasattr(b, "shape"):
return cartesian_dot_product(a, b)
print a, b, type(a), type(b),
print isinstance(a, Vector3D), isinstance(b, Vector3D)
raise NotImplementedError("could not catch these instances in dot!") | python | def dot(a, b):
r"""Dot product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
acoef = Mul(*acoef)
return acoef*dot(avect, b)
if isinstance(b, Mul):
b = b.expand()
bvect = 1
bivect = -1
for bi, fact in enumerate(b.args):
if isinstance(fact, Vector3D):
bvect = fact
bivect = bi
break
bcoef = b.args[:bivect] + b.args[bivect+1:]
bcoef = Mul(*bcoef)
return bcoef*dot(a, bvect)
if isinstance(a, Vector3D) and isinstance(b, Vector3D):
return DotProduct(a, b)
if hasattr(a, "shape") and hasattr(b, "shape"):
return cartesian_dot_product(a, b)
print a, b, type(a), type(b),
print isinstance(a, Vector3D), isinstance(b, Vector3D)
raise NotImplementedError("could not catch these instances in dot!") | [
"def",
"dot",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"Mul",
")",
":",
"a",
"=",
"a",
".",
"expand",
"(",
")",
"avect",
"=",
"1",
"aivect",
"=",
"-",
"1",
"for",
"ai",
",",
"fact",
"in",
"enumerate",
"(",
"a",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"fact",
",",
"Vector3D",
")",
":",
"avect",
"=",
"fact",
"aivect",
"=",
"ai",
"break",
"acoef",
"=",
"a",
".",
"args",
"[",
":",
"aivect",
"]",
"+",
"a",
".",
"args",
"[",
"aivect",
"+",
"1",
":",
"]",
"acoef",
"=",
"Mul",
"(",
"*",
"acoef",
")",
"return",
"acoef",
"*",
"dot",
"(",
"avect",
",",
"b",
")",
"if",
"isinstance",
"(",
"b",
",",
"Mul",
")",
":",
"b",
"=",
"b",
".",
"expand",
"(",
")",
"bvect",
"=",
"1",
"bivect",
"=",
"-",
"1",
"for",
"bi",
",",
"fact",
"in",
"enumerate",
"(",
"b",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"fact",
",",
"Vector3D",
")",
":",
"bvect",
"=",
"fact",
"bivect",
"=",
"bi",
"break",
"bcoef",
"=",
"b",
".",
"args",
"[",
":",
"bivect",
"]",
"+",
"b",
".",
"args",
"[",
"bivect",
"+",
"1",
":",
"]",
"bcoef",
"=",
"Mul",
"(",
"*",
"bcoef",
")",
"return",
"bcoef",
"*",
"dot",
"(",
"a",
",",
"bvect",
")",
"if",
"isinstance",
"(",
"a",
",",
"Vector3D",
")",
"and",
"isinstance",
"(",
"b",
",",
"Vector3D",
")",
":",
"return",
"DotProduct",
"(",
"a",
",",
"b",
")",
"if",
"hasattr",
"(",
"a",
",",
"\"shape\"",
")",
"and",
"hasattr",
"(",
"b",
",",
"\"shape\"",
")",
":",
"return",
"cartesian_dot_product",
"(",
"a",
",",
"b",
")",
"print",
"a",
",",
"b",
",",
"type",
"(",
"a",
")",
",",
"type",
"(",
"b",
")",
",",
"print",
"isinstance",
"(",
"a",
",",
"Vector3D",
")",
",",
"isinstance",
"(",
"b",
",",
"Vector3D",
")",
"raise",
"NotImplementedError",
"(",
"\"could not catch these instances in dot!\"",
")"
] | r"""Dot product of two 3d vectors. | [
"r",
"Dot",
"product",
"of",
"two",
"3d",
"vectors",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1390-L1428 |
oscarlazoarjona/fast | fast/symbolic.py | cross | def cross(a, b):
r"""Cross product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
acoef = Mul(*acoef)
return acoef*cross(avect, b)
if isinstance(b, Mul):
b = b.expand()
bvect = 1
bivect = -1
for bi, fact in enumerate(b.args):
if isinstance(fact, Vector3D):
bvect = fact
bivect = bi
break
bcoef = b.args[:bivect] + b.args[bivect+1:]
bcoef = Mul(*bcoef)
return bcoef*cross(a, bvect)
if isinstance(a, Vector3D) and isinstance(b, Vector3D):
return CrossProduct(a, b) | python | def cross(a, b):
r"""Cross product of two 3d vectors."""
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
acoef = Mul(*acoef)
return acoef*cross(avect, b)
if isinstance(b, Mul):
b = b.expand()
bvect = 1
bivect = -1
for bi, fact in enumerate(b.args):
if isinstance(fact, Vector3D):
bvect = fact
bivect = bi
break
bcoef = b.args[:bivect] + b.args[bivect+1:]
bcoef = Mul(*bcoef)
return bcoef*cross(a, bvect)
if isinstance(a, Vector3D) and isinstance(b, Vector3D):
return CrossProduct(a, b) | [
"def",
"cross",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"Mul",
")",
":",
"a",
"=",
"a",
".",
"expand",
"(",
")",
"avect",
"=",
"1",
"aivect",
"=",
"-",
"1",
"for",
"ai",
",",
"fact",
"in",
"enumerate",
"(",
"a",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"fact",
",",
"Vector3D",
")",
":",
"avect",
"=",
"fact",
"aivect",
"=",
"ai",
"break",
"acoef",
"=",
"a",
".",
"args",
"[",
":",
"aivect",
"]",
"+",
"a",
".",
"args",
"[",
"aivect",
"+",
"1",
":",
"]",
"acoef",
"=",
"Mul",
"(",
"*",
"acoef",
")",
"return",
"acoef",
"*",
"cross",
"(",
"avect",
",",
"b",
")",
"if",
"isinstance",
"(",
"b",
",",
"Mul",
")",
":",
"b",
"=",
"b",
".",
"expand",
"(",
")",
"bvect",
"=",
"1",
"bivect",
"=",
"-",
"1",
"for",
"bi",
",",
"fact",
"in",
"enumerate",
"(",
"b",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"fact",
",",
"Vector3D",
")",
":",
"bvect",
"=",
"fact",
"bivect",
"=",
"bi",
"break",
"bcoef",
"=",
"b",
".",
"args",
"[",
":",
"bivect",
"]",
"+",
"b",
".",
"args",
"[",
"bivect",
"+",
"1",
":",
"]",
"bcoef",
"=",
"Mul",
"(",
"*",
"bcoef",
")",
"return",
"bcoef",
"*",
"cross",
"(",
"a",
",",
"bvect",
")",
"if",
"isinstance",
"(",
"a",
",",
"Vector3D",
")",
"and",
"isinstance",
"(",
"b",
",",
"Vector3D",
")",
":",
"return",
"CrossProduct",
"(",
"a",
",",
"b",
")"
] | r"""Cross product of two 3d vectors. | [
"r",
"Cross",
"product",
"of",
"two",
"3d",
"vectors",
"."
] | train | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/symbolic.py#L1431-L1462 |
tilde-lab/tilde | tilde/core/settings.py | write_settings | def write_settings(settings):
'''
Saves user's settings
@returns True on success
@returns False on failure
'''
if not os.access(DATA_DIR, os.W_OK): return False
try:
f = open(DATA_DIR + os.sep + SETTINGS_FILE, 'w')
f.writelines(json.dumps(settings, indent=0))
f.close()
os.chmod(os.path.abspath(DATA_DIR + os.sep + SETTINGS_FILE), 0o777) # to avoid (or create?) IO problems with multiple users
except IOError:
return False
else:
return True | python | def write_settings(settings):
'''
Saves user's settings
@returns True on success
@returns False on failure
'''
if not os.access(DATA_DIR, os.W_OK): return False
try:
f = open(DATA_DIR + os.sep + SETTINGS_FILE, 'w')
f.writelines(json.dumps(settings, indent=0))
f.close()
os.chmod(os.path.abspath(DATA_DIR + os.sep + SETTINGS_FILE), 0o777) # to avoid (or create?) IO problems with multiple users
except IOError:
return False
else:
return True | [
"def",
"write_settings",
"(",
"settings",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"DATA_DIR",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"False",
"try",
":",
"f",
"=",
"open",
"(",
"DATA_DIR",
"+",
"os",
".",
"sep",
"+",
"SETTINGS_FILE",
",",
"'w'",
")",
"f",
".",
"writelines",
"(",
"json",
".",
"dumps",
"(",
"settings",
",",
"indent",
"=",
"0",
")",
")",
"f",
".",
"close",
"(",
")",
"os",
".",
"chmod",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"DATA_DIR",
"+",
"os",
".",
"sep",
"+",
"SETTINGS_FILE",
")",
",",
"0o777",
")",
"# to avoid (or create?) IO problems with multiple users",
"except",
"IOError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Saves user's settings
@returns True on success
@returns False on failure | [
"Saves",
"user",
"s",
"settings"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/settings.py#L109-L124 |
tilde-lab/tilde | tilde/core/settings.py | get_hierarchy | def get_hierarchy(settings):
'''
Gets main mapping source according to what a data classification is made
Gets the hierarchy groups (only for GUI)
Gets the hierarchy values
'''
hierarchy, hierarchy_groups, hierarchy_values = [], [], {}
hgroup_ids, enumerated_vals = {}, set()
session = connect_database(settings)
for item in session.query(model.Hierarchy_value).all():
try:
hierarchy_values[item.cid].update({item.num: item.name})
except KeyError:
hierarchy_values[item.cid] = {item.num: item.name}
enumerated_vals.add(item.cid)
try:
for item in session.query(model.Hierarchy).all():
if item.has_facet and not item.has_topic: raise RuntimeError('Fatal error: "has_facet" implies "has_topic"')
if item.slider and not '.' in item.slider: raise RuntimeError('Fatal error: "has_slider" must have a reference to some table field')
hierarchy.append({
'cid':item.cid,
'category':item.name,
'source':item.source,
'html':item.html,
'has_slider':item.slider,
'sort':item.sort,
'multiple':item.multiple,
'optional':item.optional,
'has_summary_contrb':item.has_summary_contrb,
'has_column':item.has_column,
'has_facet':item.has_facet,
'creates_topic':item.has_topic,
'is_chem_formula':item.chem_formula,
'plottable':item.plottable,
'enumerated':True if item.cid in enumerated_vals else False
})
try: hgroup_ids[item.hgroup_id].append(item.cid)
except KeyError: hgroup_ids[item.hgroup_id] = [item.cid]
except RuntimeError as e:
session.close()
sys.exit(e)
for item in session.query(model.Hierarchy_group).all():
hierarchy_groups.append({
'id': item.hgroup_id,
'category': item.name,
'html_pocket': '', # specially for JavaScript client
'landing_group': item.landing_group,
'settings_group': item.settings_group,
'includes': hgroup_ids[item.hgroup_id]
})
session.close()
return hierarchy, hierarchy_groups, hierarchy_values | python | def get_hierarchy(settings):
'''
Gets main mapping source according to what a data classification is made
Gets the hierarchy groups (only for GUI)
Gets the hierarchy values
'''
hierarchy, hierarchy_groups, hierarchy_values = [], [], {}
hgroup_ids, enumerated_vals = {}, set()
session = connect_database(settings)
for item in session.query(model.Hierarchy_value).all():
try:
hierarchy_values[item.cid].update({item.num: item.name})
except KeyError:
hierarchy_values[item.cid] = {item.num: item.name}
enumerated_vals.add(item.cid)
try:
for item in session.query(model.Hierarchy).all():
if item.has_facet and not item.has_topic: raise RuntimeError('Fatal error: "has_facet" implies "has_topic"')
if item.slider and not '.' in item.slider: raise RuntimeError('Fatal error: "has_slider" must have a reference to some table field')
hierarchy.append({
'cid':item.cid,
'category':item.name,
'source':item.source,
'html':item.html,
'has_slider':item.slider,
'sort':item.sort,
'multiple':item.multiple,
'optional':item.optional,
'has_summary_contrb':item.has_summary_contrb,
'has_column':item.has_column,
'has_facet':item.has_facet,
'creates_topic':item.has_topic,
'is_chem_formula':item.chem_formula,
'plottable':item.plottable,
'enumerated':True if item.cid in enumerated_vals else False
})
try: hgroup_ids[item.hgroup_id].append(item.cid)
except KeyError: hgroup_ids[item.hgroup_id] = [item.cid]
except RuntimeError as e:
session.close()
sys.exit(e)
for item in session.query(model.Hierarchy_group).all():
hierarchy_groups.append({
'id': item.hgroup_id,
'category': item.name,
'html_pocket': '', # specially for JavaScript client
'landing_group': item.landing_group,
'settings_group': item.settings_group,
'includes': hgroup_ids[item.hgroup_id]
})
session.close()
return hierarchy, hierarchy_groups, hierarchy_values | [
"def",
"get_hierarchy",
"(",
"settings",
")",
":",
"hierarchy",
",",
"hierarchy_groups",
",",
"hierarchy_values",
"=",
"[",
"]",
",",
"[",
"]",
",",
"{",
"}",
"hgroup_ids",
",",
"enumerated_vals",
"=",
"{",
"}",
",",
"set",
"(",
")",
"session",
"=",
"connect_database",
"(",
"settings",
")",
"for",
"item",
"in",
"session",
".",
"query",
"(",
"model",
".",
"Hierarchy_value",
")",
".",
"all",
"(",
")",
":",
"try",
":",
"hierarchy_values",
"[",
"item",
".",
"cid",
"]",
".",
"update",
"(",
"{",
"item",
".",
"num",
":",
"item",
".",
"name",
"}",
")",
"except",
"KeyError",
":",
"hierarchy_values",
"[",
"item",
".",
"cid",
"]",
"=",
"{",
"item",
".",
"num",
":",
"item",
".",
"name",
"}",
"enumerated_vals",
".",
"add",
"(",
"item",
".",
"cid",
")",
"try",
":",
"for",
"item",
"in",
"session",
".",
"query",
"(",
"model",
".",
"Hierarchy",
")",
".",
"all",
"(",
")",
":",
"if",
"item",
".",
"has_facet",
"and",
"not",
"item",
".",
"has_topic",
":",
"raise",
"RuntimeError",
"(",
"'Fatal error: \"has_facet\" implies \"has_topic\"'",
")",
"if",
"item",
".",
"slider",
"and",
"not",
"'.'",
"in",
"item",
".",
"slider",
":",
"raise",
"RuntimeError",
"(",
"'Fatal error: \"has_slider\" must have a reference to some table field'",
")",
"hierarchy",
".",
"append",
"(",
"{",
"'cid'",
":",
"item",
".",
"cid",
",",
"'category'",
":",
"item",
".",
"name",
",",
"'source'",
":",
"item",
".",
"source",
",",
"'html'",
":",
"item",
".",
"html",
",",
"'has_slider'",
":",
"item",
".",
"slider",
",",
"'sort'",
":",
"item",
".",
"sort",
",",
"'multiple'",
":",
"item",
".",
"multiple",
",",
"'optional'",
":",
"item",
".",
"optional",
",",
"'has_summary_contrb'",
":",
"item",
".",
"has_summary_contrb",
",",
"'has_column'",
":",
"item",
".",
"has_column",
",",
"'has_facet'",
":",
"item",
".",
"has_facet",
",",
"'creates_topic'",
":",
"item",
".",
"has_topic",
",",
"'is_chem_formula'",
":",
"item",
".",
"chem_formula",
",",
"'plottable'",
":",
"item",
".",
"plottable",
",",
"'enumerated'",
":",
"True",
"if",
"item",
".",
"cid",
"in",
"enumerated_vals",
"else",
"False",
"}",
")",
"try",
":",
"hgroup_ids",
"[",
"item",
".",
"hgroup_id",
"]",
".",
"append",
"(",
"item",
".",
"cid",
")",
"except",
"KeyError",
":",
"hgroup_ids",
"[",
"item",
".",
"hgroup_id",
"]",
"=",
"[",
"item",
".",
"cid",
"]",
"except",
"RuntimeError",
"as",
"e",
":",
"session",
".",
"close",
"(",
")",
"sys",
".",
"exit",
"(",
"e",
")",
"for",
"item",
"in",
"session",
".",
"query",
"(",
"model",
".",
"Hierarchy_group",
")",
".",
"all",
"(",
")",
":",
"hierarchy_groups",
".",
"append",
"(",
"{",
"'id'",
":",
"item",
".",
"hgroup_id",
",",
"'category'",
":",
"item",
".",
"name",
",",
"'html_pocket'",
":",
"''",
",",
"# specially for JavaScript client",
"'landing_group'",
":",
"item",
".",
"landing_group",
",",
"'settings_group'",
":",
"item",
".",
"settings_group",
",",
"'includes'",
":",
"hgroup_ids",
"[",
"item",
".",
"hgroup_id",
"]",
"}",
")",
"session",
".",
"close",
"(",
")",
"return",
"hierarchy",
",",
"hierarchy_groups",
",",
"hierarchy_values"
] | Gets main mapping source according to what a data classification is made
Gets the hierarchy groups (only for GUI)
Gets the hierarchy values | [
"Gets",
"main",
"mapping",
"source",
"according",
"to",
"what",
"a",
"data",
"classification",
"is",
"made",
"Gets",
"the",
"hierarchy",
"groups",
"(",
"only",
"for",
"GUI",
")",
"Gets",
"the",
"hierarchy",
"values"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/settings.py#L126-L177 |
hammerlab/stancache | stancache/utils.py | is_field_unique_by_group | def is_field_unique_by_group(df, field_col, group_col):
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
return all(num_distinct == 1) | python | def is_field_unique_by_group(df, field_col, group_col):
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
return all(num_distinct == 1) | [
"def",
"is_field_unique_by_group",
"(",
"df",
",",
"field_col",
",",
"group_col",
")",
":",
"def",
"num_unique",
"(",
"x",
")",
":",
"return",
"len",
"(",
"pd",
".",
"unique",
"(",
"x",
")",
")",
"num_distinct",
"=",
"df",
".",
"groupby",
"(",
"group_col",
")",
"[",
"field_col",
"]",
".",
"agg",
"(",
"num_unique",
")",
"return",
"all",
"(",
"num_distinct",
"==",
"1",
")"
] | Determine if field is constant by group in df | [
"Determine",
"if",
"field",
"is",
"constant",
"by",
"group",
"in",
"df"
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/utils.py#L36-L42 |
hammerlab/stancache | stancache/utils.py | _list_files_in_path | def _list_files_in_path(path, pattern="*.stan"):
"""
indexes a directory of stan files
returns as dictionary containing contents of files
"""
results = []
for dirname, subdirs, files in os.walk(path):
for name in files:
if fnmatch(name, pattern):
results.append(os.path.join(dirname, name))
return(results) | python | def _list_files_in_path(path, pattern="*.stan"):
"""
indexes a directory of stan files
returns as dictionary containing contents of files
"""
results = []
for dirname, subdirs, files in os.walk(path):
for name in files:
if fnmatch(name, pattern):
results.append(os.path.join(dirname, name))
return(results) | [
"def",
"_list_files_in_path",
"(",
"path",
",",
"pattern",
"=",
"\"*.stan\"",
")",
":",
"results",
"=",
"[",
"]",
"for",
"dirname",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"name",
"in",
"files",
":",
"if",
"fnmatch",
"(",
"name",
",",
"pattern",
")",
":",
"results",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"name",
")",
")",
"return",
"(",
"results",
")"
] | indexes a directory of stan files
returns as dictionary containing contents of files | [
"indexes",
"a",
"directory",
"of",
"stan",
"files",
"returns",
"as",
"dictionary",
"containing",
"contents",
"of",
"files"
] | train | https://github.com/hammerlab/stancache/blob/22f2548731d0960c14c0d41f4f64e418d3f22e4c/stancache/utils.py#L45-L56 |
tilde-lab/tilde | tilde/classifiers/perovskites.py | generate_random_perovskite | def generate_random_perovskite(lat=None):
'''
This generates a random valid perovskite structure in ASE format.
Useful for testing.
Binary and organic perovskites are not considered.
'''
if not lat:
lat = round(random.uniform(3.5, Perovskite_tilting.OCTAHEDRON_BOND_LENGTH_LIMIT*2), 3)
A_site = random.choice(Perovskite_Structure.A)
B_site = random.choice(Perovskite_Structure.B)
Ci_site = random.choice(Perovskite_Structure.C)
Cii_site = random.choice(Perovskite_Structure.C)
while covalent_radii[chemical_symbols.index(A_site)] - \
covalent_radii[chemical_symbols.index(B_site)] < 0.05 or \
covalent_radii[chemical_symbols.index(A_site)] - \
covalent_radii[chemical_symbols.index(B_site)] > 0.5:
A_site = random.choice(Perovskite_Structure.A)
B_site = random.choice(Perovskite_Structure.B)
return crystal(
[A_site, B_site, Ci_site, Cii_site],
[(0.5, 0.25, 0.0), (0.0, 0.0, 0.0), (0.0, 0.25, 0.0), (0.25, 0.0, 0.75)],
spacegroup=62, cellpar=[lat*math.sqrt(2), 2*lat, lat*math.sqrt(2), 90, 90, 90]
) | python | def generate_random_perovskite(lat=None):
'''
This generates a random valid perovskite structure in ASE format.
Useful for testing.
Binary and organic perovskites are not considered.
'''
if not lat:
lat = round(random.uniform(3.5, Perovskite_tilting.OCTAHEDRON_BOND_LENGTH_LIMIT*2), 3)
A_site = random.choice(Perovskite_Structure.A)
B_site = random.choice(Perovskite_Structure.B)
Ci_site = random.choice(Perovskite_Structure.C)
Cii_site = random.choice(Perovskite_Structure.C)
while covalent_radii[chemical_symbols.index(A_site)] - \
covalent_radii[chemical_symbols.index(B_site)] < 0.05 or \
covalent_radii[chemical_symbols.index(A_site)] - \
covalent_radii[chemical_symbols.index(B_site)] > 0.5:
A_site = random.choice(Perovskite_Structure.A)
B_site = random.choice(Perovskite_Structure.B)
return crystal(
[A_site, B_site, Ci_site, Cii_site],
[(0.5, 0.25, 0.0), (0.0, 0.0, 0.0), (0.0, 0.25, 0.0), (0.25, 0.0, 0.75)],
spacegroup=62, cellpar=[lat*math.sqrt(2), 2*lat, lat*math.sqrt(2), 90, 90, 90]
) | [
"def",
"generate_random_perovskite",
"(",
"lat",
"=",
"None",
")",
":",
"if",
"not",
"lat",
":",
"lat",
"=",
"round",
"(",
"random",
".",
"uniform",
"(",
"3.5",
",",
"Perovskite_tilting",
".",
"OCTAHEDRON_BOND_LENGTH_LIMIT",
"*",
"2",
")",
",",
"3",
")",
"A_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"A",
")",
"B_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"B",
")",
"Ci_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"C",
")",
"Cii_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"C",
")",
"while",
"covalent_radii",
"[",
"chemical_symbols",
".",
"index",
"(",
"A_site",
")",
"]",
"-",
"covalent_radii",
"[",
"chemical_symbols",
".",
"index",
"(",
"B_site",
")",
"]",
"<",
"0.05",
"or",
"covalent_radii",
"[",
"chemical_symbols",
".",
"index",
"(",
"A_site",
")",
"]",
"-",
"covalent_radii",
"[",
"chemical_symbols",
".",
"index",
"(",
"B_site",
")",
"]",
">",
"0.5",
":",
"A_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"A",
")",
"B_site",
"=",
"random",
".",
"choice",
"(",
"Perovskite_Structure",
".",
"B",
")",
"return",
"crystal",
"(",
"[",
"A_site",
",",
"B_site",
",",
"Ci_site",
",",
"Cii_site",
"]",
",",
"[",
"(",
"0.5",
",",
"0.25",
",",
"0.0",
")",
",",
"(",
"0.0",
",",
"0.0",
",",
"0.0",
")",
",",
"(",
"0.0",
",",
"0.25",
",",
"0.0",
")",
",",
"(",
"0.25",
",",
"0.0",
",",
"0.75",
")",
"]",
",",
"spacegroup",
"=",
"62",
",",
"cellpar",
"=",
"[",
"lat",
"*",
"math",
".",
"sqrt",
"(",
"2",
")",
",",
"2",
"*",
"lat",
",",
"lat",
"*",
"math",
".",
"sqrt",
"(",
"2",
")",
",",
"90",
",",
"90",
",",
"90",
"]",
")"
] | This generates a random valid perovskite structure in ASE format.
Useful for testing.
Binary and organic perovskites are not considered. | [
"This",
"generates",
"a",
"random",
"valid",
"perovskite",
"structure",
"in",
"ASE",
"format",
".",
"Useful",
"for",
"testing",
".",
"Binary",
"and",
"organic",
"perovskites",
"are",
"not",
"considered",
"."
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/classifiers/perovskites.py#L126-L151 |
alexwlchan/specktre | src/specktre/cli.py | check_positive_integer | def check_positive_integer(name, value):
"""Check a value is a positive integer.
Returns the value if so, raises ValueError otherwise.
"""
try:
value = int(value)
is_positive = (value > 0)
except ValueError:
raise ValueError('%s should be an integer; got %r' % (name, value))
if is_positive:
return value
else:
raise ValueError('%s should be positive; got %r' % (name, value)) | python | def check_positive_integer(name, value):
"""Check a value is a positive integer.
Returns the value if so, raises ValueError otherwise.
"""
try:
value = int(value)
is_positive = (value > 0)
except ValueError:
raise ValueError('%s should be an integer; got %r' % (name, value))
if is_positive:
return value
else:
raise ValueError('%s should be positive; got %r' % (name, value)) | [
"def",
"check_positive_integer",
"(",
"name",
",",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"is_positive",
"=",
"(",
"value",
">",
"0",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'%s should be an integer; got %r'",
"%",
"(",
"name",
",",
"value",
")",
")",
"if",
"is_positive",
":",
"return",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"'%s should be positive; got %r'",
"%",
"(",
"name",
",",
"value",
")",
")"
] | Check a value is a positive integer.
Returns the value if so, raises ValueError otherwise. | [
"Check",
"a",
"value",
"is",
"a",
"positive",
"integer",
"."
] | train | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/cli.py#L40-L55 |
alexwlchan/specktre | src/specktre/cli.py | check_color_input | def check_color_input(value):
"""Check a value is a valid colour input.
Returns a parsed `RGBColor` instance if so, raises ValueError
otherwise.
"""
value = value.lower()
# Trim a leading hash
if value.startswith('#'):
value = value[1:]
if len(value) != 6:
raise ValueError(
'Color should be six hexadecimal digits, got %r (%s)' %
(value, len(value)))
if re.sub(r'[a-f0-9]', '', value):
raise ValueError(
'Color should only contain hex characters, got %r' % value)
red = int(value[0:2], base=16)
green = int(value[2:4], base=16)
blue = int(value[4:6], base=16)
return RGBColor(red, green, blue) | python | def check_color_input(value):
"""Check a value is a valid colour input.
Returns a parsed `RGBColor` instance if so, raises ValueError
otherwise.
"""
value = value.lower()
# Trim a leading hash
if value.startswith('#'):
value = value[1:]
if len(value) != 6:
raise ValueError(
'Color should be six hexadecimal digits, got %r (%s)' %
(value, len(value)))
if re.sub(r'[a-f0-9]', '', value):
raise ValueError(
'Color should only contain hex characters, got %r' % value)
red = int(value[0:2], base=16)
green = int(value[2:4], base=16)
blue = int(value[4:6], base=16)
return RGBColor(red, green, blue) | [
"def",
"check_color_input",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"# Trim a leading hash",
"if",
"value",
".",
"startswith",
"(",
"'#'",
")",
":",
"value",
"=",
"value",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"value",
")",
"!=",
"6",
":",
"raise",
"ValueError",
"(",
"'Color should be six hexadecimal digits, got %r (%s)'",
"%",
"(",
"value",
",",
"len",
"(",
"value",
")",
")",
")",
"if",
"re",
".",
"sub",
"(",
"r'[a-f0-9]'",
",",
"''",
",",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'Color should only contain hex characters, got %r'",
"%",
"value",
")",
"red",
"=",
"int",
"(",
"value",
"[",
"0",
":",
"2",
"]",
",",
"base",
"=",
"16",
")",
"green",
"=",
"int",
"(",
"value",
"[",
"2",
":",
"4",
"]",
",",
"base",
"=",
"16",
")",
"blue",
"=",
"int",
"(",
"value",
"[",
"4",
":",
"6",
"]",
",",
"base",
"=",
"16",
")",
"return",
"RGBColor",
"(",
"red",
",",
"green",
",",
"blue",
")"
] | Check a value is a valid colour input.
Returns a parsed `RGBColor` instance if so, raises ValueError
otherwise. | [
"Check",
"a",
"value",
"is",
"a",
"valid",
"colour",
"input",
"."
] | train | https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/cli.py#L58-L82 |
tilde-lab/tilde | tilde/apps/perovskite_tilting/perovskite_tilting.py | Perovskite_tilting.get_octahedra | def get_octahedra(self, atoms, periodicity=3):
'''
Extract octahedra as lists of sequence numbers of corner atoms
'''
octahedra = []
for n, i in enumerate(atoms):
found = []
if i.symbol in Perovskite_Structure.B:
for m, j in enumerate(self.virtual_atoms):
if j.symbol in Perovskite_Structure.C and self.virtual_atoms.get_distance(n, m) <= self.OCTAHEDRON_BOND_LENGTH_LIMIT:
found.append(m)
if (periodicity == 3 and len(found) == 6) or (periodicity == 2 and len(found) in [5, 6]):
octahedra.append([n, found])
if not len(octahedra): raise ModuleError("Cannot extract valid octahedra: not enough corner atoms found!")
return octahedra | python | def get_octahedra(self, atoms, periodicity=3):
'''
Extract octahedra as lists of sequence numbers of corner atoms
'''
octahedra = []
for n, i in enumerate(atoms):
found = []
if i.symbol in Perovskite_Structure.B:
for m, j in enumerate(self.virtual_atoms):
if j.symbol in Perovskite_Structure.C and self.virtual_atoms.get_distance(n, m) <= self.OCTAHEDRON_BOND_LENGTH_LIMIT:
found.append(m)
if (periodicity == 3 and len(found) == 6) or (periodicity == 2 and len(found) in [5, 6]):
octahedra.append([n, found])
if not len(octahedra): raise ModuleError("Cannot extract valid octahedra: not enough corner atoms found!")
return octahedra | [
"def",
"get_octahedra",
"(",
"self",
",",
"atoms",
",",
"periodicity",
"=",
"3",
")",
":",
"octahedra",
"=",
"[",
"]",
"for",
"n",
",",
"i",
"in",
"enumerate",
"(",
"atoms",
")",
":",
"found",
"=",
"[",
"]",
"if",
"i",
".",
"symbol",
"in",
"Perovskite_Structure",
".",
"B",
":",
"for",
"m",
",",
"j",
"in",
"enumerate",
"(",
"self",
".",
"virtual_atoms",
")",
":",
"if",
"j",
".",
"symbol",
"in",
"Perovskite_Structure",
".",
"C",
"and",
"self",
".",
"virtual_atoms",
".",
"get_distance",
"(",
"n",
",",
"m",
")",
"<=",
"self",
".",
"OCTAHEDRON_BOND_LENGTH_LIMIT",
":",
"found",
".",
"append",
"(",
"m",
")",
"if",
"(",
"periodicity",
"==",
"3",
"and",
"len",
"(",
"found",
")",
"==",
"6",
")",
"or",
"(",
"periodicity",
"==",
"2",
"and",
"len",
"(",
"found",
")",
"in",
"[",
"5",
",",
"6",
"]",
")",
":",
"octahedra",
".",
"append",
"(",
"[",
"n",
",",
"found",
"]",
")",
"if",
"not",
"len",
"(",
"octahedra",
")",
":",
"raise",
"ModuleError",
"(",
"\"Cannot extract valid octahedra: not enough corner atoms found!\"",
")",
"return",
"octahedra"
] | Extract octahedra as lists of sequence numbers of corner atoms | [
"Extract",
"octahedra",
"as",
"lists",
"of",
"sequence",
"numbers",
"of",
"corner",
"atoms"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/apps/perovskite_tilting/perovskite_tilting.py#L141-L157 |
tilde-lab/tilde | tilde/apps/perovskite_tilting/perovskite_tilting.py | Perovskite_tilting.get_tiltplane | def get_tiltplane(self, sequence):
'''
Extract the main tilting plane basing on Z coordinate
'''
sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z)
in_plane = []
for i in range(0, len(sequence)-4):
if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
abs(self.virtual_atoms[ sequence[i+1] ].z - self.virtual_atoms[ sequence[i+2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
abs(self.virtual_atoms[ sequence[i+2] ].z - self.virtual_atoms[ sequence[i+3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE:
in_plane = [sequence[j] for j in range(i, i+4)]
return in_plane | python | def get_tiltplane(self, sequence):
'''
Extract the main tilting plane basing on Z coordinate
'''
sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z)
in_plane = []
for i in range(0, len(sequence)-4):
if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
abs(self.virtual_atoms[ sequence[i+1] ].z - self.virtual_atoms[ sequence[i+2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \
abs(self.virtual_atoms[ sequence[i+2] ].z - self.virtual_atoms[ sequence[i+3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE:
in_plane = [sequence[j] for j in range(i, i+4)]
return in_plane | [
"def",
"get_tiltplane",
"(",
"self",
",",
"sequence",
")",
":",
"sequence",
"=",
"sorted",
"(",
"sequence",
",",
"key",
"=",
"lambda",
"x",
":",
"self",
".",
"virtual_atoms",
"[",
"x",
"]",
".",
"z",
")",
"in_plane",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sequence",
")",
"-",
"4",
")",
":",
"if",
"abs",
"(",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"]",
"]",
".",
"z",
"-",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"+",
"1",
"]",
"]",
".",
"z",
")",
"<",
"self",
".",
"OCTAHEDRON_ATOMS_Z_DIFFERENCE",
"and",
"abs",
"(",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"+",
"1",
"]",
"]",
".",
"z",
"-",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"+",
"2",
"]",
"]",
".",
"z",
")",
"<",
"self",
".",
"OCTAHEDRON_ATOMS_Z_DIFFERENCE",
"and",
"abs",
"(",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"+",
"2",
"]",
"]",
".",
"z",
"-",
"self",
".",
"virtual_atoms",
"[",
"sequence",
"[",
"i",
"+",
"3",
"]",
"]",
".",
"z",
")",
"<",
"self",
".",
"OCTAHEDRON_ATOMS_Z_DIFFERENCE",
":",
"in_plane",
"=",
"[",
"sequence",
"[",
"j",
"]",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"i",
"+",
"4",
")",
"]",
"return",
"in_plane"
] | Extract the main tilting plane basing on Z coordinate | [
"Extract",
"the",
"main",
"tilting",
"plane",
"basing",
"on",
"Z",
"coordinate"
] | train | https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/apps/perovskite_tilting/perovskite_tilting.py#L159-L170 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.