-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import numpy as np | ||
|
||
def spherical_from_cartesian(x, y, z): | ||
""" | ||
Convert cartesian coordinates to spherical coordinates. | ||
Parameters | ||
---------- | ||
x : float | ||
x-coordinate | ||
y : float | ||
y-coordinate | ||
z : float | ||
z-coordinate | ||
Returns | ||
------- | ||
r : float | ||
radial coordinate | ||
theta : float | ||
polar angle | ||
phi : float | ||
azimuthal angle | ||
""" | ||
|
||
r = np.sqrt(x**2 + y**2 + z**2 ) | ||
theta = np.arccos(z/r) | ||
phi = np.arctan2(y, x) | ||
|
||
return np.array([r, theta, phi]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
from qctools.tools import * | ||
import numpy as np | ||
|
||
def test_spherical_from_cartesian(): | ||
""" | ||
testing spherical_from_cartesian function | ||
""" | ||
np.random.seed(42) | ||
x_lst = np.random.uniform(-1, 1, 10) | ||
y_lst = np.random.uniform(-1, 1, 10) | ||
z_lst = np.random.uniform(-1, 1, 10) | ||
|
||
res = [] | ||
for x, y, z in zip(x_lst, y_lst, z_lst): | ||
res.append(spherical_from_cartesian(x, y, z)) | ||
|
||
res = np.array(res) | ||
|
||
# convert back to cartesian | ||
x_res = res[:, 0] * np.sin(res[:, 1]) * np.cos(res[:, 2]) | ||
y_res = res[:, 0] * np.sin(res[:, 1]) * np.sin(res[:, 2]) | ||
z_res = res[:, 0] * np.cos(res[:, 1]) | ||
|
||
np.testing.assert_allclose(x_res, x_lst, atol=1e-5, rtol=1e-5) | ||
np.testing.assert_allclose(y_res, y_lst, atol=1e-5, rtol=1e-5) | ||
np.testing.assert_allclose(z_res, z_lst, atol=1e-5, rtol=1e-5) |