When they're not builtins, they're boltons.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Mathematical utilities, statistical analysis, and data summarization tools. Includes bit manipulation, number clamping, descriptive statistics, histogram formatting, and comprehensive data analysis capabilities.
Basic mathematical operations and number manipulation.
def clamp(x, lower=float('-inf'), upper=float('inf')):
"""
Clamp value between bounds.
Parameters:
- x (numeric): Value to clamp
- lower (numeric): Lower bound (default: negative infinity)
- upper (numeric): Upper bound (default: positive infinity)
Returns:
numeric: Clamped value
"""
def ceil(x, options=None):
"""
Ceiling function with rounding options.
Parameters:
- x (numeric): Value to round up
- options: Rounding options
Returns:
numeric: Ceiling value
"""
def floor(x, options=None):
"""
Floor function with rounding options.
Parameters:
- x (numeric): Value to round down
- options: Rounding options
Returns:
numeric: Floor value
"""Utilities for working with bits and binary operations.
class Bits:
"""Bit manipulation and representation utility class."""
def __init__(self, value=0, length=None): ...
def __getitem__(self, index): ...
def __setitem__(self, index, value): ...
def __len__(self): ...
def __int__(self): ...
def __str__(self): ...
def __repr__(self): ...
def flip(self, index): ...
def set(self, index, value=1): ...
def clear(self, index): ...
def count(self): ...
def to_bytes(self, length=None, byteorder='big'): ...
@classmethod
def from_bytes(cls, bytes_obj, byteorder='big'): ...Comprehensive statistical analysis and data summarization.
class Stats:
"""Statistical analysis class with descriptive statistics."""
def __init__(self, data=None): ...
def add(self, value): ...
def extend(self, values): ...
@property
def count(self): ...
@property
def mean(self): ...
@property
def median(self): ...
@property
def mode(self): ...
@property
def std_dev(self): ...
@property
def variance(self): ...
@property
def min(self): ...
@property
def max(self): ...
@property
def range(self): ...
def quantile(self, q): ...
def percentile(self, p): ...
def histogram(self, bins=10): ...
def describe(self): ...
def describe(data, quantiles=None, format=None):
"""
Generate descriptive statistics summary.
Parameters:
- data (iterable): Data to analyze
- quantiles (list, optional): Custom quantiles to calculate
- format (str, optional): Output format ('dict', 'text')
Returns:
dict or str: Statistical summary
"""Format and display histogram data.
def format_histogram_counts(bin_counts, width=None, **kwargs):
"""
Format histogram data for display.
Parameters:
- bin_counts (list): List of (bin_edge, count) tuples
- width (int, optional): Display width for formatting
Returns:
str: Formatted histogram display
"""from boltons.mathutils import clamp, Bits
from boltons.statsutils import Stats, describe
# Mathematical operations
value = clamp(150, lower=0, upper=100)
print(value) # 100 (clamped to upper bound)
negative = clamp(-10, lower=0, upper=100)
print(negative) # 0 (clamped to lower bound)
# Bit manipulation
bits = Bits(0b10110010, length=8)
print(bits) # "10110010"
print(bits[0]) # 0 (rightmost bit)
print(bits[7]) # 1 (leftmost bit)
bits.set(0) # Set rightmost bit
print(bits) # "10110011"
bits.flip(1) # Flip second bit
print(bits) # "10110001"
print(f"Set bits: {bits.count()}") # Count of 1-bits
# Convert to/from bytes
byte_data = bits.to_bytes(1, 'big')
new_bits = Bits.from_bytes(byte_data, 'big')
# Statistical analysis
data = [1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 8, 9, 10]
stats = Stats(data)
print(f"Mean: {stats.mean}") # 5.0
print(f"Median: {stats.median}") # 4.0
print(f"Mode: {stats.mode}") # 4 (most frequent)
print(f"Std Dev: {stats.std_dev}") # Standard deviation
print(f"Range: {stats.range}") # 9 (max - min)
# Quick statistical summary
summary = describe(data)
print(summary) # Dictionary with comprehensive statistics
# Add more data
stats.extend([11, 12, 13, 14, 15])
print(f"Updated mean: {stats.mean}")
# Quantiles and percentiles
q1 = stats.quantile(0.25) # First quartile
q3 = stats.quantile(0.75) # Third quartile
p90 = stats.percentile(90) # 90th percentile
print(f"Q1: {q1}, Q3: {q3}, P90: {p90}")from boltons.statsutils import Stats, format_histogram_counts
import random
# Generate sample data
random.seed(42)
sample_data = [random.gauss(50, 15) for _ in range(1000)]
# Comprehensive analysis
stats = Stats(sample_data)
print(f"Dataset size: {stats.count}")
print(f"Mean: {stats.mean:.2f}")
print(f"Median: {stats.median:.2f}")
print(f"Standard deviation: {stats.std_dev:.2f}")
print(f"Variance: {stats.variance:.2f}")
# Histogram analysis
histogram_data = stats.histogram(bins=20)
formatted_hist = format_histogram_counts(histogram_data, width=60)
print("Distribution:")
print(formatted_hist)
# Custom quantile analysis
quantiles = [0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99]
print("Quantile analysis:")
for q in quantiles:
value = stats.quantile(q)
print(f" {q*100:2.0f}th percentile: {value:.2f}")
# Detailed description
full_description = stats.describe()
print("Full statistical description:")
for key, value in full_description.items():
print(f" {key}: {value}")from boltons.mathutils import Bits
# Process flags and permissions
permissions = Bits(0b00000000, length=8)
READ_BIT = 0
WRITE_BIT = 1
EXECUTE_BIT = 2
ADMIN_BIT = 7
# Set permissions
permissions.set(READ_BIT)
permissions.set(WRITE_BIT)
permissions.set(ADMIN_BIT)
print(f"Permissions: {permissions}") # Binary representation
print(f"Can read: {bool(permissions[READ_BIT])}")
print(f"Can write: {bool(permissions[WRITE_BIT])}")
print(f"Can execute: {bool(permissions[EXECUTE_BIT])}")
print(f"Is admin: {bool(permissions[ADMIN_BIT])}")
# Serialize permissions
perm_bytes = permissions.to_bytes(1, 'big')
print(f"Serialized: {perm_bytes.hex()}")
# Deserialize and verify
restored_perms = Bits.from_bytes(perm_bytes, 'big')
print(f"Restored: {restored_perms}")
assert permissions.to_bytes(1, 'big') == restored_perms.to_bytes(1, 'big')# Statistical description return type (from Stats.describe())
StatisticalSummary = dict # Contains keys: count, mean, std, min, 25%, 50%, 75%, max
# Histogram data format
HistogramBin = tuple # (bin_edge, count) pairsInstall with Tessl CLI
npx tessl i tessl/pypi-boltons