From 039f7ffe585b3267d77bbb9c6a572198146727dd Mon Sep 17 00:00:00 2001 From: Grant Sanderson Date: Sat, 18 Aug 2018 20:13:49 -0700 Subject: [PATCH] Simple and small performance improvements --- utils/bezier.py | 4 ++-- utils/color.py | 19 ++++++++++++++++--- utils/simple_functions.py | 11 +++++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/utils/bezier.py b/utils/bezier.py index acf18533..f61c47e5 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 500d5b9c..4625fa45 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 23669e70..35ad2c97 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