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
| Command | Result |
| 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-schema | Prints the plain-text API summary: the context line, then functions and types with their signatures. |
| lmpy --lmcode-schema --json | Prints 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-signatures | Prints 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-md | Prints the generated API reference as Markdown. |
| lmpy --version | Prints the release identity in the form lmpy X.Y.Z. |
| lmpy --help, lmpy -h | Prints the usage text and exits 0. |
Exit codes
| Code | Meaning | Frame phase |
| 0 | Success. | none (ok is true) |
| 2 | Usage error: missing or invalid arguments, invalid invocation metadata. LMScript compile errors in the calling program also exit 2, from lmscript. | cli |
| 3 | Load or run-time error: unreadable or mismatched bytecode, or a failing host call such as a singular matrix. | load or run |
| 4 | Application 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.
| Field | Present when | Meaning |
| ok | always | true on success, false on any failure. |
| result | ok is true | By 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.failures | default result | Counts of passed and failed checks and the list of failures, each with name and detail. |
| phase | ok is false | cli, load, run or app. |
| code | ok is false | An error code such as CLI_USAGE, LOAD_BAD_BYTECODE, LOAD_SCHEMA_MISMATCH, LOAD_UNBOUND, RUN_HOST, RUN_ERROR or APP_FAIL. |
| message | ok is false | The diagnostic. Run-time messages start with dsl line N:C and name the operation. |
| line, column | run-time errors with a source position | The position inside the lmcode block. |
Block declaration and runner
| Form | Meaning |
| 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
| Name | Type | Meaning |
| out | Out | values 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
| Signature | Meaning |
| arange(float, float, float) -> Vec | start, start+step, ... below stop (numpy.arange) |
| arange(int) -> Vec | 0, 1, ..., n-1 as floats |
| concat(Vec, Vec) -> Vec | concatenation |
| full(int, float) -> Vec | n copies of a value |
| linspace(float, float, int) -> Vec | n evenly spaced values from start to stop inclusive (numpy.linspace) |
| ones(int) -> Vec | n ones |
| vec() -> Vec | empty vector |
| vec(float) -> Vec | one-element vector |
| vec(float, float) -> Vec | two-element vector |
| vec(float, float, float) -> Vec | three-element vector |
| vec(float, float, float, float) -> Vec | four-element vector |
| vec(float, float, float, float, float) -> Vec | 5-element vector |
| vec(float, float, float, float, float, float) -> Vec | 6-element vector |
| vec(float, float, float, float, float, float, float) -> Vec | 7-element vector |
| vec(float, float, float, float, float, float, float, float) -> Vec | 8-element vector |
| vec(string) -> Vec | parse numbers separated by spaces/commas (brackets allowed, nan accepted): vec("1 2.5 -3") |
| zeros(int) -> Vec | n 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
| Method | Meaning |
| abs() -> Vec | elementwise absolute value |
| add(Vec) -> Vec | elementwise sum |
| add(float) -> Vec | add a scalar |
| all_finite() -> bool | true when no element is NaN or infinite |
| apply(string) -> Vec | evaluate an expression in x for each element: v.apply("exp(-x^2/2)") |
| apply(string, string, Vec) -> Vec | evaluate an expression in x and a second named vector elementwise: x.apply("x*w", "w", w) |
| argmax() -> int | index of the first maximum |
| argmin() -> int | index of the first minimum |
| argsort() -> Vec | indexes that sort ascending (stable) |
| at(int) -> float | element i (negative counts from the end) |
| ceil() -> Vec | elementwise ceiling |
| clip(float, float) -> Vec | clamp each element to [lo, hi] |
| copy() -> Vec | independent copy |
| cos() -> Vec | elementwise cosine |
| count() -> int | number of nonzero, non-NaN entries (count of a mask) |
| cumsum() -> Vec | cumulative sum |
| diff() -> Vec | first differences x[i+1]-x[i] |
| div(Vec) -> Vec | elementwise quotient (IEEE: x/0 is inf or nan) |
| div(float) -> Vec | divide by a scalar |
| dot(Vec) -> float | inner product |
| eq(float) -> Vec | mask (1.0/0.0) of x == c |
| eq(Vec) -> Vec | elementwise mask of x == y |
| exp() -> Vec | elementwise exponential |
| extend(Vec) -> Vec | in place: append another vector; returns the vector |
| find() -> Vec | indexes of the nonzero, non-NaN entries (numpy.flatnonzero of a mask) |
| floor() -> Vec | elementwise floor |
| fmt(int) -> string | space-separated values with fixed decimals |
| ge(float) -> Vec | mask (1.0/0.0) of x >= c |
| ge(Vec) -> Vec | elementwise mask of x >= y |
| gt(float) -> Vec | mask (1.0/0.0) of x > c |
| gt(Vec) -> Vec | elementwise mask of x > y |
| isnan() -> Vec | elementwise 1.0 where NaN, else 0.0 |
| json() -> string | JSON array text |
| le(float) -> Vec | mask (1.0/0.0) of x <= c |
| le(Vec) -> Vec | elementwise mask of x <= y |
| len() -> int | length |
| log() -> Vec | elementwise natural logarithm |
| log10() -> Vec | elementwise base-10 logarithm |
| log1p() -> Vec | elementwise log(1 + x) |
| lt(float) -> Vec | mask (1.0/0.0) of x < c |
| lt(Vec) -> Vec | elementwise mask of x < y |
| max() -> float | maximum (NaN if any NaN) |
| mean() -> float | arithmetic mean |
| median() -> float | median |
| min() -> float | minimum (NaN if any NaN) |
| mul(Vec) -> Vec | elementwise product |
| mul(float) -> Vec | scale by a scalar |
| ne(float) -> Vec | mask (1.0/0.0) of x != c |
| ne(Vec) -> Vec | elementwise mask of x != y |
| neg() -> Vec | negation |
| norm() -> float | Euclidean norm |
| pow(float) -> Vec | elementwise power |
| prod() -> float | product |
| push(float) -> Vec | in place: append x; returns the vector |
| quantile(float) -> float | quantile q in [0,1], linear interpolation (numpy default) |
| reverse() -> Vec | reversed copy |
| round() -> Vec | elementwise round half to even (numpy.round) |
| rsub(float) -> Vec | scalar minus each element |
| set(int, float) -> Vec | in place: element i = x; returns the vector |
| sin() -> Vec | elementwise sine |
| slice(int, int) -> Vec | elements [start, stop) (numpy slicing; negative indexes count from the end, out-of-range clamps) |
| sort() -> Vec | ascending copy (NaN last) |
| sqrt() -> Vec | elementwise square root |
| square() -> Vec | elementwise x*x |
| std(int) -> float | standard deviation with ddof |
| sub(Vec) -> Vec | elementwise difference |
| sub(float) -> Vec | subtract a scalar |
| sum() -> float | sum (compensated) |
| take(Vec) -> Vec | elements at the given (float, integral) indexes |
| tanh() -> Vec | elementwise hyperbolic tangent |
| unique() -> Vec | sorted distinct values |
| var(int) -> float | variance with ddof (0 population, 1 sample) |
| where(Vec) -> Vec | elements 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
| Signature | Meaning |
| split(string, string) -> StrVec | split text on a separator (no trimming) |
| strs() -> StrVec | empty list |
| strs(string) -> StrVec | comma-separated names, trimmed: strs("x1, x2") |
| strs(int, string) -> StrVec | n copies of one string (a label column) |
Type StrVec
List of strings.
| Method | Meaning |
| at(int) -> string | element i |
| contains(string) -> bool | membership |
| index(string) -> int | first position or -1 |
| join(string) -> string | join with a separator |
| json() -> string | JSON array text |
| len() -> int | length |
| push(string) -> StrVec | in 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
| Signature | Meaning |
| cols(Vec) -> Mat | one-column matrix |
| cols(Vec, Vec) -> Mat | column_stack of two vectors |
| cols(Vec, Vec, Vec) -> Mat | column_stack of three vectors |
| cols(Vec, Vec, Vec, Vec) -> Mat | column_stack of four vectors |
| diag(Vec) -> Mat | diagonal matrix |
| eye(int) -> Mat | n x n identity |
| mat(int, int) -> Mat | rows x cols zeros |
| mat(Vec, int, int) -> Mat | reshape a vector, row-major, to rows x cols |
| mat(string) -> Mat | parse 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
| Method | Meaning |
| add(Mat) -> Mat | elementwise sum |
| add_col(Vec) -> Mat | new matrix with the vector appended as a last column |
| at(int, int) -> float | element (i, j) |
| block(int, int, int, int) -> Mat | sub-matrix (row, col, nrows, ncols) |
| col(int) -> Vec | column j |
| col_means() -> Vec | mean of each column |
| col_sums() -> Vec | sum of each column |
| cols() -> int | column count |
| flatten() -> Vec | row-major values |
| hadamard(Mat) -> Mat | elementwise product |
| hstack(Mat) -> Mat | columns of this then other |
| json() -> string | nested JSON arrays, row-major |
| max_abs_diff(Mat) -> float | max |a - b| (shapes must match) |
| mul(Mat) -> Mat | matrix product (numpy @) |
| mul(Vec) -> Vec | matrix-vector product |
| mul(float) -> Mat | scale |
| neg() -> Mat | negation |
| row(int) -> Vec | row i |
| row_sums() -> Vec | sum of each row |
| rows() -> int | row count |
| set(int, int, float) -> Mat | in place: element (i, j) = x; returns the matrix |
| sub(Mat) -> Mat | elementwise difference |
| sum() -> float | sum of all elements |
| t() -> Mat | transpose |
| take_rows(Vec) -> Mat | rows at the given indexes |
| vstack(Mat) -> Mat | rows of this then other |
| with_intercept() -> Mat | new 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
| Signature | Meaning |
| opts() -> Opts | empty options |
Type Opts
Named options builder: opts().set("method", "BFGS").set("tol", 1e-8).
| Method | Meaning |
| has(string) -> bool | whether a key is set |
| set(string, float) -> Opts | in place: float option |
| set(string, int) -> Opts | in place: int option |
| set(string, string) -> Opts | in place: string option |
| set(string, bool) -> Opts | in place: bool option |
| set(string, Vec) -> Opts | in place: vector option |
| set(string, StrVec) -> Opts | in place: name-list option |
| set(string, Mat) -> Opts | in 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.
| Method | Meaning |
| flag(string) -> bool | bool field |
| has(string) -> bool | whether a field exists |
| int(string) -> int | int field |
| json() -> string | the whole result as JSON text |
| keys() -> StrVec | field names in order |
| mat(string) -> Mat | matrix field |
| num(string) -> float | float field (an int field widens) |
| ok() -> bool | status == "OK" |
| res(string) -> Res | nested result field |
| status() -> string | the status field ("OK", "NO_CONVERGENCE", ...) |
| strs(string) -> StrVec | name-list field |
| text(string) -> string | string field |
| vec(string) -> Vec | vector field |
Utilities
Formatting and numeric helpers that the DSL's built-ins (str, float, int, sqrt, pow, ...) do not cover.
Utilities: functions
| Signature | Meaning |
| atan2(float, float) -> float | atan2(y, x) |
| eval(string) -> float | evaluate a constant expression (pycli expression grammar) |
| eval(string, string, float) -> float | evaluate an expression in one named variable |
| eval(string, StrVec, Vec) -> float | evaluate an expression with named variables bound to values |
| exp(float) -> float | e^x |
| fmt(float, int) -> string | fixed decimals: fmt(3.14159, 2) is "3.14" |
| fmt_g(float, int) -> string | printf %.Ng (significant digits) |
| hypot(float, float) -> float | sqrt(x^2 + y^2) without overflow |
| inf() -> float | +infinity |
| is_finite(float) -> bool | x is neither NaN nor infinite |
| is_nan(float) -> bool | x is NaN |
| log(float) -> float | natural log |
| log10(float) -> float | base-10 log |
| nan() -> float | quiet NaN |
| pad(string, int) -> string | left-justify to a width (negative width right-justifies) |
| pi() -> float | π |
| tan(float) -> float | tangent |
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).
| Method | Meaning |
| check(string, bool) -> bool | record a named check; returns the condition |
| close(string, float, float, float) -> bool | check |got - want| <= tol (NaN fails) |
| close(string, Vec, Vec, float) -> bool | check every |got[i] - want[i]| <= tol (lengths must match) |
| close_rel(string, float, float, float) -> bool | check |got - want| <= rtol * max(|want|, 1e-300) |
| fail(string) -> void | stop now with an application failure (exit 4) |
| log(string) -> void | write a line to stderr (stdout is reserved for the JSON result) |
| put(string, float) -> void | record a float |
| put(string, int) -> void | record an int |
| put(string, string) -> void | record a string |
| put(string, bool) -> void | record a bool |
| put(string, Vec) -> void | record a vector (JSON array) |
| put(string, StrVec) -> void | record a list of strings |
| put(string, Mat) -> void | record a matrix (nested arrays) |
| put(string, Res) -> void | record a whole result object |
| put(string, Frame) -> void | record 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
| Signature | Meaning |
| csv(string) -> Frame | parse CSV text (same rules as read_csv) |
| frame() -> Frame | empty frame (add columns with with) |
| read_csv(string) -> Frame | read a CSV file with a header row (a column is numeric when every cell parses; empty/NA/nan are NaN) |
| read_csv(string, Opts) -> Frame | read_csv with options: sep (one char), header (bool), names (StrVec), text (StrVec: columns kept as text) |
Type Frame
Column table.
| Method | Meaning |
| cell(string, int) -> string | one cell as text (column, row) |
| col(string) -> Vec | numeric column as a vector |
| csv() -> string | the frame as CSV text |
| drop(StrVec) -> Frame | all columns except these |
| filter(string) -> Frame | rows where the expression is nonzero: f.filter("x > 0 & y < 3") |
| has(string) -> bool | whether a column exists |
| head(int) -> Frame | first n rows |
| is_missing(string, int) -> bool | whether a cell is missing (NaN, or an absent text value after a join) |
| is_numeric(string) -> bool | whether a column is numeric |
| json() -> string | {columns, rows, data} JSON text |
| mutate(string, string) -> Frame | new frame with column NAME = expression over numeric columns: f.mutate("bmi", "w / (h/100)^2") |
| names() -> StrVec | column names in order |
| ncols() -> int | column count |
| nrows() -> int | row count |
| num(string, int) -> float | one numeric cell (column, row) |
| rename(string, string) -> Frame | rename one column |
| select(StrVec) -> Frame | these columns, in this order |
| sort(string, bool) -> Frame | stable sort by one column (ascending when true; NaN last) |
| tail(int) -> Frame | last n rows |
| take(Vec) -> Frame | rows at these indexes |
| text(string) -> StrVec | any column as text (numbers formatted, NaN as empty) |
| to_mat(StrVec) -> Mat | numeric columns as a matrix (rows x len(names)) |
| where(string, string) -> Frame | rows whose column (as text) equals a value |
| with(string, Vec) -> Frame | new frame with a numeric column added or replaced |
| with(string, StrVec) -> Frame | new frame with a text column added or replaced |
| write_csv(string) -> void | write 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
| Signature | Meaning |
| format_time(float) -> string | seconds since 1970 UTC as YYYY-MM-DD HH:MM:SS |
| parse_time(string) -> float | ISO-8601 text as seconds since 1970 UTC |
More methods of Frame
| Method | Meaning |
| concat(Frame) -> Frame | rows of this frame then the other (same column names and kinds) |
| describe() -> Frame | summary of the numeric columns: a stat column (count, mean, std, min, 25%, 50%, 75%, max) and one column each (pandas describe) |
| dropna() -> Frame | rows with no missing value in any column |
| dropna(StrVec) -> Frame | rows with no missing value in these columns |
| fillna(string, float) -> Frame | replace NaN in a numeric column |
| groupby(StrVec, string) -> Frame | group 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) -> Frame | groupby; the bool drops rows whose key is missing (pandas dropna=True) |
| merge(Frame, StrVec, string) -> Frame | database 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) -> Frame | merge 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) -> Frame | pivot table (index column, columns column, values column, agg): one row per index value, one column per distinct columns value (sorted) |
| resample(string, string, string) -> Frame | time 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) -> Vec | trailing window aggregate of a numeric column (pandas rolling: the first window-1 values are NaN) |
| rolling(string, int, string, Opts) -> Vec | rolling with min_periods (int) and center (bool) |
| shift(string, int) -> Vec | a numeric column shifted by n rows (positive: later rows see earlier values; vacated cells NaN) |
| times(string) -> Vec | an ISO-8601 text column as seconds since 1970-01-01 UTC (offsets applied) |
| unique(string) -> StrVec | distinct values of a column as text, in first-seen order (missing omitted) |
| value_counts(string) -> Frame | frame {value (text), count} sorted by count descending, then value |
More methods of Vec
| Method | Meaning |
| rolling(int, string) -> Vec | trailing 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
| Signature | Meaning |
| mat_frame(Mat, StrVec) -> Frame | a matrix as a frame with these column names (pycli array_to_frame) |
| read_npy(string) -> Mat | a .npy file as a matrix (a rank-1 array becomes one column) |
| read_npy_vec(string) -> Vec | a rank-1 (or single-column) .npy file as a vector |
| read_safetensors(string, string) -> Mat | one tensor (file, key) as a matrix (rank 1 becomes one column) |
| read_safetensors_vec(string, string) -> Vec | one rank-1 tensor (file, key) as a vector |
| read_text(string) -> string | read a whole text file |
| remove_file(string) -> bool | delete a file; false when it did not exist |
| write_npy(string, Vec) -> void | write a vector as a rank-1 float64 .npy |
| write_npy(string, Mat) -> void | write a matrix as a rank-2 float64 .npy |
| write_safetensors(string, string, Vec) -> void | write a vector as one F64 tensor (file, key, data) |
| write_safetensors(string, string, Mat) -> void | write a matrix as one F64 tensor (file, key, data) |
| write_text(string, string) -> void | write 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
| Method | Meaning |
| cholesky() -> Mat | lower-triangular L with A = L L^T (must be symmetric positive definite) |
| cond() -> float | 2-norm condition number s_max / s_min |
| det() -> float | determinant |
| eig() -> Res | general eigenvalues: fields values_re, values_im (sorted by real part, then imaginary), real (bool: all imaginary parts 0) |
| eigh() -> Res | symmetric eigen-decomposition: fields values (ascending), vectors (columns), reconstruction_error |
| expm() -> Mat | matrix exponential (Padé scaling and squaring) |
| inv() -> Mat | inverse (singular matrices are refused) |
| is_symmetric(float) -> bool | max |A - A^T| <= tol |
| logm() -> Mat | principal matrix logarithm (real result required) |
| lstsq(Vec) -> Res | least squares (SVD, numpy.linalg.lstsq): x, rank, singular_values, residues, residual_norm, status OK/RANK_DEFICIENT |
| lstsq(Vec, Opts) -> Res | least squares with rcond (relative singular-value cutoff; default eps * max(m, n)) |
| lu() -> Res | LU with partial pivoting A = P L U (scipy.linalg.lu): fields p, l, u |
| norm() -> float | Frobenius norm |
| norm(string) -> float | matrix norm: fro, nuc, 1, -1, 2, -2, inf, -inf (numpy ord) |
| pinv() -> Mat | Moore-Penrose pseudo-inverse (cutoff eps * max(m, n) * s_max) |
| qr() -> Res | reduced QR A = Q R (Householder): fields q, r, reconstruction_error |
| rank() -> int | numerical rank (SVD, tolerance s_max * max(m, n) * eps) |
| slogdet() -> Res | sign and log|det| (numpy.linalg.slogdet): fields sign, logabsdet |
| solve(Vec) -> Vec | x with A x = b (LU with partial pivoting; singular matrices are refused) |
| solve(Vec, string) -> Vec | solve with assume_a = gen, sym (exactly symmetric) or pos (Cholesky; must be positive definite) |
| solve(Mat) -> Mat | X with A X = B (several right-hand sides) |
| sqrtm() -> Mat | principal matrix square root (real result required) |
| svd() -> Res | thin SVD A = U diag(s) Vt: fields u (Mat), s (Vec, descending), vt (Mat), reconstruction_error |
| trace() -> float | sum 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
| Signature | Meaning |
| sparse(int, int) -> Sparse | empty rows x cols sparse matrix (fill with add) |
| sparse(Vec, Vec, Vec, int, int) -> Sparse | from COO triplets (row indexes, column indexes, values, rows, cols); duplicates are summed |
| sparse(Mat) -> Sparse | from a dense matrix (zeros dropped) |
| speye(int) -> Sparse | n x n sparse identity |
| tridiag(int, float, float, float) -> Sparse | n x n tridiagonal matrix with constant (lower, diagonal, upper) bands |
Type Sparse
Sparse float64 matrix. Operator * multiplies by a Vec.
Operators: * → mul
| Method | Meaning |
| add(int, int, float) -> Sparse | in place: A[i, j] += x; returns the matrix |
| bicgstab(Vec, Opts) -> Res | BiCGSTAB for general A: rtol, atol, maxiter, x0 |
| cg(Vec) -> Res | conjugate gradient for symmetric positive definite A: x, status, iterations, residual_norm, relative_residual |
| cg(Vec, Opts) -> Res | cg with rtol (default 1e-5), atol, maxiter (default 10 n), x0 |
| cols() -> int | column count |
| eigsh(int, Opts) -> Res | k 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) -> Res | restarted GMRES: rtol, atol, restart (default 20), maxiter, x0 |
| mul(Vec) -> Vec | matrix-vector product |
| nnz() -> int | stored nonzeros (after summing duplicates) |
| rows() -> int | row count |
| solve(Vec) -> Vec | direct sparse LU solve (scipy spsolve); singular matrices are refused |
| t() -> Sparse | transpose |
| to_dense() -> Mat | dense 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
| Signature | Meaning |
| airy(float) -> Res | Airy functions (scipy.special.airy): fields ai, aip, bi, bip |
| airy(Vec) -> Res | Airy functions elementwise: Vec fields ai, aip, bi, bip |
| dist(string) -> Dist | distribution with default parameters (families without shape parameters: norm, uniform, expon, cauchy, laplace, logistic, gumbel_r, rayleigh) |
| dist(string, Opts) -> Dist | distribution with parameters (scipy names; unknown or missing ones are errors that list the valid ones) |
| dist_names() -> StrVec | the 31 distribution families |
| logsumexp(Vec) -> float | log(sum(exp(v))) without overflow (scipy.special.logsumexp) |
| pearsonr(Vec, Vec) -> Res | Pearson correlation with the two-sided p-value of the exact beta null (scipy.stats.pearsonr): statistic, pvalue, df |
| rng(int) -> Rng | generator seeded like numpy.random.default_rng(seed) (seed >= 0) |
| special(string, float) -> float | scipy.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) -> Vec | scipy.special function by name (pycli special_fn): elementwise |
| special(string, float, float) -> float | scipy.special function by name (pycli special_fn): two arguments |
| special(string, float, Vec) -> Vec | scipy.special function by name (pycli special_fn): scalar first argument, vector second (e.g. jv(v, x)) |
| special(string, Vec, float) -> Vec | scipy.special function by name (pycli special_fn): vector first argument, scalar second (e.g. boxcox(x, lmbda)) |
| special(string, Vec, Vec) -> Vec | scipy.special function by name (pycli special_fn): two vectors of one length (length-1 vectors broadcast) |
| special(string, float, float, float) -> float | scipy.special function by name (pycli special_fn): three arguments (betainc family) |
| special(string, float, float, Vec) -> Vec | scipy.special function by name (pycli special_fn): three arguments, vector last |
| special(string, Vec, Vec, Vec) -> Vec | scipy.special function by name (pycli special_fn): three vectors |
| special(string, float, float, float, float) -> float | scipy.special function by name (pycli special_fn): four arguments (hyp2f1) |
| special(string, float, float, float, Vec) -> Vec | scipy.special function by name (pycli special_fn): four arguments, vector last |
| special(string, Vec, Vec, Vec, Vec) -> Vec | scipy.special function by name (pycli special_fn): four vectors |
| special_names() -> StrVec | names accepted by special() |
| ttest_1samp(Vec, float) -> Res | one-sample t test against popmean (scipy.stats.ttest_1samp, two-sided): statistic, pvalue, df |
| ttest_ind(Vec, Vec) -> Res | two-sample t test with pooled variance (scipy.stats.ttest_ind, two-sided) |
| ttest_ind(Vec, Vec, Opts) -> Res | two-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))).
| Method | Meaning |
| cdf(float) -> float | cumulative distribution function |
| cdf(Vec) -> Vec | cumulative distribution function (elementwise) |
| interval(float) -> Vec | central interval [ppf((1-c)/2), ppf((1+c)/2)] with confidence c in [0, 1] |
| is_discrete() -> bool | true for the discrete families |
| isf(float) -> float | inverse survival function; p must be in [0, 1] |
| isf(Vec) -> Vec | inverse survival function; p must be in [0, 1] (elementwise) |
| logcdf(float) -> float | log cdf |
| logcdf(Vec) -> Vec | log cdf (elementwise) |
| logpdf(float) -> float | log density (log mass for a discrete family) |
| logpdf(Vec) -> Vec | log density (log mass for a discrete family) (elementwise) |
| logpmf(float) -> float | log probability mass (discrete families only) |
| logpmf(Vec) -> Vec | log probability mass, elementwise (discrete families only) |
| logsf(float) -> float | log survival function |
| logsf(Vec) -> Vec | log survival function (elementwise) |
| mean() -> float | mean (inf or NaN where undefined, as scipy) |
| median() -> float | median ppf(0.5) |
| moments() -> Res | pycli fn=moments: fields mean, var, skew, kurtosis (excess, as scipy), moments_undefined (names of the non-finite ones), status |
| name() -> string | family name |
| params() -> Res | the resolved parameters (scipy names, plus loc and scale) |
| pdf(float) -> float | density (the mass function for a discrete family, as pycli fn=pdf) |
| pdf(Vec) -> Vec | density (the mass function for a discrete family, as pycli fn=pdf) (elementwise) |
| pmf(float) -> float | probability mass (discrete families only) |
| pmf(Vec) -> Vec | probability mass, elementwise (discrete families only) |
| ppf(float) -> float | quantile function (inverse cdf); p must be in [0, 1] |
| ppf(Vec) -> Vec | quantile function (inverse cdf); p must be in [0, 1] (elementwise) |
| rvs(int, int) -> Vec | n random variates from seed (pycli fn=rvs; numpy Generator(PCG64(seed)); a shorter n is a prefix of a longer one) |
| sf(float) -> float | survival function 1 - cdf |
| sf(Vec) -> Vec | survival function 1 - cdf (elementwise) |
| std() -> float | standard deviation |
| support() -> Vec | [lower, upper] end of the support |
| var() -> float | variance |
Type Rng
A numpy-compatible random generator: the stream of numpy.random.default_rng(seed) (PCG64 + SeedSequence). Methods advance it in place.
| Method | Meaning |
| beta(int, float, float) -> Vec | n beta variates (Generator.beta) |
| binomial(int, int, float) -> Vec | n binomial counts with trials and p (Generator.binomial) |
| choice(Vec, int, bool) -> Vec | n elements of a vector, with or without replacement (Generator.choice, shuffle=True) |
| exponential(int, float) -> Vec | n exponential variates with the given scale (Generator.exponential) |
| gamma(int, float, float) -> Vec | n gamma variates (shape, scale) (Generator.gamma) |
| integers(int, int, int) -> Vec | n integers in [lo, hi) (Generator.integers, int64, Lemire's method) |
| jumped() -> Rng | an independent generator: this state advanced by (phi - 1) * 2^128 draws (PCG64.jumped) |
| normal(int, float, float) -> Vec | n normal variates with mean mu and standard deviation sd (Generator.normal) |
| permutation(int) -> Vec | a random permutation of 0..n-1 (Generator.permutation) |
| poisson(int, float) -> Vec | n Poisson counts (Generator.poisson) |
| random(int) -> Vec | n uniforms in [0, 1) (Generator.random) |
| shuffle(Vec) -> Vec | a shuffled copy of a vector (Generator.permutation of an array) |
| standard_normal(int) -> Vec | n standard normal variates (Generator.standard_normal) |
| uniform(int, float, float) -> Vec | n 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
| Signature | Meaning |
| least_squares(string, string, StrVec, Vec, Opts) -> Res | fit 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) -> Res | minimise 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) -> Res | minimise c.x subject to x >= 0 (HiGHS; see the Opts form) |
| linprog(Vec, Opts) -> Res | LP/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) -> Res | minimise 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) -> Res | minimize 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) -> Res | integral 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) -> Res | quad 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) -> Res | solve 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) -> Res | root 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) -> Res | bracketed 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) -> Res | root_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
| Signature | Meaning |
| ode(StrVec, StrVec, Vec, float, float) -> Res | solve 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) -> Res | solve an initial value problem with options (method, rtol, atol, t_eval, events, ... and $ constants); same result fields |
| ode_sol(StrVec, StrVec, Vec, float, float) -> OdeSol | like ode, keeping the dense output for evaluation at any time inside the integrated range |
| ode_sol(StrVec, StrVec, Vec, float, float, Opts) -> OdeSol | like 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.
| Method | Meaning |
| eval(float) -> Vec | state vector at time t (t must lie in the integrated range) |
| eval(Vec) -> Mat | states at several times: one row per time, one column per state |
| res() -> Res | the run's result (the fields of ode) |
| t_max() -> float | end of the integrated range (the terminal event time when one stopped the run) |
| t_min() -> float | start 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
| Signature | Meaning |
| interp(string, Vec, Vec) -> Interp | build a 1-D interpolant of kind linear, nearest, cubic, pchip, akima, makima, smoothing or rbf (default options) |
| interp(string, Vec, Vec, Opts) -> Interp | build a 1-D interpolant with options (bc_type, lam, kernel, epsilon, smoothing, degree, extrapolate) |
| interp(string, Mat, Vec) -> Interp | build an n-D radial basis function interpolant (kind must be rbf; one row of x per node) |
| interp(string, Mat, Vec, Opts) -> Interp | build 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.
| Method | Meaning |
| coeffs() -> Mat | PPoly 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) -> float | derivative of order nu at x (0 = value; above the degree it is 0; right-hand value at a node) |
| deriv(Vec, int) -> Vec | derivative of order nu at each x |
| eval(float) -> float | value at x |
| eval(Vec) -> Vec | values at each x |
| eval(Mat) -> Vec | rbf values at the points (one row per point) |
| info() -> Res | fields: status, message, kind, n_nodes, extrapolate, bc_type (cubic), lam (smoothing: the given or GCV value), interpolation_error (rbf) |
| integrate(float, float) -> float | definite integral from a to b (negative when b < a; bounds in the node range unless extrapolate is extend) |
| knots() -> Vec | breakpoints of the piecewise polynomial (the nodes; rbf: empty) |
| status() -> string | OK, 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
| Signature | Meaning |
| coherence(Vec, Vec, float) -> Res | magnitude-squared coherence |Pxy|^2 / (Pxx Pyy): fields f, cxy, df, n_segments, n_bins, peak_index, peak_freq |
| coherence(Vec, Vec, float, Opts) -> Res | coherence with window, nperseg, noverlap, nfft, detrend |
| convolve(Vec, Vec, string) -> Vec | discrete linear convolution (numpy.convolve), mode full, same or valid |
| csd(Vec, Vec, float) -> Res | cross spectral density (Welch): fields f, pxy_re, pxy_im, magnitude, df, n_segments, n_bins, peak_index, peak_freq |
| csd(Vec, Vec, float, Opts) -> Res | csd with the welch options |
| detrend(Vec, string) -> Vec | remove the mean (constant) or the least-squares line (linear) (scipy.signal.detrend) |
| fft(Vec, Vec) -> Res | complex FFT of re + i im (numpy.fft.fft): fields re, im |
| fftfreq(int, float) -> Vec | sample frequencies of fft (numpy.fft.fftfreq) |
| fftshift(Vec) -> Vec | move the zero-frequency term to the centre (numpy.fft.fftshift) |
| filtfilt(Vec, Vec, Vec) -> Vec | zero-phase filtering with b/a (scipy filtfilt: odd extension, padlen 3*max(len(a), len(b))) |
| filtfilt(Vec, Vec, Vec, Opts) -> Vec | filtfilt with padtype (odd, even, constant, none) and padlen |
| find_peaks(Vec) -> Res | all local maxima (scipy find_peaks, pycli sig_peaks): fields status (OK or NO_PEAKS), indices, n_peaks |
| find_peaks(Vec, Opts) -> Res | find_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) -> Res | frequency response of b/a at angular frequencies w (rad/sample): fields freqs, magnitude, phase |
| freqz(Vec, Vec, Vec, float) -> Res | frequency response of b/a at frequencies in Hz for sampling frequency fs |
| ifft(Vec, Vec) -> Res | inverse complex FFT with 1/n scaling (numpy.fft.ifft): fields re, im |
| iir(string, int, float) -> Filter | design 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) -> Filter | iir with one (low/high) or two (band) cutoff frequencies |
| iir(string, int, float, Opts) -> Filter | iir 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) -> Filter | iir with cutoff frequencies and options (see above) |
| irfft(Vec, Vec, int) -> Vec | inverse of rfft with output length n (numpy.fft.irfft) |
| lfilter(Vec, Vec, Vec) -> Vec | filter x with transfer function b/a, zero initial state (scipy lfilter, direct form II transposed) |
| peak_prominences(Vec, Vec) -> Res | prominence of each peak index (scipy peak_prominences): fields prominences, left_bases, right_bases |
| peak_prominences(Vec, Vec, Opts) -> Res | peak_prominences with wlen (window length in samples) |
| peak_widths(Vec, Vec) -> Res | width of each peak at half prominence (scipy peak_widths): fields widths, width_heights, left_ips, right_ips |
| peak_widths(Vec, Vec, Opts) -> Res | peak_widths with rel_height (default 0.5) and wlen |
| periodogram(Vec, float) -> Res | periodogram (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) -> Res | periodogram with window (name or Vec), nfft, detrend (constant, linear, none), return_onesided, scaling (density, spectrum) |
| rfft(Vec) -> Res | real-input FFT (numpy.fft.rfft): fields re, im (n/2+1 values) |
| rfft(Vec, int) -> Res | rfft of x truncated or zero-padded to n |
| rfft_abs(Vec) -> Vec | magnitudes |rfft(x)| |
| rfftfreq(int, float) -> Vec | sample frequencies of rfft for n samples spaced d apart (numpy.fft.rfftfreq) |
| savgol(Vec, int, int) -> Vec | Savitzky-Golay smoothing (scipy savgol_filter, mode interp): window_length, polyorder |
| savgol(Vec, int, int, Opts) -> Vec | savgol with deriv, delta, mode (interp, mirror, nearest, constant, wrap), cval |
| savgol_coeffs(int, int) -> Vec | Savitzky-Golay convolution coefficients (scipy savgol_coeffs) |
| sos_filter(Mat) -> Filter | a Filter from given second-order sections (n x 6, a0 = 1 in column 3); frequencies as fractions of Nyquist |
| sos_filter(Mat, float) -> Filter | a Filter from second-order sections with a sampling frequency fs (Hz) |
| spectrogram(Vec, float) -> Res | spectrogram (scipy defaults: tukey 0.25 window, nperseg 256, noverlap nperseg/8, density): fields f, t, sxx (Mat, frequencies x times) |
| spectrogram(Vec, float, Opts) -> Res | spectrogram with window, nperseg, noverlap, nfft, detrend, return_onesided, scaling |
| welch(Vec, float) -> Res | Welch PSD (hann, nperseg 256 or the signal length, 50% overlap): same fields as periodogram |
| welch(Vec, float, Opts) -> Res | Welch PSD with window, nperseg, noverlap, nfft, detrend, return_onesided, scaling, average (mean, median) |
| window(string, int) -> Vec | periodic 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) -> Vec | window 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')).
| Method | Meaning |
| ba() -> Res | transfer-function coefficients b, a (scipy zpk2tf; poorly conditioned for high orders: prefer sos) |
| filter(Vec) -> Vec | causal filtering with zero initial state (scipy sosfilt) |
| filtfilt(Vec) -> Vec | zero-phase forward-backward filtering (scipy sosfiltfilt: odd extension, padlen 3*(2*n_sections+1-...)) |
| filtfilt(Vec, Opts) -> Vec | sosfiltfilt with options padtype (odd, even, constant, none) and padlen (int) |
| fs() -> float | sampling frequency (NaN when frequencies are fractions of Nyquist) |
| gain(float) -> float | |H| at one frequency (Hz with fs, else a fraction of Nyquist) |
| info() -> Res | pycli sig_filter fields: status, family, order, btype, n_sections, sos, max_pole_radius, stable, marginal |
| marginal() -> bool | a pole within 1e-6 of the unit circle (rings for a very long time) |
| max_pole_radius() -> float | largest pole modulus of the rounded sections (50-digit arithmetic, as pycli) |
| n_sections() -> int | number of second-order sections |
| order() -> int | filter order as designed (for sos_filter: the number of nonzero denominator terms) |
| response(Vec) -> Res | frequency response at the given frequencies (Hz with fs, else fractions of Nyquist): fields freqs, magnitude, phase (radians) |
| sos() -> Mat | second-order sections (n_sections x 6: b0 b1 b2 a0 a1 a2) |
| stable() -> bool | all poles strictly inside the unit circle (max_pole_radius < 1) |
| status() -> string | OK, or UNSTABLE (filter and filtfilt refuse an unstable filter) |
| zpk() -> Res | zeros, 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
| Signature | Meaning |
| cdist(Mat, Mat, string) -> Mat | distance 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) -> Mat | cdist 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) -> Mat | distance matrix of the rows of a with themselves (symmetric, zero diagonal for a true metric) |
| hull(Mat) -> Res | convex 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) -> Res | k 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) -> Res | knn with options: p (Minkowski norm in [1, 64] or inf(); default 2) |
| knn(Mat, int) -> Res | k nearest points of every point among the points themselves (a point is its own nearest neighbour) |
| knn(Mat, int, Opts) -> Res | self-query knn with options: p, exclude_self (drop each point from its own list) |
| knn_radius(Mat, Mat, float) -> Res | all 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) -> Res | knn_radius with options: p, max_pairs (default 1000000; more is an error) |
| knn_radius(Mat, float, Opts) -> Res | radius neighbours of every point among the points themselves; options p, max_pairs, exclude_self |
| pdist(Mat, string) -> Vec | condensed pairwise distances (scipy pdist): d(0,1), d(0,2), ..., d(n-2,n-1) |
| pdist(Mat, string, Opts) -> Vec | pdist 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
| Signature | Meaning |
| graph(bool) -> Graph | empty graph (true: directed); add edges with edge |
| graph(Frame, string, string, bool) -> Graph | graph from an edge list frame (from column, to column, directed) with unit weights |
| graph(Frame, string, string, string, bool) -> Graph | graph from an edge list frame with a weight column (from, to, weight, directed) |
| graph(Frame, string, string, bool, Opts) -> Graph | graph 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.
| Method | Meaning |
| all_distances() -> Res | all-pairs Dijkstra distances (scipy csgraph): nodes (sorted), distance (Mat, NaN = unreachable), n_unreachable_pairs |
| all_distances(Opts) -> Res | all pairs with method dijkstra, bellman_ford (Johnson; status NEGATIVE_CYCLE with cycle) or bfs |
| directed() -> bool | whether the graph is directed |
| distances(string) -> Res | Dijkstra 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) -> Res | distances with method dijkstra, bellman_ford or bfs |
| edge(string, string, float) -> Graph | in place: add an edge u -> v (both ways when undirected) with a weight; returns the graph |
| edge(string, string, float, float) -> Graph | in place: add an edge with a weight and a capacity (for flows); returns the graph |
| has_node(string) -> bool | whether a node exists |
| k_shortest(string, string, int) -> Res | the 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) -> Res | k_shortest with method dijkstra (weights) or bfs (edge counts) |
| max_flow(string, string) -> Res | maximum 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) -> Res | cheapest 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) -> Res | minimum-cost flow for node supplies (positive) and demands (negative); status UNBALANCED when they do not sum to zero |
| min_cut(string, string) -> Res | minimum s-t cut (networkx minimum_cut partition): value, cut_from, cut_to, cut_capacity, n_cut_edges, source_side, source_side_size |
| n_edges() -> int | edges as added (parallel edges and self loops included) |
| n_nodes() -> int | node count |
| node(string) -> Graph | in place: add a node (no-op when present); returns the graph |
| nodes() -> StrVec | node names in sorted order |
| shortest_path(string, string) -> Res | Dijkstra 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) -> Res | shortest 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
| Signature | Meaning |
| acf(Vec, int) -> Res | sample 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) -> Res | acf 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) -> Res | augmented 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) -> Res | adfuller 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) -> Res | ARIMA(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) -> Res | ARIMA 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) -> Res | GLM 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) -> Res | GLM 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) -> Res | GLM with a +-joined right-hand side: glm(f, "count", "C(group)", "poisson") |
| glm(Frame, string, string, string, Opts) -> Res | GLM with a +-joined right-hand side and options |
| kpss(Vec) -> Res | KPSS 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) -> Res | kpss with options: regression (c or ct), nlags ("auto", "legacy" or an int) |
| ljung_box(Vec, int) -> Res | Ljung-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) -> Res | ljung_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) -> Res | ljung_box at an explicit strictly increasing list of lags |
| ljung_box(Vec, Vec, Opts) -> Res | ljung_box at explicit lags with options (model_df, boxpierce) |
| ols(Frame, string, StrVec) -> Res | OLS 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) -> Res | OLS/WLS with options: weights (column: WLS), cov_type, groups (cluster column), use_t, alpha, na_action, include, intercept |
| ols(Frame, string, string) -> Res | OLS 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) -> Res | OLS/WLS with a +-joined right-hand side and options |
| pacf(Vec, int) -> Res | partial 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) -> Res | pacf 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
| Signature | Meaning |
| adjusted_rand_score(Vec, Vec) -> float | adjusted Rand index of two labelings (sklearn.metrics.adjusted_rand_score; 1 = same partition) |
| kmeans(Mat, int) -> Estimator | k-means with k clusters (sklearn KMeans, Lloyd, k-means++, n_init 10, seed 0) |
| kmeans(Mat, int, Opts) -> Estimator | k-means with options seed, n_init, max_iter, tol, init |
| label_encode(StrVec) -> Res | text labels to codes (sklearn LabelEncoder): fields codes (Vec, 0-based index into classes), classes (sorted StrVec) |
| load_model(string) -> Estimator | read a model written by Estimator.save (JSON, format lmpy_model 1) |
| ml_cv(string, Mat, Vec, int) -> Res | k-fold cross-validation (pycli ml_cv): stratified for classifiers (accuracy), kfold for regressors (r2), no shuffle |
| ml_cv(string, Mat, Vec, int, Opts) -> Res | cross-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) -> Estimator | fit a supervised model (pycli ml_fit): kind, features x (rows x p), target y (class labels or values) |
| ml_fit(string, Mat, Vec, Opts) -> Estimator | fit a supervised model with hyperparameters and scale (standardise features first; learned from the training rows) |
| ml_fit(string, Mat) -> Estimator | fit an unsupervised model: kmeans (2 clusters), pca (2 components) or standard_scaler |
| ml_fit(string, Mat, Opts) -> Estimator | fit 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) -> Res | metrics 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) -> Res | metrics 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) -> Res | metrics 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.
| Method | Meaning |
| centers() -> Mat | k-means cluster centres (one row per cluster) |
| classes() -> Vec | sorted class labels (classifiers) |
| coef() -> Mat | coefficients as a matrix: one row per decision function (regressors and binary classifiers: 1 row) |
| decision_function(Mat) -> Mat | decision scores (logistic, linear_svc, lda); binary models give one column, positive for classes()[1] |
| inertia() -> float | k-means within-cluster sum of squared distances |
| intercept() -> Vec | intercepts, one per decision function (regressors: one value) |
| json() -> string | the model file text (JSON) |
| kind() -> string | the family (linear, logistic, kmeans, ...) |
| labels() -> Vec | k-means cluster index of every training row |
| n_iter() -> int | iterations used (lasso/elastic_net epochs, logistic/linear_svc Newton steps, k-means Lloyd iterations of the best run) |
| ok() -> bool | status is OK |
| params() -> Res | fitted 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) -> Vec | predictions: class labels, regression values or cluster indexes (pycli ml_predict kind predict) |
| predict_proba(Mat) -> Mat | class probabilities, one column per class in classes() order (logistic, gaussian_nb, lda, knn_classifier) |
| save(string) -> void | write the model as JSON (atomic replace); load_model reads it back with identical predictions |
| score(Mat, Vec) -> float | accuracy (classifiers) or R^2 (regressors) on x, y |
| status() -> string | OK, RANK_DEFICIENT (linear: minimum-norm solution kept) or NO_CONVERGENCE |
| task() -> string | regression, classification, clustering, decomposition or scaling |
| transform(Mat) -> Mat | standard_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.
| Item | Values |
| Operators | + - * / ^ < <= > >= == != & | |
| Precedence, lowest to highest | |; &; < <= > >= == !=; + -; * /; unary -; ^ |
| Constants | pi, e |
| Functions of one argument | exp, 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 arguments | atan2, pmin, pmax, beta, lbeta, choose, lchoose |
| Functions of three arguments | ifelse |
| Reducers over a data vector | sum, mean, prod, min, max |
| Reserved names | list |
| Bindings | Option 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
| Function | Signatures |
| str_contains | str_contains(string, string) -> bool |
| str_ends_with | str_ends_with(string, string) -> bool |
| str_find | str_find(string, string) -> int |
| str_is_float | str_is_float(string) -> bool |
| str_is_int | str_is_int(string) -> bool |
| str_len | str_len(string) -> int |
| str_lower | str_lower(string) -> string |
| str_match | str_match(string, string) -> bool |
| str_repeat | str_repeat(string, int) -> string |
| str_replace | str_replace(string, string, string) -> string |
| str_split | str_split(string, string) -> StrList |
| str_starts_with | str_starts_with(string, string) -> bool |
| str_substr | str_substr(string, int, int) -> string |
| str_to_float | str_to_float(string) -> float |
| str_to_int | str_to_int(string) -> int |
| str_trim | str_trim(string) -> string |
| str_upper | str_upper(string) -> string |
Encoding and templates
| Function | Signatures |
| str_base64_decode | str_base64_decode(string) -> string |
| str_base64_encode | str_base64_encode(string) -> string |
| str_hex_decode | str_hex_decode(string) -> string |
| str_hex_encode | str_hex_encode(string) -> string |
| template_render | template_render(string, Json) -> string |
Math
| Function | Signatures |
| math_abs | math_abs(int) -> int; math_abs(float) -> float |
| math_ceil | math_ceil(int) -> int; math_ceil(float) -> float |
| math_floor | math_floor(int) -> int; math_floor(float) -> float |
| math_max | math_max(int, int) -> int; math_max(float, float) -> float |
| math_min | math_min(int, int) -> int; math_min(float, float) -> float |
| math_pow | math_pow(int, int) -> int; math_pow(float, float) -> float |
| math_round | math_round(int) -> int; math_round(float) -> float |
| math_sqrt | math_sqrt(int) -> int; math_sqrt(float) -> float |
Files
| Function | Signatures |
| file_append | file_append(string, string) -> void |
| file_exists | file_exists(string) -> bool |
| file_lines | file_lines(string) -> StrList |
| file_read | file_read(string) -> string |
| file_write | file_write(string, string) -> void |
Collection constructors and JSON
| Function | Signatures |
| float_list | float_list() -> FloatList |
| float_map | float_map() -> FloatMap |
| float_pq | float_pq() -> FloatPQ |
| float_queue | float_queue() -> FloatQueue |
| float_stack | float_stack() -> FloatStack |
| int_list | int_list() -> IntList |
| int_map | int_map() -> IntMap |
| int_pq | int_pq() -> IntPQ |
| int_queue | int_queue() -> IntQueue |
| int_stack | int_stack() -> IntStack |
| json_parse | json_parse(string) -> Json |
| str_list | str_list() -> StrList |
| str_map | str_map() -> StrMap |
| str_pq | str_pq() -> StrPQ |
| str_queue | str_queue() -> StrQueue |
| str_stack | str_stack() -> StrStack |
Result helpers
| Function | Signatures |
| lmcode_return_null | lmcode_return_null() -> void |
| lmcode_return_put | lmcode_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_null | lmcode_return_put_null(string) -> void |
| lmcode_return_set | lmcode_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
| Type | Methods |
| FloatList | add(float) -> FloatList; at(int) -> float; clear() -> FloatList; contains(float) -> bool; index_of(float) -> int; len() -> int; set(int, float) -> FloatList |
| FloatMap | len() -> 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 |
| FloatPQ | push(float, float) -> FloatPQ; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatPQ |
| FloatQueue | push(float) -> FloatQueue; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatQueue; at(int) -> float |
| FloatStack | push(float) -> FloatStack; pop() -> float; peek() -> float; len() -> int; empty() -> bool; clear() -> FloatStack; at(int) -> float |
| IntList | add(int) -> IntList; at(int) -> int; clear() -> IntList; contains(int) -> bool; index_of(int) -> int; len() -> int; set(int, int) -> IntList |
| IntMap | len() -> 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 |
| IntPQ | push(int, float) -> IntPQ; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntPQ |
| IntQueue | push(int) -> IntQueue; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntQueue; at(int) -> int |
| IntStack | push(int) -> IntStack; pop() -> int; peek() -> int; len() -> int; empty() -> bool; clear() -> IntStack; at(int) -> int |
| Json | kind() -> 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 |
| StrList | add(string) -> StrList; at(int) -> string; clear() -> StrList; contains(string) -> bool; index_of(string) -> int; join(string) -> string; len() -> int; set(int, string) -> StrList |
| StrMap | clear() -> 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 |
| StrPQ | push(string, float) -> StrPQ; pop() -> string; peek() -> string; len() -> int; empty() -> bool; clear() -> StrPQ |
| StrQueue | push(string) -> StrQueue; pop() -> string; peek() -> string; len() -> int; empty() -> bool; clear() -> StrQueue; at(int) -> string |
| StrStack | push(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
| Interface | Signature |
| 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
| Function | Signature |
| rest_config | rest_config(string, string) -> void |
| rest_route | rest_route(string, string, string) -> void |
| rest_serve | rest_serve() -> void |
| rest_stop | rest_stop() -> void |
| rest_cli | rest_cli(StrList) -> string |
Route templates accept {param} and {rest...} placeholders as well as :param and :rest... placeholders.
RestExchange methods
| Method | Signature |
| method | method() -> string |
| path | path() -> string |
| query | query(string) -> string |
| has_query | has_query(string) -> bool |
| param | param(string) -> string |
| header | header(string) -> string |
| has_header | has_header(string) -> bool |
| body | body() -> string |
| status | status(int) -> void |
| set_header | set_header(string, string) -> void |
| send | send(string) -> void |
| json | json(string) -> void |
| get | get(string) -> string |
| set | set(string, string) -> void |
| increment | increment(string) -> int |