Skip to content

Commit

Permalink
add sperical_from_cartesian
Browse files Browse the repository at this point in the history
  • Loading branch information
RichRick1 committed Mar 22, 2024
1 parent 510d1cb commit 008bc97
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
30 changes: 30 additions & 0 deletions qctools/tools.py
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])
26 changes: 26 additions & 0 deletions tests/test_tools.py
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)

0 comments on commit 008bc97

Please sign in to comment.