nnsa.cwt package
Submodules
nnsa.cwt.config module
nnsa.cwt.mothers module
Classes:
|
Implements the Morlet wavelet class. |
|
|
|
Implements the Paul wavelet class. |
Functions:
|
Return a Mother wavelet object. |
- class nnsa.cwt.mothers.Morlet(*args: Any, **kwargs: Any)[source]
Bases:
Morlet,MotherImplements the Morlet wavelet class.
Note that the input parameters f and f0 are angular frequencies. f0 should be more than 0.8 for this function to be correct, its default value is f0 = 6.
Methods:
psi_ft(f)Fourier transform of the approximate Morlet wavelet.
smooth(W, dt, dj, scales[, time, scale, ...])Smoothing function used in coherence analysis.
- class nnsa.cwt.mothers.Mother[source]
Bases:
objectMethods:
coi(*args, **kwargs)flambda()freq2scal(f)get_J(s0, dj[, min_freq])get_dj(max_freq, min_freq, J)get_max_scale(dt, n0)get_min_freq(dt, n0)get_min_scale(dt)get_s0(dt)scal2freq(s)smooth(*args, **kwargs)
nnsa.cwt.plotting module
Author: Tim Hermans (tim-hermans@hotmail.com).
Functions:
|
Compute and plot CWT power in dB. |
|
Plot a scalogram with freqs in logscale. |
|
Plot time frequency map using plt.pcolormesh. |
- nnsa.cwt.plotting.plot_cwt_scalogram(x, fs=1, ax=None, cwt_kwargs=None, plot_kwargs=None)[source]
Compute and plot CWT power in dB.
nnsa.cwt.transforms module
Functions:
|
Compute partial wavelet coherence (coherence between x and y, while removing influence from z). |
|
Compute wavelet-based coherence. |
|
Wrapper of pycwt.cwt, which adds interpolation of nans, and optional detrending and normalization prior to CWT. |
|
Compute cwt for 1D or 2D array. |
|
Inverse wavelet transform. |
|
Compute partial coherence between Wx and Wy, while controlling for influence of variable(s) Wz. |
|
Compute the wavelet coherence transform from the raw CWTs of x and y. |
|
Compute smoothed cross-wavelet transform and auto-transforms of Wx and Wy. |
- nnsa.cwt.transforms.compute_partial_coherence(x, y, z, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1, **kwargs)[source]
Compute partial wavelet coherence (coherence between x and y, while removing influence from z).
- Parameters:
x (array-like) – 1D signal array with length N.
y (array_like) – 1D signal array. Must have the same length and sample frequency as x.
z (array_like or list) – 1D signal array. Must have the same length and sample frequency as x. Can also be a list of 1D signal arrays, in which case the confounding relation from each of these signals will be removed.
dt (float) – sample period of x, y and z in seconds (1/fs).
dj (float, optional) – 2log spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation. See pycwt.cwt. Defaults to 1/10.
s0 (float, optional) – smallest scale (highest frequency). See pycwt.cwt.
J (int, optional) – number of scales - 1. See pycwt.cwt. Determines lowest frequency together with s0 and ds.
wavelet (Mother, optional) – mother wavelet (from pycwt.mothers). If None, defaults to DEFAULT_WAVELET.
detrend_order (int, optional) – if not None, detrend the signals with polynomial of specified order.
normalize (bool, optional) – bool specifying whether to normalize (zero mean, unit variance) signals x, y and z before computation or not. Defaults to True.
... – see cwt() for other parameters.
**kwargs – optional parameters for pct().
- Returns:
Cxy (np.ma.MaskedArray) – 2D masked array with wavelet based magnitude squared coherence, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
Axy (np.ma.MaskedArray) – 2D masked array with phase angles of the cross-spectrum, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
freqs (np.ndarray) – frequencies in Hz corresponding to the first axis of Cxy and Axy.
insidecoi (np.ndarray) – masks for the pixels in Cxy affected by edge effects/artefacts (dependent on coimode). Dimensions are (n_freqs, n_time).
- nnsa.cwt.transforms.compute_wavelet_coherence(x, y, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1, **kwargs)[source]
Compute wavelet-based coherence.
Adopted from the wct function of the pycwt package (https://pypi.org/project/pycwt/).
- Parameters:
x (array-like) – signal array with length N.
y (array_like) – signal array. Must have the same length and sample frequency as x.
dt (float) – sample period of x and y in seconds (1/fs).
dj (float, optional) – 2log spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation. See pycwt.cwt. Defaults to 1/12.
s0 (float, optional) – smallest scale (highest frequency). See pycwt.cwt.
J (int, optional) – number of scales - 1. See pycwt.cwt. Determines lowest frequency together with s0 and ds.
wavelet (Mother, optional) – mother wavelet (from pycwt.mothers). If None, defaults to DEFAULT_WAVELET.
detrend_order (int, optional) – if not None, detrend the signals with polynomial of specified order.
normalize (bool, optional) – bool specifying whether to normalize (zero mean, unit variance) signals x and y before computation or not. Defaults to True.
... – see cwt() for other parameters.
**kwargs – optional parameters for wct().
- Returns:
Cxy (np.ma.MaskedArray) – 2D masked array with wavelet based magnitude squared coherence, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
Axy (np.ma.MaskedArray) – 2D masked array with phase angles of the cross-spectrum, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
freqs (np.ndarray) – frequencies in Hz corresponding to the first axis of Cxy and Axy.
insidecoi (np.ndarray) – masks for the pixels in Cxy affected by edge effects/artefacts (dependent on coimode). Dimensions are (n_freqs, n_time).
- nnsa.cwt.transforms.cwt(x, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1)[source]
Wrapper of pycwt.cwt, which adds interpolation of nans, and optional detrending and normalization prior to CWT.
- Parameters:
x (np.ndarray) – 1D array.
dt (float) – sampling interval (seconds).
dj (float) – spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation and plot.
s0 (float) – smallest scale of the wavelet. Default value is 2*dt.
J (float) – Number of scales less one. Scales range from s0 up to s0 * 2**(J * dj), which gives a total of (J + 1) scales. Default is J = (log2(N * dt / so)) / dj.
wavelet (str or instance of a wavelet class) – mother wavelet.default is Morlet wavelet.
detrend_order (int) – order for polynomial detrending. If None, does not perform any detrending.
normalize (bool) – normalize (center mean, unit std) prior to CWT computation.
remove_outliers (bool) – if normalize is True, removes outliers (mean +- 4*SD) and then computes the mean and SD for normalization.
check_reconstruction (bool) – check reconstruction error. If above 5%, raises an error.
nan_policy (str) – how to handle nans. Choose from: - ‘zeros’: replace with zeros. - ‘interp’: interpolate (linearly). - ‘error’: raise error if there are any nans in the input.
coimode (str, optional) – the mask in which the output may be considered significantly affected by edge effects or artefacts. Choose from: - ‘coi’: mask where edge effects are important (Cone Of Influence as defined by Torrence et al. 1998). - ‘moi’: mask where edge effects or artefacts are important (Mask Of Influence, see thesis Tim Hermans section 4.2.3).
moi_threshold (float, optional) – if coimode == ‘moi’, this can be used to define the threshold for MOI (see compute_moi()).
verbose (int) – verbosity level.
- Returns:
array with dimensions (scales, time) containing the wavelet coefficients. scales (np.ndarray): scales corresponding to Wx. freqs (np.ndarray): Fourier frequencies corresponding to the scales. insidecoi (np.ndarray): boolean array with same size as Wx, containing True if the value is inside the
cone of influence (COI).
- Return type:
Wx (np.ndarray)
- nnsa.cwt.transforms.cwt_2d(x, **kwargs)[source]
Compute cwt for 1D or 2D array.
- Parameters:
x (np.ndarray) – either 1D or 2D array. If 2D, should have shape (channels, time).
- Returns:
W (np.ndarray) – either 2D (if x is 1D) or 3D (if x is 2D)
- nnsa.cwt.transforms.icwt(W, scales, dt, dj, wavelet, cdelta=None)[source]
Inverse wavelet transform.
Note that the implementation in pycwt is NOT correct! See Torrence and Compo (1998), eq. (11). This function implements it correctly.
Note that possible effects of detrending of the signal prior to CWT are not reconstructed.
- nnsa.cwt.transforms.pct(Wx, Wy, Wz, scales, dt, dj, wavelet, smooth_kwargs=None)[source]
Compute partial coherence between Wx and Wy, while controlling for influence of variable(s) Wz.
References
X. Meng, “The time-frequency dependence of unemployment on real input prices: a wavelet coherency and partial coherency approach,” Applied Economics, vol. 52, no. 10, pp. 1124–1140, Sep. 2019.
- Parameters:
Wx (np.ndarray) – 2D array with wavelet coefficients for x (scales, time).
Wy (np.ndarray) – wavelet coefficients for y (scales, time).
Wz (np.ndarray or list) – wavelet coefficients of all the confounding variable (scales, time). Can also be a list when there is more than 1 confounding variables. Each element in the list should then contain the wavelet coefficients of one of the confounding variables.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
smooth_kwargs – dict with optional parameters for wavelet.smooth().
- Returns:
Cxyz (np.ndarray) – partial coherence values (between 0 and 1).
Axyz (np.ndarray) – phase of complex partial coherence.
- nnsa.cwt.transforms.wct(Wx, Wy, scales, dt, dj, wavelet, smooth_kwargs=None)[source]
Compute the wavelet coherence transform from the raw CWTs of x and y.
- Parameters:
Wx – 2D array with wavelet coefficients.
Wy – 2D array with wavelet coefficients.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
smooth_kwargs – dict with optional parameters for wavelet.smooth().
- Returns:
Cxy (np.ndarray) – coherence values (between 0 and 1).
Axy (np.ndarray) – cross-wavelet phase between Wx and Wy.
- nnsa.cwt.transforms.xwt_smooth(Wx, Wy, scales, dt, dj, wavelet, **kwargs)[source]
Compute smoothed cross-wavelet transform and auto-transforms of Wx and Wy.
Used for (partial) wavelet coherence.
- Parameters:
Wx – 2D array with wavelet coefficients.
Wy – 2D array with wavelet coefficients.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
**kwargs – optional parameters for wavelet.smooth().
- Returns:
Sxy, Sx, Sy – smoothed cross and auto spectra.
Wxy – non-smoothed (but possible averaged) cross-spectrum.
nnsa.cwt.utils module
Author: Tim Hermans (tim-hermans@hotmail.com).
Functions:
|
|
|
Compute the cone of influence (COI). |
|
Compute the mask of influence (MOI) in the wavelet (time-frequency) domain, given the nan mask in time domain. |
|
Compute power in specified band. |
|
For backward compatibility. |
|
Averages the instantaneous power in a specific scale band (s_min, s_max). |
|
Total power over all scales, averaged over time. |
|
Helper function to reconstuct x from its CWT. |
- nnsa.cwt.utils.compute_coi(n0, dt, freqs, wavelet)[source]
Compute the cone of influence (COI).
The COI is a mask with True values at locations where the wavelet transform is significantly influenced by artefacts (hence these regions should not be included in the interpretation of the result).
- Parameters:
n0 (int) – number of time points of the transform.
dt (float) – sampling period (1/fs).
freqs (np.ndarray) – frequency array of the transform.
wavelet (Wavelet) – wavelet object.
- Returns:
insidecoi (np.ndarray) – boolean array with shape (n0, len(freqs)). Contains True at locations inside the COI, False otherwise.
- nnsa.cwt.utils.compute_moi(nan_mask, scales, dt, dj, wavelet, threshold=0.0786496, ignore_short_nans=True)[source]
Compute the mask of influence (MOI) in the wavelet (time-frequency) domain, given the nan mask in time domain.
Where the cone of influence (COI) only considers edge effects, the mask of influence (MOI) extends this idea to edge effects and nan effects (e.g. due to missing samples in the time series prior to a wavelet transform).
- Parameters:
nan_mask (np.ndarray) – 1D boolean mask for time dimension that is True at locations of missing values/artefacts, i.e. at values where the input signal cannot be trusted.
scales – parameters used by the wavelet decomposition.
dt – parameters used by the wavelet decomposition.
dj – parameters used by the wavelet decomposition.
wavelet – parameters used by the wavelet decomposition.
threshold (float or None) – the relative contribution of nan samples to the wavelet transform. By default, is taken as the area under the Gaussian after the e-folding time (equivalent to the definition of cone of influence for a Morlet wavelet according to Torrence et al. 1998). If None, does not apply a threshold and the result of convolution is returned.
ignore_short_nans (bool) – if True, nans with a length shorter than the Nyquist period are ignored. This is determined per wavelet scale.
- Returns:
moi (np.ndarray) – boolean array same size as C containing True at locations where edge effects or missing data (nan) effects cannot be ignored.
- nnsa.cwt.utils.compute_power_cwt(x, dt, freq_low=None, freq_high=None, dj=0.1, wavelet=None, max_nan=0.5, **kwargs)[source]
Compute power in specified band.
For values in the cone of influence (COI), time averaged values are taken. If at a given point in time, more than `max_nan`*100 % frequencies are in the COI, nan is returned at that time point.
- Parameters:
x (np.ndarray) – 1D signal array.
dt (float) – sample period of x (1/fs).
freq_low (float, optional) – lower frequency cutoff for bandpower. If None, takes lowest possible.
freq_high (float, optional) – upper frequency cutoff for bandpower. If None, takes highest possible.
dj (float, optional) – scale spacing (in log-space).
wavelet (mothers.Mother, optional) – wavelet to use. Defaults to DEFAULT_WAVELET.
max_nan (float, optional) – maximum fraction of frequencies in the specified bands that can be nan at a given time (e.g. due to COI). If the number of nans if greater, nan is returned at that time point. If None, does not insert any nans in the output.
**kwargs (optional) – optional keyword arguments for cwt().
- Returns:
power (np.ndarray) – array with same size as x containing the wavelet power in the specified band.
- nnsa.cwt.utils.compute_reconstruction(Wx, scales, x, **cwt_kwargs)[source]
For backward compatibility.
- nnsa.cwt.utils.cwt_power(W, scales, dt, dj, s_min=None, s_max=None, wavelet=None, cdelta=None)[source]
Averages the instantaneous power in a specific scale band (s_min, s_max).
- Parameters:
W (np.ndarray) – 2D array containing the coefficients of the wavelet transform.
scales (np.ndarray) – array with scales.
dt – parameters of the wavelet transform.
dj – parameters of the wavelet transform.
wavelet – parameters of the wavelet transform.
cdelta (float) – reconstruction factor. Scaling factor for the power (is a contsant across all scales, just scales the output). If not given, takes the empirically defined cdelta from the wavelet (if exists). Alternatively, specify 1 if you don’t care about scaling.
s_min (float) – minimum scale to include in the band. Defaults to the lowest scale.
s_max (float) – max scale in the band. Defaults to largest scale.
- Returns:
pow (np.ndarray)
Module contents
This module contains code for analyses that make use of the continuous wavelet transform (CWT).
Classes:
|
Implements the Morlet wavelet class. |
|
|
|
Implements the Paul wavelet class. |
Functions:
|
|
|
Compute the cone of influence (COI). |
|
Compute the mask of influence (MOI) in the wavelet (time-frequency) domain, given the nan mask in time domain. |
|
Compute partial wavelet coherence (coherence between x and y, while removing influence from z). |
|
Compute power in specified band. |
|
For backward compatibility. |
|
Compute wavelet-based coherence. |
|
Wrapper of pycwt.cwt, which adds interpolation of nans, and optional detrending and normalization prior to CWT. |
|
Compute cwt for 1D or 2D array. |
|
Averages the instantaneous power in a specific scale band (s_min, s_max). |
|
Total power over all scales, averaged over time. |
|
Return a Mother wavelet object. |
|
Inverse wavelet transform. |
|
Compute partial coherence between Wx and Wy, while controlling for influence of variable(s) Wz. |
|
Compute and plot CWT power in dB. |
|
Plot a scalogram with freqs in logscale. |
|
Plot time frequency map using plt.pcolormesh. |
|
Helper function to reconstuct x from its CWT. |
|
Compute the wavelet coherence transform from the raw CWTs of x and y. |
|
Compute smoothed cross-wavelet transform and auto-transforms of Wx and Wy. |
- class nnsa.cwt.Morlet(*args: Any, **kwargs: Any)[source]
Bases:
Morlet,MotherImplements the Morlet wavelet class.
Note that the input parameters f and f0 are angular frequencies. f0 should be more than 0.8 for this function to be correct, its default value is f0 = 6.
Methods:
psi_ft(f)Fourier transform of the approximate Morlet wavelet.
smooth(W, dt, dj, scales[, time, scale, ...])Smoothing function used in coherence analysis.
- class nnsa.cwt.Mother[source]
Bases:
objectMethods:
coi(*args, **kwargs)flambda()freq2scal(f)get_J(s0, dj[, min_freq])get_dj(max_freq, min_freq, J)get_max_scale(dt, n0)get_min_freq(dt, n0)get_min_scale(dt)get_s0(dt)scal2freq(s)smooth(*args, **kwargs)
- class nnsa.cwt.Paul(*args: Any, **kwargs: Any)[source]
Bases:
Paul,MotherImplements the Paul wavelet class.
Note that the input parameter f is the angular frequency and that the default order for this wavelet is m=4.
Methods:
psi(t)Paul wavelet as described in Torrence and Compo (1998).
- nnsa.cwt.compute_coi(n0, dt, freqs, wavelet)[source]
Compute the cone of influence (COI).
The COI is a mask with True values at locations where the wavelet transform is significantly influenced by artefacts (hence these regions should not be included in the interpretation of the result).
- Parameters:
n0 (int) – number of time points of the transform.
dt (float) – sampling period (1/fs).
freqs (np.ndarray) – frequency array of the transform.
wavelet (Wavelet) – wavelet object.
- Returns:
insidecoi (np.ndarray) – boolean array with shape (n0, len(freqs)). Contains True at locations inside the COI, False otherwise.
- nnsa.cwt.compute_moi(nan_mask, scales, dt, dj, wavelet, threshold=0.0786496, ignore_short_nans=True)[source]
Compute the mask of influence (MOI) in the wavelet (time-frequency) domain, given the nan mask in time domain.
Where the cone of influence (COI) only considers edge effects, the mask of influence (MOI) extends this idea to edge effects and nan effects (e.g. due to missing samples in the time series prior to a wavelet transform).
- Parameters:
nan_mask (np.ndarray) – 1D boolean mask for time dimension that is True at locations of missing values/artefacts, i.e. at values where the input signal cannot be trusted.
scales – parameters used by the wavelet decomposition.
dt – parameters used by the wavelet decomposition.
dj – parameters used by the wavelet decomposition.
wavelet – parameters used by the wavelet decomposition.
threshold (float or None) – the relative contribution of nan samples to the wavelet transform. By default, is taken as the area under the Gaussian after the e-folding time (equivalent to the definition of cone of influence for a Morlet wavelet according to Torrence et al. 1998). If None, does not apply a threshold and the result of convolution is returned.
ignore_short_nans (bool) – if True, nans with a length shorter than the Nyquist period are ignored. This is determined per wavelet scale.
- Returns:
moi (np.ndarray) – boolean array same size as C containing True at locations where edge effects or missing data (nan) effects cannot be ignored.
- nnsa.cwt.compute_partial_coherence(x, y, z, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1, **kwargs)[source]
Compute partial wavelet coherence (coherence between x and y, while removing influence from z).
- Parameters:
x (array-like) – 1D signal array with length N.
y (array_like) – 1D signal array. Must have the same length and sample frequency as x.
z (array_like or list) – 1D signal array. Must have the same length and sample frequency as x. Can also be a list of 1D signal arrays, in which case the confounding relation from each of these signals will be removed.
dt (float) – sample period of x, y and z in seconds (1/fs).
dj (float, optional) – 2log spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation. See pycwt.cwt. Defaults to 1/10.
s0 (float, optional) – smallest scale (highest frequency). See pycwt.cwt.
J (int, optional) – number of scales - 1. See pycwt.cwt. Determines lowest frequency together with s0 and ds.
wavelet (Mother, optional) – mother wavelet (from pycwt.mothers). If None, defaults to DEFAULT_WAVELET.
detrend_order (int, optional) – if not None, detrend the signals with polynomial of specified order.
normalize (bool, optional) – bool specifying whether to normalize (zero mean, unit variance) signals x, y and z before computation or not. Defaults to True.
... – see cwt() for other parameters.
**kwargs – optional parameters for pct().
- Returns:
Cxy (np.ma.MaskedArray) – 2D masked array with wavelet based magnitude squared coherence, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
Axy (np.ma.MaskedArray) – 2D masked array with phase angles of the cross-spectrum, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
freqs (np.ndarray) – frequencies in Hz corresponding to the first axis of Cxy and Axy.
insidecoi (np.ndarray) – masks for the pixels in Cxy affected by edge effects/artefacts (dependent on coimode). Dimensions are (n_freqs, n_time).
- nnsa.cwt.compute_power_cwt(x, dt, freq_low=None, freq_high=None, dj=0.1, wavelet=None, max_nan=0.5, **kwargs)[source]
Compute power in specified band.
For values in the cone of influence (COI), time averaged values are taken. If at a given point in time, more than `max_nan`*100 % frequencies are in the COI, nan is returned at that time point.
- Parameters:
x (np.ndarray) – 1D signal array.
dt (float) – sample period of x (1/fs).
freq_low (float, optional) – lower frequency cutoff for bandpower. If None, takes lowest possible.
freq_high (float, optional) – upper frequency cutoff for bandpower. If None, takes highest possible.
dj (float, optional) – scale spacing (in log-space).
wavelet (mothers.Mother, optional) – wavelet to use. Defaults to DEFAULT_WAVELET.
max_nan (float, optional) – maximum fraction of frequencies in the specified bands that can be nan at a given time (e.g. due to COI). If the number of nans if greater, nan is returned at that time point. If None, does not insert any nans in the output.
**kwargs (optional) – optional keyword arguments for cwt().
- Returns:
power (np.ndarray) – array with same size as x containing the wavelet power in the specified band.
- nnsa.cwt.compute_wavelet_coherence(x, y, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1, **kwargs)[source]
Compute wavelet-based coherence.
Adopted from the wct function of the pycwt package (https://pypi.org/project/pycwt/).
- Parameters:
x (array-like) – signal array with length N.
y (array_like) – signal array. Must have the same length and sample frequency as x.
dt (float) – sample period of x and y in seconds (1/fs).
dj (float, optional) – 2log spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation. See pycwt.cwt. Defaults to 1/12.
s0 (float, optional) – smallest scale (highest frequency). See pycwt.cwt.
J (int, optional) – number of scales - 1. See pycwt.cwt. Determines lowest frequency together with s0 and ds.
wavelet (Mother, optional) – mother wavelet (from pycwt.mothers). If None, defaults to DEFAULT_WAVELET.
detrend_order (int, optional) – if not None, detrend the signals with polynomial of specified order.
normalize (bool, optional) – bool specifying whether to normalize (zero mean, unit variance) signals x and y before computation or not. Defaults to True.
... – see cwt() for other parameters.
**kwargs – optional parameters for wct().
- Returns:
Cxy (np.ma.MaskedArray) – 2D masked array with wavelet based magnitude squared coherence, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
Axy (np.ma.MaskedArray) – 2D masked array with phase angles of the cross-spectrum, where values inside the cone of influence (COI) are masked. Shape corresponds to (freqs, time).
freqs (np.ndarray) – frequencies in Hz corresponding to the first axis of Cxy and Axy.
insidecoi (np.ndarray) – masks for the pixels in Cxy affected by edge effects/artefacts (dependent on coimode). Dimensions are (n_freqs, n_time).
- nnsa.cwt.cwt(x, dt, dj=0.1, s0=-1, J=-1, wavelet=None, detrend_order=2, normalize=True, remove_outliers=False, check_reconstruction=False, nan_policy='zeros', coimode='moi', moi_threshold=0.0786496, verbose=1)[source]
Wrapper of pycwt.cwt, which adds interpolation of nans, and optional detrending and normalization prior to CWT.
- Parameters:
x (np.ndarray) – 1D array.
dt (float) – sampling interval (seconds).
dj (float) – spacing between discrete scales. Smaller values will result in better scale resolution, but slower calculation and plot.
s0 (float) – smallest scale of the wavelet. Default value is 2*dt.
J (float) – Number of scales less one. Scales range from s0 up to s0 * 2**(J * dj), which gives a total of (J + 1) scales. Default is J = (log2(N * dt / so)) / dj.
wavelet (str or instance of a wavelet class) – mother wavelet.default is Morlet wavelet.
detrend_order (int) – order for polynomial detrending. If None, does not perform any detrending.
normalize (bool) – normalize (center mean, unit std) prior to CWT computation.
remove_outliers (bool) – if normalize is True, removes outliers (mean +- 4*SD) and then computes the mean and SD for normalization.
check_reconstruction (bool) – check reconstruction error. If above 5%, raises an error.
nan_policy (str) – how to handle nans. Choose from: - ‘zeros’: replace with zeros. - ‘interp’: interpolate (linearly). - ‘error’: raise error if there are any nans in the input.
coimode (str, optional) – the mask in which the output may be considered significantly affected by edge effects or artefacts. Choose from: - ‘coi’: mask where edge effects are important (Cone Of Influence as defined by Torrence et al. 1998). - ‘moi’: mask where edge effects or artefacts are important (Mask Of Influence, see thesis Tim Hermans section 4.2.3).
moi_threshold (float, optional) – if coimode == ‘moi’, this can be used to define the threshold for MOI (see compute_moi()).
verbose (int) – verbosity level.
- Returns:
array with dimensions (scales, time) containing the wavelet coefficients. scales (np.ndarray): scales corresponding to Wx. freqs (np.ndarray): Fourier frequencies corresponding to the scales. insidecoi (np.ndarray): boolean array with same size as Wx, containing True if the value is inside the
cone of influence (COI).
- Return type:
Wx (np.ndarray)
- nnsa.cwt.cwt_2d(x, **kwargs)[source]
Compute cwt for 1D or 2D array.
- Parameters:
x (np.ndarray) – either 1D or 2D array. If 2D, should have shape (channels, time).
- Returns:
W (np.ndarray) – either 2D (if x is 1D) or 3D (if x is 2D)
- nnsa.cwt.cwt_power(W, scales, dt, dj, s_min=None, s_max=None, wavelet=None, cdelta=None)[source]
Averages the instantaneous power in a specific scale band (s_min, s_max).
- Parameters:
W (np.ndarray) – 2D array containing the coefficients of the wavelet transform.
scales (np.ndarray) – array with scales.
dt – parameters of the wavelet transform.
dj – parameters of the wavelet transform.
wavelet – parameters of the wavelet transform.
cdelta (float) – reconstruction factor. Scaling factor for the power (is a contsant across all scales, just scales the output). If not given, takes the empirically defined cdelta from the wavelet (if exists). Alternatively, specify 1 if you don’t care about scaling.
s_min (float) – minimum scale to include in the band. Defaults to the lowest scale.
s_max (float) – max scale in the band. Defaults to largest scale.
- Returns:
pow (np.ndarray)
- nnsa.cwt.cwt_total_power(W, scales, dt, dj, wavelet=None, cdelta=None)[source]
Total power over all scales, averaged over time.
- Parameters:
cwt_power(). (see) –
- nnsa.cwt.get_wavelet(wavelet)[source]
Return a Mother wavelet object.
- Parameters:
wavelet (str or Wavelet) – e.g. ‘Morlet(6)’.
- Returns:
w (Mother) – wavelet object.
- nnsa.cwt.icwt(W, scales, dt, dj, wavelet, cdelta=None)[source]
Inverse wavelet transform.
Note that the implementation in pycwt is NOT correct! See Torrence and Compo (1998), eq. (11). This function implements it correctly.
Note that possible effects of detrending of the signal prior to CWT are not reconstructed.
- nnsa.cwt.pct(Wx, Wy, Wz, scales, dt, dj, wavelet, smooth_kwargs=None)[source]
Compute partial coherence between Wx and Wy, while controlling for influence of variable(s) Wz.
References
X. Meng, “The time-frequency dependence of unemployment on real input prices: a wavelet coherency and partial coherency approach,” Applied Economics, vol. 52, no. 10, pp. 1124–1140, Sep. 2019.
- Parameters:
Wx (np.ndarray) – 2D array with wavelet coefficients for x (scales, time).
Wy (np.ndarray) – wavelet coefficients for y (scales, time).
Wz (np.ndarray or list) – wavelet coefficients of all the confounding variable (scales, time). Can also be a list when there is more than 1 confounding variables. Each element in the list should then contain the wavelet coefficients of one of the confounding variables.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
smooth_kwargs – dict with optional parameters for wavelet.smooth().
- Returns:
Cxyz (np.ndarray) – partial coherence values (between 0 and 1).
Axyz (np.ndarray) – phase of complex partial coherence.
- nnsa.cwt.plot_cwt_scalogram(x, fs=1, ax=None, cwt_kwargs=None, plot_kwargs=None)[source]
Compute and plot CWT power in dB.
- nnsa.cwt.plot_scalogram(time, freqs, C, insidecoi=None, alpha=0.75, prange=None, time_scale='seconds', db=False, ax=None, colorbar=False, **kwargs)[source]
Plot a scalogram with freqs in logscale.
- nnsa.cwt.plot_tf_map(C, time=None, freqs=None, time_scale='seconds', freq_scale='Hz', colorbar=True, ax=None, **kwargs)[source]
Plot time frequency map using plt.pcolormesh.
- nnsa.cwt.reconstruct_x(Wx, x, scales, cwt_kwargs)[source]
Helper function to reconstuct x from its CWT.
- nnsa.cwt.wct(Wx, Wy, scales, dt, dj, wavelet, smooth_kwargs=None)[source]
Compute the wavelet coherence transform from the raw CWTs of x and y.
- Parameters:
Wx – 2D array with wavelet coefficients.
Wy – 2D array with wavelet coefficients.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
smooth_kwargs – dict with optional parameters for wavelet.smooth().
- Returns:
Cxy (np.ndarray) – coherence values (between 0 and 1).
Axy (np.ndarray) – cross-wavelet phase between Wx and Wy.
- nnsa.cwt.xwt_smooth(Wx, Wy, scales, dt, dj, wavelet, **kwargs)[source]
Compute smoothed cross-wavelet transform and auto-transforms of Wx and Wy.
Used for (partial) wavelet coherence.
- Parameters:
Wx – 2D array with wavelet coefficients.
Wy – 2D array with wavelet coefficients.
scales – cwt parameters/output.
dt – cwt parameters/output.
dj – cwt parameters/output.
wavelet – cwt parameters/output.
**kwargs – optional parameters for wavelet.smooth().
- Returns:
Sxy, Sx, Sy – smoothed cross and auto spectra.
Wxy – non-smoothed (but possible averaged) cross-spectrum.