Skip to content

Commit

Permalink
Use math convention in polar coordinates (ManimCommunity#2095)
Browse files Browse the repository at this point in the history
* switched phi and theta

* added tests

Co-authored-by: Darylgolden <darylgolden@gmail.com>
  • Loading branch information
icedcoffeeee and Darylgolden committed Sep 28, 2021
1 parent eb09675 commit bb92fee
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
41 changes: 33 additions & 8 deletions manim/utils/space_ops.py
Expand Up @@ -27,6 +27,8 @@
"get_winding_number",
"cross2d",
"earclip_triangulation",
"cartesian_to_spherical",
"spherical_to_cartesian",
"perpendicular_bisector",
]

Expand Down Expand Up @@ -752,22 +754,45 @@ def earclip_triangulation(verts: np.ndarray, ring_ends: list) -> list:
return [indices[mi] for mi in meta_indices]


def cartesian_to_spherical(vec):
def cartesian_to_spherical(vec: Sequence[float]) -> np.ndarray:
"""Returns an array of numbers corresponding to each
polar coordinate value (distance, phi, theta).
Parameters
----------
vec
A numpy array ``[x, y, z]``.
"""
norm = np.linalg.norm(vec)
if norm == 0:
return 0, 0, 0
r = norm
theta = np.arccos(vec[2] / r)
phi = np.arctan2(vec[1], vec[0])
return r, theta, phi
phi = np.arccos(vec[2] / r)
theta = np.arctan2(vec[1], vec[0])
return np.array([r, phi, theta])


def spherical_to_cartesian(spherical: Sequence[float]) -> np.ndarray:
"""Returns a numpy array ``[x, y, z]`` based on the spherical
coordinates given.
def spherical_to_cartesian(r, theta, phi):
Parameters
----------
spherical
A list of three floats that correspond to the following:
r - The distance between the point and the origin.
theta - The azimuthal angle of the point to the positive x-axis.
phi - The vertical angle of the point to the positive z-axis.
"""
r, theta, phi = spherical
return np.array(
[
r * np.cos(phi) * np.sin(theta),
r * np.sin(phi) * np.sin(theta),
r * np.cos(theta),
r * np.cos(theta) * np.sin(phi),
r * np.sin(theta) * np.sin(phi),
r * np.cos(phi),
],
)

Expand Down
13 changes: 13 additions & 0 deletions tests/test_space_ops.py
@@ -0,0 +1,13 @@
import numpy as np

from manim import cartesian_to_spherical, spherical_to_cartesian


def test_polar_coords():
a = np.array([1, 1, 0])
b = (2, np.pi / 2, np.pi / 2)
assert all(
np.round(cartesian_to_spherical(a), 4)
== np.round([2 ** 0.5, np.pi / 2, np.pi / 4], 4),
)
assert all(np.round(spherical_to_cartesian(b), 4) == np.array([0, 2, 0]))

0 comments on commit bb92fee

Please sign in to comment.