screamer.js
    Preparing search index...

    Pipelines and graphs

    A single op is a point transform: one input event in, one output event out. A Pipeline composes several ops (and combinators) into a reusable graph, built once and run as many times as you like on stored data or on a live event stream.

    Input(name) declares a source the graph will read from. It does not hold data itself; data is bound later, when the pipeline is called:

    import { Input } from "@screamer-labs/screamer";

    const x = Input("x");

    Passing an Input node (or any other node) through an op factory does not run the op. It returns a symbolic node describing "apply this op here", and defers the actual computation until the graph is compiled and called:

    import { RollingMean, Diff } from "@screamer-labs/screamer";

    const x = Input("x");
    const y = Diff(1)(RollingMean(3)(x));

    y now describes a two-stage chain: a 3-period rolling mean, followed by a first difference. Nothing has been computed yet.

    An op or dropna given several nodes, such as Add()(a, b) over two 2-column inputs, takes them as separate streams of events, merged into one stream as merge merges: by index, and at equal indexes in the order of the node's inputs (its first input first, which need not be the Pipeline's first input). Batch and live calls give the same order. An event waits until the other streams have passed its index, at most maxPending events. To join streams into one row instead, use combineLatest.

    import { Pipeline } from "@screamer-labs/screamer";

    const pipeline = new Pipeline([x], [y]); // [declared inputs], [outputs]

    const { values, index } = pipeline([1, 2, 3, 4, 5, 6]);

    pipeline.dispose();

    new Pipeline(inputs, outputs) compiles the graph once. Each call pipeline(feeds) binds data to the declared inputs and runs the whole graph in a single pass, so a multi-op chain never recomputes a subgraph shared by two outputs.

    For a single-input pipeline, feeds can be a bare array or typed array. For multiple inputs, or to supply an explicit index axis, pass an object keyed by input name:

    const a = Input("a");
    const b = Input("b");
    const y = combineLatest([a, b]); // an output node that uses both inputs
    const p = new Pipeline([a, b], [y]);

    p({
    a: { values: new Float64Array([1, 2, 3]), index: new Float64Array([0, 2, 4]) },
    b: new Float64Array([10, 20, 30]), // index defaults to 0, 1, 2, ...
    });

    A pipeline with one output returns a single { values, index } object; a pipeline with several outputs returns an array of them, one per declared output.

    Each feed has one index value per row of values. A flat array or typed array is one value per row; rows of several values come as an NdArray ({ data, shape: [T, K] }). An index of another length throws RangeError naming both lengths.

    new Pipeline(inputs, outputs, { alignOutputs }) sets how several outputs come back. With alignOutputs: true (the default), every output is put on one index: the sorted union of the output indexes, with one row per distinct index. Each output holds its latest value at every row, and the rows start once every output has a value. All outputs then share one index array and have the same number of rows; each output keeps its own columns. With alignOutputs: false, each output keeps its own index and length.

    const a = Input("a");
    const b = Input("b");
    const p = new Pipeline([a, b], [a, b]); // alignOutputs: true

    const [outA, outB] = p({
    a: { values: [1, 2, 3], index: [0, 2, 4] },
    b: { values: [10, 20], index: [1, 3] },
    });
    // outA.index and outB.index are both [1, 2, 3, 4]
    // outA.values is [1, 2, 2, 3]; outB.values is [10, 10, 20, 20]

    live().result() returns the same shape as the batch call.

    maxPending (default 1,000,000) is the most events a join may hold while it waits for another stream: each combineLatest node without its own maxPending, each filter node, and the join of a cumulative resample with its driver and of an operator or dropna given several streams. More throws RangeError and ends a live session. It is an integer from 1 to 2**53; another number throws RangeError, and a value that is not an integer TypeError.

    Dispose the pipeline with pipeline.dispose() when you are done with it. See Lifecycle for why you should not separately dispose the ops that went into building the graph.

    pipeline.toJSON() gives the description of the pipeline as a plain object: its inputs, its nodes with their settings, its outputs, alignOutputs and maxPending. As for any object with a toJSON method, JSON.stringify(pipeline) writes it as JSON text, also inside a larger object. Pipeline.fromJSON(json) builds a new, runnable pipeline from that text, or from the object, each node by its factory, so the copy shares no state with the original. toDict() and Pipeline.fromDict(object) are the object forms by Python's names.

    const x = Input("x");
    const p = new Pipeline([x], [resample(RollingMean(5)(x), { every: 10, agg: "ohlc" })]);
    const text = JSON.stringify(p); // save this string to a file
    const q = Pipeline.fromJSON(text); // the same pipeline, the same results

    The format is Python's: a pipeline saved by Python's to_json() loads here, and one saved here loads with Python's Pipeline.from_json, with the same results. The settings keep their Python names (window_size, not windowSize). JSON.stringify writes a setting that is not finite, such as Clip({ lower: -Infinity }), as null, which loads as "not given". toJSONText(indent) writes the text Python's to_json(indent) writes, -Infinity and -0.0 included (JavaScript writes 3 where Python writes 3.0, as it has one number type); Pipeline.fromJSON reads it, which JSON.parse does not. toJSONText(null) writes one line.

    A text or description that does not describe a pipeline throws RangeError naming the problem, such as "unknown functor class: 'NoSuchOp'" or "Pipeline description: node 1: input 7 is not an earlier node"; a setting a factory refuses throws as the factory does.

    pipeline.live() returns an event-by-event driver. Each driver runs on its own compiled engine and its own copies of the ops, so several drivers of one pipeline and batch calls never interfere; driver.dispose() frees its engine at once (else the garbage collector or pipeline.dispose() does). Push one event at a time, then flush and drain the result:

    const driver = pipeline.live();
    driver.push("x", /* index */ 0, /* value */ 1);
    driver.push("x", 1, 2);
    driver.push("x", 2, 3);
    // An array (or typed array) is one multi-column event, such as an OHLC bar:
    // bars.push("bars", 0, [100, 102, 99.5, 101.5]);
    driver.flush();
    const { values, index } = driver.result();

    driver.advance(now) moves logical time to now, closing every resample window whose boundary has passed by now, empty ones included (filled per fill). flush() is the end of input; advance leaves count= and threshold= windows open. After flush(), push and advance throw RangeError; start a new live() session to feed more events.

    An input keeps the width of its first event (a number is width 1); an event of another width throws RangeError. pushWide is an alias of push for arrays. An index is a number with a whole value inside the int64 range; any other index throws TypeError. An index below the input's previous event, or below an earlier advance(now), throws RangeError, and the session goes on as if the event had not been sent; equal indexes are allowed. A null value is NaN, and a string (even "3") throws TypeError; parse text first with Number(). A rejection that happens after part of the graph took the event (a combineLatest buffer that overflows, for example) makes every later call, result() included, throw until a new live() session starts.

    Streaming a pipeline this way reproduces its batch output exactly on the same data: pipeline(data) and pipeline.live() fed the same events one by one always agree. For a pipeline with several outputs, driver.result() returns one { values, index } per output, aligned when the pipeline aligns its outputs. Aligned outputs keep each output's latest value from one result() to the next, so the rows of repeated calls, put end to end, are the batch rows. A call returns a row only once every output has moved past its index; after flush() it returns every row.

    An input that gets no events holds the aligned rows. While an input is silent, for example a clock that stopped ticking or a feed that paused, the outputs fed by it do not move, so the other outputs' rows wait in memory until advance(now) or flush(). In a long-running session, call advance(now) from time to time: it moves every input to now and releases the rows below it. An output that emits rarely holds the others' rows the same way, but only for one bar: an every or count resample tells the alignment where its open bar starts, so the rows of the open bar wait until it closes.

    Combinators are graph nodes that combine or reshape streams, rather than transforming one stream's values. Each one takes node arguments and returns a node, so it composes into a graph the same way an op does.

    combineLatest(nodes, opts?): as-of latest-value join across N node streams on possibly different index axes. emit: "when_all" (the default) emits once every input has produced a value; emit: "on_any" emits on any input event. Given arrays, {values, index} streams or iterators instead of nodes, combineLatest joins them directly, with an optional layout, as Python's combine_latest does.

    import { combineLatest } from "@screamer-labs/screamer";

    const joined = combineLatest([a, b]); // -> a wide 2-column stream, latest a & latest b

    resample(node, opts): causal windowed downsample. every buckets by a fixed index width; count buckets by a fixed number of arrivals; agg picks the reducer ("mean", "last", "sum", "ohlc", and others). With fill: "nan" or "carry", maxFill (default 1,000,000) bounds the empty bars of one gap: an event or an advance(now) that would close more empty buckets at once throws RangeError before it builds any bar, as Python's max_fill does. The limit counts one step, so a live session that advances in small steps fills a gap that a batch call rejects. A rejected advance(now) leaves the session usable, as a rejected event does; later events must still come at or after now.

    With clock: true, a bar at clock tick t holds the values with index in (previous tick, t]. In a live session the bar comes out once the value stream has passed t: a value above t, an advance(now) with now > t, or flush(). A value at t still joins the bar, so advance(t) is not enough: after values up to 50 and ticks at 60 and 70, bar 60 comes out at advance(61), not at advance(60).

    import { resample } from "@screamer-labs/screamer";

    const bars = resample(x, { every: 5, agg: "mean" });
    // index 0..9 -> two bars labelled at 0 and 5, each the mean of its 5 points

    A built-in agg reduces every column of a wide stream on its own. "ohlc" on an X-column stream gives 4 * X columns in column-major field order, [open0, high0, low0, close0, open1, ...], in every mode (every, count, clock), batch and live. The result's values has shape [T', 4 * X]; read the data as [T', X, 4] (row t, column k, field f is at data[(t * X + k) * 4 + f]), which is the Python eager result.

    select(node, columns): pick one or more columns from a wide (multi-output) stream.

    import { select } from "@screamer-labs/screamer";

    const lo = select(RollingMinMax(3)(x), 0); // the min column only

    dropna(nodes, opts?): drop events with NaN. how: "any" (the default) drops a row with any NaN across its columns; how: "all" drops only rows that are all NaN. Useful right after an op whose warmup produces NaN, to start a downstream computation only once real values start flowing:

    import { dropna } from "@screamer-labs/screamer";

    const warm = dropna(RollingMean(3)(x)); // skips the two NaN warmup events

    filter(data, mask): keep each data value whose aligned mask event is nonzero; zero or NaN drops it. The data and the mask are one column each; a wider stream throws RangeError, so select the column to gate first.

    import { filter } from "@screamer-labs/screamer";

    const gated = filter(x, mask);

    delay(node, k): re-stamp each event's index by k index units; values are unchanged. Useful for lining up a signal with a lagged copy of itself before combining the two.

    import { delay } from "@screamer-labs/screamer";

    const lagged = delay(x, 2);

    resample, select, dropna, filter and delay also run directly, as Python's Resample, Select, Dropna, Filter and Delay do. Given arrays (a typed array, an Array, T rows or an NdArray), or an indexed stream { values, index }, each returns { values, index }; the index is null for a positional select or dropna. Given an iterator of { value, index } events, each returns an iterator of { value, index } rows. Every form runs the same C++ node through a one-node Pipeline, so the rows match the graph's.

    import { resample, select, dropna, delay } from "@screamer-labs/screamer";

    resample(new Float64Array([0, 1, 2, 3, 4]), { every: 2 });
    // { values: Float64Array [1, 3, 4], index: Float64Array [0, 2, 4] }

    select({ data: new Float64Array([0, 1, 2, 3, 4, 5]), shape: [3, 2] }, 1);
    // { values: Float64Array [1, 3, 5], index: null }

    dropna([{ values: [1, NaN, 3] }, { values: [NaN, 2, 4] }]);
    // two streams, merged in index order: { values: Float64Array [1, 2, 3, 4], index: null }

    delay({ values: [0, 1, 2], index: [0, 1, 5] }, 2);
    // { values: Float64Array [0, 1, 2], index: Float64Array [2, 3, 7] }

    Several streams of dropna are an array of { values, index } objects ({ values } for a positional one), as a plain array of arrays is the rows of one stream. A delay needs the index. A resample driver (threshold, or the clock of clock: true) goes in its driver option. On (T, ...assets) values, a built-in agg reduces every column on its own and the result keeps the asset axes, [T', ...assets], with a last axis of 4 for "ohlc".

    A Pipeline called with an iterator of { value, index } events (one input), or an object of such iterators keyed by input name, runs lazily: it returns a generator that reads one event at a time, as Python's pipeline(iter(...)) does. The feeds merge in index order, ties in input order, and the rows are those a batch call gives: { value, index } for one output (a number, or an array of the output's columns), { values, index } with one value per output for aligned outputs. Nothing is read before the first next(); leaving the loop early closes the iterators. Each run has its own operator state, as a live() session does.

    const x = Input("x");
    const p = new Pipeline([x], [RollingMean(2)(x)]);

    for (const row of p([{ value: 1, index: 0 }, { value: 2, index: 1 }].values())) {
    console.log(row); // { value: NaN, index: 0 }, then { value: 1.5, index: 1 }
    }

    Iterators beside arrays throw TypeError; so do several outputs with alignOutputs: false, which have no one row per index (use the batch call).