lmfluid reference

Complete reference for lmfluid 0.2.2: the host command line, exit codes and result frame, the context object, all six host types with their 59 method signatures, expression syntax, CSV layouts, limits, and the standard library the host ships.

Command line

ArgumentsBehaviorExit
--versionPrint lmfluid and the version on stdout0
--noticesPrint the embedded third-party notices0
--lmcode-schema --jsonPrint the exact embedded schema bytes (JSON, dsl.schema 2, name lmfluid)0
--lmcode-schemaPrint the registered signatures, one per line0
--lmcode-signaturesPrint the registered signatures, one per line: 266 lines in 0.2.2 (1 context, 59 host methods, 206 standard)0
--lmcode FILE [FILE ...]Load and verify every bytecode file, then run each in order, stopping at the first failure; one result frame on stdout0, 3, 4
--dry-run --lmcode FILE [FILE ...]Dry mode: load and verify without numerical work or file effects. --dry-run may also follow the files, but may appear only once0, 3
No arguments, unknown flags, an empty file name, a file name starting with two hyphens, or extra arguments after a query flagUsage text on stderr and a failure frame with code CLI_USAGE2

The usage text printed by the host is:

usage: lmfluid --version | --notices | --lmcode-schema [--json] | --lmcode-signatures | [--dry-run] --lmcode FILE [FILE ...]
environment: LMFLUID_MAX_MEMORY_MB  total memory budget in MiB (default 4096); a program that needs more
             stops with a run error (exit 3) instead of allocating

Environment variables

VariableMeaning
LMFLUID_MAX_MEMORY_MBTotal memory budget in MiB, default 4096. Must be a positive whole number; anything else is a usage error (exit 2)
LMCODE_INVOCATION_FILESet by run_lmcode to pass invocation metadata (parts, dry mode) to the host; not set by hand. A standalone --dry-run that contradicts real-mode metadata is refused with exit 2
GITHUB_TOKENRead by lmscript, not by the host, when install="github:lmctl-ai/lmfluid@latest" resolves the release through the GitHub API

Exit codes and result frame

ExitPhase in the frameMeaning
0Success
2cliCommand-line or invocation metadata error (code CLI_USAGE)
3load, runBytecode could not be read or verified (for example code LOAD_BAD_BYTECODE), or a program failed while running (for example code RUN_HOST), including the memory budget
4appApplication or output contract failure (error code APP_FAIL)

For --lmcode invocations stdout carries exactly one frame between the marker lines LMCODE_RETURN_BEGIN and LMCODE_RETURN_END. A failure frame produced by a real run:

lmfluid --lmcode missing.dslb
LMCODE_RETURN_BEGIN
{"ok":false,"phase":"load","code":"LOAD_BAD_BYTECODE","message":"cannot read missing.dslb"}
LMCODE_RETURN_END

In dry mode the same frame additionally carries dry true. run_lmcode parses the frame and returns it to the script as a map: ok and result on success; ok, phase, code, message and, for run errors, line and column on failure.

Block declaration

prog = _lmcode_ cli="lmfluid" install="github:lmctl-ai/lmfluid@latest";
# host program: let, arithmetic, for (k in range(a, b)) { ... }, if, method calls on fluid
end _lmcode_
r = run_lmcode(prog);
assert(r.ok);
ElementMeaning
cli="lmfluid"Host binary that supplies the schema and runs the block
install="github:lmctl-ai/lmfluid@latest"Release that lmscript downloads into its tool cache when the host is missing
run_lmcode(prog)Run the compiled block; returns the result map
lmscript --check FILE.lmsCompile blocks without running; needs the host schema cached by an earlier real run

Context objects

NameTypeDescription
fluidFluidThe only context object. The schema declares no free host functions; everything is a method of fluid or of an object it returns

Host types and methods

Signatures are quoted from the host schema. Parameter names in descriptions follow the repository documentation; the schema itself records only types.

Fluid

Type of the context object fluid: factory for every other type, plus helpers.

MethodSignaturesDescription
rect(int, int, float, float) -> MeshQuadrilateral mesh of nx by ny elements on a rectangle lx by ly; boundary attributes 1 bottom, 2 right, 3 top, 4 left
box(int, int, int, float, float, float) -> MeshHexahedral mesh of nx by ny by nz elements on a box lx by ly by lz; attributes 1 bottom, 2 front, 3 right, 4 back, 5 left, 6 top
load_mesh(string) -> MeshRead an MFEM mesh v1.0 or v1.2 text file; validated before parsing, other formats rejected
poisson(Mesh, int) -> ProblemProblem -div(k grad u) = f on the mesh with H1 elements of the given order (1 to 3)
heat(Mesh, int) -> ProblemProblem u_t - div(k grad u) = f, integrated by backward Euler; order 1 to 3
elasticity(Mesh, int) -> ProblemIsotropic linear elasticity problem (plane strain in 2D); order 1 to 3
channel(int, int, float, float) -> LBMD2Q9 simulation nx by ny, viscosity nu, body acceleration g along x; periodic in x, walls at bottom and top; g must be finite and within ±0.02
cavity(int, int, float, float) -> LBMD2Q9 lid-driven cavity nx by ny, viscosity nu, lid speed; magnitude of the lid speed must be below 0.2
periodic(int, int, float) -> LBMD2Q9 simulation nx by ny, viscosity nu, periodic in both directions
assert_close(float, float, float) -> voidFail the run unless the first two values differ by at most the absolute tolerance; message assert_close failed: a vs b
assert_true(bool) -> voidFail the run with assert_true failed when the condition is false
matrix(int, int) -> MatrixZero matrix of rows by cols for recording results; at most 10 million entries
eval(string) -> floatEvaluate an expression string to a float; the result must be finite
print(string) -> voidWrite a line of text to stderr

Mesh

A quadrilateral or hexahedral mesh.

MethodSignaturesDescription
dimension() -> intSpace dimension of the mesh, 2 or 3
elements() -> intNumber of elements
save(string) -> voidWrite the mesh as an MFEM mesh text file that load_mesh can read

Problem

A finite-element problem builder. Every builder method returns the problem, so calls chain.

MethodSignaturesDescription
diffusion(string) -> ProblemScalar coefficient k as an expression; must be finite and positive where evaluated
source(string) -> ProblemScalar source f as an expression
initial(string) -> ProblemInitial condition for a heat problem at t = 0
dirichlet(int, string) -> ProblemScalar essential boundary data on a boundary attribute; attribute 0 selects all boundaries
displacement(int, string, string, string) -> ProblemVector essential boundary data ux, uy, uz on an attribute (all components); the third expression is unused in 2D
force(string, string, string) -> ProblemBody force expressions fx, fy, fz for elasticity; the third is unused in 2D
lame(float, float) -> ProblemLamé parameters lambda and mu of the isotropic material
tol(float, int) -> ProblemRelative tolerance and maximum iterations of the iterative linear solver
solve() -> FieldSolve a steady Poisson or elasticity problem and return the field
evolve(float, float) -> FieldAdvance a heat problem from t = 0 to end_time with step dt and return the final field

Field

A computed finite-element solution. It owns its mesh and space.

MethodSignaturesDescription
value(float, float) -> float; (float, float, float, int) -> floatValue at a mesh point: (x, y) reads component 0 in 2D; (x, y, z, component) takes a zero-based component. Points outside the mesh fail
gradient(float, float, int) -> float; (float, float, float, int, int) -> floatDerivative at a point along direction 0 (x), 1 (y) or 2 (z): (x, y, direction), or (x, y, z, component, direction)
l2_error(string) -> floatIntegrated L2 error of a scalar field against an exact expression
l2_error_vector(string, string, string) -> floatIntegrated L2 error of a vector field against exact expressions ex, ey, ez
sample(int, int) -> Matrix; (int, int, int) -> MatrixSample the bounding box on an nx by ny (by nz) grid; columns x, y, z, u or x, y, z, ux, uy and uz when present
dofs() -> intNumber of degrees of freedom of the solution
components() -> intNumber of solution components (1 for scalar problems)
time() -> floatTime of the field; the end time for a heat solution

LBM

A D2Q9 lattice-Boltzmann simulation in lattice units. Cell indices are zero-based.

MethodSignaturesDescription
init(string, string) -> LBMSet the velocity field from expressions ux, uy at cell centres; resets density to one, time to zero and the force average
run(int) -> LBMAdvance the given number of lattice steps (0 to 10 million per call) from the current state
velocity(int, int, int) -> floatVelocity component 0 (x) or 1 (y) at cell (ix, iy)
density(int, int) -> floatDensity at cell (ix, iy)
mass() -> floatTotal mass over fluid cells
max_speed() -> floatLargest speed over fluid cells
kinetic_energy() -> floatKinetic energy over fluid cells
steps() -> intNumber of steps taken since construction or the last init
sample() -> MatrixMatrix with one row per cell: x, y, rho, ux, uy, speed at centres ix+0.5, iy+0.5
obstacle(string) -> LBMMark cells whose centre gives expression > 0 as solid (no-slip, halfway bounceback); calls add up; at least one fluid cell must remain
is_solid(int, int) -> boolWhether cell (ix, iy) is solid
solid_cells() -> intNumber of solid cells
solid_force(int) -> floatMomentum-exchange force component 0 or 1 on all solid cells, averaged over the last run call
tau() -> floatRelaxation time 0.5 + 3 nu
mach() -> floatMach number of the largest speed
vorticity() -> MatrixMatrix with columns x, y, omega, solid (central differences, no-slip walls)

Matrix

A dense table of floats with zero-based indices.

MethodSignaturesDescription
rows() -> intNumber of rows
cols() -> intNumber of columns
get(int, int) -> floatEntry at zero-based (row, col)
set(int, int, float) -> MatrixSet a finite entry at zero-based (row, col); returns the matrix
save_csv(string) -> voidWrite headerless CSV with 17 significant digits; overwrites the path

Enumerated values

The schema defines no enum types. These integer and string arguments take a fixed set of values.

ArgumentValues
Finite-element order1, 2 or 3
Boundary attribute0 for all boundaries; rect: 1 bottom, 2 right, 3 top, 4 left; box: 1 bottom, 2 front, 3 right, 4 back, 5 left, 6 top; imported meshes: their own attributes, 1 to 100000
Field componentZero-based: 0 for scalar fields; 0, 1 and, in 3D, 2 for displacement
Gradient direction0 x, 1 y, 2 z; must be below the mesh dimension
LBM velocity and force component0 x, 1 y
Problem kindChosen by the constructor: poisson, heat or elasticity

Expression strings

ItemSupported
Variablesx, y, z, t (z is 0 in 2D; lattice x and y are cell centres ix+0.5, iy+0.5)
ConstantsNumbers and pi
OperatorsArithmetic and the power operator ^
Functionssin, cos, exp, log, sqrt, abs, min, max, sign and similar elementary functions
ConstraintsResults must be finite; diffusion must be positive; an obstacle expression is solid where it is greater than 0

CSV layouts

SourceColumnsRows
Scalar field.samplex, y, z, uOne per grid point of the bounding box
Elasticity field.samplex, y, z, ux, uy and, in 3D, uzOne per grid point
flow.samplex, y, rho, ux, uy, speedOne per lattice cell
flow.vorticityx, y, omega, solidOne per lattice cell
fluid.matrixWhatever the script setAs created

Files have no header, deterministic order and 17 significant digits.

Limits and diagnostics

LimitValueMessage when exceeded
Total memory4096 MiB by default (LMFLUID_MAX_MEMORY_MB)memory budget exceeded, naming the variable; exit 3
Objects per arena100000 each for meshes, problems, fields, simulations, matricesobject limit exceeded
Finite-element order1 to 3FEM order outside allowed range
Mesh elements100000mesh element limit exceeded
Degrees of freedom1 million
Sample points5 million
fluid.matrix entries10 millionmatrix exceeds 10 million entries
Lattice sizeAt least 3 by 3, at most 1 million cellsLBM grid must be at least 3 by 3; LBM grid exceeds 1 million cells
Steps per run call0 to 10 millionLBM steps must be between 0 and 10000000
Channel accelerationFinite, within ±0.02LBM acceleration must be finite and within +/-0.02
Lid speedFinite, magnitude below 0.2LBM lid speed must be finite and have magnitude below 0.2
ViscosityFinite and positiveLBM viscosity must be finite, positive, and representable in tau
Flow speedError at 0.45 or a non-finite value; stderr warning above Mach 0.3; stderr warning when tau is below 0.51LBM became numerically unstable
Point queriesInside the meshpoint is outside mesh
Matrix accessIndices in range, finite valuesMatrix index outside range; Matrix value must be finite

Standard library (lmcode_std_v3)

lmfluid 0.2.2 vendors the lmcode-cpp SDK at the commit pinned in sdk.lock (93bddf1) and registers its standard library by default. The vendored schema fragment is named lmcode_std_v3 and has 206 canonical signatures: 83 function signatures and 123 method signatures on 16 standard types. They are available in every lmfluid block without a declaration, alongside the fluid context, and appear in lmfluid --lmcode-signatures.

In lmfluid programs the most useful groups are the result sink (return numbers to the outer script without a file), the float and string collections (collect values in a loop), the string functions (build expression strings and file names), and the file functions. The file functions add no sandbox: relative paths resolve against the working directory and writes overwrite.

Function groups

GroupSignaturesPurpose
String17Byte-string search, slicing, case, split, replace, numeric parsing and glob match
Encoding4Base64 and hexadecimal encode and decode
Math16Integer and float overloads of abs, ceil, floor, max, min, pow, round and sqrt
File5Unrestricted whole-file byte read, write, append, existence test and LF line split
Collection constructors15Create empty lists, maps, queues, stacks and priority queues of int, float and string
JSON and templates2Parse JSON text into a Json value; render a text template from a Json value
Result sink24Set the value that run_lmcode returns as result: one value, or named fields
Collection and Json methods123Methods of the 16 standard types listed below
Total20683 function signatures plus 123 method signatures

Standard functions

GroupFunctionSignatures
Stringstr_contains(string, string) -> bool
Stringstr_ends_with(string, string) -> bool
Stringstr_find(string, string) -> int
Stringstr_is_float(string) -> bool
Stringstr_is_int(string) -> bool
Stringstr_len(string) -> int
Stringstr_lower(string) -> string
Stringstr_match(string, string) -> bool
Stringstr_repeat(string, int) -> string
Stringstr_replace(string, string, string) -> string
Stringstr_split(string, string) -> StrList
Stringstr_starts_with(string, string) -> bool
Stringstr_substr(string, int, int) -> string
Stringstr_to_float(string) -> float
Stringstr_to_int(string) -> int
Stringstr_trim(string) -> string
Stringstr_upper(string) -> string
Encodingstr_base64_encode(string) -> string
Encodingstr_base64_decode(string) -> string
Encodingstr_hex_encode(string) -> string
Encodingstr_hex_decode(string) -> string
Mathmath_abs(int) -> int; (float) -> float
Mathmath_ceil(int) -> int; (float) -> float
Mathmath_floor(int) -> int; (float) -> float
Mathmath_max(int, int) -> int; (float, float) -> float
Mathmath_min(int, int) -> int; (float, float) -> float
Mathmath_pow(int, int) -> int; (float, float) -> float
Mathmath_round(int) -> int; (float) -> float
Mathmath_sqrt(int) -> int; (float) -> float
Filefile_append(string, string) -> void
Filefile_exists(string) -> bool
Filefile_lines(string) -> StrList
Filefile_read(string) -> string
Filefile_write(string, string) -> void
Collection constructorsfloat_list() -> FloatList
Collection constructorsfloat_map() -> FloatMap
Collection constructorsfloat_pq() -> FloatPQ
Collection constructorsfloat_queue() -> FloatQueue
Collection constructorsfloat_stack() -> FloatStack
Collection constructorsint_list() -> IntList
Collection constructorsint_map() -> IntMap
Collection constructorsint_pq() -> IntPQ
Collection constructorsint_queue() -> IntQueue
Collection constructorsint_stack() -> IntStack
Collection constructorsstr_list() -> StrList
Collection constructorsstr_map() -> StrMap
Collection constructorsstr_pq() -> StrPQ
Collection constructorsstr_queue() -> StrQueue
Collection constructorsstr_stack() -> StrStack
JSON and templatesjson_parse(string) -> Json
JSON and templatestemplate_render(string, Json) -> string
Result sinklmcode_return_null() -> void
Result sinklmcode_return_put(string, bool) -> void; (string, float) -> void; (string, FloatList) -> void; (string, FloatMap) -> void; (string, int) -> void; (string, IntList) -> void; (string, IntMap) -> void; (string, Json) -> void; (string, StrList) -> void; (string, StrMap) -> void; (string, string) -> void
Result sinklmcode_return_put_null(string) -> void
Result sinklmcode_return_set(bool) -> void; (float) -> void; (FloatList) -> void; (FloatMap) -> void; (int) -> void; (IntList) -> void; (IntMap) -> void; (Json) -> void; (StrList) -> void; (StrMap) -> void; (string) -> void

Standard types and methods

TypeMethodSignature
FloatListadd(float) -> FloatList
FloatListat(int) -> float
FloatListclear() -> FloatList
FloatListcontains(float) -> bool
FloatListindex_of(float) -> int
FloatListlen() -> int
FloatListset(int, float) -> FloatList
FloatMaplen() -> int
FloatMaphas(string) -> bool
FloatMapget(string) -> float
FloatMapget_or(string, float) -> float
FloatMapset(string, float) -> FloatMap
FloatMapkey_at(int) -> string
FloatMapremove(string) -> bool
FloatMapclear() -> FloatMap
FloatMapkeys() -> StrList
FloatMapvalues() -> FloatList
FloatPQpush(float, float) -> FloatPQ
FloatPQpop() -> float
FloatPQpeek() -> float
FloatPQlen() -> int
FloatPQempty() -> bool
FloatPQclear() -> FloatPQ
FloatQueuepush(float) -> FloatQueue
FloatQueuepop() -> float
FloatQueuepeek() -> float
FloatQueuelen() -> int
FloatQueueempty() -> bool
FloatQueueclear() -> FloatQueue
FloatQueueat(int) -> float
FloatStackpush(float) -> FloatStack
FloatStackpop() -> float
FloatStackpeek() -> float
FloatStacklen() -> int
FloatStackempty() -> bool
FloatStackclear() -> FloatStack
FloatStackat(int) -> float
IntListadd(int) -> IntList
IntListat(int) -> int
IntListclear() -> IntList
IntListcontains(int) -> bool
IntListindex_of(int) -> int
IntListlen() -> int
IntListset(int, int) -> IntList
IntMaplen() -> int
IntMaphas(string) -> bool
IntMapget(string) -> int
IntMapget_or(string, int) -> int
IntMapset(string, int) -> IntMap
IntMapkey_at(int) -> string
IntMapremove(string) -> bool
IntMapclear() -> IntMap
IntMapkeys() -> StrList
IntMapvalues() -> IntList
IntPQpush(int, float) -> IntPQ
IntPQpop() -> int
IntPQpeek() -> int
IntPQlen() -> int
IntPQempty() -> bool
IntPQclear() -> IntPQ
IntQueuepush(int) -> IntQueue
IntQueuepop() -> int
IntQueuepeek() -> int
IntQueuelen() -> int
IntQueueempty() -> bool
IntQueueclear() -> IntQueue
IntQueueat(int) -> int
IntStackpush(int) -> IntStack
IntStackpop() -> int
IntStackpeek() -> int
IntStacklen() -> int
IntStackempty() -> bool
IntStackclear() -> IntStack
IntStackat(int) -> int
Jsonkind() -> string
Jsonlen() -> int
Jsonat(int) -> Json
Jsonget(string) -> Json
Jsonhas(string) -> bool
Jsonkeys() -> StrList
Jsonas_string() -> string
Jsonas_int() -> int
Jsonas_float() -> float
Jsonas_bool() -> bool
Jsonto_json() -> string
StrListadd(string) -> StrList
StrListat(int) -> string
StrListclear() -> StrList
StrListcontains(string) -> bool
StrListindex_of(string) -> int
StrListjoin(string) -> string
StrListlen() -> int
StrListset(int, string) -> StrList
StrMapclear() -> StrMap
StrMapget(string) -> string
StrMapget_or(string, string) -> string
StrMaphas(string) -> bool
StrMapkey_at(int) -> string
StrMaplen() -> int
StrMapremove(string) -> bool
StrMapset(string, string) -> StrMap
StrMapkeys() -> StrList
StrMapvalues() -> StrList
StrPQpush(string, float) -> StrPQ
StrPQpop() -> string
StrPQpeek() -> string
StrPQlen() -> int
StrPQempty() -> bool
StrPQclear() -> StrPQ
StrQueuepush(string) -> StrQueue
StrQueuepop() -> string
StrQueuepeek() -> string
StrQueuelen() -> int
StrQueueempty() -> bool
StrQueueclear() -> StrQueue
StrQueueat(int) -> string
StrStackpush(string) -> StrStack
StrStackpop() -> string
StrStackpeek() -> string
StrStacklen() -> int
StrStackempty() -> bool
StrStackclear() -> StrStack
StrStackat(int) -> string

Standard REST and CLI interfaces (current catalog, not yet in this host)

The current lmcode_std_v3 catalog in lmcode-cpp has 226 canonical signatures. The 20 signatures beyond the 206 that lmfluid vendors are the former lmcode_std_rest_v1 module: 5 functions and 15 RestExchange methods, together with 10 standard interfaces. lmfluid does not ship them yet; it picks them up when it syncs its pinned lmcode-cpp SDK and publishes a release. Until then a lmfluid program that calls rest_route or declares a RestGet handler does not compile against the lmfluid schema.

InterfaceSignatureRole
RestGet(RestExchange exchange) -> voidHandler for GET routes
RestPost(RestExchange exchange) -> voidHandler for POST routes
RestPut(RestExchange exchange) -> voidHandler for PUT routes
RestDelete(RestExchange exchange) -> voidHandler for DELETE routes
RestPatch(RestExchange exchange) -> voidHandler for PATCH routes
RestHead(RestExchange exchange) -> voidHandler for HEAD routes
RestOptions(RestExchange exchange) -> voidHandler for OPTIONS routes
RestHandler(RestExchange exchange) -> voidGeneric handler bound by rest_route to an annotation name
CliCommand(RestExchange exchange) -> voidHandler for a command dispatched by rest_cli
CliOption(RestExchange exchange) -> voidHandler for an option dispatched by rest_cli
FunctionSignatureBehavior
rest_config(string, string) -> voidStore a configuration key and value; the keys prefix and base_path set the route prefix and max_body_bytes sets the request body limit
rest_route(string, string, string) -> voidRegister method, path template and handler annotation; templates accept {param} and {rest...} or :param and :rest... placeholders
rest_serve() -> voidRequest serving after the program body; routes are frozen from this call on
rest_stop() -> voidStop serving
rest_cli(StrList) -> stringStateless CLI mode: dispatch an argument vector to options, commands and REST routes and return the response text
RestExchange methodSignatureBehavior
method() -> stringRequest method
path() -> stringRequest path
query(string) -> stringQuery parameter value, empty when absent
has_query(string) -> boolWhether a query parameter is present
param(string) -> stringRoute template parameter value, empty when absent
header(string) -> stringRequest header value; repeated headers are joined with a comma and a space
has_header(string) -> boolWhether a request header is present
body() -> stringRequest body bytes
status(int) -> voidSet the response status; values outside 200..599 are a host error
set_header(string, string) -> voidSet a response header; Content-Length, Connection and Transfer-Encoding are managed by the server
send(string) -> voidSet the response body
json(string) -> voidSet the response body and the Content-Type application/json
get(string) -> stringRead a shared state value, empty when absent
set(string, string) -> voidWrite a shared state value
increment(string) -> intIncrement a shared named counter and return it