Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

change interface of units

leotrs9d61aac8b7ff
diff --git a/manim/utils/unit.py b/manim/utils/unit.py
index b26597c3a..ac5050016 100644
--- a/manim/utils/unit.py
+++ b/manim/utils/unit.py
@@ -5,18 +5,33 @@ import numpy as np
from .. import constants, config
-def m(val):
- return val
+__all__ = ['Pixels', 'Degrees', 'Munits', 'Percent']
-def px(val):
- return val * config.frame_width / config.pixel_width
+class _PixelUnits:
+ def __mul__(self, val):
+ return val * config.frame_width / config.pixel_width
+ def __rmul__(self, val):
+ return val * config.frame_width / config.pixel_width
-def pct(val, axis):
- if np.array_equal(axis, constants.X_AXIS):
- return val / 100 * config.frame_width
- if np.array_equal(axis, constants.Y_AXIS):
- return val / 100 * config.frame_height
- if np.array_equal(axis, constants.Z_AXIS):
- raise NotImplementedError("length of Z axis is undefined...")
+
+class Percent:
+ def __init__(self, axis):
+ if np.array_equal(axis, constants.X_AXIS):
+ self.length = config.frame_width
+ if np.array_equal(axis, constants.Y_AXIS):
+ self.length = config.frame_height
+ if np.array_equal(axis, constants.Z_AXIS):
+ raise NotImplementedError("length of Z axis is undefined")
+
+ def __mul__(self, val):
+ return val / 100 * self.length
+
+ def __rmul__(self, val):
+ return val / 100 * self.length
+
+
+Pixels = _PixelUnits()
+Degrees = constants.PI / 180
+Munits = 1
diff --git a/tests/test_units.py b/tests/test_units.py
new file mode 100644
index 000000000..7fe8c3c9d
--- /dev/null
+++ b/tests/test_units.py
@@ -0,0 +1,27 @@
+import pytest
+from manim import config, X_AXIS, Y_AXIS, Z_AXIS, PI
+from manim.utils.unit import Pixels, Degrees, Munits, Percent
+import numpy as np
+
+
+def test_units():
+ # make sure we are using the right frame geometry
+ assert config.pixel_width == 1920
+ assert np.isclose(config.frame_height, 8.0)
+
+ # Munits should be equivalent to the internal logical units
+ assert np.isclose(8.0 * Munits, config.frame_height)
+
+ # Pixels should convert from pixels to Munits
+ assert np.isclose(1920 * Pixels, config.frame_width)
+
+ # Percent should give the fractional length of the frame
+ assert np.isclose(50 * Percent(X_AXIS), config.frame_width / 2)
+ assert np.isclose(50 * Percent(Y_AXIS), config.frame_height / 2)
+
+ # The length of the Z axis is not defined
+ with pytest.raises(NotImplementedError):
+ Percent(Z_AXIS)
+
+ # Degrees should convert from degrees to radians
+ assert np.isclose(180 * Degrees, PI)