Learn

Contents

eLucid8 from Python

The elucid8 package runs eLucid8 programs from a Python script or notebook, with pandas or Polars DataFrames and pyarrow tables in and out. You write no configuration file and read no output file by hand: give it a program and your data, and it gives you a table. Every answer is exactly what the elucid8 command gives, because the package runs that command: elucid8 run for one run, and elucid8 serve for a program kept loaded.

Status: the package is on the Python Package Index as elucid8, from release 0.18.0, with the elucid8 command for every platform the Download page offers. The programs on this page are in the notation the package reads from 0.20.0 (input(…) and output(…), with x[t = 4] and restrict … end from 0.19.0); python3 -m pip install --upgrade elucid8 gets the newest.

Installing it

From the Python Package Index, with pandas, which the examples on this page use:

python3 -m pip install "elucid8[pandas]"

It needs Python 3.9 or later and installs pyarrow. pandas and Polars are optional: the package uses them when they are installed (python3 -m pip install elucid8 alone installs neither; "elucid8[polars]" adds Polars).

The package carries the elucid8 command for macOS (Apple silicon and Intel), Linux (x86-64 and ARM64, any distribution) and Windows (x86-64), the same files the Download page offers, so nothing else needs installing. To use another copy of the command, set ELUCID8_BIN to its path. Installing the package also puts the command on your PATH, as elucid8.

For an AI assistant working in a sandbox (from 0.26.0): elucid8.guide() returns the guide to eLucid8 for AI agents, the text https://elucid8-lang.org/llms-full.txt serves, from the bundled command with no network (elucid8.guide(short=True) the short one, https://elucid8-lang.org/llms.txt); python -m elucid8 guide prints it.

On Linux with glibc, the package also carries the desktop build, which opens windows: elucid8 window, elucid8 gallery and elucid8 playground use it on computers with glibc 2.35 or later and WebKitGTK 4.1 (sudo apt install libwebkit2gtk-4.1-0 on Debian and Ubuntu, webkit2gtk4.1 on Fedora, webkit2gtk-4.1 on Arch).

A first run

import pandas as pd

import elucid8

pd.set_option("display.max_columns", None, "display.width", 120, "display.max_colwidth", None)
program = """
x = input("x", t : inf)
running = x fby.t (running + next.t x)
ratio = running / x
"""
x = pd.DataFrame({"t": [0, 1, 2, 3, 4, 5], "value": [3, 1, 4, 0, 5, 9]})

table = elucid8.run(program, {"x": x}, query="ratio[t = 2..6]")
print(table)
print(elucid8.tidy(table))
   t  ratio_value ratio_kind ratio_error  ratio_origin     ratio_message  ratio_ts ratio_trail
0  2     2.000000      value         NaN           NaN               NaN         0         NaN
1  3          NaN      error    division  ratio[t = 3]  division by zero         0         NaN
2  4     2.600000      value         NaN           NaN               NaN         0         NaN
3  5     2.444444      value         NaN           NaN               NaN         0         NaN
4  6          NaN        eod         NaN           NaN               NaN         0         NaN
   t  ratio_value ratio_kind ratio_error  ratio_origin     ratio_message  ratio_ts
0  2     2.000000      value         NaN           NaN               NaN         0
1  3          NaN      error    division  ratio[t = 3]  division by zero         0
2  4     2.600000      value         NaN           NaN               NaN         0
3  5     2.444444      value         NaN           NaN               NaN         0
4  6          NaN        eod         NaN           NaN               NaN         0

Programs and plans

elucid8.run and elucid8.Service take a program's text, a path to a program (.el8) or a plan (.json), or a plan from elucid8.compile:

import elucid8

plan = elucid8.compile('x = input("x", t : 10)\ntwice = 2 * x\n')
print("plan version", plan.data["planVersion"])
plan.save("twice-plan.json")
table = elucid8.run("twice-plan.json", {"x": {"t": [0, 1], "value": [1.5, 4]}}, query="twice[t = 0..1]", as_="arrow")
print(table.column("twice_value").to_pylist())
plan version 26
[3.0, 8.0]

Which compiler. By default elucid8.compile uses the compiler in the elucid8 command (elucid8 compile), which the wheels bundle: offline, with no Node.js and no network. Two others can be chosen:

compilerwhenhow
the command's ("builtin")by defaultelucid8 compile, offline; the plan the reference compiler gives, byte for byte, but for its engineVersion (elucid8-rs/…), which names the compiler
the website's ("web")compiler="web"the program's text is sent to https://elucid8-lang.org/api/compile, which answers with the plan; it needs the network, and up to 30 programs a minute from one address
a local one ("local")compiler="local"the reference compiler in a copy of the eLucid8 repository, on Node.js 24: set ELUCID8_COMPILER to the path of packages/evaluator/bin/elucid8-compile.ts

elucid8.which_compiler() says which one a call will use. A program that does not compile raises CompileError, with the compiler's message, line and column.

Data in

Give each input the program reads, by its channel (input("x", t : 10) reads channel x; the name of the value that reads it works too):

whatread as
a pandas DataFrameits columns: one per dimension, value, and optionally ts. A named index (df.set_index(["t", "x"])) counts as columns. A missing value (None, NaN, pd.NA) is missing data, an error of kind missing (fill={"missing": 0} reads it as 0)
a Polars DataFrameits columns; a null is missing data, an error of kind missing, as in pandas (a Polars NaN is the number NaN)
a pyarrow Table or RecordBatch, a dict of columns, a list of rowsthe same columns
a path to a .csv, .jsonl, .parquet, .arrows or .arrow filethe file, read by the command as its data files are
elucid8.Input(data, time=…, value=…, fill=…, names=…, row=…, wide=…, columns=…, kinds=…)the data with the options of an input's entry (inputs): time="ms" names its time column, value="price" the column of its values, fill={"missing": 0} reads a point the data do not list inside the input's bound, or a missing value, as 0 instead of missing data, an error of kind missing (any number, boolean or text in place of 0; past the end of the data a point is eod whatever fill says), row="i" reads each row's position (0 for the first) as the input's dimension i, for a table with no column for it (A file with no column for its rows), wide="quantity" reads the names of its value columns as that dimension's coordinates
an entry, as deploy.json writes one ({"from": "x.csv", "time": "ts"})that entry; also an input answered on demand, {"from": {"builtin": "simulated", "answer": "score"}, "deadlineMs": 200} (Inputs answered on demand)
elucid8.connector("postgres", {"table": "readings"}, env=["DATABASE_URL"])the rows a connector reads from another system, here a PostgreSQL table (pip install "elucid8[postgres]"); the command runs the connector with this Python

Tables are written as an Arrow file for the command; a table holding an elucid8.Error is written as JSON lines, since Arrow has no cell for an error.

Timestamps, eod and errors in data. A column ts holds each row's timestamp in milliseconds; elucid8.Error("…") puts an error in a value column. A missing value (None, NaN) is missing data, an error of kind missing, as is a point inside the input's bound that the data do not list; for counts, where no value means nothing happened, elucid8.Input(…, fill={"missing": 0}) reads both as 0, as here:

import pandas as pd

import elucid8

program = """
visits = input("visits", t : 6)
change = visits - visits[t = #t - 1]
"""
visits = pd.DataFrame({
    "t": [0, 1, 2, 3, 4],
    "value": [12, 15, elucid8.Error("counter fault"), 9, None],
    "ts": [1000, 2000, 3000, 4000, 5000],
})
print(elucid8.tidy(elucid8.run(program, {"visits": elucid8.Input(visits, fill={"missing": 0})}, query="change[t = 1..5]")).to_string())
   t  change_value change_kind change_error  change_origin change_message  change_ts
0  1           3.0       value          NaN            NaN            NaN       2000
1  2           NaN       error         data  visits[t = 2]  counter fault       3000
2  3           NaN       error         data  visits[t = 2]  counter fault       4000
3  4          -9.0       value          NaN            NaN            NaN       5000
4  5           0.0       value          NaN            NaN            NaN       5000

.to_string() prints every column. A plain print shows ... where a table is wider than its display: choose the columns you want (table[["t", "change_value", "change_error"]]) or set pandas' display options, as A first run does (pd.set_option("display.max_columns", None, "display.width", 120)).

The missing value at t = 4 reads 0 at its row's time, and t = 5, which has no row, reads 0 too. Without fill, both are missing data: change_kind is error, change_error is missing, and change_message says input visits has no data at this point. An answer's timestamp is the time of the newest data it read (Values and timestamps); the error names where it started.

Names. A dimension whose coordinates are texts (Tutorial, section 17) is read from a column of names; a dimension with a name map takes names={"sym": {"AAPL": 0, "MSFT": 1}} (a dict, a list of names numbered from 0, or a map file's path), and its answers come back with the names. An input with no dimensions (rate = input("rate")) is a table of one row with a value column.

Other sections of the configuration, names and options, are arguments of the same names, as deploy.json writes them (Command reference); threads= limits the threads. config= starts from a deploy.json you have (elucid8-deploy/2): its paths keep their meaning, and the arguments are added to it. Programs and connectors given in the call (elucid8.connector(…), an entry with "process", in inputs or in config= as a dict) are started without asking, since your code names them; those a deploy.json file given as config= names are started only with allow_programs=True (or your yes recorded in .elucid8-allowed beside it), so read it first (Programs need your permission). elucid8.Service takes the same allow_programs. An output with "outside": true is refused when config= is a dict, and when it is a file without your yes recorded in .elucid8-allowed beside it (elucid8 run at a terminal asks and records it), as elucid8 run refuses it without --allow-outside (Is it safe to run?).

Answers out

With Polars, names as coordinates and an output channel the program writes:

import polars as pl

import elucid8

program = """
sales = input("sales", zone : {"north", "south", "east"}, month : 3)
total = restrict sum sales over (zone : {"north", "south", "east"}) end to (month : 3) end
growth = sales - sales[month = #month - 1]
output("by_month") = total
"""
sales = pl.DataFrame({
    "zone": ["north", "south", "east", "north", "south", "east", "north"],
    "month": [0, 0, 0, 1, 1, 1, 2],
    "value": [10.0, 12.0, 7.0, 11.0, 15.0, 6.5, 12.5],
})
out = elucid8.run(program, {"sales": sales}, as_="polars")
print(elucid8.tidy(out["by_month"]))
growth = elucid8.run(program, {"sales": sales}, query='growth[zone = {"north", "east"}, month = 1..2]', as_="polars")
print(elucid8.tidy(growth))
shape: (3, 7)
┌───────┬───────────────┬───────────────┬──────────────┬──────────────┬──────────────┬─────────────┐
│ month ┆ by_month_valu ┆ by_month_kind ┆ by_month_err ┆ by_month_ori ┆ by_month_mes ┆ by_month_ts │
│ ---   ┆ e             ┆ ---           ┆ or           ┆ gin          ┆ sage         ┆ ---         │
│ i64   ┆ ---           ┆ cat           ┆ ---          ┆ ---          ┆ ---          ┆ i64         │
│       ┆ f64           ┆               ┆ cat          ┆ str          ┆ str          ┆             │
╞═══════╪═══════════════╪═══════════════╪══════════════╪══════════════╪══════════════╪═════════════╡
│ 0     ┆ 29.0          ┆ value         ┆ null         ┆ null         ┆ null         ┆ 0           │
│ 1     ┆ 32.5          ┆ value         ┆ null         ┆ null         ┆ null         ┆ 0           │
│ 2     ┆ 12.5          ┆ value         ┆ null         ┆ null         ┆ null         ┆ 0           │
└───────┴───────────────┴───────────────┴──────────────┴──────────────┴──────────────┴─────────────┘
shape: (4, 8)
┌───────┬───────┬──────────────┬─────────────┬─────────────┬─────────────┬─────────────┬───────────┐
│ zone  ┆ month ┆ growth_value ┆ growth_kind ┆ growth_erro ┆ growth_orig ┆ growth_mess ┆ growth_ts │
│ ---   ┆ ---   ┆ ---          ┆ ---         ┆ r           ┆ in          ┆ age         ┆ ---       │
│ str   ┆ i64   ┆ f64          ┆ cat         ┆ ---         ┆ ---         ┆ ---         ┆ i64       │
│       ┆       ┆              ┆             ┆ cat         ┆ cat         ┆ cat         ┆           │
╞═══════╪═══════╪══════════════╪═════════════╪═════════════╪═════════════╪═════════════╪═══════════╡
│ north ┆ 1     ┆ 1.0          ┆ value       ┆ null        ┆ null        ┆ null        ┆ 0         │
│ north ┆ 2     ┆ 1.5          ┆ value       ┆ null        ┆ null        ┆ null        ┆ 0         │
│ east  ┆ 1     ┆ -0.5         ┆ value       ┆ null        ┆ null        ┆ null        ┆ 0         │
│ east  ┆ 2     ┆ null         ┆ error       ┆ missing     ┆ sales[zone  ┆ input sales ┆ 0         │
│       ┆       ┆              ┆             ┆             ┆ = "east",   ┆ has no data ┆           │
│       ┆       ┆              ┆             ┆             ┆ month = 2…  ┆ at thi…     ┆           │
└───────┴───────┴──────────────┴─────────────┴─────────────┴─────────────┴─────────────┴───────────┘

total at month 2 is 12.5: only the north reported for it, and an aggregate leaves out missing data and says how many points it left out (here a warning, Elucid8Warning, that 2 missing points of sales were left out). growth in the east at month 2 is an error of kind missing: the east has no row there.

A table with a column per quantity, and the warm readings only, with pandas:

import pandas as pd

import elucid8

program = """
readings = input("readings", t : 4, quantity : {"temperature", "humidity"})
warm = if readings > 20 then readings else eod
output("table") = readings
output("warm") = warm
"""
readings = pd.DataFrame({
    "t": [0, 0, 1, 1, 2, 2, 3, 3],
    "quantity": ["temperature", "humidity"] * 4,
    "value": [18.5, 40.0, 21.5, 35.0, 19.0, 42.0, 22.0, 38.0],
})
out = elucid8.run(program, {"readings": readings}, outputs={"table": {"wide": "quantity"}, "warm": {"skip": "eod"}}, timestamps=False)
print(out["table"][["t", "temperature", "humidity"]])
print(elucid8.tidy(out["warm"]))
   t  temperature  humidity
0  0         18.5      40.0
1  1         21.5      35.0
2  2         19.0      42.0
3  3         22.0      38.0
      quantity  t  warm_value warm_kind warm_error warm_origin warm_message
0     humidity  0        40.0     value        NaN        None         None
1     humidity  1        35.0     value        NaN        None         None
2     humidity  2        42.0     value        NaN        None         None
3     humidity  3        38.0     value        NaN        None         None
4  temperature  1        21.5     value        NaN        None         None
5  temperature  3        22.0     value        NaN        None         None

table comes back in the shape a spreadsheet has, a row per t; warm holds only the readings above 20, each at its own point, the temperatures at t = 0 and 2 left out. Each column of table also has its _kind, _error, _origin, _message and _trail beside it (temperature_kind, …, and temperature_ts without timestamps=False), as Arrow and Parquet write them.

Lists, records and sets

From 0.23.0. A value may be a list, record or set. In Python a list is a list, a record a dict of its fields and a set a frozenset (frozen, so that a set can hold sets); inside a set a list is a tuple and a record an elucid8.FrozenRecord, a dict that cannot change, since a Python set holds only values that do not. Numbers inside are floats, with −0, NaN and the infinities kept.

Given to run or Service, lists, tuples, dicts with text keys, sets and frozensets in a table's cells are written as the command reads them: an input holding one is written as JSON lines, the only data files collections are read from. A dict whose keys are not all texts, or a collection holding None, is refused with a message saying so.

import polars as pl

import elucid8

program = """
order = input("order", t : 3)
cost = order.qty * order.price
sizes = elements(order.sizes)
small = those s from order.sizes if s < 3 end
"""
orders = [
    {"t": 0, "value": {"qty": 2, "price": 3.5, "sizes": [1, 2, 2]}},
    {"t": 1, "value": {"qty": 1, "price": 10.0, "sizes": [4]}},
    {"t": 2, "value": {"qty": 3, "price": 2.0, "sizes": []}},
]
print(elucid8.tidy(elucid8.run(program, {"order": orders}, query="cost[t = 0..2]", timestamps=False)))
sizes = elucid8.run(program, {"order": orders}, query="sizes[t = 0..2]", timestamps=False)
print(list(sizes["sizes_value"]))
print(elucid8.tidy(elucid8.run(program, {"order": orders}, query="small[t = 0..2]", as_="polars", timestamps=False)))
   t  cost_value cost_kind cost_error cost_origin cost_message
0  0         7.0     value        NaN         NaN          NaN
1  1        10.0     value        NaN         NaN          NaN
2  2         6.0     value        NaN         NaN          NaN
[frozenset({1.0, 2.0}), frozenset({4.0}), frozenset()]
shape: (3, 6)
┌─────┬─────────────────┬────────────┬─────────────┬──────────────┬───────────────┐
│ t   ┆ small_value     ┆ small_kind ┆ small_error ┆ small_origin ┆ small_message │
│ --- ┆ ---             ┆ ---        ┆ ---         ┆ ---          ┆ ---           │
│ i64 ┆ list[f64]       ┆ cat        ┆ cat         ┆ cat          ┆ cat           │
╞═════╪═════════════════╪════════════╪═════════════╪══════════════╪═══════════════╡
│ 0   ┆ [1.0, 2.0, 2.0] ┆ value      ┆ null        ┆ null         ┆ null          │
│ 1   ┆ []              ┆ value      ┆ null        ┆ null         ┆ null          │
│ 2   ┆ []              ┆ value      ┆ null        ┆ null         ┆ null          │
└─────┴─────────────────┴────────────┴─────────────┴──────────────┴───────────────┘

In pandas a value column of collections is a column of Python values. In Polars and pyarrow it is a nested column when every value in it has one shape (here list[f64]; a record is a struct, a set a list of its elements in eLucid8's order); otherwise, as for values of mixed types, each value's JSON text, the form JSON lines write (a list as a JSON array, a record as {"record": {…}}, a set as {"set": […]}). elucid8.to_xarray holds each collection as its JSON text, as a Zarr store would hold text.

As an xarray dataset

From 0.19.0. elucid8.to_xarray turns a query's table, or an output's records, into an xarray dataset over the query's dimensions, with their coordinates: for a value v, v_value (NaN where a cell is not a value), v_kind (0 a value, 1 eod, 2 an error, named by its CF attributes), v_ts and, when there are errors, v_error, v_origin, v_message and v_trail (text, the empty text where a cell is not an error). It is the dataset a Zarr store of the same query gives, so matplotlib, Plotly and napari draw it as Seeing your results shows. It needs xarray (python3 -m pip install xarray):

import pandas as pd

import elucid8

program = """
reading = input("reading", t : 3, x : 4)
smooth = restrict mean reading over (x : #x - 1 .. #x + 1) end to (t : 3, x : 4) end
"""
reading = pd.DataFrame({
    "t": [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2],
    "x": [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2],
    "value": [1.0, 2.0, 4.0, 8.0, 2.0, elucid8.Error("sensor fault"), 6.0, 10.0, 3.0, 5.0, 7.0],
})
table = elucid8.run(program, {"reading": reading}, query="smooth[t = 0..2, x = 0..3]")
ds = elucid8.to_xarray(table)
print(list(ds.data_vars), dict(ds.sizes))
print(ds["smooth_value"].values.round(3))
print(ds["smooth_kind"].values)
['smooth_value', 'smooth_kind', 'smooth_ts', 'smooth_error', 'smooth_origin', 'smooth_message', 'smooth_trail'] {'t': 3, 'x': 4}
[[1.5   2.333 4.667 6.   ]
 [  nan   nan   nan 8.   ]
 [4.    5.    6.    7.   ]]
[[0 0 0 0]
 [2 2 2 0]
 [0 0 0 0]]

At t = 1 the sensor fault at x = 1 makes the three cells that read it errors; at t = 2, x = 3 has no reading, so the means that read it leave it out (with a warning saying so) and smooth at x = 3 is the mean of x = 2 alone. A table that does not hold a whole box in order is refused.

When something goes wrong

exceptionwhen
CompileErrorthe program does not compile (message, line, column)
InvalidErrorthe plan, the data, the configuration or a query is invalid; nothing was computed (the command's exit code 3)
ProgramErrora query stopped with a program error, such as the demand-depth limit; results holds what was computed before it
BinaryNotFoundno elucid8 command: none bundled (a package installed from source), no ELUCID8_BIN, none on the PATH
InvalidRequest, OverBudget, Cancelled, ServiceErrora service refused a request, a query passed its time budget or was cancelled, or the service could not be started or reached

Each carries the command's own message. Every one is an elucid8.Elucid8Error. A warning the command gives (missing data an aggregate left out) is a Python warning, elucid8.Elucid8Warning; a query that leaves out a dimension of its value is refused, an InvalidError.

import elucid8

try:
    elucid8.compile('x = input("x", t : 10)\ny = x +\n')
except elucid8.CompileError as e:
    print("does not compile:", e.line, e.column, e.message)

try:
    elucid8.run('x = input("x", t : 10)\n', {"x": {"t": [0, 1], "value": [1, 2]}}, query="y[t = 0]")
except elucid8.InvalidError as e:
    print("invalid:", e)
does not compile: 3 1 expected an expression, found "end of input"
invalid: query 1 (y): unknown value y

A program kept loaded: elucid8.Service

elucid8.Service starts elucid8 serve on a free port of this machine, over HTTP, with a token of its own, and keeps it until it is closed (at the end of a with block, by close(), or when Python exits). Queries reuse what earlier ones computed, new data arrives with advance, and a subscription answers again each time the data it reads change:

# pip install elucid8 pandas
import pandas as pd, elucid8

program = """
x = input("x", t : inf)
running = x fby.t (running + next.t x)
"""
x = pd.DataFrame({"t": [0, 1, 2, 3, 4, 5], "value": [3, 1, 4, 0, 5, 9]})

with elucid8.Service(program, {"x": x}) as service:
    print(elucid8.tidy(service.query("running[t = 3..5]")).to_string())
    newest = service.subscribe("running[t = last]")
    print("now:", next(newest).results[0]["outcome"]["value"])
    reply = service.advance("x", pd.DataFrame({"t": [6, 7], "value": [2, 8]}))
    print("advance:", reply["status"])
    answer = next(newest)
    print("after it:", answer.frame()[["t", "running_value"]].to_dict("records"))
    print("evaluations:", service.stats()["totals"]["evaluations"])
print("stopped:", service.process.poll() is not None)
   t  running_value running_kind running_error running_origin running_message  running_ts
0  3            8.0        value           NaN            NaN             NaN           0
1  4           13.0        value           NaN            NaN             NaN           0
2  5           22.0        value           NaN            NaN             NaN           0
now: 22
advance: done
after it: [{'t': 7, 'running_value': 32.0}]
evaluations: 8
stopped: True

Connecting to a service started elsewhere (for example as a service): elucid8.Service(url="http://127.0.0.1:8080", token="…"). Closing it leaves the service running.

Seeing a value play: show

From 0.19.0, elucid8.show starts a service for a program, as elucid8.Service does, and shows one of its values in the eLucid8 Player, the page the service serves: a picture, a chart or a number, played along the dimension the value iterates along, every frame an answer of the service.

import elucid8

elucid8.show("heat.el8", {"initial": "initial.csv"}, value="heat")

In a script, the browser opens on the Player and show waits, printing Showing heat at http://127.0.0.1:52811/player#k=… (Ctrl-C to stop); Ctrl-C stops the service and the script goes on. In a notebook (Jupyter, VS Code's notebooks) the Player appears in the cell's output, no browser opens, and the cell returns at once; so it does in the interactive interpreter, where the service runs until close() or Python exits.

service.show("heat") shows a value of a service already started (or connected to), and returns at once; closing that Player leaves the service running. With live=True the Player follows new data, so service.advance(...) in a later cell updates it by itself.

The link holds a read-only key: whoever has it can watch, not change the service. A notebook whose kernel runs on another machine (Colab, JupyterHub) cannot show the Player yet: it needs a browser on the same machine as Python.

Where next