import { CogniteClient } from '@cognite/sdk'; import { g as DatapointAggregate, N as NodeId, P as CognitePort } from '../types-DgFXaO28.cjs'; /** * A timestamped numeric value. Used both for the formula result * (`datapoints`) and for each aligned input series (`inputs`). */ type DataPoint = { timestamp: Date; value: number; }; /** How several time series behind one parameter are combined into one. */ type ReducerType = "min" | "max" | "sum" | "average"; /** How the time-series parameters of a query are joined on time. */ type AlignmentMode = "intersect" | "strict"; /** One time series' datapoints, ascending by timestamp once normalized. */ type Series = DataPoint[]; /** * A fixed scalar input to a calculation, broadcast across every timestamp in * the result. No datapoints are fetched for it. */ type ConstantParameter = { type: "constant"; /** The placeholder name used to reference this parameter in the formula. */ alias: string; value: number; }; /** Fields shared by every parameter that reads datapoints from Cognite. */ type TimeSeriesParameterBase = { /** The placeholder name used to reference this parameter in the formula. */ alias: string; /** Optional aggregate to apply; requires `granularity` when set. */ aggregateType?: DatapointAggregate; /** Aggregate granularity (e.g. `"1h"`); required when `aggregateType` is set. */ granularity?: string; }; /** * A single time series input to a calculation. * * When `aggregateType` is set the datapoints are fetched as aggregates and a * `granularity` is required; otherwise raw datapoints are used. */ type TimeSeriesParameter = TimeSeriesParameterBase & { type: "single_timeseries"; /** The time series instance to read datapoints from. */ timeSeries: NodeId; }; /** * Two or more time series combined into a single input by `reducer`. * * The series are combined by intersecting on timestamp, so prefer * `aggregateType` + `granularity` here: raw datapoints from independent * series rarely share exact timestamps. */ type MultiTimeSeriesParameter = TimeSeriesParameterBase & { type: "multi_timeseries"; /** The time series instances to read datapoints from; at least two, unique. */ timeSeries: NodeId[]; reducer: ReducerType; }; /** Any input a formula placeholder can resolve to. */ type CalculatorParameter = ConstantParameter | TimeSeriesParameter | MultiTimeSeriesParameter; /** A formula plus the parameters its placeholders resolve to. */ type CalculatorQuery = { /** Formula referencing parameters by ``{alias}`` (see `evaluate`). */ formula: string; parameters: CalculatorParameter[]; /** How time-series parameters are joined on time; defaults to `"intersect"`. */ alignment?: AlignmentMode; }; /** * The datapoints produced by evaluating a `CalculatorQuery`, plus the aligned * parameter series the formula actually evaluated. * * `inputs[alias][i]` is the point used to compute `datapoints[i]`. These * series are already in memory at evaluation time (after retrieval, any * multi-series reduction, timestamp alignment, and constant broadcast), so * returning them does not refetch from CDF. */ type CalculationResult = { query: CalculatorQuery; datapoints: DataPoint[]; /** Aligned series used by the formula, keyed by parameter alias. */ inputs: Record; }; /** * Evaluates formula-based calculations over Cognite time series datapoints. * * Each {@link CalculatorQuery} pairs a formula with the parameters its * placeholders resolve to. The calculator fetches the required datapoints * (de-duplicating shared time series), joins the query's time-series * parameters onto a single time axis, and evaluates the formula * element-by-element. */ declare class Calculator { private readonly retriever; private readonly seriesReducer; constructor(cognite: CogniteClient | CognitePort); /** Evaluate a single query over the given time range. */ calculate(query: CalculatorQuery, start: Date, end: Date): Promise; /** * Evaluate several queries over the given time range, retrieving every * parameter's datapoints in a single de-duplicated round trip. */ calculateMultiples(queries: CalculatorQuery[], start: Date, end: Date): Promise; private calculateOne; /** Collapses a parameter's time series down to the single series it stands for. */ private collapse; private alignSeries; } /** * Base error for every failure raised by the calculator. * * {@link FormulaError} and its subclasses derive from this, so a caller that * only wants to distinguish "the calculator failed" from "something else * failed" can catch this single type. */ declare class CalculatorError extends Error { constructor(message: string); } /** Raised when Cognite returns datapoints the retriever cannot use. */ declare class DatapointsRetrievalError extends CalculatorError { constructor(message: string); } /** Binary arithmetic operators supported by the formula grammar. */ type BinaryOp = "add" | "sub" | "mul" | "div" | "pow" | "mod"; /** Unary arithmetic operators supported by the formula grammar. */ type UnaryOp = "pos" | "neg"; /** Comparison operators supported by the formula grammar. */ type CompareOp = "eq" | "ne" | "lt" | "le" | "gt" | "ge"; /** Boolean operators supported by the formula grammar. */ type BoolOpKind = "and" | "or"; type NameNode = { readonly kind: "name"; readonly id: string; }; type ConstantNode = { readonly kind: "constant"; readonly value: number; }; type BinOpNode = { readonly kind: "binop"; readonly op: BinaryOp; readonly left: ExprNode; readonly right: ExprNode; }; type UnaryOpNode = { readonly kind: "unaryop"; readonly op: UnaryOp; readonly operand: ExprNode; }; type CompareNode = { readonly kind: "compare"; readonly left: ExprNode; readonly ops: readonly CompareOp[]; readonly comparators: readonly ExprNode[]; }; type BoolOpNode = { readonly kind: "boolop"; readonly op: BoolOpKind; readonly values: readonly ExprNode[]; }; type IfExpNode = { readonly kind: "ifexp"; readonly test: ExprNode; readonly body: ExprNode; readonly orelse: ExprNode; }; type CallNode = { readonly kind: "call"; readonly name: string; readonly args: readonly ExprNode[]; }; /** Any node of a compiled formula expression tree. */ type ExprNode = NameNode | ConstantNode | BinOpNode | UnaryOpNode | CompareNode | BoolOpNode | IfExpNode | CallNode; /** A parsed, validated formula ready to be evaluated over parameter series. */ type CompiledFormula = { /** The whitespace-normalized formula text. */ readonly raw: string; /** The formula text after placeholders were replaced with safe identifiers. */ readonly expression: string; /** The validated expression tree. */ readonly tree: ExprNode; /** Original parameter names in first-appearance order. */ readonly variables: readonly string[]; /** Mapping of original parameter name to its safe identifier. */ readonly nameMap: ReadonlyMap; /** Whether the formula needs element-by-element (short-circuiting) evaluation. */ readonly hasConditional: boolean; }; /** * Normalize the formula text, then compile it (memoized by normalized text). * Use {@link clearCache} to inspect or reset the compilation cache. */ declare function compileFormula(formula: string): CompiledFormula; /** Clear the memoized formula compilation cache. */ declare function clearCache(): void; /** A single formula parameter: an aligned sequence of numeric values. */ type ParameterValue = readonly number[]; /** The result of evaluating a formula: one value per aligned series element. */ type EvaluationResult = number[]; /** Mapping of parameter name to its numeric series. */ type Parameters = Record; /** * Evaluate a formula over aligned numeric parameter sequences. * * Placeholders are written as ``{name}`` and each resolves to the matching * entry in `parameters`. The following operators are supported: * * - arithmetic: ``+`` ``-`` ``*`` ``/`` ``**`` ``%`` (binary) and ``+`` ``-`` (unary) * - comparisons: ``==`` ``!=`` ``<`` ``<=`` ``>`` ``>=`` * - boolean: ``and`` ``or`` * - conditional: ``{A} / {B} if {B} != 0 else 0`` * - functions: ``rolling_average({A}, N)`` — same-length simple moving * average. The window ``N`` must be a positive integer constant. * Incomplete windows at the start of a series average whatever points * exist so far, so the result stays aligned with the inputs. Put * value-dependent guards *inside* the series argument: an outer * ``if`` does not protect neighbors in the window of a selected index. * * Structural problems (bad syntax, unknown identifiers, missing parameters, * mismatched lengths, non-numeric values) throw a subclass of `FormulaError`. * * When every referenced parameter is an empty sequence the result is an empty * array — there is nothing to compute over, so this is treated as a valid * (empty) result rather than an error. A *mix* of empty and non-empty * parameters is still a length mismatch and throws `ParameterLengthError`. * * Arithmetic failures that depend on the parameter *values* are surfaced as * arithmetic errors (subclasses of `ArithmeticError`) rather than * `FormulaError`: dividing or taking a modulo by zero throws * `ZeroDivisionError` and an overflowing exponentiation throws `OverflowError`. * * Conditional expressions, comparisons and boolean operators are evaluated * element-by-element: for each series element only the selected branch is * evaluated, so a division-by-zero (or other value-dependent failure) in the * branch that is *not* selected for a given element never throws. If an * index selects ``rolling_average``, the series argument is also evaluated * on that index's window (including neighbors that would not have selected * the call). A call that is never selected, and indexes that are not in any * selected window, are not evaluated. */ declare function evaluate(formula: string, parameters?: Parameters): EvaluationResult; /** * Structural formula problems (bad syntax, unknown identifiers, missing * parameters, mismatched lengths or timestamps, non-numeric values) are * reported as a subclass of {@link FormulaError}. * * Value-dependent arithmetic failures (division/modulo by zero, overflowing * exponentiation) are intentionally *not* {@link FormulaError}s: they extend * {@link ArithmeticError} instead. */ /** Base error for every structural formula problem. */ declare class FormulaError extends CalculatorError { constructor(message: string); } /** Raised when formula syntax or operations are not supported. */ declare class InvalidFormulaError extends FormulaError { constructor(message: string); } /** Raised when a formula references parameters that were not provided. */ declare class MissingParameterError extends FormulaError { readonly missing: readonly string[]; constructor(missing: string[]); } /** Raised when a parameter value is not a valid numeric sequence. */ declare class ParameterError extends FormulaError { constructor(message: string); } /** Raised when referenced parameters do not all share the same length. */ declare class ParameterLengthError extends ParameterError { readonly lengths: Readonly>; constructor(lengths: Record); } /** Raised when a query has only constants and so has no time axis. */ declare class MissingTimeAxisError extends ParameterError { readonly aliases: readonly string[]; constructor(aliases: string[]); } /** Raised when time-series parameters do not share the same timestamps. */ declare class ParameterTimestampError extends ParameterError { readonly aliases: readonly string[]; constructor(aliases: string[]); } /** * Base for value-dependent arithmetic failures. Deliberately separate from * {@link FormulaError} because these depend on the data, not the formula. */ declare class ArithmeticError extends Error { constructor(message: string); } /** Raised when a division or modulo has a zero divisor. */ declare class ZeroDivisionError extends ArithmeticError { constructor(message: string); } /** Raised when an exponentiation overflows the floating-point range. */ declare class OverflowError extends ArithmeticError { constructor(message: string); } /** * Rejects a query the calculator cannot evaluate. * * `Calculator` runs it for you; call it directly to fail early on a query * built from untrusted input, such as a JSON payload. */ declare function validateCalculatorQuery(query: unknown): void; /** Validates several queries, reporting every problem across all of them. */ declare function validateCalculatorQueries(queries: readonly unknown[]): void; export { type AlignmentMode, ArithmeticError, type CalculationResult, Calculator, CalculatorError, type CalculatorParameter, type CalculatorQuery, type CompiledFormula, type ConstantParameter, type DataPoint, DatapointsRetrievalError, type EvaluationResult, FormulaError, InvalidFormulaError, MissingParameterError, MissingTimeAxisError, type MultiTimeSeriesParameter, OverflowError, ParameterError, ParameterLengthError, ParameterTimestampError, type ParameterValue, type Parameters, type ReducerType, type Series, type TimeSeriesParameter, ZeroDivisionError, clearCache, compileFormula, evaluate, validateCalculatorQueries, validateCalculatorQuery };