lmpy guide
This guide explains how lmpy is built and how its pieces fit together: the compile and run pipeline, the value model, options and results, expression strings, the standard catalog, and the limits to plan around. The complete list of signatures is in the reference.
Overview
lmpy is one C++17 executable that runs LMScript lmcode bytecode against a numerical library. Everything except the system C library is linked in, so it needs no Python, R, Docker or other shared library at run time. Programs are _lmcode_ blocks in an LMScript file. lmscript type-checks a block against the lmpy schema and compiles it to bytecode; run_lmcode starts lmpy, which loads the bytecode, binds it to its embedded schema, runs it, and prints one framed result that run_lmcode decodes.
The design replaces a call-per-operation model with one program of many steps. A block reads data, transforms it, fits a model, checks the answer and reports, all in native memory. Arrays are values (Vec, Mat, Frame) passed between calls, not files exchanged between processes.
Compile and run pipeline
- The block header names the host. With cli="lmpy", lmscript asks the binary for its schema (lmpy --lmcode-schema --json) and compiles against exactly those bytes. With install="github:lmctl-ai/lmpy@latest" it first downloads the release asset when lmpy is not available. With schema="file" it compiles against a schema file.
- Type errors are reported at compile time with a file, line and column: a wrong argument type, an unknown method or a misspelt function never reaches the host.
- run_lmcode passes the compiled program to lmpy --lmcode. The host loads every input before any part executes, so a malformed later part cannot leave file effects of an earlier one behind.
- Each part gets its own out collector. After the run the host writes one LMCODE_RETURN_BEGIN / JSON / LMCODE_RETURN_END frame; several parts return a result array in registration order.
- run_lmcode returns the decoded JSON: ok and result, or ok, phase, code and message.
The schema is generated from the same registry that executes the calls, as are the API reference (lmpy --api-md) and the signature list (lmpy --lmcode-signatures). The bytecode is bound to the schema bytes by hash, which is why compiling with cli= against the binary that will run the block is the dependable route.
Value model
| Type | Meaning | Mutability |
|---|---|---|
| Vec | 1-D float64 array; operators +, -, * are elementwise and a float broadcasts | Methods return new vectors except push, set and extend, which change the vector in place |
| StrVec | List of strings for column names, unknowns and labels | push appends in place |
| Mat | Dense float64 matrix; * is the matrix product with a Mat, a matrix-vector product with a Vec and scaling with a float; hadamard is the elementwise product | Methods return new matrices |
| Frame | Column table: numeric columns are float64 with NaN for missing values, other columns are text | Immutable; every method returns a new frame |
| Opts | Named, validated options for one operation | set changes it in place and returns it for chaining |
| Res | Named, typed result fields, possibly nested | Read-only |
| Dist, Rng, Sparse, OdeSol, Interp, Filter, Graph, Estimator | Typed objects that are used again after they are built: evaluate a distribution, draw numbers, solve, interpolate, filter, search paths, predict | Rng methods advance the generator in place |
Masks are vectors of 1.0 and 0.0 produced by comparison methods such as gt and le; where selects by mask and find returns the indexes. Indexes returned by operations are 0-based floats.
Options and results
Operations with defaults have an overload without options and one with a trailing Opts. Option keys follow the names used by numpy, scipy, pandas, statsmodels and scikit-learn (method, tol, maxiter, rtol, t_eval and so on). Every key is read and validated, so a misspelt key is a run-time error instead of being ignored.
Results distinguish two kinds of failure. Bad input (wrong shapes, an unknown method, non-finite data where finite data is required, a singular matrix in solve) is a run-time error whose message names the operation. A numerical outcome is a status string in the Res, such as OK, NO_CONVERGENCE or RANK_DEFICIENT: the program continues and decides what to do, usually with out.check on ok().
Expression strings
Objectives, residual models, equation systems, differential-equation right-hand sides, and table filters and mutations are written as expression strings, for example 100*(y-x^2)^2 + (1-x)^2. The host parses them with a closed grammar: arithmetic and comparison operators, the constants pi and e, elementary and special functions, ifelse, and the reducers sum, mean, prod, min and max. They cannot call host functions or run code.
The unknowns are named by a StrVec. An option key that starts with $ binds a name for the expressions of that one operation: a float gives a scalar constant and a Vec gives a data vector, read as x[i] or through a reducer. Every expression evaluation in optimisation counts against max_evals and the optional time_limit, so an iterative method reports a status and never hangs.
p = _lmcode_ cli="lmpy" install="github:lmctl-ai/lmpy@latest";
let o = opts().set("method", "DOP853").set("rtol", 0.0000000001).set("atol", 0.000000000001).set("max_output_points", 161);
o.set("$b", 0.3).set("$g", 0.1).set("$population", 1000.0);
o.set("events", strs("b*s*i/population-g*i")).set("direction", vec(-1.0));
let r = ode(strs("-b*s*i/population, b*s*i/population-g*i, g*i"), strs("s, i, r"), vec(999.0, 1.0, 0.0), 0.0, 160.0, o);
out.check("status OK", r.ok());
out.check("population conserved", r.mat("y").row_sums().sub(1000.0).abs().max() <= 0.000001);
let peak = r.vec("event_t").at(0);
out.close("pinned peak day (scipy DOP853)", peak, 38.35530767144, 0.000001);
out.put("peak_day", peak);
out.put("peak_infected", r.mat("event_y").row(0).at(1));
end _lmcode_
res = run_lmcode(p);
require(res.ok, json_stringify(res));
v = res.result.values;
println(sprintf("peak_day=%.6f peak_infected=%.6f", v.peak_day, v.peak_infected));
lmscript sir.lms peak_day=38.355308 peak_infected=300.796071
This SIR epidemic model, adapted from examples/dsl/ode-sir.lms in the repository, binds three constants, locates the infection peak with an event expression, and pins the answer computed by scipy.
Result model
By default the result of a part is an object with values, holding everything recorded with out.put in order, and checks, holding the passed and failed counts and the failures with name and detail. A failed check does not stop the block: the remaining statements run, and at the end the host reports an application failure whose message names every failed check. out.fail stops immediately. out.log writes a line to standard error, because standard output is reserved for the frame.
A block can replace the default result with the standard result helpers lmcode_return_set, lmcode_return_put and lmcode_return_null. Failed checks still make the run an application failure.
p = _lmcode_ cli="lmpy" install="github:lmctl-ai/lmpy@latest";
let v = linspace(0.0, 1.0, 5);
out.check("five points", v.len() == 5);
lmcode_return_put("mean", v.mean());
lmcode_return_put("label", "linspace");
end _lmcode_
r = run_lmcode(p);
require(r.ok, json_stringify(r));
println(json_stringify(r.result));
lmscript ret.lms
{"mean":0.5,"label":"linspace"}
Standard catalog
The lmcode-cpp runtime inside lmpy installs the standard lmcode catalog, and lmscript declares it at compile time, so a block can mix standard functions with the host API. lmpy 0.1.46 vendors lmcode_std_v3 with 206 canonical signatures: string functions, encoding and template_render, math functions, file read and write, typed lists, maps, queues, stacks and priority queues, a Json type, and the lmcode_return helpers. The lmpy schema stays host-only with 551 signature lines; lmpy --lmcode-signatures prints both, 757 lines.
The current lmcode_std_v3 catalog in lmcode-cpp has 226 signatures. It adds the standard REST and CLI interfaces: RestGet, RestPost, RestPut, RestDelete, RestPatch, RestHead, RestOptions, RestHandler, CliCommand and CliOption, the functions rest_config, rest_route, rest_serve, rest_stop and rest_cli, and 15 RestExchange methods. lmpy 0.1.46 does not ship them; it picks them up when it syncs the runtime and publishes a release.
p = _lmcode_ cli="lmpy" install="github:lmctl-ai/lmpy@latest";
let names = str_split("ctrl,trt1,trt2", ",");
let labels = str_list();
for (k in range(0, names.len())) { labels.add(str_upper(names.at(k))); }
let rng_draws = rng(7).standard_normal(1000);
out.put("groups", labels.join(" "));
out.put("largest", math_max(3, names.len()));
out.put("mean_abs_below_one", rng_draws.mean() < 1.0 && rng_draws.mean() > -1.0);
end _lmcode_
r = run_lmcode(p);
require(r.ok, json_stringify(r));
println(json_stringify(r.result.values));
lmscript std.lms
{"groups":"CTRL TRT1 TRT2","largest":3,"mean_abs_below_one":true}
Operation families
| Family | Entry points | Modelled on |
|---|---|---|
| Vectors, matrices, tables | vec, mat, cols, read_csv, groupby, merge, rolling, resample | numpy arrays and a pandas DataFrame subset |
| Linear algebra and sparse | Mat methods solve, lstsq, decompositions, matrix functions; sparse, speye, tridiag | scipy.linalg and scipy.sparse, on Eigen 3.4 |
| Statistics | dist, rng, special functions, classical tests such as ttest_ind | scipy.stats 1.16 and numpy's PCG64 generator |
| Optimisation | minimize, least_squares, root_scalar, root, quad, linprog | scipy.optimize and scipy.integrate; HiGHS for LP and MILP |
| Differential equations | ode | scipy.integrate.solve_ivp: RK45, RK23, DOP853, Radau, BDF, LSODA |
| Interpolation, signal, spatial | interp, iir, welch, find_peaks, fft, cdist | scipy.interpolate, scipy.signal 1.16, scipy.spatial |
| Graphs | graph | networkx-style shortest paths and flows |
| Statistical models | ols, glm, arima, acf, adfuller | statsmodels 0.14 |
| Machine learning | ml_fit, ml_cv, ml_metrics, load_model | scikit-learn 1.7.2 subset |
The repository's examples/python directory holds 29 published Python recipes next to lmpy versions that pin every Python answer, so compatibility is measured per value.
Limits and differences
- Not implemented: random forests and gradient boosting (a clear error), the trust-constr minimiser, analog filter design, and convex hulls above three dimensions.
- LSODA is an automatic switch from RK45 to BDF, not ODEPACK. L-BFGS-B reaches the same optimum as scipy with different iteration counts.
- Numerics are single-threaded, deterministic IEEE arithmetic. Random numbers come only from an explicit integer seed.
- Run-time objects live in an arena for the whole run, so very long loops that create objects grow memory.
- A local variable in a block cannot reuse a schema function name such as dist, full or root.
- Inside a block, write comments on # lines; an apostrophe in a // comment inside the block is a compile error.
- The block language itself provides the built-ins sin, cos, sqrt, abs, floor, pow, min, max, clamp, lerp, int, float, str and range; the host adds exp, log, log10, tan, atan2, hypot, pi, fmt and similar helpers.
- Array files: .npy and .safetensors reads accept rank 1 or 2; writes are float64. Parquet is not supported.
- lmpy serves only the lmcode interface; plotting is out of scope.
Continue with the skill for the working procedure, the reference for signatures, and the generated API reference in the repository.