lmpy reference

Complete reference for the lmpy numerical host as released in lmpy 0.1.46: command-line flags, exit codes, the result frame, every host type, method and function, the out context object, the expression grammar, and the standard lmcode catalog it ships. The host tables are generated from the output of lmpy --api-md, which the repository keeps as native/API.md.

See also the quick reference, the skill and the guide.

Command-line flags

CommandResult
lmpy --lmcode FILE [FILE ...]Runs the bytecode files in order. Every input is loaded before any part executes. Prints exactly one result frame; several files return a result array in registration order.
lmpy --dry-run --lmcode FILE [FILE ...]Validates and loads the inputs without running callbacks and returns null results. A dry flag that contradicts real-mode invocation metadata is refused as a usage error.
lmpy --lmcode-schemaPrints the plain-text API summary: the context line, then functions and types with their signatures.
lmpy --lmcode-schema --jsonPrints the exact schema bytes the bytecode binds to (the same bytes as native/schema/lmpy.dsl.json and the release asset lmpy.dsl.json).
lmpy --schema [--json]Older alias of --lmcode-schema still accepted by the 0.1.46 command line.
lmpy --lmcode-signaturesPrints the canonical signatures of the whole registry, one per line: 757 lines in 0.1.46 (551 host lines including the context line, plus 206 standard catalog signatures).
lmpy --api-mdPrints the generated API reference as Markdown.
lmpy --versionPrints the release identity in the form lmpy X.Y.Z.
lmpy --help, lmpy -hPrints the usage text and exits 0.

Exit codes

CodeMeaningFrame phase
0Success.none (ok is true)
2Usage error: missing or invalid arguments, invalid invocation metadata. LMScript compile errors in the calling program also exit 2, from lmscript.cli
3Load or run-time error: unreadable or mismatched bytecode, or a failing host call such as a singular matrix.load or run
4Application failure: out.fail was called or at least one out.check, out.close or out.close_rel failed.app

Result frame

The host writes one frame to standard output: a line LMCODE_RETURN_BEGIN, one JSON document, and a line LMCODE_RETURN_END. run_lmcode decodes it and returns the JSON document as an LMScript map.

FieldPresent whenMeaning
okalwaystrue on success, false on any failure.
resultok is trueBy default an object with values (everything recorded with out.put, in order) and checks. An explicit lmcode_return_set, lmcode_return_put or lmcode_return_null call replaces this default result. Dry runs return null.
result.checks.passed, result.checks.failed, result.checks.failuresdefault resultCounts of passed and failed checks and the list of failures, each with name and detail.
phaseok is falsecli, load, run or app.
codeok is falseAn error code such as CLI_USAGE, LOAD_BAD_BYTECODE, LOAD_SCHEMA_MISMATCH, LOAD_UNBOUND, RUN_HOST, RUN_ERROR or APP_FAIL.
messageok is falseThe diagnostic. Run-time messages start with dsl line N:C and name the operation.
line, columnrun-time errors with a source positionThe position inside the lmcode block.

Block declaration and runner

FormMeaning
prog = _lmcode_ cli="lmpy" install="github:lmctl-ai/lmpy@latest"; ... end _lmcode_Compiles the block against the schema printed by the lmpy binary. When lmpy is not installed, lmscript downloads the release asset for the platform into its tool cache and verifies its SHA-256 digest.
prog = _lmcode_ schema="path/to/lmpy.dsl.json"; ... end _lmcode_Compiles against a schema file, as the repository examples under examples/dsl do.
r = run_lmcode(prog);Runs the block on the declared host and returns the decoded frame: r.ok, r.result, or r.phase, r.code and r.message on failure.
r = run_lmcode(prog, {command: [bin, "--lmcode", "$DSLFILE"]});Runs the block with an explicit host command; the repository runner examples/dsl/lmpy.lms uses this form with the LMPY environment variable or lmpy on PATH.

Context objects

NameTypeMeaning
outOutvalues and checks returned to the caller as JSON

Vectors

Vec is a 1-D float64 array (numpy ndarray of rank 1). Methods return new vectors unless marked in place. Arithmetic operators are elementwise; mixing a Vec with a float broadcasts the float.

Vectors: functions

SignatureMeaning
arange(float, float, float) -> Vecstart, start+step, ... below stop (numpy.arange)
arange(int) -> Vec0, 1, ..., n-1 as floats
concat(Vec, Vec) -> Vecconcatenation
full(int, float) -> Vecn copies of a value
linspace(float, float, int) -> Vecn evenly spaced values from start to stop inclusive (numpy.linspace)
ones(int) -> Vecn ones
vec() -> Vecempty vector
vec(float) -> Vecone-element vector
vec(float, float) -> Vectwo-element vector
vec(float, float, float) -> Vecthree-element vector
vec(float, float, float, float) -> Vecfour-element vector
vec(float, float, float, float, float) -> Vec5-element vector
vec(float, float, float, float, float, float) -> Vec6-element vector
vec(float, float, float, float, float, float, float) -> Vec7-element vector
vec(float, float, float, float, float, float, float, float) -> Vec8-element vector
vec(string) -> Vecparse numbers separated by spaces/commas (brackets allowed, nan accepted): vec("1 2.5 -3")
zeros(int) -> Vecn zeros

Type Vec

1-D float64 array. Operators: +, -, * elementwise (Vec or float on either side), unary -.

Operators: * → mul, + → add, - → sub, neg → neg, r* → mul, r+ → add, r- → rsub

MethodMeaning
abs() -> Vecelementwise absolute value
add(Vec) -> Vecelementwise sum
add(float) -> Vecadd a scalar
all_finite() -> booltrue when no element is NaN or infinite
apply(string) -> Vecevaluate an expression in x for each element: v.apply("exp(-x^2/2)")
apply(string, string, Vec) -> Vecevaluate an expression in x and a second named vector elementwise: x.apply("x*w", "w", w)
argmax() -> intindex of the first maximum
argmin() -> intindex of the first minimum
argsort() -> Vecindexes that sort ascending (stable)
at(int) -> floatelement i (negative counts from the end)
ceil() -> Vecelementwise ceiling
clip(float, float) -> Vecclamp each element to [lo, hi]
copy() -> Vecindependent copy
cos() -> Vecelementwise cosine
count() -> intnumber of nonzero, non-NaN entries (count of a mask)
cumsum() -> Veccumulative sum
diff() -> Vecfirst differences x[i+1]-x[i]
div(Vec) -> Vecelementwise quotient (IEEE: x/0 is inf or nan)
div(float) -> Vecdivide by a scalar
dot(Vec) -> floatinner product
eq(float) -> Vecmask (1.0/0.0) of x == c
eq(Vec) -> Vecelementwise mask of x == y
exp() -> Vecelementwise exponential
extend(Vec) -> Vecin place: append another vector; returns the vector
find() -> Vecindexes of the nonzero, non-NaN entries (numpy.flatnonzero of a mask)
floor() -> Vecelementwise floor
fmt(int) -> stringspace-separated values with fixed decimals
ge(float) -> Vecmask (1.0/0.0) of x >= c
ge(Vec) -> Vecelementwise mask of x >= y
gt(float) -> Vecmask (1.0/0.0) of x > c
gt(Vec) -> Vecelementwise mask of x > y
isnan() -> Vecelementwise 1.0 where NaN, else 0.0
json() -> stringJSON array text
le(float) -> Vecmask (1.0/0.0) of x <= c
le(Vec) -> Vecelementwise mask of x <= y
len() -> intlength
log() -> Vecelementwise natural logarithm
log10() -> Vecelementwise base-10 logarithm
log1p() -> Vecelementwise log(1 + x)
lt(float) -> Vecmask (1.0/0.0) of x < c
lt(Vec) -> Vecelementwise mask of x < y
max() -> floatmaximum (NaN if any NaN)
mean() -> floatarithmetic mean
median() -> floatmedian
min() -> floatminimum (NaN if any NaN)
mul(Vec) -> Vecelementwise product
mul(float) -> Vecscale by a scalar
ne(float) -> Vecmask (1.0/0.0) of x != c
ne(Vec) -> Vecelementwise mask of x != y
neg() -> Vecnegation
norm() -> floatEuclidean norm
pow(float) -> Vecelementwise power
prod() -> floatproduct
push(float) -> Vecin place: append x; returns the vector
quantile(float) -> floatquantile q in [0,1], linear interpolation (numpy default)
reverse() -> Vecreversed copy
round() -> Vecelementwise round half to even (numpy.round)
rsub(float) -> Vecscalar minus each element
set(int, float) -> Vecin place: element i = x; returns the vector
sin() -> Vecelementwise sine
slice(int, int) -> Vecelements [start, stop) (numpy slicing; negative indexes count from the end, out-of-range clamps)
sort() -> Vecascending copy (NaN last)
sqrt() -> Vecelementwise square root
square() -> Vecelementwise x*x
std(int) -> floatstandard deviation with ddof
sub(Vec) -> Vecelementwise difference
sub(float) -> Vecsubtract a scalar
sum() -> floatsum (compensated)
take(Vec) -> Vecelements at the given (float, integral) indexes
tanh() -> Vecelementwise hyperbolic tangent
unique() -> Vecsorted distinct values
var(int) -> floatvariance with ddof (0 population, 1 sample)
where(Vec) -> Vecelements whose mask entry is nonzero (boolean indexing x[mask])

Text lists

StrVec is a list of strings: column names, labels, path lists.

Text lists: functions

SignatureMeaning
split(string, string) -> StrVecsplit text on a separator (no trimming)
strs() -> StrVecempty list
strs(string) -> StrVeccomma-separated names, trimmed: strs("x1, x2")
strs(int, string) -> StrVecn copies of one string (a label column)

Type StrVec

List of strings.

MethodMeaning
at(int) -> stringelement i
contains(string) -> boolmembership
index(string) -> intfirst position or -1
join(string) -> stringjoin with a separator
json() -> stringJSON array text
len() -> intlength
push(string) -> StrVecin place: append; returns the list

Matrices

Mat is a dense float64 matrix. * is the matrix product (numpy @) when both sides are matrices, a matrix-vector product with a Vec, and scaling with a float; use hadamard for the elementwise product.

Matrices: functions

SignatureMeaning
cols(Vec) -> Matone-column matrix
cols(Vec, Vec) -> Matcolumn_stack of two vectors
cols(Vec, Vec, Vec) -> Matcolumn_stack of three vectors
cols(Vec, Vec, Vec, Vec) -> Matcolumn_stack of four vectors
diag(Vec) -> Matdiagonal matrix
eye(int) -> Matn x n identity
mat(int, int) -> Matrows x cols zeros
mat(Vec, int, int) -> Matreshape a vector, row-major, to rows x cols
mat(string) -> Matparse rows separated by ; (or JSON nested arrays): mat("1 2; 3 4")

Type Mat

Dense float64 matrix. Operators: +, - (Mat), * (Mat, Vec or float), unary -, float * Mat.

Operators: * → mul, + → add, - → sub, neg → neg, r* → mul

MethodMeaning
add(Mat) -> Matelementwise sum
add_col(Vec) -> Matnew matrix with the vector appended as a last column
at(int, int) -> floatelement (i, j)
block(int, int, int, int) -> Matsub-matrix (row, col, nrows, ncols)
col(int) -> Veccolumn j
col_means() -> Vecmean of each column
col_sums() -> Vecsum of each column
cols() -> intcolumn count
flatten() -> Vecrow-major values
hadamard(Mat) -> Matelementwise product
hstack(Mat) -> Matcolumns of this then other
json() -> stringnested JSON arrays, row-major
max_abs_diff(Mat) -> floatmax |a - b| (shapes must match)
mul(Mat) -> Matmatrix product (numpy @)
mul(Vec) -> Vecmatrix-vector product
mul(float) -> Matscale
neg() -> Matnegation
row(int) -> Vecrow i
row_sums() -> Vecsum of each row
rows() -> introw count
set(int, int, float) -> Matin place: element (i, j) = x; returns the matrix
sub(Mat) -> Matelementwise difference
sum() -> floatsum of all elements
t() -> Mattranspose
take_rows(Vec) -> Matrows at the given indexes
vstack(Mat) -> Matrows of this then other
with_intercept() -> Matnew matrix with a leading column of ones (sm.add_constant)

Options and results

Operations take an optional Opts (named options, validated: an unknown key is an error) and return a Res (named, typed result fields). Field and option names follow pycli's JSON names.

Options and results: functions

SignatureMeaning
opts() -> Optsempty options

Type Opts

Named options builder: opts().set("method", "BFGS").set("tol", 1e-8).

MethodMeaning
has(string) -> boolwhether a key is set
set(string, float) -> Optsin place: float option
set(string, int) -> Optsin place: int option
set(string, string) -> Optsin place: string option
set(string, bool) -> Optsin place: bool option
set(string, Vec) -> Optsin place: vector option
set(string, StrVec) -> Optsin place: name-list option
set(string, Mat) -> Optsin place: matrix option

Type Res

Typed result fields. Reading a missing field or the wrong kind is a run-time error that lists the fields.

MethodMeaning
flag(string) -> boolbool field
has(string) -> boolwhether a field exists
int(string) -> intint field
json() -> stringthe whole result as JSON text
keys() -> StrVecfield names in order
mat(string) -> Matmatrix field
num(string) -> floatfloat field (an int field widens)
ok() -> boolstatus == "OK"
res(string) -> Resnested result field
status() -> stringthe status field ("OK", "NO_CONVERGENCE", ...)
strs(string) -> StrVecname-list field
text(string) -> stringstring field
vec(string) -> Vecvector field

Utilities

Formatting and numeric helpers that the DSL's built-ins (str, float, int, sqrt, pow, ...) do not cover.

Utilities: functions

SignatureMeaning
atan2(float, float) -> floatatan2(y, x)
eval(string) -> floatevaluate a constant expression (pycli expression grammar)
eval(string, string, float) -> floatevaluate an expression in one named variable
eval(string, StrVec, Vec) -> floatevaluate an expression with named variables bound to values
exp(float) -> floate^x
fmt(float, int) -> stringfixed decimals: fmt(3.14159, 2) is "3.14"
fmt_g(float, int) -> stringprintf %.Ng (significant digits)
hypot(float, float) -> floatsqrt(x^2 + y^2) without overflow
inf() -> float+infinity
is_finite(float) -> boolx is neither NaN nor infinite
is_nan(float) -> boolx is NaN
log(float) -> floatnatural log
log10(float) -> floatbase-10 log
nan() -> floatquiet NaN
pad(string, int) -> stringleft-justify to a width (negative width right-justifies)
pi() -> floatπ
tan(float) -> floattangent

Reporting

The out context object collects named values and checks. The host returns them in one terminal invocation frame with JSON payload {"ok": true, "result": {"values": {...}, "checks": {...}}}; a failed check makes the run an application failure (exit 4) whose message names every failed check.

Type Out

Result collector (the context variable out).

MethodMeaning
check(string, bool) -> boolrecord a named check; returns the condition
close(string, float, float, float) -> boolcheck |got - want| <= tol (NaN fails)
close(string, Vec, Vec, float) -> boolcheck every |got[i] - want[i]| <= tol (lengths must match)
close_rel(string, float, float, float) -> boolcheck |got - want| <= rtol * max(|want|, 1e-300)
fail(string) -> voidstop now with an application failure (exit 4)
log(string) -> voidwrite a line to stderr (stdout is reserved for the JSON result)
put(string, float) -> voidrecord a float
put(string, int) -> voidrecord an int
put(string, string) -> voidrecord a string
put(string, bool) -> voidrecord a bool
put(string, Vec) -> voidrecord a vector (JSON array)
put(string, StrVec) -> voidrecord a list of strings
put(string, Mat) -> voidrecord a matrix (nested arrays)
put(string, Res) -> voidrecord a whole result object
put(string, Frame) -> voidrecord a table as {columns, rows, data}

Tables

Frame is a column table (pandas DataFrame subset): numeric columns are float64 with NaN for missing values; other columns are text. Expressions in filter/mutate see the numeric columns by name plus row (0-based index). Frames are immutable: every method returns a new frame.

Tables: functions

SignatureMeaning
csv(string) -> Frameparse CSV text (same rules as read_csv)
frame() -> Frameempty frame (add columns with with)
read_csv(string) -> Frameread a CSV file with a header row (a column is numeric when every cell parses; empty/NA/nan are NaN)
read_csv(string, Opts) -> Frameread_csv with options: sep (one char), header (bool), names (StrVec), text (StrVec: columns kept as text)

Type Frame

Column table.

MethodMeaning
cell(string, int) -> stringone cell as text (column, row)
col(string) -> Vecnumeric column as a vector
csv() -> stringthe frame as CSV text
drop(StrVec) -> Frameall columns except these
filter(string) -> Framerows where the expression is nonzero: f.filter("x > 0 & y < 3")
has(string) -> boolwhether a column exists
head(int) -> Framefirst n rows
is_missing(string, int) -> boolwhether a cell is missing (NaN, or an absent text value after a join)
is_numeric(string) -> boolwhether a column is numeric
json() -> string{columns, rows, data} JSON text
mutate(string, string) -> Framenew frame with column NAME = expression over numeric columns: f.mutate("bmi", "w / (h/100)^2")
names() -> StrVeccolumn names in order
ncols() -> intcolumn count
nrows() -> introw count
num(string, int) -> floatone numeric cell (column, row)
rename(string, string) -> Framerename one column
select(StrVec) -> Framethese columns, in this order
sort(string, bool) -> Framestable sort by one column (ascending when true; NaN last)
tail(int) -> Framelast n rows
take(Vec) -> Framerows at these indexes
text(string) -> StrVecany column as text (numbers formatted, NaN as empty)
to_mat(StrVec) -> Matnumeric columns as a matrix (rows x len(names))
where(string, string) -> Framerows whose column (as text) equals a value
with(string, Vec) -> Framenew frame with a numeric column added or replaced
with(string, StrVec) -> Framenew frame with a text column added or replaced
write_csv(string) -> voidwrite the frame as CSV (atomic replace)

Table operations

Grouping, joins, rolling windows, time resampling, reshaping and summaries (pycli frame_groupby, frame_merge, frame_rolling, frame_resample, frame_inspect). An aggregation spec is "col:agg|agg, col:agg"; result columns are named col__agg like pycli. Aggregations: sum, mean, count (non-missing), size (rows), min, max, std and var (ddof 1), median, first, last, nunique, prod.

Table operations: functions

SignatureMeaning
format_time(float) -> stringseconds since 1970 UTC as YYYY-MM-DD HH:MM:SS
parse_time(string) -> floatISO-8601 text as seconds since 1970 UTC

More methods of Frame

MethodMeaning
concat(Frame) -> Framerows of this frame then the other (same column names and kinds)
describe() -> Framesummary of the numeric columns: a stat column (count, mean, std, min, 25%, 50%, 75%, max) and one column each (pandas describe)
dropna() -> Framerows with no missing value in any column
dropna(StrVec) -> Framerows with no missing value in these columns
fillna(string, float) -> Framereplace NaN in a numeric column
groupby(StrVec, string) -> Framegroup by key columns and aggregate: f.groupby(strs("region"), "sales:sum|mean"); groups sorted, a missing key is its own group (pandas dropna=False)
groupby(StrVec, string, bool) -> Framegroupby; the bool drops rows whose key is missing (pandas dropna=True)
merge(Frame, StrVec, string) -> Framedatabase join on key columns, how = inner, left, right or outer (pandas.merge: outer is sorted by key; clashing names get _x/_y)
merge(Frame, StrVec, string, Opts) -> Framemerge with options: validate (one_to_one, one_to_many, many_to_one, many_to_many), indicator (bool: adds _merge = left_only/right_only/both), suffixes (StrVec of two)
pivot(string, string, string, string) -> Framepivot table (index column, columns column, values column, agg): one row per index value, one column per distinct columns value (sorted)
resample(string, string, string) -> Frametime bins over an ISO-8601 text (or epoch-seconds) column: rule 15min, 1h, 1D (bins from midnight of the first day, labelled left), W/W-DAY (weeks ending on DAY, labelled right), MS/ME, QS/QE, YS/YE; empty bins are kept (pandas resample)
rolling(string, int, string) -> Vectrailing window aggregate of a numeric column (pandas rolling: the first window-1 values are NaN)
rolling(string, int, string, Opts) -> Vecrolling with min_periods (int) and center (bool)
shift(string, int) -> Veca numeric column shifted by n rows (positive: later rows see earlier values; vacated cells NaN)
times(string) -> Vecan ISO-8601 text column as seconds since 1970-01-01 UTC (offsets applied)
unique(string) -> StrVecdistinct values of a column as text, in first-seen order (missing omitted)
value_counts(string) -> Frameframe {value (text), count} sorted by count descending, then value

More methods of Vec

MethodMeaning
rolling(int, string) -> Vectrailing window aggregate (same rules as Frame.rolling)

Array files

NumPy .npy and .safetensors arrays (pycli's artifact formats). Reads accept the dtypes pycli accepts (<f8 <f4 <i8 <i4 |u1 |b1; F64 F32 I64 I32 U8 BOOL), rank 1 or 2; writes are float64 and atomic.

Array files: functions

SignatureMeaning
mat_frame(Mat, StrVec) -> Framea matrix as a frame with these column names (pycli array_to_frame)
read_npy(string) -> Mata .npy file as a matrix (a rank-1 array becomes one column)
read_npy_vec(string) -> Veca rank-1 (or single-column) .npy file as a vector
read_safetensors(string, string) -> Matone tensor (file, key) as a matrix (rank 1 becomes one column)
read_safetensors_vec(string, string) -> Vecone rank-1 tensor (file, key) as a vector
read_text(string) -> stringread a whole text file
remove_file(string) -> booldelete a file; false when it did not exist
write_npy(string, Vec) -> voidwrite a vector as a rank-1 float64 .npy
write_npy(string, Mat) -> voidwrite a matrix as a rank-2 float64 .npy
write_safetensors(string, string, Vec) -> voidwrite a vector as one F64 tensor (file, key, data)
write_safetensors(string, string, Mat) -> voidwrite a matrix as one F64 tensor (file, key, data)
write_text(string, string) -> voidwrite a text file (atomic replace)

Linear algebra

Dense solves, least squares, matrix properties, decompositions and matrix functions on Mat (pycli la_solve, la_lstsq, la_props, la_decomp, la_matrix_fn; Eigen 3.4 underneath). A singular or ill-posed input is a run-time error, except lstsq, which reports status RANK_DEFICIENT.

More methods of Mat

MethodMeaning
cholesky() -> Matlower-triangular L with A = L L^T (must be symmetric positive definite)
cond() -> float2-norm condition number s_max / s_min
det() -> floatdeterminant
eig() -> Resgeneral eigenvalues: fields values_re, values_im (sorted by real part, then imaginary), real (bool: all imaginary parts 0)
eigh() -> Ressymmetric eigen-decomposition: fields values (ascending), vectors (columns), reconstruction_error
expm() -> Matmatrix exponential (Padé scaling and squaring)
inv() -> Matinverse (singular matrices are refused)
is_symmetric(float) -> boolmax |A - A^T| <= tol
logm() -> Matprincipal matrix logarithm (real result required)
lstsq(Vec) -> Resleast squares (SVD, numpy.linalg.lstsq): x, rank, singular_values, residues, residual_norm, status OK/RANK_DEFICIENT
lstsq(Vec, Opts) -> Resleast squares with rcond (relative singular-value cutoff; default eps * max(m, n))
lu() -> ResLU with partial pivoting A = P L U (scipy.linalg.lu): fields p, l, u
norm() -> floatFrobenius norm
norm(string) -> floatmatrix norm: fro, nuc, 1, -1, 2, -2, inf, -inf (numpy ord)
pinv() -> MatMoore-Penrose pseudo-inverse (cutoff eps * max(m, n) * s_max)
qr() -> Resreduced QR A = Q R (Householder): fields q, r, reconstruction_error
rank() -> intnumerical rank (SVD, tolerance s_max * max(m, n) * eps)
slogdet() -> Ressign and log|det| (numpy.linalg.slogdet): fields sign, logabsdet
solve(Vec) -> Vecx with A x = b (LU with partial pivoting; singular matrices are refused)
solve(Vec, string) -> Vecsolve with assume_a = gen, sym (exactly symmetric) or pos (Cholesky; must be positive definite)
solve(Mat) -> MatX with A X = B (several right-hand sides)
sqrtm() -> Matprincipal matrix square root (real result required)
svd() -> Resthin SVD A = U diag(s) Vt: fields u (Mat), s (Vec, descending), vt (Mat), reconstruction_error
trace() -> floatsum of the diagonal

Sparse matrices

Sparse is a compressed sparse matrix (pycli la_sparse). Build it from COO triplets (duplicates add up, like scipy) or entry by entry, then solve directly (solve, SuperLU-style sparse LU), iteratively (cg, gmres, bicgstab; options rtol, atol, maxiter, x0, gmres restart) or find eigenvalues of a symmetric matrix (eigsh, implicitly restarted Lanczos as in ARPACK).

Sparse matrices: functions

SignatureMeaning
sparse(int, int) -> Sparseempty rows x cols sparse matrix (fill with add)
sparse(Vec, Vec, Vec, int, int) -> Sparsefrom COO triplets (row indexes, column indexes, values, rows, cols); duplicates are summed
sparse(Mat) -> Sparsefrom a dense matrix (zeros dropped)
speye(int) -> Sparsen x n sparse identity
tridiag(int, float, float, float) -> Sparsen x n tridiagonal matrix with constant (lower, diagonal, upper) bands

Type Sparse

Sparse float64 matrix. Operator * multiplies by a Vec.

Operators: * → mul

MethodMeaning
add(int, int, float) -> Sparsein place: A[i, j] += x; returns the matrix
bicgstab(Vec, Opts) -> ResBiCGSTAB for general A: rtol, atol, maxiter, x0
cg(Vec) -> Resconjugate gradient for symmetric positive definite A: x, status, iterations, residual_norm, relative_residual
cg(Vec, Opts) -> Rescg with rtol (default 1e-5), atol, maxiter (default 10 n), x0
cols() -> intcolumn count
eigsh(int, Opts) -> Resk eigenvalues of a symmetric matrix (ARPACK-style Lanczos): which LA, SA, LM or SM (default LM), seed (start vector), ncv, tol, maxiter; fields w (ascending), vectors (Mat, columns), max_residual, nconv, status
gmres(Vec, Opts) -> Resrestarted GMRES: rtol, atol, restart (default 20), maxiter, x0
mul(Vec) -> Vecmatrix-vector product
nnz() -> intstored nonzeros (after summing duplicates)
rows() -> introw count
solve(Vec) -> Vecdirect sparse LU solve (scipy spsolve); singular matrices are refused
t() -> Sparsetranspose
to_dense() -> Matdense copy

Statistics

Probability distributions (pycli stats_dist, stats_dist_to), special functions (special_fn, special_fn_to), numpy-compatible random numbers and classical tests. Distributions follow scipy.stats 1.16 parameter names and formulas (each family is a port of its scipy class; special functions are scipy's own xsf/Cephes code or Boost.Math with scipy's policies). dist(name, opts) takes the scipy parameters plus loc (and scale for continuous families); pycli's names are accepted too: uniform low/high, gamma shape, lognorm mu/sigma (of the underlying normal), poisson lam. Families: norm, t, uniform, expon, gamma, beta, lognorm, chi2, genextreme, genpareto, skewnorm, johnsonsu, levy_stable (S1), nct, ncf, vonmises, truncnorm, weibull_min, cauchy, laplace, logistic, gumbel_r, pareto, rayleigh, f, poisson, binom, zipf, betabinom, nbinom, geom. Probabilities outside [0, 1] are errors; NaN inputs give NaN. Discrete ppf(0) and isf(1) are the first support point (pycli). Random variates reproduce numpy.random.Generator(PCG64(seed)) exactly for the numpy-sampled families (pycli's rvs; nct, skewnorm, betabinom and levy_stable use PCG64(seed) and its jumped() stream as pycli did); the quantile-sampled families (genextreme, genpareto, johnsonsu, truncnorm, weibull_min, cauchy, gumbel_r, pareto) use numpy's uniform stream through lmpy's quantile function. Deviations from scipy: Student t cdf/ppf use Boost (scipy: CDFLIB), Bessel/Airy outside [-10, 10] use Boost (scipy: AMOS), levy_stable integrates with Gauss-Kronrod (scipy: QUADPACK), Poisson ppf uses the generic discrete search.

Statistics: functions

SignatureMeaning
airy(float) -> ResAiry functions (scipy.special.airy): fields ai, aip, bi, bip
airy(Vec) -> ResAiry functions elementwise: Vec fields ai, aip, bi, bip
dist(string) -> Distdistribution with default parameters (families without shape parameters: norm, uniform, expon, cauchy, laplace, logistic, gumbel_r, rayleigh)
dist(string, Opts) -> Distdistribution with parameters (scipy names; unknown or missing ones are errors that list the valid ones)
dist_names() -> StrVecthe 31 distribution families
logsumexp(Vec) -> floatlog(sum(exp(v))) without overflow (scipy.special.logsumexp)
pearsonr(Vec, Vec) -> ResPearson correlation with the two-sided p-value of the exact beta null (scipy.stats.pearsonr): statistic, pvalue, df
rng(int) -> Rnggenerator seeded like numpy.random.default_rng(seed) (seed >= 0)
special(string, float) -> floatscipy.special function by name (pycli special_fn): name/arity: erf/1, erfc/1, erfcx/1, erfinv/1, erfcinv/1, expit/1, logit/1, log_expit/1, ndtr/1, log_ndtr/1, ndtri/1, ndtri_exp/1, ellipk/1, ellipe/1, gamma/1, gammaln/1, digamma/1, psi/1, zeta/1, lambertw/1, i0e/1, cosm1/1, gammainc/2, gammaincc/2, gammaincinv/2, gammainccinv/2, zeta/2, polygamma/2, lambertw/2, jv/2, yv/2, iv/2, kv/2, spherical_jn/2, struve/2, owens_t/2, boxcox/2, inv_boxcox/2, boxcox1p/2, inv_boxcox1p/2, xlogy/2, xlog1py/2, beta/2, betaln/2, poch/2, betainc/3, betaincc/3, betaincinv/3, betainccinv/3, hyp2f1/4. NaN outside the domain (pycli DOMAIN_ERROR), +-inf at poles (NON_FINITE)
special(string, Vec) -> Vecscipy.special function by name (pycli special_fn): elementwise
special(string, float, float) -> floatscipy.special function by name (pycli special_fn): two arguments
special(string, float, Vec) -> Vecscipy.special function by name (pycli special_fn): scalar first argument, vector second (e.g. jv(v, x))
special(string, Vec, float) -> Vecscipy.special function by name (pycli special_fn): vector first argument, scalar second (e.g. boxcox(x, lmbda))
special(string, Vec, Vec) -> Vecscipy.special function by name (pycli special_fn): two vectors of one length (length-1 vectors broadcast)
special(string, float, float, float) -> floatscipy.special function by name (pycli special_fn): three arguments (betainc family)
special(string, float, float, Vec) -> Vecscipy.special function by name (pycli special_fn): three arguments, vector last
special(string, Vec, Vec, Vec) -> Vecscipy.special function by name (pycli special_fn): three vectors
special(string, float, float, float, float) -> floatscipy.special function by name (pycli special_fn): four arguments (hyp2f1)
special(string, float, float, float, Vec) -> Vecscipy.special function by name (pycli special_fn): four arguments, vector last
special(string, Vec, Vec, Vec, Vec) -> Vecscipy.special function by name (pycli special_fn): four vectors
special_names() -> StrVecnames accepted by special()
ttest_1samp(Vec, float) -> Resone-sample t test against popmean (scipy.stats.ttest_1samp, two-sided): statistic, pvalue, df
ttest_ind(Vec, Vec) -> Restwo-sample t test with pooled variance (scipy.stats.ttest_ind, two-sided)
ttest_ind(Vec, Vec, Opts) -> Restwo-sample t test; option equal_var (default true; false = Welch)

Type Dist

A frozen probability distribution (dist("gamma", opts().set("a", 3.0).set("scale", 2.0))).

MethodMeaning
cdf(float) -> floatcumulative distribution function
cdf(Vec) -> Veccumulative distribution function (elementwise)
interval(float) -> Veccentral interval [ppf((1-c)/2), ppf((1+c)/2)] with confidence c in [0, 1]
is_discrete() -> booltrue for the discrete families
isf(float) -> floatinverse survival function; p must be in [0, 1]
isf(Vec) -> Vecinverse survival function; p must be in [0, 1] (elementwise)
logcdf(float) -> floatlog cdf
logcdf(Vec) -> Veclog cdf (elementwise)
logpdf(float) -> floatlog density (log mass for a discrete family)
logpdf(Vec) -> Veclog density (log mass for a discrete family) (elementwise)
logpmf(float) -> floatlog probability mass (discrete families only)
logpmf(Vec) -> Veclog probability mass, elementwise (discrete families only)
logsf(float) -> floatlog survival function
logsf(Vec) -> Veclog survival function (elementwise)
mean() -> floatmean (inf or NaN where undefined, as scipy)
median() -> floatmedian ppf(0.5)
moments() -> Respycli fn=moments: fields mean, var, skew, kurtosis (excess, as scipy), moments_undefined (names of the non-finite ones), status
name() -> stringfamily name
params() -> Resthe resolved parameters (scipy names, plus loc and scale)
pdf(float) -> floatdensity (the mass function for a discrete family, as pycli fn=pdf)
pdf(Vec) -> Vecdensity (the mass function for a discrete family, as pycli fn=pdf) (elementwise)
pmf(float) -> floatprobability mass (discrete families only)
pmf(Vec) -> Vecprobability mass, elementwise (discrete families only)
ppf(float) -> floatquantile function (inverse cdf); p must be in [0, 1]
ppf(Vec) -> Vecquantile function (inverse cdf); p must be in [0, 1] (elementwise)
rvs(int, int) -> Vecn random variates from seed (pycli fn=rvs; numpy Generator(PCG64(seed)); a shorter n is a prefix of a longer one)
sf(float) -> floatsurvival function 1 - cdf
sf(Vec) -> Vecsurvival function 1 - cdf (elementwise)
std() -> floatstandard deviation
support() -> Vec[lower, upper] end of the support
var() -> floatvariance

Type Rng

A numpy-compatible random generator: the stream of numpy.random.default_rng(seed) (PCG64 + SeedSequence). Methods advance it in place.

MethodMeaning
beta(int, float, float) -> Vecn beta variates (Generator.beta)
binomial(int, int, float) -> Vecn binomial counts with trials and p (Generator.binomial)
choice(Vec, int, bool) -> Vecn elements of a vector, with or without replacement (Generator.choice, shuffle=True)
exponential(int, float) -> Vecn exponential variates with the given scale (Generator.exponential)
gamma(int, float, float) -> Vecn gamma variates (shape, scale) (Generator.gamma)
integers(int, int, int) -> Vecn integers in [lo, hi) (Generator.integers, int64, Lemire's method)
jumped() -> Rngan independent generator: this state advanced by (phi - 1) * 2^128 draws (PCG64.jumped)
normal(int, float, float) -> Vecn normal variates with mean mu and standard deviation sd (Generator.normal)
permutation(int) -> Veca random permutation of 0..n-1 (Generator.permutation)
poisson(int, float) -> Vecn Poisson counts (Generator.poisson)
random(int) -> Vecn uniforms in [0, 1) (Generator.random)
shuffle(Vec) -> Veca shuffled copy of a vector (Generator.permutation of an array)
standard_normal(int) -> Vecn standard normal variates (Generator.standard_normal)
uniform(int, float, float) -> Vecn uniforms in [lo, hi) (Generator.uniform)

Optimisation, roots, quadrature and linear programming

Minimisation (minimize, scipy.optimize.minimize), nonlinear least squares (least_squares, scipy.optimize.least_squares with curve_fit covariances), bracketed and multivariate roots (root_scalar, root), adaptive quadrature (quad, QUADPACK) and LP/MILP (linprog, HiGHS). Objectives, models and equations are expression strings in pycli's grammar; the unknowns are named by a StrVec, and option keys starting with $ bind constants and data vectors (opts().set("$x", xs)). Numerical outcomes are a status (OK, NO_CONVERGENCE, EVAL_LIMIT, TIME_LIMIT, NON_FINITE, NUMERICAL_FAILURE, ...); bad input is a run-time error. Every expression evaluation counts against max_evals (default 500000) and the optional time_limit (seconds); a stopped run reports the best point so far.

Optimisation, roots, quadrature and linear programming: functions

SignatureMeaning
least_squares(string, string, StrVec, Vec, Opts) -> Resfit model(row) to the response data vector (pycli opt_least_squares): residual_i = (model - response_i) / sigma_i, every $ data vector read row by row; options: method (trf, dogbox, lm), loss (linear, soft_l1, huber, cauchy, arctan), f_scale, tol (ftol = xtol = gtol, default 1e-10), max_nfev (default 1000), lower/upper, absolute_sigma, max_evals, time_limit, $name bindings, sigma (float or Vec). Result: x, par, std_err, se, cov (curve_fit convention), cov_status, cost, rss, residuals, status, nfev, optimality, jacobian_condition
least_squares(StrVec, StrVec, Vec, Opts) -> Resminimise the sum of squared residual expressions (concatenated; one naming a data vector yields one residual per row, one with a reducer or none yields one); options: method (trf, dogbox, lm), loss (linear, soft_l1, huber, cauchy, arctan), f_scale, tol (ftol = xtol = gtol, default 1e-10), max_nfev (default 1000), lower/upper, absolute_sigma, max_evals, time_limit, $name bindings. Result as the model form
linprog(Vec) -> Resminimise c.x subject to x >= 0 (HiGHS; see the Opts form)
linprog(Vec, Opts) -> ResLP/MILP with HiGHS (pycli opt_linprog, scipy linprog method highs): options A_ub, b_ub, A_eq, b_eq (Mat/Vec), lower/upper (Vec; default 0 and +inf), integrality (Vec of 0/1), maximize, time_limit (default 10 s), node_limit, maxiter, mip_rel_gap. Result: x, fun (= objective), slack, con, status, message, nit, mip, ineqlin_marginals, eqlin_marginals, lower_marginals, upper_marginals, duals {ub, eq, lower, upper}, mip_gap, mip_node_count, primal_feasible, optimality_verified
minimize(string, StrVec, Vec) -> Resminimise an expression over the named unknowns from x0 (pycli opt_minimize, BFGS): x, par, fun, status, message, nit, nfev, njev, evals
minimize(string, StrVec, Vec, Opts) -> Resminimize with options: method (Nelder-Mead, Powell, BFGS, L-BFGS-B, SLSQP; default SLSQP with constraints, L-BFGS-B with bounds, else BFGS), tol, maxiter (default 1000), max_evals, time_limit, gradient (StrVec, one expression per unknown; checked against finite differences at x0), lower/upper (Vec; NaN or +-inf = open), eq/ineq (StrVec; ineq means expr >= 0; SLSQP), nonfinite (inf|error), $name bindings; result adds constraint_violation with constraints
quad(string, string, float, float) -> Resintegral of f(var) from a to b (pycli num_quad; QUADPACK QAGS, QAGI for inf()/-inf() limits): value, abserr, neval, subdivisions, status
quad(string, string, float, float, Opts) -> Resquad with options epsabs, epsrel (default 1.49e-8), limit (subintervals, default 50), points (Vec of break points, QAGP), max_evals, time_limit, $name bindings
root(StrVec, StrVec, Vec) -> Ressolve n equations = 0 in n named unknowns from x0 with MINPACK hybr (pycli opt_root); success is verified by max|f| <= residual_tol: x, par, fun, residual_norm, residual_max, nfev, status, evals
root(StrVec, StrVec, Vec, Opts) -> Resroot with options method (hybr, lm; brentq with bracket), bracket (Vec lower, upper: one equation, x0 ignored), xtol (default 1e-12), residual_tol (default 1e-8), maxiter (brentq only), max_evals, time_limit, $name bindings
root_scalar(string, string, float, float) -> Resbracketed root of f(var) on [lower, upper] with brentq (pycli num_root): root, f_root, iterations, function_calls, status, evals
root_scalar(string, string, float, float, Opts) -> Resroot_scalar with options method (brentq, bisect, ridder, toms748), xtol (default 2e-12), rtol (default 4 eps), maxiter (default 100), max_evals, time_limit, $name bindings

Ordinary differential equations

Initial value problems dy/dt = f(t, y) with expression right-hand sides (pycli ode_solve, ode_solve_to; scipy.integrate.solve_ivp). rhs[i] is the expression for d(state[i])/dt in the state names, t, y[i] and $-bound constants (opts().set("$beta", 0.3)). Methods RK45 (default), RK23, DOP853, Radau, BDF are ports of scipy's solvers (same step control, dense output and finite-difference Jacobian); LSODA is an automatic switch from RK45 to BDF when Hairer's stiffness test fires, not ODEPACK. Options (pycli names and defaults): method, rtol (1e-6), atol (1e-9, float or one per state), t_eval (ordered times; t0/t1 are added when missing) or max_output_points (101 uniform samples), max_step, first_step, events (StrVec of expressions whose zeros are located by brentq on the dense output), direction (Vec of -1/0/1), terminal (Vec: 0 = record only, k = stop at the k-th occurrence), max_events (32: a non-terminal event stops the run with EVENT_LIMIT at that count), max_evals (200000 expression evaluations), max_steps (10000 accepted steps). Result statuses: OK, STEP_SIZE_TOO_SMALL, NO_CONVERGENCE, EVAL_LIMIT, STEP_LIMIT, EVENT_LIMIT, NON_FINITE (a NaN/inf RHS or event value stops the run); a non-OK run keeps the samples computed so far and ends at the last accepted state.

Ordinary differential equations: functions

SignatureMeaning
ode(StrVec, StrVec, Vec, float, float) -> Ressolve an initial value problem ode(rhs, state, y0, t0, t1) with RK45 at rtol 1e-6, atol 1e-9 on 101 points; result: status, message, termination (end/event/failed), method, final_time, final_state, state_names, t (Vec), y (Mat: one row per time, one column per state), event_counts, event_t, event_y (Mat), event_index (grouped by event), nfev, njev, nlu, steps, rhs_calls, event_calls, evals, nonfinite_evals, success, partial_trajectory, effective_output_points, endpoints_added
ode(StrVec, StrVec, Vec, float, float, Opts) -> Ressolve an initial value problem with options (method, rtol, atol, t_eval, events, ... and $ constants); same result fields
ode_sol(StrVec, StrVec, Vec, float, float) -> OdeSollike ode, keeping the dense output for evaluation at any time inside the integrated range
ode_sol(StrVec, StrVec, Vec, float, float, Opts) -> OdeSollike ode with options, keeping the dense output (DOP853 then spends 3 extra RHS calls per step, as in scipy)

Type OdeSol

Dense ODE solution (solve_ivp dense_output): the piecewise interpolant of every accepted step plus the run's result.

MethodMeaning
eval(float) -> Vecstate vector at time t (t must lie in the integrated range)
eval(Vec) -> Matstates at several times: one row per time, one column per state
res() -> Resthe run's result (the fields of ode)
t_max() -> floatend of the integrated range (the terminal event time when one stopped the run)
t_min() -> floatstart of the integrated range

Interpolation

1-D interpolants and n-D radial basis functions (pycli interp_eval, interp_eval_to; scipy.interpolate). interp(kind, x, y[, opts]) builds an Interp once; evaluate, differentiate and integrate it as often as needed. Kinds: linear (make_interp_spline k=1), nearest (interp1d nearest), cubic (CubicSpline, option bc_type not-a-knot (default) / natural / clamped / periodic), pchip (monotone Fritsch-Carlson, PchipInterpolator), akima, makima (Akima1DInterpolator), smoothing (make_smoothing_spline; lam >= 0, omitted = generalised cross-validation; lam / h^3 is capped at 1e11 as in pycli), rbf (RBFInterpolator; kernel thin_plate_spline (default), linear, cubic, quintic, multiquadric, inverse_multiquadric, inverse_quadratic, gaussian; epsilon (1), smoothing (0), degree). x must be finite and strictly increasing (rbf: one row per node). Option extrapolate: error (default: a point outside the nodes is a run-time error), nan, or extend (the end polynomial; rbf: the nodes' bounding box is the range). At a node a piecewise interpolant takes its right-hand piece. An rbf whose system is singular or that misses its own nodes by more than 1e-6 of the data scale has status SINGULAR / ILL_CONDITIONED and cannot be evaluated.

Interpolation: functions

SignatureMeaning
interp(string, Vec, Vec) -> Interpbuild a 1-D interpolant of kind linear, nearest, cubic, pchip, akima, makima, smoothing or rbf (default options)
interp(string, Vec, Vec, Opts) -> Interpbuild a 1-D interpolant with options (bc_type, lam, kernel, epsilon, smoothing, degree, extrapolate)
interp(string, Mat, Vec) -> Interpbuild an n-D radial basis function interpolant (kind must be rbf; one row of x per node)
interp(string, Mat, Vec, Opts) -> Interpbuild an n-D radial basis function interpolant with options (kernel, epsilon, smoothing, degree, extrapolate)

Type Interp

Interpolant built by interp: piecewise polynomial (PPoly form) or radial basis function.

MethodMeaning
coeffs() -> MatPPoly coefficients: one row per power (highest first), one column per interval in the local variable x - knot (nearest/rbf: the rbf weights as one column, nearest: the node values)
deriv(float, int) -> floatderivative of order nu at x (0 = value; above the degree it is 0; right-hand value at a node)
deriv(Vec, int) -> Vecderivative of order nu at each x
eval(float) -> floatvalue at x
eval(Vec) -> Vecvalues at each x
eval(Mat) -> Vecrbf values at the points (one row per point)
info() -> Resfields: status, message, kind, n_nodes, extrapolate, bc_type (cubic), lam (smoothing: the given or GCV value), interpolation_error (rbf)
integrate(float, float) -> floatdefinite integral from a to b (negative when b < a; bounds in the node range unless extrapolate is extend)
knots() -> Vecbreakpoints of the piecewise polynomial (the nodes; rbf: empty)
status() -> stringOK, or SINGULAR / ILL_CONDITIONED for an rbf that could not be built

Signal processing

IIR filter design and filtering (iir -> Filter, pycli sig_filter), spectral estimates (periodogram, welch, csd, coherence, spectrogram; pycli sig_spectrum), peak finding (find_peaks, peak_prominences, peak_widths; pycli sig_peaks), FFT (pocketfft), windows, detrending, convolution and Savitzky-Golay smoothing. Ports of scipy.signal 1.16: the same zpk prototypes, bilinear transform and pole-zero pairing (zpk2sos, pairing nearest), the same padding in filtfilt (odd extension, scipy's default padlen) and the same find_peaks selection order. Frequencies are in Hz when fs is given, otherwise fractions of the Nyquist frequency (scipy's convention).

Signal processing: functions

SignatureMeaning
coherence(Vec, Vec, float) -> Resmagnitude-squared coherence |Pxy|^2 / (Pxx Pyy): fields f, cxy, df, n_segments, n_bins, peak_index, peak_freq
coherence(Vec, Vec, float, Opts) -> Rescoherence with window, nperseg, noverlap, nfft, detrend
convolve(Vec, Vec, string) -> Vecdiscrete linear convolution (numpy.convolve), mode full, same or valid
csd(Vec, Vec, float) -> Rescross spectral density (Welch): fields f, pxy_re, pxy_im, magnitude, df, n_segments, n_bins, peak_index, peak_freq
csd(Vec, Vec, float, Opts) -> Rescsd with the welch options
detrend(Vec, string) -> Vecremove the mean (constant) or the least-squares line (linear) (scipy.signal.detrend)
fft(Vec, Vec) -> Rescomplex FFT of re + i im (numpy.fft.fft): fields re, im
fftfreq(int, float) -> Vecsample frequencies of fft (numpy.fft.fftfreq)
fftshift(Vec) -> Vecmove the zero-frequency term to the centre (numpy.fft.fftshift)
filtfilt(Vec, Vec, Vec) -> Veczero-phase filtering with b/a (scipy filtfilt: odd extension, padlen 3*max(len(a), len(b)))
filtfilt(Vec, Vec, Vec, Opts) -> Vecfiltfilt with padtype (odd, even, constant, none) and padlen
find_peaks(Vec) -> Resall local maxima (scipy find_peaks, pycli sig_peaks): fields status (OK or NO_PEAKS), indices, n_peaks
find_peaks(Vec, Opts) -> Resfind_peaks with height, threshold, prominence, width, plateau_size (a minimum, or Vec (min, max), nan = open), distance, wlen, rel_height; adds scipy's properties for the options given: peak_heights, left/right_thresholds, prominences, left/right_bases, widths, width_heights, left/right_ips, plateau_sizes, left/right_edges
freqz(Vec, Vec, Vec) -> Resfrequency response of b/a at angular frequencies w (rad/sample): fields freqs, magnitude, phase
freqz(Vec, Vec, Vec, float) -> Resfrequency response of b/a at frequencies in Hz for sampling frequency fs
ifft(Vec, Vec) -> Resinverse complex FFT with 1/n scaling (numpy.fft.ifft): fields re, im
iir(string, int, float) -> Filterdesign a digital IIR filter (pycli sig_filter): kind butter, cheby1, cheby2, ellip, bessel; order 1..20; cutoff in Hz with fs, else a fraction of Nyquist; one cutoff = lowpass, two = bandpass by default
iir(string, int, Vec) -> Filteriir with one (low/high) or two (band) cutoff frequencies
iir(string, int, float, Opts) -> Filteriir with options: btype lowpass/highpass/bandpass/bandstop, fs (Hz), rp (dB, cheby1/ellip), rs (dB, cheby2/ellip), norm (bessel: phase (default), delay, mag)
iir(string, int, Vec, Opts) -> Filteriir with cutoff frequencies and options (see above)
irfft(Vec, Vec, int) -> Vecinverse of rfft with output length n (numpy.fft.irfft)
lfilter(Vec, Vec, Vec) -> Vecfilter x with transfer function b/a, zero initial state (scipy lfilter, direct form II transposed)
peak_prominences(Vec, Vec) -> Resprominence of each peak index (scipy peak_prominences): fields prominences, left_bases, right_bases
peak_prominences(Vec, Vec, Opts) -> Respeak_prominences with wlen (window length in samples)
peak_widths(Vec, Vec) -> Reswidth of each peak at half prominence (scipy peak_widths): fields widths, width_heights, left_ips, right_ips
peak_widths(Vec, Vec, Opts) -> Respeak_widths with rel_height (default 0.5) and wlen
periodogram(Vec, float) -> Resperiodogram (pycli sig_spectrum method periodogram; boxcar window, constant detrend, density): fields status, method, window, n_samples, n_segments, n_bins, df, f, pxx, total_power, enbw, peak_index, peak_freq
periodogram(Vec, float, Opts) -> Resperiodogram with window (name or Vec), nfft, detrend (constant, linear, none), return_onesided, scaling (density, spectrum)
rfft(Vec) -> Resreal-input FFT (numpy.fft.rfft): fields re, im (n/2+1 values)
rfft(Vec, int) -> Resrfft of x truncated or zero-padded to n
rfft_abs(Vec) -> Vecmagnitudes |rfft(x)|
rfftfreq(int, float) -> Vecsample frequencies of rfft for n samples spaced d apart (numpy.fft.rfftfreq)
savgol(Vec, int, int) -> VecSavitzky-Golay smoothing (scipy savgol_filter, mode interp): window_length, polyorder
savgol(Vec, int, int, Opts) -> Vecsavgol with deriv, delta, mode (interp, mirror, nearest, constant, wrap), cval
savgol_coeffs(int, int) -> VecSavitzky-Golay convolution coefficients (scipy savgol_coeffs)
sos_filter(Mat) -> Filtera Filter from given second-order sections (n x 6, a0 = 1 in column 3); frequencies as fractions of Nyquist
sos_filter(Mat, float) -> Filtera Filter from second-order sections with a sampling frequency fs (Hz)
spectrogram(Vec, float) -> Resspectrogram (scipy defaults: tukey 0.25 window, nperseg 256, noverlap nperseg/8, density): fields f, t, sxx (Mat, frequencies x times)
spectrogram(Vec, float, Opts) -> Resspectrogram with window, nperseg, noverlap, nfft, detrend, return_onesided, scaling
welch(Vec, float) -> ResWelch PSD (hann, nperseg 256 or the signal length, 50% overlap): same fields as periodogram
welch(Vec, float, Opts) -> ResWelch PSD with window, nperseg, noverlap, nfft, detrend, return_onesided, scaling, average (mean, median)
window(string, int) -> Vecperiodic window of length n as scipy get_window: hann, hamming, blackman, boxcar, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, cosine, triang, tukey (alpha 0.5)
window(string, int, Opts) -> Vecwindow with sym (bool, symmetric instead of periodic) and the shape parameter alpha (tukey), beta (kaiser) or std (gaussian)

Type Filter

Digital IIR filter in second-order sections (scipy iirfilter(..., output='sos')).

MethodMeaning
ba() -> Restransfer-function coefficients b, a (scipy zpk2tf; poorly conditioned for high orders: prefer sos)
filter(Vec) -> Veccausal filtering with zero initial state (scipy sosfilt)
filtfilt(Vec) -> Veczero-phase forward-backward filtering (scipy sosfiltfilt: odd extension, padlen 3*(2*n_sections+1-...))
filtfilt(Vec, Opts) -> Vecsosfiltfilt with options padtype (odd, even, constant, none) and padlen (int)
fs() -> floatsampling frequency (NaN when frequencies are fractions of Nyquist)
gain(float) -> float|H| at one frequency (Hz with fs, else a fraction of Nyquist)
info() -> Respycli sig_filter fields: status, family, order, btype, n_sections, sos, max_pole_radius, stable, marginal
marginal() -> boola pole within 1e-6 of the unit circle (rings for a very long time)
max_pole_radius() -> floatlargest pole modulus of the rounded sections (50-digit arithmetic, as pycli)
n_sections() -> intnumber of second-order sections
order() -> intfilter order as designed (for sos_filter: the number of nonzero denominator terms)
response(Vec) -> Resfrequency response at the given frequencies (Hz with fs, else fractions of Nyquist): fields freqs, magnitude, phase (radians)
sos() -> Matsecond-order sections (n_sections x 6: b0 b1 b2 a0 a1 a2)
stable() -> boolall poles strictly inside the unit circle (max_pole_radius < 1)
status() -> stringOK, or UNSTABLE (filter and filtfilt refuse an unstable filter)
zpk() -> Reszeros, poles and gain of the digital design: fields z_re, z_im, p_re, p_im, k (designed filters only)

Spatial

Nearest neighbours, distance matrices and convex hulls on point matrices whose rows are points (pycli spatial_knn, spatial_dist, spatial_hull; scipy.spatial semantics). Neighbour rows are ordered by distance and then by point index; indices are 0-based and returned as float matrices.

Spatial: functions

SignatureMeaning
cdist(Mat, Mat, string) -> Matdistance matrix between the rows of a and b (scipy cdist; pycli spatial_dist): euclidean, sqeuclidean, cityblock, chebyshev, minkowski, cosine, correlation, hamming, jaccard (non-zero is true), canberra, braycurtis, mahalanobis
cdist(Mat, Mat, string, Opts) -> Matcdist with options: p (minkowski), vi (Mat, mahalanobis inverse covariance, symmetric within 1e-12), allow_nan (undefined pairs become NaN instead of an error)
cdist(Mat, string) -> Matdistance matrix of the rows of a with themselves (symmetric, zero diagonal for a true metric)
hull(Mat) -> Resconvex hull of 2-D or 3-D points (scipy ConvexHull, Qhull Qt; pycli spatial_hull convex_hull): status OK/DEGENERATE, volume, area, vertices (Vec of indices; 2-D counter-clockwise from the lowest index), simplices (Mat: edges in 2-D, outward counter-clockwise triangles in 3-D), n_vertices, n_simplices, n_points, dim
knn(Mat, Mat, int) -> Resk nearest points of every query row, Euclidean (pycli spatial_knn): indices, distances (queries x k), status, n_points, n_queries, k, p, search
knn(Mat, Mat, int, Opts) -> Resknn with options: p (Minkowski norm in [1, 64] or inf(); default 2)
knn(Mat, int) -> Resk nearest points of every point among the points themselves (a point is its own nearest neighbour)
knn(Mat, int, Opts) -> Resself-query knn with options: p, exclude_self (drop each point from its own list)
knn_radius(Mat, Mat, float) -> Resall points within a distance (inclusive) of every query (pycli spatial_knn radius mode): counts per query, flat indices and distances (CSR layout), n_pairs
knn_radius(Mat, Mat, float, Opts) -> Resknn_radius with options: p, max_pairs (default 1000000; more is an error)
knn_radius(Mat, float, Opts) -> Resradius neighbours of every point among the points themselves; options p, max_pairs, exclude_self
pdist(Mat, string) -> Veccondensed pairwise distances (scipy pdist): d(0,1), d(0,2), ..., d(n-2,n-1)
pdist(Mat, string, Opts) -> Vecpdist with the cdist options

Graphs

Directed or undirected graphs with string node names, built edge by edge or from a frame's edge list; shortest paths (Dijkstra, Bellman-Ford, BFS hops, Yen's k shortest simple paths, all pairs) and flows (maximum flow, minimum cut, minimum-cost flow) with pycli's graph_paths / graph_flow result fields and statuses (OK, UNREACHABLE, NEGATIVE_CYCLE, INFEASIBLE, UNBALANCED, NUMERICAL_FAILURE). Node lists are sorted by name (numerically when every name is an integer). Parallel edges keep the smallest weight for paths and add capacities for flows.

Graphs: functions

SignatureMeaning
graph(bool) -> Graphempty graph (true: directed); add edges with edge
graph(Frame, string, string, bool) -> Graphgraph from an edge list frame (from column, to column, directed) with unit weights
graph(Frame, string, string, string, bool) -> Graphgraph from an edge list frame with a weight column (from, to, weight, directed)
graph(Frame, string, string, bool, Opts) -> Graphgraph from an edge list frame with options weight (column; default unit weights) and capacity (column, for flows)

Type Graph

Graph: nodes are strings; each edge has a weight (path length, or the unit cost for min_cost_flow) and an optional capacity.

MethodMeaning
all_distances() -> Resall-pairs Dijkstra distances (scipy csgraph): nodes (sorted), distance (Mat, NaN = unreachable), n_unreachable_pairs
all_distances(Opts) -> Resall pairs with method dijkstra, bellman_ford (Johnson; status NEGATIVE_CYCLE with cycle) or bfs
directed() -> boolwhether the graph is directed
distances(string) -> ResDijkstra distances from a source to every reachable node (pycli graph_paths without a target): nodes, distance, hops, predecessor ("" for the source), n_reachable, n_unreachable
distances(string, Opts) -> Resdistances with method dijkstra, bellman_ford or bfs
edge(string, string, float) -> Graphin place: add an edge u -> v (both ways when undirected) with a weight; returns the graph
edge(string, string, float, float) -> Graphin place: add an edge with a weight and a capacity (for flows); returns the graph
has_node(string) -> boolwhether a node exists
k_shortest(string, string, int) -> Resthe k shortest simple paths, shortest first (Yen; networkx shortest_simple_paths): k_found, paths (StrVec of comma-joined node names), lengths, hops; status UNREACHABLE when there is none
k_shortest(string, string, int, Opts) -> Resk_shortest with method dijkstra (weights) or bfs (edge counts)
max_flow(string, string) -> Resmaximum flow (Dinitz; pycli graph_flow max_flow): value, flow_from, flow_to, flow (edges with positive flow, sorted), n_flow_edges, integral, tolerance
min_cost_flow(string, string, float) -> Rescheapest way to send an integer amount from source to sink (edge weight = unit cost; integer capacities and costs): status OK/INFEASIBLE, cost, flow_from, flow_to, flow
min_cost_flow(StrVec, Vec) -> Resminimum-cost flow for node supplies (positive) and demands (negative); status UNBALANCED when they do not sum to zero
min_cut(string, string) -> Resminimum s-t cut (networkx minimum_cut partition): value, cut_from, cut_to, cut_capacity, n_cut_edges, source_side, source_side_size
n_edges() -> intedges as added (parallel edges and self loops included)
n_nodes() -> intnode count
node(string) -> Graphin place: add a node (no-op when present); returns the graph
nodes() -> StrVecnode names in sorted order
shortest_path(string, string) -> ResDijkstra shortest path (pycli graph_paths with a target): status OK/UNREACHABLE, path (StrVec), length, hops, n_reachable, n_unreachable, n_nodes, n_edges
shortest_path(string, string, Opts) -> Resshortest path with method dijkstra (non-negative weights), bellman_ford (negative weights; status NEGATIVE_CYCLE with cycle) or bfs (fewest edges; length = hops)

Statistical models

Regression models and time-series statistics after statsmodels 0.14 (pycli sm_ols, sm_glm, sm_arima, sm_tsa_acf, sm_tsa_tools). Model terms are strings: a numeric column x1, an interaction x1:x2, a categorical C(g) or C(g, ref) (treatment coding; the reference defaults to the first sorted level; columns are named g[T.level]; a text column is categorical without C), an expression I(x1^2) (pycli expression grammar over the numeric columns and $ scalar bindings), raw powers poly(x, 3) (named x, x^2, x^3), 1/const to place the intercept and 0/-1 to drop it. Results keep pycli's field names; undefined uncertainty (rank deficiency, no residual degrees of freedom) is NaN. Common options of ols/glm: cov_type (nonrobust, HC0-HC3, cluster with groups), use_t, alpha (interval level 1-alpha), na_action (error or drop), include (StrVec: fitted, residuals), intercept (bool).

Statistical models: functions

SignatureMeaning
acf(Vec, int) -> Ressample autocorrelation at lags 0..nlags (pycli sm_tsa_acf kind acf; statsmodels acf, divide by n): n, lags, values, ci_lower, ci_upper (Bartlett, 95%), status
acf(Vec, int, Opts) -> Resacf with options: adjusted (divide by n - k), alpha, qstat (adds Ljung-Box qstat and pvalues for lags 1..nlags), fft (accepted; sums are direct)
adfuller(Vec) -> Resaugmented Dickey-Fuller unit-root test (pycli sm_tsa_tools adfuller; constant, AIC lag choice): statistic, p_value (MacKinnon), used_lag, nobs, critical_values {1%, 5%, 10%}, icbest, maxlag
adfuller(Vec, Opts) -> Resadfuller with options: regression (c, ct, ctt, n), maxlag (int; default ceil(12 (n/100)^(1/4)) clipped), autolag (AIC, BIC, t-stat, none)
arima(Vec, int, int, int) -> ResARIMA(p, d, q) by exact maximum likelihood (pycli sm_arima; statsmodels SARIMAX state space): coefficients {names, estimate, std_err (opg), statistic, p_value, ci_lower, ci_upper}, params, param_names, bse, sigma2, llf, aic, bic, hqic, nobs_effective, residuals, converged, status (NaN = missing)
arima(Vec, int, int, int, Opts) -> ResARIMA with options: trend (n, c, t, ct; c is the regression intercept), seasonal_order (Vec [P, D, Q, s]), exog (Mat), exog_names, exog_future (Mat), forecast_steps (adds forecast {mean, lower, upper}), alpha, cov_type (opg, oim, approx, none), method (lbfgs/bfgs), maxiter (200), start_params (Vec, statsmodels order), enforce_stationarity, enforce_invertibility
glm(Frame, string, StrVec, string) -> ResGLM by IRLS (pycli sm_glm) with family gaussian, poisson, binomial, gamma, inverse_gaussian or negative_binomial and its default link: coefficients, deviance, null_deviance, pearson_chi2, scale, llf, aic, bic, df_model, df_resid, converged, n_iter, status
glm(Frame, string, StrVec, string, Opts) -> ResGLM with options: link, offset / exposure (columns; exposure needs the log link), var_weights (alias weights), freq_weights, nb_alpha (negative binomial dispersion, default 1), maxiter (100), tol (1e-8, absolute deviance change), cov_type, groups, use_t, alpha, na_action, include, intercept
glm(Frame, string, string, string) -> ResGLM with a +-joined right-hand side: glm(f, "count", "C(group)", "poisson")
glm(Frame, string, string, string, Opts) -> ResGLM with a +-joined right-hand side and options
kpss(Vec) -> ResKPSS stationarity test (pycli sm_tsa_tools kpss; level, automatic lags): statistic, p_value (table interpolation), p_value_bounded none/above/below, lags, critical_values {10%, 5%, 2.5%, 1%}
kpss(Vec, Opts) -> Reskpss with options: regression (c or ct), nlags ("auto", "legacy" or an int)
ljung_box(Vec, int) -> ResLjung-Box test of no autocorrelation for lags 1..m (pycli sm_tsa_tools ljung_box): lags, statistic, p_value, model_df
ljung_box(Vec, int, Opts) -> Resljung_box with options: model_df (fitted ARMA parameters; lags model_df+1..m are tested against chi2(lag - model_df)), boxpierce (adds bp_statistic, bp_p_value)
ljung_box(Vec, Vec) -> Resljung_box at an explicit strictly increasing list of lags
ljung_box(Vec, Vec, Opts) -> Resljung_box at explicit lags with options (model_df, boxpierce)
ols(Frame, string, StrVec) -> ResOLS of column y on the terms (pycli sm_ols): coefficients {names, estimate, std_err, statistic, p_value, ci_lower, ci_upper}, n_obs, r2, r2_adj, sigma, f_statistic, f_p_value, llf, aic, bic, ssr, df_model, df_resid, rank, condition_number, durbin_watson, jarque_bera, omnibus, skew, kurtosis, coding, status
ols(Frame, string, StrVec, Opts) -> ResOLS/WLS with options: weights (column: WLS), cov_type, groups (cluster column), use_t, alpha, na_action, include, intercept
ols(Frame, string, string) -> ResOLS with the terms written as one right-hand side joined by +: ols(f, "y", "x1 + x2 + C(g, a) + x1:x2")
ols(Frame, string, string, Opts) -> ResOLS/WLS with a +-joined right-hand side and options
pacf(Vec, int) -> Respartial autocorrelation at lags 0..nlags by Yule-Walker with n denominator (pycli sm_tsa_acf kind pacf, method ywm = R's pacf): values, ci_lower, ci_upper (+-z/sqrt(n))
pacf(Vec, int, Opts) -> Respacf with options: method (ywm, ywadjusted, ols, ols-inefficient, ols-adjusted, ldadjusted, ldb), alpha; nlags < n/2

Machine learning

scikit-learn 1.7.2 subset (pycli ml_fit, ml_predict, ml_cv, ml_metrics). ml_fit(kind, x, y) fits a supervised Estimator (kinds linear, ridge, lasso, elastic_net, logistic, linear_svc, gaussian_nb, lda, knn_classifier, knn_regressor; classes are the sorted distinct y values) and ml_fit(kind, x) an unsupervised one (kmeans, pca, standard_scaler). Hyperparameters use pycli's ml-spec names and defaults (alpha, l1_ratio, C, tol, max_iter, class_weight, var_smoothing, n_components, n_neighbors, weights, n_clusters, n_init, init, seed, whiten, fit_intercept) plus scale (pycli preprocess.scale). Estimator status is OK, RANK_DEFICIENT (linear) or NO_CONVERGENCE. Random forests and gradient boosting are not supported. k-means and shuffled CV draw from numpy's RandomState(seed) (MT19937), as sklearn does.

Machine learning: functions

SignatureMeaning
adjusted_rand_score(Vec, Vec) -> floatadjusted Rand index of two labelings (sklearn.metrics.adjusted_rand_score; 1 = same partition)
kmeans(Mat, int) -> Estimatork-means with k clusters (sklearn KMeans, Lloyd, k-means++, n_init 10, seed 0)
kmeans(Mat, int, Opts) -> Estimatork-means with options seed, n_init, max_iter, tol, init
label_encode(StrVec) -> Restext labels to codes (sklearn LabelEncoder): fields codes (Vec, 0-based index into classes), classes (sorted StrVec)
load_model(string) -> Estimatorread a model written by Estimator.save (JSON, format lmpy_model 1)
ml_cv(string, Mat, Vec, int) -> Resk-fold cross-validation (pycli ml_cv): stratified for classifiers (accuracy), kfold for regressors (r2), no shuffle
ml_cv(string, Mat, Vec, int, Opts) -> Rescross-validation with options cv (kfold|stratified|group|timeseries), shuffle, seed, groups (Vec), metrics (StrVec: accuracy, f1_macro, roc_auc, log_loss | mse, mae, r2), scoring, and the kind's hyperparameters and scale. Result: status, scores, mean, std (scoring metric), metric_scores/metric_mean/metric_std (per metric), train_rows, test_rows, test_fold, completed_folds
ml_fit(string, Mat, Vec) -> Estimatorfit a supervised model (pycli ml_fit): kind, features x (rows x p), target y (class labels or values)
ml_fit(string, Mat, Vec, Opts) -> Estimatorfit a supervised model with hyperparameters and scale (standardise features first; learned from the training rows)
ml_fit(string, Mat) -> Estimatorfit an unsupervised model: kmeans (2 clusters), pca (2 components) or standard_scaler
ml_fit(string, Mat, Opts) -> Estimatorfit an unsupervised model with options: kmeans n_clusters, n_init (10), max_iter (300), tol (1e-8), init (k-means++|random), seed (0); pca n_components, whiten
ml_metrics(Vec, Vec) -> Resmetrics of predictions (pycli ml_metrics): classification (integral labels, <= 30) gives accuracy, balanced_accuracy, precision, recall, f1, confusion_matrix, labels; otherwise r2, mse, rmse, mae. status OK or UNDEFINED (see undefined)
ml_metrics(Vec, Vec, Opts) -> Resmetrics with options metrics (StrVec), kind (auto|classification|regression), average (binary|macro|micro|weighted), pos_label, zero_division (undefined|0|1), y_score (Vec: roc_auc, log_loss, brier)
ml_metrics(Vec, Opts) -> Resmetrics from y_true and options only (y_pred and/or y_score given as options)

Type Estimator

A fitted scikit-learn-style model: predict, predict_proba, decision_function, transform, score, params, save.

MethodMeaning
centers() -> Matk-means cluster centres (one row per cluster)
classes() -> Vecsorted class labels (classifiers)
coef() -> Matcoefficients as a matrix: one row per decision function (regressors and binary classifiers: 1 row)
decision_function(Mat) -> Matdecision scores (logistic, linear_svc, lda); binary models give one column, positive for classes()[1]
inertia() -> floatk-means within-cluster sum of squared distances
intercept() -> Vecintercepts, one per decision function (regressors: one value)
json() -> stringthe model file text (JSON)
kind() -> stringthe family (linear, logistic, kmeans, ...)
labels() -> Veck-means cluster index of every training row
n_iter() -> intiterations used (lasso/elastic_net epochs, logistic/linear_svc Newton steps, k-means Lloyd iterations of the best run)
ok() -> boolstatus is OK
params() -> Resfitted attributes (sklearn names without the trailing underscore): coef, intercept, classes, rank, theta, var, means, priors, scalings, cluster_centers, inertia, labels, components, mean, explained_variance(_ratio), singular_values, scale, n_iter ...
predict(Mat) -> Vecpredictions: class labels, regression values or cluster indexes (pycli ml_predict kind predict)
predict_proba(Mat) -> Matclass probabilities, one column per class in classes() order (logistic, gaussian_nb, lda, knn_classifier)
save(string) -> voidwrite the model as JSON (atomic replace); load_model reads it back with identical predictions
score(Mat, Vec) -> floataccuracy (classifiers) or R^2 (regressors) on x, y
status() -> stringOK, RANK_DEFICIENT (linear: minimum-norm solution kept) or NO_CONVERGENCE
task() -> stringregression, classification, clustering, decomposition or scaling
transform(Mat) -> Matstandard_scaler: standardised x; pca: component scores; lda: discriminant axes; kmeans: distances to the centres

Expression grammar

Objectives, models, right-hand sides, filters and mutations are expression strings parsed by the host's closed grammar, defined in expr-spec.json in the repository. They are not LMScript and cannot call host functions.

ItemValues
Operators+ - * / ^ < <= > >= == != & |
Precedence, lowest to highest|; &; < <= > >= == !=; + -; * /; unary -; ^
Constantspi, e
Functions of one argumentexp, log, log1p, expm1, log2, log10, sqrt, abs, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, floor, ceiling, trunc, round, sign, gamma, lgamma, digamma, pnorm, dnorm, qnorm, plogis
Functions of two argumentsatan2, pmin, pmax, beta, lbeta, choose, lchoose
Functions of three argumentsifelse
Reducers over a data vectorsum, mean, prod, min, max
Reserved nameslist
BindingsOption keys that start with $ bind a scalar or a data vector for the expressions of that operation; a bound vector x is read as x[i] or through a reducer.

Standard catalog lmcode_std_v3 as shipped

lmpy 0.1.46 vendors the lmcode-cpp runtime at the commit pinned in native/sdk.lock. Its standard catalog is named lmcode_std_v3 and has 206 canonical signatures: 83 function signatures and 123 methods on 16 types. The runtime installs them and lmscript declares them, so they are callable in every lmpy block although the lmpy schema lists only host members. The tables below are read from the vendored native/cpp/std/lmcode-std.schema.json.

Strings

FunctionSignatures
str_containsstr_contains(string, string) -> bool
str_ends_withstr_ends_with(string, string) -> bool
str_findstr_find(string, string) -> int
str_is_floatstr_is_float(string) -> bool
str_is_intstr_is_int(string) -> bool
str_lenstr_len(string) -> int
str_lowerstr_lower(string) -> string
str_matchstr_match(string, string) -> bool
str_repeatstr_repeat(string, int) -> string
str_replacestr_replace(string, string, string) -> string
str_splitstr_split(string, string) -> StrList
str_starts_withstr_starts_with(string, string) -> bool
str_substrstr_substr(string, int, int) -> string
str_to_floatstr_to_float(string) -> float
str_to_intstr_to_int(string) -> int
str_trimstr_trim(string) -> string
str_upperstr_upper(string) -> string

Encoding and templates

FunctionSignatures
str_base64_decodestr_base64_decode(string) -> string
str_base64_encodestr_base64_encode(string) -> string
str_hex_decodestr_hex_decode(string) -> string
str_hex_encodestr_hex_encode(string) -> string
template_rendertemplate_render(string, Json) -> string

Math

FunctionSignatures
math_absmath_abs(int) -> int; math_abs(float) -> float
math_ceilmath_ceil(int) -> int; math_ceil(float) -> float
math_floormath_floor(int) -> int; math_floor(float) -> float
math_maxmath_max(int, int) -> int; math_max(float, float) -> float
math_minmath_min(int, int) -> int; math_min(float, float) -> float
math_powmath_pow(int, int) -> int; math_pow(float, float) -> float
math_roundmath_round(int) -> int; math_round(float) -> float
math_sqrtmath_sqrt(int) -> int; math_sqrt(float) -> float

Files

FunctionSignatures
file_appendfile_append(string, string) -> void
file_existsfile_exists(string) -> bool
file_linesfile_lines(string) -> StrList
file_readfile_read(string) -> string
file_writefile_write(string, string) -> void

Collection constructors and JSON

FunctionSignatures
float_listfloat_list() -> FloatList
float_mapfloat_map() -> FloatMap
float_pqfloat_pq() -> FloatPQ
float_queuefloat_queue() -> FloatQueue
float_stackfloat_stack() -> FloatStack
int_listint_list() -> IntList
int_mapint_map() -> IntMap
int_pqint_pq() -> IntPQ
int_queueint_queue() -> IntQueue
int_stackint_stack() -> IntStack
json_parsejson_parse(string) -> Json
str_liststr_list() -> StrList
str_mapstr_map() -> StrMap
str_pqstr_pq() -> StrPQ
str_queuestr_queue() -> StrQueue
str_stackstr_stack() -> StrStack

Result helpers

FunctionSignatures
lmcode_return_nulllmcode_return_null() -> void
lmcode_return_putlmcode_return_put(string, bool) -> void; lmcode_return_put(string, float) -> void; lmcode_return_put(string, FloatList) -> void; lmcode_return_put(string, FloatMap) -> void; lmcode_return_put(string, int) -> void; lmcode_return_put(string, IntList) -> void; lmcode_return_put(string, IntMap) -> void; lmcode_return_put(string, Json) -> void; lmcode_return_put(string, StrList) -> void; lmcode_return_put(string, StrMap) -> void; lmcode_return_put(string, string) -> void
lmcode_return_put_nulllmcode_return_put_null(string) -> void
lmcode_return_setlmcode_return_set(bool) -> void; lmcode_return_set(float) -> void; lmcode_return_set(FloatList) -> void; lmcode_return_set(FloatMap) -> void; lmcode_return_set(int) -> void; lmcode_return_set(IntList) -> void; lmcode_return_set(IntMap) -> void; lmcode_return_set(Json) -> void; lmcode_return_set(StrList) -> void; lmcode_return_set(StrMap) -> void; lmcode_return_set(string) -> void

Standard types and methods

TypeMethods
FloatListadd(float) -> FloatList; at(int) -> float; clear() -> FloatList; contains(float) -> bool; index_of(float) -> int; len() -> int; set(int, float) -> FloatList
FloatMaplen() -> int; has(string) -> bool; get(string) -> float; get_or(string, float) -> float; set(string, float) -> FloatMap; key_at(int) -> string; remove(string) -> bool; clear() -> FloatMap; keys() -> StrList; values() -> FloatList
FloatPQpush(float, float) -> FloatPQ; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatPQ
FloatQueuepush(float) -> FloatQueue; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatQueue; at(int) -> float
FloatStackpush(float) -> FloatStack; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatStack; at(int) -> float
IntListadd(int) -> IntList; at(int) -> int; clear() -> IntList; contains(int) -> bool; index_of(int) -> int; len() -> int; set(int, int) -> IntList
IntMaplen() -> int; has(string) -> bool; get(string) -> int; get_or(string, int) -> int; set(string, int) -> IntMap; key_at(int) -> string; remove(string) -> bool; clear() -> IntMap; keys() -> StrList; values() -> IntList
IntPQpush(int, float) -> IntPQ; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntPQ
IntQueuepush(int) -> IntQueue; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntQueue; at(int) -> int
IntStackpush(int) -> IntStack; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntStack; at(int) -> int
Jsonkind() -> string; len() -> int; at(int) -> Json; get(string) -> Json; has(string) -> bool; keys() -> StrList; as_string() -> string; as_int() -> int; as_float() -> float; as_bool() -> bool; to_json() -> string
StrListadd(string) -> StrList; at(int) -> string; clear() -> StrList; contains(string) -> bool; index_of(string) -> int; join(string) -> string; len() -> int; set(int, string) -> StrList
StrMapclear() -> StrMap; get(string) -> string; get_or(string, string) -> string; has(string) -> bool; key_at(int) -> string; len() -> int; remove(string) -> bool; set(string, string) -> StrMap; keys() -> StrList; values() -> StrList
StrPQpush(string, float) -> StrPQ; pop() -> string; peek() -> string; len() -> int; empty() -> bool; clear() -> StrPQ
StrQueuepush(string) -> StrQueue; pop() -> string; peek() -> string; len() -> int; empty() -> bool; clear() -> StrQueue; at(int) -> string
StrStackpush(string) -> StrStack; pop() -> string; peek() -> string; len() -> int; empty() -> bool; clear() -> StrStack; at(int) -> string

Standard REST and CLI interfaces

The current lmcode_std_v3 catalog in lmcode-cpp has 226 canonical signatures. The 20 additional signatures are the former lmcode_std_rest_v1 module: five functions and 15 RestExchange methods, together with 10 standard interfaces. lmpy 0.1.46 does not ship them: its vendored catalog is the 206-signature one above, and lmpy --lmcode-signatures lists no rest_ function and no RestExchange method. lmpy picks them up when it syncs the lmcode-cpp runtime and publishes a release. They are listed here so a program can be planned against the catalog; do not call them in a block that targets lmpy 0.1.46.

Interfaces

InterfaceSignature
CliCommand(exchange: RestExchange) -> void
CliOption(exchange: RestExchange) -> void
RestDelete(exchange: RestExchange) -> void
RestGet(exchange: RestExchange) -> void
RestHandler(exchange: RestExchange) -> void
RestHead(exchange: RestExchange) -> void
RestOptions(exchange: RestExchange) -> void
RestPatch(exchange: RestExchange) -> void
RestPost(exchange: RestExchange) -> void
RestPut(exchange: RestExchange) -> void

Functions

FunctionSignature
rest_configrest_config(string, string) -> void
rest_routerest_route(string, string, string) -> void
rest_serverest_serve() -> void
rest_stoprest_stop() -> void
rest_clirest_cli(StrList) -> string

Route templates accept {param} and {rest...} placeholders as well as :param and :rest... placeholders.

RestExchange methods

MethodSignature
methodmethod() -> string
pathpath() -> string
queryquery(string) -> string
has_queryhas_query(string) -> bool
paramparam(string) -> string
headerheader(string) -> string
has_headerhas_header(string) -> bool
bodybody() -> string
statusstatus(int) -> void
set_headerset_header(string, string) -> void
sendsend(string) -> void
jsonjson(string) -> void
getget(string) -> string
setset(string, string) -> void
incrementincrement(string) -> int