Skip to main content

Mlib

一个0依赖库

不依赖random,math等标准库

纯python制作,不使用C拓展

快速开始

git clone https://github.com/limo1027/mlib
cd mlib
python -c "from gaskill.test import run_test; run_test()"

Learn More?

最新版本差异: 在plus中添加一个新的数据库,读极快,但是写偏慢MLIB HELP

A pure Python mathematics and utilities library

============================================================================ ABC - ABSTRACT BASE CLASSES (zero dependencies)

ABC - Abstract base class metaclass ABC() - Base class with ABCMeta

abstractmethod(func) - Mark method as abstract abstractclassmethod(func) - Mark class method as abstract abstractstaticmethod(func) - Mark static method as abstract abstractproperty(func) - Mark property as abstract

USAGE: class MyClass(ABC): @abstractmethod def my_method(self): pass

============================================================================ SMATH - MATHEMATICAL FUNCTIONS

CONSTANTS: pi = 3.141592653589793 e = 2.718281828459045 tau = 2*pi phi = 1.618033988749895 EPSILON = 1e-18 INF = float('inf')

ARITHMETIC: gcd(a,b) - Greatest common divisor lcm(a,b) - Least common multiple factorial(n) - n! (supports float via Gamma function) comb(n,k) - Combination C(n,k) perm(n,k) - Permutation P(n,k) is_prime(n) - Primality test (deterministic for n < 2^64) is_prime_fast(n) - Miller-Rabin primality test prime_factors(n) - Prime factorization, returns dict fibonacci(n) - nth Fibonacci number egcd(a,m) - Modular inverse of a mod m relative_error(self_val, real_val) - Relative error

POWER AND ROOTS: sqrt(x) - Square root (returns Complex for negative) cbrt(x) - Cube root root(x, n=2) - nth root pow(base, exp) - Built-in, works with Complex

EXPONENTIAL AND LOGARITHMS: exp(x) - e^x (supports Complex) ln(x) - Natural logarithm (supports Complex) log(x, base=None) - Logarithm with specified base log10(x) - Base-10 logarithm log2(x) - Base-2 logarithm

TRIGONOMETRY (angles in radians): sin(x) - Sine cos(x) - Cosine tan(x) - Tangent cot(x) - Cotangent sec(x) - Secant csc(x) - Cosecant asin(x) - Arc sine acos(x) - Arc cosine atan(x) - Arc tangent atan2(y,x) - Two-argument arc tangent sinc(x) - Sinc function sin(x)/x versin(x) - Versine 1-cos(x) coversin(x) - Coversine 1-sin(x) exsec(x) - Exsecant sec(x)-1 excsc(x) - Excosecant csc(x)-1 hav(x) - Haversine (1-cos(x))/2 archav(x) - Inverse haversine

HYPERBOLIC: sinh(x) - Hyperbolic sine cosh(x) - Hyperbolic cosine tanh(x) - Hyperbolic tangent coth(x) - Hyperbolic cotangent sech(x) - Hyperbolic secant csch(x) - Hyperbolic cosecant asinh(x) - Inverse hyperbolic sine acosh(x) - Inverse hyperbolic cosine atanh(x) - Inverse hyperbolic tangent acoth(x) - Inverse hyperbolic cotangent asech(x) - Inverse hyperbolic secant acsch(x) - Inverse hyperbolic cosecant

GAMMA AND BETA: gamma(z) - Gamma function log_gamma(z) - Log Gamma function ln(|Gamma(z)|) digamma(z) - Digamma function (approximate) beta(a,b) - Beta function B(a,b) = Gamma(a)*Gamma(b)/Gamma(a+b)

GUDERMANNIAN: gudermannian(x) - Gudermannian function gd(x) = 2*atan(tanh(x/2)) inv_gudermannian(x) - Inverse Gudermannian

ANGLE CONVERSION: rad(deg) - Degrees to radians deg(rad) - Radians to degrees normalize_angle(angle) - Normalize to [-pi, pi] wrap(x,a,b) - Wrap x into [a,b) clamp(x,min,max) - Clamp to range lerp(a,b,t) - Linear interpolation inv_lerp(a,b,v) - Inverse linear interpolation map(x,in_min,in_max,out_min,out_max,clamp_result=False) - Remap values

ROUNDING: floor(x) - Floor ceil(x) - Ceiling trunc(x) - Truncate fract(x) - Fractional part sign(x) - Sign: -1, 0, 1

VECTOR UTILITIES: hypot(*args) - Euclidean norm distance(p1,p2) - Distance between points angle_between(v1,v2) - Angle between vectors nearest(value, candidates) - Nearest value in list product(arr) - Product of array

EXCEPTIONS: MathError - Base math exception UndeFinedError - Undefined operation error

============================================================================ COMPLEX - COMPLEX NUMBERS

Complex(real, imag=None) - Complex number class

PROPERTIES: real - Real part imag - Imaginary part r - Magnitude (modulus) theta - Phase (argument)

METHODS: conjugate() - Return conjugate copy() - Return copy

OPERATORS: +, -, *, /, **, -, +, ==, !=, %, abs, hash

CREATION: Complex(3,4) -> (3+4i) Complex("3+4i") -> (3+4i) Complex(1j) -> i

============================================================================ SFRAC - EXACT FRACTIONS

Frac(numerator, denominator=None) - Exact rational number

PROPERTIES: n - Numerator d - Denominator

METHODS: as_percent(precision=0) - Percent string with precision digits

OPERATORS: +, -, *, /, **, -, +, ==, !=, <, <=, >, >=, %, abs, ~ (reciprocal) int(), float(), hash(), round()

FORMATTING: format(f, '%') - Percent: "25%" format(f, '.1%') - Percent with precision: "25.0%" format(f, 'l') - LaTeX: "\frac{1}{2}" format(f, 'm') - Mixed: "3 + 1/2" format(f, '/') - Fraction: "1/2" format(f, '.3f') - Float: "0.333"

============================================================================ SVECTOR - 2D, 3D, 4D VECTORS

vec2(x=0, y=0) - 2D vector vec3(x=0, y=0, z=0) - 3D vector vec4(x=0, y=0, z=0, w=0) - 4D vector

VEC2 METHODS: dot(other) - Dot product cross(other) - 2D cross product (scalar) length() - Magnitude length_squared() - Squared magnitude normalize() - Unit vector (zero returns zero) distance(other) - Distance to other vector distance_squared(other) - Squared distance lerp(other, t) - Linear interpolation rotate(angle) - Rotate by angle (radians) rotate_around(center, angle) - Rotate around a point reflect(normal) - Reflect vector project(onto) - Project onto another vector reject(onto) - Reject (perpendicular component) angle() - Vector angle (radians) angle_to(other) - Angle to other vector perpendicular() - Perpendicular vector (CCW 90 deg) scale(sx, sy=None) - Scale vector copy() - Return copy

VEC2 STATIC: zero(), one(), up(), down(), left(), right() from_angle(angle) - Unit vector from angle lerp_batch(v1, v2, t_values) - Batch linear interpolation

VEC3 METHODS: dot(other) - Dot product cross(other) - Cross product length() - Magnitude length_squared() - Squared magnitude normalize() - Unit vector distance(other) - Distance distance_squared(other) - Squared distance lerp(other, t) - Linear interpolation reflect(normal) - Reflect vector project(onto) - Project onto vector reject(onto) - Reject (perpendicular component) rotate_x(angle) - Rotate around X axis rotate_y(angle) - Rotate around Y axis rotate_z(angle) - Rotate around Z axis rotate_around(center, axis, angle) - Rotate around point and axis scale(sx, sy=None, sz=None) - Scale vector to_tuple() - Convert to tuple to_list() - Convert to list copy() - Return copy

VEC3 STATIC: zero(), one(), up(), down(), left(), right(), forward(), back() from_tuple(t), from_list(lst)

VEC4 METHODS: dot(other) - Dot product cross(other) - 3D cross product (first 3 components) length() - Magnitude length_squared() - Squared magnitude normalize() - Unit vector distance(other) - Distance distance_squared(other) - Squared distance lerp(other, t) - Linear interpolation reflect(normal) - Reflect vector project(onto) - Project onto vector reject(onto) - Reject (perpendicular component) to_vec3(w_divide=True) - Convert to vec3 (homogeneous divide) to_tuple(), to_list() - Convert to tuple/list to_rgba() - Convert to RGBA tuple (0-255) to_rgb() - Convert to RGB tuple (0-255) copy() - Return copy

VEC4 STATIC: zero(), one(), unit_x(), unit_y(), unit_z(), unit_w() from_vec3(v, w=1.0), from_rgba(r,g,b,a=255), from_tuple(t), from_list(lst)

SHORTCUT FUNCTIONS: v2(x=0, y=0), v3(x=0, y=0, z=0), v4(x=0, y=0, z=0, w=0) vlerp(v1, v2, t), distance(v1, v2), dot(v1, v2), cross(v1, v2) normalize(v), angle_between(v1, v2)

============================================================================ SMATRIX - MATRIX OPERATIONS

Matrix(data) - General matrix class

CREATION: Matrix([[a,b],[c,d]]) - From 2D list Matrix([1,2,3]) - Row vector matrix(data) - Shortcut for Matrix(data)

PROPERTIES: rows, cols, T (transpose)

METHODS: transpose() - Transpose matrix trace() - Trace (diagonal sum) det() - Determinant inverse() - Inverse matrix rank() - Matrix rank lu_decomposition() - Returns (L, U) copy() - Deep copy submatrix(row_start,row_end,col_start,col_end) - Extract submatrix minor(i,j) - Minor (determinant with row i, col j removed) cofactor(i,j) - Cofactor adjugate() - Adjugate matrix frobenius_norm() - Frobenius norm infinity_norm() - Infinity norm (row sum) one_norm() - 1-norm (column sum) is_symmetric() - Check symmetric is_identity() - Check identity matrix is_diagonal() - Check diagonal matrix diagonal() - Extract diagonal to_vector() - Convert to list if vector

OPERATORS: +, -, *, / (scalar), ==, -, []

SPECIAL MATRICES: rotation_matrix_2d(theta) - 2D rotation rotation_matrix_x(theta), rotation_matrix_y(theta), rotation_matrix_z(theta) scaling_matrix_2d(sx, sy=None) - 2D scaling scaling_matrix_3d(sx, sy=None, sz=None) - 3D scaling translation_matrix_2d(tx, ty) - 2D translation (3x3 homogeneous) translation_matrix_3d(tx, ty, tz) - 3D translation (4x4 homogeneous)

FUNCTIONS: solve_linear(A, b) - Solve Ax = b eigenvalues_2x2(matrix) - Eigenvalues of 2x2 matrix kronecker(A,B) - Kronecker product outer_product(v1,v2) - Outer product matrix_from_func(func, rows, cols=None, start=(0,0)) - Create from function

============================================================================ SQUATERNION - QUATERNIONS FOR 3D ROTATION

Quaternion(w=1.0, x=0.0, y=0.0, z=0.0) - Quaternion class

IDENTITY AND ZERO: IDENTITY = Quaternion(1,0,0,0) ZERO = Quaternion(0,0,0,0)

METHODS: copy() - Return copy conjugate() - Conjugate quaternion norm() - Norm (magnitude) norm_squared() - Squared norm normalize() - Unit quaternion inverse() - Inverse quaternion dot(other) - Dot product to_axis_angle() - Returns (axis, angle) tuple to_matrix() - Convert to 3x3 rotation matrix rotate_vector(v) - Rotate a vector

STATIC METHODS: from_axis_angle(axis, angle) - Create from axis-angle from_euler(roll, pitch, yaw) - Create from Euler angles (Z-Y-X) from_two_vectors(v1, v2) - Create rotation from v1 to v2

OPERATORS: +, -, *, / (scalar), -, ==, !=, [] (index)

FUNCTIONS: slerp(q1, q2, t) - Spherical linear interpolation nlerp(q1, q2, t) - Normalized linear interpolation squad(q0, q1, q2, q3, t) - Spherical quadrangle interpolation angular_velocity(q1, q2, dt) - Angular velocity between quaternions integrate_angular_velocity(q, omega, dt) - Integrate angular velocity look_at(eye, target, up=None) - Create quaternion looking at target random_quaternion(rng=None) - Random unit quaternion

============================================================================ SRANDOM - RANDOM NUMBER GENERATOR

Random(seed=None) - Deterministic PRNG

METHODS: seed(seed) - Reset seed next(a=0, b=9) - Next random integer in [a,b] randint(a,b) - Random integer in [a,b] random() - Random float in [0,1) random_float(start,end) - Random float in [start,end] choice(candidates) - Random element from list choices(arr, weight=None) - Weighted random selection shuffle(items) - Shuffle list in-place shuffle_copy(items) - Return shuffled copy sample(items, k) - Random k elements without replacement gauss(mu=0.0, sigma=1.0) - Gaussian (normal) distribution random_from_func(func, x_min, x_max, step=0.01, y_max=None) - Sample from function uuid() - Generate UUID v4 random_ascii(length=16, charset='ascii') - Random ASCII string roll(expr) - Roll dice expression (e.g., "2d6+3") hash(seed) - Custom hash function hash_digit(n) - Digit hash

CHARSETS for random_ascii: 'ascii' - Printable ASCII (33-126) 'alnum' - Alphanumeric 'alpha' - Letters only 'digit' - Digits only 'hex' - Hexadecimal digits 'base64' - Base64 alphabet 'all' - All 256 bytes

GLOBAL FUNCTIONS: random(rng=None) - Random float randint(a,b,rng=None) - Random integer choice(seq,rng=None) - Random choice shuffle(seq,rng=None) - Shuffle list sample(seq,k,rng=None) - Random sample random_ascii(length=16, charset='ascii', rng=None) - Random string

============================================================================ SCOLOR - COLOR MANIPULATION

FUNCTIONS: rgb(r,g,b) - RGB color tuple (0-255) rgba(r,g,b,a=255) - RGBA color tuple (0-255) hex_to_rgb(hex_str) - Hex string to RGB (e.g., "#FF0000" -> (255,0,0)) rgb_to_hex(r,g,b) - RGB to hex string

CONVERSIONS: rgb_to_hsv(r,g,b) - RGB to HSV (h: 0-360, s: 0-1, v: 0-1) hsv_to_rgb(h,s,v) - HSV to RGB (0-255) rgb_to_cymb(r,g,b) - RGB to CYMB (CMYK variant) cymb_to_rgb(c,y,m,k) - CYMB to RGB

COLOR OPERATIONS: complementary(color, mode='rgb') - Complementary color color_lerp(c1,c2,t) - Color linear interpolation blend(c1,c2, mode='normal', alpha=0.5) - Color blending gradient_at(color_dict, t) - Sample gradient at t gradient_range(color_dict, steps=256) - Generate gradient list grayscale(color) - Convert to grayscale invert(color) - Invert color adjust_brightness(color, factor) - Adjust brightness adjust_saturation(color, factor) - Adjust saturation adjust_hue(color, degrees) - Adjust hue set_alpha(color, alpha) - Set alpha channel premultiply_alpha(color) - Premultiply alpha distance(c1,c2) - Euclidean color distance luminance(color) - Perceived luminance (0-1) contrast_ratio(c1,c2) - WCAG contrast ratio is_dark(color, threshold=0.5) - Check if dark is_light(color, threshold=0.5) - Check if light mix(c1,c2, amount=0.5) - Mix colors random_color(rng=None) - Random RGB color

BLEND MODES: 'normal', 'multiply', 'screen', 'overlay', 'add', 'subtract', 'difference', 'average'

PREDEFINED COLORS: WHITE, BLACK, RED, GREEN, BLUE, YELLOW, PURPLE, ORANGE, CYAN, GRAY BROWN, PINK, GOLD, MAGENTA, BACKGROUND, LIGHT_BLUE, LIGHT_GRAY LIGHT_ORANGE, LIGHT_GREEN, LIGHT_BROWN, LIGHT_PINK, LIGHT_PURPLE LIGHT_CYAN, LIGHT_YELLOW, LIGHT_CORAL, DARK_GREEN, DARK_BLUE DARK_RED, DARK_GOLD, DARK_PURPLE, DARK_BROWN, DARK_CYAN, DARK_ORANGE DARK_GRAY, DARK_PINK, AQUA, LAVENDER, CORAL, TEAL, INDIGO, VIOLET MAROON, OLIVE, NAVY, LIME, FUCHSIA, SILVER PRIMARY, SECONDARY, SUCCESS, WARNING, ERROR, INFO, TRANSPARENT

============================================================================ SGEOMETRY - 2D GEOMETRY

Rect(x=0, y=0, w=0, h=0, angle=0) - Rectangle (angle in radians) Circle(center, radius) - Circle Polygon(points) - Polygon (vec2 or tuples) Line2(p1, p2) - 2D line segment

RECT PROPERTIES: x, y, w, h, angle (degrees), left, right, top, bottom, center topleft, topright, bottomleft, bottomright, width, height, area

RECT METHODS: collide_point(x, y) - Point inside rect collide_rect(other) - Rect vs rect collision collide_circle(circle) - Rect vs circle collision inflate(dw, dh) - Expand rect expand(*args) - Expand to include point or rect move(dx, dy) - Move rect union(other) - Bounding box of two rects get_rects(step=10) - Convert to AABB rectangle list (for rendering)

CIRCLE PROPERTIES: center, radius, area

CIRCLE METHODS: collide_point(x, y) - Point inside circle collide_circle(other) - Circle vs circle collide_rect(rect) - Circle vs rect get_rects(step=10) - Convert to AABB rectangle list

POLYGON METHODS: vertices - List of vec2 edges - List of edge vectors normals - List of outward normals contains_point(point) - Point in polygon test contains_point_accurate(point) - Point in or on polygon get_aabb() - Bounding box (min_x, min_y, w, h) convex_hull() - Compute convex hull (returns Polygon) triangulate() - Triangulate (ear clipping) collide_rect(rect) - Polygon vs rect collide_polygon(other) - Polygon vs polygon (SAT) move(dx, dy) - Translate polygon rotate(angle, center=None) - Rotate polygon scale(factor, center=None) - Scale polygon get_rects(step=10) - Convert to AABB rectangle list

LINE2 METHODS: length() - Line length closest_point(p) - Closest point on line collide_point(x,y,tolerance=0.1) - Point near line intersect_line(other) - Line-line intersection

RAY FUNCTIONS: raycast_rect(ray_origin, ray_dir, rect) - Ray vs rect collision reflect(vector, normal) - Reflect vector

SHORTCUTS: rect(x,y,w,h,angle=0), circle(center, radius), line(p1,p2)

============================================================================ SGEOMETRY3D - 3D GEOMETRY

AABB(min_point, max_point) - Axis-Aligned Bounding Box Ray(origin, direction) - Ray Sphere(center, radius) - Sphere Plane(normal, point/d) - Plane

AABB METHODS: from_center_size(center, size) - Create from center and size from_points(points) - Create from point list center, size, extents - Properties expand(point) - Expand to include point inflate(amount) - Uniform expansion contains_point(point) - Point inside intersects_aabb(other) - AABB vs AABB intersects_sphere(center, radius) - AABB vs sphere surface_area() - Surface area volume() - Volume merge(other) - Merge AABBs

RAY METHODS: point_at(t) - Point on ray at distance t intersect_sphere(center, radius) - Ray vs sphere intersect_plane(point, normal) - Ray vs plane intersect_triangle(v0,v1,v2) - Ray vs triangle intersect_aabb(aabb) - Ray vs AABB closest_point_to(point) - Closest point on ray distance_to_point(point) - Distance from ray to point

SPHERE METHODS: contains_point(point) - Point inside intersects_sphere(other) - Sphere vs sphere intersects_aabb(aabb) - Sphere vs AABB surface_area(), volume()

PLANE METHODS: from_three_points(p1,p2,p3) - Create from 3 points distance_to_point(point) - Signed distance project_point(point) - Project point to plane is_on_plane(point, tolerance) - Check if on plane

FUNCTION: project_3d_to_2d(point, camera_pos, camera_angle, fov, width, height) - 3D to 2D projection

============================================================================ SCURVE - CURVES AND SPLINES

BEZIER CURVES: quadratic_bezier(p0, p1, p2, t) - Quadratic Bezier cubic_bezier(p0, p1, p2, p3, t) - Cubic Bezier bezier(points, t) - Arbitrary degree Bezier (de Casteljau) bezier_derivative(points, t, order=1) - Derivative (tangent) bezier_path(points, steps=100) - Generate curve points bezier_length(points, steps=100) - Approximate curve length de_casteljau_subdivide(points, t) - Subdivide curve

B-SPLINE: b_spline(control_points, knots, degree, t) - B-spline evaluation b_spline_curve(control_points, degree=3, steps=100) - Generate curve points uniform_knots(n, degree) - Uniform knot vector clamped_knots(n, degree) - Clamped knot vector

NURBS: nurbs(control_points, weights, knots, degree, t) - NURBS evaluation

GENERAL: curve_length(points_func, steps=100) - General curve length _lerp(p0,p1,t) - Linear interpolation helper

============================================================================ SEASING - EASING FUNCTIONS

BASIC: linear(t) - Constant speed

QUADRATIC: quad_in(t) - Accelerate (t^2) quad_out(t) - Decelerate (t*(2-t)) quad_in_out(t) - Accelerate then decelerate

CUBIC: cubic_in(t) - t^3 cubic_out(t) - (t-1)^3 + 1 cubic_in_out(t) - Cubic accelerate/decelerate

SINE: sine_in(t) - Sine accelerate sine_out(t) - Sine decelerate sine_in_out(t) - Sine ease

EXPONENTIAL: expo_in(t) - Exponential accelerate expo_out(t) - Exponential decelerate expo_in_out(t) - Exponential ease

CIRCULAR: circ_in(t) - Circular accelerate circ_out(t) - Circular decelerate circ_in_out(t) - Circular ease

BACK: back_in(t) - Pull back then forward back_out(t) - Overshoot then return

BOUNCE: bounce_out(t) - Bounce at end bounce_in(t) - Bounce at start bounce_in_out(t) - Bounce both ends

ELASTIC: elastic_out(t, amplitude=1, period=0.3) - Elastic out elastic_in(t, amplitude=1, period=0.3) - Elastic in

TWEEN: tween(start, end, duration, elapsed, easing=linear) - Compute tween value Tween(start, end, duration, easing=linear) - Tween animation class

Tween METHODS: update(dt) - Update and return value reset() - Reset animation

DICTIONARY: EASING - Dict of all easing functions (string -> function) ease(t, type='linear') - Get easing by name

============================================================================ SINTERP - INTERPOLATION FUNCTIONS

lerp(a,b,t) - Linear interpolation (clamped 0-1) lerp_unclamped(a,b,t) - Linear interpolation (no clamp) bilerp(v00,v10,v01,v11,x,y) - Bilinear interpolation trilerp(v000,v100,v010,v110,v001,v101,v011,v111,x,y,z) - Trilinear interpolation slerp(v1,v2,t) - Spherical linear interpolation (for vectors) smoothstep(edge0, edge1, x) - Smooth step function smootherstep(edge0, edge1, x) - Smoother step function coserp(a,b,t) - Cosine interpolation cubic_bezier(p0,p1,p2,p3,t) - Cubic Bezier value cubic_bezier_derivative(p0,p1,p2,p3,t) - Cubic Bezier derivative catmull_rom(p0,p1,p2,p3,t) - Catmull-Rom spline hermite(p0,t0,p1,t1,s) - Hermite curve inverse_lerp(a,b,value) - Inverse linear interpolation remap(value,in_min,in_max,out_min,out_max) - Remap value pingpong(value,length) - Ping-pong value damp(current,target,lambda_val,dt) - Damped interpolation spring(current,target,velocity,frequency,damping,dt) - Spring interpolation

============================================================================ SCACHE - CACHING

LFUCache(max_size=100) - Least Frequently Used cache LRUCache(max_size=100) - Least Recently Used cache TTLCache(max_size=100, default_ttl=None) - Time-to-live cache CacheEntry(key, value, ttl=None) - Cache entry with TTL RingBuffer(capacity) - Fixed-size FIFO buffer CacheStats() - Cache statistics

memoize(max_size=128, method=False) - Memoization decorator

LFUCache METHODS: get(key, default=None), set(key, value), setitem, getitem contains, pop(key, default=None), clear(), keys(), values(), items() size, max_size (properties), len, repr

LRUCache METHODS: get(key, default=None), set(key, value), setitem, getitem contains, pop(key, default=None), clear(), keys(), values(), items() size, max_size (properties), len, repr

TTLCache METHODS: get(key, default=None, current_time=0), set(key, value, ttl=None, current_time=0) clear(), remove_expired(current_time), size (property), len, repr

RingBuffer METHODS: push(item), pop(), peek(), clear(), capacity (property), is_empty(), is_full()

CacheStats METHODS: record_hit(), record_miss(), record_eviction() hits, misses, evictions, total_requests, hit_rate (properties) reset(), repr

memoize USAGE: @memoize(max_size=128) def expensive_func(x): return x*x

@memoize(max_size=128, method=True) def expensive_method(self, x): return x*x

============================================================================ SEVENT - EVENT SYSTEM

EventSystem(dt=0.016) - Event system class event = EventSystem() - Global event instance

EVENT SYSTEM METHODS: on(event_name, handler) - Register permanent listener (returns ID) once(event_name, handler) - Run once then auto-remove times(count, event_name, handler) - Run fixed times then auto-remove when(event_name, condition, handler) - Condition-triggered listener wheel_once(event_name, condition, handler) - Condition-triggered, runs once delay(delay_time, event_name, handler) - Delayed event emit(event_name, *args, **kwargs) - Trigger event update(dt=None) - Update delayed events remove(event_name, listener_id) - Remove listener redo(event_name, listener_id) - Reactivate listener clear(event_name=None) - Clear listeners

============================================================================ SFSM - FINITE STATE MACHINE

State(name) - State base class StateMachine(initial_state=None) - Finite state machine FunctionState(name, on_enter, on_exit, on_update, on_event) - Functional state StateTransition() - State transition table

State METHODS: enter(old_state) - Called on enter exit(new_state) - Called on exit update(dt) - Called each frame handle_event(event) - Process event, return next state

StateMachine METHODS: add_state(state) - Add state remove_state(state_name) - Remove state set_state(state_name) - Switch state update(dt) - Update current state handle_event(event) - Process event transition_to(state_name) - Switch state revert_to_previous() - Go back to previous state lock() - Lock state changes unlock() - Unlock state changes current_state, current_state_name, previous_state, states (properties) has_state(state_name), clear()

FunctionState USAGE: on_enter = lambda old: print("Entering") state = FunctionState("my_state", on_enter=on_enter)

StateTransition METHODS: add_transition(from_state, to_state, condition=None) - Add transition get_transition(from_state, context=None) - Get target state clear()

============================================================================ SPOOL - OBJECT POOL

ObjectPool(factory=None, reset_func=None, max_size=100) - Object pool PooledObject() - Poolable object base class AutoReleasePool() - Auto-release context manager StackAllocator(initial_capacity=100) - LIFO allocator

ObjectPool METHODS: acquire(*args, **kwargs) - Get object from pool release(obj) - Return object to pool clear() - Clear pool available_count, in_use_count, total_count (properties) len, repr

PooledObject METHODS: recycle() - Return to pool on_acquire() - Called when acquired on_release() - Called when released is_active (property)

AutoReleasePool METHODS: enter, exit - Context manager support add(obj, release_method='recycle') - Add object to pool release_all() - Release all objects count (property)

StackAllocator METHODS: push(obj) - Push object pop() - Pop object pop_multiple(count) - Pop multiple objects clear() - Clear stack size, capacity (properties) len, repr

============================================================================ SPATHFINDER - PATHFINDING ALGORITHMS

astar(grid, start, end, heuristic='manhattan', allow_diagonal=False) - A* search astar_weighted(grid, start, end, weight=1.0, ...) - Weighted A* dijkstra(grid, start, end, weights=None, allow_diagonal=False) - Dijkstra bfs(grid, start, end) - Breadth-first search bidirectional_bfs(grid, start, end) - Bidirectional BFS dfs_maker(width, height, start=(1,1), seed=None) - Generate maze

astar_cost(cost_grid, start, end, heuristic='manhattan', allow_diagonal=False) - A* with cost grid dijkstra_cost(cost_grid, start, end, allow_diagonal=False) - Dijkstra with cost grid get_path_cost(cost_grid, path, allow_diagonal=False) - Calculate path cost create_cost_grid(grid, default_cost=1.0, wall_cost=-1.0, custom_costs=None) - Create cost grid

HEURISTICS: 'manhattan' - |dx| + |dy| 'euclidean' - sqrt(dx^2 + dy^2) 'chebyshev' - max(|dx|, |dy|) 'octile' - max(|dx|,|dy|) + (sqrt(2)-1) * min(|dx|,|dy|)

RETURN VALUE: All pathfinders return list of vec2 points or None if no path

GRID FORMAT: 0 = passable, 1 = wall (or any non-zero value)

COST GRID FORMAT: Positive values = movement cost -1 = wall (impassable)

============================================================================ SSAVER - SAVE/Load SYSTEM (SGT format)

SGTsaver() - Save/load state with checksum

METHODS: set_value(**kwargs) - Set multiple values add(key, value) - Set single value (chainable) save(filename, use_hash=True) - Save to file load(filename, require_hash=True) - Load from file get(key, default=None) - Get value getitem(key), setitem(key, value) - Dict-style access

SUPPORTED TYPES: str, int, float, bool, list, tuple, dict vec2, vec3 (and similar objects with x,y,z attributes)

FILE FORMAT: #key=value #key2=value2 hash=checksum

USAGE: s = SGTsaver() s.set_value(name="player", score=100) s.save("save.sgt") s2 = SGTsaver() s2.load("save.sgt") print(s2["name"]) # "player"

============================================================================ SFORMAT - FORMATTING UTILITIES

uuid4(obj) - Convert any object to UUID superscript(n) - Convert number to superscript string visual_len(t) - Visual length (Chinese = 2, ASCII = 1) center(s, width) - Center align by visual width table(data, border_style="unicode", shows={...}) - Pretty table

TABLE BORDER STYLES: 'unicode', 'ascii', 'double', 'rounded'

TABLE SHOWS FORMAT: shows = {"left": 5, "right": 5, "top": 5, "bottom": 5} Controls how many rows/columns to show (ellipsis for hidden)

ordinal(number) - Convert to ordinal string (1st, 2nd, 3rd) to_poly(expr, use_star=False) - Convert expression to polynomial string number_to_english(n) - Convert integer to English words english_to_number(s) - Convert English words to integer insert(base_str, place, insert_str) - Insert substring at position encode(string) - Encode string to numeric representation decode(encoded) - Decode numeric representation time_format(seconds, mode='auto') - Format time duration

TIME FORMAT MODES: 'auto' - Adaptive (1s, 1m, 1h, 1d) 'full' - HH:MM:SS 'short' - Xh Ym Zs 'words' - X hours Y minutes Z seconds

file_size(size_bytes, mode='auto', decimal=False) - Format file size

FILE SIZE MODES: 'auto' - Adaptive (SI) 'bits' - Bits (Kb, Mb, etc.) 'si' - SI units (KB, MB, GB) 'binary' - Binary units (KiB, MiB, GiB) 'short' - Short (B, K, M, G) 'full' - Full words (bytes, kilobytes)

============================================================================ SNOISE - NOISE GENERATION

PerlinNoise(seed=None, octaves=4, persistence=0.5, lacunarity=2.0) SimplexNoise(seed=None, octaves=4, persistence=0.5, lacunarity=2.0) Snoise(falloff=1.0) - Simple noise field from control points

PerlinNoise METHODS: noise2d(x, y) - 2D Perlin noise [-1, 1] fbm2d(x, y) - Fractal Brownian motion terrain_height(x, y) - Terrain height (ridges)

SimplexNoise METHODS: noise2d(x, y) - 2D Simplex noise [-1, 1] (no grid artifacts) fbm2d(x, y) - Fractal Brownian motion

Snoise METHODS: add_point(x, y, value) - Add control point add_points(*points) - Add multiple points clear() - Clear all points set_falloff(falloff) - Set falloff factor call(x, y, use_cache=True) - Get noise value sample_rect(x1,y1,x2,y2,step=1.0) - Sample region heatmap(x1,y1,x2,y2,step=1.0) - Generate heatmap (0-255)

SHORTCUT: snoise_from_points(points, falloff=1.0) - Create Snoise from points

============================================================================ SCRYPT - CRYPTOGRAPHY

rsa_generate_keys(bits=512) - Generate RSA key pair rsa_encrypt(message, public_key) - RSA encryption rsa_decrypt(cipher, private_key) - RSA decryption

simple_encrypt(value, key=None, second=None) - Simple encryption simple_decrypt(cipher, key, IV, second=None) - Simple decryption

share_secret(plaintext, keys, threshold) - Secret sharing (encrypt) recover_secret(shares_dict, threshold) - Secret sharing (decrypt)

RSA KEY FORMAT: {'e': e, 'd': d, 'n': n, 'p': p, 'q': q, 'phi': phi}

simple_encrypt RETURN: If key is None: (cipher, key, IV) If key is provided: (cipher, IV)

Secret sharing USAGE: shares = share_secret("secret", ["key1", "key2", "key3"], threshold=2) recovered = recover_secret(shares, 2) # Any 2 shares enough

============================================================================ SOLVER - EQUATION SOLVING

solve_linear(a,b) - Solve ax + b = 0 solve_quadratic(a,b,c) - Solve ax^2 + bx + c = 0 (supports complex) solve_cubic(a,b,c,d) - Solve ax^3 + bx^2 + cx + d = 0 (supports complex) solve_polynomial(coefficients) - Auto-select solver (degree <= 3) solve_polynomial_numerical(coefficients, max_iter=1000, tol=1e-10) - Numerical solver (any degree) roots(coefficients) - Alias for solve_polynomial_numerical poly(val, coefficients) - Evaluate polynomial

COEFFICIENTS FORMAT: [a, b, c, d] for ax^3 + bx^2 + cx + d

EXCEPTION: NoSolutionError - No solution found

============================================================================ SSTAT - STATISTICS

CENTRAL TENDENCY: mean(data) - Arithmetic mean geometric_mean(data) - Geometric mean harmonic_mean(data) - Harmonic mean median(data) - Median mode(data) - Mode (all values) quantile(data, p) - Quantile (p in [0,1]) quartiles(data) - (Q1, Q2, Q3) iqr(data) - Interquartile range

DISPERSION: variance(data, ddof=0) - Variance stdev(data, ddof=0) - Standard deviation mad(data) - Mean absolute deviation range_stat(data) - Range (max - min) cv(data, ddof=0) - Coefficient of variation

SHAPE: skewness(data, ddof=0) - Skewness kurtosis(data, ddof=0) - Kurtosis (excess)

RELATIONSHIP: covariance(x,y) - Covariance correlation(x,y) - Pearson correlation spearman(x,y) - Spearman rank correlation linear_regression(x,y) - Linear regression (returns slope, intercept, R^2)

PROBABILITY DISTRIBUTIONS: normal_pdf(x, mu=0, sigma=1) - Normal PDF normal_cdf(x, mu=0, sigma=1) - Normal CDF (approx) binomial_pmf(k, n, p) - Binomial PMF poisson_pmf(k, lam) - Poisson PMF

HYPOTHESIS TESTING: z_score(x, mu, sigma) - Z-score t_test(data, mu0) - One-sample t-test (returns t, p) chi_square(observed, expected) - Chi-square test f_test(a,b) - F-test (variance ratio)

TRANSFORMATIONS: normalize(data, new_min=0, new_max=1) - Normalize to range standardize(data) - Standardize (mean=0, stdev=1)

TIME SERIES: rolling_mean(data, window) - Moving average ewma(data, alpha) - Exponential weighted moving average

SUMMARY: summary(data) - Complete statistical summary (dict) probability_distribution(data) - Probability distribution (dict)

============================================================================ SBASE64 - BASE ENCODINGS

b16encode(data), b16decode(data) - Base16 (hex) b32encode(data), b32decode(data) - Base32 b64encode(data), b64decode(data) - Base64 b64urlencode(data), b64urldecode(data) - Base64 URL-safe b58encode(data), b58decode(data) - Base58 (Bitcoin) b256encode(data), b256decode(data) - Base256 (Chinese characters)

DATA TYPE: All functions accept and return bytes

Base64 URL-safe: Uses '-' and '_' instead of '+' and '/'

Base58: Uses Bitcoin alphabet: 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz (Note: 0, O, I, l are excluded)

Base256: Uses Chinese characters from 0x4E00 Encodes each byte as a 3-byte UTF-8 character

============================================================================ PICKLE - CUSTOM BINARY SERIALIZATION

pack(obj) - Pack any object to bytes unpack(data, pos=0) - Unpack bytes to object dump(obj, filename) - Save object to file load(filename) - Load object from file

pack_float(num) - Pack float to binary string unpack_float(byte_data) - Unpack float from bytes pack_int(n, bits=None) - Pack integer pack_str(n) - Pack string bits_to_bytes(bits) - Binary string to bytes bytes_to_bits(data) - Bytes to binary string pack_to_file(obj, filename) - Pack and write to file

SUPPORTED TYPES: str, int, float, bool, list, tuple, dict, None

FILE FORMAT: Type marker + data + terminator 'S' - String (varint length + UTF-8) 'I' - Non-negative integer (varint) 'i' - Negative integer (varint) 'F' - Float (8 bytes IEEE 754) 'B' - Boolean (1 byte) 'L' - List (items + 'E') 'D' - Dictionary (key+value pairs + 'E') 'N' - None

============================================================================ HASHLIB - SHA-256 AND HASHING

sha256(message) - SHA-256 hash (returns hex string) DJB2(s, capacity=0xffffffff) - DJB2 hash

MESSAGE TYPES: str - UTF-8 encoded bytes - Raw bytes list of ints - Bytes as integers

SHA-256 INTERNALS (exported): rotr(x,n) - Rotate right shr(x,n) - Shift right xor3(a,b,c) - XOR of three add_mod32(a,b) - 32-bit add ch(x,y,z), maj(x,y,z) - SHA functions sigma0(x), sigma1(x), gamma0(x), gamma1(x) - SHA functions pad_message(msg_bytes) - Padding bytes_to_words(block) - Block to words compress_block(block_bytes, h_vals) - Compression

============================================================================ BMP - BMP IMAGE READER/WRITER

BMPImage(width, height) - BMP image class

METHODS: set_pixel(x, y, color) - Set pixel (R,G,B) or (R,G,B,A) get_pixel(x, y) - Get pixel color save(filename) - Save as BMP to_rgb() - Remove alpha channel load(filename) - Load from file (class method) load_from_bytes(data) - Load from bytes (class method)

COLOR FORMAT: RGB: (r, g, b) each 0-255 RGBA: (r, g, b, a) each 0-255

SUPPORTED BIT DEPTHS (loading): 1, 4, 8, 16, 24, 32

SAVING: 24-bit (RGB) or 32-bit (RGBA)

FACTORY METHODS: create_checkerboard(width, height, size=10) - Checkerboard pattern create_gradient(width, height) - Gradient pattern

EXCEPTION: BMPError - BMP operation error

============================================================================ ECC - ELLIPTIC CURVE CRYPTOGRAPHY (ECDSA)

ecdsa_sign_with_k(private_key, message, k) - ECDSA signature with custom k ecdsa_verify(public_key, message, signature) - ECDSA verification is_valid_private_key(k) - Check private key is_valid_k(k) - Check ephemeral key

CURVE: secp256k1 (Bitcoin curve) p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F a = 0, b = 7 n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 G = Base point (x, y)

SIGNATURE FORMAT: (r, s) where r and s are integers

USAGE: priv = 123456789 msg = "Hello, world!" k = 987654321 # Must be random and unique r, s = ecdsa_sign_with_k(priv, msg, k) pub = G * priv # Public key valid = ecdsa_verify(pub, msg, (r, s))

============================================================================ DECIMAL - HIGH-PRECISION DECIMAL

Decimal(value, fr_len=None) - High-precision decimal

SETTINGS: decimal.prec = 50 - Global precision (default 50)

FUNCTIONS: dec_pi() - Pi to decimal.prec digits dec_e() - e to decimal.prec digits dec_ln2() - ln(2) to decimal.prec digits dec_exp(value) - Exponential dec_ln(value) - Natural logarithm dec_sin(x) - Sine dec_cos(x) - Cosine dec_atan(x) - Arc tangent asin(x) - Arc sine (using dec_atan)

OPERATORS: +, -, *, /, //, %, **, -, +, ==, !=, <, <=, >, >=, abs int(), float(), round()

FORMATTING: repr() - 'Decimal("3.14")' str() - 'Decimal("3.14")'

USAGE: d1 = Decimal("3.141592653589793") d2 = Decimal(2) result = d1 * d2 # Decimal("6.283185307179586")

============================================================================ POLY - POLYNOMIALS

Poly(terms=None) - Polynomial class Poly.from_string(poly_str) - Parse polynomial string

TERMS FORMAT: [(coeff, {var: exp, ...}), ...] Example: [(3, {'x': 2}), (2, {'x': 1}), (1, {})] = 3x^2 + 2x + 1

METHODS: degree(var=None) - Degree of polynomial evaluate(values) - Evaluate with variable values derivative(var='x') - Differentiate factor() - Factor polynomial extract_gcf() - Extract greatest common factor

OPERATORS: +, -, *, -, ==

FUNCTIONS: factors_to_str(factors) - Convert factor list to string

USAGE: p = Poly.from_string("x^2 + 2x + 1") p.evaluate({'x': 3}) # 16 p.derivative() # 2x + 2 p.factor() # [(x+1), (x+1)]

============================================================================ RADICAL - EXACT RADICALS

Radical(index, radicand, coeff=1) - Exact radical representation

real_sqrt(n) - Square root (index=2) real_root(n, x) - nth root

PROPERTIES: index - Root index radicand - Value under root (int, float, Frac, tuple, or Radical) coeff - Coefficient

METHODS: approx() - Float approximation conjugate() - Conjugate for rationalization

OPERATORS: +, -, *, /, **, -, +, ==, hash, float()

USAGE: r = Radical(2, 12) # sqrt(12) = 2sqrt(3) print(r) # 2√(3) r.approx() # 3.464101615... r = Radical(2, 2) * Radical(2, 3) # sqrt(6) r + Radical(2, 3) # sqrt(2) + sqrt(3) (kept as sum)

============================================================================ ZIP - COMPRESSION (LZ77 + HUFFMAN)

compress(data) - Compress bytes decompress(data, codes, count) - Decompress

COMPRESS FORMAT: Returns (compressed_bytes, codes_dict, symbol_count)

USAGE: data = b"Hello, world!" compressed, codes, count = compress(data) original = decompress(compressed, codes, count)

ALGORITHM:

  1. LZ77 sliding window compression
  2. Huffman coding on symbols

============================================================================ RE - REGULAR EXPRESSIONS

Regex(pattern) - Regular expression engine

METHODS: match(text) - Return True if pattern matches

SUPPORTED SYNTAX: . - Any character

    • Zero or more
    • One or more ? - Zero or one | - Alternation ^ - Start anchor $ - End anchor [abc] - Character class [a-z] - Character range [^abc] - Negated character class {n} - Exactly n times {n,m} - Between n and m times {n,} - n or more times () - Grouping

ESCAPE SEQUENCES: \d - Digit \D - Non-digit \w - Word character (A-Z, a-z, 0-9, _) \W - Non-word character \s - Whitespace \S - Non-whitespace

USAGE: re = Regex(r"\d+") re.match("123") # True re.match("abc") # False

re = Regex(r"^[A-Z]+\d+$") re.match("ABC123") # True

============================================================================ DATABASE - DISK-BASED KEY-VALUE STORE

DiskKV(filepath, initial_capacity=131072) - Key-value store on disk

METHODS: set(key, value) - Set key-value (string keys and values) get(key, default=None) - Get value flush() - Force write to disk close() - Close database

PROPERTIES: capacity - Current capacity count - Number of keys

USAGE: db = DiskKV("data.db") db.set("name", "John") db.set("age", "30") print(db.get("name")) # "John" db.close()

============================================================================ TESTER - UNIT TESTING FRAMEWORK

TestCase - Test case base class TestRunner - Test runner test - Decorator: mark test method skip(reason="") - Decorator: skip test

DECORATORS: @test - Mark method as test @skip("reason") - Skip test

ASSERTIONS: assert_equal(a,b) - a == b assert_not_equal(a,b) - a != b assert_almost_equal(a,b,places=7) - round(a-b, places) == 0 assert_not_almost_equal(a,b,places=7) - round(a-b, places) != 0 assert_greater(a,b) - a > b assert_greater_equal(a,b) - a >= b assert_less(a,b) - a < b assert_less_equal(a,b) - a <= b assert_true(x) - bool(x) is True assert_false(x) - bool(x) is False assert_is(a,b) - a is b assert_is_not(a,b) - a is not b assert_is_none(x) - x is None assert_is_not_none(x) - x is not None assert_in(a,b) - a in b assert_not_in(a,b) - a not in b assert_isinstance(a,b) - isinstance(a,b) assert_not_isinstance(a,b) - not isinstance(a,b) assert_issubclass(a,b) - issubclass(a,b) assert_not_issubclass(a,b) - not issubclass(a,b) assert_count_equal(a,b) - Same elements (order ignored) assert_starts_with(a,b) - a.startswith(b) assert_not_starts_with(a,b) - not a.startswith(b) assert_ends_with(a,b) - a.endswith(b) assert_not_ends_with(a,b) - not a.endswith(b) assert_has_attr(a,b) - hasattr(a,b) assert_not_has_attr(a,b) - not hasattr(a,b)

assert_raises(exc_class) - Context manager for exceptions

HOOKS: setup() - Before each test teardown() - After each test setup_class() - Before all tests in class teardown_class() - After all tests in class

USAGE: class MyTest(TestCase): @test def test_add(self): self.assert_equal(1+1, 2)

  @test
  @skip("not implemented")
  def test_mul(self):
      pass

runner = TestRunner() runner.run_all()

============================================================================ SUI - SIMPLE UI COMPONENTS

Label(x,y,width,height,text="", **kwargs) - Text label Button(x,y,width,height,text="", **kwargs) - Clickable button Bar(x,y,width,height,value=1.0, **kwargs) - Progress/health bar Entry(x,y,width,height,text="", **kwargs) - Text input

render_all(components) - Render all components draw(cmd_type) - Decorator to register render handler

LABEL PARAMETERS: color - Background color (default (240,240,240)) text_color - Text color (default (0,0,0)) align - 'left', 'center', 'right'

BUTTON PARAMETERS: color - Normal color hover_color - Hover color press_color - Pressed color text_color - Text color border - True/False radius - Corner radius

BUTTON METHODS: handle_event(mouse_pos, keys) - Update hover state press() - Press button release() - Release button (returns True if clicked)

BAR PARAMETERS: bg_color - Background color fill_color - Fill color text_color - Text color show_text - Show percentage orientation - 'horizontal' or 'vertical'

BAR METHODS: set_hp(current, max_hp) - Set health value

ENTRY PARAMETERS: placeholder - Placeholder text placeholder_color - Placeholder color color - Background color text_color - Text color border - True/False radius - Corner radius cursor_blink_tim - Blink interval (ms)

ENTRY METHODS: handle_event(mouse_pos, keys, dt) - Process input (returns True on submit) config(**kwargs) - Configure component

COMPONENT METHODS: config(**kwargs) - Set parameters render() - Return render commands destroy() - Hide component enter(x,y) - Check if mouse inside

============================================================================ VECTOR AND QUATERNION QUICK REFERENCE

VECTOR OPERATORS: v + v, v - v, v * scalar, v / scalar, v == v, -v, v[i]

QUATERNION OPERATORS: q + q, q - q, q * q, q * scalar, q / scalar, -q, q == q, q[i]

FFT - FAST FOURIER TRANSFORM

fft(x) - Fast Fourier Transform (supports any length, auto-pads to power of 2) ifft(X, original_length=None) - Inverse FFT

fftfreq(N, d=1.0) - Generate frequency coordinates for FFT fftshift(x) - Shift zero frequency to center ifftshift(x) - Inverse of fftshift

magnitude_spectrum(x, shift=False) - Compute magnitude spectrum |X| power_spectrum(x, shift=False) - Compute power spectrum |X|^2 phase_spectrum(x, shift=False) - Compute phase spectrum angle(X)

INPUT/OUTPUT: x - List of numbers (int, float, or Complex) X - List of Complex numbers (FFT output)

RETURN VALUES: fft(x) - Returns (X, N) where N is original length (for ifft) ifft(X, original_length) - Returns list of Complex (or numbers) fftfreq(N, d) - Returns list of frequencies (d = sampling interval)

USAGE: from mlib.plus.fft import fft, ifft, fftfreq, fftshift, magnitude_spectrum

Basic FFT x = [1.0, 2.0, 3.0, 4.0] X, N = fft(x) x_recovered = ifft(X, N)

Frequency analysis freqs = fftfreq(len(x), d=0.01) mag = magnitude_spectrum(x, shift=True)

Shift zero frequency to center X_shifted = fftshift(X)

NOTES:

Input length does NOT need to be a power of 2 (auto-padding applied)

fft() returns (spectrum, original_length) for proper reconstruction

fftshift() and ifftshift() work for both even and odd lengths

EXAMPLES:

Sine wave analysis from mlib import pi, sin t = [i * 0.01 for i in range(100)] x = [sin(2pi50*t[i]) for i in range(len(t))] X, N = fft(x) freqs = fftfreq(N, d=0.01) mag = magnitude_spectrum(x, shift=True)

Peak at 50 Hz Filtering X, N = fft(x) for i in range(len(X)): if abs(fftfreq(N, 0.01)[i]) > 100: X[i] = 0 filtered = ifft(X, N)

============================================================================ IMPORT PATHS

from mlib import * from mlib.gaskill import * from mlib.plus import *

Main package imports everything from gaskill and plus subpackages.

Metadata

Release files for gaskill 3.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gaskill 3.1.0
File Size Uploaded
gaskill-3.1.0.tar.gz 154.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for gaskill 3.1.0
File Interpreter ABI Platform
gaskill-3.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 320.6 kB

Release files / gaskill-3.1.0.tar.gz

Download URL gaskill-3.1.0.tar.gz
Size 154.5 kB
Tags Source
SHA-256 checksum
How to use checksums
da8158fc4dec4e6ae899c71c485a8a8a504a9501e72e2e7c8e528e2b08f7d91c
BLAKE2b-256 checksum
How to use checksums
13ab1d97abd70d0c372cf953e776cabeb40227adcba02212367035348b4e6d3b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.4

Release files / gaskill-3.1.0-py3-none-any.whl

Download URL gaskill-3.1.0-py3-none-any.whl
Size 166.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f7d2cdfc195651ffe272c9a5de3b1c2197f495a665889070a3754bbff6cc054b
BLAKE2b-256 checksum
How to use checksums
2bb314c71748ecce9204f0e0f4addbb133bcdc1207647669f33f8dad10d210c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.4

Release history Release notifications | RSS feed

3.2.0

2 release files

3.1.2

2 release files

3.1.1

2 release files

This release

3.1.0 This release

2 release files

3.0.1

2 release files

3.0.0

2 release files

2.17.0

2 release files

2.15.2

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page