Simple and small performance improvements

This commit is contained in:
Grant Sanderson
2018-08-18 20:13:49 -07:00
parent 6f57a8bc5e
commit 039f7ffe58
3 changed files with 29 additions and 5 deletions

View File

@ -1,7 +1,7 @@
import numpy as np import numpy as np
from scipy import linalg 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 from utils.space_ops import get_norm
CLOSED_THRESHOLD = 0.001 CLOSED_THRESHOLD = 0.001
@ -10,7 +10,7 @@ CLOSED_THRESHOLD = 0.001
def bezier(points): def bezier(points):
n = len(points) - 1 n = len(points) - 1
return lambda t: sum([ 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) for k, point in enumerate(points)
]) ])

View File

@ -11,9 +11,12 @@ from utils.simple_functions import clip_in_place
def color_to_rgb(color): def color_to_rgb(color):
if not isinstance(color, Color): if isinstance(color, str):
color = Color(color) return hex_to_rgb(color)
return np.array(color.get_rgb()) elif isinstance(color, Color):
return np.array(color.get_rgb())
else:
raise Exception("Invalid color type")
def color_to_rgba(color, alpha=1): 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) 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): def invert_color(color):
return rgb_to_color(1.0 - color_to_rgb(color)) return rgb_to_color(1.0 - color_to_rgb(color))

View File

@ -8,6 +8,17 @@ def sigmoid(x):
return 1.0 / (1 + np.exp(-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): def choose(n, r):
if n < r: if n < r:
return 0 return 0