3b1b-manim/manimlib/utils/simple_functions.py

102 lines
2.3 KiB
Python
Raw Normal View History

2022-12-18 09:13:11 -08:00
from __future__ import annotations
2022-04-12 19:19:59 +08:00
from functools import lru_cache
import hashlib
import inspect
import math
2022-04-12 19:19:59 +08:00
import numpy as np
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Callable, TypeVar, Iterable
from manimlib.typing import FloatArray
Scalable = TypeVar("Scalable", float, FloatArray)
def sigmoid(x: float | FloatArray):
return 1.0 / (1 + np.exp(-x))
2022-01-26 13:03:14 +08:00
@lru_cache(maxsize=10)
def choose(n: int, k: int) -> int:
return math.comb(n, k)
def gen_choose(n: int, r: int) -> int:
return int(np.prod(range(n, n - r, -1)) / math.factorial(r))
def get_num_args(function: Callable) -> int:
return function.__code__.co_argcount
2019-01-29 14:22:46 -08:00
def get_parameters(function: Callable) -> Iterable[str]:
return inspect.signature(function).parameters.keys()
def clip(a: float, min_a: float, max_a: float) -> float:
if a < min_a:
return min_a
elif a > max_a:
return max_a
return a
def arr_clip(arr: np.ndarray, min_a: float, max_a: float) -> np.ndarray:
arr[arr < min_a] = min_a
arr[arr > max_a] = max_a
return arr
def fdiv(a: Scalable, b: Scalable, zero_over_zero_value: Scalable | None = None) -> Scalable:
"""
Less heavyweight name for np.true_divide, enabling
default behavior for 0/0
"""
if zero_over_zero_value is not None:
out = np.full_like(a, zero_over_zero_value)
where = np.logical_or(a != 0, b != 0)
else:
out = None
where = True
return np.true_divide(a, b, out=out, where=where)
2019-02-06 21:16:26 -08:00
def binary_search(
function: Callable[[float], float],
target: float,
lower_bound: float,
upper_bound: float,
tolerance:float = 1e-4
) -> float | None:
2019-02-06 21:16:26 -08:00
lh = lower_bound
rh = upper_bound
mh = (lh + rh) / 2
2019-02-06 21:16:26 -08:00
while abs(rh - lh) > tolerance:
lx, mx, rx = [function(h) for h in (lh, mh, rh)]
if lx == target:
return lx
if rx == target:
return rx
if lx <= target and rx >= target:
if mx > target:
rh = mh
else:
lh = mh
elif lx > target and rx < target:
lh, rh = rh, lh
else:
return None
mh = (lh + rh) / 2
2019-02-06 21:16:26 -08:00
return mh
Cleaner local caching of Tex/Text data, and partially cleaned up configuration (#2259) * Remove print("Reloading...") * Change where exception mode is set, to be quieter * Add default fallback monitor for when no monitors are detected * Have StringMobject work with svg strings rather than necessarily writing to file Change SVGMobject to allow taking in a string of svg code as an input * Add caching functionality, and have Tex and Text both use it for saved svg strings * Clean up tex_file_writing * Get rid of get_tex_dir and get_text_dir * Allow for a configurable cache location * Make caching on disk a decorator, and update implementations for Tex and Text mobjects * Remove stray prints * Clean up how configuration is handled In principle, all we need here is that manim looks to the default_config.yaml file, and updates it based on any local configuration files, whether in the current working directory or as specified by a CLI argument. * Make the default size for hash_string an option * Remove utils/customization.py * Remove stray prints * Consolidate camera configuration This is still not optimal, but at least makes clearer the way that importing from constants.py kicks off some of the configuration code. * Factor out configuration to be passed into a scene vs. that used to run a scene * Use newer extract_scene.main interface * Add clarifying message to note what exactly is being reloaded * Minor clean up * Minor clean up * If it's worth caching to disk, then might as well do so in memory too during development * No longer any need for custom hash_seeds in Tex and Text * Remove display_during_execution * Get rid of (no longer used) mobject_data directory reference * Remove get_downloads_dir reference from register_font * Update where downloads go * Easier use of subdirectories in configuration * Add new pip requirements
2024-12-05 16:51:14 -06:00
def hash_string(string: str, n_bytes=16) -> str:
hasher = hashlib.sha256(string.encode())
Cleaner local caching of Tex/Text data, and partially cleaned up configuration (#2259) * Remove print("Reloading...") * Change where exception mode is set, to be quieter * Add default fallback monitor for when no monitors are detected * Have StringMobject work with svg strings rather than necessarily writing to file Change SVGMobject to allow taking in a string of svg code as an input * Add caching functionality, and have Tex and Text both use it for saved svg strings * Clean up tex_file_writing * Get rid of get_tex_dir and get_text_dir * Allow for a configurable cache location * Make caching on disk a decorator, and update implementations for Tex and Text mobjects * Remove stray prints * Clean up how configuration is handled In principle, all we need here is that manim looks to the default_config.yaml file, and updates it based on any local configuration files, whether in the current working directory or as specified by a CLI argument. * Make the default size for hash_string an option * Remove utils/customization.py * Remove stray prints * Consolidate camera configuration This is still not optimal, but at least makes clearer the way that importing from constants.py kicks off some of the configuration code. * Factor out configuration to be passed into a scene vs. that used to run a scene * Use newer extract_scene.main interface * Add clarifying message to note what exactly is being reloaded * Minor clean up * Minor clean up * If it's worth caching to disk, then might as well do so in memory too during development * No longer any need for custom hash_seeds in Tex and Text * Remove display_during_execution * Get rid of (no longer used) mobject_data directory reference * Remove get_downloads_dir reference from register_font * Update where downloads go * Easier use of subdirectories in configuration * Add new pip requirements
2024-12-05 16:51:14 -06:00
return hasher.hexdigest()[:n_bytes]