API Reference¶
Public API¶
utilities — NumPy-backed utility functions.
All public symbols are re-exported from utilities.core so
callers can simply write:
from utilities import sort_real, get_constant, convert_units
This package is a self-contained set of utility functions inspired by IMSL Fortran Numerical Library Utilities chapter, backed by numpy, scipy.stats, math, and the Python standard library.
- utilities.sort_real(x, ascending=True)¶
Sort a real array (IMSL SVRGN). Returns a sorted copy.
- Parameters:
x (np.ndarray) – 1-D array of real values to sort.
ascending (bool) – If
True(default) sort ascending;Falsefor descending.
- Returns:
1-D sorted copy of
xasfloat64.- Return type:
np.ndarray
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.sort_real_indexed(x, ascending=True)¶
Sort a real array and return permutation indices (IMSL SVRGP).
- Parameters:
x (np.ndarray) – 1-D array of real values to sort.
ascending (bool) – Sort direction. Default is ascending.
- Returns:
(sorted_array, permutation_indices)where
sorted_array[i] == x[permutation_indices[i]].
- Return type:
tuple[np.ndarray, np.ndarray]
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.sort_integer(x, ascending=True)¶
Sort an integer array (IMSL SVIGN). Returns a sorted copy.
- Parameters:
x (np.ndarray) – 1-D array of integers to sort.
ascending (bool) – Sort direction. Default is ascending.
- Returns:
1-D sorted integer array.
- Return type:
np.ndarray
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.sort_integer_indexed(x, ascending=True)¶
Sort an integer array and return permutation indices (IMSL SVIGP).
- Parameters:
x (np.ndarray) – 1-D array of integers to sort.
ascending (bool) – Sort direction. Default is ascending.
- Returns:
(sorted_array, permutation_indices).- Return type:
tuple[np.ndarray, np.ndarray]
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.sort_by_abs(x, ascending=True)¶
Sort a real array by absolute value (IMSL SVRBN). Returns a sorted copy.
The returned array contains the original signed values ordered by their absolute magnitude.
- Parameters:
x (np.ndarray) – 1-D array of real values.
ascending (bool) – Sort direction by absolute magnitude. Default ascending.
- Returns:
Copy of
xordered by absolute value.- Return type:
np.ndarray
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.sort_by_abs_indexed(x, ascending=True)¶
Sort a real array by absolute value with permutation indices (IMSL SVRBP).
- Parameters:
x (np.ndarray) – 1-D array of real values.
ascending (bool) – Sort direction by absolute magnitude. Default ascending.
- Returns:
(sorted_array, permutation_indices)where elements are ordered by absolute value.
- Return type:
tuple[np.ndarray, np.ndarray]
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D.
- utilities.search_sorted_real(x, value)¶
Binary search in a sorted real array (IMSL SRCH).
- Parameters:
x (np.ndarray) – 1-D sorted real array (ascending order).
value (float) – The value to search for.
- Returns:
- Index
isuch thatx[i] <= value < x[i+1]. Returns
-1ifvalue < x[0]andlen(x) - 1ifvalue >= x[-1].
- Index
- Return type:
int
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D or is empty.
- utilities.search_sorted_integer(x, value)¶
Binary search in a sorted integer array (IMSL ISRCH).
- Parameters:
x (np.ndarray) – 1-D sorted integer array (ascending order).
value (int) – The integer value to search for.
- Returns:
- Index
isuch thatx[i] <= value < x[i+1]. Returns
-1ifvalue < x[0].
- Index
- Return type:
int
- Raises:
TypeError – If
xis not a numpy array.ValueError – If
xis not 1-D or is empty.
- utilities.permute_vector(x, perm)¶
Apply a permutation to a vector (IMSL PERMU). Returns
x[perm].- Parameters:
x (np.ndarray) – 1-D input vector of length n.
perm (np.ndarray) – 1-D integer permutation array of length n. Each element must be a valid index into
x.
- Returns:
Permuted copy of
x.- Return type:
np.ndarray
- Raises:
TypeError – If
xorpermare not numpy arrays.ValueError – If shapes are incompatible.
- utilities.permute_matrix(A, perm, axis=0)¶
Permute rows or columns of a matrix (IMSL PERMA).
- Parameters:
A (np.ndarray) – 2-D matrix of shape
(m, n).perm (np.ndarray) – 1-D integer permutation array.
axis (int) –
0to permute rows (default),1to permute columns.
- Returns:
Permuted copy of
A.- Return type:
np.ndarray
- Raises:
TypeError – If
Aorpermare not numpy arrays.ValueError – If
Ais not 2-D,axisis invalid, orpermlength does not match the selected dimension.
- utilities.random_uniform(n, seed=None)¶
Generate
nuniform(0, 1) random numbers (IMSL RNUNF/RNUN).Uses
numpy.random.- Parameters:
n (int) – Number of random values to generate. Must be positive.
seed (int | None) – Optional random seed for reproducibility.
- Returns:
1-D array of
nvalues uniformly distributed in[0, 1).- Return type:
np.ndarray
- Raises:
ValueError – If
nis not positive.
- utilities.random_generate(n, distribution='uniform', seed=None, **kwargs)¶
Generate random numbers from a named distribution (IMSL RAND_GEN).
- Parameters:
n (int) – Number of random values to generate. Must be positive.
distribution (str) – Distribution name. Supported values:
'uniform','normal','exponential','gamma','beta','chi2','f','t'.seed (int | None) – Optional seed for reproducibility.
**kwargs – Distribution-specific keyword arguments forwarded to the underlying numpy generator. For example
scale=2.0for exponential,a=2.0, b=5.0for beta,df=3for chi2/t.
- Returns:
1-D array of
nsamples from the requested distribution.- Return type:
np.ndarray
- Raises:
ValueError – If
nis not positive ordistributionis not supported.
- utilities.rng_set_seed(seed)¶
Set the global random seed (IMSL RNSET). Uses
numpy.random.seed.- Parameters:
seed (int) – Non-negative integer seed value.
- Returns:
None
- Raises:
TypeError – If
seedis not an integer.ValueError – If
seedis negative.
- Return type:
None
- utilities.rng_get_seed()¶
Get the last seed set via
rng_set_seed()(IMSL RNGET).- Returns:
- The last seed value passed to
rng_set_seed(), or0if the seed has never been explicitly set in this session.
- The last seed value passed to
- Return type:
int
- utilities.faure_sequence(n_points, n_dim, seed=None)¶
Generate a Faure low-discrepancy sequence (IMSL FAURE_INIT/NEXT).
Returns an array of shape
(n_points, n_dim)with values in[0, 1]^n_dim. Implemented viascipy.stats.qmc.Haltonas a well-studied low-discrepancy approximation.- Parameters:
n_points (int) – Number of quasi-random points to generate.
n_dim (int) – Number of dimensions. Must be at least 1.
seed (int | None) – Optional seed for scrambling. If
Noneno scrambling is applied.
- Returns:
Array of shape
(n_points, n_dim)in[0, 1]^n_dim.- Return type:
np.ndarray
- Raises:
ValueError – If
n_pointsorn_dimare not positive integers.
- utilities.get_constant(name)¶
Return a mathematical or physical constant (IMSL CONST).
Supported names (case-insensitive):
'pi','e','euler_gamma','golden_ratio','speed_of_light','planck','boltzmann','avogadro','gravitational','electron_mass','proton_mass','elementary_charge','vacuum_permittivity','vacuum_permeability','gas_constant','faraday','stefan_boltzmann'.- Parameters:
name (str) – Case-insensitive constant name from the supported set.
- Returns:
The numerical value of the constant in SI units.
- Return type:
float
- Raises:
KeyError – If
nameis not a recognised constant.
- utilities.convert_units(value, from_unit, to_unit)¶
Convert a value between units (IMSL CUNIT).
- Parameters:
value (float) – Numeric value to convert.
from_unit (str) – Source unit string (see supported categories below).
to_unit (str) – Target unit string (must be in the same category).
- Return type:
float
Supported unit categories:
Length:
'm','km','cm','mm','ft','in','yd','mile','nmi'Mass:
'kg','g','lb','oz','tonne'Temperature:
'C','F','K','R'Pressure:
'Pa','kPa','MPa','bar','atm','psi','mmHg','torr'Energy:
'J','kJ','MJ','cal','kcal','BTU','eV','kWh'Power:
'W','kW','MW','hp','BTU/h'Velocity:
'm/s','km/h','mph','knot','ft/s'Angle:
'rad','deg','grad'Time:
's','ms','us','min','h','day','week','year'Volume:
'm3','L','mL','gal','ft3','in3'
- Returns:
Converted value in
to_unit.- Return type:
float
- Raises:
KeyError – If
from_unitorto_unitis not recognised.ValueError – If
from_unitandto_unitbelong to different physical categories.
- Parameters:
value (float)
from_unit (str)
to_unit (str)
- utilities.prime_factors(n)¶
Decompose an integer into prime factors (IMSL PRIME).
- Parameters:
n (int) – Positive integer to factorise. Must be >= 2.
- Returns:
- Sorted list of prime factors with repetition.
For example,
prime_factors(12) == [2, 2, 3].
- Return type:
list[int]
- Raises:
TypeError – If
nis not an integer.ValueError – If
nis less than 2.
- utilities.hypot_safe(a, b)¶
Compute
sqrt(a^2 + b^2)without underflow or overflow (IMSL HYPOT).Uses
math.hypot()for numerically stable computation.- Parameters:
a (float) – First leg of the right triangle.
b (float) – Second leg of the right triangle.
- Returns:
Hypotenuse length
sqrt(a^2 + b^2).- Return type:
float
- utilities.days_from_epoch(year, month, day)¶
Number of days from Jan 1, 1900 to the given date (IMSL NDAYS).
Jan 1, 1900 itself returns 0.
- Parameters:
year (int) – Four-digit year.
month (int) – Month (1–12).
day (int) – Day of month (1–31).
- Returns:
Number of days since Jan 1, 1900 (0-based).
- Return type:
int
- Raises:
ValueError – If the date is invalid or before Jan 1, 1900.
- utilities.date_from_days(n)¶
Return the date for
ndays from Jan 1, 1900 (IMSL NDYIN).- Parameters:
n (int) – Number of days from Jan 1, 1900 (0 = Jan 1, 1900).
- Returns:
(year, month, day)of the resulting date.- Return type:
tuple[int, int, int]
- Raises:
ValueError – If
nis negative.
- utilities.day_of_week(year, month, day)¶
Return the day of week for a given date (IMSL IDYWK).
Uses
datetime.- Parameters:
year (int) – Four-digit year.
month (int) – Month (1–12).
day (int) – Day of month (1–31).
- Returns:
Day index where 0 = Monday, …, 6 = Sunday.
- Return type:
int
- Raises:
ValueError – If the date is invalid.
- utilities.cpu_time()¶
Return elapsed CPU time in seconds (IMSL CPSEC).
Uses
time.process_time().- Parameters:
None
- Returns:
CPU process time in seconds since the start of the process.
- Return type:
float
- utilities.launch_documentation(opener=<function open>, package_dir=None)¶
Launch package documentation in a web browser.
The launcher opens local HTML documentation only.
- Parameters:
opener (Callable[[str], bool]) – Browser opener function. Defaults to
webbrowser.open.package_dir (Path | None) – Optional package directory override used for tests. Defaults to the directory of this module.
- Returns:
The
file://...URI opened.- Return type:
str
- Raises:
FileNotFoundError – If no local documentation index can be located.