Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Simple and small performance improvements

Grant Sanderson039f7ffe585b
diff --git a/utils/bezier.py b/utils/bezier.py
index acf18533f..f61c47e50 100644
--- a/utils/bezier.py
+++ b/utils/bezier.py
@@ -1,7 +1,7 @@
import numpy as np
from scipy import linalg
-from utils.simple_functions import choose
+from utils.simple_functions import choose_using_cache
from utils.space_ops import get_norm
CLOSED_THRESHOLD = 0.001
@@ -10,7 +10,7 @@ CLOSED_THRESHOLD = 0.001
def bezier(points):
n = len(points) - 1
return lambda t: sum([
- ((1 - t)**(n - k)) * (t**k) * choose(n, k) * point
+ ((1 - t)**(n - k)) * (t**k) * choose_using_cache(n, k) * point
for k, point in enumerate(points)
])
diff --git a/utils/color.py b/utils/color.py
index 500d5b9c4..4625fa455 100644
--- a/utils/color.py
+++ b/utils/color.py
@@ -11,9 +11,12 @@ from utils.simple_functions import clip_in_place
def color_to_rgb(color):
- if not isinstance(color, Color):
- color = Color(color)
- return np.array(color.get_rgb())
+ if isinstance(color, str):
+ return hex_to_rgb(color)
+ elif isinstance(color, Color):
+ return np.array(color.get_rgb())
+ else:
+ raise Exception("Invalid color type")
def color_to_rgba(color, alpha=1):
@@ -35,6 +38,16 @@ def rgb_to_hex(rgb):
return "#" + "".join('%02x' % int(255 * x) for x in rgb)
+def hex_to_rgb(hex_code):
+ hex_part = hex_code[1:]
+ if len(hex_part) == 3:
+ "".join([2 * c for c in hex_part])
+ return np.array([
+ int(hex_part[i:i + 2], 16) / 255
+ for i in range(0, 6, 2)
+ ])
+
+
def invert_color(color):
return rgb_to_color(1.0 - color_to_rgb(color))
diff --git a/utils/simple_functions.py b/utils/simple_functions.py
index 23669e707..35ad2c973 100644
--- a/utils/simple_functions.py
+++ b/utils/simple_functions.py
@@ -8,6 +8,17 @@ def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
+CHOOSE_CACHE = {}
+
+
+def choose_using_cache(n, r):
+ if n not in CHOOSE_CACHE:
+ CHOOSE_CACHE[n] = {}
+ if r not in CHOOSE_CACHE[n]:
+ CHOOSE_CACHE[n][r] = choose(n, r)
+ return CHOOSE_CACHE[n][r]
+
+
def choose(n, r):
if n < r:
return 0