/**
 * @file index.d.ts
 * @description Comprehensive TypeScript declarations for scirs2-wasm.
 *
 * This file provides hand-authored type declarations that supplement the
 * auto-generated wasm-bindgen `*.d.ts` file.  Import from `scirs2-wasm`
 * (the package entry-point) rather than from this file directly.
 *
 * All numeric arrays accepted by the WASM layer may be passed as either
 * a native `Float64Array` or a plain `number[]`; the JS/WASM bridge
 * converts both transparently.
 */

// ---------------------------------------------------------------------------
// Re-export raw WASM types (generated by wasm-bindgen)
// ---------------------------------------------------------------------------
export type { WasmArray, WasmMatrix, PerformanceTimer } from "../pkg/scirs2_wasm";

// ===========================================================================
// SECTION 1 — Statistics: descriptive structs
// ===========================================================================

/**
 * Full descriptive statistics for a numeric dataset.
 *
 * Obtained from {@link compute_descriptive_stats}.
 *
 * All statistics use **population** formulas (ddof=0) for variance and
 * standard deviation.  The `count` field is the number of non-NaN
 * observations.
 *
 * Call `.free()` when done to release WASM memory.
 */
export interface IDescriptiveStats {
    /** Arithmetic mean. */
    readonly mean: number;
    /** Population variance (ddof=0). */
    readonly variance: number;
    /** Population standard deviation (ddof=0). */
    readonly std_dev: number;
    /** Minimum value in the dataset. */
    readonly min: number;
    /** Maximum value in the dataset. */
    readonly max: number;
    /** Median (50th percentile via linear interpolation). */
    readonly median: number;
    /** Fisher's skewness (third standardised central moment). */
    readonly skewness: number;
    /**
     * Excess kurtosis (fourth standardised central moment minus 3).
     * Positive values indicate heavier tails than a normal distribution.
     */
    readonly kurtosis: number;
    /** Number of observations. */
    readonly count: number;
    /** Sum of all observations. */
    readonly sum: number;
    /** First quartile (25th percentile). */
    readonly q25: number;
    /** Third quartile (75th percentile). */
    readonly q75: number;
    /** Interquartile range (q75 - q25). */
    readonly iqr: number;
}

/**
 * WASM-backed class; implements {@link IDescriptiveStats}.
 * Must call `.free()` after use.
 */
export declare class DescriptiveStats implements IDescriptiveStats {
    readonly mean: number;
    readonly variance: number;
    readonly std_dev: number;
    readonly min: number;
    readonly max: number;
    readonly median: number;
    readonly skewness: number;
    readonly kurtosis: number;
    readonly count: number;
    readonly sum: number;
    readonly q25: number;
    readonly q75: number;
    readonly iqr: number;
    free(): void;
}

/**
 * Compute comprehensive descriptive statistics for a dataset.
 *
 * Returns a {@link DescriptiveStats} object — **must be freed** after use.
 *
 * @example
 * ```ts
 * const ds = compute_descriptive_stats(new Float64Array([1, 2, 3, 4, 5]));
 * console.log(ds.mean, ds.std_dev, ds.skewness);
 * ds.free();
 * ```
 */
export declare function compute_descriptive_stats(
    data: Float64Array | number[]
): DescriptiveStats;

// ===========================================================================
// SECTION 2 — Statistics: linear regression
// ===========================================================================

/**
 * OLS simple linear regression result: y = slope·x + intercept.
 *
 * Obtained from {@link wasm_linear_regression_typed}.
 * Must call `.free()` after use.
 */
export declare class WasmLinearModel {
    /** Regression slope β₁. */
    readonly slope: number;
    /** Regression intercept β₀. */
    readonly intercept: number;
    /** Coefficient of determination R² ∈ [0, 1]. */
    readonly r_squared: number;
    /** Standard error of the slope estimate. */
    readonly std_err_slope: number;
    /** Standard error of the intercept estimate. */
    readonly std_err_intercept: number;
    /** Number of observations used. */
    readonly n: number;

    /**
     * Predict ŷ for a new x value.
     * @param x — predictor value.
     */
    predict(x: number): number;

    /**
     * Predict ŷ for an array of x values.
     * @param xs — predictor values.
     */
    predict_batch(xs: Float64Array | number[]): Float64Array;

    free(): void;
}

/**
 * Fit OLS simple linear regression y = slope·x + intercept.
 *
 * Returns a {@link WasmLinearModel} — **must be freed** after use.
 * All fields are `NaN` if the input is invalid (fewer than 2 points,
 * length mismatch, or constant x).
 */
export declare function wasm_linear_regression_typed(
    x: Float64Array | number[],
    y: Float64Array | number[]
): WasmLinearModel;

// ===========================================================================
// SECTION 3 — Statistics: hypothesis tests
// ===========================================================================

/**
 * Result of a Student's t-test.
 *
 * Obtained from {@link wasm_t_test_one_sample_typed} or
 * {@link wasm_t_test_two_sample_typed}.
 * Must call `.free()` after use.
 */
export declare class WasmTTestResult {
    /** t-statistic. */
    readonly t_stat: number;
    /** Two-tailed p-value. */
    readonly p_value: number;
    /** Degrees of freedom. */
    readonly df: number;
    /** True when p_value < 0.05. */
    readonly significant_at_05: boolean;
    /** True when p_value < 0.01. */
    readonly significant_at_01: boolean;
    free(): void;
}

/**
 * One-sample t-test: tests whether the sample mean equals `mu`.
 *
 * Returns a {@link WasmTTestResult} — **must be freed** after use.
 * All fields are `NaN` / `false` for samples with fewer than 2 elements.
 *
 * @param data — sample values.
 * @param mu   — hypothesised population mean.
 */
export declare function wasm_t_test_one_sample_typed(
    data: Float64Array | number[],
    mu: number
): WasmTTestResult;

/**
 * Two-sample Welch t-test: tests whether the means of `x` and `y` differ.
 *
 * Returns a {@link WasmTTestResult} — **must be freed** after use.
 *
 * @param x — first sample.
 * @param y — second sample.
 */
export declare function wasm_t_test_two_sample_typed(
    x: Float64Array | number[],
    y: Float64Array | number[]
): WasmTTestResult;

// ===========================================================================
// SECTION 4 — Statistics: KS test
// ===========================================================================

/**
 * Result of the Kolmogorov–Smirnov normality test.
 *
 * Obtained from {@link wasm_ks_test_normality}.
 * Must call `.free()` after use.
 */
export declare class WasmKSResult {
    /**
     * KS test statistic D — maximum absolute deviation between the
     * empirical CDF and the Gaussian CDF fit to the data.
     */
    readonly statistic: number;
    /** Approximate two-tailed p-value via the Kolmogorov asymptotic distribution. */
    readonly p_value: number;
    /**
     * True when p_value > 0.05 (i.e. we fail to reject the null hypothesis
     * of normality at α = 0.05).
     */
    readonly is_normal_at_05: boolean;
    free(): void;
}

/**
 * Kolmogorov–Smirnov normality test (Lilliefors variant approximation).
 *
 * Tests whether `data` is consistent with a Normal distribution by comparing
 * the empirical CDF against the Gaussian CDF with the same sample mean and
 * standard deviation.
 *
 * Returns a {@link WasmKSResult} — **must be freed** after use.
 * `statistic` is `NaN` for samples with fewer than 3 elements.
 */
export declare function wasm_ks_test_normality(
    data: Float64Array | number[]
): WasmKSResult;

// ===========================================================================
// SECTION 5 — Statistics: histogram
// ===========================================================================

/**
 * Histogram result.
 *
 * Obtained from {@link wasm_histogram}.
 * Must call `.free()` after use.
 */
export declare class WasmHistogram {
    /** Bin edges — length = n_bins + 1. */
    readonly edges: Float64Array;
    /** Count of observations in each bin — length = n_bins. */
    readonly counts: Uint32Array;
    /**
     * Probability density in each bin: count / (total * bin_width).
     * Integrates to 1 over all bins.
     */
    readonly density: Float64Array;
    /** Number of bins. */
    readonly n_bins: number;
    /** Total number of observations counted. */
    readonly total: number;

    /** Centre of each bin — length = n_bins. */
    bin_centers(): Float64Array;

    /** Width of each bin (uniform spacing). */
    bin_width(): number;

    free(): void;
}

/**
 * Compute a histogram of `data` with `n_bins` equally-spaced bins.
 *
 * The bins span `[min(data), max(data)]`; the last bin is closed on the right.
 * Returns an empty histogram if `data` is empty or `n_bins` is 0.
 *
 * The returned object — **must be freed** after use.
 *
 * @example
 * ```ts
 * const h = wasm_histogram(new Float64Array([1,2,2,3,3,3,4]), 4);
 * console.log(h.edges, h.counts);
 * h.free();
 * ```
 */
export declare function wasm_histogram(
    data: Float64Array | number[],
    n_bins: number
): WasmHistogram;

// ===========================================================================
// SECTION 6 — Statistics: correlation helpers
// ===========================================================================

/**
 * Spearman rank correlation coefficient ρ ∈ [-1, 1].
 *
 * Converts each array to fractional ranks (average ranks for ties) and
 * computes Pearson correlation on the rank vectors.
 *
 * @returns `NaN` for empty or mismatched-length inputs, or constant arrays.
 */
export declare function wasm_spearman_correlation_typed(
    x: Float64Array | number[],
    y: Float64Array | number[]
): number;

// ===========================================================================
// SECTION 7 — Signal processing (enhanced)
// ===========================================================================

/**
 * Forward FFT of a real-valued signal.
 *
 * The input is zero-padded to the next power of two.
 * The output is a flat interleaved array `[re₀, im₀, re₁, im₁, …]`
 * of length `2 * N` where `N` is the padded length.
 *
 * @returns Empty array for empty input.
 */
export declare function wasm_fft_real(signal: Float64Array | number[]): Float64Array;

/**
 * Inverse FFT of a complex spectrum, returning the real part.
 *
 * The input must be an interleaved `(re, im)` array of **even** length,
 * as produced by {@link wasm_fft_real}.
 *
 * @returns Empty array for invalid input.
 */
export declare function wasm_ifft_real(spectrum: Float64Array | number[]): Float64Array;

/**
 * One-sided Power Spectral Density via Welch's method.
 *
 * Divides the signal into 50%-overlapping Hann-windowed segments of
 * `segment_len` samples, computes the FFT of each, and averages the
 * squared magnitudes.
 *
 * @param signal       — real-valued input signal.
 * @param sample_rate  — sampling rate in Hz (must be > 0).
 * @param segment_len  — segment length (rounded up internally to the next power of two).
 *
 * @returns One-sided PSD values of length `⌈segment_len/2⌉ + 1` (units: signal²/Hz).
 *          Returns an empty array on invalid input.
 */
export declare function wasm_power_spectral_density(
    signal: Float64Array | number[],
    sample_rate: number,
    segment_len: number
): Float64Array;

/**
 * Short-Time Fourier Transform magnitude spectrogram.
 *
 * Slides a Hann window of length `window_size` over the signal with a step
 * of `hop_size` samples and returns the FFT magnitude at each frame.
 *
 * @param signal      — real-valued input signal.
 * @param window_size — FFT window length (zero-padded to next power of two).
 * @param hop_size    — step between consecutive frames (must be ≥ 1).
 *
 * @returns Flattened row-major `Float64Array` of shape `(n_frames, n_freq)`
 *          where `n_freq = window_size / 2 + 1`.
 *          Access element `(frame, freq)`: `result[frame * n_freq + freq]`.
 *          Returns empty array on invalid input.
 */
export declare function wasm_stft(
    signal: Float64Array | number[],
    window_size: number,
    hop_size: number
): Float64Array;

/**
 * Linear convolution of `signal` and `kernel` (full output).
 *
 * Output length = `signal.length + kernel.length - 1`.
 * Uses direct O(N·M) computation for small sizes and FFT-based convolution
 * for larger sizes (threshold: N·M > 4096).
 *
 * @returns Empty array if either input is empty.
 */
export declare function wasm_convolution_1d(
    signal: Float64Array | number[],
    kernel: Float64Array | number[]
): Float64Array;

/**
 * Causal boxcar (uniform) moving average.
 *
 * Each output element is the mean of the immediately preceding `window`
 * samples (including the current sample), using a sliding-sum for O(n)
 * complexity.
 *
 * @param signal — input signal.
 * @param window — window length (must be ≥ 1 and ≤ signal.length).
 *
 * @returns Output of the same length as `signal`, or empty array on invalid params.
 */
export declare function wasm_moving_average_simple(
    signal: Float64Array | number[],
    window: number
): Float64Array;

/**
 * Second-order Butterworth low-pass IIR filter (bilinear transform design).
 *
 * Attenuates frequencies above `cutoff_hz` with a 12 dB/octave roll-off.
 * Applied as a single second-order section (biquad) in Direct Form II Transposed.
 *
 * @param signal      — input real-valued signal.
 * @param cutoff_hz   — -3 dB cutoff frequency in Hz (must be in `(0, sample_rate/2)`).
 * @param sample_rate — sampling rate in Hz.
 *
 * @returns Filtered signal of the same length, or empty array on invalid params.
 */
export declare function wasm_butter_lowpass(
    signal: Float64Array | number[],
    cutoff_hz: number,
    sample_rate: number
): Float64Array;

/**
 * Compute the frequency axis for a real FFT output.
 *
 * @param n           — number of samples in the time-domain signal.
 * @param sample_rate — sampling rate in Hz.
 *
 * @returns `Float64Array` of length `n / 2 + 1` with frequency values in Hz.
 */
export declare function wasm_fft_frequencies(n: number, sample_rate: number): Float64Array;

/**
 * Magnitude (absolute value) of an interleaved FFT output.
 *
 * @param spectrum — interleaved `(re, im)` array from {@link wasm_fft_real}.
 * @returns Magnitude array of length `spectrum.length / 2`.
 */
export declare function wasm_fft_magnitude(spectrum: Float64Array | number[]): Float64Array;

/**
 * Phase (argument) in radians of an interleaved FFT output.
 *
 * @param spectrum — interleaved `(re, im)` array from {@link wasm_fft_real}.
 * @returns Phase array of length `spectrum.length / 2`, values in `(-π, π]`.
 */
export declare function wasm_fft_phase(spectrum: Float64Array | number[]): Float64Array;

// ===========================================================================
// SECTION 8 — Linear algebra (existing wasm_ prefixed flat-slice API)
// ===========================================================================

/** Flat matrix-matrix multiplication (m×k) · (k×n) → (m×n). */
export declare function wasm_matmul(
    a: Float64Array | number[],
    b: Float64Array | number[],
    m: number,
    k: number,
    n: number
): Float64Array;

/** Transpose a flat row-major matrix. */
export declare function wasm_transpose(
    a: Float64Array | number[],
    rows: number,
    cols: number
): Float64Array;

/** Dot product of two equal-length vectors. */
export declare function wasm_dot_product(
    a: Float64Array | number[],
    b: Float64Array | number[]
): number;

/** L2 (Euclidean) norm of a vector. */
export declare function wasm_l2_norm(v: Float64Array | number[]): number;

/** Element-wise vector addition. */
export declare function wasm_vec_add(
    a: Float64Array | number[],
    b: Float64Array | number[]
): Float64Array;

/** Element-wise vector subtraction. */
export declare function wasm_vec_sub(
    a: Float64Array | number[],
    b: Float64Array | number[]
): Float64Array;

/** Scalar multiplication. */
export declare function wasm_vec_scale(v: Float64Array | number[], scalar: number): Float64Array;

/**
 * Solve [a,b; c,d] · [x; y] = [e; f].
 * Returns `[x, y]` or `[NaN, NaN]` if singular.
 */
export declare function wasm_solve_2x2(
    a: number, b: number, c: number, d: number, e: number, f: number
): Float64Array;

/**
 * Thin QR decomposition via Modified Gram-Schmidt.
 * Returns flat `[Q_flat (rows×k), R_flat (k×cols)]` where `k = min(rows, cols)`.
 */
export declare function wasm_qr(
    a: Float64Array | number[],
    rows: number,
    cols: number
): Float64Array;

/**
 * Power-iteration thin SVD.
 * Returns flat `[U_flat (rows×k), S (k), V_flat (cols×k)]`.
 */
export declare function wasm_svd_power(
    a: Float64Array | number[],
    rows: number,
    cols: number,
    n_components: number
): Float64Array;

/** Frobenius norm of a flat matrix: sqrt(Σ aᵢⱼ²). */
export declare function wasm_frobenius_norm(a: Float64Array | number[]): number;

/** Z-score normalisation: (vᵢ - mean) / std. */
export declare function wasm_normalize(v: Float64Array | number[]): Float64Array;

/** Solve n×n linear system from flat row-major A and vector b. */
export declare function wasm_matrix_solve(
    a: Float64Array | number[],
    b: Float64Array | number[],
    n: number
): Float64Array;

/** Full thin Golub-Reinsch SVD as JSON. */
export declare function wasm_svd(
    data: Float64Array | number[],
    rows: number,
    cols: number
): SvdJsonResult;

/** Structured JSON result from {@link wasm_svd}. */
export interface SvdJsonResult {
    /** Left singular vectors — rows × k (k = min(rows, cols)). */
    readonly U: number[][];
    /** Singular values in descending order — length k. */
    readonly s: number[];
    /** Right singular vectors (transposed) — k × cols. */
    readonly Vt: number[][];
    /** Numerical rank. */
    readonly rank: number;
    readonly rows: number;
    readonly cols: number;
}

// ===========================================================================
// SECTION 9 — Statistics (existing wasm_ prefixed raw-slice API)
// ===========================================================================

/** Arithmetic mean. Returns `NaN` for empty input. */
export declare function wasm_mean(data: Float64Array | number[]): number;

/** Sample standard deviation (ddof=1). Returns `NaN` for fewer than 2 samples. */
export declare function wasm_std(data: Float64Array | number[]): number;

/** Pearson correlation coefficient ρ ∈ [-1, 1]. */
export declare function wasm_pearson_correlation(
    x: Float64Array | number[],
    y: Float64Array | number[]
): number;

/** Two-sample Welch t-test as JSON. */
export declare function wasm_t_test(
    x: Float64Array | number[],
    y: Float64Array | number[]
): WasmTTestJson | string;

/** Simple OLS linear regression as JSON. */
export declare function wasm_linear_regression(
    x: Float64Array | number[],
    y: Float64Array | number[]
): WasmLinearRegressionJson | string;

/** JSON shape returned by {@link wasm_t_test}. */
export interface WasmTTestJson {
    readonly statistic: number;
    readonly p_value: number;
    readonly degrees_of_freedom: number;
}

/** JSON shape returned by {@link wasm_linear_regression}. */
export interface WasmLinearRegressionJson {
    readonly slope: number;
    readonly intercept: number;
    readonly r2: number;
}

// ===========================================================================
// SECTION 10 — FFT (existing module, re-declared for convenience)
// ===========================================================================

/** Forward FFT of interleaved complex input → interleaved complex output. */
export declare function fft(data: Float64Array | number[]): Float64Array;

/** Inverse FFT of interleaved complex input → interleaved complex output. */
export declare function ifft(data: Float64Array | number[]): Float64Array;

/** Real FFT (input real, output interleaved half-spectrum). */
export declare function rfft(data: Float64Array | number[]): Float64Array;

/** Inverse real FFT. */
export declare function irfft(data: Float64Array | number[], n?: number): Float64Array;

/** FFT frequency bins in cycles/sample ([-0.5, +0.5)). */
export declare function fftfreq(n: number, d?: number): Float64Array;

/** FFT magnitude spectrum. */
export declare function fft_magnitude(data: Float64Array | number[]): Float64Array;

/** FFT phase spectrum. */
export declare function fft_phase(data: Float64Array | number[]): Float64Array;

/** One-sided power spectrum. */
export declare function power_spectrum(data: Float64Array | number[]): Float64Array;

// ===========================================================================
// SECTION 11 — WasmMatrix class
// ===========================================================================

/**
 * Dense row-major f64 matrix with wasm-bindgen bindings.
 *
 * Element `(r, c)` is at index `r * cols + c` in the internal flat storage.
 *
 * Must call `.free()` when done.
 *
 * @example
 * ```ts
 * const m = new WasmMatrix(3, 3);
 * m.set(0, 0, 1); m.set(1, 1, 2); m.set(2, 2, 3);
 * const d = m.determinant();
 * const evs = m.eigenvalues();
 * m.free();
 * ```
 */
export declare class WasmMatrix {
    /**
     * Create a zero-initialised matrix.
     * @throws {Error} if rows or cols is 0.
     */
    constructor(rows: number, cols: number);

    /**
     * Create a matrix from a flat row-major array.
     * @throws {Error} if data.length !== rows * cols.
     */
    static from_vec(rows: number, cols: number, data: number[]): WasmMatrix;

    /** Create an n×n identity matrix. */
    static identity(n: number): WasmMatrix;

    /** Number of rows. */
    rows(): number;

    /** Number of columns. */
    cols(): number;

    /**
     * Get element at (row, col).
     * @throws {Error} if indices are out of bounds.
     */
    get(row: number, col: number): number;

    /**
     * Set element at (row, col).
     * @throws {Error} if indices are out of bounds.
     */
    set(row: number, col: number, val: number): void;

    /** Return a copy of the flat row-major data. */
    to_vec(): number[];

    /** Matrix multiplication: this × other. Throws on shape mismatch. */
    multiply(other: WasmMatrix): WasmMatrix;

    /** Transpose. */
    transpose(): WasmMatrix;

    /** Determinant (square matrices only). */
    determinant(): number;

    /** Matrix inverse (square matrices only). Throws if singular. */
    inverse(): WasmMatrix;

    /** Eigenvalues of a square matrix (real parts via QR iteration). */
    eigenvalues(): number[];

    /** Frobenius norm: sqrt(Σ aᵢⱼ²). */
    norm_frobenius(): number;

    /** Trace (sum of diagonal elements). */
    trace(): number;

    /** Element-wise addition. */
    add(other: WasmMatrix): WasmMatrix;

    /** Element-wise subtraction. */
    sub(other: WasmMatrix): WasmMatrix;

    /** Scalar multiplication. */
    scale(s: number): WasmMatrix;

    free(): void;
}

// ===========================================================================
// SECTION 12 — High-level TypeScript facade types
// ===========================================================================

/** Result of the high-level {@link SciRS2.stats} method. */
export interface StatsResult {
    readonly mean: number;
    readonly std: number;
    readonly variance: number;
    readonly median: number;
    readonly min: number;
    readonly max: number;
    readonly sum: number;
    readonly count: number;
}

/** Result of the high-level {@link SciRS2.tTest} method. */
export interface TTestResult {
    readonly statistic: number;
    readonly p_value: number;
    readonly degrees_of_freedom: number;
}

/** Result of the high-level {@link SciRS2.linearRegression} method. */
export interface LinearRegressionResult {
    readonly slope: number;
    readonly intercept: number;
    readonly r2: number;
}

/** Thin SVD from {@link SciRS2.svdPower}. */
export interface PowerSvdResult {
    /** Left singular vectors, shape [rows, k], row-major. */
    readonly U: Float64Array;
    /** Singular values in descending order. */
    readonly S: Float64Array;
    /** Right singular vectors, shape [cols, k], column-major. */
    readonly V: Float64Array;
    /** Number of components computed. */
    readonly k: number;
}

/** Thin QR from {@link SciRS2.qr}. */
export interface QrResult {
    /** Q factor, shape [rows, k], row-major. */
    readonly Q: Float64Array;
    /** R factor, shape [k, cols], row-major. */
    readonly R: Float64Array;
    /** Effective rank k = min(rows, cols). */
    readonly k: number;
}

/** Paired FFT result from {@link SciRS2.fft}. */
export interface FftResult {
    /** Interleaved (re, im) pairs from the raw FFT. */
    readonly complex: Float64Array;
    /** Magnitude spectrum. */
    readonly magnitude: Float64Array;
    /** Phase spectrum in radians. */
    readonly phase: Float64Array;
}

/** STFT result from {@link SciRS2.stft}. */
export interface StftResult {
    /**
     * Flattened magnitude spectrogram (n_frames × n_freq), row-major.
     * Access element (frame, freq): `data[frame * n_freq + freq]`.
     */
    readonly data: Float64Array;
    /** Number of time frames. */
    readonly n_frames: number;
    /** Number of frequency bins (= window_size / 2 + 1). */
    readonly n_freq: number;
    /** Frequency bin edges in Hz (requires sample_rate). */
    readonly frequencies?: Float64Array;
}

/** PSD result from {@link SciRS2.psd}. */
export interface PsdResult {
    /** One-sided PSD values (units: signal²/Hz). */
    readonly values: Float64Array;
    /** Frequency axis in Hz. */
    readonly frequencies: Float64Array;
}

/** Matrix decomposition info from {@link SciRS2.matrixDecomp}. */
export interface MatrixDecompResult {
    readonly eigenvalues: number[];
    readonly norm: number;
    readonly trace: number;
    readonly determinant: number;
}

/** Minimisation result from {@link SciRS2.minimize}. */
export interface MinimizeResult {
    readonly x: number | number[];
    readonly fun: number;
    readonly nit: number;
    readonly success: boolean;
}

// ===========================================================================
// SECTION 13 — TypeScript Matrix wrapper class
// ===========================================================================

/**
 * A lightweight TypeScript wrapper around a flat `Float64Array` with shape
 * metadata.  Provides a NumPy-like interface for constructing and inspecting
 * matrices before passing them to the WASM layer.
 *
 * For heavy computation, prefer constructing a {@link WasmMatrix} directly.
 */
export declare class Matrix {
    /** Flat row-major data. */
    readonly data: Float64Array;
    readonly rows: number;
    readonly cols: number;

    /**
     * Construct from flat data.
     * @throws {RangeError} if data.length !== rows * cols.
     */
    constructor(data: Float64Array | number[], rows: number, cols: number);

    /** Shape as `[rows, cols]`. */
    readonly shape: [number, number];

    /** Get element at (r, c). */
    get(r: number, c: number): number;

    /** Set element at (r, c). */
    set(r: number, c: number, v: number): void;

    /** Lift to a {@link WasmMatrix} for WASM operations. */
    toWasmMatrix(): WasmMatrix;

    /** Create from a {@link WasmMatrix}. */
    static fromWasmMatrix(m: WasmMatrix): Matrix;

    /** All-zeros matrix. */
    static zeros(rows: number, cols: number): Matrix;

    /** Identity matrix. */
    static identity(n: number): Matrix;

    /**
     * Construct from a 2-D array of arrays.
     * @throws {RangeError} if rows are jagged.
     */
    static fromArray2D(data: number[][]): Matrix;

    /** Convert to a 2-D array of arrays. */
    toArray2D(): number[][];
}

// ===========================================================================
// SECTION 14 — SciRS2 high-level facade
// ===========================================================================

/**
 * High-level scientific computing facade over the scirs2-wasm bindings.
 *
 * Obtain an instance via `await init()`.
 *
 * @example
 * ```ts
 * import { init } from "scirs2-wasm";
 * const sci = await init();
 *
 * // Statistics
 * const ds = sci.descriptiveStats(new Float64Array([1, 2, 3, 4, 5]));
 *
 * // Signal processing
 * const psd = sci.psd(signal, 1000, 256);
 * const spec = sci.stft(signal, 128, 64);
 *
 * // Linear algebra
 * const { Q, R } = sci.qr(flatMatrix, rows, cols);
 * ```
 */
export declare class SciRS2 {
    // -- Linear algebra (WasmMatrix-based) ------------------------------------

    /** Matrix–matrix multiplication using the WasmMatrix API. */
    matmul(a: Matrix, b: Matrix): Matrix;

    /** Solve Ax = b using the WasmArray solver. */
    solve(a: Matrix, b: Float64Array): Float64Array;

    /** Eigenvalues, norm, trace, determinant of a square matrix. */
    matrixDecomp(a: Matrix): MatrixDecompResult;

    // -- Linear algebra (flat-slice API) -------------------------------------

    /** Matrix-matrix multiplication (flat). */
    matmulFlat(
        a: Float64Array,
        b: Float64Array,
        m: number,
        k: number,
        n: number
    ): Float64Array;

    /** Transpose a flat row-major matrix. */
    transposeFlat(a: Float64Array, rows: number, cols: number): Float64Array;

    /** Dot product. */
    dotProduct(a: Float64Array, b: Float64Array): number;

    /** L2 norm. */
    l2Norm(v: Float64Array): number;

    /** Element-wise addition. */
    vecAdd(a: Float64Array, b: Float64Array): Float64Array;

    /** Element-wise subtraction. */
    vecSub(a: Float64Array, b: Float64Array): Float64Array;

    /** Scalar multiplication. */
    vecScale(v: Float64Array, scalar: number): Float64Array;

    /** Solve 2×2 system. */
    solve2x2(
        a: number, b: number, c: number, d: number, e: number, f: number
    ): [number, number];

    /** Thin QR decomposition. */
    qr(a: Float64Array, rows: number, cols: number): QrResult;

    /** Power-iteration thin SVD. */
    svdPower(
        a: Float64Array,
        rows: number,
        cols: number,
        nComponents: number
    ): PowerSvdResult;

    /** Frobenius norm. */
    frobeniusNorm(a: Float64Array): number;

    /** Z-score normalisation. */
    normalize(v: Float64Array): Float64Array;

    // -- Statistics (typed struct API) ----------------------------------------

    /**
     * Compute comprehensive descriptive statistics.
     * Returns a typed {@link DescriptiveStats} struct — **must be freed**.
     */
    descriptiveStats(data: Float64Array): DescriptiveStats;

    /**
     * Fit OLS linear regression and return a typed model — **must be freed**.
     */
    linearRegressionTyped(x: Float64Array, y: Float64Array): WasmLinearModel;

    /**
     * One-sample t-test — returns a typed result **must be freed**.
     */
    tTestOneSample(data: Float64Array, mu: number): WasmTTestResult;

    /**
     * Two-sample Welch t-test — returns a typed result **must be freed**.
     */
    tTestTwoSample(x: Float64Array, y: Float64Array): WasmTTestResult;

    /**
     * KS normality test — returns a typed result **must be freed**.
     */
    ksTest(data: Float64Array): WasmKSResult;

    /**
     * Histogram — returns a typed result **must be freed**.
     */
    histogram(data: Float64Array, nBins: number): WasmHistogram;

    /** Spearman rank correlation coefficient. */
    spearmanCorrelation(x: Float64Array, y: Float64Array): number;

    // -- Statistics (raw-slice API) -------------------------------------------

    rawMean(data: Float64Array): number;
    rawStd(data: Float64Array): number;
    pearsonCorrelation(x: Float64Array, y: Float64Array): number;
    tTest(x: Float64Array, y: Float64Array): TTestResult;
    linearRegression(x: Float64Array, y: Float64Array): LinearRegressionResult;

    /** Compute high-level stats from a Float64Array. */
    stats(data: Float64Array): StatsResult;

    // -- Signal processing (enhanced) -----------------------------------------

    /**
     * Forward FFT of a real signal.
     * Pads to next power of two; returns interleaved (re, im) pairs plus
     * convenience magnitude and phase arrays.
     */
    fftReal(signal: Float64Array): FftResult;

    /**
     * Inverse FFT (real part only).
     * Input must be interleaved (re, im) pairs from {@link fftReal}.
     */
    ifftReal(spectrum: Float64Array): Float64Array;

    /**
     * One-sided Power Spectral Density (Welch method).
     */
    psd(
        signal: Float64Array,
        sampleRate: number,
        segmentLen: number
    ): PsdResult;

    /**
     * Short-Time Fourier Transform magnitude spectrogram.
     */
    stft(
        signal: Float64Array,
        windowSize: number,
        hopSize: number,
        sampleRate?: number
    ): StftResult;

    /**
     * Convolve a signal with a kernel (full output).
     * Uses FFT-based convolution for large inputs automatically.
     */
    convolve1D(signal: Float64Array, kernel: Float64Array): Float64Array;

    /**
     * Causal boxcar moving average.
     */
    movingAverage(signal: Float64Array, window: number): Float64Array;

    /**
     * Second-order Butterworth low-pass IIR filter.
     */
    butterLowpass(
        signal: Float64Array,
        cutoffHz: number,
        sampleRate: number
    ): Float64Array;

    // -- Spectral (existing) --------------------------------------------------

    /** Complex FFT (interleaved input/output). */
    fft(signal: Float64Array): FftResult;

    /** Inverse complex FFT. */
    ifft(complex: Float64Array): Float64Array;

    /** Convolve (existing binding, full mode). */
    convolve(signal: Float64Array, kernel: Float64Array): Float64Array;

    // -- Optimisation ---------------------------------------------------------

    minimize(a: number, b: number, tol?: number, maxIter?: number): MinimizeResult;
}

// ===========================================================================
// SECTION 15 — Module initialisation
// ===========================================================================

/**
 * Initialise the SciRS2 WASM module.
 *
 * Must be called (and awaited) exactly once before invoking any other API.
 * Returns a {@link SciRS2} facade instance.
 *
 * @param wasmPath — Optional path / URL override for the `.wasm` binary.
 *
 * @example
 * ```ts
 * import { init } from "scirs2-wasm";
 * const sci = await init();
 * ```
 */
export declare function init(wasmPath?: string): Promise<SciRS2>;

// Utility functions
export declare function version(): string;
export declare function log(message: string): void;
export declare function has_simd_support(): boolean;
export declare function capabilities(): Record<string, unknown>;
export declare function memory_usage(): Record<string, unknown>;

// ===========================================================================
// SECTION 16 — Machine Learning (ml module)
// ===========================================================================

/**
 * Lightweight linear regression / ridge regression model for client-side
 * inference.  Weights are stored as f64 arrays and can be serialized to JSON.
 */
export declare class WasmKMeans {
    free(): void;
    /** Number of cluster centroids. */
    readonly k: number;
    /**
     * Construct a WasmKMeans model with `k` clusters.
     * @param k  Number of clusters (≥ 1).
     * @param maxIter  Maximum number of Lloyd's iterations (default 100).
     */
    constructor(k: number, maxIter?: number);
    /**
     * Fit the model on `data` (row-major flat array, `nRows × nCols`).
     * @param data  Flat f64 feature matrix.
     * @param nCols  Number of features per sample.
     */
    fit(data: Float64Array, nCols: number): void;
    /**
     * Predict the cluster label for a single sample.
     * @param sample  f64 feature vector of length `nCols`.
     */
    predict(sample: Float64Array): number;
    /** Serialize model weights as a JSON string. */
    to_json(): string;
    /** Restore a model from a JSON string produced by {@link to_json}. */
    static from_json(json: string): WasmKMeans;
}

/** Gaussian Naïve Bayes classifier for multi-class problems. */
export declare class WasmNaiveBayes {
    free(): void;
    /**
     * Construct a WasmNaiveBayes classifier.
     * @param numClasses  Total number of target classes.
     * @param numFeatures  Number of features per sample.
     */
    constructor(numClasses: number, numFeatures: number);
    /**
     * Fit on labeled training data.
     * @param data  Flat f64 feature matrix (row-major, `nRows × numFeatures`).
     * @param labels  Integer class labels for each row.
     * @param nRows  Number of training samples.
     */
    fit(data: Float64Array, labels: Uint32Array, nRows: number): void;
    /**
     * Predict the class label for a single feature vector.
     * @param sample  f64 feature vector of length `numFeatures`.
     */
    predict(sample: Float64Array): number;
    /** Log-probability scores for all classes for a single sample. */
    predict_log_proba(sample: Float64Array): Float64Array;
    /** Serialize model to a JSON string. */
    to_json(): string;
    /** Deserialize model from a JSON string produced by {@link to_json}. */
    static from_json(json: string): WasmNaiveBayes;
}

/**
 * Batch prediction helpers (operate on a flat matrix without loading a model
 * object, useful when weights arrive at the last moment).
 */
export declare function linear_model_predict_batch(
    weights: Float64Array,
    bias: number,
    data: Float64Array,
    nCols: number,
): Float64Array;

export declare function kmeans_predict_batch(
    centroids: Float64Array,
    nCols: number,
    data: Float64Array,
): Uint32Array;

export declare function naive_bayes_predict_batch(
    data: Float64Array,
    nCols: number,
    modelJson: string,
): Uint32Array;

// ===========================================================================
// SECTION 17 — Streaming Computation (streaming module)
// ===========================================================================

/**
 * Incremental mean, variance, and skewness via Welford's online algorithm.
 *
 * Suitable for long data streams where storing all values is impractical.
 */
export declare class OnlineStats {
    free(): void;
    constructor();
    /** Feed a single sample. */
    update(x: number): void;
    /** Feed a batch of samples. */
    update_batch(xs: Float64Array): void;
    /** Current sample count. */
    count(): number;
    /** Running arithmetic mean. */
    mean(): number;
    /** Running population variance (ddof=0). */
    variance(): number;
    /** Running population standard deviation (ddof=0). */
    std_dev(): number;
    /** Running skewness (Fisher–Pearson). */
    skewness(): number;
    /** Reset all accumulators. */
    reset(): void;
}

/** Rolling window statistics (mean, variance, min, max) over the last N samples. */
export declare class RollingWindow {
    free(): void;
    /**
     * Create a rolling window of size `n`.
     * @param n  Window length (≥ 1).
     */
    constructor(n: number);
    /** Push a new sample, evicting the oldest when full. */
    push(x: number): void;
    /** Rolling mean over the current window. */
    mean(): number;
    /** Rolling population variance (ddof=0). */
    variance(): number;
    /** Minimum value in the current window. */
    min(): number;
    /** Maximum value in the current window. */
    max(): number;
    /** Number of samples currently stored (≤ window size). */
    len(): number;
    /** Whether the window contains no samples. */
    is_empty(): boolean;
}

/**
 * Overlap-add FFT for streaming audio / time-series data.
 *
 * Suitable for processing data that arrives in variable-length chunks.
 */
export declare class StreamingFFT {
    free(): void;
    /**
     * Create a streaming FFT processor.
     * @param frameLen  FFT frame length (must be a power of two).
     * @param hopLen    Hop size between consecutive frames.
     */
    constructor(frameLen: number, hopLen: number);
    /**
     * Push a chunk of samples and obtain any complete FFT frames.
     * @param samples  New f32 audio samples.
     * @returns  Interleaved (re, im) FFT frames, or empty if no frame was completed.
     */
    push(samples: Float32Array): Float32Array;
    /** Flush remaining buffered samples (zero-padded to fill the last frame). */
    flush(): Float32Array;
    /** Number of FFT frames produced so far. */
    frames_produced(): number;
}

/**
 * Generic accumulate → process → emit pipeline.
 *
 * Buffers incoming samples until a configurable block size is reached,
 * then calls an internal processing step and emits the result.
 */
export declare class BufferedProcessor {
    free(): void;
    /**
     * Construct a buffered processor.
     * @param blockSize  Number of f64 samples per processing block.
     */
    constructor(blockSize: number);
    /**
     * Push a batch of samples into the internal buffer.
     * @returns  Processed output block if `blockSize` samples are ready, else null.
     */
    push_batch(samples: Float64Array): Float64Array | null;
    /** Flush any remaining buffered samples with zero-padding. */
    flush(): Float64Array | null;
    /** Total number of samples ingested. */
    samples_ingested(): number;
    /** Total number of blocks emitted. */
    blocks_emitted(): number;
}

// ===========================================================================
// SECTION 18 — SIMD-Accelerated Operations (simd_ops module)
// ===========================================================================

/** Whether WASM SIMD128 is active in this build. */
export declare function simd_ops_available(): boolean;

/**
 * Dot product of two f32 vectors (SIMD128-accelerated when available).
 * @throws  If `a.length !== b.length`.
 */
export declare function simd_dot_product_f32(a: Float32Array, b: Float32Array): number;

/**
 * Square matrix multiplication C = A × B, where A, B, C are `n × n` f32 matrices
 * in row-major flat form (SIMD128-accelerated when available).
 * @throws  If array lengths do not match `n * n`.
 */
export declare function simd_matrix_multiply_f32(
    a: Float32Array,
    b: Float32Array,
    n: number,
): Float32Array;

/**
 * Numerically stable softmax activation (SIMD128-accelerated when available).
 * @throws  If `input` is empty.
 */
export declare function simd_softmax_f32(input: Float32Array): Float32Array;

/** Element-wise ReLU activation (SIMD128-accelerated when available). */
export declare function simd_relu_f32(input: Float32Array): Float32Array;

/** Element-wise sigmoid activation (SIMD128-accelerated when available). */
export declare function simd_sigmoid_f32(input: Float32Array): Float32Array;

/**
 * Element-wise addition of two f32 vectors (SIMD128-accelerated when available).
 * @throws  If `a.length !== b.length`.
 */
export declare function simd_add_f32(a: Float32Array, b: Float32Array): Float32Array;

/**
 * Element-wise multiplication of two f32 vectors (SIMD128-accelerated when available).
 * @throws  If `a.length !== b.length`.
 */
export declare function simd_mul_f32(a: Float32Array, b: Float32Array): Float32Array;

/** L2 norm (Euclidean length) of an f32 vector (SIMD128-accelerated when available). */
export declare function simd_l2_norm_f32(input: Float32Array): number;

// ===========================================================================
// SECTION 19 — WebWorker Communication (worker module)
// ===========================================================================

/** A flat, transferable representation of an ndarray-compatible tensor. */
export declare class TransferableArray {
    free(): void;
    /** Flat row-major data buffer. */
    data: Float64Array;
    /** Shape of the array, e.g. `[3, 4]` for a 3×4 matrix. */
    shape: number[];
    /** Data type tag (`"f64"`). */
    dtype: string;
    /**
     * Construct from flat data and shape.
     * @throws  If `data.length !== shape.reduce((a, b) => a * b, 1)`.
     */
    constructor(data: Float64Array, shape: number[]): TransferableArray;
    /** Total number of elements. */
    numel(): number;
    /** Number of dimensions. */
    ndim(): number;
    /** Serialize to a JSON string for `postMessage` transfer. */
    to_json(): string;
    /** Deserialize from a JSON string produced by {@link to_json}. */
    static from_json(json: string): TransferableArray;
}

/** Pool of (virtual) worker entries with state tracking. */
export declare class WorkerPool {
    free(): void;
    /** Construct a pool with `maxWorkers` slots. */
    constructor(maxWorkers: number): WorkerPool;
    /** Register a worker with the given id. Returns true if successful. */
    register_worker(id: number): boolean;
    /** Mark a worker as busy. Returns false if the worker is not registered. */
    mark_busy(id: number): boolean;
    /** Mark a worker as idle. Returns false if the worker is not registered. */
    mark_idle(id: number): boolean;
    /** Remove a worker from the pool. */
    remove_worker(id: number): boolean;
    /** Number of currently idle workers. */
    idle_count(): number;
    /** Number of currently busy workers. */
    busy_count(): number;
    /** Total number of registered workers. */
    total_count(): number;
    /** Whether the pool has capacity for another worker. */
    has_capacity(): boolean;
}

/**
 * Serialize an f64 array with a shape tag into a JSON string suitable for
 * passing via `postMessage` to a Worker.
 */
export declare function serialize_for_worker(
    data: Float64Array,
    shape: number[],
): string;

/**
 * Deserialize a {@link TransferableArray} from a JSON string produced by
 * {@link serialize_for_worker}.
 */
export declare function deserialize_from_worker(json: string): TransferableArray;

/**
 * Parse a raw worker message JSON string and return a typed JS value
 * describing the message kind and payload.
 */
export declare function parse_worker_message(json: string): unknown;
