---
file_format: mystnb
kernelspec:
  name: python3
---

(z_score)=
# Z-Score

The Z-Score detrending is a standard score that measures the number of standard deviations a data point is from the mean. It is calculated as:

$$Z = \frac{X - \mu}{\sigma}$$

where $X$ is the data point, $\mu$ is the mean, and $\sigma$ is the standard deviation.

```python
from delaynet.detrending_methods import z_score

# Apply Z-Score detrending
detrended_ts = z_score(time_series)

# Apply Z-Score detrending with periodicity
detrended_ts = z_score(time_series, periodicity=24, max_periods=7)
```

The Z-Score detrending in `delaynet` can take into account the periodicity of the time series. This is useful for data with seasonal patterns, such as daily or weekly cycles. The `periodicity` parameter specifies the number of time steps in one period, and the `max_periods` parameter limits the number of periods to consider before and after the current value.

```{code-cell}
:tags: [hide-input]
import delaynet as dn
from numpy.random import default_rng
import matplotlib.pyplot as plt

# Generate fMRI data for a single node
fmri_data = dn.preparation.data_generator.gen_fmri(
    ts_len=1000,               # Length of time series
    downsampling_factor=2,     # Downsampling factor
    time_resolution=0.2,       # Time resolution
    coupling_strength=2.0,     # Coupling strength
    noise_initial_sd=1.0,      # Standard deviation of initial noise
    noise_final_sd=0.1,        # Standard deviation of final noise
    rng=default_rng(25968)     # Random number generator seed
)[:, 0]

plt.figure(figsize=(10, 5), dpi=300)
plt.plot(fmri_data, label='Original FMRI Data')
plt.title('Original and Z-Score Detrended FMRI Data')
plt.plot(dn.detrending_methods.z_score(fmri_data, periodicity=40), label='Z-Score Detrended FMRI Data with Periodicity=40')
plt.plot(dn.detrending_methods.z_score(fmri_data, periodicity=40, max_periods=3), label='Periodicity=40 + max periods=3')
plt.legend()
plt.ylim(-5, 5)
plt.grid()
plt.show()
```

(link_to_method)=
```{eval-rst}
.. automethod:: delaynet.detrending_methods.z_score
    :noindex:
```
