stats

stats

new stats()

Main class used for statistical analyses and data cleaning.

Source:

Methods

(static) arrchange(data) → {Array.<Object>}

Changes a m x n matrix into a n x m matrix (transpose). Mainly used for creating google charts. M != N.

Parameters:
Name Type Description
data Object

Contains: nd-JS array representing [[m],[n]] matrix.

Source:
Returns:

[[n],[m]] array.

Type
Array.<Object>
Example
hydro.analyze.stats.arrchange({data: [[someSize1],[someSize2]]})

(static) autocovarianceMatrix(data, params) → {Object}

Still needs some testing Compute the autocovariance matrix from the autocorrelation values

Parameters:
Name Type Description
data Object

array with autocorrelation values

params number

number of lags

Author:
  • riya-patil
Source:
Returns:

Autocovariance matrix

Type
Object
Example
const acTestData = [1, 0.7, 0.5, 0.3];
const lags = 2
hydro.analyze.stats.autocovarianceMatrix({params: lag, data : actestData});

(static) basicstats(data) → {Array.<Object>}

Returns an array that Contains the basic statistics of a dataset. It is used afterwards to be prompted using google graphing tools.

Parameters:
Name Type Description
data Object

1d-JS array with data arranged as [data].

Source:
Returns:

flatenned array for the dataset.

Type
Array.<Object>
Example
hydro.analyze.stats.basicstats({data: [someData]})

(static) bernoulliDist(params) → {Number}

Probability mass function (PMF) of a Bernoulli distribution The Bernoulli distribution is a discrete probability distribution for a random variable that takes the value 1 with probability of success p and the value 0 with probability of failure (1-p). It models binary outcomes like success/failure, yes/no, or true/false.

Parameters:
Name Type Description
params Object

Contains: f (indicator for failure=0 or success=1) and s (probability of success, between 0 and 1)

Author:
  • riya-patil
Source:
Returns:

Probability mass function of the Bernoulli distribution at the specified point

Type
Number
Example
// Calculate probability of success (f=1) with p=0.7
hydro.analyze.stats.bernoulliDist({ params: { f: 1, s: 0.7 } }); // Returns 0.7

// Calculate probability of failure (f=0) with p=0.7
hydro.analyze.stats.bernoulliDist({ params: { f: 0, s: 0.7 } }); // Returns 0.3

(static) binomialCoefficient(trials, s) → {Number}

Calculates the binomial coefficient (n choose k format)

Parameters:
Name Type Description
trials Number

The number of trials

s Number

The number of successes

Author:
  • riya-patil
Source:
Returns:

The binomial coefficient (trials choose s)

Type
Number

(static) binomialDist(params, args) → {Number}

Calculates the probability mass function (PMF) of a Binomial Distribution The binomial distribution models the number of successes in a fixed number of independent trials, each with the same probability of success. In hydrology, it can be used to model discrete event occurrences like the number of days with rainfall exceeding a threshold in a given month, or the number of flood events in a year.

Parameters:
Name Type Description
params Object

Contains: trials (integer n ≥ 0, the total number of independent trials) and probSuccess (probability p of success in a single trial, 0 ≤ p ≤ 1)

args Object

Contains: s (integer k, 0 ≤ k ≤ n, representing the number of successes)

Author:
  • riya-patil
Source:
Returns:

The probability of getting exactly k successes in n trials with probability p of success

Type
Number
Example
// Calculate the probability of exactly 3 rainy days out of 10 days,
// when the probability of rain on any given day is 0.3
hydro.analyze.stats.binomialDist({ 
  params: { 
    trials: 10,       // 10 days observed
    probSuccess: 0.3  // 30% chance of rain on any given day
  }, 
  args: { 
    s: 3              // We want exactly 3 rainy days
  }
}); // Returns approximately 0.2668

// Find the probability of having at most 2 flood events in 5 years
// when annual probability of a flood is 0.2
// First calculate P(X=0) + P(X=1) + P(X=2)
const p0 = hydro.analyze.stats.binomialDist({ params: { trials: 5, probSuccess: 0.2 }, args: { s: 0 }});
const p1 = hydro.analyze.stats.binomialDist({ params: { trials: 5, probSuccess: 0.2 }, args: { s: 1 }});
const p2 = hydro.analyze.stats.binomialDist({ params: { trials: 5, probSuccess: 0.2 }, args: { s: 2 }});
const atMost2 = p0 + p1 + p2; // Gives the cumulative probability

(static) breuschPaganTest(params) → {Object}

Performs the Breusch-Pagan test for heteroscedasticity.

Parameters:
Name Type Description
params Object

errors: Array of residuals, regressors: Array of regressor variables

Author:
  • riya-patil
Source:
Throws:

If the input arrays have different lengths.

Type
Error
Returns:

Object containing test statistic and p-value.

Type
Object
Example
const params = {
  errors: [1, 2, 3, 4, 5],
  regressors: [[1, 1], [2, 1], [3, 1], [4, 1], [5, 1]]
};
hydro.analyze.stats.breuschPaganTest({ params });

(static) chisqCDF(x, k) → {number}

Calculates the cumulative distribution function (CDF) of the chi-square distribution NOTE: This will require revision in the future, readjusting considering lookups or fitting to a gamma distribution instead

Parameters:
Name Type Description
x number

The value at which to evaluate the CDF

k number

The degrees of freedom

Author:
  • riya-patil
Source:
Returns:

The cumulative probability

Type
number
Example
const x = 10
const df = 20
hydro.analyze.stats.chisCDF(10, 20)

(static) cleaner(data) → {Array.<Object>}

Filters out items in an array that are undefined, NaN, null, ", etc.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array with data to be cleaned as [dataValues]

Source:
Returns:

Cleaned array.

Type
Array.<Object>
Example
hydro.analyze.stats.cleaner({data: [someValues]})

(static) computeD(data) → {Number}

D-statistic Computes D-statistic from two samples to evaluate if they come from the same distribution Reference: Kottegoda & Rosso, 2008.

Parameters:
Name Type Description
data Array.<Object>

2d-JS array containing ordered as [samples_A, samples_B], with each being 1-d arrays

Author:
  • Alexander Michalek & Renato Amorim, IFC, University of Iowa.
Source:
Returns:

d-statistic of the samples

Type
Number
Example
hydro.analyze.stats.computeD({data: [samples_A, samples_B]})

(static) copydata(data) → {Object}

Makes a deep copy of original data for further manipulation.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array or object with original data.

Source:
Returns:

Deep copy of original data.

Type
Object
Example
hydro.analyze.stats.copydata({data: [someData]})

(static) correlation() → {Number}

Calculates pearson coefficient for bivariate analysis. The sets must be of the same size.

Parameters:
Name Type Description
params.data Object

An object containing the two data sets as set1 and set2.

Source:
Returns:

Pearson coefficient.

Type
Number
Example
const data = {set1: [1,2,3], set2: [2,4,6]};
const pearsonCoefficient = hydro1.analyze.stats.correlation({data})

(static) datagaps(data) → {Number}

Identifies gaps in data.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array with data as [data].

Source:
Returns:

Number of gaps in data.

Type
Number
Example
hydro.analyze.stats.datagaps({data: [someData]})

(static) dateparser(data) → {Array.<Object>}

Changes a 1d-date array into local strings. Used mainly for changing displaying into google charts.

Parameters:
Name Type Description
data Array.<Object>

Contains: 1-dJS array with date values as [dateValue].

Source:
Returns:

Array with date parsed.

Type
Array.<Object>
Example
hydro.analyze.stats.dateparser({data: [someValues]})

(static) differencing(params, data) → {Array}

Performs differencing on a time series dataset to remove trend or seasonality from the data

Parameters:
Name Type Description
params Object

Contains the order parameter

data Array

1D array of numerical values representing a time series

Author:
  • riya-patil
Source:
Throws:

If the order is invalid

Type
Error
Returns:

Differenced time series

Type
Array
Example
const order = 1;
const timeSeries = [1, 3, 6, 10, 15];
const differencedSeries = stats.differencing({ order, data: timeSeries });

(static) efficiencies(params, data) → {Number|Object}

Calculates various efficiency metrics to evaluate model performance Efficiency metrics are essential for evaluating hydrological model performance by comparing simulated outputs with observed data. These metrics help quantify the accuracy and reliability of models for streamflow prediction, water quality simulation, or other hydrological processes.

Parameters:
Name Type Description
params Object

Contains: type (type of efficiency metric to calculate) Options include: - 'NSE': Nash-Sutcliffe Efficiency (ranges from -∞ to 1, with 1 being perfect) - 'determination': Coefficient of determination (R²) (ranges from 0 to 1) - 'agreement': Index of agreement (ranges from 0 to 1) - 'all': Calculate all available metrics

data Array

Array containing two arrays: [observed, modeled] values

Source:
Returns:
  • A number representing the calculated metric, or an object containing multiple metrics if 'all' is specified
Type
Number | Object
Example
// Calculate Nash-Sutcliffe Efficiency for a streamflow model
const observedFlow = [12.5, 15.2, 22.8, 31.5, 25.4, 18.7, 10.3, 8.2];
const modeledFlow = [11.3, 14.7, 20.5, 28.9, 27.1, 16.2, 11.8, 7.5];

const nse = hydro.analyze.stats.efficiencies({ 
  params: { type: 'NSE' }, 
  data: [observedFlow, modeledFlow] 
});
console.log(`NSE: ${nse.toFixed(3)}`); // Example: NSE: 0.856

// Calculate all efficiency metrics for model evaluation
const metrics = hydro.analyze.stats.efficiencies({ 
  params: { type: 'all' }, 
  data: [observedFlow, modeledFlow] 
});

console.log(`NSE: ${metrics.NSE.toFixed(3)}`);       // Example: 0.856
console.log(`R²: ${metrics.r2.toFixed(3)}`);         // Example: 0.923
console.log(`Agreement: ${metrics.d.toFixed(3)}`);   // Example: 0.947

// Interpretation guidelines for NSE values in hydrology:
// NSE > 0.8: Excellent model performance
// 0.6 < NSE < 0.8: Very good performance
// 0.4 < NSE < 0.6: Good performance
// 0.2 < NSE < 0.4: Poor performance
// NSE < 0.2: Unacceptable performance

(static) exponentialMovingAverage(args) → {Array.<number>}

Computes the Exponential Moving Average (EMA) for a given dataset.

Parameters:
Name Type Description
args Object

Contains the dataset as 'data' (1D JavaScript array) and the 'alpha' value (smoothing factor between 0 and 1)

Author:
  • riya-patil
Source:
Returns:

The Exponential Moving Average (EMA) values for the dataset

Type
Array.<number>
Example
const dataset= [1,2,3,4,5]
const params={alpha: 0.5}
hydro.analyze.stats.exponentialMovingAverage({params, data});

(static) fastfourier(data) → {Array.<Object>}

Fast fourier analysis over a 1d dataset and see if there are any patterns within the data. Should be considered to be used for small data sets.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array with data as [data]

Source:
Returns:

calculated array.

Type
Array.<Object>
Example
hydro.analyze.stats.fastfourier({data: [someData]})

(static) flatenise(params, data) → {Array.<Object>}

Helper function for preparing nd-JSarrays for charts and tables for duration/discharge.

Parameters:
Name Type Description
params Object

Contains: columns (nd-JS array with names as [someName1, someName2,...])

data Object

Contains: nd-JS array object required to be flatenned as [[somedata1, somedata2,...],[somedata1, somedata2,...],...]

Source:
Returns:

Flatenned array.

Type
Array.<Object>
Example
hydro.analyze.stats.flatenise({params:{columns: [someName1, someName2,...]},
data: [[somedata1, somedata2,...],[somedata1, somedata2,...],...]})

(static) frequency(data) → {Object}

Calculates the frequency in data.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Object with frenquency distribution.

Type
Object
Example
hydro.analyze.stats.frequency({data: [data]})

(static) gammaCDFApprox(params, data) → {number}

Regularized incomplete gamma function approximation using series expansion.

Parameters:
Name Type Description
params Object

Parameters for the function

Properties
Name Type Description
alpha number

Shape parameter

beta number

Scale parameter

data Object

Data input (array with single value x)

Source:
Returns:

Regularized incomplete gamma CDF value

Type
number

(static) gapfiller(params, data) → {Array.<Object>}

Fills data gaps (either time missig or data missing). Unfinished.

Parameters:
Name Type Description
params Object

Contains: type (time or data)

data Object

Contains: 2d-JS array with data or time gaps to be filled as [[time],[data]].

Source:
Returns:

Array with gaps filled.

Type
Array.<Object>
Example
hydro.analyze.stats.gapfiller({params: {type: 'someType'}, data: [[time1,time2...], [data1, data2,...]]})

(static) gapremoval(data) → {Number}

Remove gaps in data with an option to fill the gap.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Number of gaps found in the data.

Type
Number
Example
hydro.analyze.stats.gapremoval({data: [someData]})

(static) gaussianDist(params) → {Number}

Computes the probability density function (PDF) of a Gaussian (normal) distribution

Parameters:
Name Type Description
params Object

x (value at which to compute the PDF), mean (mean of the distribution), and stddev (standard deviation of the distribution)

Author:
  • riya-patil
Source:
Returns:

Probability density function of the Gaussian distribution

Type
Number
Example
const testData = {
    x: 2.5,
    mean: 3,
    stddev: 1.2
  };
  hydro.analyze.stats.gaussianDist({params: testData});

(static) generateRandomData(size, rangeopt) → {Array.<number>}

Generates an array of random integers within a specified range.

Parameters:
Name Type Attributes Default Description
size number

The number of elements in the array to be generated.

range number <optional>
100

The upper limit (exclusive) of the range from which the random integers will be generated.

Source:
Returns:

An array of random integers between 0 and range-1, of length size.

Type
Array.<number>
Example
hydro.analyze.stats.generateRandomDat
(10, 50) // returns [23, 48, 15, 9, 36,
28, 39, 18, 20, 22]

(static) geometricDist(params, args) → {Number}

Calculates the probability mass function (PMF) of a Geometric Distribution

Parameters:
Name Type Description
params Object

Contains the probability of success "s" (where 0 <= s <= 1) as a parameter.

args Number

Contains the number of trials until the first success trials (trials >= 1)

Author:
  • riya-patil
Source:
Returns:

The probability of getting the first success on the n-th trial

Type
Number
Example
hydro.analyze.stats.geometricDist({ params: { s: 0.5 }, args: { trials: 3 }, data: [] });
0.125

(static) getNextState(transitionMatrix, currentState) → {number}

Gets the next state based on the transition probabilities defined in the transition matrix.

Parameters:
Name Type Description
transitionMatrix Array.<Array.<number>>

transition matrix representing the probabilities of transitioning between states.

currentState number

current state of the function

Author:
  • riya-patil
Source:
Returns:

Next state selected based on the transition probabilities.

Type
number
Example
const transitionMatrix = [
  [0.2, 0.8], 
  [0.5, 0.5],
    ];
  const initialState = 0;

(static) gevDistribution(params) → {Number}

Computes the probability density function (PDF) of the Generalized Extreme Value (GEV) distribution The GEV distribution is widely used in hydrology for modeling extreme events like maximum rainfall or flood discharges. It combines three extreme value distributions: Gumbel (Type I), Fréchet (Type II), and Weibull (Type III) into a single parametric family.

Parameters:
Name Type Description
params Object

Contains: x (value at which to compute the PDF), mu (location parameter, determines the mode of the distribution), sigma (scale parameter > 0, controls the spread of the distribution), xi (shape parameter, determines the tail behavior - xi=0 gives Gumbel, xi>0 gives Fréchet, xi<0 gives Weibull)

Author:
  • riya-patil
Source:
Returns:

Probability density function value of the GEV distribution at point x

Type
Number
Example
// Calculate PDF for Gumbel distribution (xi=0)
hydro.analyze.stats.gevDistribution({
  params: { 
    x: 50,      // Value at which to evaluate the PDF
    mu: 30,     // Location parameter
    sigma: 10,  // Scale parameter
    xi: 0       // Shape parameter (Gumbel distribution)
  }
});

// Calculate PDF for Fréchet distribution (xi>0)
hydro.analyze.stats.gevDistribution({
  params: { 
    x: 50,
    mu: 30,
    sigma: 10,
    xi: 0.2     // Positive shape parameter (heavy tail)
  }
});

(static) gumbelDist(params) → {Number}

Calculates the probability density function (PDF) of the Gumbel Distribution

Parameters:
Name Type Description
params Object

Contains the parameters 'mu' (location parameter) and 'beta' (scale parameter).

Author:
  • riya-patil
Source:
Returns:

Probability density at the given value 'x'.

Type
Number
Example
hydro.analyze.stats.gumbelDist({ params: { mu: 0, beta: 1, x: 2}})

(static) interoutliers(paramsopt, data) → {Array}

Removes interquartile outliers from an array or a set of arrays.

Parameters:
Name Type Attributes Default Description
params Object <optional>
{ q1: 0.25, q2: 0.75 }

Parameters object.

data Array

Data to filter. If a 2D array is provided, the first array will be considered as a time array.

Source:
Returns:
  • Filtered data.
Type
Array
Example
hydro.analyze.stats.interoutliers({ params: { q1: 0.25, q2: 0.75 }, data: [1, 2, 3, 100, 4, 5, 6]});

(static) itemfilter(data) → {Array.<Object>}

Filters out items in an array based on another array.

Parameters:
Name Type Description
data Object

Contains: 2d-JS array with data to be kept and removed as [[dataKept],[dataRemoved]]

Source:
Returns:

Cleaned array.

Type
Array.<Object>
Example
hydro.analyze.stats.itemfilter({data: [[dataKept], [dataRemoved]]})

(static) joinarray(data) → {Array.<Object>}

Preprocessing tool for joining arrays for table display.

Parameters:
Name Type Description
data Object

2d-JS array as [[someData1], [someData2]]

Source:
Returns:

Array for table display.

Type
Array.<Object>
Example
hydro.analyze.stats.joinarray({data: [[someData1], [someData2]]})

(static) KS_computePValue(data) → {Array.<Object>}

Kolmogorov Smirnov Two-sided Test Calculates the P value, based on the D-statistic from the function above. Reference: Kottegoda & Rosso, 2008.

Parameters:
Name Type Description
data Array.<Object>

2d-JS array containing ordered as [samples_A, samples_B], with each being 1-d arrays

Author:
  • Alexander Michalek & Renato Amorim, IFC, University of Iowa
Source:
Returns:

array with [p-Statistic, d-Statistic]

Type
Array.<Object>
Example
hydro.analyze.stats.KS_computePValue({data: [samples_A, samples_B]})

(static) KS_rejectAtAlpha(params, data) → {Number}

Reject P statistic based on a significance level alpha. Reference: Kottegoda & Rosso, 2008.

Parameters:
Name Type Description
params Object

contains {alpha: Number} with alpha being the significance level

data Array.<Object>

2d-JS array containing ordered as [samples_A, samples_B], with each being 1-d arrays

Author:
  • Alexander Michalek & Renato Amorim, IFC, University of Iowa
Source:
Returns:

rejection if p is less than the significance level

Type
Number
Example
hydro.analyze.stats.KS_rejectAtAlpha({params: {alpha: someAlpha}, data: [samples_A, samples_B]})

(static) linearMovingAverage(params, data) → {Array}

Calculates the Linear Moving Average (LMA) of a given dataset.

Parameters:
Name Type Description
params Number

Contains the windowSize parameter.

data Array

1D array of numerical values.

Author:
  • riya-patil
Source:
Throws:

If the window size is invalid.

Type
Error
Returns:

Array of moving averages.

Type
Array
Example
const windowSize = 5;
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
hydro.analyze.stats.linearMovingAverage({ windowSize, data });

(static) lognormalDist(params, args) → {Number}

Calculates the probability density function (PDF) of the Lognormal Distribution

Parameters:
Name Type Description
params Object

Contains the parameters 'mu' and 'sigma' which represent the mean and standard deviation of the associated normal distribution.

args Object

Contains the argument 'x' which represents the value at which to evaluate the PDF.

Author:
  • riya-patil
Source:
Returns:

Probability density at 'x' in the Lognormal Distribution.

Type
Number
Example
hydro.analyze.stats.lognormalDist({params: { mu: 0, sigma: 1 }, args: { x: 2 }})

(static) LogSeriesDistribution(params, args) → {Number}

Calculates the probability mass function (PMF) of the Log series Distribution

Parameters:
Name Type Description
params Object

Contains the parameter 'probSuccess' which represents the probability of success in a single trial.

args Object

Contains the argument 'trials' (trials >= 1) which represents the number of trials.

Author:
  • riya-patil
Source:
Returns:

Probability of achieving the first success in # of trials.

Type
Number
Example
hydro.analyze.stats.logSeriesDist({params: {probSuccess: 0.2, trials: 3}})

(static) matrixInverse(matrix) → {Array}

Computes the inverse of a matrix

Parameters:
Name Type Description
matrix Array

Matrix to compute inverse of

Author:
  • riya-patil
Source:
Returns:

Inverse of the matrix

Type
Array
Example
const matrix = [[1, 2, 3], [4, 5, 6]];
hydro.analyze.stats.matrixInverse(matrix)

(static) max(data) → {Number}

Maximum value of an array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Maximum value of a dataset.

Type
Number
Example
hydro.analyze.stats.max({data: [data]})

(static) mean(data) → {Number}

Calculates the mean of a 1d array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Mean of the data.

Type
Number
Example
hydro.analyze.stats.mean({data: [data]})

(static) median(data) → {Number}

Calculates the median values for a 1d array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Median of the data.

Type
Number
Example
hydro.analyze.stats.median({data: [data]})

(static) min(data) → {Number}

Minimum value of an array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Minimum value of a dataset.

Type
Number
Example
hydro.analyze.stats.min({data: [data]})

(static) MK(params, data) → {Object}

Performs the Mann-Kendall trend test for time series data The Mann-Kendall test is a non-parametric statistical test used to identify trends in time series data. In hydrology, it's widely used to detect monotonic trends in climate variables, streamflow, water quality, and other environmental data. This test is particularly valuable because it doesn't require normally distributed data and is robust against outliers.

Parameters:
Name Type Description
params Object

Contains alpha (significance level, default 0.05)

data Object

Array of time series data to test for trend

Source:
Returns:

Results containing:

  • S: Mann-Kendall statistic
  • z: Standardized test statistic
  • p: p-value of the test
  • trend: String indicating detected trend ("increasing", "decreasing", or "no trend")
  • significant: Boolean indicating if trend is statistically significant
Type
Object
Example
// Detect trend in annual streamflow data (m³/s) over 30 years
const annualStreamflow = [
  105, 98, 102, 95, 90, 100, 92, 87, 93, 85,
  88, 82, 80, 85, 78, 75, 80, 76, 72, 70,
  75, 68, 65, 72, 67, 62, 65, 60, 58, 55
];

const trendResult = hydro.analyze.stats.MK({
  params: { alpha: 0.05 },  // 5% significance level
  data: annualStreamflow
});

// Interpret the results for water resource management
if (trendResult.significant) {
  if (trendResult.trend === "decreasing") {
    console.log("Significant decreasing trend detected in streamflow");
    console.log("Water management implication: Potential water scarcity issues");
  } else if (trendResult.trend === "increasing") {
    console.log("Significant increasing trend detected in streamflow");
    console.log("Water management implication: Potential increased flood risk");
  }
} else {
  console.log("No significant trend detected in streamflow");
}
console.log(`Test statistic (S): ${trendResult.S}`);
console.log(`p-value: ${trendResult.p}`);

(static) multinomialDistribution(params) → {Object}

Multinomial Distribution - Generates random samples from a multinomial distribution.

Parameters:
Name Type Description
params Object

probabilities: 1D array of probabilities for each category; n: Number of samples to generate

Author:
  • riya-patil
Source:
Returns:

samples: 2D array of generated samples, where each row represents a sample and each column represents a category frequencies: 2D array of frequencies for each category in the generated samples

Type
Object
Example
const multinomialData = {
  probabilities: [0.2, 0.3, 0.5],
  n: 100
};
hydro.analyze.stats.multinomialDistribution({ params: multinomialData });

(static) multipleMatrix(matrix1, matrix2) → {Array}

Multiplies two matrices

Parameters:
Name Type Description
matrix1 Array

First matrix

matrix2 Array

Second matrix

Author:
  • riya-patil
Source:
Returns:

Result of matrix multiplication

Type
Array
Example
const matrix1 = [[1, 2], [3, 4]];
const matrix2 = [[5, 6], [7, 8]];
hydro.analyze.stats.multiplyMatrix(matrix1, matrix2)

(static) multiregression(data) → {Array}

Performs multivariate regression analysis

Parameters:
Name Type Description
data Object

Data for the multivariate regression

Author:
  • riya-patil
Source:
Returns:

Coefficients of the linear regression model.

Type
Array
Example
const X = [[1, 2], [3, 4], [5, 6]];
const y = [3, 5, 7];
hydro.analyze.stats.multiregression({ data: { X, y } });

(static) normalcdf(data, data) → {Array.<Object>|Number}

Normal distribution

Parameters:
Name Type Description
data Array.<Object>

Contains: 1d-JS array with timeseries

data Array.<Object>

1d-JS array

Author:
  • Alexander Michalek & Renato Amorim, IFC, University of Iowa.
Source:
Returns:
  • 1d array with 3 values: p-value, value sum and z value

    Type
    Array.<Object>
  • number value for the distribution

    Type
    Number
Example
hydro.analyze.stats.normalcdf({data: [someData]})

(static) normalDistribution(params) → {Number}

Computes the probability density function of a normal distribution.

Parameters:
Name Type Description
params Object

Contains: z-value.

Source:
Returns:

Probability density function of the normal distribution.

Type
Number
Example
hydro.analyze.stats.normalDistributio
({params: {z: 1.5}})

(static) normoutliers(paramsopt, argsopt, data, data[0]opt, data[1) → {Array}

Filters the outliers from the given data set based on its standard score (z-score).

Parameters:
Name Type Attributes Default Description
params Object <optional>
{}

An object containing optional parameters.

Properties
Name Type Attributes Default Description
low Number <optional>
-0.5

The lower threshold value for filtering data.

high Number <optional>
0.5

The higher threshold value for filtering data.

args Object <optional>

An object containing any additional arguments.

data Array

The data set to filter outliers from.

data[0] Array <optional>
[]

An optional array of timestamps corresponding to the data.

data[1 Array

The main data array containing values to filter outliers from.

Source:
Returns:

Returns the filtered data set. If timestamps are provided, it will return an array of timestamps and filtered data set as [t, out]. If no timestamps are provided, it will return the filtered data set.

Type
Array
Example
// Filter outliers from the data set between z-scores of -0.5 and 0.5
let data = [1, 2, 3, 4, 5, 10, 12, 15, 20];
let filteredData = hydro.analyze.stats.normoutliers({ params: { low: -0.5, high: 0.5 }, data: data });
// filteredData => [1, 2, 3, 4, 5, 15, 20]

// Filter outliers from the data set between z-scores of -1 and 1 with timestamps
let data = [[1, 2, 3, 4, 5, 10, 12, 15, 20], [1, 2, 3, 4, 5, 10, 12, 15, 200]];
let [timestamps, filteredData] = hydro.analyze.stats.normoutliers({ params: { low: -1, high: 1 }, data: data });
// timestamps => [1, 2, 3, 4, 5, 10, 12, 15]
// filteredData => [1, 2, 3, 4, 5, 10, 12, 15]

(static) numerise(data) → {Array.<Object>}

Turns data from numbers to strings. Usable when retrieving data or uploading data.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array with data composed of strings as [dataValues].

Source:
Returns:

Array as numbers.

Type
Array.<Object>
Example
hydro.analyze.stats.numerise({data: [someValues]})

(static) onearray(data) → {Array.<Object>}

Retrieves a 1D array with the data.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array as [data]

Source:
Returns:

Array object.

Type
Array.<Object>
Example
hydro.analyze.stats.onearray({data: [someData]})

(static) outremove(params, args, data) → {Array.<Object>}

Remove outliers from dataset. It uses p1 and p2 as outliers to remove.

Parameters:
Name Type Description
params Object

Contains: type ('normalized', 'interquartile')

args Object

Contains: p1 (low end value), p2 (high end value) both depending on outlier analysis type

data Object

Contains: 2d-JS array with time series data as [[time],[data]].

Source:
Returns:

Array with cleaned data.

Type
Array.<Object>
Example
hydro.analyze.stats.outremove({params: {type: 'someType'}, args: {p1: 'someNum', p2: 'someNum'},
data: [[time1, time2,...], [data1, data2,...]]})

(static) poissonProcess(params) → {Array}

Generates a sequence of events following a Poisson process A Poisson process models the occurrence of random events where the time between events follows an exponential distribution. In hydrology, this is useful for modeling random occurrences such as rainfall events, flood peaks, or extreme weather phenomena that happen at a known average rate but with random timing.

Parameters:
Name Type Description
params Object

Contains: - lambda (event rate, average number of events per time unit) - timeFrame (duration for which to simulate the process) - type (optional, "time" for event times or "count" for event counts in intervals)

Author:
  • riya-patil
Source:
Returns:

For type="time": Array of time points when events occur For type="count": Array of counts per unit time interval

Type
Array
Example
// Scenario: Generate a synthetic sequence of storm events over a 30-day period
// Assuming storms occur at a rate of 0.2 per day (on average, 1 storm every 5 days)

// Get the timing of storm events over the 30-day period
const stormTimes = hydro.analyze.stats.poissonProcess({
  params: {
    lambda: 0.2,      // Rate of 0.2 storms per day
    timeFrame: 30,    // 30-day simulation period
    type: "time"      // Return the timing of events
  }
});
console.log("Storm events occur at days:", stormTimes);
// Example output: [3.2, 8.7, 15.4, 21.1, 28.9]

// Or get the daily count of storms for each day in the 30-day period
const dailyStormCounts = hydro.analyze.stats.poissonProcess({
  params: {
    lambda: 0.2,      // Rate of 0.2 storms per day
    timeFrame: 30,    // 30-day simulation period
    type: "count"     // Return counts per interval
  }
});
// Example output: [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]

// This synthetic data can be used for:
// - Testing rainfall-runoff models with varying storm patterns
// - Evaluating flood risk under different precipitation scenarios
// - Studying reservoir operation under random inflow conditions

(static) push(data) → {Array.<Object>}

Pushes at the end of an array the data of another array.

Parameters:
Name Type Description
data Object

Contains: 2d-JS array with data arranged as [[willPush],[pushed]]

Source:
Returns:

Last dataset with pushed data.

Type
Array.<Object>
Example
hydro.analyze.stats.push({data: [[dataSet1], [dataSet2]]})

(static) quantile(params, data) → {Array.<Object>}

Quantile calculator for given data.

Parameters:
Name Type Description
params Object

Contains: q(quartile as 0.25, 0.75, or required)

data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Array with values fitting the quartile.

Type
Array.<Object>
Example
hydro.analyze.stats.quantile({params: {q: 'someNum'}, data: [data]})

(static) range(data) → {Array}

Gives the range of a dataset

Parameters:
Name Type Description
data Object

Contains: 1d-JS array with data as [data].

Source:
Returns:

Range of the data.

Type
Array
Example
hydro.analyze.stats.range({data: [someData]})

(static) regression(data) → {Array}

Computes the coefficients of a linear regression model.

Parameters:
Name Type Description
data Object

Object containing predictor variables (X) and target variable (y).

Author:
  • riya-patil
Source:
Returns:

Coefficients of the linear regression model.

Type
Array
Example
const X = [[1, 2], [3, 4], [5, 6]];
const y = [3, 5, 7];
hydro.analyze.stats.regression({ data: { X, y } });

(static) residualVariance(data) → {number|Error}

Computes the variance of residuals in a regression model to detect heteroskedasticity

Parameters:
Name Type Description
data Array

1D array of numerical values representing the residuals.

Author:
  • riya-patil
Source:
Returns:
  • Variance of residuals

    Type
    number
  • if not given valid array of residuals or not given correct number of arrays

    Type
    Error
Example
const residuals = [1.5, -2.1, 0.8, -1.2, 2.5];
const variance = stats.residualVariance({ data: residuals });

(static) returnPeriod(params) → {Number}

Calculates the return period for a given probability of occurrence In hydrology, the return period (or recurrence interval) represents the average time between events of a certain magnitude. It is fundamental for flood frequency analysis, infrastructure design, and risk assessment. The return period T is calculated as T = 1/p, where p is the probability of exceedance in a given year.

Parameters:
Name Type Description
params Object

Contains probability (decimal between 0 and 1, probability of occurrence in a given time unit)

Source:
Throws:

If probability is not between 0 and 1

Type
Error
Returns:

Return period (average time between events of the specified probability)

Type
Number
Example
// Calculate the return period for a flood with a 0.01 (1%) annual exceedance probability
const hundredYearFlood = hydro.analyze.stats.returnPeriod({
  params: { probability: 0.01 }
});
// Returns 100 (years)

// Calculate return periods for different design events
const designEvents = [
  { name: "2-year event", probability: 0.5 },
  { name: "10-year event", probability: 0.1 },
  { name: "25-year event", probability: 0.04 },
  { name: "50-year event", probability: 0.02 },
  { name: "100-year event", probability: 0.01 },
  { name: "500-year event", probability: 0.002 }
];

// Calculate and display the return periods
designEvents.forEach(event => {
  const period = hydro.analyze.stats.returnPeriod({
    params: { probability: event.probability }
  });
  console.log(`${event.name}: ${period} years`);
});

// This information can be used for:
// - Designing hydraulic structures like bridges, culverts, and dams
// - Establishing flood insurance rates and floodplain regulations
// - Assessing risk for critical infrastructure

(static) runMarkovChainMonteCarlo(data) → {Array.<number>}

Generates a random simulated number when run with a dataset

Parameters:
Name Type Description
data Array.<Object>

passes data from multiple objects

Author:
  • riya-patil
Source:
Returns:

returns an array of the simulated results

Type
Array.<number>
Example
const options = {
      params: {
      iterations: 100,
    },
    data: {
      initialState,
      transitionMatrix,
      },
    };
    hydro.analyze.stats.runMarkovChainMonteCarlo(options);

(static) runMonteCarlo(data) → {Array.<number>}

Generates a random simulated number when run with a dataset

Parameters:
Name Type Description
data Array.<Object>

passes data from multiple objects

Author:
  • riya-patil
Source:
Returns:

returns an array of the simulated results

Type
Array.<number>
Example
const testData = [
      [1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
    ];
    hydro.analyze.stats.runMonteCarlo({data: testData})

(static) runSimulation(data) → {Number}

Generates a random simulated number when run with a dataset

Parameters:
Name Type Description
data Object

passes data from an object

Author:
  • riya-patil
Source:
Returns:

Returns a simulated number

Type
Number
Example
const testData = [
      [1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
    ];
    hydro.analyze.stats.simulate({data: testData})

(static) runVegas(data) → {Array.<number>}

Generates a random simulated number when run with a dataset

Parameters:
Name Type Description
data Array.<Object>

passes data from multiple objects

Author:
  • riya-patil
Source:
Returns:

returns an array of the simulated results

Type
Array.<number>
Example
const testData = [
      [1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
    ];
    hydro.analyze.stats.runVegas({data: testData})

(static) simpleMovingAverage(params, data) → {Array}

Calculates the Simple Moving Average of a given data set

Parameters:
Name Type Description
params Object

Contains the parameter 'windowSize' which specifies the size of the moving average window.

data Object

Contains the array of data points.

Author:
  • riya-patil
Source:
Returns:

Array of moving average values.

Type
Array
Example
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const windowSize = 3;
hydro.analyze.stats.simpleMovingAverage({ params: { windowSize }, data });

(static) spiCompute(params, data) → {Array}

Computes the Standardized Precipitation Index (SPI) using gamma fit and inverse normal transformation.

Parameters:
Name Type Description
params Object

Parameters for SPI computation

Properties
Name Type Description
scale number

Aggregation scale for SPI (e.g., 12 for SPI-12)

data Array

Input precipitation time series (1D array)

Source:
Returns:

SPI time series

Type
Array

(static) standardize(data) → {Array.<Object>}

Use mean and standard deviation to standardize the original dataset.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Array with standardized data.

Type
Array.<Object>
Example
hydro.analyze.stats.standardize({data: [data]})

(static) stddev(data) → {Number}

Calculates standard deviation of a 1d array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Standard deviation.

Type
Number
Example
hydro.analyze.stats.stddev({data: [data]})

(static) sum(data) → {Number}

Sums all data in a 1-d array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Sum of all data in an array.

Type
Number
Example
hydro.analyze.stats.sum({data: [data]})

(static) sumsqrd(data) → {Number}

Calculates sum of squares for a dataset.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Sum of squares for data.

Type
Number
Example
hydro.analyze.stats.sumsqrd({data: [data]})

(static) timegaps(params, data) → {Array.<Object>}

Identifies gaps in time. Used for filling gaps if required by the user. Time in minutes and timestep must be divisible by the total time of the event.

Parameters:
Name Type Description
params Object

Contains: timestep (in min)

data Object

Contains: 1d-JS array with timedata in minutes as [timeData].

Source:
Returns:

Array with gaps.

Type
Array.<Object>
Example
hydro.analyze.stats.timegaps({params: {timestep: 'someNum'} data: [timeData]})

(static) transposeMatrix(matrix) → {Array}

Transposes a matrix

Parameters:
Name Type Description
matrix Array

Matrix to transpose

Author:
  • riya-patil
Source:
Returns:

Transposed matrix

Type
Array
Example
const matrix = [[1, 2, 3], [4, 5, 6]];
hydro.analyze.stats.transposeMatrix(matrix)

(static) uniformDist(params, args) → {Number}

Calculates the probability density function (PDF) of the Uniform Distribution

Parameters:
Name Type Description
params Object

Contains the parameters 'a' (lower bound) and 'b' (upper bound).

args Object

Contains the argument 'x' at which to evaluate the PDF.

Author:
  • riya-patil
Source:
Returns:

Probability density at the given value 'x'.

Type
Number
Example
hydro.analyze.stats.uniformDist({ params: { a: 0, b: 1 }, args: { x: 0.5 } })

(static) unique(data) → {Array.<Object>}

Unique values in an array.

Parameters:
Name Type Description
data Object

Contains: 1d-JS array object with data as [data].

Source:
Returns:

Array with unique values.

Type
Array.<Object>
Example
hydro.analyze.stats.unique({data: [data]})

(static) variance(data) → {Number}

Calculate variance for an 1-d array of data.

Parameters:
Name Type Description
data Object

Contains 1d-JS array object with data as [data].

Source:
Returns:

Variance of the data.

Type
Number
Example
hydro.analyze.stats.variance({data: [data]})