diff --git a/CHANGELOG.md b/CHANGELOG.md index 144c0122..0d089030 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,18 +16,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 documented and tested: - when the rows after `t` are replaced by any values (finite, NaN or inf), row `t` is unchanged bit for bit, with every supported reducer; - - when the rows after `t` are removed, row `t` is unchanged to 1e-9 - (absolute) for outputs that depend continuously on the correlations: no - reduction, `"strength"`, the summaries (`tc.WeightedStrength`, - `tc.Communities`) and the linear models listed below once fitted. Removal - changes the correlations by round-off, and the eigenvector-based graph - measures (`"eigenvector_centrality"`, `"pagerank_centrality"`, - `"pagerank_centrality_abs"`) can differ by more at a correlation matrix - whose leading eigenvalues coincide, and the t statistics of - `tc.tstat_combine` where the subjects' correlations nearly coincide - (always with two subjects and `tc.isfc`): they divide by the spread - across subjects and agree to about 1e-9 of their magnitude instead (0.12 - on 3.8e7 in the case measured; replacement changes no bit); + - when the rows after `t` are removed, row `t` is unchanged bit for bit + as well with the built-in kernel functions, with every supported + reducer and combine function (the graph measures and `tc.tstat_combine` + included) and for smoothed values (`cfun=None`): the estimator computes + a row with the same operations whatever the length of the series. + Kernel rows are taken in groups with the shapes they have in a series + without an end (rows and columns beyond the data are zeros), each row of + features is a matrix product of its own, and the columns of a chunk of + kernel rows are those of its first row; the effective sample sizes that + `min_samples` is compared with are summed over the same columns; a + streamed step leaves every correlation as the product of its own row of + features gave it (no average with the transposed pair, which depended + on the blocks of nodes, so on T and `max_memory_gb`: the two + orientations of a pair agree to round-off); a fitted model reduces 128 + rows at a time, the last batch filled with rows of zeros. No output of + a causal call depends on `max_memory_gb`. This is tested, not proven: + it holds when the linear-algebra library computes a row of a matrix + product of a given shape from that row's operands alone, and NumPy's + elementwise functions a value from that value alone; the tests ran + with Accelerate (macOS) when this was written. Tested at cuts at, just before + and just after multiples of 16 and 128 rows, for every built-in kernel, + events, NaN samples, `min_samples`, kernels wider than 512 timepoints, + 150 features (several blocks of features), every length from 1, fitted + reducers, `refit_every`, `FeaturesModel.transform`, `min_samples` at + the effective sizes that occur, several memory limits + (`tests/test_causal_estimator.py`, `tests/test_causal_features.py`, + `tests/test_causal_fit.py`), and in configurations drawn at random + (`tests/test_causal_removal_random.py`: 300 draws in every run, 3000 + in the slow run); + - with a kernel array or a kernel function of your own, the columns of a + chunk are found from its weights and can depend on the length, so + removal is documented to 1e-9 (absolute) for outputs that depend + continuously on the correlations (no reduction, `"strength"`, the + summaries and the linear models listed below once fitted), not for the + eigenvector-based graph measures at a correlation matrix whose leading + eigenvalues coincide, and to about 1e-9 of their magnitude for the t + statistics of `tc.tstat_combine` where the subjects' correlations + nearly coincide (no changed bit was measured with such kernels either); - with `include_zero=False`, row `t` is also unchanged when row `t` itself changes; - with a fitted reducer (`fit_timepoints=n`, below) this holds for rows @@ -35,10 +61,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 removed; - smoothed values (`cfun=None`) are on the scale of the data (each chunk of 128 rows is centered on the kernel-weighted mean at its first row, which - is added back, never on a mean over later rows): under removal - they agree to round-off relative to the magnitude of the data (to 1e-9 or - 8 units in the last place of the largest magnitude of the data, whichever - is larger); replacement changes no bit; + is added back, never on a mean over later rows): replacement + changes no bit, nor removal with the built-in kernel functions; with a + kernel of your own they agree under removal to round-off relative to + the magnitude of the data (to 1e-9 or 8 units in the last place of the + largest magnitude of the data, whichever is larger); - a series of any length runs (one row included), and its output is the first rows of the output of a longer series. @@ -119,6 +146,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 without `components_`, or that fails a check, raises `ValueError` (`"UMAP"`, `"KernelPCA"`, `"Isomap"`, `"MDS"`, `"TSNE"`, `"SpectralEmbedding"`, `"LocallyLinearEmbedding"`). + - A model asked for at least as many components as its input has columns + is not fitted and returns the columns as they are, whatever the number + of training rows (the number asked for is `n_components` given with the + model, in its `kwargs` or of a model object, otherwise `ndims`). The + widths are those of the call without `causal=True`: `n_components` + given with the model is the width of a fitted model's output, and + decides whether a model is fitted; when none is, the output has the + columns of the input and zero columns up to `ndims` only. A model + object given in a model dict is not fitted or changed by a causal call + (a copy is fitted; a call without `causal=True` fits the object, as in + 0.3.1). Asked + for fewer components than columns but more than there are defined + training rows, it is fitted with as many components as those rows (an + `n_components` given with the model is replaced), and zero columns are + appended for the others, with the warning of `reduce`. + - `"FastICA"` (the name, or a model dict with the name, scikit-learn's + class or an object of it), when it is asked for fewer components than + it has columns (with at least as many, the columns are returned as they + are, as for every model), is given the columns that vary over the + training rows first + and is asked for no more components than the rank of the centered + training rows (`numpy.linalg.matrix_rank`; at most the columns that + vary and the rows less one: zero columns are appended for the others, + with the warning of `reduce`; `ValueError` when no column varies). + FastICA divides by the singular values of its rows, and a fit with more + components than their rank did not reproduce its training rows (the + call raised; found by the random removal test, for example 9 defined + training rows and 15 components). scikit-learn's FastICA sets the + sign of each component from its loading on the first column, which for + vectorized correlations is a diagonal entry (1 in every row): the + loading is 0 up to the round-off of the SVD, and where it was exactly 0 + the fit held NaN and the call raised ("A has a NaN entry": 136 of 240 + calls of `features(..., order=2, rfun="FastICA", delta_rfun="FastICA")` + measured on macOS, one test on Linux). Calls without `causal=True` are + not changed. - `"PCA"` is fitted with `svd_solver="full"` in causal mode unless a model dict gives a solver (the randomized solver that scikit-learn chooses for large inputs failed the check that a model reproduces its training rows, @@ -203,6 +265,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `tests/test_chunked_kernels.py`) pass unchanged. `min_samples`, `fit_timepoints`, `refit_every` or `return_model=True` given without `causal=True` raise `ValueError`. +- `tc.tstat_combine`: an entry whose values across subjects differ by + round-off only now has the statistic of an entry whose values are equal: + t = +inf or -inf with the sign of the mean of its values (p = 0), or 0 + (p = 1) for a mean of 0. Round-off is a range across the subjects of at + most 128 eps (2.8e-14), or that times the largest magnitude when it + exceeds 1 (`helpers._round_off_spread`). The bound is absolute for + magnitudes up to 1: values closer than 2.8e-14 are treated as equal + whatever their size, so `tc.tstat_combine` of 1e-16 and 2e-16 is +inf + (3 in 0.3.1). The round-off of a correlation is absolute, at the scale + of 1: the same correlation below 0.01 computed in two orders differed by + at most 0.19 eps, which was up to 14,000 eps of its own size. In 0.3.1 such an entry had the mean divided + by that round-off: a finite t of up to 1e16 in magnitude, and scipy's + `RuntimeWarning` about precision loss. This is what differs from 0.3.1, + with and without `causal=True`: the entries of `tc.isfc` with two subjects + (its two correlation matrices are the same numbers computed in two + orders) that were not equal bit for bit, 32 of 700 in one case measured + (2 subjects, 70 timepoints, 4 features; |t| up to 1.3e16; the other 668 + were already +-inf) and 1190 of 39,000 in another (120 timepoints, 25 + features), and any entry of a list given to `tc.tstat_combine` with a range + that small. Every other output is unchanged bit for bit (3000 random + lists of 3 to 6 matrices, 288,000 entries, and the stored-output tests). + The same correlation computed in two orders differed by at most 61 eps in + 33.8 million entries measured, except in the first defined row of + `causal=True` (3 samples), where 13 entries differed by more than 128 eps + (up to 3108 eps) and keep their finite statistic. A range of 1e-13 or + more is a difference between subjects, as before. - `install_requires`: `hypertools>=1.1` (was `hypertools>=0.8`; see Fixed). The `tutorials` extra keeps `hypertools>=1.2`. diff --git a/CLAUDE.md b/CLAUDE.md index 660c71f3..5d074399 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,9 +80,9 @@ The `timecorr` function accepts: - `combine`: how per-subject results are combined (`null_combine` keeps them separate) - `rfun`: dimensionality reduction applied to the vectorized correlations (a model name, a graph measure, a summary such as `tc.WeightedStrength(signed=True)` or `"communities"`, or a callable); in `features` also `"auto"` (the default) and dicts keyed by order, with `delta_rfun` for the feeding path -The estimator (`wcorr`) is a kernel-weighted Pearson correlation; a true delta kernel (`eye_weights`) gives co-fluctuations (products of z-scored series). It reads every kernel (a T x T array or a `LagKernel`) through `helpers._KernelRows`, in chunks of 128 rows (`_kernels.CHUNK`), each a contiguous block over its columns, with one span finder (`_time_slices`, which also reads the prepared rows of `_KernelRows`) and one rescaling of extreme rows, so an array and the equal `LagKernel` give identical results (`tests/test_chunked_kernels.py`; `tests/test_kernels_reference.py` compares with stored outputs of commit 6b3d23a, written by `tests/fixtures/make_chunked_kernels_reference.py`); blocks are kept up to `_KERNEL_CACHE_ELEMENTS` (32 MB) and computed again beyond it, and the kernel memory of a `LagKernel` is at most that plus about 4 blocks of 128 x T (`_kernel_work_elements`, used by `estimate_memory_gb`, whose keyword `weights_function` counts a user's kernel function as T x T arrays). Its kernel products are time sliced: each chunk is multiplied only with the span of columns where it has non-zero weight, unless the spans cover more than half the kernel or the samples, their squares or cross products are not all finite; then each chunk spans every column (`helpers._TIME_SLICING = False` forces that; `tests/test_time_sliced_estimation.py` compares both). The two differ only in the order of floating-point summation, but entries whose kernel-weighted variance nearly cancels are sensitive to that order in either path, so the tests compare those entries by a conditioning measure computed from the data and kernel. A kernel-weighted variance counts as zero (correlations 0, counted in the zero-variance warning) when it is at most 1e-10 of the mean square of the globally centered column or at the round-off level of the raw column (`helpers._zero_variance` and `_round_off_variance`, also used by the delta kernel's and `segment`'s z-scores). Columns are centered on their overall means, so with a one-sided kernel only well-conditioned estimates are independent of the excluded timepoints; estimates near the 1e-10 threshold can differ (`tests/test_estimator_causality.py`). Fisher z averaging and `tstat_combine` treat values at most `helpers._UNIT_TOLERANCE` (128 eps, 2.8e-14) below +-1 or at most 1e-12 above as +-1 (`helpers._correlation_z`). +The estimator (`wcorr`) is a kernel-weighted Pearson correlation; a true delta kernel (`eye_weights`) gives co-fluctuations (products of z-scored series). It reads every kernel (a T x T array or a `LagKernel`) through `helpers._KernelRows`, in chunks of 128 rows (`_kernels.CHUNK`), each a contiguous block over its columns, with one span finder (`_time_slices`, which also reads the prepared rows of `_KernelRows`) and one rescaling of extreme rows, so an array and the equal `LagKernel` give identical results (`tests/test_chunked_kernels.py`; `tests/test_kernels_reference.py` compares with stored outputs of commit 6b3d23a, written by `tests/fixtures/make_chunked_kernels_reference.py`); blocks are kept up to `_KERNEL_CACHE_ELEMENTS` (32 MB) and computed again beyond it, and the kernel memory of a `LagKernel` is at most that plus about 4 blocks of 128 x T (`_kernel_work_elements`, used by `estimate_memory_gb`, whose keyword `weights_function` counts a user's kernel function as T x T arrays). Its kernel products are time sliced: each chunk is multiplied only with the span of columns where it has non-zero weight, unless the spans cover more than half the kernel or the samples, their squares or cross products are not all finite; then each chunk spans every column (`helpers._TIME_SLICING = False` forces that; `tests/test_time_sliced_estimation.py` compares both). The two differ only in the order of floating-point summation, but entries whose kernel-weighted variance nearly cancels are sensitive to that order in either path, so the tests compare those entries by a conditioning measure computed from the data and kernel. A kernel-weighted variance counts as zero (correlations 0, counted in the zero-variance warning) when it is at most 1e-10 of the mean square of the globally centered column or at the round-off level of the raw column (`helpers._zero_variance` and `_round_off_variance`, also used by the delta kernel's and `segment`'s z-scores). Columns are centered on their overall means, so with a one-sided kernel only well-conditioned estimates are independent of the excluded timepoints; estimates near the 1e-10 threshold can differ (`tests/test_estimator_causality.py`). Fisher z averaging and `tstat_combine` treat values at most `helpers._UNIT_TOLERANCE` (128 eps, 2.8e-14) below +-1 or at most 1e-12 above as +-1 (`helpers._correlation_z`). `tstat_combine` gives an entry whose values across subjects have a range of at most `_UNIT_TOLERANCE` (128 eps, 2.8e-14), or that times the largest magnitude when it exceeds 1 (`helpers._round_off_spread`; absolute below 1, so values closer than 2.8e-14 are equal whatever their size, 1e-16 and 2e-16 included: a correlation's round-off is absolute, 0.19 eps measured for correlations below 0.01, up to 14,000 eps of their size), the value of an entry without spread: +-inf with the sign of the mean, 0 for a mean of 0 (p 0 or 1), in causal and non-causal mode; `isfc` of two subjects computes the same correlations in two orders, which differ by up to 61 eps (measured; more in the first defined row of causal mode, 3 samples, whose entries above the bound keep their finite statistic); `tests/test_round_off_variance.py`. -Causal mode (`causal=True`; `tests/test_causal_*.py`). The guarantee as documented: row `t` is unchanged bit for bit when rows after `t` are replaced by any values (finite, NaN, inf), and to 1e-9 when they are removed, for outputs continuous in the correlations (no reduction, `"strength"`, the summaries, linear models once fitted); the eigenvector-based graph measures (`"eigenvector_centrality"`, the PageRank measures) can differ by more under removal where leading eigenvalues coincide, and the t statistics of `tstat_combine` where the subjects' correlations nearly coincide (always with two subjects and `isfc`; to about 1e-9 of their magnitude); smoothed values (`cfun=None`) agree under removal to round-off relative to the data's magnitude (1e-9 or 8 units in the last place of the largest magnitude); with `include_zero=False` row `t` is also unchanged when row `t` changes; with a fitted reducer the guarantee is for rows `t >= fit_timepoints`, and a row before is unchanged when rows from `fit_timepoints` on change. The kernel is backward (`'forward'`/`'post'` raise) and its parameters must be given (`weights_params=None` raises for every kernel; `{}` for one without parameters); `eye_weights`, `cfun=tc.wisfc` (but not `functools.partial(tc.wisfc, subject_weights=...)`, recognized as the built-in with fixed weights), events given as features, and a kernel array or user kernel function with weight above the diagonal (`_check_causal_kernel`) raise `ValueError`; a callable `cfun`/`combine`/`rfun` of the user's runs with one `UserWarning` that the guarantee does not cover it (`timecorr._builtin_combine` names the built-in combine functions); `timecorr(causal=True, cfun=None)` ignores `rfun` as without `causal`; event boundaries at or beyond the end of the data are ignored, so a prefix runs with the events of the whole series, and every prefix from T = 1 runs. The estimator (`helpers._causal_setup`, `_causal_block`): `_causal_clean` turns inf and `|x| > 1e150` (`_CAUSAL_MAX`) into NaN; a timepoint without any sample gets zero kernel columns; a row is defined (`_causal_defined`) with at least 3 observed timepoints of non-zero weight and, with `min_samples` (default None), an effective sample size `(sum |w|)**2 / sum w**2` over them of at least `min_samples` (relative tolerance 1e-12; smoothing uses the effective size only, per feature; a number no built-in kernel row can reach raises, decided from the lag profile by `_kernel_reach` / `_check_reachable`, independent of T; for a Mexican hat wider than about 2 million samples the reach is an upper bound about 1% above, `_strided_reach` with `_STRIDED_MARGIN` 1.01), and undefined rows are NaN, the diagonal included (zero-variance entries stay 0); chunks are always time sliced and computed a group of 16 rows at a time (`_CAUSAL_GROUP`, larger for chunks weighting more than `_CAUSAL_SPAN` = 512 columns), each group centered on the kernel-weighted mean of the observed samples at its first row (`_group_reference`; without one, `_causal_reference`: the mean of the earlier observed samples in the span, else the first observed sample), never on the overall mean; a row uses the sums for complete data exactly when no timepoint it weights has a NaN sample and the pairwise sums otherwise, so later values change no bit; the zero-variance rule (`_causal_zero_variance`) is `_zero_variance` about the group's reference or a kernel-weighted standard deviation below 1e-9 (`_CAUSAL_CONSTANT`) of `|kernel-weighted mean|` (a column constant up to round-off, which causal mode does not set to its mean). `mat2vec` zeroes NaN above the diagonal, so code that vectorizes causal correlations has to put the NaN rows back. Reducers in causal mode skip NaN rows (fits use defined rows; transforms return NaN rows as NaN; a defined row is one without any NaN or infinite value, `timecorr._defined_rows`, for models, summaries and graph measures alike: hypertools imputes from every row it is given and the summaries raise for NaN, so a partly NaN row, as of smoothing in `features`, is left out of fits and is a row of NaN in the output; streamed steps without `max_memory_gb` use the block size of data with NaN samples for every recording (`summaries._Units.has_nan`), so later NaN samples change no bit; a model needs 2 defined training rows, a summary 1, the shift null 40 rows) and combine functions give NaN on the union of the subjects' NaN rows; at orders >= 2 the NaN rows of the feeding features are missing data, so warm-up accumulates over orders. Hypertools models: the guarantee covers `_GUARANTEED_MODELS` of `timecorr.py` (scikit-learn's PCA, IncrementalPCA, TruncatedSVD, FastICA, FactorAnalysis, by exact class); any other model whose fitted estimator has `components_`, reproduces its training rows to 1e-9 and reduces rows one at a time as together is used with one `UserWarning` per call (`_uncovered_model`, `_warn_uncovered_models`); a model without `components_` or failing a check raises `ValueError` (UMAP, KernelPCA, Isomap, MDS, TSNE, SpectralEmbedding, LocallyLinearEmbedding); `"PCA"` is fitted with `svd_solver="full"` unless a model dict gives a solver; a model output column constant on the training rows up to round-off (`_FROZEN_RTOL` 1e-9, `_FROZEN_ZERO_RTOL` 1e-12) is frozen: a value within that tolerance of the column's training mean is returned as that mean, other values as computed; a model asked for at least as many components as columns changes nothing (zero columns appended). The warning text about undefined timepoints counts rows of the whole output (ruled not part of the guarantee, which is about returned values). +Causal mode (`causal=True`; `tests/test_causal_*.py`). The guarantee as documented: row `t` is unchanged bit for bit when rows after `t` are replaced by any values (finite, NaN, inf) and, with the built-in kernel functions, when they are removed (every reducer, combine function and `cfun=None` included; `test_removing_later_rows_changes_no_bit*` and `*_exact_under_removal` in `tests/test_causal_*.py`); with a kernel array or kernel function of the user's removal is documented to 1e-9 for outputs continuous in the correlations (no reduction, `"strength"`, the summaries, linear models once fitted), not for the eigenvector-based graph measures where leading eigenvalues coincide, to about 1e-9 of their magnitude for `tstat_combine` t statistics of nearly equal correlations, and for smoothed values to round-off relative to the data's magnitude (1e-9 or 8 units in the last place of the largest magnitude); with `include_zero=False` row `t` is also unchanged when row `t` changes; with a fitted reducer the guarantee is for rows `t >= fit_timepoints`, and a row before is unchanged when rows from `fit_timepoints` on change. The kernel is backward (`'forward'`/`'post'` raise) and its parameters must be given (`weights_params=None` raises for every kernel; `{}` for one without parameters); `eye_weights`, `cfun=tc.wisfc` (but not `functools.partial(tc.wisfc, subject_weights=...)`, recognized as the built-in with fixed weights), events given as features, and a kernel array or user kernel function with weight above the diagonal (`_check_causal_kernel`) raise `ValueError`; a callable `cfun`/`combine`/`rfun` of the user's runs with one `UserWarning` that the guarantee does not cover it (`timecorr._builtin_combine` names the built-in combine functions); `timecorr(causal=True, cfun=None)` ignores `rfun` as without `causal`; event boundaries at or beyond the end of the data are ignored, so a prefix runs with the events of the whole series, and every prefix from T = 1 runs. The estimator (`helpers._causal_setup`, `_causal_block`): `_causal_clean` turns inf and `|x| > 1e150` (`_CAUSAL_MAX`) into NaN; a timepoint without any sample gets zero kernel columns; a row is defined (`_causal_defined`) with at least 3 observed timepoints of non-zero weight and, with `min_samples` (default None), an effective sample size `(sum |w|)**2 / sum w**2` over them of at least `min_samples` (relative tolerance 1e-12; smoothing uses the effective size only, per feature; a number no built-in kernel row can reach raises, decided from the lag profile by `_kernel_reach` / `_check_reachable`, independent of T; for a Mexican hat wider than about 2 million samples the reach is an upper bound about 1% above, `_strided_reach` with `_STRIDED_MARGIN` 1.01), and undefined rows are NaN, the diagonal included (zero-variance entries stay 0); chunks are always time sliced and computed a group of 16 rows at a time (`_CAUSAL_GROUP`, larger for chunks weighting more than `_CAUSAL_SPAN` = 512 columns). What makes removal exact: no shape or operand of the operations that give a row depends on the length of the series or on the block of features asked for. `_causal_groups` gives every group the row count `n` and columns `c0:g0+n` it has in a complete chunk of a series without an end (`_group_block` and `_group_span` fill rows and columns beyond the data with zeros; the group size comes from `t0 + CHUNK - c0`, not from the chunk's last column); `_time_slices(always=True)` takes a `LagKernel` chunk's first column from `LagKernel.span` (that of its first row), not from its non-zero weights (a Mexican hat is exactly 0 at lag sigma); `_causal_block` computes the cross products of each row of features as one item of a stacked `np.matmul` (BLAS results of one 2-D product depend on which other rows and columns are in it; measured on Accelerate), the triangle of an autocorrelation in aligned sets of `_CAUSAL_FEATURES` = 8 rows of features with the columns from the set's first row on (`state["triangular"]`; `_wcorr_blocks` uses blocks that are multiples of 8; the streamed path of `_corr_row_blocks` uses every column), and `_causal_pairwise` the pairwise sums the same way; `_causal_smooth` pads each chunk to 128 rows and to the columns up to `t0 + CHUNK`; `_kernel_samples` sums the effective sizes of `min_samples` over the same columns; a causal streamed block (`_corr_row_blocks`) sets its diagonal and averages no pair with its transpose (`_symmetrize_block(average=False)`: the blocks of nodes depend on T and `max_memory_gb`, so the two orientations of a pair agree to round-off only); `_FittedModel._reduce` gives hypertools `_APPLY_ROWS` = 128 rows at a time, zero-filled. No causal output depends on `max_memory_gb`. All of it is tested, not proven (it needs a BLAS that computes a row of a product of fixed shape from that row alone; run with Accelerate so far): `tests/test_causal_removal_random.py` draws configurations (300 in every run, 3000 slow); a draw is left out only when its error message matches one of the named invalid configurations in its `INVALID`, any other exception fails the test. Each group is centered on the kernel-weighted mean of the observed samples at its first row (`_group_reference`; without one, `_causal_reference`: the mean of the earlier observed samples in the span, else the first observed sample), never on the overall mean; a row uses the sums for complete data exactly when no timepoint it weights has a NaN sample and the pairwise sums otherwise, so later values change no bit; the zero-variance rule (`_causal_zero_variance`) is `_zero_variance` about the group's reference or a kernel-weighted standard deviation below 1e-9 (`_CAUSAL_CONSTANT`) of `|kernel-weighted mean|` (a column constant up to round-off, which causal mode does not set to its mean). `mat2vec` zeroes NaN above the diagonal, so code that vectorizes causal correlations has to put the NaN rows back. Reducers in causal mode skip NaN rows (fits use defined rows; transforms return NaN rows as NaN; a defined row is one without any NaN or infinite value, `timecorr._defined_rows`, for models, summaries and graph measures alike: hypertools imputes from every row it is given and the summaries raise for NaN, so a partly NaN row, as of smoothing in `features`, is left out of fits and is a row of NaN in the output; streamed steps without `max_memory_gb` use the block size of data with NaN samples for every recording (`summaries._Units.has_nan`), so later NaN samples change no bit; a model needs 2 defined training rows, a summary 1, the shift null 40 rows) and combine functions give NaN on the union of the subjects' NaN rows; at orders >= 2 the NaN rows of the feeding features are missing data, so warm-up accumulates over orders. Hypertools models: the guarantee covers `_GUARANTEED_MODELS` of `timecorr.py` (scikit-learn's PCA, IncrementalPCA, TruncatedSVD, FastICA, FactorAnalysis, by exact class); any other model whose fitted estimator has `components_`, reproduces its training rows to 1e-9 and reduces rows one at a time as together is used with one `UserWarning` per call (`_uncovered_model`, `_warn_uncovered_models`); a model without `components_` or failing a check raises `ValueError` (UMAP, KernelPCA, Isomap, MDS, TSNE, SpectralEmbedding, LocallyLinearEmbedding); `"PCA"` is fitted with `svd_solver="full"` unless a model dict gives a solver; `"FastICA"` is given the columns that vary on the training rows first (`helpers._varying_first`, `_FittedModel.order`; `components` are returned in the order of the input) and at most as many components as the rank of the centered training rows, only when a model is fitted (fewer components than columns; the name, or a model dict with the name, the class or an object: `_is_fastica`) (scikit-learn multiplies a component by the sign of its loading on the first column, a constant diagonal entry: 0 on some platforms, and the fit then holds NaN); a model output column constant on the training rows up to round-off (`_FROZEN_RTOL` 1e-9, `_FROZEN_ZERO_RTOL` 1e-12) is frozen: a value within that tolerance of the column's training mean is returned as that mean, other values as computed; a model asked for at least as many components as columns changes nothing (zero columns appended), whatever the number of training rows (`helpers._causal_components`: the number asked for is `n_components` given with the model, in `kwargs` or of an object, else `ndims`; fewer than the columns but more than the training rows: fitted with as many as the rows, an explicit `n_components` replaced, zero columns appended with the warning of `reduce`). The warning text about undefined timepoints counts rows of the whole output (ruled not part of the guarantee, which is about returned values). ### Data Flow diff --git a/docs/api.rst b/docs/api.rst index 8eb63dc5..1d5fca16 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -209,14 +209,19 @@ With ``causal=True`` (keyword-only, in ``timecorr``, ``features``, ``two_path_step``, and in ``wcorr``, ``autofc``, ``isfc`` and ``wisfc``), row ``t`` of every output is computed from rows ``0..t`` of the data only. The row is unchanged, bit for bit, when later rows are replaced by any values (NaN and -inf included), and to 1e-9 when later rows are removed, for outputs that depend -continuously on the correlations (no reduction, ``"strength"``, the summaries, -and linear models such as PCA once fitted); the eigenvector-based graph -measures (``"eigenvector_centrality"``, the PageRank measures) can differ by -more under removal at a correlation matrix whose leading eigenvalues coincide, -and the t statistics of ``tstat_combine`` where the subjects' correlations -nearly coincide (always with two subjects and ``isfc``): they divide by the -spread across subjects, and agree to about 1e-9 of their magnitude instead. +inf included) and, with the built-in kernel functions, when later rows are +removed: a row is computed with the same operations whatever the length of the +series and whatever ``max_memory_gb`` (tested, also in configurations drawn at +random, not proven: it holds when the linear-algebra library computes a row of +a matrix product of a given shape from that row's operands alone). With a +kernel array or a kernel function of your own, removal is +documented to 1e-9 for outputs that depend continuously on the correlations (no +reduction, ``"strength"``, the summaries, and linear models such as PCA once +fitted); the eigenvector-based graph measures (``"eigenvector_centrality"``, +the PageRank measures) can then differ by more at a correlation matrix whose +leading eigenvalues coincide, and the t statistics of ``tstat_combine`` where +the subjects' correlations nearly coincide agree to about 1e-9 of their +magnitude. With ``include_zero=False`` the row is also unchanged when row ``t`` itself changes. The calls without ``causal=True`` are not changed by it. @@ -229,7 +234,7 @@ changes. The calls without ``causal=True`` are not changed by it. X, model = tc.features(x[:250], order=2, causal=True, cfun=tc.autofc, fit_timepoints=200, return_model=True, **kernels) later = model.transform(x) # all 300 rows, nothing fitted - # later[k][:250] equals X[k] to 1e-9; X[k][:2] is NaN (warm-up), X[2][:4] too + # later[k][:250] equals X[k] bit for bit; X[k][:2] is NaN (warm-up), X[2][:4] too # the reducers fitted again every 50 rows, each time on all rows before X, info = tc.features(x, order=2, causal=True, cfun=tc.autofc, rfun="PCA", diff --git a/docs/tutorial/causal.ipynb b/docs/tutorial/causal.ipynb index 24d3cdee..e5702ea3 100644 --- a/docs/tutorial/causal.ipynb +++ b/docs/tutorial/causal.ipynb @@ -28,10 +28,10 @@ "id": "causal-02", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:36.749760Z", - "iopub.status.busy": "2026-11-23T23:15:36.749495Z", - "iopub.status.idle": "2026-11-23T23:15:36.754285Z", - "shell.execute_reply": "2026-11-23T23:15:36.753831Z" + "iopub.execute_input": "2026-11-24T01:59:08.452595Z", + "iopub.status.busy": "2026-11-24T01:59:08.452495Z", + "iopub.status.idle": "2026-11-24T01:59:08.458374Z", + "shell.execute_reply": "2026-11-24T01:59:08.457390Z" } }, "outputs": [], @@ -51,10 +51,10 @@ "id": "causal-03", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:36.755556Z", - "iopub.status.busy": "2026-11-23T23:15:36.755480Z", - "iopub.status.idle": "2026-11-23T23:15:41.519461Z", - "shell.execute_reply": "2026-11-23T23:15:41.517707Z" + "iopub.execute_input": "2026-11-24T01:59:08.460481Z", + "iopub.status.busy": "2026-11-24T01:59:08.460358Z", + "iopub.status.idle": "2026-11-24T01:59:13.239503Z", + "shell.execute_reply": "2026-11-24T01:59:13.238857Z" } }, "outputs": [ @@ -104,10 +104,10 @@ "id": "causal-05", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:41.522727Z", - "iopub.status.busy": "2026-11-23T23:15:41.522554Z", - "iopub.status.idle": "2026-11-23T23:15:41.624230Z", - "shell.execute_reply": "2026-11-23T23:15:41.623170Z" + "iopub.execute_input": "2026-11-24T01:59:13.241296Z", + "iopub.status.busy": "2026-11-24T01:59:13.241131Z", + "iopub.status.idle": "2026-11-24T01:59:13.351752Z", + "shell.execute_reply": "2026-11-24T01:59:13.351323Z" } }, "outputs": [ @@ -145,10 +145,10 @@ "id": "causal-07", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:41.634370Z", - "iopub.status.busy": "2026-11-23T23:15:41.634234Z", - "iopub.status.idle": "2026-11-23T23:15:45.560156Z", - "shell.execute_reply": "2026-11-23T23:15:45.559000Z" + "iopub.execute_input": "2026-11-24T01:59:13.353645Z", + "iopub.status.busy": "2026-11-24T01:59:13.353537Z", + "iopub.status.idle": "2026-11-24T01:59:17.499316Z", + "shell.execute_reply": "2026-11-24T01:59:17.498685Z" } }, "outputs": [ @@ -197,10 +197,10 @@ "id": "causal-09", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:45.561729Z", - "iopub.status.busy": "2026-11-23T23:15:45.561635Z", - "iopub.status.idle": "2026-11-23T23:15:57.109160Z", - "shell.execute_reply": "2026-11-23T23:15:57.108239Z" + "iopub.execute_input": "2026-11-24T01:59:17.500705Z", + "iopub.status.busy": "2026-11-24T01:59:17.500610Z", + "iopub.status.idle": "2026-11-24T01:59:29.354896Z", + "shell.execute_reply": "2026-11-24T01:59:29.354269Z" } }, "outputs": [ @@ -208,7 +208,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "X[1], later days removed: largest change 3.6e-15 (largest value 17.2); rows equal: False\n", + "X[1], later days removed: largest change 0.0e+00 (largest value 17.2); rows equal: True\n", "X[2], later days removed: largest change 0.0e+00 (largest value 5.1); rows equal: True\n" ] }, @@ -236,7 +236,7 @@ "id": "causal-10", "metadata": {}, "source": [ - "What [`tc.features`](https://timecorr.readthedocs.io/en/latest/generated/timecorr.features.html) documents: a row at or after `fit_timepoints` is unchanged bit for bit when later rows are replaced, and to 1e-9 when they are removed. A row inside the training span depends on the training span and on nothing after it." + "What [`tc.features`](https://timecorr.readthedocs.io/en/latest/generated/timecorr.features.html) documents: a row at or after `fit_timepoints` is unchanged bit for bit when later rows are replaced or, with the built-in kernel functions, removed. A row inside the training span depends on the training span and on nothing after it." ] }, { @@ -255,10 +255,10 @@ "id": "causal-12", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:15:57.110546Z", - "iopub.status.busy": "2026-11-23T23:15:57.110441Z", - "iopub.status.idle": "2026-11-23T23:16:01.407813Z", - "shell.execute_reply": "2026-11-23T23:16:01.404911Z" + "iopub.execute_input": "2026-11-24T01:59:29.356898Z", + "iopub.status.busy": "2026-11-24T01:59:29.356783Z", + "iopub.status.idle": "2026-11-24T01:59:33.864572Z", + "shell.execute_reply": "2026-11-24T01:59:33.863737Z" } }, "outputs": [ @@ -304,10 +304,10 @@ "id": "causal-14", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:01.428565Z", - "iopub.status.busy": "2026-11-23T23:16:01.424908Z", - "iopub.status.idle": "2026-11-23T23:16:01.615506Z", - "shell.execute_reply": "2026-11-23T23:16:01.611263Z" + "iopub.execute_input": "2026-11-24T01:59:33.866330Z", + "iopub.status.busy": "2026-11-24T01:59:33.866229Z", + "iopub.status.idle": "2026-11-24T01:59:34.044772Z", + "shell.execute_reply": "2026-11-24T01:59:34.043868Z" } }, "outputs": [ @@ -355,10 +355,10 @@ "id": "causal-16", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:01.624383Z", - "iopub.status.busy": "2026-11-23T23:16:01.624270Z", - "iopub.status.idle": "2026-11-23T23:16:03.047688Z", - "shell.execute_reply": "2026-11-23T23:16:03.046752Z" + "iopub.execute_input": "2026-11-24T01:59:34.046336Z", + "iopub.status.busy": "2026-11-24T01:59:34.046232Z", + "iopub.status.idle": "2026-11-24T01:59:35.600857Z", + "shell.execute_reply": "2026-11-24T01:59:35.600122Z" } }, "outputs": [ @@ -421,10 +421,10 @@ "id": "causal-18", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:03.049475Z", - "iopub.status.busy": "2026-11-23T23:16:03.049380Z", - "iopub.status.idle": "2026-11-23T23:16:16.452089Z", - "shell.execute_reply": "2026-11-23T23:16:16.451270Z" + "iopub.execute_input": "2026-11-24T01:59:35.602781Z", + "iopub.status.busy": "2026-11-24T01:59:35.602666Z", + "iopub.status.idle": "2026-11-24T01:59:49.985049Z", + "shell.execute_reply": "2026-11-24T01:59:49.984629Z" } }, "outputs": [ @@ -490,10 +490,10 @@ "id": "causal-20", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:16.453447Z", - "iopub.status.busy": "2026-11-23T23:16:16.453360Z", - "iopub.status.idle": "2026-11-23T23:16:16.521946Z", - "shell.execute_reply": "2026-11-23T23:16:16.520277Z" + "iopub.execute_input": "2026-11-24T01:59:49.986643Z", + "iopub.status.busy": "2026-11-24T01:59:49.986536Z", + "iopub.status.idle": "2026-11-24T01:59:50.054978Z", + "shell.execute_reply": "2026-11-24T01:59:50.054451Z" } }, "outputs": [ @@ -556,10 +556,10 @@ "id": "causal-22", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:16.523450Z", - "iopub.status.busy": "2026-11-23T23:16:16.523358Z", - "iopub.status.idle": "2026-11-23T23:16:16.526143Z", - "shell.execute_reply": "2026-11-23T23:16:16.525711Z" + "iopub.execute_input": "2026-11-24T01:59:50.056334Z", + "iopub.status.busy": "2026-11-24T01:59:50.056244Z", + "iopub.status.idle": "2026-11-24T01:59:50.059266Z", + "shell.execute_reply": "2026-11-24T01:59:50.058545Z" } }, "outputs": [ @@ -608,10 +608,10 @@ "id": "causal-25", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:16.527467Z", - "iopub.status.busy": "2026-11-23T23:16:16.527395Z", - "iopub.status.idle": "2026-11-23T23:16:16.558246Z", - "shell.execute_reply": "2026-11-23T23:16:16.557546Z" + "iopub.execute_input": "2026-11-24T01:59:50.060649Z", + "iopub.status.busy": "2026-11-24T01:59:50.060573Z", + "iopub.status.idle": "2026-11-24T01:59:50.089414Z", + "shell.execute_reply": "2026-11-24T01:59:50.088840Z" }, "tags": [ "nbsphinx-thumbnail" @@ -649,10 +649,10 @@ "id": "causal-26", "metadata": { "execution": { - "iopub.execute_input": "2026-11-23T23:16:16.559576Z", - "iopub.status.busy": "2026-11-23T23:16:16.559471Z", - "iopub.status.idle": "2026-11-23T23:16:16.561359Z", - "shell.execute_reply": "2026-11-23T23:16:16.561051Z" + "iopub.execute_input": "2026-11-24T01:59:50.090685Z", + "iopub.status.busy": "2026-11-24T01:59:50.090603Z", + "iopub.status.idle": "2026-11-24T01:59:50.092672Z", + "shell.execute_reply": "2026-11-24T01:59:50.092175Z" } }, "outputs": [ @@ -660,7 +660,7 @@ "name": "stdout", "output_type": "stream", "text": [ - "notebook run time: 35 s\n" + "notebook run time: 37 s\n" ] } ], diff --git a/tests/fixtures/make_tstat_nonfinite_reference.py b/tests/fixtures/make_tstat_nonfinite_reference.py new file mode 100644 index 00000000..14772595 --- /dev/null +++ b/tests/fixtures/make_tstat_nonfinite_reference.py @@ -0,0 +1,34 @@ +"""Write ``tstat_nonfinite_reference.npz``: what ``tstat_combine`` returns +(t and p) for every list of ``nonfinite_inputs`` in +``tests/test_round_off_variance.py``, the lists of 2 and 3 values with at +least one infinite or NaN value. + +Run from the repository root, with the timecorr package of the commit whose +outputs are to be frozen first on the import path (for example +``PYTHONPATH= python +tests/fixtures/make_tstat_nonfinite_reference.py``). The file was written +with the package at commit 589c2a1 (release 0.3.1's ``tstat_combine``). +""" + +import os +import sys +import warnings + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(1, os.path.dirname(HERE)) + +import timecorr # noqa: E402 +from test_round_off_variance import nonfinite_inputs # noqa: E402 + +if __name__ == "__main__": + print(f"timecorr from {os.path.dirname(timecorr.__file__)}") + out = {} + for size, values in nonfinite_inputs().items(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + t, p = timecorr.tstat_combine([column[np.newaxis] for column in values.T], + return_pvals=True) + out[f"t{size}"], out[f"p{size}"] = t[0], p[0] + np.savez(os.path.join(HERE, "tstat_nonfinite_reference.npz"), **out) diff --git a/tests/fixtures/tstat_nonfinite_reference.npz b/tests/fixtures/tstat_nonfinite_reference.npz new file mode 100644 index 00000000..dc707ba5 Binary files /dev/null and b/tests/fixtures/tstat_nonfinite_reference.npz differ diff --git a/tests/test_causal_estimator.py b/tests/test_causal_estimator.py index 1927025f..c71c06af 100644 --- a/tests/test_causal_estimator.py +++ b/tests/test_causal_estimator.py @@ -1393,8 +1393,9 @@ def test_smoothing_ignores_the_reducer_as_without_causal(): def test_tstat_combine_is_exact_under_replacement_and_conditioned_under_removal(): - # the reviewer's input: two subjects, whose isfc correlations are the - # same, so every t statistic divides round-off by a spread near zero + # the reviewer's input: two subjects with different events, whose isfc + # correlations differ by about 1e-8, so every t statistic is very + # sensitive to the last bit of a correlation rng = np.random.RandomState(4) xs = [rng.randn(70, 4) for _ in range(2)] xs[0][48, 1] = np.inf @@ -1411,8 +1412,8 @@ def test_tstat_combine_is_exact_under_replacement_and_conditioned_under_removal( assert np.array_equal(np.isnan(cut), np.isnan(full[:51])) finite = np.isfinite(cut) & np.isfinite(full[:51]) assert np.array_equal(np.isfinite(cut), np.isfinite(full[:51])) - # not required to 1e-9 (the documented exception; 0.12 on 3.8e7 was - # measured on macOS, 0 on Linux), but to 1e-8 of the magnitude + # 0.12 on 3.8e7 was measured here on macOS before removal changed no + # bit (test_tstat_combine_is_exact_under_removal requires equality); this bound stays difference = np.abs(cut[finite] - full[:51][finite]) assert np.max(difference / np.maximum(1.0, np.abs(cut[finite]))) <= 1e-8 # subjects whose correlations differ: to 1e-9 of the magnitude, and @@ -1438,3 +1439,307 @@ def test_tstat_combine_is_exact_under_replacement_and_conditioned_under_removal( doc = " ".join(getattr(tc, name).__doc__.split()) assert "the t statistics of ``tstat_combine``" in doc assert "to about 1e-9 of their magnitude" in doc + + +# ---------------------------------------------------------------------------- +# removal changes no bit: the estimator computes a row with the same +# operations whatever the length of the series +# ---------------------------------------------------------------------------- + + +def _removal_data(n_subjects, T, K, seed=0, missing=False): + rng = np.random.default_rng(100 + seed) + data = [np.cumsum(rng.standard_normal((T, K)), axis=0) * 0.1 + + rng.standard_normal((T, K)) for _ in range(n_subjects)] + if missing: + for x in data: + x[rng.random(x.shape) < 0.02] = np.nan + x[rng.integers(5, T, 3)] = np.nan # timepoints without a sample + x[rng.integers(5, T), 0] = np.inf + x[rng.integers(5, T), 1] = -1e200 + return data + + +def _cuts(T, near=(16, 128)): + """Lengths at, just before and just after multiples of the group and + chunk sizes, and a few others.""" + cuts = set(range(1, 8)) | {T - 1} + for m in near: + for k in range(m, T, m if m > 16 else 48): + cuts |= {k - 1, k, k + 1} + cuts |= set(range(23, T, 37)) + return sorted(c for c in cuts if 1 <= c < T) + + +def _identical_under_removal(run, data, cuts): + """The cuts at which the rows of the shorter series are not, bit for + bit, the first rows of the whole one (``run``: data -> array or list).""" + full = _as_list(run(data)) + changed = [] + for n in cuts: + out = _as_list(run([x[:n] for x in data])) + if not all(np.array_equal(o, f[:n], equal_nan=True) for o, f in zip(out, full)): + changed.append(n) + return changed + + +def _timecorr_runner(n_subjects, **kwargs): + def run(data): + return _quiet(tc.timecorr, data[0] if n_subjects == 1 else data, + causal=True, **kwargs) + return run + + +G25 = {"weights_params": {"var": 25}} +# name: (subjects, T, K, missing samples, arguments of timecorr) +REMOVAL = { + "autofc": (1, 300, 6, False, dict(cfun=tc.autofc, **G25)), + "autofc-missing": (1, 300, 6, True, dict(cfun=tc.autofc, **G25)), + "isfc": (3, 300, 5, False, dict(cfun=tc.isfc, **G25)), + "isfc-missing": (3, 300, 5, True, dict(cfun=tc.isfc, **G25)), + "isfc-corrmean": (3, 300, 5, True, dict(cfun=tc.isfc, combine=tc.corrmean_combine, + **G25)), + "isfc-tstat": (3, 300, 5, False, dict(cfun=tc.isfc, combine=tc.tstat_combine, + **G25)), + "wisfc": (3, 300, 5, True, dict( + cfun=functools.partial(tc.wisfc, subject_weights=SUBJECT_WEIGHTS), **G25)), + "events": (1, 300, 5, False, dict(cfun=tc.autofc, events=[40, 128, 131, 200], **G25)), + "events-per-subject": (3, 300, 4, True, dict( + cfun=tc.isfc, events=[[20, 160], [25, 129, 265], None], **G25)), + "min-samples": (1, 300, 5, True, dict(cfun=tc.autofc, min_samples=8, **G25)), + "exclude-zero": (1, 300, 5, False, dict(cfun=tc.autofc, include_zero=False, **G25)), + "exclude-near": (1, 300, 5, False, dict(cfun=tc.autofc, exclude_timepoints=-3, + **G25)), + "exclude-far": (1, 300, 5, True, dict(cfun=tc.autofc, exclude_timepoints=20, **G25)), + "strength": (1, 300, 6, True, dict(cfun=tc.autofc, rfun="strength", **G25)), + "laplace": (1, 300, 5, True, dict(cfun=tc.autofc, weights_function=tc.laplace_weights, + weights_params={"scale": 6})), + "t": (1, 300, 5, False, dict(cfun=tc.autofc, weights_function=tc.t_weights, + weights_params={"df": 3})), + "mexican-hat": (1, 300, 5, True, dict( + cfun=tc.autofc, weights_function=tc.mexican_hat_weights, + weights_params={"sigma": 5})), + "mexican-hat-events": (1, 300, 5, False, dict( + cfun=tc.autofc, weights_function=tc.mexican_hat_weights, + weights_params={"sigma": 5}, events=[123, 251])), + "boxcar": (1, 300, 5, True, dict(cfun=tc.autofc, weights_function=tc.boxcar_weights, + weights_params={"width": 21})), + "uniform": (1, 300, 5, False, dict(cfun=tc.autofc, weights_function=tc.uniform_weights, + weights_params={})), + # more than 8 features (the triangle of an autocorrelation is computed 8 + # rows of features at a time) + "autofc-30": (1, 200, 30, True, dict(cfun=tc.autofc, **G25)), +} + + +@pytest.mark.parametrize("case", sorted(REMOVAL)) +def test_removing_later_rows_changes_no_bit(case): + n_subjects, T, K, missing, kw = REMOVAL[case] + data = _removal_data(n_subjects, T, K, missing=missing) + cuts = _cuts(T) if case in ("autofc", "isfc-missing", "events-per-subject", + "mexican-hat-events") else _cuts(T)[::3] + assert _identical_under_removal(_timecorr_runner(n_subjects, **kw), data, cuts) == [] + + +# kernels with weight at more than 512 lags: larger groups of rows +WIDE = { + "laplace": dict(weights_function=tc.laplace_weights, weights_params={"scale": 40}), + "gaussian": dict(weights_params={"var": 150.0 ** 2}), + "boxcar-1000": dict(weights_function=tc.boxcar_weights, weights_params={"width": 1000}), + "boxcar-1100": dict(weights_function=tc.boxcar_weights, weights_params={"width": 1100}), + "uniform": dict(weights_function=tc.uniform_weights, weights_params={}), +} + + +@pytest.mark.parametrize("kernel", sorted(WIDE)) +def test_removing_later_rows_changes_no_bit_with_wide_kernels(kernel): + data = _removal_data(1, 1300, 4, missing=kernel == "laplace") + cuts = [n for m in (496, 512, 544, 640, 1024, 1056, 1152, 1280) + for n in (m - 17, m - 1, m, m + 1, m + 15)] + run = _timecorr_runner(1, cfun=tc.autofc, **WIDE[kernel]) + assert _identical_under_removal(run, data, cuts) == [] + + +def test_every_length_from_one_row_is_the_start_of_the_whole_series(): + data = _removal_data(2, 70, 4, missing=True) + for kw in (dict(cfun=tc.isfc, **G25), dict(cfun=tc.autofc, **G25), + dict(cfun=tc.autofc, combine=tc.mean_combine, **G25)): + assert _identical_under_removal(_timecorr_runner(2, **kw), data, + range(1, 70)) == [] + + +def test_removal_changes_no_bit_whatever_the_blocks_of_features(): + # T * K * K above the estimator's block: the features are computed in + # blocks whose size follows from T + from timecorr import helpers + + T, K = 420, 150 + assert helpers._wcorr_block_rows(T, K) < K + assert helpers._wcorr_block_rows(160, K) != helpers._wcorr_block_rows(T, K) + data = _removal_data(2, T, K, missing=True) + for n_subjects, kw in ((1, dict(cfun=tc.autofc, **G25)), (2, dict(cfun=tc.isfc, **G25))): + run = _timecorr_runner(n_subjects, **kw) + assert _identical_under_removal(run, data[:n_subjects], [129, 160, 331]) == [] + + +def test_wcorr_and_the_correlation_functions_are_exact_under_removal(): + data = _removal_data(2, 200, 5, missing=True) + a, b = data + cuts = _cuts(200)[::4] + + def kernel(n): + return tc.gaussian_weights(n, {"var": 25}, direction="backward") + + for min_samples in (None, 6): + full = _quiet(tc.wcorr, a, b, kernel(200), causal=True, min_samples=min_samples) + auto = _quiet(tc.autofc, a, kernel(200), causal=True, min_samples=min_samples) + inter = _quiet(tc.isfc, data, kernel(200), causal=True, min_samples=min_samples) + for n in cuts: + assert np.array_equal( + _quiet(tc.wcorr, a[:n], b[:n], kernel(n), causal=True, + min_samples=min_samples), + full[:, :, :n], equal_nan=True) + assert np.array_equal( + _quiet(tc.autofc, a[:n], kernel(n), causal=True, min_samples=min_samples), + auto[:n], equal_nan=True) + cut = _quiet(tc.isfc, [x[:n] for x in data], kernel(n), causal=True, + min_samples=min_samples) + assert all(np.array_equal(c, f[:n], equal_nan=True) + for c, f in zip(cut, inter)) + + +def test_tstat_combine_is_exact_under_removal(): + # the whole-branch review's input: a statistic of 3.8e7 that changed by + # 0.12 when the rows after row 50 were removed + rng = np.random.RandomState(4) + xs = [rng.randn(70, 4) for _ in range(2)] + xs[0][48, 1] = np.inf + run = _timecorr_runner(2, cfun=tc.isfc, combine=tc.tstat_combine, min_samples=3, + events=[[20, 60], [25, 65]], **G25) + full = run(xs) + assert np.nanmax(np.abs(full[np.isfinite(full)])) > 1e7 + assert _identical_under_removal(run, xs, range(1, 70)) == [] + # a spread across subjects that is tiny and real: subject 1 is subject 0 + # plus noise of 1e-9 + rng = np.random.RandomState(5) + base = rng.randn(120, 4) + ys = [base, base + 1e-9 * rng.randn(120, 4)] + run = _timecorr_runner(2, cfun=tc.autofc, combine=tc.tstat_combine, **G25) + full = run(ys) + assert np.nanmax(np.abs(full[np.isfinite(full)])) > 1e9 + assert _identical_under_removal(run, ys, _cuts(120)) == [] + + +def test_the_columns_of_a_group_do_not_depend_on_later_rows(): + # a Mexican hat is exactly 0 at lag sigma: with an event sigma rows + # before a chunk of 128 rows, the chunk's first row has no weight at the + # event's first timepoint and its second row has, so the columns of the + # chunk, found from its weights, depended on whether that row exists + from timecorr import helpers + + assert helpers.mexican_hat_profile(np.arange(8), {"sigma": 5})[5] == 0 + + def groups(T): + kernel = helpers._lag_kernel(T, tc.mexican_hat_weights, {"sigma": 5}, + "backward", True, None) + kernel = kernel.with_events((np.arange(T) >= 123).astype(int)) + rows = helpers._KernelRows(kernel) + rows.prepare(True, always=True) + return {g[1]: g for g in helpers._causal_groups(rows)} + + whole = groups(140) + for T in (129, 130, 131): + cut = groups(T) + assert cut[128][3] == whole[128][3] == 123 # c0: the event's first row + assert (cut[128][4], cut[128][5]) == (whole[128][4], whole[128][5]) == (144, 16) + # the shapes of every group, for cuts of an ordinary kernel + for T in (17, 129, 200, 513, 700): + for width in (25, 400 ** 2): + def shapes(n): + kernel = helpers._lag_kernel(n, tc.gaussian_weights, {"var": width}, + "backward", True, None) + rows = helpers._KernelRows(kernel) + rows.prepare(True, always=True) + return {g[1]: g[3:] for g in helpers._causal_groups(rows)} + long, short = shapes(1400), shapes(T) + assert short and all(long[g0] == s for g0, s in short.items()) + + +SMOOTH = { + "gaussian": G25, + "gaussian-wide": {"weights_params": {"var": 150.0 ** 2}}, + "laplace": dict(weights_function=tc.laplace_weights, weights_params={"scale": 6}), + "mexican-hat": dict(weights_function=tc.mexican_hat_weights, + weights_params={"sigma": 5}), + "boxcar": dict(weights_function=tc.boxcar_weights, weights_params={"width": 21}), + "uniform": dict(weights_function=tc.uniform_weights, weights_params={}), + "events": dict(events=[40, 128, 131, 200], **G25), + "min-samples": dict(min_samples=8, **G25), + "exclude-zero": dict(include_zero=False, **G25), +} + + +@pytest.mark.parametrize("case", sorted(SMOOTH)) +def test_removing_later_rows_changes_no_bit_of_smoothed_values(case): + for missing in (False, True): + data = _removal_data(2, 300, 5, missing=missing) + for x in data: + x += 1e6 # a level far above the variation + run = _timecorr_runner(2, cfun=None, **SMOOTH[case]) + assert _identical_under_removal(run, data, _cuts(300)[::2]) == [] + + +# ---------------------------------------------------------------------------- +# review of the exact-removal branch: min_samples at an effective size that +# occurs +# ---------------------------------------------------------------------------- + + +def test_min_samples_at_an_effective_size_that_occurs_is_exact_under_removal(): + # the reviewer's input: the effective size of row 8 was summed over the + # columns of the series (7.937065553951692 with 17 rows, + # 7.937065553951693 with 15), so the row was NaN in one and finite in + # the other + x = np.random.default_rng(0).normal(size=(17, 3)) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, + min_samples=7.93706555395963) + whole = _quiet(tc.timecorr, x, **kw) + part = _quiet(tc.timecorr, x[:15], **kw) + assert np.array_equal(whole[:15], part, equal_nan=True) + + +@pytest.mark.parametrize("cfun", [tc.autofc, None], ids=["autofc", "smoothing"]) +def test_every_occurring_effective_size_as_min_samples(cfun): + # min_samples at, just below and just above the effective sizes that + # the kernel rows have, with and without missing samples + from timecorr import helpers + + rng = np.random.default_rng(5) + changed = [] + for T, cut in ((17, 15), (40, 33), (150, 129), (300, 257)): + x = rng.normal(size=(T, 3)) + kernels = (dict(weights_params={"var": 25}), + dict(weights_function=tc.laplace_weights, weights_params={"scale": 4}), + dict(weights_function=tc.t_weights, weights_params={"df": 3})) + for kernel in kernels: + for missing in (False, True): + data = x.copy() + if missing: + data[rng.random(data.shape) < 0.05] = np.nan + lag = helpers._lag_kernel(cut, kernel.get("weights_function", + tc.gaussian_weights), + kernel["weights_params"], "backward", True, None) + sizes = np.unique(helpers._kernel_samples(lag)[1]) + sizes = sizes[sizes > 3][:: max(1, sizes.size // 12)] + for size in sizes: + for m in (np.nextafter(size, 0), size, np.nextafter(size, np.inf), + size * (1 + 1e-12), size * (1 - 1e-12)): + kw = dict(causal=True, cfun=cfun, min_samples=float(m), **kernel) + try: + whole = _quiet(tc.timecorr, data, **kw) + except ValueError: # no row reaches it + continue + part = _quiet(tc.timecorr, data[:cut], **kw) + if not np.array_equal(whole[:cut], part, equal_nan=True): + changed.append((T, cut, missing, m)) + assert changed == [] diff --git a/tests/test_causal_features.py b/tests/test_causal_features.py index 41e9d106..2c16f06b 100644 --- a/tests/test_causal_features.py +++ b/tests/test_causal_features.py @@ -856,3 +856,69 @@ def my_cfun(data, weights): warnings.simplefilter("always") f(data, **{**kw, "combine": combine}) assert not [c for c in caught if "guarantee" in str(c.message)] + + +# ---------------------------------------------------------------------------- +# removal changes no bit of the correlations, so none of what is computed +# from them row by row +# ---------------------------------------------------------------------------- + + +def _modules(n_subjects, T, K, seed=0): + rng = np.random.default_rng(100 + seed) + shared = np.repeat(rng.standard_normal((T, K // 3 + 1)), 3, axis=1)[:, :K] + data = [shared + 0.7 * rng.standard_normal((T, K)) for _ in range(n_subjects)] + for x in data: + x[rng.random(x.shape) < 0.01] = np.nan + return data + + +def _outputs(result): + """The arrays of every order of a ``features`` result (with + ``return_delta``: of both lists), without the data.""" + out = [] + for by_order in (result if isinstance(result, tuple) else (result,)): + for value in by_order[1:]: + if value is not None: + out += value if isinstance(value, list) else [value] + return out + + +def _first_rows_identical(whole, part, n): + return all(np.array_equal(a[:n], b, equal_nan=True) + for a, b in zip(_outputs(whole), _outputs(part))) + + +EXACT_REMOVAL = { + "unreduced": (1, 12, dict(order=2, cfun=tc.autofc, rfun=None, delta_rfun=None)), + "strength": (1, 12, dict(order=3, cfun=tc.autofc, rfun="strength", + delta_rfun="strength")), + "eigenvector": (1, 12, dict(order=2, cfun=tc.autofc, rfun="eigenvector_centrality", + delta_rfun="strength")), + "pagerank": (1, 12, dict(order=2, cfun=tc.autofc, rfun="pagerank_centrality", + delta_rfun="strength")), + "pagerank-abs": (1, 12, dict(order=2, cfun=tc.autofc, + rfun="pagerank_centrality_abs", delta_rfun="strength")), + "isfc": (3, 9, dict(order=2, rfun="strength", delta_rfun="strength")), + "isfc-corrmean": (3, 9, dict(order=2, rfun="strength", delta_rfun="strength", + combine=tc.corrmean_combine)), + "isfc-tstat": (3, 9, dict(order=2, rfun="strength", delta_rfun="strength", + combine=tc.tstat_combine)), + "wisfc": (3, 9, dict(order=2, rfun="strength", delta_rfun="strength", cfun=WISFC)), + "smoothing": (1, 12, dict(order=2, cfun=None, rfun=None, delta_rfun=None)), +} +REMOVAL_CUTS = (17, 65, 129, 160, 161, 255, 256, 257, 329) + + +@pytest.mark.parametrize("case", sorted(EXACT_REMOVAL)) +def test_features_without_a_fit_are_exact_under_removal(case): + n_subjects, K, kw = EXACT_REMOVAL[case] + data = _modules(n_subjects, 330, K) + + def run(d): + return _quiet(tc.features, d[0] if n_subjects == 1 else d, causal=True, + return_delta=True, **PARAMS, **kw) + + whole = run(data) + for n in REMOVAL_CUTS: + assert _first_rows_identical(whole, run([x[:n] for x in data]), n), n diff --git a/tests/test_causal_fit.py b/tests/test_causal_fit.py index 30282ba9..0571b7d6 100644 --- a/tests/test_causal_fit.py +++ b/tests/test_causal_fit.py @@ -19,6 +19,8 @@ import warnings import hypertools as hyp +import functools + import numpy as np import pytest @@ -1247,3 +1249,450 @@ def test_every_reducer_takes_a_partly_nan_row_as_undefined(name): reduced = _apply_frozen(smooth, frozen) assert np.array_equal(np.isnan(reduced).all(axis=1), partial) assert not np.isnan(reduced[~partial]).any() + + +# ---------------------------------------------------------------------------- +# removal changes no bit of the correlations; with reducers fitted on the +# first rows, none of the features either in the cases below +# ---------------------------------------------------------------------------- + +_FITTED_REMOVAL = { + "auto": (1, 12, dict(order=3, cfun=tc.autofc)), + "auto-isfc": (3, 12, dict(order=2)), + "pca": (1, 12, dict(order=3, cfun=tc.autofc, rfun="PCA", delta_rfun="PCA")), + "pca-isfc": (3, 9, dict(order=2, rfun="PCA", delta_rfun="PCA", ndims=3)), + "strength": (1, 12, dict(order=3, cfun=tc.autofc, + rfun=tc.WeightedStrength(signed=True), + delta_rfun="weighted_strength")), + "communities": (1, 12, dict(order=2, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun={1: tc.Communities(n=4), + 2: "weighted_strength"})), + "ica": (1, 9, dict(order=2, cfun=tc.autofc, rfun={"model": "FastICA"}, + delta_rfun="weighted_strength")), + "factor-analysis": (1, 9, dict(order=2, cfun=tc.autofc, rfun="FactorAnalysis", + delta_rfun="weighted_strength")), + "truncated-svd": (1, 9, dict(order=2, cfun=tc.autofc, rfun="TruncatedSVD", + delta_rfun="weighted_strength")), + "incremental-pca": (1, 9, dict(order=2, cfun=tc.autofc, rfun="IncrementalPCA", + delta_rfun="weighted_strength")), + # a streamed step with more nodes than a block of the estimator + "streamed-60": (1, 60, dict(order=1, cfun=tc.autofc, rfun="weighted_strength", + delta_rfun=None)), +} + + +@pytest.mark.parametrize("case", sorted(_FITTED_REMOVAL)) +def test_fitted_features_are_exact_under_removal(case): + from .test_causal_features import _first_rows_identical, _modules + + n_subjects, K, kw = _FITTED_REMOVAL[case] + data = _modules(n_subjects, 330, K) + kw = dict(causal=True, fit_timepoints=150, return_delta=True, **PARAMS, **kw) + + def take(d): + return d[0] if n_subjects == 1 else d + + whole, model = _quiet(tc.features, take(data), return_model=True, **kw) + for n in (150, 151, 160, 161, 200, 255, 256, 257, 329): + part = [x[:n] for x in data] + assert _first_rows_identical(whole, _quiet(tc.features, take(part), **kw), n), n + # the model of the whole series, applied to the shorter one + applied = _quiet(model.transform, take(part), return_delta=True) + assert _first_rows_identical(whole, applied, n), n + + +def test_refits_are_exact_under_removal(): + from .test_causal_features import _first_rows_identical, _modules + + data = _modules(1, 330, 12)[0] + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="PCA", + delta_rfun="weighted_strength", fit_timepoints=150, refit_every=40, + return_delta=True, **PARAMS) + whole = _quiet(tc.features, data, **kw) + for n in (151, 190, 191, 230, 256, 271, 329): + assert _first_rows_identical(whole, _quiet(tc.features, data[:n], **kw), n), n + + +# ---------------------------------------------------------------------------- +# review of the exact-removal branch: nothing depends on the blocks of +# features of a streamed step, which depend on T and max_memory_gb +# ---------------------------------------------------------------------------- + + +def _review_input(): + x = np.random.default_rng(123).normal(size=(259, 17)) + x[50, 3] = np.nan + common = dict(causal=True, cfun=tc.autofc, fit_timepoints=40, + weights_params={"var": 25}, delta_weights_params={"var": 9}) + return x, common + + +def test_streamed_rows_do_not_depend_on_the_block_of_features(): + from timecorr.helpers import _corr_row_blocks, _lag_kernel + + x, _ = _review_input() + kernel = _lag_kernel(len(x), tc.gaussian_weights, {"var": 25}, "backward", True, None) + + def rows(step): + return np.concatenate([R for _, _, R, _, _ in _corr_row_blocks( + x, x, kernel, True, step, causal=True)]) + + whole = rows(17) + for step in (1, 3, 8, 16): + assert np.array_equal(whole, rows(step), equal_nan=True), step + # the diagonal is 1 where defined, and the two orientations of a pair + # agree to round-off + defined = ~np.isnan(whole[0, 0]) + assert (whole[np.arange(17), np.arange(17)][:, defined] == 1).all() + assert np.nanmax(np.abs(whole - whole.transpose(1, 0, 2))) < 1e-12 + + +@pytest.mark.parametrize("order", [1, 2]) +def test_streamed_summaries_are_exact_under_removal_and_max_memory(order): + from .test_causal_features import _first_rows_identical + + x, common = _review_input() + kw = dict(order=order, rfun="weighted_strength", delta_rfun="weighted_strength", + return_delta=True, **common) + whole, model = _quiet(tc.features, x, max_memory_gb=0.01, return_model=True, **kw) + # the reviewer's cut, and others + for n in (63, 41, 64, 127, 129, 200, 258): + part = _quiet(tc.features, x[:n], max_memory_gb=0.01, **kw) + assert _first_rows_identical(whole, part, n), n + assert _first_rows_identical(whole, _quiet(model.transform, x[:n], + return_delta=True), n), n + for memory in (None, 0.006, 0.008, 0.02, 0.05, 1.0): + other = _quiet(tc.features, x, max_memory_gb=memory, **kw) + assert _first_rows_identical(whole, other, len(x)), memory + + +def test_a_frozen_model_reduces_a_row_whatever_the_number_of_rows(): + from timecorr.helpers import _model_reduce + + import hypertools as hyp + + rng = np.random.default_rng(0) + for columns, ndims in ((136, 3), (153, 3), (21, 5), (45, 9)): + rows = rng.normal(size=(300, columns)) + _, fitted = _model_reduce([rows[:40]], "PCA", ndims, return_model=True) + # one product of all rows differed with the number of rows on macOS + # (Accelerate; not with OpenBLAS): at 9 to 11 rows of 153 columns, + # at 59 of the 299 lengths of 21 columns + together = np.asarray(hyp.reduce(rows, reduce=fitted.model)) + whole = fitted.apply([rows])[0] + assert np.allclose(whole, together, rtol=0, atol=1e-12) + for n in list(range(1, 14)) + [41, 127, 128, 129, 255, 256, 257, 299]: + assert np.array_equal(fitted.apply([rows[:n]])[0], whole[:n]), n + # and whatever the other arrays of the list + both = fitted.apply([rows[:127], rows[100:]]) + assert np.array_equal(both[0], whole[:127]) + assert fitted.apply([rows[:0]])[0].shape == (0, ndims) + + +def test_refitted_models_are_exact_under_removal(): + # the reviewer's input: [2][126, 2] was 0.15126289987033542 with 259 + # rows and 0.15126289987033548 with 127 + from .test_causal_features import _first_rows_identical + + x, common = _review_input() + kw = dict(order=3, rfun="PCA", delta_rfun="PCA", ndims=3, refit_every=40, + return_delta=True, **common) + whole = _quiet(tc.features, x, **kw) + for n in (127, 81, 120, 121, 128, 200, 201, 258): + assert _first_rows_identical(whole, _quiet(tc.features, x[:n], **kw), n), n + + +WISFC_2 = functools.partial(tc.wisfc, subject_weights=np.ones((2, 2)) - np.eye(2)) + +_STREAMED = { + "strength": (1, 30, dict(cfun=tc.autofc, rfun="weighted_strength", + delta_rfun="weighted_strength")), + "strength-split-signed": (1, 30, dict( + cfun=tc.autofc, rfun=tc.WeightedStrength(signed=True, split=True), + delta_rfun=tc.WeightedStrength(split=True))), + "communities": (1, 30, dict( + cfun=tc.autofc, rfun={1: tc.Communities(n=4, signed=True), 2: "weighted_strength"}, + delta_rfun={1: tc.Communities(n=5), 2: "weighted_strength"})), + "auto": (1, 30, dict(cfun=tc.autofc)), + "isfc": (3, 24, dict(rfun="weighted_strength", delta_rfun="weighted_strength")), + "isfc-auto": (3, 24, dict()), + "wisfc-communities": (3, 24, dict( + cfun=WISFC, rfun={1: tc.Communities(n=4), 2: "weighted_strength"}, + delta_rfun="weighted_strength")), +} + + +@pytest.mark.parametrize("case", sorted(_STREAMED)) +def test_streamed_steps_do_not_depend_on_the_memory_limit(case): + # the blocks of nodes of a streamed step follow from max_memory_gb and + # T (30 nodes: blocks of 4 to 30 with these limits) + from .test_causal_features import _first_rows_identical, _modules + + n_subjects, K, kw = _STREAMED[case] + data = _modules(n_subjects, 200, K, seed=3) + kw = dict(order=2, causal=True, fit_timepoints=80, return_delta=True, + weights_params={"var": 25}, delta_weights_params={"var": 9}, **kw) + + def run(d, memory): + return _quiet(tc.features, d[0] if n_subjects == 1 else d, + max_memory_gb=memory, **kw) + + whole = run(data, None) + for memory in (0.02, 0.03, 0.05, 0.1): + assert _first_rows_identical(whole, run(data, memory), 200), memory + for n in (81, 127, 129, 160, 199): + assert _first_rows_identical(whole, run([x[:n] for x in data], 0.05), n), n + + +# ---------------------------------------------------------------------------- +# FastICA and the constant columns of vectorized correlations +# ---------------------------------------------------------------------------- + + +def test_fastica_is_fitted_with_a_varying_first_column(): + # scikit-learn's FastICA multiplies each whitening vector by the sign of + # its loading on the first feature. The first column of vectorized + # autocorrelations is a diagonal entry, 1 in every row: its loading is 0 + # up to the round-off of the SVD, and where it is exactly 0 the + # component is multiplied by 0 and the fit holds NaN ("A has a NaN + # entry"; 136 of 240 of these calls on macOS, and + # test_linear_models_are_taken_and_guaranteed[FastICA] on Linux) + kernels = dict(weights_params={"var": 25}, delta_weights_params={"var": 16}) + for seed in range(20): + for K, ndims in ((2, 1), (3, 2), (4, 3), (5, 3)): + x = np.random.default_rng(seed).standard_normal((120, K)) + kw = dict(order=2, causal=True, cfun=tc.autofc, rfun="FastICA", + delta_rfun="FastICA", ndims=ndims, fit_timepoints=80, + return_delta=True, **kernels) + # (ndims 1: order 2 has one feature, whose correlations are one + # constant column, returned as it is) + (X, D), model = _quiet(tc.features, x, return_model=True, **kw) + for out in X[1:] + D[1:]: + assert out.shape == (120, ndims) + defined = ~np.isnan(out).any(axis=1) + assert defined[20:].all() and np.isfinite(out[defined]).all() + # the model applied to other rows, and to the rows of the fit + again = _quiet(model.transform, x[:100], return_delta=True) + assert all(np.array_equal(a[:100], b, equal_nan=True) + for a, b in zip(X[1:] + D[1:], again[0][1:] + again[1][1:])) + # the fitted model itself: its components are in the order of the + # columns given, and it reduces the rows of the fit to what the fit gave + from timecorr.helpers import _model_reduce + + rng = np.random.default_rng(2) + rows = np.tanh(rng.standard_normal((126, 3))) + rows[:, [0, 2]] = 1.0 + reduced, fitted = _quiet(_model_reduce, [rows], "FastICA", 1, return_model=True) + assert list(fitted.order) == [1, 0, 2] + assert fitted.components.shape == (1, 3) and fitted.components[0, 1] != 0 + assert np.allclose(fitted.components[0, [0, 2]], 0, atol=1e-12) + assert np.allclose(fitted.apply([rows])[0], reduced[0], rtol=0, atol=1e-9) + # other models, and FastICA with a first column that varies, as before + assert _quiet(_model_reduce, [rows], "PCA", 1, return_model=True)[1].order is None + assert _quiet(_model_reduce, [rows[:, ::-1][:, [1, 0, 2]]], "FastICA", 1, + return_model=True)[1].order is None + + +def test_fastica_asked_for_every_column_changes_nothing(): + # review: a model asked for at least as many components as columns + # returns the columns as they are; the FastICA handling of constant + # columns came before that and fitted one component with zero columns + from timecorr.helpers import _model_reduce + + rows = np.column_stack([np.ones(40), np.random.default_rng(2).normal(size=40), + np.ones(40)]) + reduced, fitted = _quiet(_model_reduce, [rows], "FastICA", 3, return_model=True) + assert fitted.model is None and fitted.order is None and fitted.pad == 0 + assert np.array_equal(reduced[0], rows) + for K in (1, 2): + x = np.random.default_rng(K).standard_normal((120, K)) + kw = dict(order=1, causal=True, cfun=tc.autofc, delta_rfun=None, + weights_params={"var": 25}, delta_weights_params={"var": 16}) + plain = _quiet(tc.features, x, rfun=None, **kw)[1] + for ndims in (3, 5): + out = _quiet(tc.features, x, rfun="FastICA", ndims=ndims, fit_timepoints=80, + **kw)[1] + assert out.shape == (120, ndims) + assert np.array_equal(out[:, :plain.shape[1]], plain, equal_nan=True) + defined = ~np.isnan(plain).any(axis=1) + assert (out[defined][:, plain.shape[1]:] == 0).all() + + +def test_fastica_given_as_a_class_or_an_object_is_fastica(): + # review: only the name was recognized; the class still raised "array + # must not contain infs or NaNs" + from sklearn.decomposition import FastICA + + x = np.random.default_rng(0).normal(size=(120, 2)) + kw = dict(causal=True, cfun=tc.autofc, weights_params={"var": 25}, fit_timepoints=80) + named = _quiet(tc.timecorr, x, rfun="FastICA", **kw) + assert named.shape == (120, 2) and np.isfinite(named[10:]).all() + forms = [{"model": FastICA}, {"model": "FastICA"}, {"model": "FastICA", "kwargs": {}}, + {"model": FastICA, "kwargs": {"max_iter": 300}}, + {"model": FastICA(random_state=0)}] + for rfun in forms: + out = _quiet(tc.timecorr, x, rfun=rfun, **kw) + assert np.isfinite(out[10:]).all(), rfun + assert np.allclose(np.abs(out[10:]), np.abs(named[10:]), rtol=0, atol=1e-6), rfun + + +def test_fastica_without_a_varying_column_says_so(): + from timecorr.helpers import _model_reduce + + rows = np.ones((40, 3)) + with pytest.raises(ValueError, match="no column of its input varies"): + _quiet(_model_reduce, [rows], "FastICA", 2, return_model=True) + + +def test_fastica_with_fewer_training_rows_than_components(): + # review (a draw of the random removal test that was discarded): 9 + # defined training rows have rank 8 once centered; FastICA asked for 9 + # components divides by a singular value of 0, and the fit did not + # reproduce its rows (by 0.363). It gets rows - 1 components. + rng = np.random.default_rng(65) + data = [rng.standard_normal((60, 15)) for _ in range(2)] + kw = dict(causal=True, cfun=tc.autofc, combine=tc.mean_combine, rfun="FastICA", + weights_function=tc.uniform_weights, weights_params={}, fit_timepoints=11) + import warnings + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + whole = tc.timecorr(data, **kw) + assert any("at most 8 components" in str(w.message) for w in caught) + assert whole.shape == (60, 15) + assert np.isnan(whole[:2]).all() and np.isfinite(whole[2:]).all() + assert (whole[2:, 8:] == 0).all() and np.ptp(whole[2:, :8], axis=0).min() > 0 + part = _quiet(tc.timecorr, [x[:28] for x in data], **kw) + assert np.array_equal(whole[:28], part, equal_nan=True) + + +def test_fastica_gets_no_more_components_than_the_rank_of_its_rows(): + # another draw of the random removal test: the correlations of the first + # rows of two subjects (5 defined rows each, 91 columns) have rank 4, + # and FastICA asked for 9 components did not reproduce them (by 8.7) + rng = np.random.default_rng(85) + data = [rng.standard_normal((11, 13)) for _ in range(2)] + kw = dict(causal=True, cfun=WISFC_2, rfun="FastICA", fit_timepoints=7, + weights_function=tc.laplace_weights, weights_params={"scale": 4}) + whole = _quiet(tc.timecorr, data, **kw) + assert [w.shape for w in whole] == [(11, 13)] * 2 + for w in whole: + used = np.flatnonzero(np.ptp(w[2:], axis=0) > 0) + assert 1 <= used.size <= 4 and np.isfinite(w[2:]).all() + part = _quiet(tc.timecorr, [x[:9] for x in data], **kw) + assert all(np.array_equal(w[:9], p, equal_nan=True) for w, p in zip(whole, part)) + + +# ---------------------------------------------------------------------------- +# fourth review: the identity with few training rows, explicit n_components +# ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize("model", GUARANTEED_MODELS) +def test_a_model_asked_for_every_column_changes_nothing_with_few_training_rows(model): + # the reviewer's input: 4 defined training rows, 10 columns, ndims 10. + # The components were capped by the rows before the request was + # compared with the columns, so a model was fitted (FastICA differed + # from the correlations by 31.9, PCA by 2.63) + x = np.random.default_rng(0).normal(size=(31, 4)) + kw = dict(order=1, causal=True, cfun=tc.autofc, delta_rfun=None, + weights_params={"var": 9}, delta_weights_params={"var": 9}) + plain = _quiet(tc.features, x, rfun=None, **kw)[1] + for ndims in (10, 13): + out, fitted = _quiet(tc.features, x, rfun=model, ndims=ndims, fit_timepoints=6, + return_model=True, **kw) + assert out[1].shape == (31, ndims) + assert np.array_equal(out[1][:, :10], plain, equal_nan=True) + assert (out[1][2:, 10:] == 0).all() + again = _quiet(fitted.transform, x[:20]) + assert np.array_equal(again[1], out[1][:20], equal_nan=True) + # with refits + out = _quiet(tc.features, x, rfun=model, ndims=10, fit_timepoints=6, refit_every=8, + **kw) + assert np.array_equal(out[1], plain, equal_nan=True) + + +@pytest.mark.parametrize("model", GUARANTEED_MODELS) +def test_an_explicit_number_of_components_is_capped_like_ndims(model): + # the reviewer's input: FastICA with n_components=4 in kwargs was fitted + # with 4 components on 4 training rows (rank 3) and did not reproduce + # them; the name alone, capped at the rank, ran + import sklearn.decomposition + + x = np.random.default_rng(0).normal(size=(31, 4)) + kw = dict(causal=True, cfun=tc.autofc, fit_timepoints=6, weights_params={"var": 9}) + cls = getattr(sklearn.decomposition, model) + + def instance(n): + # (an object without random_state is not the same model twice) + seeded = "random_state" in inspect.signature(cls).parameters + return cls(n_components=n, **({"random_state": 0} if seeded else {})) + + named = _quiet(tc.timecorr, x, rfun=model, **kw) + assert named.shape == (31, 4) and np.isfinite(named[2:]).all() + forms = [{"model": model, "kwargs": {"n_components": 4}}, + {"model": cls, "kwargs": {"n_components": 4}}, + {"model": model, "params": {"n_components": 4}}, + {"model": instance(4)}] + for rfun in forms: + out = _quiet(tc.timecorr, x, rfun=rfun, **kw) + assert out.shape == (31, 4) and np.isfinite(out[2:]).all(), rfun + assert np.array_equal(np.ptp(out[2:], axis=0) > 0, np.ptp(named[2:], axis=0) > 0) + assert np.array_equal(out[:20], _quiet(tc.timecorr, x[:20], rfun=rfun, **kw), + equal_nan=True) + # more components than the 4 training rows give, fewer than the 10 + # columns: as many as the rows give, and zero columns + for rfun in ({"model": model, "kwargs": {"n_components": 7}}, + {"model": instance(7)}): + out = _quiet(tc.timecorr, x, rfun=rfun, **kw) + assert out.shape == (31, 7) and np.isfinite(out[2:]).all(), rfun + assert (out[2:, 4:] == 0).all() + # at least as many as the columns: the correlations as they are + plain = _quiet(tc.timecorr, x, **{**kw, "fit_timepoints": None}) + for rfun in ({"model": model, "kwargs": {"n_components": 30}}, + {"model": instance(30)}, + {"model": cls, "kwargs": {"n_components": 10}}): + out = _quiet(tc.timecorr, x, rfun=rfun, **kw) + assert np.array_equal(out, plain, equal_nan=True), rfun + + +def test_the_width_with_an_explicit_number_of_components_is_that_without_causal(): + # scoped review: what decides the width when n_components is given with + # the model and ndims too. The causal call returns the width of the + # call without causal=True for the same model: n_components when a + # model is fitted; the columns as they are when n_components covers + # them, with zero columns up to ndims (not up to n_components) + import pickle + + from sklearn.decomposition import PCA + + x = np.random.default_rng(0).normal(size=(31, 4)) + base = dict(order=1, cfun=tc.autofc, delta_rfun=None, weights_params={"var": 9}, + delta_weights_params={"var": 9}) + expect = {(13, 2): 10, (10, 13): 13, (30, 4): 10, (3, 2): 3, (3, 5): 3, (7, 2): 7, + (7, 9): 7} + for (n, ndims), width in expect.items(): + for rfun in ({"model": "PCA", "kwargs": {"n_components": n}}, + {"model": PCA(n_components=n)}): + plain = _quiet(tc.features, x, rfun=rfun, ndims=ndims, **base)[1] + out, model = _quiet(tc.features, x, rfun=rfun, ndims=ndims, causal=True, + fit_timepoints=6, return_model=True, **base) + assert plain.shape == out[1].shape == (31, width), (n, ndims) + for fitted in (model, pickle.loads(pickle.dumps(model))): + again = _quiet(fitted.transform, x[:20]) + assert np.array_equal(again[1], out[1][:20], equal_nan=True) + + +def test_a_causal_call_leaves_the_model_object_of_the_caller_as_it_was(): + from sklearn.decomposition import PCA, FactorAnalysis, FastICA + + x = np.random.default_rng(0).normal(size=(60, 4)) + kw = dict(order=1, causal=True, cfun=tc.autofc, delta_rfun=None, fit_timepoints=30, + ndims=3, weights_params={"var": 9}, delta_weights_params={"var": 9}) + for given in (PCA(n_components=3), FastICA(random_state=0), + FactorAnalysis(n_components=3, random_state=0)): + before = dict(vars(given)) + out, model = _quiet(tc.features, x, rfun={"model": given}, return_model=True, **kw) + assert vars(given) == before # not fitted, no parameter changed + assert np.isfinite(out[1][2:]).all() + assert model.fits[(1, "analysis")].model_ is not given diff --git a/tests/test_causal_removal_random.py b/tests/test_causal_removal_random.py new file mode 100644 index 00000000..5a9b646f --- /dev/null +++ b/tests/test_causal_removal_random.py @@ -0,0 +1,289 @@ +"""Removal changes no bit: configurations drawn at random. + +Each draw is a causal ``timecorr`` or ``features`` call on a series and on +its first ``cut`` rows; the first ``cut`` rows of every output must be equal +bit for bit (``np.array_equal`` with NaN equal to NaN). The draws cover T +from 1 to 300, 1 to 40 features, 1 to 3 subjects, every built-in kernel, +``min_samples`` at effective sizes that occur at the cut, events, NaN and +infinite samples, the correlation and combine functions, reducers with and +without a fit, ``refit_every``, orders 1 to 3 and small memory limits. +""" + +import functools +import warnings + +import numpy as np +import pytest + +import timecorr as tc +from timecorr import helpers + +KERNELS = [ + (tc.gaussian_weights, {"var": 9}), + (tc.gaussian_weights, {"var": 100}), + (tc.gaussian_weights, {"var": 150.0 ** 2}), + (tc.laplace_weights, {"scale": 4}), + (tc.t_weights, {"df": 3}), + (tc.mexican_hat_weights, {"sigma": 5}), + (tc.boxcar_weights, {"width": 11}), + (tc.uniform_weights, {}), +] +MEASURES = ["strength", "eigenvector_centrality", "pagerank_centrality", + "pagerank_centrality_abs"] +MODELS = ["PCA", "IncrementalPCA", "TruncatedSVD", "FastICA", "FactorAnalysis"] + + +def _data(rng, S, T, K): + kind = rng.choice(["white", "walk", "offset", "shared"]) + data = [] + shared = rng.standard_normal((T, K)) + for _ in range(S): + x = rng.standard_normal((T, K)) + if kind == "walk": + x = np.cumsum(x, axis=0) + elif kind == "offset": + x = x + 1e4 + elif kind == "shared": + x = x + shared + if rng.random() < 0.4: + x[rng.random(x.shape) < rng.choice([0.002, 0.03])] = np.nan + if rng.random() < 0.15 and T > 2: + x[rng.integers(T), rng.integers(K)] = rng.choice([np.inf, -np.inf]) + data.append(x) + return data + + +def _min_samples(rng, kernel, cut): + """None, or a value at or next to an effective size of a kernel row of + the series cut at ``cut``.""" + if rng.random() < 0.5: + return None + lag = helpers._lag_kernel(cut, kernel[0], kernel[1], "backward", True, None) + sizes = np.unique(helpers._kernel_samples(lag)[1]) + sizes = sizes[sizes >= 1] + if not sizes.size: + return None + size = float(rng.choice(sizes)) + value = rng.choice([size, np.nextafter(size, 0), np.nextafter(size, np.inf), + size * (1 + 1e-12), size * (1 - 1e-12), np.ceil(size)]) + return float(max(1.0, value)) + + +def _events(rng, S, T): + if rng.random() < 0.7 or T < 8: + return None + one = lambda: sorted(int(b) for b in rng.choice(np.arange(1, T + 20), # noqa: E731 + size=rng.integers(1, 4), + replace=False)) + if S > 1 and rng.random() < 0.5: + return [one() for _ in range(S)] + return one() + + +def draw(rng): + """``(label, run, data, cut, with_model)``: ``run(data)`` is the list + of the output arrays of the call drawn; with ``with_model``, + ``run(data, True)`` is that of ``transform`` of the model the first + call returned.""" + T = int(rng.choice([rng.integers(1, 20), rng.integers(1, 301), rng.integers(120, 301)])) + cut = int(rng.choice([rng.integers(1, T + 1), max(1, T - int(rng.integers(0, 3)))])) + S = int(rng.choice([1, 1, 2, 3])) + K = int(rng.choice([rng.integers(1, 7), rng.integers(1, 15), rng.integers(1, 41)])) + kernel = KERNELS[rng.integers(len(KERNELS))] + kw = dict(causal=True, weights_function=kernel[0], weights_params=kernel[1]) + kw["min_samples"] = _min_samples(rng, kernel, cut) + events = _events(rng, S, T) + if events is not None: + kw["events"] = events + if rng.random() < 0.15: + kw["include_zero"] = False + cfuns = [tc.autofc, None] if S == 1 else [tc.autofc, tc.isfc, None, functools.partial( + tc.wisfc, subject_weights=np.ones((S, S)) - np.eye(S))] + cfun = cfuns[rng.integers(len(cfuns))] + kw["cfun"] = cfun + if S > 1 and cfun is not None and rng.random() < 0.6: + kw["combine"] = [tc.corrmean_combine, tc.mean_combine, tc.tstat_combine][ + rng.integers(3)] + fit = int(rng.integers(max(1, cut // 3), cut + 1)) + fitted = False + if rng.random() < 0.45: + function = tc.timecorr + choice = rng.random() + if cfun is None or choice < 0.25: + K = min(K, 12) + elif choice < 0.5: + kw["rfun"] = MEASURES[rng.integers(len(MEASURES))] + K = min(K, 15) + elif choice < 0.75: + kw["rfun"] = MODELS[rng.integers(len(MODELS))] + fitted = True + K = min(K, 15) + else: + kw["rfun"] = ["weighted_strength", tc.WeightedStrength(signed=True), + tc.Communities(n=2), "communities"][rng.integers(4)] + fitted = True + if fitted: + kw["fit_timepoints"] = fit + else: + function = tc.features + delta = KERNELS[rng.integers(len(KERNELS))] + kw.update(order=int(rng.integers(1, 4)), delta_weights_function=delta[0], + delta_weights_params=delta[1], return_delta=True) + choice = rng.random() + if cfun is None or choice < 0.15: + kw.update(rfun=None, delta_rfun=None) + K = min(K, 3 if kw["order"] == 3 else 4) + elif choice < 0.35: + kw.update(rfun=MEASURES[rng.integers(len(MEASURES))], delta_rfun="strength") + K = min(K, 15) + elif choice < 0.55: + fitted = True # the defaults + elif choice < 0.75: + fitted = True + kw.update(rfun=MODELS[rng.integers(len(MODELS))], + delta_rfun=["PCA", "weighted_strength"][rng.integers(2)]) + if rng.random() < 0.5 and kw["delta_rfun"] == "PCA": + kw["ndims"] = int(rng.integers(2, 5)) + K = min(K, 15) + else: + fitted = True + kw.update(rfun=["weighted_strength", tc.WeightedStrength(signed=True)][ + rng.integers(2)], delta_rfun="weighted_strength") + if fitted: + kw["fit_timepoints"] = fit + if rng.random() < 0.35 and cut > fit: + kw["refit_every"] = int(rng.integers(1, max(2, (cut - fit) // 2 + 1)) + 5) + if rng.random() < 0.4: + kw["max_memory_gb"] = float(rng.choice([0.004, 0.01, 0.05])) + data = _data(rng, S, T, K) + + # the fitted pipeline of the whole series, applied to the shorter one + with_model = function is tc.features and fitted and "refit_every" not in kw + models = [] + + def run(arrays, transform=False): + arrays = [np.array(a) for a in arrays] + given = arrays[0] if S == 1 else arrays + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if transform: + out = models[0].transform(given, return_delta=True, + events=kw.get("events")) + elif with_model: + out, model = function(given, return_model=True, **kw) + models.append(model) + else: + out = function(given, **kw) + flat = [] + for part in (out if isinstance(out, tuple) else (out,)): + for value in (part if isinstance(part, list) else [part]): + if isinstance(value, list): + flat += value + elif value is not None: + flat.append(value) + return [np.asarray(value) for value in flat] + + label = dict(kw, function=function.__name__, T=T, cut=cut, S=S, K=K) + return label, run, data, cut, with_model + + +def _same(whole, part, cut): + return len(whole) == len(part) and all( + a[:cut].shape == b.shape and np.array_equal(a[:cut], b, equal_nan=True) + for a, b in zip(whole, part)) + + +# Draws that are not valid calls, by the message of the error they raise: +# only these are left out; any other exception is a failure of the test. +INVALID = { + "min_samples no kernel row reaches": + r"min_samples=\S+ is more than a row of the kernel can have", + "fit rows without defined correlations": + r"fit_timepoints\)[^.]* hold (no row|no timepoint|fewer than 2 rows) with defined", + "too few features or rows for communities": + r"needs at least 4 features|Communities needs K >= 4|communities exceed K // 2" + r"|needs at least \d+ timepoints|Communities needs the number of communities n" + r"|the shift null needs T >= 40 timepoints", + "FastICA on correlations without a varying column": + r"FastICA cannot be fitted: no column of its input varies", + "more memory than max_memory_gb": + r"more than max_memory_gb", +} +MEMORY = "more memory than max_memory_gb" + + +def _raised(run, data): + """The exception ``run(data)`` raises, or None.""" + try: + run(data) + except Exception as error: + return error + return None + + +def _invalid(error): + """The key of ``INVALID`` that the message of ``error`` matches, or None.""" + import re + + if error is None: + return None + for reason, pattern in INVALID.items(): + if re.search(pattern, str(error)): + return reason + return None + + +def check(seed, draws): + """Run ``draws`` draws of ``seed``: ``(compared, skipped, failures)``, + ``skipped`` the number of draws left out by reason (``INVALID``).""" + import collections + + rng = np.random.default_rng(seed) + compared = 0 + skipped = collections.Counter() + failures = [] + for index in range(draws): + label, run, data, cut, with_model = draw(rng) + try: + whole = run(data) + except Exception as error: + reason = _invalid(error) + if reason is None: + failures.append((seed, index, label, + f"{type(error).__name__}: {error}")) + else: + skipped[reason] += 1 + # the shorter series is the same invalid call (it holds the + # rows of the fit, and no check reads the length); only a + # memory limit can be enough for it + again = _raised(run, [x[:cut] for x in data]) + if _invalid(again) != reason and reason != MEMORY: + failures.append((seed, index, label, + f"the series raises ({error}); the shorter one: " + f"{again!r}")) + continue + try: + part = run([x[:cut] for x in data]) + except Exception as error: + failures.append((seed, index, label, f"the shorter series raises: {error}")) + continue + compared += 1 + if not _same(whole, part, cut): + failures.append((seed, index, label, "different")) + elif with_model and not _same(whole, run([x[:cut] for x in data], True), cut): + failures.append((seed, index, label, "transform different")) + return compared, skipped, failures + + +def test_removal_changes_no_bit_in_configurations_drawn_at_random(): + compared, skipped, failures = check(0, 300) + assert failures == [] + assert compared >= 150 + + +@pytest.mark.slow +@pytest.mark.parametrize("seed", [1, 2, 3, 4, 5, 6]) +def test_removal_changes_no_bit_in_many_configurations_drawn_at_random(seed): + compared, skipped, failures = check(seed, 500) + assert failures == [] + assert compared >= 250 diff --git a/tests/test_round_off_variance.py b/tests/test_round_off_variance.py index 37a999b2..f390aa6e 100644 --- a/tests/test_round_off_variance.py +++ b/tests/test_round_off_variance.py @@ -384,3 +384,203 @@ def test_round_off_bound_covers_the_measured_round_off(monkeypatch): # order's kernel; Accelerate and OpenBLAS alike; see the comment above # helpers._ROUND_OFF) assert bound > 37.95 * eps + + +# --- tstat_combine: a spread across subjects at round-off level is none ------ +# +# With two subjects, isfc correlates subject 0 with subject 1 and subject 1 +# with subject 0: the same numbers, computed in two orders. They differ in +# their last bits in a few entries, and the t statistic divided the mean by +# that difference (finite |t| up to 1e16 next to +-inf). + + +def _two_subject_isfc(seed, T, K, **kw): + rng = np.random.RandomState(seed) + data = [rng.randn(T, K) for _ in range(2)] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + subjects = tc.timecorr(data, cfun=tc.isfc, combine=tc.null_combine, + weights_params={"var": 25}, **kw) + t, p = tc.timecorr(data, cfun=tc.isfc, + combine=lambda c: np.stack(tc.tstat_combine(c, True)), + weights_params={"var": 25}, **kw) + return subjects, t, p + + +@pytest.mark.parametrize("seed, T, K", [(4, 70, 4), (0, 300, 10), (1, 120, 25)]) +def test_tstat_combine_of_two_subjects_isfc_has_no_round_off_statistic(seed, T, K): + (a, b), t, p = _two_subject_isfc(seed, T, K) + spread = np.abs(a - b) + # the two subjects' correlations are the same up to round-off (on macOS + # not bit for bit: 32 of the 700 entries of the first case differed, by + # at most 61 eps over all cases measured) + assert spread.max() <= 128 * np.finfo(float).eps + assert not np.isnan(t).any() + mean = (a + b) / 2 + assert np.array_equal(t, np.where(mean > 0, np.inf, np.where(mean < 0, -np.inf, 0.0))) + assert np.array_equal(p, np.where(mean == 0, 1.0, 0.0)) + + +def test_tstat_combine_of_two_subjects_isfc_in_causal_mode(): + (a, b), t, _ = _two_subject_isfc(4, 70, 4, causal=True) + defined = ~np.isnan(a).any(axis=1) + assert np.array_equal(np.isnan(t).any(axis=1), ~defined) + # (the first defined row has 3 samples: its correlations can differ by + # more than round-off of well-conditioned sums, see tstat_combine) + rows = np.flatnonzero(defined)[1:] + assert np.isinf(t[rows]).all() + assert np.array_equal(np.sign(t[rows]), np.sign((a + b)[rows])) + + +def _reference_t(corrs): + """The statistic as it was: scipy's one-sample t-test of the Fisher z.""" + from scipy.stats import ttest_1samp + + with np.errstate(divide="ignore", invalid="ignore"), warnings.catch_warnings(): + warnings.simplefilter("ignore") # scipy: nearly identical data + return ttest_1samp(np.arctanh(np.stack(corrs, axis=2)), 0, axis=2) + + +def test_tstat_combine_of_subjects_that_differ_is_unchanged(): + rng = np.random.default_rng(0) + entries = 0 + smallest = np.inf + for trial in range(3000): + S = int(rng.integers(3, 7)) + corrs = [np.tanh(rng.standard_normal((8, 12)) * rng.choice([0.01, 0.3, 1.5])) + for _ in range(S)] + stacked = np.stack(corrs, axis=2) + smallest = min(smallest, np.ptp(stacked, axis=2).min()) + t, p = tc.tstat_combine(corrs, return_pvals=True) + expect = _reference_t(corrs) + assert np.array_equal(t, expect.statistic) and np.array_equal(p, expect.pvalue) + entries += t.size + assert entries == 3000 * 96 and smallest > 1e-9 + + +def test_tstat_combine_keeps_a_small_real_spread(): + # the reviewer's input: the two subjects have different events, so their + # correlations differ where a kernel row reaches over a boundary of one + # subject only; a difference of 1e-8 is not round-off + rng = np.random.RandomState(4) + xs = [rng.randn(70, 4) for _ in range(2)] + xs[0][48, 1] = np.inf + kw = dict(causal=True, cfun=tc.isfc, weights_params={"var": 25}, min_samples=3, + events=[[20, 60], [25, 65]]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + a, b = tc.timecorr(xs, combine=tc.null_combine, **kw) + t = tc.timecorr(xs, combine=tc.tstat_combine, **kw) + spread = np.abs(a - b) + real = (spread > 1e-12) & np.isfinite(spread) + small = real & (spread < 1e-7) + assert small.any() + with np.errstate(divide="ignore", invalid="ignore"): + expect = _reference_t([a, b]).statistic + assert np.isfinite(t[real]).all() and np.array_equal(t[real], expect[real]) + assert np.abs(t[small]).max() > 1e6 # ill-conditioned, and what was returned + + +@pytest.mark.parametrize("values, expect", [ + ((0.3, 0.3 + 2 * np.finfo(float).eps), np.inf), + ((-0.3, -0.3 + 100 * np.finfo(float).eps, -0.3), -np.inf), + ((1e-17, -1e-17), 0.0), # a mean of 0 + ((3e-17, 1e-17), np.inf), + ((50.0, 50.0 * (1 + 4 * np.finfo(float).eps)), np.inf), # raw values: relative + ((-50.0, -50.0 * (1 + 4 * np.finfo(float).eps)), -np.inf), +]) +def test_tstat_combine_round_off_spread_gives_the_zero_spread_value(values, expect): + with warnings.catch_warnings(): + warnings.simplefilter("error") + t, p = tc.tstat_combine([np.array([[v]]) for v in values], return_pvals=True) + assert t[0, 0] == expect + assert p[0, 0] == (1.0 if expect == 0 else 0.0) + + +@pytest.mark.parametrize("values", [ + (0.3, 0.3 + 1e-13), # 450 units of round-off: a difference + (0.3, 0.3 + 1e-9), + (50.0, 50.0 + 1e-11), + (1e-13, -1e-13), +]) +def test_tstat_combine_keeps_spreads_above_round_off(values): + from scipy.stats import ttest_1samp + + t = tc.tstat_combine([np.array([[v]]) for v in values])[0, 0] + v = np.array(values) + expect = ttest_1samp(v if np.abs(v).max() > 1 else np.arctanh(v), 0).statistic + assert np.isfinite(t) and t == expect + + +# --- non-finite values are not a spread at round-off level (review) ---------- + +NONFINITE_VALUES = (-np.inf, np.inf, np.nan, 0.0, 0.3, -0.3, 1.0, -1.0, 1.5, -40.0) + + +def nonfinite_inputs(): + """``{S: array (lists, S)}``: every list of S = 2 and 3 of + ``NONFINITE_VALUES`` with at least one infinite or NaN value.""" + import itertools + + out = {} + for size in (2, 3): + lists = np.array(list(itertools.product(NONFINITE_VALUES, repeat=size))) + out[size] = lists[~np.isfinite(lists).all(axis=1)] + return out + + +def test_tstat_combine_of_non_finite_values_is_what_it_was(): + # [-inf, +inf] has an infinite range and an infinite scale, and + # inf <= 128 eps * inf is true: it gave t = 0, p = 0 instead of NaN + import os + + reference = np.load(os.path.join(os.path.dirname(__file__), "fixtures", + "tstat_nonfinite_reference.npz")) + for size, values in nonfinite_inputs().items(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + t, p = tc.tstat_combine([column[np.newaxis] for column in values.T], + return_pvals=True) + assert t.shape == (1, len(values)) and len(values) in (51, 657) + for got, name in ((t, f"t{size}"), (p, f"p{size}")): + different = ~((got[0] == reference[name]) + | (np.isnan(got[0]) & np.isnan(reference[name]))) + assert not different.any(), values[different][:5] + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + t, p = tc.tstat_combine([np.array([[-np.inf]]), np.array([[np.inf]])], True) + assert np.isnan(t[0, 0]) and np.isnan(p[0, 0]) + + +# --- the bound is absolute for magnitudes up to 1 (review, round 3) ---------- + + +def test_tstat_combine_round_off_bound_is_absolute_below_one(): + # documented behavior: values closer than 128 eps (2.8e-14) are one + # value whatever their size, so 1e-16 and 2e-16 (t = 3 with the plain + # formula) give +inf + t, p = tc.tstat_combine([np.array([[1e-16]]), np.array([[2e-16]])], return_pvals=True) + assert t[0, 0] == np.inf and p[0, 0] == 0 + t = tc.tstat_combine([np.array([[1e-10]]), np.array([[1e-10 + 1e-15]])]) + assert t[0, 0] == np.inf + # above 1 the bound is relative: 128 eps times the largest magnitude + eps = np.finfo(float).eps + assert tc.tstat_combine([np.array([[1e6]]), np.array([[1e6 * (1 + 100 * eps)]])])[0, 0] \ + == np.inf + assert np.isfinite(tc.tstat_combine([np.array([[1e6]]), + np.array([[1e6 + 1e-6]])])[0, 0]) + # why: the round-off of a correlation is absolute, at the scale of 1. + # The same small correlation computed in two orders (isfc of two + # subjects) differs by a fraction of eps, which is many eps of its own + # size. Measured on macOS over 12 such pairs of recordings (1.17 + # million entries): for |r| < 0.01, 65 entries differ by more than 128 + # eps of their magnitude (up to 14,000 eps), none by more than 0.19 eps. + rng = np.random.default_rng(0) + data = [rng.standard_normal((300, 25)) for _ in range(2)] + a, b = tc.timecorr(data, cfun=tc.isfc, combine=tc.null_combine, + weights_params={"var": 2500}) + small = np.maximum(np.abs(a), np.abs(b)) < 0.01 + assert small.sum() > 1000 + assert np.abs(a - b)[small].max() <= 4 * eps + t = tc.tstat_combine([a, b]) + assert np.isinf(t).all() diff --git a/timecorr/helpers.py b/timecorr/helpers.py index a9895afa..c20eed03 100644 --- a/timecorr/helpers.py +++ b/timecorr/helpers.py @@ -1282,17 +1282,27 @@ def _time_slices(weights, finite=True, always=False): ``0 * inf = NaN`` that slicing would skip), when T' or T is 0, or when the spans cover more than ``_TIME_SLICE_MAX_FRACTION`` of the kernel's entries. ``always=True`` (the causal estimator) returns the spans - whatever ``_TIME_SLICING``, ``finite`` and the fraction covered are. + whatever ``_TIME_SLICING``, ``finite`` and the fraction covered are. With + it, the first column of a ``LagKernel``'s chunk is the one the kernel + gives (``LagKernel.span``), which no later row changes. """ kernel = as_kernel(weights) T_out, T = kernel.shape slices = None if (always or (_TIME_SLICING and finite)) and T_out and T: + # the causal estimator: the first column of a chunk must not depend + # on the rows after the chunk's first (a row may exist or not, as + # the series is longer or shorter). A LagKernel's own first column + # is that of the chunk's first row (the largest lag with weight, + # the start of its event), whereas a weight that is exactly 0 + # inside the kernel (a Mexican hat at lag sigma) can keep the + # first row from the column a later row weights. + structural = always and isinstance(getattr(kernel, "kernel", kernel), LagKernel) slices, covered = [], 0 for t0, t1, c0, _, _, w in blocks(kernel, CHUNK): cols = (w != 0).any(axis=0) if cols.any(): - s0 = c0 + int(cols.argmax()) + s0 = c0 if structural else c0 + int(cols.argmax()) s1 = c0 + w.shape[1] - int(cols[::-1].argmax()) else: s0 = s1 = 0 @@ -1852,6 +1862,13 @@ def _kernel_samples(kernel, observed=None): ``observed`` is a boolean vector over the T timepoints (None: all). Each row is scaled by its largest weight first, so tiny weights do not underflow when squared. + + The kernel has no weight above its diagonal (the causal estimator). + Each chunk of rows is summed over the columns of a chunk of a series + without an end, from its first column to the chunk's last row, with + zeros beyond the data: a sum's last bit depends on the number of terms, + which must not depend on the length of the series (a row at exactly + ``min_samples`` would be defined at one length and not at another). """ T_out = kernel.shape[0] count = np.zeros(T_out, dtype=np.int64) @@ -1863,8 +1880,11 @@ def _kernel_samples(kernel, observed=None): for t0, t1, c0, c1, key, w in blocks(kernel, CHUNK, _abs_weights): stats = seen.get(key) if (key is not None and everything) else None if stats is None: + block, m = w, min(c1, t0 + CHUNK) - c0 + w = np.zeros((t1 - t0, t0 + CHUNK - c0)) + w[:, :m] = block[:, :m] if not everything: - w = w * observed[c0:c1] + w[:, :m] *= observed[c0 : c0 + m] n = np.count_nonzero(w, axis=1) peak = w.max(axis=1, keepdims=True, initial=0.0) with np.errstate(invalid="ignore"): @@ -1969,41 +1989,74 @@ def _group_reference(x, weights, c0, g0, c1): A correlation does not depend on the reference; a reference close to the samples a row weights keeps its sums well conditioned. """ - span = x[c0:c1] + span = _group_span(x, c0, c1) ok = ~np.isnan(span) num = weights @ np.where(ok, span, 0.0) den = weights @ ok.astype(np.float64) ref = _safe_divide(num, den) none = den == 0 if none.any(): - ref[none] = _causal_reference(x[:, none], c0, g0, c1) + ref[none] = _causal_reference(x[:, none], c0, g0, min(c1, x.shape[0])) return ref def _causal_groups(rows): """ - ``(i, g0, g1, c0, c1)`` for the groups of consecutive rows ``g0:g1`` of - each chunk ``i`` of a prepared ``_KernelRows`` whose kernel has no - weight above its diagonal: the group's weights lie in columns ``c0:c1`` - (the chunk's columns before row ``g1``). A group has ``_CAUSAL_GROUP`` - rows, times the number of ``_CAUSAL_SPAN`` columns the chunk weights - (rounded up), at most the chunk. + ``(i, g0, g1, c0, c1, n)`` for the groups of consecutive rows ``g0:g1`` + of each chunk ``i`` of a prepared ``_KernelRows`` whose kernel has no + weight above its diagonal. + + A group is computed with the shapes of a group of a series without an + end, so that the operations that give a row do not depend on the number + of timepoints after it (removing later rows changes no bit): ``n`` is + the number of rows the group has in a complete chunk (``g1 - g0`` rows + exist; the others are rows of zero weight), and its columns are + ``c0:c1`` with ``c1 = g0 + n`` (the columns at or beyond the end of the + data are columns of zeros). ``n`` is ``_CAUSAL_GROUP``, times the + number of ``_CAUSAL_SPAN`` columns a complete chunk weights (rounded + up), at most what is left of the chunk. """ groups = [] for i, (t0, t1, c0, c1) in enumerate(rows.spans): - size = _CAUSAL_GROUP * max(1, -(-(c1 - c0) // _CAUSAL_SPAN)) + if c1 <= c0: + continue # a chunk without weight + end = t0 + CHUNK + size = _CAUSAL_GROUP * max(1, -(-(end - c0) // _CAUSAL_SPAN)) for g0 in range(t0, t1, size): - g1 = min(t1, g0 + size) - if min(c1, g1) > c0: - groups.append((i, g0, g1, c0, min(c1, g1))) + n = min(end, g0 + size) - g0 + groups.append((i, g0, min(t1, g0 + n), c0, g0 + n, n)) return groups def _group_block(rows, group, kind): - """The rows and columns of a group of ``_causal_groups`` (a new array).""" - i, g0, g1, c0, c1 = group - t0 = rows.spans[i][0] - return np.ascontiguousarray(rows._block(i, kind)[g0 - t0 : g1 - t0, : c1 - c0]) + """The ``n`` rows and the columns ``c0:c1`` of a group of + ``_causal_groups`` (a new array; zeros where the kernel has no row or + column).""" + i, g0, g1, c0, c1, n = group + t0, _, _, k1 = rows.spans[i] + block = rows._block(i, kind) + out = np.zeros((n, c1 - c0)) + m = min(k1, c1) - c0 + out[: g1 - g0, :m] = block[g0 - t0 : g1 - t0, :m] + return out + + +def _group_span(x, c0, c1): + """Rows ``c0:c1`` of ``x`` (an array of timepoints, or timepoints by + columns); rows at or beyond its end are zeros. A view when every row + exists.""" + part = x[c0:c1] + if part.shape[0] == c1 - c0: + return part + out = np.zeros((c1 - c0,) + x.shape[1:], dtype=x.dtype) + out[: part.shape[0]] = part + return out + + +# The triangle of an autocorrelation is computed this many rows of features +# at a time, each with the features from the first of them on (the blocks of +# ``_wcorr_blocks`` are whole numbers of them in causal mode). +_CAUSAL_FEATURES = 8 def _causal_setup(a, b, rows, autocorrelation, min_samples): @@ -2058,6 +2111,9 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): n = len(groups) state = { "causal": True, "T": a.shape[0], "rows": rows, "a": a, "b": b, + # an autocorrelation computed by _wcorr_blocks: its blocks hold the + # features from their first row on (_corr_row_blocks: every feature) + "triangular": autocorrelation, "defined": defined, "groups": groups, # groups whose columns hold a NaN sample; groups with a row that # weights one; the rows that weight none @@ -2081,6 +2137,7 @@ def _causal_setup(a, b, rows, autocorrelation, min_samples): active = np.zeros(T_out, dtype=bool) def moments(x, ref, dirty, A, W, s, g0, g1, side): + k = g1 - g0 # the rows of the group that exist x = x - ref if dirty: x[np.isnan(x)] = 0 @@ -2088,29 +2145,33 @@ def moments(x, ref, dirty, A, W, s, g0, g1, side): msq = A @ x**2 var = msq - s * mean**2 zero = _causal_zero_variance(var, msq, s, mean + ref) - state["m" + side][g0:g1] = mean - state["w" + side][g0:g1] = W @ x - state["v" + side][g0:g1] = np.where(zero, 0.0, var) - state["z" + side][g0:g1] = zero + state["m" + side][g0:g1] = mean[:k] + state["w" + side][g0:g1] = (W @ x)[:k] + state["v" + side][g0:g1] = np.where(zero, 0.0, var)[:k] + state["z" + side][g0:g1] = zero[:k] + T = a.shape[0] for g, group in enumerate(groups): - _, g0, g1, c0, c1 = group + _, g0, g1, c0, c1, _ = group + k = g1 - g0 A = _group_block(rows, group, "a") s = A.sum(axis=1)[:, np.newaxis] - active[g0:g1] = s[:, 0] > 0 - dirty = state["dirty"][g] = nan_before[c1] > nan_before[c0] + active[g0:g1] = s[:k, 0] > 0 + dirty = state["dirty"][g] = nan_before[min(c1, T)] > nan_before[c0] if dirty: - plain = (_group_block(rows, group, "s") @ with_nan[c0:c1]) == 0 + plain = (_group_block(rows, group, "s") + @ _group_span(with_nan, c0, c1))[:k] == 0 state["plain"][g0:g1] = plain state["nan"][g] = not plain.all() state["ref_a"][g] = _group_reference(a, A[0], c0, g0, c1) if not autocorrelation: state["ref_b"][g] = _group_reference(b, A[0], c0, g0, c1) W = _group_block(rows, group, "w") - state["sw"][g0:g1, 0] = W.sum(axis=1) - moments(a[c0:c1], state["ref_a"][g], dirty, A, W, s, g0, g1, "a") + state["sw"][g0:g1, 0] = W.sum(axis=1)[:k] + moments(_group_span(a, c0, c1), state["ref_a"][g], dirty, A, W, s, g0, g1, "a") if not autocorrelation: - moments(b[c0:c1], state["ref_b"][g], dirty, A, W, s, g0, g1, "b") + moments(_group_span(b, c0, c1), state["ref_b"][g], dirty, A, W, s, g0, g1, + "b") state["active"] = active # the sums for complete data set the block size; the pairwise sums of # the rows that need them are computed in blocks of their own @@ -2127,36 +2188,37 @@ def _causal_pairwise(A, W, S, xa, ok_a, xb, ok_b, ref_a, ref_b): the centered, zero-filled columns ``xa`` and ``xb`` (``ok_a``, ``ok_b``: their observed samples): ``(r, undefined, zero, few)``, each of shape (rows of the group, columns of ``xa``, columns of ``xb``). - """ - L = xa.shape[0] - sub = (A.shape[0], xa.shape[1], xb.shape[1]) - pair_ok = ok_a[:, :, np.newaxis] & ok_b[:, np.newaxis, :] - x = xa[:, :, np.newaxis] * pair_ok - y = xb[:, np.newaxis, :] * pair_ok - m = x[0].size - terms = np.concatenate( - [t.reshape(L, -1) for t in (pair_ok.astype(float), x, y, x**2, y**2)], - axis=1, - ) - s0, sx, sy, sxx, syy = np.split(A @ terms, 5, axis=1) - w0, wx, wy = np.split(W @ terms[:, : 3 * m], 3, axis=1) - wxy = W @ (x * y).reshape(L, -1) + + The sums of each column of ``xa`` are matrix products of their own + (the items of stacked ``np.matmul`` calls), so they do not depend on + the columns of ``xa`` given with it. + """ + m = xb.shape[1] + # (columns of xa, timepoints, columns of xb) + pair_ok = ok_a.T[:, :, np.newaxis] & ok_b[np.newaxis, :, :] + x = xa.T[:, :, np.newaxis] * pair_ok + y = xb[np.newaxis, :, :] * pair_ok + terms = np.concatenate([pair_ok.astype(float), x, y, x**2, y**2], axis=2) + s0, sx, sy, sxx, syy = np.split(np.matmul(A, terms), 5, axis=2) + w0, wx, wy = np.split(np.matmul(W, terms[:, :, : 3 * m]), 3, axis=2) + wxy = np.matmul(W, x * y) + few = np.matmul(S, terms[:, :, :m]) < 3 + del terms, x, y, pair_ok mx = _safe_divide(sx, s0) my = _safe_divide(sy, s0) - num = (wxy - mx * wy - my * wx + mx * my * w0).reshape(sub) + num = wxy - mx * wy - my * wx + mx * my * w0 var_a = sxx - s0 * mx**2 var_b = syy - s0 * my**2 - pairs = sub[1:] - ca = np.broadcast_to(ref_a[:, np.newaxis], pairs).reshape(-1) - cb = np.broadcast_to(ref_b[np.newaxis, :], pairs).reshape(-1) + ca = ref_a[:, np.newaxis, np.newaxis] + cb = ref_b[np.newaxis, np.newaxis, :] zero = _causal_zero_variance(var_a, sxx, s0, mx + ca) | ( _causal_zero_variance(var_b, syy, s0, my + cb) ) - var_a, var_b, zero = (v.reshape(sub) for v in (var_a, var_b, zero)) # two samples always give r = +-1: fewer than 3 is undefined - few = (S @ terms[:, :m]).reshape(sub) < 3 und = zero | few - return _correlation_ratio(num, var_a, var_b, und, sub), und, zero, few + r = _correlation_ratio(num, var_a, var_b, und, num.shape) + # (rows of the group, columns of xa, columns of xb) + return tuple(v.transpose(1, 0, 2) for v in (r, und, zero, few)) def _causal_block(state, i0, i1, j0): @@ -2167,82 +2229,125 @@ def _causal_block(state, i0, i1, j0): group computes the sums for complete data, on the data with NaN samples set to 0; a group with rows that weight a NaN sample also computes the pairwise sums, which those rows take. + + The operations that give the correlations of a row of features with + other features at a timepoint do not depend on the rows ``i0:i1`` asked + for, nor on the length of the series: every group has the shapes of + ``_causal_groups``, the cross products of each row of features are one + matrix product of their own (the items of a stacked ``np.matmul``), and + the features a row is multiplied with are fixed. For the triangle of + an autocorrelation (``state["triangular"]`` and ``j0 == i0``) these are + the features from the first row of its ``_CAUSAL_FEATURES`` rows on + (``i0`` is a multiple of that number; the entries before it are those + of the transposed pairs, computed with the rows before); otherwise the + features ``j0:``. """ rows = state["rows"] a, b = state["a"], state["b"] - shape = (rows.shape[0], i1 - i0, b.shape[1] - j0) + Kb = b.shape[1] + shape = (rows.shape[0], i1 - i0, Kb - j0) r = np.zeros(shape) undefined = np.ones(shape, dtype=bool) zero_all = np.ones(shape[0], dtype=bool) few_any = np.zeros(shape[0], dtype=bool) - # rows of ``a`` per block of pairwise sums - step = _wcorr_block_rows(state["T"], shape[2], _WCORR_NAN_PRODUCTS) + triangular = state["triangular"] and j0 == i0 + if triangular: + assert i0 % _CAUSAL_FEATURES == 0 + parts = [(s0, min(i1, s0 + _CAUSAL_FEATURES), s0) + for s0 in range(i0, i1, _CAUSAL_FEATURES)] + else: + parts = [(i0, i1, j0)] for g, group in enumerate(state["groups"]): - _, g0, g1, c0, c1 = group - L = c1 - c0 - sub = (g1 - g0,) + shape[1:] - ref_a = state["ref_a"][g, i0:i1] - ref_b = state["ref_b"][g, j0:] - xa = a[c0:c1, i0:i1] - ref_a - xb = b[c0:c1, j0:] - ref_b + _, g0, g1, c0, c1, _ = group + k = g1 - g0 # the rows of the group that exist + ref_a = state["ref_a"][g] + ref_b = state["ref_b"][g] + xa = _group_span(a, c0, c1)[:, i0:i1] - ref_a[i0:i1] + xb = _group_span(b, c0, c1)[:, j0:] - ref_b[j0:] if state["dirty"][g]: ok_a = ~np.isnan(xa) ok_b = ~np.isnan(xb) xa[~ok_a] = 0 xb[~ok_b] = 0 W = _group_block(rows, group, "w") - prod = (xa[:, :, np.newaxis] * xb[:, np.newaxis, :]).reshape(L, -1) - cross = (W @ prod).reshape(sub) - del prod - ma_i = state["ma"][g0:g1, i0:i1, np.newaxis] - mb_j = state["mb"][g0:g1, np.newaxis, j0:] - num = ( - cross - - ma_i * state["wb"][g0:g1, np.newaxis, j0:] - - mb_j * state["wa"][g0:g1, i0:i1, np.newaxis] - + ma_i * mb_j * state["sw"][g0:g1, :, np.newaxis] - ) - var_a = state["va"][g0:g1, i0:i1, np.newaxis] - var_b = state["vb"][g0:g1, np.newaxis, j0:] - zero = (state["za"][g0:g1, i0:i1, np.newaxis] - | state["zb"][g0:g1, np.newaxis, j0:]) - r_group = _correlation_ratio(num, var_a, var_b, zero, sub) - und = zero - if state["nan"][g]: - # the rows that weight a NaN sample take the pairwise sums + pairwise = state["nan"][g] + if pairwise: need = ~state["plain"][g0:g1] A = _group_block(rows, group, "a") S = _group_block(rows, group, "s") - und = zero.copy() - zero = zero.copy() - few = np.zeros(sub, dtype=bool) - for k0 in range(0, sub[1], step): - k1 = min(sub[1], k0 + step) - pr, pu, pz, pf = _causal_pairwise( - A, W, S, xa[:, k0:k1], ok_a[:, k0:k1], xb, ok_b, - ref_a[k0:k1], ref_b, - ) - r_group[need, k0:k1] = pr[need] - und[need, k0:k1] = pu[need] - zero[need, k0:k1] = pz[need] - few[need, k0:k1] = pf[need] - few_any[g0:g1] = few.reshape(sub[0], -1).any(axis=1) - zero_all[g0:g1] = zero.reshape(sub[0], -1).all(axis=1) - r[g0:g1] = r_group - undefined[g0:g1] = und + zero_group = np.ones(k, dtype=bool) + few_group = np.zeros(k, dtype=bool) + for s0, s1, jb in parts: + rows_ = slice(s0 - i0, s1 - i0) + cols = slice(jb - j0, None) + sub = (k, s1 - s0, Kb - jb) + # one product per row of features: (rows of the group) x (columns) + stack = xa.T[rows_, :, np.newaxis] * xb[np.newaxis, :, cols] + cross = np.matmul(W, stack)[:, :k].transpose(1, 0, 2) + del stack + ma_i = state["ma"][g0:g1, s0:s1, np.newaxis] + mb_j = state["mb"][g0:g1, np.newaxis, jb:] + num = ( + cross + - ma_i * state["wb"][g0:g1, np.newaxis, jb:] + - mb_j * state["wa"][g0:g1, s0:s1, np.newaxis] + + ma_i * mb_j * state["sw"][g0:g1, :, np.newaxis] + ) + var_a = state["va"][g0:g1, s0:s1, np.newaxis] + var_b = state["vb"][g0:g1, np.newaxis, jb:] + zero = (state["za"][g0:g1, s0:s1, np.newaxis] + | state["zb"][g0:g1, np.newaxis, jb:]) + r_sub = _correlation_ratio(num, var_a, var_b, zero, sub) + und = zero + if pairwise: + # the rows that weight a NaN sample take the pairwise sums + und = zero.copy() + zero = zero.copy() + few = np.zeros(sub, dtype=bool) + # (a few rows of features at a time: 10 products of the + # group's timepoints by the pairs; each row of features is + # a product of its own, so the split changes no bit) + step = _wcorr_block_rows(c1 - c0, Kb - jb, _WCORR_NAN_PRODUCTS) + for f0 in range(s0, s1, step): + f1 = min(s1, f0 + step) + at = slice(f0 - i0, f1 - i0) + pr, pu, pz, pf = _causal_pairwise( + A, W, S, xa[:, at], ok_a[:, at], xb[:, cols], ok_b[:, cols], + ref_a[f0:f1], ref_b[jb:], + ) + to = slice(f0 - s0, f1 - s0) + r_sub[:, to][need] = pr[:k][need] + und[:, to][need] = pu[:k][need] + zero[:, to][need] = pz[:k][need] + few[:, to][need] = pf[:k][need] + few_group |= few.reshape(k, -1).any(axis=1) + zero_group &= zero.reshape(k, -1).all(axis=1) + r[g0:g1, rows_, cols] = r_sub + undefined[g0:g1, rows_, cols] = und + if jb > j0: + # the pairs with the rows of features before: transposed + before = slice(0, jb - j0) + r[g0:g1, rows_, before] = r[g0:g1, before, rows_].transpose(0, 2, 1) + undefined[g0:g1, rows_, before] = ( + undefined[g0:g1, before, rows_].transpose(0, 2, 1)) + zero_all[g0:g1] = zero_group + few_any[g0:g1] = few_group return r, undefined, zero_all, few_any -def _symmetrize_block(r, undefined, offset): +def _symmetrize_block(r, undefined, offset, average=True): """ In place, for an autocorrelation block from ``_wcorr_block`` whose rows ``i0:i1`` start ``offset`` columns after its first column: set the diagonal to 1 (0 where undefined) and replace the square of columns - ``offset:offset + (i1 - i0)`` by the mean of it and its transpose. + ``offset:offset + (i1 - i0)`` by the mean of it and its transpose + (``average=False``: the diagonal only). """ c = r.shape[1] diag = np.arange(c) r[:, diag, offset + diag] = np.where(undefined[:, diag, offset + diag], 0.0, 1.0) + if not average: + return square = r[:, :, offset : offset + c] r[:, :, offset : offset + c] = (square + square.transpose(0, 2, 1)) / 2 @@ -2275,6 +2380,9 @@ def _wcorr_blocks(a, b, rows, autocorrelation, causal=False, min_samples=None): sparse = np.zeros_like(cancelled) rows_per_block = _wcorr_block_rows(T, Kb, state["n_products"]) + if causal: + # whole numbers of the rows of features _causal_block computes together + rows_per_block = max(1, rows_per_block // _CAUSAL_FEATURES) * _CAUSAL_FEATURES for i0 in range(0, Ka, rows_per_block): i1 = min(Ka, i0 + rows_per_block) j0 = i0 if autocorrelation else 0 @@ -2329,8 +2437,11 @@ def _corr_row_blocks(a, b, weights, symmetric, rows_per_block=None, *, delta case). With ``causal=True`` the rows are those of ``_wcorr(..., causal=True, - min_samples=min_samples, autocorrelation=symmetric)``: the undefined - (warm-up) rows are NaN in every block. + min_samples=min_samples, autocorrelation=symmetric)`` to round-off: the + undefined (warm-up) rows are NaN in every block, and no entry depends + on ``rows_per_block`` (each row of features is multiplied with every + feature in a product of its own, and no pair is averaged with its + transpose, so the two orientations of a pair agree to round-off only). Raises ``ValueError`` as ``_wcorr`` does, and if ``symmetric`` is True but ``a`` and ``b`` differ in shape. @@ -2367,6 +2478,7 @@ def delta_blocks(): if causal: state = _causal_setup(a, b, rows, symmetric, min_samples) + state["triangular"] = False # every block holds every feature warmup = ~state["defined"] else: rows.zero_rows(rows.support < 3) @@ -2380,7 +2492,11 @@ def blocks(): i1 = min(Ka, i0 + step) r, undefined, zero_all, few_any = _wcorr_block(state, i0, i1, 0) if symmetric: - _symmetrize_block(r, undefined, i0) + # causal: a pair is averaged with its transpose only when + # both features are in the block, and the blocks depend on + # T and on the memory limit; every entry is left as the + # product of its own row of features gave it + _symmetrize_block(r, undefined, i0, average=not causal) if warmup is not None: r[warmup] = np.nan yield i0, i1, r.transpose(1, 2, 0), active & zero_all, active & few_any @@ -2477,10 +2593,14 @@ def wcorr(a, b, weights, *, causal=False, min_samples=None): samples after ``t`` are replaced by any values, NaN and inf included, or removed (and, when the kernel gives ``t`` itself no weight, when the samples at ``t`` change). Replacing later samples changes no bit of - an earlier timepoint; removing them changes the shapes of the last - sums and so their round-off (measured: at most 6e-13, on series with - an offset, a random walk, and steps of up to 1e8 standard - deviations). The kernel must give no weight to later timepoints. The estimate is the same formula, with these differences: + an earlier timepoint. Removing them changes no bit either when the + first timepoint that a chunk of 128 kernel rows weights is one its + first row weights (the kernels ``timecorr`` builds from the built-in + kernel functions, and arrays of the same weights, a Mexican hat whose + weight is exactly 0 at a lag inside it excepted): groups of kernel + rows have the shapes of a series without an end, with zeros beyond + the data, and each feature's products are a matrix product of their + own. For other kernel arrays removal is documented to 1e-9. The kernel must give no weight to later timepoints. The estimate is the same formula, with these differences: - Data are centered, a group of 16 timepoints at a time (more for a kernel that weights more than 512 timepoints), on the kernel-weighted @@ -3409,6 +3529,36 @@ def mean_combine(vals): return np.mean(np.stack(vals, axis=2), axis=2) +def _round_off_spread(stacked): + """ + Entries of a stack of matrices (along the last axis) whose values are + one value up to round-off: their range is at most ``_UNIT_TOLERANCE`` + (128 eps, 2.8e-14), or that times the largest magnitude when it exceeds + 1 (correlations are computed to an absolute accuracy, raw + co-fluctuations to a relative one). Values closer than 2.8e-14 are + therefore one value whatever their size (1e-16 and 2e-16 are): the + same correlation below 0.01 computed in two orders differed by at most + 0.19 eps, up to 14,000 eps of its own size. + + The same correlation computed in two orders (``isfc`` of two subjects: + subject 0 with subject 1, and subject 1 with subject 0) differs by at + most 61 eps in the cases measured (33.8 million entries: five kinds of + data, T 100 to 700, 10 to 40 features, five kernels, with and without + ``causal=True``; 2.46 million of them differ at all, 99.7% by less + than 2 eps), except in the first defined row of the causal estimator, + which has 3 samples (13 entries above 128 eps, up to 3108 eps). Correlations of subjects + that differ are far apart on that scale: 3000 random stacks of 3 to 6 + subjects have no range below 1e-9. An entry with a NaN or infinite + value is not selected (an infinite range is not at most 128 eps times + an infinite magnitude, although ``inf <= inf``). + """ + finite = np.isfinite(stacked).all(axis=-1) + with np.errstate(invalid="ignore"): + spread = stacked.max(axis=-1) - stacked.min(axis=-1) + scale = np.maximum(1.0, np.abs(stacked).max(axis=-1)) + return finite & (spread <= _UNIT_TOLERANCE * scale) + + def tstat_combine(corrs, return_pvals=False): """ Element-wise one-sample t-tests (mean 0) across the matrices in a list. @@ -3422,11 +3572,28 @@ def tstat_combine(corrs, return_pvals=False): value in every matrix (zero variance across subjects, for example the diagonal of ``autofc`` results, where every value is 1) has t = +inf or -inf with the sign of that value (p = 0), or t = 0 (p = 1) when the value - is 0, with no warning. Where the values of the matrices nearly coincide + is 0, with no warning. The same holds where the values differ by + round-off only: a range across the matrices of at most 128 eps + (2.8e-14), or that times the largest magnitude when it exceeds 1, + counts as none, and the + entry has t = +inf, -inf or 0 with the sign of the mean of its values. + The bound is absolute for magnitudes up to 1: values closer than 2.8e-14 + are treated as equal whatever their size, so 1e-16 and 2e-16 give t = +inf + (3 with the plain formula). The round-off of a correlation is absolute, at + the scale of 1: the same correlation below 0.01 computed in two orders + differed by at most 0.19 eps, which was up to 14,000 eps of its own size + (65 of 153,000 such entries by more than 128 eps of their size). + That is the case of ``isfc`` with two subjects, whose correlations are + the same numbers computed in two orders (they differed by up to 61 eps + in the cases measured; in the first defined row of ``causal=True``, + which has 3 samples, 13 of 33.8 million entries differed by more than + 128 eps, up to 3108 eps, and keep their finite statistic). Where the values of the matrices + nearly coincide beyond that (1e-13 is a difference) the statistic is ill-conditioned: round-off of the correlations is - divided by a spread close to zero (with ``causal=True`` such entries - agree to about 1e-9 of their magnitude, not to 1e-9, when later rows - are removed; see ``timecorr``). + divided by a spread close to zero (with ``causal=True`` and a kernel + function of your own such entries agree to about 1e-9 of their + magnitude, not to 1e-9, when later rows are removed; with the built-in + kernel functions removal changes no bit; see ``timecorr``). Parameters ---------- @@ -3476,14 +3643,16 @@ def tstat_combine(corrs, return_pvals=False): raw = np.any(outside, axis=2, keepdims=True) vals = np.where(raw, stacked, z) # zero variance across subjects (every value equal, infinities - # included): t is +-inf with the sign of the mean, 0 for a mean of 0 - constant = np.all(vals == vals[:, :, :1], axis=2) + # included, or equal up to round-off): t is +-inf with the sign of + # the mean, 0 for a mean of 0 + constant = np.all(vals == vals[:, :, :1], axis=2) | _round_off_spread(stacked) filler = np.arange(vals.shape[2], dtype=np.float64) # any non-constant row ts, ps = ttest(np.where(constant[:, :, None], filler, vals), popmean=0, axis=2) - first = vals[:, :, 0] - signed_inf = np.where(first > 0, np.inf, np.where(first < 0, -np.inf, 0.0)) + with np.errstate(invalid="ignore"): # +inf and -inf: NaN, as before + mean = np.where(constant[:, :, None], vals, 0.0).mean(axis=2) + signed_inf = np.where(mean > 0, np.inf, np.where(mean < 0, -np.inf, 0.0)) ts = np.where(constant, signed_inf, ts) - ps = np.where(constant, np.where(first == 0, 1.0, 0.0), ps) + ps = np.where(constant, np.where(mean == 0, 1.0, 0.0), ps) if return_pvals: return ts, ps @@ -3669,6 +3838,132 @@ def _pagerank_solve(B, b): return r +def _is_fastica(rfun): + """Whether a model reducer is FastICA: the name, or a dict whose + ``"model"`` is the name, scikit-learn's class or an object of exactly + that class (the forms ``reduce`` accepts).""" + model = rfun.get("model") if isinstance(rfun, dict) else rfun + if isinstance(model, str): + return model == "FastICA" + from sklearn.decomposition import FastICA + + return model is FastICA or type(model) is FastICA + + +def _varying_first(arrays, rfun): + """ + For a ``"FastICA"`` fit: ``(order, varying)``, the number of columns + that vary over the rows of ``arrays`` and, when the first column is + constant and another varies, the order of the columns with those that + vary first (each group in its order; None otherwise). ``(None, None)`` + for another model or no rows. + + scikit-learn's FastICA multiplies each whitening vector by the sign of + its loading on the first feature. The first column of vectorized + autocorrelations is a diagonal entry (1 in every row), whose loading is + 0 up to the round-off of the SVD: where it is exactly 0, which depends + on the platform and on the last bits of the data, the component is + multiplied by 0 and the fit holds NaN. The order of the columns does + not change what a linear model computes. FastICA also divides by the + singular values of its input, so it is asked for no more components + than the rank of its centered rows (``numpy.linalg.matrix_rank``; at + most the columns that vary and the rows less one: a component beyond + it is round-off divided by round-off, or NaN, and the fit does not + reproduce its rows). + """ + if not _is_fastica(rfun): + return None, None + stacked = np.vstack(arrays) + if not stacked.shape[0]: + return None, None + constant = np.ptp(stacked, axis=0) == 0 + varying = int(np.sum(~constant)) + if not constant[0] or not varying: + return None, varying + return np.concatenate([np.flatnonzero(~constant), np.flatnonzero(constant)]), varying + + +def _explicit_components(rfun): + """``n_components`` given with a model reducer itself (in ``kwargs`` of + a model dict, or as the attribute of a model object), which hypertools + uses in place of ``ndims``; None when there is none.""" + if not isinstance(rfun, dict): + return None + asked = (rfun.get("kwargs") or {}).get("n_components") + given = rfun.get("model") + if asked is None and not isinstance(given, (str, type)): + asked = getattr(given, "n_components", None) + return asked if isinstance(asked, numbers.Integral) else None + + +def _with_components(rfun, n): + """``rfun`` with its own ``n_components`` (``_explicit_components``) + set to ``n``.""" + given = rfun.get("model") + if "n_components" in (rfun.get("kwargs") or {}): + return {**rfun, "kwargs": {**rfun["kwargs"], "n_components": n}} + from sklearn.base import clone + + return {**rfun, "model": clone(given).set_params(n_components=n)} + + +def _causal_components(arrays, rfun, ndims, n_features, n_samples): + """ + The components of a causal model fit: ``(rfun, ndims, n_fit, order, + rank_capped)``. + + The number asked for is ``n_components`` given with the model itself + (``_explicit_components``), otherwise ``ndims``. Asked for at least as + many components as there are columns, no model is fitted, whatever the + number of rows: hypertools returns the columns as they are (``n_fit`` + is the number of columns). Otherwise the model is fitted with as many + components as asked, at most the number of rows, and for FastICA at + most the rank of the centered rows, with its columns in the order + ``order`` (``_varying_first``); a larger ``n_components`` given with + the model is replaced, and ``ndims`` is the number asked for, so that + ``reduce`` appends zero columns for the components the rows do not + give. + + The width of the output is that of the call without ``causal`` for + the same model: the number asked for when a model is fitted; when + none is, the columns as they are, with zero columns up to ``ndims`` + (an ``n_components`` given with the model decides that no model is + fitted, not the number of zero columns). + """ + explicit = _explicit_components(rfun) + asked = ndims if explicit is None else int(explicit) + if asked >= n_features: + return rfun, ndims, min(ndims, n_features), None, False + n_fit = min(asked, n_samples) + order, varying = _varying_first(arrays, rfun) + rank_capped = False + if varying is not None: + if not varying: + raise _FitUnusable( + "FastICA cannot be fitted: no column of its input varies over " + f"the {n_samples} rows it is fitted on ({n_features} " + "column" + ("s" if n_features != 1 else "") + ", constant: the " + "diagonal of the correlations of the features of the order " + "before). Use another model (for example 'PCA') or more " + "features at that order." + ) + # no more components than the rank of the centered rows: FastICA + # divides by their singular values + stacked = np.vstack(arrays) + rank = max(1, int(np.linalg.matrix_rank(stacked - stacked.mean(axis=0)))) + rank_capped = rank < n_fit + n_fit = min(n_fit, rank) + if explicit is not None: + if explicit > n_fit: + rfun = _with_components(rfun, n_fit) + ndims = asked + elif varying is not None and isinstance(rfun, dict) and not isinstance( + rfun.get("model"), (str, type)): + # a FastICA object without n_components would take every column + rfun = _with_components(rfun, n_fit) + return rfun, ndims, n_fit, order, rank_capped + + def _model_reduce(corrs, rfun, ndims, return_model=False): """ The model-based reduction of ``reduce`` (``rfun`` a model name or dict, @@ -3685,7 +3980,6 @@ def _model_reduce(corrs, rfun, ndims, return_model=False): # a model cannot return more components than there are features or samples n_samples = sum(a.shape[0] for a in arrays) n_fit = min(ndims, n_features, n_samples) - if isinstance(rfun, dict) and "params" in rfun: # hypertools deprecated 'params' in favor of 'kwargs': merge both params = dict(rfun["params"] or {}) @@ -3706,7 +4000,20 @@ def _model_reduce(corrs, rfun, ndims, return_model=False): rfun = _umap_defaults(rfun) model = None + order = None if return_model: + given = rfun.get("model") if isinstance(rfun, dict) else None + if given is not None and not isinstance(given, (str, type)): + # hypertools fits the object it is given: a copy is fitted, and + # the caller's object stays as it was + from sklearn.base import clone + + rfun = {**rfun, "model": clone(given)} + rfun, ndims, n_fit, order, rank_capped = _causal_components( + arrays, rfun, ndims, n_features, n_samples) + if order is not None: + permuted = [a[:, order] for a in arrays] + corrs = permuted if isinstance(corrs, list) else permuted[0] red_corrs, model = hyp.reduce(corrs, reduce=rfun, ndims=n_fit, random_state=0, return_model=True) else: @@ -3720,7 +4027,10 @@ def _model_reduce(corrs, rfun, ndims, return_model=False): pad = ndims - n_fit _warn_user( f"reduce: the data supply at most {n_fit} components ({n_features} " - f"features, {n_samples} samples) but {ndims} were requested; the " + f"features, {n_samples} samples" + + (", FastICA: no more than the rank of the centered samples" + if return_model and rank_capped else "") + + f") but {ndims} were requested; the " f"output is padded with {pad} zero column{'s' if pad > 1 else ''}." ) if isinstance(red_corrs, list): @@ -3731,7 +4041,7 @@ def _model_reduce(corrs, rfun, ndims, return_model=False): red_corrs = np.hstack((red_corrs, np.zeros((red_corrs.shape[0], pad)))) if return_model: - return red_corrs, _FittedModel(model, n_features, max(0, ndims - n_fit)) + return red_corrs, _FittedModel(model, n_features, max(0, ndims - n_fit), order) return red_corrs @@ -3763,6 +4073,17 @@ class _FitUnusable(ValueError): _FROZEN_ZERO_RTOL = 1e-12 +# The models whose transform is known to be a linear map of each row +# (scikit-learn's classes of these names, by exact class): the models the +# guarantee of causal mode covers (``timecorr._uncovered_model``). +_GUARANTEED_MODELS = ("PCA", "IncrementalPCA", "TruncatedSVD", "FastICA", + "FactorAnalysis") + +# A frozen model of ``_GUARANTEED_MODELS`` reduces this many rows in one call +# (``_FittedModel._reduce``). +_APPLY_ROWS = 128 + + class _FittedModel: """ A hypertools model fitted by ``_model_reduce``: ``model`` (the fitted @@ -3771,7 +4092,8 @@ class _FittedModel: and ``apply`` is then the identity), the number of input columns ``n_features`` and the number of zero columns ``pad`` that ``reduce`` appends when the data supplied - fewer components than requested. ``apply`` reduces other rows with it. + fewer components than requested, and ``order``, the order in which the + model takes the columns (None: as given; ``_varying_first``). ``apply`` reduces other rows with it. ``freeze_constants(outputs)`` (the model's outputs for its training rows) records the output columns that are constant there up to @@ -3783,11 +4105,10 @@ class _FittedModel: the column's training mean as exactly that mean; other values are returned as computed. The rule reads the training rows and the row it is applied to, nothing else, so it is causal; without it the next - order would correlate that round-off, which is not reproducible to - 1e-9 when later rows are removed. + order would correlate that round-off. """ - def __init__(self, model, n_features, pad=0): + def __init__(self, model, n_features, pad=0, order=None): # the model as a pickle restores it: a fitted model's arrays can be # laid out differently in memory after pickling, which changes the # round-off of its products, so a model and its unpickled copy @@ -3800,6 +4121,8 @@ def __init__(self, model, n_features, pad=0): self.n_features = int(n_features) self.pad = int(pad) self.constants = None # (columns, their training means, tolerances) + # the order in which the model takes the columns (_varying_first) + self.order = None if order is None else np.asarray(order, dtype=np.intp) @property def estimator(self): @@ -3816,6 +4139,10 @@ def components(self): components = np.asarray(components, dtype=np.float64) if components.ndim != 2 or components.shape[1] != self.n_features: return None + if self.order is not None: # in the order of the columns given + ordered = np.empty_like(components) + ordered[:, self.order] = components + components = ordered return components def freeze_constants(self, outputs): @@ -3830,6 +4157,39 @@ def freeze_constants(self, outputs): self.constants = (columns, np.mean(stacked[:, columns], axis=0), tol[columns]) + def _row_wise(self): + """Whether the fitted estimator is exactly one of scikit-learn's + classes of ``_GUARANTEED_MODELS``.""" + import sklearn.decomposition + + return any(type(self.estimator) is getattr(sklearn.decomposition, name) + for name in _GUARANTEED_MODELS) + + def _reduce(self, a): + """One array reduced by the model, ``_APPLY_ROWS`` rows at a time + (the last rows followed by rows of zeros): the matrix products of + the model then have the same shape whatever the number of rows and + of arrays, so the bits of a reduced row depend on the rows before + it in its batch at most (a product of all rows together differs in + the last bit between a series and a shorter one). A model outside + ``_GUARANTEED_MODELS`` is given all rows together: nothing is + known of what its transform does with rows of zeros (the guarantee + of causal mode does not cover it).""" + if not self._row_wise(): + return np.asarray(hyp.reduce(a, reduce=self.model), dtype=np.float64) + parts = [] + for r0 in range(0, a.shape[0], _APPLY_ROWS): + batch = np.zeros((_APPLY_ROWS, a.shape[1])) + part = a[r0 : r0 + _APPLY_ROWS] + batch[: part.shape[0]] = part + reduced = np.asarray(hyp.reduce(batch, reduce=self.model), dtype=np.float64) + parts.append(reduced[: part.shape[0]]) + if not parts: + reduced = np.asarray(hyp.reduce(np.zeros((_APPLY_ROWS, a.shape[1])), + reduce=self.model), dtype=np.float64) + return reduced[:0] + return np.vstack(parts) + def apply(self, arrays): """The rows of a list of (rows, n_features) arrays, reduced with the fitted model (a list of arrays).""" @@ -3843,9 +4203,9 @@ def apply(self, arrays): if self.model is None: out = [a.copy() for a in arrays] # the identity else: - out = hyp.reduce(arrays, reduce=self.model) - out = out if isinstance(out, list) else [out] - out = [np.asarray(o, dtype=np.float64) for o in out] + if self.order is not None: + arrays = [a[:, self.order] for a in arrays] + out = [self._reduce(a) for a in arrays] if self.pad: out = [np.hstack((o, np.zeros((o.shape[0], self.pad)))) for o in out] if self.constants is not None: diff --git a/timecorr/higher_order.py b/timecorr/higher_order.py index 3f2d2390..27c537e5 100644 --- a/timecorr/higher_order.py +++ b/timecorr/higher_order.py @@ -1812,24 +1812,30 @@ def two_path_step( here) and recorded in summaries' ``fits_``. Default: 1. causal : bool If True (keyword-only), row ``t`` of every output is computed from - rows ``0..t`` of the data only: it is unchanged (to 1e-9; bit for - bit when later rows are replaced) when later rows are replaced by - any values, NaN and inf included, or removed, and with - ``include_zero=False`` also when row ``t`` itself changes. + rows ``0..t`` of the data only: it is unchanged when later rows + are replaced by any values, NaN and inf included, or removed, and + with ``include_zero=False`` also when row ``t`` itself changes. Replacing later rows changes no bit, with every supported reducer. - Removing them changes the correlations by round-off, so the - outputs agree to 1e-9 where they depend continuously on the - correlations (no reduction, ``"strength"``, the summaries, and - linear models such as PCA once fitted); the eigenvector-based - graph measures (``"eigenvector_centrality"``, the PageRank - measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide, and the t statistics of ``tstat_combine``, - which divide by the spread of the subjects' correlations, where - that spread is close to zero (always with two subjects and - ``isfc``: their correlations are the same), to about 1e-9 of - their magnitude instead. With ``cfun=None`` the steps smooth their - input, and smoothed values agree to round-off relative to the - magnitude of the data (see ``timecorr``). Default: False. With + With the built-in kernel functions, removing them changes no bit + either (every reducer and ``combine`` function and ``cfun=None`` + included): a row is computed with the same operations whatever + the length of the series and whatever ``max_memory_gb`` (tested, + also in configurations drawn at random, not proven: it holds when + the linear-algebra library computes a row of a matrix product of + a given shape from that row's operands alone). With a kernel function of your own the + columns of a chunk of kernel rows are found from its weights and + can depend on the length; removal is then documented to 1e-9 + where the outputs depend continuously on the correlations (no + reduction, ``"strength"``, the summaries, and linear models such + as PCA once fitted); the eigenvector-based graph measures + (``"eigenvector_centrality"``, the PageRank measures) can then + differ by more at a correlation matrix whose leading eigenvalues + coincide, and the t statistics of ``tstat_combine``, which divide + by the spread of the subjects' correlations, where that spread is + close to zero, agree to about 1e-9 of their magnitude instead; + with ``cfun=None`` the steps smooth their input, and smoothed + values then agree to round-off relative to the magnitude of the + data (see ``timecorr``). Default: False. With ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be @@ -1904,7 +1910,8 @@ def two_path_step( correlations there, a summary 1, the shift null 40 rows of input. The fits do not change, bit for bit, whatever follows row ``n-1``. Every row is then reduced with them: row ``t >= n`` is - unchanged (to 1e-9; bit for bit under replacement) when rows after + unchanged (bit for bit; under removal with the built-in kernel + functions, see ``causal``) when rows after ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every @@ -1924,7 +1931,27 @@ def two_path_step( the rows it is given together). A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended - for the components beyond them), as without ``causal``. + up to ``ndims``), whatever the number of training + rows; the number asked for is ``n_components`` given with the + model (in its ``kwargs``, or of a model object; it decides + whether a model is fitted and the width of a fitted model's + output, not the number of zero columns: the widths are those of + the call without ``causal``), otherwise ``ndims``. Asked for + fewer components than columns + but more than there are defined training rows, a model is fitted + with as many components as those rows, and zero columns are + appended for the others, with a warning. + ``"FastICA"`` (when it is fitted: asked for fewer components than + columns) is given the columns that vary over the training rows + first and is asked for no more components than the rank of the + centered training rows (zero columns are appended for the + others, with a warning; ``ValueError`` when no column varies): + scikit-learn sets the sign of a component from its loading on + the first column, which for vectorized correlations is a + diagonal entry, 1 in every row, and the fit held NaN where that + loading was exactly 0; and it divides by the singular values of + the rows, so a component beyond their rank did not reproduce the + training rows. ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for large inputs does not reproduce its @@ -2955,24 +2982,30 @@ def features( Default: False. causal : bool If True (keyword-only), row ``t`` of every output is computed from - rows ``0..t`` of the data only: it is unchanged (to 1e-9; bit for - bit when later rows are replaced) when later rows are replaced by - any values, NaN and inf included, or removed, and with - ``include_zero=False`` also when row ``t`` itself changes. + rows ``0..t`` of the data only: it is unchanged when later rows + are replaced by any values, NaN and inf included, or removed, and + with ``include_zero=False`` also when row ``t`` itself changes. Replacing later rows changes no bit, with every supported reducer. - Removing them changes the correlations by round-off, so the - outputs agree to 1e-9 where they depend continuously on the - correlations (no reduction, ``"strength"``, the summaries, and - linear models such as PCA once fitted); the eigenvector-based - graph measures (``"eigenvector_centrality"``, the PageRank - measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide, and the t statistics of ``tstat_combine``, - which divide by the spread of the subjects' correlations, where - that spread is close to zero (always with two subjects and - ``isfc``: their correlations are the same), to about 1e-9 of - their magnitude instead. With ``cfun=None`` the steps smooth their - input, and smoothed values agree to round-off relative to the - magnitude of the data (see ``timecorr``). Default: False. With + With the built-in kernel functions, removing them changes no bit + either (every reducer and ``combine`` function and ``cfun=None`` + included): a row is computed with the same operations whatever + the length of the series and whatever ``max_memory_gb`` (tested, + also in configurations drawn at random, not proven: it holds when + the linear-algebra library computes a row of a matrix product of + a given shape from that row's operands alone). With a kernel function of your own the + columns of a chunk of kernel rows are found from its weights and + can depend on the length; removal is then documented to 1e-9 + where the outputs depend continuously on the correlations (no + reduction, ``"strength"``, the summaries, and linear models such + as PCA once fitted); the eigenvector-based graph measures + (``"eigenvector_centrality"``, the PageRank measures) can then + differ by more at a correlation matrix whose leading eigenvalues + coincide, and the t statistics of ``tstat_combine``, which divide + by the spread of the subjects' correlations, where that spread is + close to zero, agree to about 1e-9 of their magnitude instead; + with ``cfun=None`` the steps smooth their input, and smoothed + values then agree to round-off relative to the magnitude of the + data (see ``timecorr``). Default: False. With ``causal=True``: - both paths use backward kernels (``include_timepoints`` may be @@ -3047,7 +3080,8 @@ def features( correlations there, a summary 1, the shift null 40 rows of input. The fits do not change, bit for bit, whatever follows row ``n-1``. Every row is then reduced with them: row ``t >= n`` is - unchanged (to 1e-9; bit for bit under replacement) when rows after + unchanged (bit for bit; under removal with the built-in kernel + functions, see ``causal``) when rows after ``t`` are replaced or removed, and a row ``t < n`` (in sample: the fits have read rows after it) when rows from ``n`` on are replaced or removed. ``n`` equal to the number of timepoints fits on every @@ -3067,7 +3101,27 @@ def features( the rows it is given together). A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended - for the components beyond them), as without ``causal``. + up to ``ndims``), whatever the number of training + rows; the number asked for is ``n_components`` given with the + model (in its ``kwargs``, or of a model object; it decides + whether a model is fitted and the width of a fitted model's + output, not the number of zero columns: the widths are those of + the call without ``causal``), otherwise ``ndims``. Asked for + fewer components than columns + but more than there are defined training rows, a model is fitted + with as many components as those rows, and zero columns are + appended for the others, with a warning. + ``"FastICA"`` (when it is fitted: asked for fewer components than + columns) is given the columns that vary over the training rows + first and is asked for no more components than the rank of the + centered training rows (zero columns are appended for the + others, with a warning; ``ValueError`` when no column varies): + scikit-learn sets the sign of a component from its loading on + the first column, which for vectorized correlations is a + diagonal entry, 1 in every row, and the fit held NaN where that + loading was exactly 0; and it divides by the singular values of + the rows, so a component beyond their rank did not reproduce the + training rows. ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for large inputs does not reproduce its diff --git a/timecorr/model.py b/timecorr/model.py index 8693b32b..c5ff91a3 100644 --- a/timecorr/model.py +++ b/timecorr/model.py @@ -281,7 +281,7 @@ def _match_model(new, previous, order, path): signs = np.where(cosine[source, np.arange(c)] < 0, -1.0, 1.0) if np.array_equal(source, np.arange(c)) and np.all(signs > 0): return new - matched = _FittedModel(new.model, new.n_features, new.pad) # a copy + matched = _FittedModel(new.model, new.n_features, new.pad, new.order) # a copy if matched.model is new.model: # (a model that cannot be pickled, as one of a class defined in a # function, was taken as it is: reorder a copy, not the fit itself) @@ -298,7 +298,7 @@ def _match_model(new, previous, order, path): setattr(estimator, _COLUMN_PER_COMPONENT, np.ascontiguousarray(value[:, source] * signs)) # as a pickle restores it, like every fitted model (see _FittedModel) - matched = _FittedModel(matched.model, new.n_features, new.pad) + matched = _FittedModel(matched.model, new.n_features, new.pad, new.order) if new.constants is not None: columns, means, tol = (np.array(v) for v in new.constants) real = columns < c @@ -765,9 +765,9 @@ def transform(self, data, return_delta=False, return_info=False, *, events=None) Every row is computed causally, as by the ``features`` call that made the model: row ``t`` of every output uses rows ``0..t`` of - ``data`` and the frozen fits only, so it is unchanged (to 1e-9 for - features built from correlations; see ``features``) when later rows - are replaced or removed, and + ``data`` and the frozen fits only, so it is unchanged (bit for + bit; under removal with the built-in kernel functions, see + ``features``) when later rows are replaced or removed, and ``transform`` of the data of the fit returns what that call returned. diff --git a/timecorr/timecorr.py b/timecorr/timecorr.py index 5b13df2e..70c4a6a2 100644 --- a/timecorr/timecorr.py +++ b/timecorr/timecorr.py @@ -30,6 +30,8 @@ _check_causal_kernel, _check_min_samples, _check_rfun, + _group_span, + _GUARANTEED_MODELS, _lag_kernel, _warn_user, autofc, @@ -73,29 +75,42 @@ def _causal_smooth(x, weights, min_samples): observed = np.where(valid, x, 0.0) valid = valid.astype(np.float64) out = np.full(observed.shape, np.nan) - for t0, t1, c0, c1, _, w in blocks(as_kernel(weights), CHUNK, _abs_weights): + for t0, t1, c0, c1, _, block in blocks(as_kernel(weights), CHUNK, _abs_weights): if c1 <= c0: continue + # the chunk with the shapes of a chunk of a series without an end + # (rows of zero weight after the last row, columns of zeros after + # the last timepoint), so that the operations that give a row do + # not depend on the number of rows after it + # (a kernel array's chunk spans every column: those after the + # chunk's last row have no weight and are left out) + k = t1 - t0 + end = t0 + CHUNK + m = min(c1, end) - c0 + w = np.zeros((CHUNK, end - c0)) + w[:k, :m] = block[:, :m] + c1 = end # each row scaled by its largest weight, so squares do not underflow peak = w.max(axis=1, keepdims=True, initial=0.0) with np.errstate(invalid="ignore"): w = np.divide(w, peak, out=np.zeros_like(w), where=peak != 0) - den = w @ valid[c0:c1] + den = w @ _group_span(valid, c0, c1) defined = den > 0 # the chunk's samples are centered on its first row's weighted # mean (of samples that row weights: none after it), so the # round-off of the sums is relative to the variation of the # data, not to its level first = np.zeros(den.shape[1]) - np.divide(w[0] @ observed[c0:c1], den[0], out=first, where=defined[0]) - centered = observed[c0:c1] - first - centered *= valid[c0:c1] + np.divide(w[0] @ _group_span(observed, c0, c1), den[0], out=first, + where=defined[0]) + centered = _group_span(observed, c0, c1) - first + centered *= _group_span(valid, c0, c1) num = w @ centered if min_samples is not None: - ess = np.divide(den**2, (w * w) @ valid[c0:c1], + ess = np.divide(den**2, (w * w) @ _group_span(valid, c0, c1), out=np.zeros_like(den), where=defined) defined &= ess >= min_samples * (1 - _MIN_SAMPLES_RTOL) - np.divide(num, den, out=out[t0:t1], where=defined) + np.divide(num[:k], den[:k], out=out[t0:t1], where=defined[:k]) out[t0:t1] += first undefined = np.isnan(out).any(axis=1) if undefined.any(): @@ -506,8 +521,8 @@ def _fit_reducer(corrs, rfun, ndims=None, *, order=None, path=None, append_fit=F # linear map of each row. A fitted estimator is one of them by its exact # class: a subclass can pass every probe of ``_fit_reducer`` (they reduce # training rows only) and still reduce a row differently with later rows. -_GUARANTEED_MODELS = ("PCA", "IncrementalPCA", "TruncatedSVD", "FastICA", - "FactorAnalysis") +# (the tuple is defined in helpers, whose _FittedModel reduces them in +# batches of a fixed number of rows) _GUARANTEED_TEXT = ( f"scikit-learn's {', '.join(_GUARANTEED_MODELS[:-1])} and " f"{_GUARANTEED_MODELS[-1]}, by exact class: a subclass is not one" @@ -885,26 +900,32 @@ def timecorr( raise ``ValueError``. Default: None. causal : bool True: row ``t`` of the output uses no sample after timepoint ``t``. - It is unchanged (to 1e-9) when the rows after ``t`` are replaced by - any values, NaN and inf included, or removed; with + It is unchanged when the rows after ``t`` are replaced by any + values, NaN and inf included, or removed; with ``include_zero=False`` also when row ``t`` itself changes. Replacing later rows changes no bit, with every supported ``rfun``. - Removing them changes the correlations by round-off, so the - outputs agree to 1e-9 where they depend continuously on the - correlations (no reduction, ``"strength"``, the summaries, and - linear models such as PCA once fitted); the eigenvector-based - graph measures (``"eigenvector_centrality"``, the PageRank - measures) can differ by more at a correlation matrix whose leading - eigenvalues coincide, and the t statistics of ``tstat_combine``, - which divide by the spread of the subjects' correlations, where - that spread is close to zero (always with two subjects and - ``isfc``: their correlations are the same), to about 1e-9 of - their magnitude instead. Smoothed values (``cfun=None``) are on the - scale of the data, not bounded like correlations: when later rows - are removed they agree to round-off relative to the magnitude of - the data, that is to 1e-9 or 8 units in the last place of the - largest magnitude of the data, whichever is larger (1.2e-7 for - data near 1e8); replacement still changes no bit. Keyword only. + With the built-in kernel functions, removing them changes no bit + either (every ``rfun`` and ``combine`` function and ``cfun=None`` + included): a row is computed with the same operations whatever + the length of the series (tested, also in configurations drawn at + random, not proven: it holds when the linear-algebra library + computes a row of a matrix product of a given shape from that + row's operands alone). With a kernel function of your own the + columns of a chunk of kernel rows are found from its weights and + can depend on the length; removal is then documented to 1e-9 + where the outputs depend continuously on the correlations (no + reduction, ``"strength"``, the summaries, and linear models such + as PCA once fitted); the eigenvector-based graph measures + (``"eigenvector_centrality"``, the PageRank measures) can then + differ by more at a correlation matrix whose leading eigenvalues + coincide, and the t statistics of ``tstat_combine``, which divide + by the spread of the subjects' correlations, where that spread is + close to zero, agree to about 1e-9 of their magnitude instead; + smoothed values (``cfun=None``), which are on the scale of the + data, then agree to round-off relative to the magnitude of the + data, that is to 1e-9 or 8 units in the last place of the largest + magnitude of the data, whichever is larger (1.2e-7 for data near + 1e8). Keyword only. Default: False. With ``causal=True``: - the kernel is backward: ``include_timepoints`` 'all' (the @@ -976,7 +997,8 @@ def timecorr( It is fitted to the correlations of rows ``0..n-1`` that are defined (not NaN: see ``min_samples``; a model needs 2 such rows, a summary 1) and then reduces every row, so row ``t >= n`` is - unchanged (to 1e-9; bit for bit under replacement) when rows after + unchanged (bit for bit; under removal with the built-in kernel + functions, see ``causal``) when rows after ``t`` are replaced or removed, and a row ``t < n`` when rows from ``n`` on are. ``n`` equal to the number of timepoints fits on every row. A model must be a linear map applied to each row by itself. @@ -998,7 +1020,26 @@ def timecorr( some of them depends on the rows it is given together). A model asked for as many components as its input has columns, or more, changes nothing (zero columns are appended - for the components beyond them), as without ``causal``. + for the components beyond them), whatever the number of training + rows; the number asked for is ``n_components`` given with the + model (in its ``kwargs``, or of a model object; the output then + has the columns of the input and no zero columns, as without + ``causal``), otherwise the number of features. Asked for fewer + components than columns + but more than there are defined training rows, a model is fitted + with as many components as those rows, and zero columns are + appended for the others, with a warning. + ``"FastICA"`` (when it is fitted: asked for fewer components than + columns) is given the columns that vary over the training rows + first and is asked for no more components than the rank of the + centered training rows (zero columns are appended for the + others, with a warning; ``ValueError`` when no column varies): + scikit-learn sets the sign of a component from its loading on + the first column, which for vectorized correlations is a + diagonal entry, 1 in every row, and the fit held NaN where that + loading was exactly 0; and it divides by the singular values of + the rows, so a component beyond their rank did not reproduce the + training rows. ``"PCA"`` is fitted with ``svd_solver="full"`` unless a model dict gives a solver, because the randomized solver scikit-learn chooses for