#Using eLucid8 from your code
Your application asks eLucid8 for results and uses them in its own tools: Python with NumPy or pandas, JavaScript, or the shell. This page shows how, with short examples you can copy. Each one starts the elucid8 command, reads what it writes, and prints what it found; the output shown under each example is what it prints.
From Python, the elucid8 package does this for you: DataFrames in and out, no configuration file or output file to handle, and a service kept loaded with one object (eLucid8 from Python). This page shows what it does underneath, and how to do it from any language.
There are two ways to ask:
elucid8 runanswers the queries you give it and stops. Use it from a script, a scheduled job or a notebook.elucid8 servekeeps your program loaded and answers queries as they arrive, reusing what earlier queries computed. Use it from an application that asks again and again, or whose data changes while it runs.
And six forms for the answers:
| form | what it is | use it for |
|---|---|---|
| JSON lines (the default) | one line per point: the value's name, its coordinates and its outcome | anything; every detail of every error |
CSV (--format csv) | a table: a column per dimension, then a column per value asked for, running_value (and running_ts with --timestamps) | spreadsheets, pandas, the shell |
frame (--format frame) | a whole query over a box (a row, a grid, a cube) as one block: its axes, a value, a kind and a timestamp per cell, and the errors | arrays: NumPy, nested lists, JavaScript |
NumPy (--format npz) | one query's frame as a NumPy file: arrays shaped by the axes | NumPy, with no conversion |
Arrow (--format arrow) | one query's frame as an Apache Arrow table, one row per cell | pandas, Polars, DuckDB |
Parquet (--format parquet) | the same table as an Apache Parquet file | pandas, Polars, DuckDB, and files kept for later |
From 0.19.0, two more forms are for drawing: a Zarr store (--format zarr) for xarray, matplotlib, Plotly and napari, and a Vega-Lite chart (--format vega-lite) for Jupyter, VS Code and Observable (Seeing your results).
A program may also name its outputs itself (output("smooth") = smooth): records with a column per dimension and one for the value, written by elucid8 run without a query (the section Outputs named in the program, below).
The programs on this page are in the language's notation v0.2, whose plans (version 19)
elucid8runs from 0.20.0../elucid8 --versionsays which version you have.
#The two programs on this page
The running sum from the Deploy tutorial: follow its steps to get the folder running-sum, with plan.json, deploy.json, its data in data/x.csv and the elucid8 command. Its data ends at t = 5, and x is 0 at t = 3, so ratio is an error there.
A grid of readings, for frames. In the playground, paste this program:
-- Readings on a 4 × 3 grid, each smoothed with its neighbours along x.
grid = input("reading", x : 4, y : 3)
smooth = mean grid over (x : #x - 1 .. #x + 1) end
grid is the readings within the 4 × 3 grid, and eod (no data) outside it; the mean leaves out positions beyond the grid's edges, so a reading at the edge is smoothed with the neighbours it has.
Give the input reading (which the program calls grid) this table. One sensor reports a fault, and the cell at x = 0, y = 2 is written eod, so grid is eod (end of data) there:
x,y,value
0,0,10
1,0,12
2,0,14
3,0,error: sensor fault
0,1,11
1,1,13
2,1,15
3,1,17
0,2,
1,2,16
2,2,18
3,2,20
Query smooth at x = 1, y = 1 (the answer is 13), sign in, save the program with the title Readings and press Download. Unzip readings.zip and copy the elucid8 command into the folder readings, beside plan.json. In that grid, smooth is a value where every neighbour is a number, an error where a neighbour is an error (the sensor fault), and the mean of the others where a neighbour is missing (the empty cell at x = 0, y = 2: missing data, which the mean leaves out, with a warning).
Every example below says which folder to run it in. Each one runs the command as ./elucid8, the copy in that folder; if yours is elsewhere, change that one line.
#Frames, in brief
# In the readings folder:
./elucid8 run plan.json --config deploy.json --query 'smooth[y = 0..2, x = 0..3]' --format frame
{"name":"smooth","axes":[{"name":"y","range":[0,2]},{"name":"x","range":[0,3]}],"type":"number","values":[11,12,null,null,12,13,15,16,16,17,18,19],"kinds":[0,0,2,2,0,0,0,0,0,0,0,0],"kindNames":["value","eod","error"],"ts":{"axis":"y","values":[0,0,0]},"errors":{"2":{"error":"data","message":"sensor fault","origin":{"name":"reading","context":{"x":3,"y":0}},"via":{"length":1,"path":[{"name":"reading","context":{"x":3,"y":0}}]}},"3":{"error":"data","message":"sensor fault","origin":{"name":"reading","context":{"x":3,"y":0}},"via":{"length":1,"path":[{"name":"reading","context":{"x":3,"y":0}}]}}}}
axes, in the order the query names them: herey(3 rows), thenx(4 columns). Each axis has arange, both ends included.values, one per cell, the last axis varying fastest: the first four are rowy = 0. A cell that is not a value isnull.kinds, one per cell:0a value,1eod,2an error. Read them together withvalues:nullalone does not say whether a cell is eod or an error.ts: the cells' timestamps (the time of the latest data each was computed from, in milliseconds). Where every cell's timestamp is a function of its coordinate on one axis, as here (all 0:readinghas no times), it is written once per coordinate of that axis; otherwise it is a list, one per cell.errors: each error cell's position in the list, and the error. Cells 2 and 3 failed because the reading atx = 3, y = 0reported "sensor fault".type:numberwhen every value is a number (alsoboolean,jsonfor a mix,nonewhen no cell is a value).
A number JSON cannot hold (-0, NaN, Infinity, which only data can bring in) comes as {"special": "-0"}, {"special": "NaN"} and so on. The command reference describes every field.
#Python, standard library only
A frame as nested lists, with the kinds beside it and each error described. Save this as grid.py:
# grid.py: run it in the readings folder with python3 grid.py
import itertools
import json
import subprocess
ELUCID8 = "./elucid8" # the elucid8 command
def frame(query):
"""Runs one query over a box and returns its frame."""
out = subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json", "--query", query, "--format", "frame"],
capture_output=True, text=True, check=True,
).stdout
return json.loads(out)
SPECIAL = {"-0": -0.0, "NaN": float("nan"), "Infinity": float("inf"), "-Infinity": float("-inf")}
def value(v):
"""A cell's value: numbers JSON cannot hold come as {"special": ...}."""
return SPECIAL[v["special"]] if isinstance(v, dict) else v
def coordinates(axis):
if "range" in axis:
return list(range(axis["range"][0], axis["range"][1] + 1))
return axis["labels"]
def nested(cells, shape):
"""Cells in frame order (the last axis fastest) as nested lists of that shape."""
if not shape:
return cells[0]
size = len(cells) // shape[0]
return [nested(cells[i * size:(i + 1) * size], shape[1:]) for i in range(shape[0])]
def describe(error):
"""An error as one line; one that started elsewhere says where."""
if "via" in error:
start = error["origin"]
return "via {} at {}: {}".format(start["name"], start["context"], error["message"])
return error["message"]
f = frame("smooth[y = 0..2, x = 0..3]")
names = [a["name"] for a in f["axes"]]
shape = [len(coordinates(a)) for a in f["axes"]]
print("axes", names, "shape", shape)
values = nested([value(v) for v in f["values"]], shape)
kinds = nested(f["kinds"], shape)
for row, row_kinds in zip(values, kinds):
print(row, row_kinds)
# Every cell's coordinates, in frame order, to say where each eod and error is.
points = list(itertools.product(*[coordinates(a) for a in f["axes"]]))
for i, kind in enumerate(f["kinds"]):
where = ", ".join("{} = {}".format(n, c) for n, c in zip(names, points[i]))
if kind == 1:
print(where + ": eod")
elif kind == 2:
print(where + ": error, " + describe(f["errors"][str(i)]))
axes ['y', 'x'] shape [3, 4]
[11, 12, None, None] [0, 0, 2, 2]
[12, 13, 15, 16] [0, 0, 0, 0]
[16, 17, 18, 19] [0, 0, 0, 0]
y = 0, x = 2: error, via reading at {'x': 3, 'y': 0}: sensor fault
y = 0, x = 3: error, via reading at {'x': 3, 'y': 0}: sensor fault
check=True raises an exception when the command does not finish normally. Exit code 1 means a query stopped with a program error (for example the demand-depth limit): the frame is still written, with the cells computed before it and a programError message (with check=True, it is in the exception's stdout). The command reference lists every exit code.
#Python with NumPy
The same frame as a NumPy array with a mask: a masked cell is not a value, and NumPy's masked operations skip it. This and the pandas examples need those packages: install them with python3 -m pip install numpy pandas (in a virtual environment if you use one). Save this as grid_numpy.py:
# grid_numpy.py: run it in the readings folder with python3 grid_numpy.py
import json
import subprocess
import numpy as np
ELUCID8 = "./elucid8" # the elucid8 command
SPECIAL = {"-0": -0.0, "NaN": np.nan, "Infinity": np.inf, "-Infinity": -np.inf}
out = subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--format", "frame"],
capture_output=True, text=True, check=True,
).stdout
f = json.loads(out)
assert f["type"] in ("number", "none"), "this example reads numbers only"
shape = [a["range"][1] - a["range"][0] + 1 for a in f["axes"]]
kinds = np.array(f["kinds"], dtype=np.uint8).reshape(shape)
numbers = [SPECIAL[v["special"]] if isinstance(v, dict) else (0.0 if v is None else v) for v in f["values"]]
grid = np.ma.masked_array(np.array(numbers, dtype=float).reshape(shape), mask=kinds != 0)
print(grid)
print("mean of the values:", grid.mean())
print("eod cells (y, x):", np.argwhere(kinds == 1).tolist())
print("error cells (y, x):", np.argwhere(kinds == 2).tolist())
# A plain array with NaN where a cell is not a value, for tools that do not read masks.
# It hides which cells were eod and which were errors: keep `kinds` beside it.
print(grid.filled(np.nan))
[[11.0 12.0 -- --]
[12.0 13.0 15.0 16.0]
[16.0 17.0 18.0 19.0]]
mean of the values: 14.9
eod cells (y, x): []
error cells (y, x): [[0, 2], [0, 3]]
[[11. 12. nan nan]
[12. 13. 15. 16.]
[16. 17. 18. 19.]]
- The mask, not NaN, marks the cells without a value (eod or an error). The positions are indices into the array (
[0, 2]is the first row, third column:y = 0, x = 2); add each axis's first coordinate to get coordinates. - The NaN view loses information. NaN cannot say whether a cell was eod or an error, and a source can hold a real
NaN(as{"special": "NaN"}), which would look the same. Use it only together withkinds.
#Python with pandas
From CSV. --format csv writes a table pandas reads as it is. Save this as table.py:
# table.py: run it in the running-sum folder with python3 table.py
import io
import subprocess
import pandas as pd
ELUCID8 = "./elucid8" # the elucid8 command
out = subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "running[t = 0..5]", "--query", "ratio[t = 2..4]", "--format", "csv"],
capture_output=True, text=True, check=True,
).stdout
table = pd.read_csv(io.StringIO(out))
print(table.to_string())
name t running_value running_kind running_message ratio_value ratio_kind ratio_message
0 running 0 3.0 value NaN NaN NaN NaN
1 running 1 4.0 value NaN NaN NaN NaN
2 running 2 8.0 value NaN NaN NaN NaN
3 running 3 8.0 value NaN NaN NaN NaN
4 running 4 13.0 value NaN NaN NaN NaN
5 running 5 22.0 value NaN NaN NaN NaN
6 ratio 2 NaN NaN NaN 2.0 value NaN
7 ratio 3 NaN NaN NaN NaN error division division by zero
8 ratio 4 NaN NaN NaN 2.6 value NaN
Each value asked for has its own columns, named after it, empty in the rows of the other values: running_value holds its data, running_kind says what each answer is (value, eod, or error and the error's kind, as error division) and running_message holds an error's message. With --timestamps, a running_ts column follows them: each answer's timestamp, the time of the latest data it was computed from, in milliseconds (Values and timestamps); CSV carries it only when asked, and the other formats unless asked not to. A cell that is not a value leaves _value empty, so a column of numbers reads as numbers, and its kind says why it is empty: no error turns silently into a number, or into a missing one.
From a frame, as a long table: one row per cell, a column per axis, then value and kind. Save this as long.py:
# long.py: run it in the readings folder with python3 long.py
import itertools
import json
import subprocess
import pandas as pd
ELUCID8 = "./elucid8" # the elucid8 command
KINDS = ["value", "eod", "error"]
out = subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--format", "frame"],
capture_output=True, text=True, check=True,
).stdout
f = json.loads(out)
axes = [range(a["range"][0], a["range"][1] + 1) if "range" in a else a["labels"] for a in f["axes"]]
rows = [point + (v, KINDS[k]) for point, v, k in zip(itertools.product(*axes), f["values"], f["kinds"])]
table = pd.DataFrame(rows, columns=[a["name"] for a in f["axes"]] + ["value", "kind"])
print(table)
print("mean of the values:", table[table["kind"] == "value"]["value"].mean())
y x value kind
0 0 0 11.0 value
1 0 1 12.0 value
2 0 2 NaN error
3 0 3 NaN error
4 1 0 12.0 value
5 1 1 13.0 value
6 1 2 15.0 value
7 1 3 16.0 value
8 2 0 16.0 value
9 2 1 17.0 value
10 2 2 18.0 value
11 2 3 19.0 value
mean of the values: 14.9
pandas shows the cells that are not values as NaN; the kind column says which they are. Filter on kind rather than on NaN, for the reasons in the NumPy section.
#Python with NumPy and Arrow files
Needs elucid8 0.4.0 or later. Instead of a frame on standard output, the command can write one query straight to a file your tools read natively: a NumPy .npz (--format npz, or a name ending in .npz) or an Apache Arrow stream (--format arrow, or a name ending in .arrows). Numbers stay binary, nothing needs converting, and the kinds come with them. These examples need their packages: python3 -m pip install numpy pandas pyarrow polars duckdb (in a virtual environment if you use one). The command reference describes both files.
NumPy. numpy.load gives the values already shaped by the axes, and the kinds beside them. Save this as grid_npz.py:
# grid_npz.py: run it in the readings folder with python3 grid_npz.py
import json
import subprocess
import numpy as np
ELUCID8 = "./elucid8" # the elucid8 command
# A name ending in .npz chooses the format.
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.npz"],
check=True,
)
with np.load("smooth.npz") as f:
values, kinds = f["smooth_value"], f["smooth_kind"]
axes = json.loads(f["axes.json"])
errors = json.loads(f["errors.json"]) if "errors.json" in f.files else {}
print("axes", [a["name"] for a in axes], "shape", values.shape, values.dtype)
grid = np.ma.masked_array(values, mask=kinds != 0)
print(grid)
print("mean of the values:", grid.mean())
print("eod cells (y, x):", np.argwhere(kinds == 1).tolist())
for i, error in errors.items():
y, x = np.unravel_index(int(i), kinds.shape) # the index is into the flattened array
print("cell", [int(y), int(x)], "error:", error["message"])
axes ['y', 'x'] shape (3, 4) float64
[[11.0 12.0 -- --]
[12.0 13.0 15.0 16.0]
[16.0 17.0 18.0 19.0]]
mean of the values: 14.9
eod cells (y, x): []
cell [0, 2] error: sensor fault
cell [0, 3] error: sensor fault
smooth_valueholds 0 where a cell is not a value, never NaN: mask it withkinds, as here.errors.jsonindexes the flattened array;np.unravel_indexturns an index into the cell's position.
pyarrow and pandas. An Arrow file is a table with one row per cell: a column per axis, then smooth_value, smooth_kind (value, eod or error), smooth_error, smooth_origin and smooth_message (on an error, its kind, where it started and its cause in words), smooth_ts and smooth_trail, named after the value asked for. Save this as arrow_pandas.py:
# arrow_pandas.py: run it in the readings folder with python3 arrow_pandas.py
import subprocess
import pyarrow as pa
ELUCID8 = "./elucid8" # the elucid8 command
# A name ending in .arrows (an Arrow stream) chooses the format.
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.arrows"],
check=True,
)
with pa.ipc.open_stream("smooth.arrows") as reader:
table = reader.read_all()
print(table.schema.names, table.num_rows, "rows")
df = table.to_pandas()
print(df[["y", "x", "smooth_value", "smooth_kind", "smooth_ts"]])
print("mean of the values:", df[df["smooth_kind"] == "value"]["smooth_value"].mean())
for row in df[df["smooth_kind"] == "error"].itertuples():
print("y =", row.y, "x =", row.x, "error:", row.smooth_error, "from", row.smooth_origin, "-", row.smooth_message)
['y', 'x', 'smooth_value', 'smooth_kind', 'smooth_error', 'smooth_origin', 'smooth_message', 'smooth_ts', 'smooth_trail'] 12 rows
y x smooth_value smooth_kind smooth_ts
0 0 0 11.0 value 0
1 0 1 12.0 value 0
2 0 2 NaN error 0
3 0 3 NaN error 0
4 1 0 12.0 value 0
5 1 1 13.0 value 0
6 1 2 15.0 value 0
7 1 3 16.0 value 0
8 2 0 16.0 value 0
9 2 1 17.0 value 0
10 2 2 18.0 value 0
11 2 3 19.0 value 0
mean of the values: 14.9
y = 0 x = 2 error: data from reading[x = 3, y = 0] - sensor fault
y = 0 x = 3 error: data from reading[x = 3, y = 0] - sensor fault
In Arrow, a cell that is not a value is null; pandas shows it as NaN, and the smooth_kind column says which it is.
Polars reads the same file itself. Save this as arrow_polars.py:
# arrow_polars.py: run it in the readings folder with python3 arrow_polars.py
import subprocess
import polars as pl
ELUCID8 = "./elucid8" # the elucid8 command
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.arrows"],
check=True,
)
df = pl.read_ipc_stream("smooth.arrows")
# Per row y: how many cells are values, and their mean (nulls are not values, so mean skips them).
print(df.group_by("y").agg((pl.col("smooth_kind") == "value").sum().alias("values"), pl.col("smooth_value").mean().alias("mean")).sort("y"))
shape: (3, 3)
┌─────┬────────┬──────┐
│ y ┆ values ┆ mean │
│ --- ┆ --- ┆ --- │
│ i64 ┆ u32 ┆ f64 │
╞═════╪════════╪══════╡
│ 0 ┆ 2 ┆ 11.5 │
│ 1 ┆ 4 ┆ 14.0 │
│ 2 ┆ 4 ┆ 17.5 │
└─────┴────────┴──────┘
DuckDB runs SQL over the table pyarrow read. Save this as arrow_duckdb.py:
# arrow_duckdb.py: run it in the readings folder with python3 arrow_duckdb.py
import subprocess
import duckdb
import pyarrow as pa
ELUCID8 = "./elucid8" # the elucid8 command
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.arrows"],
check=True,
)
with pa.ipc.open_stream("smooth.arrows") as reader:
smooth = reader.read_all()
# DuckDB queries the Arrow table by its Python name.
for row in duckdb.sql("SELECT x, count(*) FILTER (WHERE smooth_kind = 'value') AS n, avg(smooth_value) AS mean FROM smooth GROUP BY x ORDER BY x").fetchall():
print(row)
print(duckdb.sql("SELECT smooth_kind, count(*) FROM smooth GROUP BY smooth_kind ORDER BY smooth_kind").fetchall())
(0, 3, 13.0)
(1, 3, 14.0)
(2, 2, 16.5)
(3, 2, 17.5)
[('error', 2), ('value', 10)]
SQL's avg skips nulls, so the cells that are not values are left out of the means, and smooth_kind counts them.
#Python with Parquet files
Needs elucid8 0.16.0 or later. An Apache Parquet file (--format parquet, or a name ending in .parquet) holds the same table as the Arrow file above, with the same columns, and pandas, Polars and DuckDB read it by name. It suits results you keep. The command reference describes it.
pandas. Save this as parquet_pandas.py:
# parquet_pandas.py: run it in the readings folder with python3 parquet_pandas.py
import subprocess
import pandas as pd
ELUCID8 = "./elucid8" # the elucid8 command
# A name ending in .parquet chooses the format.
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.parquet"],
check=True,
)
df = pd.read_parquet("smooth.parquet")
print(list(df.columns), len(df), "rows")
# One row per y, one column per x; cells that are not values are NaN.
print(df.pivot(index="y", columns="x", values="smooth_value"))
print("cells by kind:", df["smooth_kind"].value_counts().sort_index().to_dict())
for row in df[df["smooth_kind"] == "error"].itertuples():
print("y =", row.y, "x =", row.x, "error:", row.smooth_error, "from", row.smooth_origin, "-", row.smooth_message)
['y', 'x', 'smooth_value', 'smooth_kind', 'smooth_error', 'smooth_origin', 'smooth_message', 'smooth_ts', 'smooth_trail'] 12 rows
x 0 1 2 3
y
0 11.0 12.0 NaN NaN
1 12.0 13.0 15.0 16.0
2 16.0 17.0 18.0 19.0
cells by kind: {'error': 2, 'value': 10}
y = 0 x = 2 error: data from reading[x = 3, y = 0] - sensor fault
y = 0 x = 3 error: data from reading[x = 3, y = 0] - sensor fault
Polars. Save this as parquet_polars.py:
# parquet_polars.py: run it in the readings folder with python3 parquet_polars.py
import subprocess
import polars as pl
ELUCID8 = "./elucid8" # the elucid8 command
subprocess.run(
[ELUCID8, "run", "plan.json", "--config", "deploy.json",
"--query", "smooth[y = 0..2, x = 0..3]", "--out", "smooth.parquet"],
check=True,
)
df = pl.read_parquet("smooth.parquet")
# Per column x: how many cells are values, and their mean (nulls are not values, so mean skips them).
print(df.group_by("x").agg((pl.col("smooth_kind") == "value").sum().alias("values"), pl.col("smooth_value").mean().alias("mean")).sort("x"))
shape: (4, 3)
┌─────┬────────┬──────┐
│ x ┆ values ┆ mean │
│ --- ┆ --- ┆ --- │
│ i64 ┆ u32 ┆ f64 │
╞═════╪════════╪══════╡
│ 0 ┆ 3 ┆ 13.0 │
│ 1 ┆ 3 ┆ 14.0 │
│ 2 ┆ 2 ┆ 16.5 │
│ 3 ┆ 2 ┆ 17.5 │
└─────┴────────┴──────┘
Parquet and Arrow files are read as data too: a table your tools write, with a column per dimension and a value column (or one named <input>_value), is an input as a CSV file is ("from": "x.parquet"; Connecting eLucid8 to your data has a recipe).
#Outputs named in the program
Needs elucid8 0.20.0 or later. A program can say what it gives out, as equations: output("smooth") = smooth sends smooth out on the channel "smooth", records one per point, with a column per dimension and one for the value. elucid8 run then writes them without a query. In the playground, paste this program, give the input reading the table above, save it with the title Smoothed and press Download; unzip smoothed.zip and copy the elucid8 command into the folder smoothed:
-- Readings on a 4 × 3 grid, smoothed along x, written out side by side.
grid = input("reading", x : 4, y : 3)
smooth = restrict mean grid over (x : #x - 1 .. #x + 1) end
to (x : 4, y : 3) end
output("grid") = grid
output("smooth") = smooth
smooth is bounded to the grid here, so the two channels have the same dimensions and rows, and the deployment may write them side by side into one file. With "outputs": { "cells.csv": {"channels": ["grid", "smooth"]} } in deploy.json, --output grid --output smooth writes only those two channels, into cells.csv:
# In the smoothed folder:
./elucid8 run plan.json --config deploy.json --output grid --output smooth
cat cells.csv
x,y,grid_value,grid_kind,grid_message,smooth_value,smooth_kind,smooth_message
0,0,10,value,,11,value,
0,1,11,value,,12,value,
0,2,,error missing,input reading has no data at this point,16,value,
1,0,12,value,,12,value,
1,1,13,value,,13,value,
1,2,16,value,,17,value,
2,0,14,value,,,error data,sensor fault
2,1,15,value,,15,value,
2,2,18,value,,18,value,
3,0,,error data,sensor fault,,error data,sensor fault
3,1,17,value,,16,value,
3,2,20,value,,19,value,
Without --output, the run also answers the configuration's queries on standard output. As the Download's deploy.json comes, each channel goes to its own file in the folder out, out/grid.csv and out/smooth.csv; with no entry for a channel at all, to grid.csv beside deploy.json. deploy.json may send a channel elsewhere, "outputs": { "smooth": { "to": "smooth-today.csv" } }, in another format ("format": "jsonl", "parquet", "arrow", "npz", "frame"), or to a program; it chooses only where it goes, never what is in it (Outputs named in the program).
#Python talking to elucid8 serve
The service reads requests, one JSON object per line, on its standard input, and writes one reply per request, in order, on its standard output. This script starts it, asks for running at t = 4..5, gives it Tuesday's data (x at t = 5 is 90 instead of 9), asks again, reads the service's statistics, and stops it. Save this as service.py:
# service.py: run it in the running-sum folder with python3 service.py
import json
import subprocess
ELUCID8 = "./elucid8" # the elucid8 command
# Tuesday's data: data/x.csv with x at t = 5 changed from 9 to 90.
with open("data/x.csv") as f:
tuesday = f.read().replace("\n5,9\n", "\n5,90\n")
with open("data/x-tuesday.csv", "w") as f:
f.write(tuesday)
service = subprocess.Popen(
[ELUCID8, "serve", "plan.json", "--config", "deploy.json"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
)
def send(request):
service.stdin.write(json.dumps(request) + "\n")
service.stdin.flush()
def receive(count):
"""Reads `count` replies and returns them by id."""
replies = {}
for _ in range(count):
reply = json.loads(service.stdout.readline())
replies[reply["id"]] = reply
return replies
# Requests can be sent without waiting for replies: they are handled in the order sent.
send({"id": 1, "op": "query", "query": "running[t = 4..5]"})
send({"id": 2, "op": "advance", "input": "x", "file": "data/x-tuesday.csv"})
send({"id": 3, "op": "query", "query": "running[t = 4..5]"})
send({"id": 4, "op": "stats"})
replies = receive(4)
for i in (1, 3):
print("request", i, [r["outcome"]["value"] for r in replies[i]["results"]], replies[i]["versions"])
print("advance:", replies[2]["status"], "x is now version", replies[2]["version"])
totals = replies[4]["stats"]["totals"]
print("evaluations:", totals["evaluations"], "advances:", totals["advances"])
send({"id": 5, "op": "shutdown"})
print("shutdown:", receive(1)[5]["status"])
service.wait()
request 1 [13, 22] {'x': 'd20b5fc4a3d402cb'}
request 3 [13, 103] {'x': '7270c6cb167f44ec'}
advance: done x is now version 7270c6cb167f44ec
evaluations: 12 advances: 1
shutdown: done
- Each reply carries its request's
id, so a program can match replies to requests however it sends them. versionsnames the data each answer used: request 1 read Monday'sx, request 3 Tuesday's. A version is a fingerprint of the file's bytes.- The service's log (one line per request) goes to its standard error; this script discards it. To keep it, pass
stderr=open("serve.log", "w"). - With
"pointCache": truein the options ofdeploy.json, later queries reuse what earlier ones computed, and only the values that read the changed data are computed again. The long-running service describes every request, reply and option.
A subscription. Instead of asking again whenever new data arrives, a program can subscribe: the service answers the query at once, then again after every advance that changes what the query reads. Here the query is running[t = last], the newest point: last is the highest t that x lists, so when a new row arrives the subscription answers for it. By default each answer holds only the points whose outcome changed, or that are new. Save this as subscribe.py:
# subscribe.py: run it in the running-sum folder with python3 subscribe.py
import json
import subprocess
ELUCID8 = "./elucid8" # the elucid8 command
# New data: data/x.csv with a new row, x = 2 at t = 6; then that row corrected to x = 5.
with open("data/x.csv") as f:
so_far = f.read()
with open("data/x-wednesday.csv", "w") as f:
f.write(so_far + "6,2\n")
with open("data/x-corrected.csv", "w") as f:
f.write(so_far + "6,5\n")
service = subprocess.Popen(
[ELUCID8, "serve", "plan.json", "--config", "deploy.json"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
)
def send(request):
service.stdin.write(json.dumps(request) + "\n")
service.stdin.flush()
def receive():
return json.loads(service.stdout.readline())
def show(answer):
points = {r["context"]["t"]: r["outcome"]["value"] for r in answer["results"]}
print("answer", answer["run"], points)
# A standing query for the newest point: `last` is the highest t that x lists.
# It is answered now, and again whenever x changes.
send({"id": "newest", "op": "subscribe", "query": "running[t = last]"})
show(receive())
for file in ("data/x-wednesday.csv", "data/x-corrected.csv"):
send({"id": file, "op": "advance", "input": "x", "file": file})
print("advance:", receive()["status"])
show(receive()) # the subscription's answer, after the advance's reply
send({"id": "stop", "op": "unsubscribe", "target": "newest"})
print("unsubscribe:", receive()["status"], "then", receive()["status"])
send({"id": "end", "op": "shutdown"})
receive()
service.wait()
answer 1 {5: 22}
advance: done
answer 2 {6: 24}
advance: done
answer 3 {6: 27}
unsubscribe: done then ended
- Answers carry the subscription's
idand theirrunnumber; each comes after the reply to the advance that caused it. - A subscription ends with
unsubscribe(its last reply has the statusended), or when the service shuts down. The long-running service describes subscriptions andlastin full.
#JavaScript (Node)
A frame, printed as a grid. Save this as grid.mjs:
// grid.mjs: run it in the readings folder with node grid.mjs
import { execFileSync } from "node:child_process";
const ELUCID8 = "./elucid8"; // the elucid8 command
const out = execFileSync(ELUCID8, ["run", "plan.json", "--config", "deploy.json", "--query", "smooth[y = 0..2, x = 0..3]", "--format", "frame"], { encoding: "utf8" });
const frame = JSON.parse(out);
const [rows, columns] = frame.axes.map((a) => a.range[1] - a.range[0] + 1);
const KINDS = ["value", "eod", "error"];
for (let r = 0; r < rows; r++) {
const cells = [];
for (let c = 0; c < columns; c++) {
const i = r * columns + c; // the last axis varies fastest
cells.push((frame.kinds[i] === 0 ? String(frame.values[i]) : KINDS[frame.kinds[i]]).padStart(10));
}
console.log(cells.join(""));
}
for (const [i, error] of Object.entries(frame.errors)) console.log(`cell ${i}:`, error.message);
11 12 error error
12 13 15 16
16 17 18 19
cell 2: sensor fault
cell 3: sensor fault
The service. The same conversation as the Python example, with each reply delivered to the request that asked. Save this as service.mjs:
// service.mjs: run it in the running-sum folder with node service.mjs
import { spawn } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { createInterface } from "node:readline";
const ELUCID8 = "./elucid8"; // the elucid8 command
// Tuesday's data: data/x.csv with x at t = 5 changed from 9 to 90.
writeFileSync("data/x-tuesday.csv", readFileSync("data/x.csv", "utf8").replace("\n5,9\n", "\n5,90\n"));
const service = spawn(ELUCID8, ["serve", "plan.json", "--config", "deploy.json"], { stdio: ["pipe", "pipe", "ignore"] });
const waiting = new Map(); // request id → the function that receives its reply
createInterface({ input: service.stdout }).on("line", (line) => {
const reply = JSON.parse(line);
waiting.get(reply.id)(reply);
waiting.delete(reply.id);
});
let lastId = 0;
function ask(request) {
const id = ++lastId;
return new Promise((resolve) => {
waiting.set(id, resolve);
service.stdin.write(JSON.stringify({ id, ...request }) + "\n");
});
}
// Sent together; the service handles them in this order.
const [monday, advance, tuesday, stats] = await Promise.all([
ask({ op: "query", query: "running[t = 4..5]" }),
ask({ op: "advance", input: "x", file: "data/x-tuesday.csv" }),
ask({ op: "query", query: "running[t = 4..5]" }),
ask({ op: "stats" }),
]);
const values = (reply) => reply.results.map((r) => r.outcome.value);
console.log("Monday:", values(monday), "Tuesday:", values(tuesday));
console.log("advance:", advance.status, advance.version);
console.log("evaluations:", stats.stats.totals.evaluations);
console.log("shutdown:", (await ask({ op: "shutdown" })).status);
Monday: [ 13, 22 ] Tuesday: [ 13, 103 ]
advance: done 7270c6cb167f44ec
evaluations: 12
shutdown: done
The service exits after the shutdown's reply, and Node then ends.
#The shell
A table in a file. --format csv writes CSV; redirect it, or name a file with --out:
# In the running-sum folder:
./elucid8 run plan.json --config deploy.json --query 'running[t = 0..5]' --format csv > results.csv
cat results.csv
name,t,running_value,running_kind,running_message
running,0,3,value,
running,1,4,value,
running,2,8,value,
running,3,8,value,
running,4,13,value,
running,5,22,value,
The file uses the same notation as the data files, so it can be read back as an input.
Frames with jq. jq is a small command for JSON; it is optional, and not part of eLucid8. The kinds of every cell, then each error:
# In the readings folder:
./elucid8 run plan.json --config deploy.json --query 'smooth[y = 0..2, x = 0..3]' --format frame | jq -c '.kinds'
./elucid8 run plan.json --config deploy.json --query 'smooth[y = 0..2, x = 0..3]' --format frame | jq -r '.errors | to_entries[] | "cell \(.key): \(.value.message)"'
[0,0,2,2,0,0,0,0,0,0,0,0]
cell 2: sensor fault
cell 3: sensor fault
#Where next
- Command reference: every command, option and output format, and the configuration file.
- The long-running service: every request and reply of
elucid8 serve. - Deploy tutorial: from the playground to the
elucid8command, step by step. - Connecting eLucid8 to your data: databases, APIs and streams as inputs and destinations, with a connector template.