geodezyx.stats package

Submodules

geodezyx.stats.least_squares module

@author: psakic

This sub-module of geodezyx.stats contains functions for least-squares processing.

it can be imported directly with: from geodezyx import stats

The geodezyx toolbox is a software for simple but useful functions for Geodesy and Geophysics under the GNU LGPL v3 License

Copyright (C) 2019 Pierre Sakic et al. (IPGP, sakic@ipgp.fr) GitHub repository : https://github.com/IPGP/geodezyx

geodezyx.stats.least_squares.bins_middle(bin_edges)

Calculate the middle points of histogram bins.

Parameters:

bin_edges (array-like) – Bin edge values from numpy.histogram.

Returns:

List of bin center values (midpoints between consecutive edges).

Return type:

list

geodezyx.stats.least_squares.chi2_test_frontend(dist_inp, nbins=10, ddof=2, debug=0, mode2=False, aaa=1)

Perform chi-square goodness-of-fit test on a distribution.

Parameters:
  • dist_inp (array-like) – Input distribution data.

  • nbins (int, optional) – Number of bins for histogram. Default is 10.

  • ddof (int, optional) – Degrees of freedom correction. Default is 2.

  • debug (int, optional) – If non-zero, plot debug visualization. Default is 0.

  • mode2 (bool, optional) – Normalization mode. If False (default), normalize theoretical distribution. If True, normalize observed distribution (less common, may be incoherent). Default is False.

  • aaa (float, optional) – Scaling factor for standard deviation. Default is 1.

Returns:

(chi2_statistic, p_value) from scipy.stats.chisquare, or (nan, nan) if error.

Return type:

tuple

Warning

The method for generating theoretical values is somewhat heuristic. See MATLAB’s chi2gof.m line 185 for reference.

Notes

In debug mode, returns: bin_edges, bin_edges2, hist, gauss, chi2 Otherwise returns chi2 statistic and p-value only.

geodezyx.stats.least_squares.chi2_test_lsq(V, A, P=None, fuvin=None, risk=0.05, cleaning_std=False, cleaning_normalized=False, koefP=1)

Perform chi-square test on least squares residuals.

Parameters:
  • V (array-like) – Residuals vector.

  • A (ndarray) – Jacobian matrix.

  • P (array-like, optional) – Weight matrix (diagonal only). Default is None.

  • fuvin (float, optional) – Unitary variance factor. If None, will be calculated. Default is None.

  • risk (float, optional) – Significance level for chi-square test. Default is 0.05.

  • cleaning_std (bool, optional) – If True, clean data by removing standard deviation outliers. Default is False.

  • cleaning_normalized (bool, optional) – If True, clean data using normalized residuals (preferred over cleaning_std). Default is False.

  • koefP (float, optional) – Coefficient applied to P for finding viable solution. Default is 1.

Returns:

Test statistics if successful, None if both fuvin and P are None.

Return type:

tuple or None

Notes

P should be the diagonal of the weight matrix, not the full matrix.

Cleaning options are tricks to approach FUV=1 by removing worst values. cleaning_normalized is preferred and overrides cleaning_std.

If koefP != 1, the adjusted P is returned as second argument.

geodezyx.stats.least_squares.clean_nan(A, L)

Deprecated since version This: function is discontinued. Use nan_cleaner() instead.

Remove NaN values from a 2D array and corresponding 1D array.

Parameters:
  • A (ndarray) – 2D array to clean.

  • L (ndarray) – 1D array to clean.

Returns:

  • A_clean (ndarray) – 2D array with NaN values removed.

  • L_clean (ndarray) – 1D array with corresponding NaN values removed.

Notes

Mutually removes NaN values from both A and L at the same indices.

geodezyx.stats.least_squares.constraint_improve_N(N, C, trans=False, outsparsetype='csc')

give N normal matrix and C constraints matrix returns N compined with C trans is a (dirty) way to transpose C if made in wrong shape

convention Ghilani 2011 p424 :

N C.T C 0

geodezyx.stats.least_squares.ellipse_angle_of_rotation(a, outdeg=True)

Calculate the rotation angle of an ellipse from its equation parameters.

Parameters:
  • a (array-like) – Ellipse equation coefficients [a, b, c, d, f, g].

  • outdeg (bool, optional) – If True, return angle in degrees. If False, return in radians. Default is True.

Returns:

Rotation angle of the ellipse.

Return type:

float

References

http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html

geodezyx.stats.least_squares.ellipse_axis_length(a)

Calculate the semi-major and semi-minor axis lengths of an ellipse.

Parameters:

a (array-like) – Ellipse equation coefficients [a, b, c, d, f, g].

Returns:

Array of [semi_major_axis, semi_minor_axis].

Return type:

ndarray

References

http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html

geodezyx.stats.least_squares.ellipse_center(a)

Calculate the center coordinates of an ellipse from its equation parameters.

Parameters:

a (array-like) – Ellipse equation coefficients [a, b, c, d, f, g] from the general ellipse equation: a*x^2 + 2*b*xy + c*y^2 + 2*d*x + 2*f*y + g = 0

Returns:

Center coordinates [x0, y0].

Return type:

ndarray

References

http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html

geodezyx.stats.least_squares.ellipse_fit(x, y)

Fit an ellipse to a set of 2D points.

Parameters:
  • x (array-like) – X coordinates of the points to fit.

  • y (array-like) – Y coordinates of the points to fit.

Returns:

(a, b, phi, x0, y0) where:

  • afloat

    Semi-major axis length

  • bfloat

    Semi-minor axis length

  • phifloat

    Rotation angle in degrees

  • x0float

    X coordinate of the center

  • y0float

    Y coordinate of the center

Return type:

tuple

References

http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html

geodezyx.stats.least_squares.ellipse_get_coords(a=0.0, b=0.0, x=0.0, y=0.0, angle=0.0, k=2, out_separate_X_Y=True, trigo=True)

Draws an ellipse using (360*k + 1) discrete points.

Parameters:
  • a (float) – major axis distance

  • b (float) – minor axis distance

  • x (float) – offset along the x-axis

  • y (float) – offset along the y-axis

  • angle (float) –

    trigo/clockwise rotation [in degrees] of the ellipse; - angle=0 : the ellipse is aligned with the positive x-axis - angle=30 : rotated 30 degrees trigo/clockwise from positive x-axis

    trigo sense is the standard convention

  • k (int) – k = 1 means 361 points (degree by degree)

  • out_separate_X_Y (bool) – if True, returns separate X and Y arrays

  • trigo (bool) – if True, use trigonometric convention; if False, use clockwise convention

Notes

This function is based on pseudo code given at http://en.wikipedia.org/wiki/Ellipse

The internal convention is clockwise, but we prefer trigo convention for the Ghiliani ellipses made by error_ellipse_parameters

References

scipy-central.org/item/23/1/plot-an-ellipse

geodezyx.stats.least_squares.error_ellipse(xm, ym, sigx, sigy, sigxy, nsig=1, ne=100, scale=1)

from matlab fct http://kom.aau.dk/~borre/matlab/geodesy/errell.m It works but don’t ask why …

(X,Y) orientation convention is inverted => (Y,X) … so in a practical way you must invert X ,Y (it is not important for the axis but it is for the orientation) AND sigx,sigy,sigxy must be first normalized with the fuv

sigx, sigy, sigxy :

so as we can generate a covariance matrix cov = np.array([[sigx ** 2,sigxy],[sigxy,sigy ** 2]])

ne :

nb of segements for the ellipse

RETURNS :

xe,ye,dx2,dy2

DEBUG:

si on a xe1,ye1,_,_ = stats.error_ellipse(pxp[0],pxp[1], sigxB , sigyB , sigxyB, scale= 10000) xe2,ye2,_,_ = stats.error_ellipse(pxp[0],pxp[1], sigyB , sigxB , sigxyB, scale= 10000) et PAS les - à D et dxy0 => on a 2 ellipses differentes

si on a xe1,ye1,_,_ = stats.error_ellipse(pxp[0],pxp[1], sigxB , sigyB , sigxyB, scale= 10000) xe2,ye2,_,_ = stats.error_ellipse(pxp[0],pxp[1], sigyB , sigxB , sigxyB, scale= 10000) et AVEC les - à D et dxy0 => on a 2 ellipses differentes au moins une ellipse coincide avec celle de Ghiliani

A investiguer, en attendant, à éviter

geodezyx.stats.least_squares.error_ellipse_parameters(qxx, qyy, qxy, fuv, out_t=False)

Calculate error ellipse parameters from variance-covariance matrix elements.

Parameters:
  • qxx (float) – Variance in x direction (from variance-covariance matrix, unnormalized).

  • qyy (float) – Variance in y direction (from variance-covariance matrix, unnormalized).

  • qxy (float) – Covariance between x and y (from variance-covariance matrix, unnormalized).

  • fuv (float) – Unitary variance factor for normalization.

  • out_t (bool, optional) – If False (default), return angle in trigonometric convention (counterclockwise from x-axis). If True, return angle in clockwise direction from y-axis. Default is False.

Returns:

  • Su (float) – Semi-major axis (scaled by FUV).

  • Sb (float) – Semi-minor axis (scaled by FUV).

  • t or phi (float) –

    • If out_t=True: t (angle in clockwise direction from y-axis in degrees)

    • If out_t=False: phi (angle in trigonometric direction from x-axis in degrees)

Notes

At least one ellipse should coincide with that of Ghilani for verification.

This function calculates the principal axes and orientation of the 2D confidence ellipse from the variance-covariance matrix.

References

Strang & Borre methods for comparison.

geodezyx.stats.least_squares.error_ellipse_parameters_2(sigx, sigy, sigxy, out_deg=True)

Calculate error ellipse parameters using Strang & Borre convention.

Parameters:
  • sigx (float) – Standard deviation in x direction (must be normalized with FUV).

  • sigy (float) – Standard deviation in y direction (must be normalized with FUV).

  • sigxy (float) – Covariance between x and y (must be normalized with FUV).

  • out_deg (bool, optional) – If True, return angles in degrees. If False, return in radians. Default is True.

Returns:

(semi_major_axis, semi_minor_axis, angle)

Return type:

tuple

Warning

The (X,Y) orientation convention is inverted from standard use, so in practice you must invert X and Y inputs. This is not important for the axes magnitudes but IS important for the orientation angle.

Notes

sigx, sigy, and sigxy must be pre-normalized with the FUV.

References

Strang & Borre p. 337

geodezyx.stats.least_squares.fitEllipse_core(x, y)

Core function to fit an ellipse to 2D points using least squares.

Parameters:
  • x (array-like) – X coordinates of the points.

  • y (array-like) – Y coordinates of the points.

Returns:

Ellipse equation coefficients [a, b, c, d, f, g].

Return type:

ndarray

References

http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html

geodezyx.stats.least_squares.fuv_calc(V, A, P=1, normafuv=1)

Calculate the unitary variance factor (Facteur Unitaire de Variance).

Parameters:
  • V (array-like) – Residuals vector.

  • A (ndarray) – Jacobian matrix.

  • P (int, float, or ndarray, optional) – Weight matrix or weight value. Can be a scalar, array, or sparse matrix. Default is 1.

  • normafuv (int or float, optional) – Normalization factor for the FUV. Default is 1.

Returns:

The unitary variance factor (FUV).

Return type:

float

Notes

The FUV depends on the weight matrix P:

  • With weight of 10**-6: FUV = 439828.260843

  • With weight of 1: FUV = 4.39828260843e-07

But sigmas remain constant regardless of P weights.

Both standard arrays and sparse arrays are supported for P.

geodezyx.stats.least_squares.fuv_calc_OLD(V, A)

Deprecated since version Use: fuv_calc() instead.

Legacy implementation of unitary variance factor calculation.

Parameters:
  • V (array-like) – Residuals vector.

  • A (ndarray) – Jacobian matrix.

Returns:

The unitary variance factor.

Return type:

float

geodezyx.stats.least_squares.fuv_calc_OLD2(V, A, P=None)

Deprecated since version Use: fuv_calc() instead.

Legacy implementation of unitary variance factor with weight matrix.

Parameters:
  • V (array-like) – Residuals vector.

  • A (ndarray) – Jacobian matrix.

  • P (ndarray, optional) – Weight matrix. Default is None (identity matrix).

Returns:

The unitary variance factor.

Return type:

float

geodezyx.stats.least_squares.get_accur_coeff(i)

Get accuracy coefficients for finite difference calculations.

Parameters:

i (int) – Accuracy order index. Values > 3 return the highest accuracy coefficients.

Returns:

Array of finite difference coefficients.

Return type:

ndarray

References

https://en.wikipedia.org/wiki/Finite_difference_coefficient

geodezyx.stats.least_squares.jacobian(f, var_in_list, var_out, kwargs_f_list=[], h=1e-06, nproc=4)

Compute Jacobian matrix in parallel using multiple processes.

Parameters:
  • f (callable) – The function for which to compute the Jacobian.

  • var_in_list (iterable) – List of variables with respect to which derivation is performed.

  • var_out (int) – Output index to consider.

  • kwargs_f_list (list of dict, optional) – List of keyword argument dictionaries. Default is [].

  • h (float, optional) – Derivation step. Default is 10**-6.

  • nproc (int, optional) – Number of processes for parallel computation. Default is 4.

Returns:

Jacobian matrix with shape (n_observations, n_variables).

Return type:

ndarray

Notes

Only keyword arguments (kwargs) are managed. Positional arguments are not currently supported.

geodezyx.stats.least_squares.jacobian_line(f, var_in_list, var_out=0, kwargs_f={}, args_f=[], h=0, aray=True)

Compute a line of the Jacobian matrix (derivatives with respect to multiple variables).

Parameters:
  • f (callable) – The Python function to differentiate.

  • var_in_list (iterable) – List/tuple of variables with respect to which derivation is performed.

  • var_out (int, optional) – The output index of f to consider. Default is 0.

  • kwargs_f (dict, optional) – Dictionary of keyword arguments for f. Default is {}.

  • args_f (iterable, optional) – List/tuple of positional arguments for f. Default is [].

  • h (float, optional) – Derivation step. Default is 0 (auto-calculated).

  • aray (bool, optional) – If True, return result as numpy array. If False, return as list. Default is True.

Returns:

Array or list of partial derivatives with respect to each variable in var_in_list.

Return type:

ndarray or list

See also

partial_derive

Compute single partial derivative

geodezyx.stats.least_squares.kwargs_for_jacobian(kwdic_generik, kwdic_variables)

Build a list of kwargs dictionaries for Jacobian computations.

Parameters:
  • kwdic_generik (dict) – Dictionary of parameters that will not change across computations.

  • kwdic_variables (dict) – Dictionary of parameters that will change, with iterables as values. Each key should map to an iterable of values to be tested.

Returns:

List of keyword argument dictionaries with all combinations of variables from kwdic_variables merged with kwdic_generik.

Return type:

list of dict

Notes

Creates a Cartesian product of all iterables in kwdic_variables.

geodezyx.stats.least_squares.nan_cleaner(Ain, Bin)

Remove NaN values from two arrays/lists simultaneously.

Parameters:
  • Ain (array-like) – First input array or list.

  • Bin (array-like) – Second input array or list.

Returns:

  • Aout (ndarray) – First array with NaN values removed.

  • Bout (ndarray) – Second array with NaN values removed at the same indices as Ain.

Notes

Removes all rows where either Ain or Bin contains a NaN value.

geodezyx.stats.least_squares.partial_derive(f, var_in, var_out=0, kwargs_f={}, args_f=[], h=0, accur=-1)

Compute partial derivatives of a Python function numerically.

Parameters:
  • f (callable) – The Python function to differentiate. Must return a scalar or iterable. Parameters susceptible to be differentiated must be scalars. For instance, to differentiate a position vector X = [x,y,z], f must take arguments f(x,y,z) not f(X).

  • var_in (int or str) – The variable with respect to which the derivation is performed. Can be an int (starting with 0) or a string describing the name of the variable in f’s arguments.

  • var_out (int, optional) – The output index of f to consider. Default is 0.

  • kwargs_f (dict, optional) – Dictionary describing keyword arguments of f. Default is {}.

  • args_f (iterable, optional) – Tuple/list describing positional arguments of f. Default is [].

  • h (float, optional) – Derivation step. If h == 0, uses x * sqrt(epsilon). Default is 0. See http://en.wikipedia.org/wiki/Numerical_differentiation

  • accur (int, optional) – Accuracy coefficient index. -1 provides best accuracy (slowest). Default is -1. See https://en.wikipedia.org/wiki/Finite_difference_coefficient

Returns:

The derivative of f with respect to var_in.

Return type:

float

Notes

The function automatically adjusts h if it equals 0 using: h = x * sqrt(machine_epsilon)

References

http://en.wikipedia.org/wiki/Numerical_differentiation https://en.wikipedia.org/wiki/Finite_difference_coefficient

geodezyx.stats.least_squares.partial_derive_old(f, var_in, var_out=0, kwargs_f={}, args_f=[], h=0)

Deprecated since version Use: partial_derive() instead.

Legacy implementation for computing partial derivatives of a Python function.

Parameters:
  • f (callable) – The Python function to differentiate.

  • var_in (int or str) – Variable with respect to which derivation is performed. Can be an int (starting with 0) or a string name.

  • var_out (int, optional) – The output index of f to consider. Default is 0.

  • kwargs_f (dict, optional) – Dictionary of keyword arguments for f. Default is {}.

  • args_f (iterable, optional) – Tuple/list of positional arguments for f. Default is [].

  • h (float, optional) – Derivation step. If h == 0, uses x * sqrt(epsilon). Default is 0.

Returns:

The derivative of f with respect to var_in.

Return type:

float

References

http://en.wikipedia.org/wiki/Numerical_differentiation

geodezyx.stats.least_squares.sigmas_formal_calc(N, V, A, fuv=None, P=None)

Calculate formal standard deviations (sigmas) from least squares solution.

Parameters:
  • N (ndarray) – Normal equation matrix (A^T * P * A).

  • V (array-like) – Residuals vector.

  • A (ndarray) – Jacobian matrix.

  • fuv (float, optional) – Unitary variance factor. If None, it will be calculated. Default is None.

  • P (ndarray, optional) – Weight matrix or array. Default is None.

Returns:

Array of formal standard deviations (sigmas) for each parameter.

Return type:

ndarray

See also

fuv_calc

Calculate the unitary variance factor

geodezyx.stats.least_squares.smart_i_giver(subgrp_len_list, i_in_sublis, sublis_id, advanced=False, sublis_id_list=[])

Convert a local index within a subgroup to a global index.

Parameters:
  • subgrp_len_list (list) – List of lengths for each subgroup.

  • i_in_sublis (int) – Local index within the subgroup.

  • sublis_id (int or hashable) – The identifier of the subgroup to access.

  • advanced (bool, optional) – If True, sublis_id is a generic identifier (str, int, set, etc.) present in sublis_id_list. If False, sublis_id is an integer index. Default is False.

  • sublis_id_list (list, optional) – List of subgroup identifiers (used when advanced=True). Default is [].

Returns:

Global index.

Return type:

int

Examples

>>> subgrp_len_list = [4201, 4186, 4157, 4041, 4058, 4204, 4204, 4204, 4204]
>>> i_in_sublis = 2
>>> sublis_id = 3
>>> smart_i_giver(subgrp_len_list, i_in_sublis, sublis_id)
12544  # sum of [4201 + 4186 + 4157 + 2]
must be an int
geodezyx.stats.least_squares.triangle_arr2vect(triarrin, k=1)

Convert upper triangular matrix to 1D vector.

Parameters:
  • triarrin (ndarray) – Input 2D triangular array.

  • k (int, optional) – Diagonal offset. k=0 includes the main diagonal, k=1 excludes it. Default is 1.

Returns:

1D vector of upper triangular elements.

Return type:

ndarray

See also

numpy.triu_indices_from

Get indices of upper triangle

geodezyx.stats.least_squares.weight_mat(Sinp, Ninp=[], fuvinp=1, sparsediag=False)
Args :

Sinp : liste des Sigmas sig = sqrt(var) Ninp : liste de la taille de chaque blocs (obs) fuvinp = 1 : facteur unitaire de variance inspiré de mat_poids , fct écrite dans la lib resolution de GPShApy

Returns :

K : matrice de var-covar Q : matrice des cofacteurs p : matrice des poids inv(Q)

geodezyx.stats.least_squares.weight_mat_simple(Pinp, Ninp=[], sparsediag=False, return_digaonal_only=False)

Simple version of weight_mat : takes directly the weights (Pinp) and the size for each weigths blocks (Ninp)

Pinp and Ninp have to have the same length

Args :

Pinp : list of weigths Ninp : list of the size of each block (obs number) fuvinp = 1 : facteur unitaire de variance

Returns :

p : weigth matrix

geodezyx.stats.stats module

@author: psakic

This sub-module of geodezyx.stats contains functions for low-level statistics.

it can be imported directly with: from geodezyx import stats

The geodezyx toolbox is a software for simple but useful functions for Geodesy and Geophysics under the GNU LGPL v3 License

Copyright (C) 2019 Pierre Sakic et al. (IPGP, sakic@ipgp.fr) GitHub repository : https://github.com/IPGP/geodezyx

geodezyx.stats.stats.butter_lowpass(cutoff, fs, order=5)

Design a Butterworth lowpass digital filter.

Parameters:
  • cutoff (float) – Critical frequency (Hertz). Frequencies above this will be attenuated.

  • fs (float) – Sampling frequency (Hertz).

  • order (int, optional) – Order of the filter. Default is 5.

Returns:

  • b (numpy.ndarray) – Numerator (zeros) of the IIR filter.

  • a (numpy.ndarray) – Denominator (poles) of the IIR filter.

See also

scipy.signal.butter

Design IIR filters

butter_lowpass_filter

Apply the designed filter to data

geodezyx.stats.stats.butter_lowpass_filter(data, cutoff, fs, order=5)

Apply Butterworth lowpass digital filter to data.

Parameters:
  • data (array-like) – Input signal to be filtered.

  • cutoff (float) – Critical frequency (Hertz). Frequencies above this will be attenuated.

  • fs (float) – Sampling frequency (Hertz).

  • order (int, optional) – Order of the filter. Default is 5.

Returns:

y – Filtered signal.

Return type:

numpy.ndarray

See also

butter_lowpass

Design the lowpass filter

scipy.signal.butter

Design IIR filters

scipy.signal.lfilter

Apply IIR filters

geodezyx.stats.stats.color_of_season(datein)

Get color representation for a season.

Maps seasons to matplotlib-compatible color codes.

Parameters:

datein (datetime.date or datetime.datetime) – The date to get the season color for.

Returns:

color – Color code: ‘b’ (blue) for winter, ‘r’ (red) for summer, ‘g’ (green) for spring, ‘k’ (black) for autumn.

Return type:

str

See also

get_season

Determine season from date

geodezyx.stats.stats.confid_interval_slope(x, y, alpha=0.95)

Calculate a confidence interval on the slope of a linear trend.

Parameters:
  • x (array_like) – Independent variable.

  • y (array_like) – Dependent variable.

  • alpha (float, optional) – Confidence level (default is 0.95 for 95% confidence).

Returns:

  • mi (float) – Lower bound of the confidence interval for the slope.

  • ma (float) – Upper bound of the confidence interval for the slope.

  • Source

  • ——-

  • Based on methods from

  • http (//www.i4.auc.dk/borre/matlab)

  • http (//kom.aau.dk/~borre/matlab/)

geodezyx.stats.stats.dates_middle(start, end)

Compute the midpoint between two dates.

Parameters:
  • start (datetime or numeric) – Start date/time.

  • end (datetime or numeric) – End date/time.

Returns:

middle – The midpoint between start and end.

Return type:

datetime or numeric

geodezyx.stats.stats.detrend_timeseries(x, y)

Remove linear trend from a time series.

Removes the linear trend from Y(X) by subtracting the fitted line and restoring the original starting value.

Parameters:
  • x (list or numpy.ndarray) – Independent variable (time or similar).

  • y (list or numpy.ndarray) – Dependent variable (data values).

Returns:

  • x (numpy.ndarray) – Independent variable (unchanged).

  • yout (numpy.ndarray) – Detrended dependent variable.

geodezyx.stats.stats.find_intersection(x1, y1, x2, y2)

Find intersection points of two line plots.

Parameters:
  • x1 (array-like) – X-coordinates of the first line.

  • y1 (array-like) – Y-coordinates of the first line.

  • x2 (array-like) – X-coordinates of the second line.

  • y2 (array-like) – Y-coordinates of the second line.

Returns:

  • roots (numpy.ndarray) – X-coordinates of the intersection points.

  • y_intersect (numpy.ndarray) – Y-coordinates of the intersection points.

References

http://stackoverflow.com/questions/8094374/python-matplotlib-find-intersection-of-lineplots

geodezyx.stats.stats.gaussian_filter_gfz(tim_ref, dat_ref, width=7)

Apply Gaussian filter to smooth data.

Gaussian filter based on GFZ’s GMT_plus.pm/gaussian_kernel. Smooths data by weighted averaging using Gaussian weights.

Parameters:
  • tim_ref (array-like (list or numpy.ndarray)) – X/T component of the time series (in decimal days).

  • dat_ref (array-like (list or numpy.ndarray)) – Y component (the data values).

  • width (int, optional) – Size of the smoothing window. An odd number is recommended. Default is 7.

Returns:

dat_smt2 – Smoothed Y values with Gaussian weighting.

Return type:

numpy.ndarray

Notes

For additional smoothing ideas and references, see: - https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html - https://stackoverflow.com/questions/20618804/how-to-smooth-a-curve-in-the-right-way - https://stackoverflow.com/questions/32900854/how-to-smooth-a-line-using-gaussian-kde-kernel-in-python-setting-a-bandwidth

geodezyx.stats.stats.gaussian_filter_gfz_legacy(tim_ref, dat_ref, width=7)

Apply Gaussian filter to smooth data (legacy, slow version).

Gaussian filter based on GFZ’s GMT_plus.pm/gaussian_kernel. This is a legacy version that is VERY SLOW due to a dirty conversion from Perl code. The pythonic version gaussian_filter_gfz should be used instead.

Parameters:
  • tim_ref (array-like) – X/T component of the time series (in decimal days).

  • dat_ref (array-like) – Y component (the data values).

  • width (int, optional) – Size of the window. Odd numbers are recommended. Default is 7.

Returns:

dat_smt – Smoothed Y values.

Return type:

list

Warning

This function is VERY SLOW. Use gaussian_filter_gfz instead.

Notes

For additional smoothing ideas and references, see: - http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html - https://stackoverflow.com/questions/20618804/how-to-smooth-a-curve-in-the-right-way - https://stackoverflow.com/questions/32900854/how-to-smooth-a-line-using-gaussian-kde-kernel-in-python-setting-a-bandwidth

See also

gaussian_filter_gfz

Pythonic and faster version

geodezyx.stats.stats.get_season(now)

Determine the season for a given date.

Parameters:

now (datetime.date or datetime.datetime) – The date to determine the season for. If datetime is provided, the date component is used.

Returns:

season – The season name: ‘winter’, ‘spring’, ‘summer’, or ‘autumn’. Returns None if the date is outside the defined ranges.

Return type:

str

Notes

Season boundaries are: - Winter: Dec 21 - Mar 20 - Spring: Mar 21 - Jun 20 - Summer: Jun 21 - Sep 22 - Autumn: Sep 23 - Dec 20

geodezyx.stats.stats.harmonic_mean(a)

Compute harmonic mean of a list or array.

Parameters:

a (array-like) – Input values.

Returns:

result – The harmonic mean of the input values.

Return type:

float

geodezyx.stats.stats.lagrange1(points)

Determine Lagrangian polynomial from points (low-level function).

Creates a polynomial interpolation function using Lagrange’s method. This replaces scipy.interpolate.lagrange which is highly unstable.

Parameters:

points (list of tuple) – List of (x, y) coordinate tuples defining the polynomial.

Returns:

p – Function representing the Lagrangian polynomial.

Return type:

callable

Notes

More numerically stable than scipy.interpolate.lagrange.

References

https://gist.github.com/melpomene/2482930

geodezyx.stats.stats.lagrange2(x, y)

Determine Lagrangian polynomial from points (more Pythonic version).

Creates a polynomial interpolation function using Lagrange’s method. This version is more Pythonic but slower than lagrange1. Like lagrange1, it replaces scipy.interpolate.lagrange which is highly unstable.

Parameters:
  • x (array-like) – X-coordinates of the interpolation points.

  • y (array-like) – Y-coordinates of the interpolation points.

Returns:

p – Function representing the Lagrangian polynomial.

Return type:

callable

Notes

More numerically stable than scipy.interpolate.lagrange. More Pythonic but slower than lagrange1.

References

https://gist.github.com/melpomene/2482930

geodezyx.stats.stats.lagrange_interpolate(tdata, ydata, titrp, n=10, t_type='datetime')

Perform temporal Lagrangian polynomial interpolation.

Interpolates Y values at specified time epochs using Lagrangian polynomial fitting. The X-component represents time.

Parameters:
  • tdata (array-like of datetime) – X/T component (time) of the known interpolation points.

  • ydata (array-like of float) – Y component (data values) of the known interpolation points.

  • titrp (array-like of datetime) – Epochs at which to compute interpolated values.

  • n (int, optional) – Degree of the Lagrangian polynomial. Better if even. Default is 10.

  • t_type (str, optional) – type of the time component, can be “datetime”, “posix” or “pandas_timestamp”. The default is “datetime”. pandas_timestamp is recommended for a more precise applications (nanosecond precision instead of microsecond for datetime)

Returns:

y_intrp – Interpolated Y values at the requested epochs.

Return type:

numpy.ndarray

See also

lagrange1

Low-level Lagrangian polynomial function

conv.dt_range

Generate a range of datetime epochs

Notes

Use conv.dt_range to generate the wished epochs range.

geodezyx.stats.stats.linear_coef_a_b(x1, y1, x2, y2)

Calculate line coefficients from two points.

Calculates the slope (a) and intercept (b) coefficients of a line passing through two points (x1, y1) and (x2, y2). Input values can be scalars or iterables.

Parameters:
  • x1 (float or list or numpy.ndarray) – X-coordinate(s) of the first point.

  • y1 (float or list or numpy.ndarray) – Y-coordinate(s) of the first point.

  • x2 (float or list or numpy.ndarray) – X-coordinate(s) of the second point.

  • y2 (float or list or numpy.ndarray) – Y-coordinate(s) of the second point.

Returns:

  • a (float or numpy.ndarray) – Slope coefficient of the line.

  • b1 (float or numpy.ndarray) – Y-intercept using first point (should equal b2).

  • b2 (float or numpy.ndarray) – Y-intercept using second point (should equal b1).

geodezyx.stats.stats.linear_reg_getvalue(x, a, b, full=True)

Compute Y = a*X + b from a vector X and coefficients a and b.

Parameters:
  • x (list or numpy.ndarray) – Input values.

  • a (float) – Linear regression slope coefficient.

  • b (float) – Linear regression intercept coefficient.

  • full (bool, optional) – If True, return both X and Y = aX + b. If False, return only Y = aX + b. Default is True.

Returns:

  • y (numpy.ndarray) – Computed values Y = aX + b. Only returned if full is False.

  • x (numpy.ndarray) – Input values (unchanged). Only returned if full is True.

  • y (numpy.ndarray) – Computed values Y = aX + b. Only returned if full is True.

Notes

This function may be unstable when working with POSIX Time as X-data due to large values. Decimal Years are recommended for better numerical stability.

geodezyx.stats.stats.linear_regression(x, y, fulloutput=False, simple_lsq=False, alpha=0.95)

Performs linear regression on two vectors, X and Y, and returns the coefficients a (slope) and b (intercept).

Parameters:
  • x (list or numpy.array) – The X values.

  • y (list or numpy.array) – The Y values.

  • simple_lsq (bool, optional) – If True, performs a basic, low-level least square inversion (faster, but less outputs). If False, calls scipy’s linregress. Default is False.

  • fulloutput (bool, optional) – If True, returns additional outputs (confidence interval for the slope and standard deviation). Default is False.

  • alpha (float, optional) – The alpha value for the confidence interval. Default is .95.

Returns:

  • slope (float) – The slope (a) of the linear regression.

  • intercept (float) – The intercept (b) of the linear regression.

  • confid_interval_slope (tuple of float, optional) – The confidence interval for the slope. Only returned if fulloutput is True.

  • std_err (float, optional) – The standard deviation. Only returned if fulloutput is True.

Notes

This function performs a similar job to scipy.stats.linregress.

Regarding computation speed: low-level least square inversion is faster for small datasets. For larger datasets, scipy’s linregress is faster (n points > ~13000).

geodezyx.stats.stats.mad(data, mode='median')

Compute Median Absolute Deviation (MAD).

Parameters:
  • data (array-like) – Input data values.

  • mode (str, optional) – Mode for computing deviation center: ‘median’ or ‘mean’. Default is ‘median’.

Returns:

result – The Median Absolute Deviation.

Return type:

float

geodezyx.stats.stats.outlier_above_below(x, threshold_values, reference=<function nanmean>, theshold_absolute=True, return_booleans=True, theshold_relative_value='reference', verbose=False)

Gives values of X which are between threshold values

Parameters:
  • threshold_values (single value (float) or a 2-tuple) –

    (lower bound theshold , upper bound theshold)

    WARN : those value(s) have to be positives. Minus sign for lower bound and plus sign for upper one will be applied internally

  • reference (float or callable) – the central reference value can be a absolute fixed value (float) or a function (e.g. np.mean of np.median)

  • theshold_absolute (bool) –

    if True threshold_values are absolutes values

    >>> low = reference - threshold_values[0]
    >>> upp = reference + threshold_values[1]
    

    if False they are fractions of theshold_relative_value

    >>> low = reference - threshold_values[0] * theshold_relative_value
    >>> upp = reference + threshold_values[1] * theshold_relative_value
    

    (see also below)

  • theshold_relative_value (str or function) – if the string “reference” or None is given, then it the reference value which is used if it is a fuction (e.g. np.std()) then it is this value returned by this function which is used Only useful when theshold_absolute = False

  • return_booleans (bool) – return booleans or not

  • verbose (bool)

Returns:

  • xout (numpy array) – X between low_bound & upp_bound

  • bbool (numpy array) – X-sized array of booleans

geodezyx.stats.stats.outlier_above_below_binom(y, x, threshold_values, reference=<function nanmean>, theshold_absolute=True, theshold_relative_value='reference', return_booleans=False, detrend_first=True, verbose=False)

Gives values of Y which are between threshold values, and correct an associated X so as X => Y(X)

Parameters:
  • threshold_values (single value (float) or a 2-tuple) –

    (lower bound theshold , upper bound theshold)

    WARN : those value(s) have to be positives. Minus sign for lower bound and plus sign for upper one will be applied internally

  • reference (float or callable) – the central reference value can be a absolute fixed value (float) or a function (e.g. np.mean of np.median)

  • theshold_absolute (bool) –

    if True threshold_values are absolutes values

    >>> low = reference - threshold_values[0]
    >>> upp = reference + threshold_values[1]
    

    if False they are fractions of theshold_relative_value

    >>> low = reference - threshold_values[0] * theshold_relative_value
    >>> upp = reference + threshold_values[1] * theshold_relative_value
    

    (see also below)

  • theshold_relative_value (str or function) – if the string “reference” or None is given, then it the reference value which is used if it is a fuction (e.g. np.std()) then it is this value returned by this function which is used Only useful when theshold_absolute = False

  • detrend_first (bool) – detrend linear behavior of Y(X) first Recommended

  • return_booleans (bool) – return booleans or not

  • verbose (bool)

Returns:

  • x_out (numpy array) – X between low_bound & upp_bound

  • bbool (numpy array) – X-sized array of booleans

geodezyx.stats.stats.outlier_above_below_simple(x, low_bound, upp_bound, return_booleans=True)

Gives values of X which are between low_bound & upp_bound

Parameters:
  • x (list or numpy.array) – Values

  • upp_bound (low_bound &) – lower and upper bound of X values wished

  • return_booleans (bool) – return booleans or not

Returns:

  • xout (numpy.array) – X between low_bound & upp_bound

  • bbool (bool) – X-sized array of booleans

geodezyx.stats.stats.outlier_mad(data, threshold=3.5, verbose=False, convert_to_np_array=True, mad_mode='median', seuil=None)

clean the outlier of Ya dataset using the MAD approach

Parameters:
  • data (list or numpy.array) – Values

  • threshold (float) – MAD threshold

  • verbose (bool)

  • convert_to_np_array (bool) – if True returns output as an array, if False as a regular list

  • mad_mode (str) – ‘median’ or ‘mean’ : MAD can also be based on mean (for experimental purposes)

  • seuil (float, optional) – legacy name of ‘threshold’ argument. will override threshold value if given

Returns:

  • dataout (numpy.array) – Values cleaned of outliers

  • boolbad (numpy.array) – Y-sized booleans

  • Source

  • ——

  • Utilisation de la MAD pour detecter les outliers

  • https (//www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm)

  • https (//web.ipac.caltech.edu/staff/fmasci/home/statistics_refs/BetterThanMAD.pdf)

geodezyx.stats.stats.outlier_mad_binom(y, x, threshold=3.5, verbose=False, detrend_first=False, return_booleans=False)

clean the outlier of Y using the MAD approach and clean the corresponding values in X assuming that we have the function : X => Y(X) (be carefull, Y is the first argument)

Parameters:
  • y (list or numpy.array) – Values

  • x (list or numpy.array) – X Values so as X => Y(X)

  • threshold (float) – MAD threshold

  • verbose (bool)

  • detrend_first (bool) – detrend linear behavior of Y(X) first

  • return_booleans (bool) – return good and bad values of Y and X as booleans

Returns:

  • yclean & xclean (numpy.array)

  • bb (numpy.array (if return_booleans == True)) – Y-sized booleans

geodezyx.stats.stats.outlier_mad_binom_legacy(x, y, threshold=3.5, verbose=False, detrend_first=False, return_booleans=False)

Remove outliers from paired X,Y data using MAD (legacy version).

Legacy version with different argument order than the main version. May be unstable when detrending.

Parameters:
  • x (array-like) – X values.

  • y (array-like) – Y values (dependent on X).

  • threshold (float, optional) – MAD threshold. Default is 3.5.

  • verbose (bool, optional) – If True, print elimination information. Default is False.

  • detrend_first (bool, optional) – If True, detrend before outlier detection. Default is False.

  • return_booleans (bool, optional) – If True, also return boolean selection array. Default is False.

Returns:

  • x_clean (numpy.ndarray) – Cleaned X values.

  • y_clean (numpy.ndarray) – Cleaned Y values.

  • bb (numpy.ndarray, optional) – Boolean array indicating valid points. Only returned if return_booleans=True.

Notes

This is a legacy function. Use outlier_mad_binom for the standard version.

See also

outlier_mad_binom

Main version with correct argument order

geodezyx.stats.stats.outlier_mad_df(df, columns, threshold=3.5, columns_aggrgation=<ufunc 'logical_and'>, mad_mode='median')

Remove outliers from pandas DataFrame columns using MAD (Median Absolute Deviation).

This function applies MAD-based outlier detection to one or more columns in a pandas DataFrame and returns a filtered DataFrame. Multiple columns can be evaluated simultaneously with results aggregated using a specified logical operator.

Parameters:
  • df (pandas.DataFrame) – Input DataFrame to filter.

  • columns (str or list of str) – Column name(s) to evaluate for outliers. If a single string is provided, it will be converted to a list.

  • threshold (float, optional) – MAD threshold for outlier detection. Default is 3.5. Points where MAD > threshold are considered outliers.

  • columns_aggrgation (callable, optional) – Function to aggregate boolean masks from multiple columns. Should accept variable number of boolean arrays as arguments. Common choices: np.logical_and (any column flags as outlier), np.logical_or (all columns flag as outlier). See Notes for more details. Default is np.logical_and.

  • mad_mode (str, optional) – Mode for computing deviation center: ‘median’ or ‘mean’. Default is ‘median’.

Returns:

  • df_out (pandas.DataFrame) – Filtered DataFrame with outliers removed. Has same structure as input but with fewer rows.

  • bb_out (np.array) – Boolean array indicating valid (True) and outlier (False) rows. Size matches the number of rows in the input DataFrame.

See also

outlier_mad

Single column outlier detection using MAD

outlier_mad_binom

Paired X,Y data outlier removal with MAD

Notes

  • When multiple columns are specified, the aggregation function determines how results are combined. With np.logical_and (default), a row is kept only if it passes in ALL columns. With np.logical_or, a row is kept if it passes in ANY column.

  • Since the bad values are flagged False, and good values are True, the operator logic is inverted, which might be counterintuitive.

geodezyx.stats.stats.outlier_sigma(datasigmain, threshold=3)

Remove outliers based on sigma threshold (legacy method).

Removes points where sigma > threshold * median(sigmas). This is an old and discontinued method that is not very efficient.

Parameters:
  • datasigmain (array-like) – Input sigma (uncertainty) values.

  • threshold (int, optional) – Multiplier for the sigma threshold. Default is 3.

Returns:

  • datasigmaout (numpy.ndarray) – Sigma values filtered to exclude outliers.

  • boolbad (numpy.ndarray) – Boolean array indicating valid values (True = keep, False = outlier).

Notes

This is a legacy function and is rarely used. More modern methods like MAD-based outlier detection are recommended.

geodezyx.stats.stats.rms_mean(a)

Compute RMS (Root Mean Square) of a list or array.

Parameters:

a (array-like) – Input values.

Returns:

result – The RMS value of the input.

Return type:

float

geodezyx.stats.stats.rms_mean_alternativ(a)

Compute RMS with mean subtraction (standard deviation equivalent).

Computes: √< (A - Ā)² > instead of √< (A)² >, where Ā is the arithmetic mean. This is essentially the standard deviation.

Parameters:

a (array-like) – Input values.

Returns:

result – The RMS value with mean subtraction.

Return type:

float

Notes

This is equivalent to the standard deviation of the input.

geodezyx.stats.stats.rms_mean_kouba(a, multipl_coef=3, deg_of_freedom=7)

Compute weighted RMS (Root Mean Square) with Kouba’s method.

Parameters:
  • a (array-like) – Input values.

  • multipl_coef (int, optional) – Multiplication coefficient. Default is 3.

  • deg_of_freedom (int, optional) – Degrees of freedom. Default is 7.

Returns:

result – The weighted RMS value.

Return type:

float

geodezyx.stats.stats.running_mean(data_in, window)

Compute running mean (moving average) of data.

Parameters:
  • data_in (list or numpy.ndarray) – Input data values.

  • window (float or int) – Size of the window for the running mean.

Returns:

data_run – Running mean of the input data.

Return type:

numpy.ndarray

geodezyx.stats.stats.running_mean_1(values, window)

Compute running mean using convolution with ‘valid’ mode.

This method includes the ‘valid’ mode which requires enough datapoints. For example, without ‘valid’, it would start at the first point with no prior points, resulting in (1+0+0)/3 = 0.3333.

Parameters:
  • values (array-like) – Input data values.

  • window (int) – Window size for the running mean.

Returns:

smas – Running mean values using ‘valid’ convolution mode.

Return type:

numpy.ndarray

Notes

Internal ID: 1 See: https://sentdex.com/sentiment-analysisbig-data-and-python-tutorials-algorithmic-trading/

geodezyx.stats.stats.running_mean_2(x, n)

Compute running mean by explicit windowing.

Parameters:
  • x (array-like) – Input data values.

  • n (int) – Window size for the running mean.

Returns:

y – Running mean values.

Return type:

numpy.ndarray

Notes

Internal ID: 2 See: https://stackoverflow.com/questions/13728392/moving-average-or-running-mean

geodezyx.stats.stats.running_mean_3(x, n)

Compute running mean using cumulative sum (moyenne glissante).

Parameters:
  • x (array-like) – Input data values.

  • n (int) – Window size for the running mean.

Returns:

xout – Running mean values.

Return type:

numpy.ndarray

Notes

Internal ID: 3 See: https://stackoverflow.com/questions/13728392/moving-average-or-running-mean (Alleo’s answer)

geodezyx.stats.stats.running_mean_4(interval, window_size, convolve_mode='same')

Compute running mean using convolution with configurable mode.

This method is slower than some alternatives but provides output with the same size as input without shifting.

Parameters:
  • interval (array-like) – Input data values.

  • window_size (int) – Size of the convolution window.

  • convolve_mode (str, optional) – Convolution mode (‘same’, ‘valid’, ‘full’). Default is ‘same’.

Returns:

result – Running mean values.

Return type:

numpy.ndarray

Notes

Internal ID: 4 See: https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python

geodezyx.stats.stats.running_mean_5(data, window_width)

Compute running mean using cumulative sum method.

Parameters:
  • data (array-like) – Input data values.

  • window_width (int) – Width of the running mean window.

Returns:

ma_vec – Moving average vector.

Return type:

numpy.ndarray

Notes

Internal ID: 5 See: https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python (Roman Kh’s answer)

geodezyx.stats.stats.running_mean_convolut(data_in, window, convolve_mode='same')

Compute running mean using convolution mode.

Computes the moving average of input data using convolution with a specified mode. The result is mean-centered to avoid bias.

Parameters:
  • data_in (list or numpy.ndarray) – Input data values.

  • window (float or int) – Size of the window for the running mean.

  • convolve_mode (str, optional) – Mode for underlying convolution operation. Default is ‘same’.

Returns:

data_run – Running mean of data_in with same size as input (not shifted).

Return type:

numpy.ndarray

Notes

After stress testing, this implementation provides output with the same size as input without shifting, though it is slower than some alternatives. The subtraction of the mean is an empirical trick to center the result.

This is a wrapper based on running_mean_4. For more details on convolution modes, see: - https://stackoverflow.com/questions/13728392/moving-average-or-running-mean - https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python

geodezyx.stats.stats.sinusoide(t, a, omega, phi=0, f=None)

Generate a sinusoidal waveform.

Produces a sinusoidal waveform of the form: A * sin(ω*T + φ)

Parameters:
  • t (float or array-like) – Time variable.

  • a (float) – Amplitude, the peak deviation of the function from zero.

  • omega (float) – Angular frequency (ω = 2πf), the rate of change of the function argument in units of radians per second.

  • phi (float, optional) – Phase offset in radians, specifying where in its cycle the oscillation is at t = 0. Default is 0.

  • f (float, optional) – Ordinary frequency (cycles per second). If provided, it overrides the omega parameter. To use this parameter, set omega=0. Default is None.

Returns:

result – The sinusoidal waveform value(s).

Return type:

float or numpy.ndarray

Notes

See: https://en.wikipedia.org/wiki/Sine_wave

geodezyx.stats.stats.smooth(x, window_len=11, window='hanning')

Smooth data using a window with requested size.

This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends to minimize transient parts at the beginning and end of the output signal.

Parameters:
  • x (numpy.ndarray) – The input signal. Must be 1-dimensional.

  • window_len (int, optional) – The dimension of the smoothing window. Should be an odd integer. Default is 11.

  • window (str, optional) – The type of window from {‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’}. ‘flat’ window will produce a moving average smoothing. Default is ‘hanning’.

Returns:

y – The smoothed signal.

Return type:

numpy.ndarray

Raises:

ValueError – If input is not 1-dimensional or smaller than window size.

Notes

Works only for equally spaced data.

The output length may differ from input length. To correct this, return y[(window_len/2-1):-(window_len/2)] instead of y.

See also

numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve, scipy.signal.lfilter

References

https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html

Examples

>>> t = np.linspace(-2, 2, 0.1)
>>> x = np.sin(t) + np.random.randn(len(t)) * 0.1
>>> y = smooth(x)
geodezyx.stats.stats.time_win_basic(start, end, t_lis_inp, data_lis_inp, outposix=True, invert=False, out_array=False, out_boolis=False, only_boolis=False)

Filter data within a time window.

Selects data points that fall within a specified time window. Internally converts to POSIX time for computation.

Parameters:
  • start (datetime or float) – Start of the time window.

  • end (datetime or float) – End of the time window.

  • t_lis_inp (array-like of datetime or float) – Time values of the data points.

  • data_lis_inp (array-like) – Data values corresponding to the times.

  • outposix (bool, optional) – If True, output times in POSIX format. If False, output as datetime. Default is True.

  • invert (bool, optional) – If True, invert the boolean selection (select data outside window). Default is False.

  • out_array (bool, optional) – If True, return outputs as numpy arrays. Default is False.

  • out_boolis (bool, optional) – If True, also return the boolean selection array. Default is False.

  • only_boolis (bool, optional) – If True, skip filtering and only return boolean array. Default is False.

Returns:

  • tlisout (array-like) – Filtered time values. None if only_boolis=True.

  • datalisout (array-like) – Filtered data values. None if only_boolis=True.

  • boolis (numpy.ndarray, optional) – Boolean array indicating selected points. Only returned if out_boolis=True.

geodezyx.stats.stats.time_win_multi(start, end, t_lis, data_lislis, outposix=True, invert=False, out_array=False)

Filter multiple datasets within a time window.

Applies time window filtering to multiple data arrays simultaneously, using the same time array for all datasets.

Parameters:
  • start (datetime or float) – Start of the time window.

  • end (datetime or float) – End of the time window.

  • t_lis (array-like) – Time values for filtering.

  • data_lislis (list of array-like) – Multiple data arrays to filter.

  • outposix (bool, optional) – If True, output times in POSIX format. Default is True.

  • invert (bool, optional) – If True, invert the selection. Default is False.

  • out_array (bool, optional) – If True, return outputs as numpy arrays. Default is False.

Returns:

  • Tlisout (array-like) – Filtered time values.

  • datalislisout (list of array-like) – Filtered data arrays.

See also

time_win_basic

Filter single dataset within time window

geodezyx.stats.stats.time_win_multi_start_end(start_list_inp, end_list_inp, t_lis_inp, data_lis_inp, outposix=True, invert=False, out_array=False, out_boolis=False)

Filter data within multiple time windows simultaneously.

Selects data points that fall within ALL specified time windows. This is useful for selecting intersections of multiple time periods. Internally converts to POSIX time for computation.

Parameters:
  • start_list_inp (list of datetime or float) – Start times of the time windows.

  • end_list_inp (list of datetime or float) – End times of the time windows.

  • t_lis_inp (array-like of datetime or float) – Time values of the data points.

  • data_lis_inp (array-like) – Data values corresponding to the times.

  • outposix (bool, optional) – If True, output times in POSIX format. Default is True.

  • invert (bool, optional) – If True, invert the selection. Default is False.

  • out_array (bool, optional) – If True, return outputs as numpy arrays. Default is False.

  • out_boolis (bool, optional) – If True, also return boolean selection arrays. Default is False.

Returns:

  • tlisout (array-like) – Filtered time values.

  • datalisout (array-like) – Filtered data values.

  • boolis_opera (numpy.ndarray, optional) – Combined boolean array (intersection of all windows). Only returned if out_boolis=True.

  • boolis_stk (numpy.ndarray, optional) – Stack of individual boolean arrays for each window. Only returned if out_boolis=True.

Raises:

ValueError – If len(Start_list_in) != len(End_list_in).

geodezyx.stats.stats.wrap_to180(lon)

Wrap longitude values to the range (-180, 180].

Parameters:

lon (float or array-like) – Longitude values in degrees.

Returns:

result – Longitude values wrapped to (-180, 180].

Return type:

float or numpy.ndarray

Notes

Based on MATLAB’s wrap_to180 function.

geodezyx.stats.stats.wrap_to360(lon)

Wrap longitude values to the range [0, 360).

Parameters:

lon (float or array-like) – Longitude values in degrees.

Returns:

result – Longitude values wrapped to [0, 360].

Return type:

float or numpy.ndarray

Notes

Based on MATLAB’s wrap_to360 function.