new stats()
Main class used for statistical analyses and data cleaning.
Methods
(static) andersonDarling(params, args, data) → {Object}
Performs the Anderson-Darling test for normality.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Array of values. |
Returns:
A2-statistic and significance.
- Type
- Object
Example
hydro.analyze.stats.andersonDarling({ data: [1, 2, 3, 4, 5] });
(static) anova(params, args, data) → {Object}
Performs a one-way ANOVA.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Array of samples (arrays) e.g., [[1,2], [3,4], [5,6]]. |
Returns:
F-statistic and degrees of freedom.
- Type
- Object
Example
hydro.analyze.stats.anova({ data: [[1, 2], [3, 4], [5, 6]] });
(static) arrchange(params, args, 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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: nd-JS array representing [[m],[n]] matrix. |
Returns:
[[n],[m]] array.
- Type
- Array.<Object>
Example
hydro.analyze.stats.arrchange({data: [[someSize1],[someSize2]]});
(static) autoCorrelation(params, args, data) → {Number}
Calculates the Autocorrelation Function (ACF) for a given lag.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: lag (k). |
args |
Object | Not used by this function. |
data |
Object | Time series array. |
Returns:
Autocorrelation at lag k.
- Type
- Number
Example
hydro.analyze.stats.autoCorrelation({ params: { lag: 1 }, data: [1, 2, 3, 4, 5] });
(static) autocovarianceMatrix(params, args, data) → {Object}
Still needs some testing Compute the autocovariance matrix from the autocorrelation values.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: lags (number of lags). |
args |
Object | Not used by this function. |
data |
Object | array with autocorrelation values. |
Returns:
Autocovariance matrix.
- Type
- Object
Example
const acTestData = [1, 0.7, 0.5, 0.3];
const lags = 2;
hydro.analyze.stats.autocovarianceMatrix({params: {lags}, data : acTestData});
(static) basicstats(params, args, data) → {Array}
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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | 1d-JS array with data arranged as [data]. |
Returns:
flatenned array for the dataset.
- Type
- Array
Example
hydro.analyze.stats.basicstats({data: [1, 2, 3, 4, 5]});
(static) bernoulliDist(params, args, data) → {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). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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) betaDist(params, args, data) → {Number}
Calculates the PDF of the Beta Distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: alpha and beta. |
args |
Object | Contains: x (value, 0 <= x <= 1). |
data |
Object | Not used by this function. |
Returns:
PDF value.
- Type
- Number
Example
hydro.analyze.stats.betaDist({ params: { alpha: 2, beta: 5 }, args: { x: 0.5 } });
(static) binomialCoefficient(params, args, data) → {Number}
Calculates the binomial coefficient (n choose k format).
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: trials (The number of trials) and s (The number of successes). |
data |
Object | Not used by this function. |
Returns:
The binomial coefficient (trials choose s).
- Type
- Number
Example
hydro.analyze.stats.binomialCoefficient(5, 2);
(static) binomialDist(params, args, data) → {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). |
data |
Object | Not used by this function. |
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) bootstrap(params, args, data) → {Object}
Performs bootstrap resampling to estimate statistics.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: iterations, statistic (function name as string or function). |
args |
Object | Not used by this function. |
data |
Object | Original data array. |
Returns:
Original statistic, mean of resamples, bias, confidence interval.
- Type
- Object
Example
hydro.analyze.stats.bootstrap({ params: { iterations: 100, statistic: 'mean' }, data: [1, 2, 3, 4, 5] });
(static) breuschPaganTest(params, args, data) → {Object}
Performs the Breusch-Pagan test for heteroscedasticity.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: errors (Array of residuals) and regressors (Array of regressor variables). |
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({ data: params });
(static) chisqCDF(params, args, data) → {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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: x (The value at which to evaluate the CDF) and k (The degrees of freedom). |
data |
Object | Not used by this function. |
Returns:
The cumulative probability.
- Type
- number
Example
const x = 10;
const df = 20;
hydro.analyze.stats.chisqCDF(10, 20);
(static) cleaner(params, args, data) → {Array.<Object>}
Filters out items in an array that are undefined, NaN, null, ", etc.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: 1d-JS array with data to be cleaned as [dataValues]. |
Returns:
Cleaned array.
- Type
- Array.<Object>
Example
hydro.analyze.stats.cleaner({data: [someValues]});
(static) computeD(params, args, 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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: sampleA and sampleB (1-d arrays). |
Returns:
d-statistic of the samples.
- Type
- Number
Example
hydro.analyze.stats.computeD({data: {sampleA: [1, 2, 3], sampleB: [1, 2, 4]}});
(static) correlation(options) → {number}
Calculate Pearson correlation coefficient for bivariate analysis Measures the linear relationship between two datasets (-1 to 1) Both datasets must be the same length
Parameters:
| Name | Type | Description | |||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Pearson correlation coefficient (-1 to 1)
- Type
- number
Examples
// Perfect positive correlation
const data1 = { set1: [1, 2, 3, 4, 5], set2: [2, 4, 6, 8, 10] };
const r1 = hydro.analyze.stats.correlation({ data: data1 });
console.log(r1); // ~1.0 (strong positive correlation)
// Compare observed vs modeled streamflow
const observed = [120, 135, 142, 138, 125];
const modeled = [118, 140, 138, 135, 128];
const r = hydro.analyze.stats.correlation({
data: { set1: observed, set2: modeled }
});
console.log(`Correlation: ${r.toFixed(3)}`); // e.g., 0.985
// Interpret correlation values:
// r = 1.0: Perfect positive correlation
// r = 0.7: Strong positive correlation
// r = 0.0: No correlation
// r = -0.7: Strong negative correlation
// r = -1.0: Perfect negative correlation
(static) datagaps(params, args, data) → {Number}
Identifies gaps in data.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | Contains: 1d-JS array with data as [data]. |
Returns:
Number of gaps in data.
- Type
- Number
Example
hydro.analyze.stats.datagaps({data: [1, NaN, 3, undefined]});
(static) dateparser(params, args, data) → {Array.<Object>}
Changes a 1d-date array into local strings. Used mainly for changing displaying into google charts.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array.<Object> | Contains: 1-dJS array with date values as [dateValue]. |
Returns:
Array with date parsed.
- Type
- Array.<Object>
Example
hydro.analyze.stats.dateparser({data: [someValues]});
(static) differencing(params, args, 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. |
args |
Object | Not used by this function. |
data |
Array | 1D array of numerical values representing a time series. |
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({ params: { order }, data: timeSeries });
(static) dotProduct(params, args, data) → {number}
Calculates the dot product of two vectors. Both vectors should be represented as 1D JS arrays with the same length.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: a (The first vector) and b (The second vector). |
data |
Object | Not used by this function. |
Throws:
-
If the input vectors have different lengths.
- Type
- Error
Returns:
The dot product.
- Type
- number
Example
const a = [1, 2, 3, 4, 5];
const b = [10, 20, 30, 40, 50];
hydro.analyze.stats.dotProduct(a,b);
(static) efficiencies(options) → {number|Object}
Calculate various efficiency metrics to evaluate hydrological model performance Essential for comparing simulated outputs with observed data Supports NSE, R², Index of Agreement, RMSE, MAE, and more
Parameters:
| Name | Type | Description | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Efficiency value, or object with all metrics if type='all'
- Type
- number | Object
Examples
// Nash-Sutcliffe Efficiency (NSE) - most common hydrological metric
// NSE = 1: Perfect model, NSE = 0: Model as good as mean, NSE < 0: Model worse than mean
const observed = [10.5, 12.3, 15.8, 18.2, 14.1, 11.7, 9.8];
const modeled = [10.2, 12.1, 16.2, 17.8, 14.5, 11.3, 10.1];
const nse = hydro.analyze.stats.efficiencies({
params: { type: 'NSE' },
data: [observed, modeled]
});
console.log(`NSE: ${nse.toFixed(3)}`); // e.g., 0.985 (excellent performance)
// Coefficient of Determination (R²)
const r2 = hydro.analyze.stats.efficiencies({
params: { type: 'determination' },
data: [observed, modeled]
});
console.log(`R²: ${r2.toFixed(3)}`); // 0 to 1, higher is better
// Calculate all metrics for comprehensive model evaluation
const metrics = hydro.analyze.stats.efficiencies({
params: { type: 'all' },
data: [observed, modeled]
});
console.log('Model Performance:');
console.log(` NSE: ${metrics.NSE.toFixed(3)}`);
console.log(` R²: ${metrics.determination.toFixed(3)}`);
console.log(` Index of Agreement: ${metrics.agreement.toFixed(3)}`);
// Interpretation guide:
// NSE: >0.75 = Very good, 0.65-0.75 = Good, 0.50-0.65 = Satisfactory, <0.50 = Unsatisfactory
// R²: >0.85 = Very good correlation
// Index of Agreement: >0.90 = Excellent agreement
(static) errorMetrics(params, args, data) → {Object}
Calculates various error metrics (RMSE, MAE, MAPE, MSE).
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: observed and modeled. |
Returns:
Object with error metrics.
- Type
- Object
Example
hydro.analyze.stats.errorMetrics({ data: { observed: [1, 2, 3], modeled: [1.1, 1.9, 3.2] } });
(static) exponentialDist(params, args, data) → {Number}
Calculates the PDF of the Exponential Distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: lambda (rate). |
args |
Object | Contains: x (value). |
data |
Object | Not used by this function. |
Returns:
PDF value.
- Type
- Number
Example
hydro.analyze.stats.exponentialDist({ params: { lambda: 1 }, args: { x: 1 } });
(static) exponentialMovingAverage(params, args, data) → {Array.<number>}
Computes the Exponential Moving Average (EMA) for a given dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: alpha (smoothing factor between 0 and 1). |
args |
Object | Not used by this function. |
data |
Object | Contains: dataset (1D JavaScript array). |
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: dataset });
(static) fastfourier(params, args, data) → {Array}
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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | Contains: 1d-JS array with data as [data]. |
Returns:
calculated array.
- Type
- Array
Example
hydro.analyze.stats.fastFourier({data: [1, 2, 3, 4]});
(static) flatenise(params, args, 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,...]). |
args |
Object | Not used by this function. |
data |
Object | Contains: nd-JS array object required to be flatenned as [[somedata1, somedata2,...],[somedata1, somedata2,...],...]. |
Returns:
Flatenned array.
- Type
- Array.<Object>
Example
hydro.analyze.stats.flatenise({params:{columns: [someName1, someName2,...]},
data: [[somedata1, somedata2,...],[somedata1, somedata2,...],...]});
(static) forwardFill(params, args, data) → {Object}
Performs forward fill to replace missing values in an array with the last non-null value.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | Array of values with missing entries. |
Returns:
Object containing the filled data array and an array of replaced indices.
- Type
- Object
Example
hydro.analyze.stats.forwardFill({data: [1, null, 3, null, null, 6]});
(static) frequency(options) → {Object}
Calculate frequency distribution of values in a dataset Returns object with each unique value as key and its count as value
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Object with value:count pairs
- Type
- Object
Examples
// Analyze precipitation frequency
const rainfall = [0, 5, 0, 0, 10, 5, 0, 15, 5];
const freq = hydro.analyze.stats.frequency({ data: rainfall });
console.log(freq); // { 0: 4, 5: 3, 10: 1, 15: 1 }
console.log(`No rain on ${freq[0]} days`);
// Find most common flow value
const flow = [100, 120, 100, 150, 120, 100, 100];
const freq = hydro.analyze.stats.frequency({ data: flow });
const mostCommon = Object.entries(freq)
.sort((a, b) => b[1] - a[1])[0];
console.log(`Most frequent flow: ${mostCommon[0]} (${mostCommon[1]} times)`);
(static) fTest(params, args, data) → {Object}
Performs an F-test for equality of variances.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: sample1 and sample2. |
Returns:
F-statistic and degrees of freedom.
- Type
- Object
Example
hydro.analyze.stats.fTest({ data: { sample1: [1, 2, 3], sample2: [4, 5, 6] } });
(static) gammaCDFApprox(params, args, data) → {Number}
Regularized incomplete gamma function approximation using series expansion.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Parameters for the function: alpha (Shape parameter), beta (Scale parameter). |
args |
Object | Not used by this function. |
data |
Array | Data input (array with single value x). |
Returns:
Regularized incomplete gamma CDF value.
- Type
- Number
Example
hydro.analyze.stats.gammaCDFApprox({params: {alpha: 2, beta: 1}, data: [1.5]});
(static) gammaDist(params, args, data) → {Number}
Calculates the PDF of the Gamma Distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: alpha (shape) and beta (scale). |
args |
Object | Contains: x (value). |
data |
Object | Not used by this function. |
Returns:
PDF value.
- Type
- Number
Example
hydro.analyze.stats.gammaDist({ params: { alpha: 2, beta: 1 }, args: { x: 3 } });
(static) gapremoval(options) → {Array}
Remove or fill gaps in data with various methods Handles NaN, null, undefined, false, and custom gap values Supports interpolation, mean, and median filling strategies
Parameters:
| Name | Type | Description | ||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Data with gaps removed or filled
- Type
- Array
Examples
// Interpolate missing values
const data = [10, NaN, 14, 16, null, 20];
const filled = hydro.analyze.stats.gapremoval({
data,
args: { method: 'interpolate' }
});
console.log(filled); // [10, 12, 14, 16, 18, 20] (interpolated)
// Fill with mean
const rainfall = [12, -9999, 15, 18, -9999, 14]; // -9999 = missing
const filled = hydro.analyze.stats.gapremoval({
data: rainfall,
params: { gapValues: [-9999] },
args: { method: 'mean' }
});
// Time series with gaps
const timeSeries = [
['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04'],
[100, NaN, 120, 125]
];
const filled = hydro.analyze.stats.gapremoval({
data: timeSeries,
args: { method: 'interpolate' }
});
(static) gaussianDist(params, args, data) → {Number}
Computes the probability density function (PDF) of a Gaussian (normal) distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: x (value at which to compute the PDF), mean (mean of the distribution), and stddev (standard deviation of the distribution). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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(params, args, data) → {Array.<number>}
Generates an array of random integers within a specified range.
Parameters:
| Name | Type | Description | |||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
params |
Object | Contains size and range. Properties
|
|||||||||||||||
args |
Object | Not used by this function. |
|||||||||||||||
data |
Object | Not used by this function. |
Returns:
An array of random integers.
- Type
- Array.<number>
Example
hydro.analyze.stats.generateRandomData({ params: { size: 10, range: 50 } });
(static) geometricDist(params, args, data) → {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 |
Object | Contains the number of trials until the first success trials (trials >= 1). |
data |
Object | Not used by this function. |
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 } });
(static) getNextState(params, args, data) → {number}
Gets the next state based on the transition probabilities defined in the transition matrix.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: transitionMatrix (number[][]) and currentState (number). |
data |
Object | Not used by this function. |
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;
hydro.analyze.stats.getNextState(transitionMatrix, initialState);
(static) gevDistribution(params, args, data) → {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). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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, args, data) → {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). |
args |
Object | Contains the argument 'x' at which to evaluate the PDF. |
data |
Object | Not used by this function. |
Returns:
Probability density at the given value 'x'.
- Type
- Number
Example
hydro.analyze.stats.gumbelDist({ params: { mu: 0, beta: 1 }, args: { x: 2 }});
(static) interoutliers(options) → {Array.<number>}
Detect and remove interquartile range (IQR) outliers Uses the 1.5*IQR rule: values beyond Q1-1.5IQR or Q3+1.5IQR are outliers More robust to extreme values than z-score method
Parameters:
| Name | Type | Description | |||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Data with outliers removed
- Type
- Array.<number>
Examples
// Remove outliers from streamflow data
const flow = [100, 105, 98, 102, 500, 101, 99, 103]; // 500 is outlier
const cleaned = hydro.analyze.stats.interoutliers({
params: { q1: 0.25, q2: 0.75 },
data: flow
});
console.log(cleaned); // [100, 105, 98, 102, 101, 99, 103] (500 removed)
// IQR method for precipitation data
const rainfall = [0, 5, 10, 8, 12, 150, 7, 9, 11]; // 150 is extreme outlier
const filtered = hydro.analyze.stats.interoutliers({ data: rainfall });
// Removes values beyond Q1-1.5*IQR and Q3+1.5*IQR
// Compare original vs cleaned data
const data = [10, 12, 11, 13, 100, 12, 11, 14, 200];
const cleaned = hydro.analyze.stats.interoutliers({ data });
console.log(`Removed ${data.length - cleaned.length} outliers`);
console.log(`Mean before: ${hydro.analyze.stats.mean({data})}`);
console.log(`Mean after: ${hydro.analyze.stats.mean({data: cleaned})}`);
(static) itemfilter(params, args, data) → {Array.<Object>}
Filters out items in an array based on another array.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: 2d-JS array with data to be kept and removed as [[dataKept],[dataRemoved]]. |
Returns:
Cleaned array.
- Type
- Array.<Object>
Example
hydro.analyze.stats.itemfilter({data: [[dataKept], [dataRemoved]]});
(static) joinarray(params, args, data) → {Array.<Object>}
Preprocessing tool for joining arrays for table display.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | 2d-JS array as [[someData1], [someData2]]. |
Returns:
Array for table display.
- Type
- Array.<Object>
Example
hydro.analyze.stats.joinarray({data: [[someData1], [someData2]]});
(static) KS_computePValue(params, args, data) → {Array}
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 |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | 2d-JS array containing ordered as [samples_A, samples_B], with each being 1-d arrays. |
Returns:
array with [p-Statistic, d-Statistic].
- Type
- Array
Example
hydro.analyze.stats.KS_computePValue({data: [[1, 2, 3], [1, 2, 4]]});
(static) KS_rejectAtAlpha(params, args, data) → {Boolean}
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. |
args |
Object | Not used by this function. |
data |
Array | 2d-JS array containing ordered as [samples_A, samples_B], with each being 1-d arrays. |
Returns:
rejection if p is less than the significance level.
- Type
- Boolean
Example
hydro.analyze.stats.KS_rejectAtAlpha({params: {alpha: 0.05}, data: [[1, 2, 3], [1, 2, 4]]});
(static) kurtosis(params, args, data) → {Number}
Calculates the kurtosis of a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | Array of numeric values. |
Returns:
Kurtosis value.
- Type
- Number
Example
hydro.analyze.stats.kurtosis({data: [1, 2, 3, 4, 5]});
(static) linearMovingAverage(params, args, data) → {Array}
Calculates the Linear Moving Average (LMA) of a given dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains the windowSize parameter. |
args |
Object | Not used by this function. |
data |
Array | 1D array of numerical values. |
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({ params: { windowSize }, data });
(static) lognormalDist(params, args, data) → {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. |
data |
Object | Not used by this function. |
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, data) → {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. |
data |
Object | Not used by this function. |
Returns:
Probability of achieving the first success in # of trials.
- Type
- Number
Example
hydro.analyze.stats.logSeriesDist({params: {probSuccess: 0.2}, args: {trials: 3}});
(static) mannWhitney(params, args, data) → {Object}
Performs the Mann-Whitney U test for independent samples.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: sample1 and sample2. |
Returns:
U-statistic and p-value (approximate).
- Type
- Object
Example
hydro.analyze.stats.mannWhitney({ data: { sample1: [1, 2, 3], sample2: [4, 5, 6] } });
(static) matrixInverse(params, args, data) → {Array}
Computes the inverse of a matrix.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: matrix (Matrix to compute inverse of). |
data |
Object | Not used by this function. |
Returns:
Inverse of the matrix.
- Type
- Array
Example
const matrix = [[1, 2, 3], [4, 5, 6]];
hydro.analyze.stats.matrixInverse(matrix);
(static) max(options) → {number}
Find the maximum value in a dataset Automatically preprocesses data to handle complex structures
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Maximum value in the dataset
- Type
- number
Examples
// Find peak daily temperature
const temps = [22, 18, 25, 20, 19];
const maxTemp = hydro.analyze.stats.max({ data: temps });
console.log(`Highest temperature: ${maxTemp}°C`); // 25°C
// Find peak flow for flood analysis
const streamflow = [125.5, 138.2, 542.8, 135.1, 129.6];
const peakFlow = hydro.analyze.stats.max({ data: streamflow });
console.log(`Peak flow: ${peakFlow} m³/s`); // 542.8 m³/s
(static) mean(options) → {number}
Calculate the arithmetic mean (average) of a dataset Returns 0 for empty arrays, handles NaN values gracefully
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Arithmetic mean of the dataset, or 0 if empty
- Type
- number
Examples
// Calculate average temperature
const temps = [22.5, 23.1, 21.8, 24.2, 23.5];
const avgTemp = hydro.analyze.stats.mean({ data: temps });
console.log(avgTemp); // 23.02
// Calculate mean streamflow
const flow = [125.5, 138.2, 142.8, 135.1, 129.6];
const avgFlow = hydro.analyze.stats.mean({ data: flow });
console.log(`Average flow: ${avgFlow.toFixed(2)} m³/s`);
(static) median(options) → {number}
Calculate the median (middle value) of a dataset Handles both odd and even-length arrays, automatically sorts data Robust to outliers compared to mean
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Median value of the dataset, or 0 if empty
- Type
- number
Examples
// Odd number of values
const values1 = [1, 2, 3, 4, 5];
console.log(hydro.analyze.stats.median({ data: values1 })); // 3
// Even number of values (average of two middle values)
const values2 = [1, 2, 3, 4];
console.log(hydro.analyze.stats.median({ data: values2 })); // 2.5
// Median is robust to outliers
const precipitation = [10, 12, 11, 13, 100]; // 100 is outlier
console.log(hydro.analyze.stats.mean({ data: precipitation })); // 29.2 (affected by outlier)
console.log(hydro.analyze.stats.median({ data: precipitation })); // 12 (not affected)
(static) min(options) → {number}
Find the minimum value in a dataset Automatically preprocesses data to handle complex structures
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Minimum value in the dataset
- Type
- number
Examples
// Find minimum daily temperature
const temps = [22, 18, 25, 20, 19];
const minTemp = hydro.analyze.stats.min({ data: temps });
console.log(`Lowest temperature: ${minTemp}°C`); // 18°C
// Useful for finding lowest flow in a period
const streamflow = [125.5, 138.2, 142.8, 135.1, 129.6];
const minFlow = hydro.analyze.stats.min({ data: streamflow });
(static) MK(params, args, 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) |
args |
Object | Not used by this function. |
data |
Array | Array of time series data to test for trend |
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
});
(static) multinomialDistribution(params, args, data) → {Object}
Multinomial Distribution - Generates random samples from a multinomial distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: probabilities (1D array of probabilities for each category), n (Number of samples to generate). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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) multiplyMatrix(params, args, data) → {Array}
Multiplies two matrices.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: matrix1 and matrix2. |
data |
Object | Not used by this function. |
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(params, args, data) → {Array}
Performs multivariate regression analysis.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Data for the multivariate regression. |
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(params, args, data) → {Array}
Normal distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | Contains: 1d-JS array with timeseries. |
Returns:
1d array with probabilities.
- Type
- Array
Example
hydro.analyze.stats.normalcdf({data: [1.96, -1.96]});
(static) normalDistribution(params, args, data) → {Number}
Computes the probability density function of a normal distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: z (z-value). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
Returns:
Probability density function of the normal distribution.
- Type
- Number
Example
hydro.analyze.stats.normalDistribution({params: {z: 1.5}});
(static) normoutliers(options) → {Object}
Detect outliers using z-score (standard score) method Returns threshold bounds based on number of standard deviations Values beyond these thresholds are considered outliers
Parameters:
| Name | Type | Description | |||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Object with min and max threshold values
- Type
- Object
Examples
// Standard 3-sigma rule (|z| > 3 is outlier)
const flow = [100, 105, 98, 102, 500, 101, 99];
const bounds = hydro.analyze.stats.normoutliers({
params: { lowerBound: -3, upperBound: 3 },
data: flow
});
console.log(`Outliers beyond: ${bounds.min} - ${bounds.max}`);
// Custom threshold for flow data
const rainfall = [10, 12, 11, 150, 13, 12];
const bounds = hydro.analyze.stats.normoutliers({
params: { lowerBound: -2, upperBound: 2 },
data: rainfall
});
const outliers = rainfall.filter(v => v < bounds.min || v > bounds.max);
(static) numerise(params, args, data) → {Array.<Object>}
Turns data from numbers to strings. Usable when retrieving data or uploading data.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: 1d-JS array with data composed of strings as [dataValues]. |
Returns:
Array as numbers.
- Type
- Array.<Object>
Example
hydro.analyze.stats.numerise({data: [someValues]});
(static) outremove(params, args, data) → {Array}
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: thresholds ([min, max]), replaceValue (value to replace outliers with). |
data |
Array | Contains: 2d-JS array with time series data as [[time],[data]]. |
Returns:
Array with cleaned data.
- Type
- Array
Example
hydro.analyze.stats.outremove({args: {thresholds: [0, 10], replaceValue: 0}, data: [1, 15, 5]});
(static) partialAutoCorrelation(params, args, data) → {Number}
Calculates the Partial Autocorrelation Function (PACF) for a given lag. Uses the Yule-Walker equations (recursive method).
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: lag (k). |
args |
Object | Not used by this function. |
data |
Object | Time series array. |
Returns:
PACF at lag k.
- Type
- Number
Example
hydro.analyze.stats.partialAutoCorrelation({ params: { lag: 1 }, data: [1, 2, 3, 4, 5] });
(static) poissonProcess(params, args, data) → {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) |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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(params, args, data) → {Array.<Object>}
Pushes at the end of an array the data of another array.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: 2d-JS array with data arranged as [[willPush],[pushed]]. |
Returns:
Last dataset with pushed data.
- Type
- Array.<Object>
Example
hydro.analyze.stats.push({data: [[dataSet1], [dataSet2]]});
(static) quantile(options) → {number}
Calculate quantiles (percentiles) of a dataset Returns the value below which a given percentage of observations fall Uses linear interpolation between data points
Parameters:
| Name | Type | Description | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Value at the specified quantile
- Type
- number
Examples
// Calculate quartiles
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const Q1 = hydro.analyze.stats.quantile({ params: { q: 0.25 }, data }); // 25th percentile
const Q2 = hydro.analyze.stats.quantile({ params: { q: 0.5 }, data }); // 50th percentile (median)
const Q3 = hydro.analyze.stats.quantile({ params: { q: 0.75 }, data }); // 75th percentile
console.log(`Q1: ${Q1}, Q2: ${Q2}, Q3: ${Q3}`);
// Calculate 95th percentile for flood frequency analysis
const annualPeaks = [450, 520, 480, 650, 590, 510, 720, 480, 550, 610];
const P95 = hydro.analyze.stats.quantile({ params: { q: 0.95 }, data: annualPeaks });
console.log(`95th percentile flow: ${P95} m³/s`);
(static) randomWalk(params, args, data) → {Array}
Generates a random walk time series.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: steps, startValue, drift, volatility. |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
Returns:
Random walk series.
- Type
- Array
Example
hydro.analyze.stats.randomWalk({ params: { steps: 50, startValue: 0, drift: 0, volatility: 1 } });
(static) range(params, args, data) → {Array}
Gives the range of a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: N (number of steps). |
args |
Object | Not used by this function. |
data |
Array | Contains: 1d-JS array with data as [data]. |
Returns:
Range of the data.
- Type
- Array
Example
hydro.analyze.stats.range({data: [1, 5, 10]});
hydro.analyze.stats.range({params: {N: 5}, data: [1, 10]});
(static) regression(params, args, data) → {Array}
Computes the coefficients of a linear regression model.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Object containing predictor variables (X) and target variable (y). |
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(params, args, data) → {number|Error}
Computes the variance of residuals in a regression model to detect heteroskedasticity.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Array | 1D array of numerical values representing the residuals. |
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, args, data) → {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). |
args |
Object | Not used by this function. |
data |
Object | Not used by this function. |
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(params, args, data) → {Array}
Generates a random simulated number when run with a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: iterations (default 100), callback (optional function). |
args |
Object | Not used by this function. |
data |
Object | Contains: initialState and transitionMatrix. |
Returns:
returns an array of the simulated results.
- Type
- Array
Example
const options = {
params: {
iterations: 100,
},
data: {
initialState: 0,
transitionMatrix: [[0.5, 0.5], [0.5, 0.5]],
},
};
hydro.analyze.stats.runMarkovChainMonteCarlo(options);
(static) runMonteCarlo(params, args, data) → {Array}
Generates a random simulated number when run with a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: iterations (default 100), callback (optional function). |
args |
Object | Not used by this function. |
data |
Array | passes data from multiple objects. |
Returns:
returns an array of the simulated results.
- Type
- Array
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(params, args, data) → {Number}
Generates a random simulated number when run with a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: multiplier (optional, default 1). |
args |
Object | Not used by this function. |
data |
Array | passes data from an object. |
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.runSimulation({data: testData});
(static) runVegas(params, args, data) → {Array}
Generates a random simulated number when run with a dataset.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: iterations (default 100), callback (optional function). |
args |
Object | Not used by this function. |
data |
Array | passes data from multiple objects. |
Returns:
returns an array of the simulated results.
- Type
- Array
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) seasonalDecompose(params, args, data) → {Array}
Decomposes a time series into Trend, Seasonal, and Residual components using Classical Decomposition (Moving Averages).
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains:
|
args |
Object | Not used. |
data |
Array | Input time series data. |
Returns:
Array of arrays: [observed, trend, seasonal, residuals].
- Type
- Array
Example
const [obs, trend, seas, resid] = hydro.analyze.stats.seasonalDecompose({
params: { period: 12, model: 'additive' },
data: [...]
});
(static) shapiroWilk(params, args, data) → {Object}
Performs the Shapiro-Wilk test for normality. Uses polynomial approximations for coefficients (Royston, 1992) for n <= 50. For n > 50, this implementation falls back to a simplified approximation or should ideally use the Shapiro-Francia test.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Array of values. |
Returns:
W-statistic and p-value.
- Type
- Object
Example
hydro.analyze.stats.shapiroWilk({ data: [1, 2, 3, 4, 5] });
(static) simpleMovingAverage(params, args, 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. |
args |
Object | Not used by this function. |
data |
Array | Contains the array of data points. |
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) skewness(options) → {number}
Calculate skewness of a distribution Measures asymmetry of the probability distribution Positive skew: long tail on right, Negative skew: long tail on left
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Skewness coefficient
- Type
- number
Examples
// Symmetric distribution (skewness ≈ 0)
const symmetric = [1, 2, 3, 4, 5, 4, 3, 2, 1];
const skew1 = hydro.analyze.stats.skewness({ data: symmetric });
console.log(skew1); // ≈ 0 (symmetric)
// Right-skewed flood peaks (common in hydrology)
const floods = [100, 120, 110, 130, 500]; // 500 creates right skew
const skewness = hydro.analyze.stats.skewness({ data: floods });
console.log(skewness); // Positive value (right-skewed)
// Interpretation:
// skewness > 0: Right-skewed (tail extends right)
// skewness = 0: Symmetric
// skewness < 0: Left-skewed (tail extends left)
(static) spiCompute(params, args, 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
|
||||||
args |
Object | Not used by this function. |
||||||
data |
Object | Input precipitation time series (1D array). |
Returns:
SPI time series.
- Type
- Array
Example
hydro.analyze.hydro.spiCompute({ params: { scale: 12 }, data: [10, 20, 30, 40, 50] });
(static) standardize(options) → {Array.<number>}
Standardize data using z-score normalization Transforms data to have mean=0 and standard deviation=1 Useful for comparing variables on different scales
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Standardized data (z-scores)
- Type
- Array.<number>
Examples
// Standardize flow data
const flow = [100, 150, 200, 250, 300];
const zScores = hydro.analyze.stats.standardize({ data: flow });
console.log(zScores); // [-1.41, -0.71, 0, 0.71, 1.41] (approximately)
// Compare variables on different scales
const temp = [20, 25, 30]; // °C
const precip = [10, 50, 100]; // mm
const tempStd = hydro.analyze.stats.standardize({ data: temp });
const precipStd = hydro.analyze.stats.standardize({ data: precip });
// Now both have mean=0, std=1 and can be compared
// Identify outliers (|z| > 3 is often considered outlier)
const data = [10, 12, 11, 13, 100, 12, 11];
const zScores = hydro.analyze.stats.standardize({ data });
const outliers = data.filter((v, i) => Math.abs(zScores[i]) > 3);
console.log(outliers); // [100]
(static) stddev(options) → {number}
Calculate the standard deviation of a dataset Measures the amount of variation or dispersion from the mean Uses population standard deviation formula (divides by N, not N-1)
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Standard deviation of the dataset, or 0 if empty
- Type
- number
Examples
// Calculate variability in temperature
const dailyTemps = [20, 22, 19, 23, 21, 20, 22];
const tempStdDev = hydro.analyze.stats.stddev({ data: dailyTemps });
console.log(`Temperature variability: ±${tempStdDev.toFixed(2)}°C`);
// Compare variability of two streamflow datasets
const upstream = [100, 105, 98, 102, 101];
const downstream = [200, 350, 150, 400, 180];
console.log('Upstream stddev:', hydro.analyze.stats.stddev({ data: upstream })); // ~2.5
console.log('Downstream stddev:', hydro.analyze.stats.stddev({ data: downstream })); // ~99.8 (more variable)
(static) sum(options) → {number}
Calculate the sum of all values in a dataset Automatically handles complex data structures through preprocessing
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Sum of all values in the array
- Type
- number
Examples
// Basic sum
const total = hydro.analyze.stats.sum({ data: [1, 2, 3, 4] });
console.log(total); // 10
// Works with precipitation data
const dailyRainfall = [12.5, 0, 5.2, 18.3, 3.1];
const weeklyTotal = hydro.analyze.stats.sum({ data: dailyRainfall });
console.log(`Total rainfall: ${weeklyTotal} mm`);
(static) sumsqrd(options) → {number}
Calculate sum of squared values Used in variance calculations and sum of squared errors
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Sum of squared values
- Type
- number
Examples
// Calculate sum of squares
const data = [1, 2, 3, 4];
const ss = hydro.analyze.stats.sumsqrd({ data });
console.log(ss); // 1² + 2² + 3² + 4² = 30
// Used in error calculations
const errors = [0.5, -1.2, 0.8, -0.3];
const sse = hydro.analyze.stats.sumsqrd({ data: errors });
console.log(`Sum of squared errors: ${sse}`);
(static) timegaps(params, args, data) → {Array}
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). |
args |
Object | Not used by this function. |
data |
Array | Contains: 1d-JS array with timedata in minutes as [timeData]. |
Returns:
Array with gaps.
- Type
- Array
Example
hydro.analyze.stats.timegaps({params: {timestep: 60}, data: [0, 60, 180, 240]});
(static) transposeMatrix(params, args, data) → {Array}
Transposes a matrix.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Contains: matrix (Matrix to transpose). |
data |
Object | Not used by this function. |
Returns:
Transposed matrix.
- Type
- Array
Example
const matrix = [[1, 2, 3], [4, 5, 6]];
hydro.analyze.stats.transposeMatrix(matrix);
(static) tTest(params, args, data) → {Object}
Performs a t-test (one-sample, two-sample independent, or paired).
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: type ('one', 'two', 'paired') and mu (for one-sample). |
args |
Object | Not used by this function. |
data |
Object | Contains: sample1 and sample2 (optional). |
Returns:
t-statistic and degrees of freedom.
- Type
- Object
Example
hydro.analyze.stats.tTest({ params: { type: 'one', mu: 0 }, data: { sample1: [1, 2, 3] } });
(static) uniformDist(params, args, data) → {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. |
data |
Object | Not used by this function. |
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(options) → {Array.<number>}
Extract unique values from a dataset Removes duplicates and returns only distinct values
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Array containing only unique values
- Type
- Array.<number>
Examples
// Get unique precipitation values
const dailyRain = [0, 5, 0, 12, 5, 0, 18, 12];
const uniqueValues = hydro.analyze.stats.unique({ data: dailyRain });
console.log(uniqueValues); // [0, 5, 12, 18]
// Count number of unique flow values
const flow = [100, 120, 100, 150, 120, 100];
const unique = hydro.analyze.stats.unique({ data: flow });
console.log(`${unique.length} unique flow values:`, unique);
(static) variance(options) → {number}
Calculate the variance of a dataset Variance is the average of squared deviations from the mean Standard deviation squared (σ²)
Parameters:
| Name | Type | Description | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object | Function options Properties
|
Returns:
Variance of the dataset, or 0 if empty
- Type
- number
Examples
// Calculate variance of rainfall data
const rainfall = [10, 15, 12, 18, 14];
const variance = hydro.analyze.stats.variance({ data: rainfall });
const stddev = Math.sqrt(variance); // or use stats.stddev()
console.log(`Variance: ${variance.toFixed(2)}, StdDev: ${stddev.toFixed(2)}`);
// Variance is in squared units
const flow = [100, 120, 90, 110]; // flow in m³/s
const var_flow = hydro.analyze.stats.variance({ data: flow });
console.log(`Variance: ${var_flow} (m³/s)²`);
(static) weibullDist(params, args, data) → {Number}
Calculates the PDF of the Weibull Distribution.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Contains: k (shape) and lambda (scale). |
args |
Object | Contains: x (value). |
data |
Object | Not used by this function. |
Returns:
PDF value.
- Type
- Number
Example
hydro.analyze.stats.weibullDist({ params: { k: 2, lambda: 1 }, args: { x: 1 } });
(static) wilcoxonSignedRank(params, args, data) → {Object}
Performs the Wilcoxon Signed-Rank test for paired samples.
Parameters:
| Name | Type | Description |
|---|---|---|
params |
Object | Not used by this function. |
args |
Object | Not used by this function. |
data |
Object | Contains: sample1 and sample2. |
Returns:
W-statistic and p-value (approximate).
- Type
- Object
Example
hydro.analyze.stats.wilcoxonSignedRank({ data: { sample1: [1, 2, 3], sample2: [1.1, 2.1, 3.1] } });