# index.html.md # OSL Dynamics A Python toolbox for studying dynamic functional brain networks in M/EEG and fMRI data: from raw recordings to parcel time courses, generative models of network dynamics, and statistical significance testing. Install from conda-forge or PyPI, and check your GPU is working. A quick introduction: a typical workflow and a short example. Each stage of an analysis on real data, as scripts and notebooks you can download. Preprocessing, coregistration, source reconstruction, parcellation and sign flipping. The HMM, DyNeMo and other generative models for dynamic brain networks. GLM permutation tests with maximum statistic, cluster-based and TFCE corrections. The brain parcellations available in osl-dynamics. Common questions on preparing data, training models and post-hoc analysis. Every class and function, with its parameters. If you find this toolbox useful, please cite: > Gohil, C., Huang, R., Roberts, E., van Es, M. W., Quinn, A. J., Vidaurre, D., & Woolrich, M. W. (2024). [osl-dynamics, a toolbox for modeling fast dynamic brain activity](https://elifesciences.org/articles/91949). *eLife*, 12, RP91949. # faq.html.md # Frequently Asked Questions (FAQ) > * [Installation](faq.html.md#installation) > * [Do I need a GPU?](faq.html.md#do-i-need-a-gpu) > * [How do I use a GPU?](faq.html.md#how-do-i-use-a-gpu) > * [Data](faq.html.md#data) > * [How do I optimally preprocess my data for training an HMM or DyNeMo?](faq.html.md#how-do-i-optimally-preprocess-my-data-for-training-an-hmm-or-dynemo) > * [Can I use a structural parcellation (e.g. the AAL or Desikan-Killiany atlas)?](faq.html.md#can-i-use-a-structural-parcellation-e-g-the-aal-or-desikan-killiany-atlas) > * [Why do I need to sign flip my data before training a model?](faq.html.md#why-do-i-need-to-sign-flip-my-data-before-training-a-model) > * [Do I need to prepare my data before training a model?](faq.html.md#do-i-need-to-prepare-my-data-before-training-a-model) > * [What is time-delay embedding?](faq.html.md#what-is-time-delay-embedding) > * [How does the choice of number of lags (embeddings) affect the model when doing time-delay embedding?](faq.html.md#how-does-the-choice-of-number-of-lags-embeddings-affect-the-model-when-doing-time-delay-embedding) > * [Why doesn’t the number of time points in my inferred alphas match the original data?](faq.html.md#why-doesn-t-the-number-of-time-points-in-my-inferred-alphas-match-the-original-data) > * [I run out of memory when training a model. What can I do?](faq.html.md#i-run-out-of-memory-when-training-a-model-what-can-i-do) > * [How do I make training reproducible?](faq.html.md#how-do-i-make-training-reproducible) > * [Modeling](faq.html.md#modeling) > * [What is the Hidden Markov Model (HMM)?](faq.html.md#what-is-the-hidden-markov-model-hmm) > * [What is Dynamic Network Modes (DyNeMo)?](faq.html.md#what-is-dynamic-network-modes-dynemo) > * [What is Dynamic Network States (DyNeStE)?](faq.html.md#what-is-dynamic-network-states-dyneste) > * [What is Multi-Dynamic Network Modes (M-DyNeMo)?](faq.html.md#what-is-multi-dynamic-network-modes-m-dynemo) > * [What is HIVE (HMM with Integrated Variability Estimation)?](faq.html.md#what-is-hive-hmm-with-integrated-variability-estimation) > * [What model should I use?](faq.html.md#what-model-should-i-use) > * [What is the difference between training on amplitude envelope (AE) and time-delay embedded (TDE) data?](faq.html.md#what-is-the-difference-between-training-on-amplitude-envelope-ae-and-time-delay-embedded-tde-data) > * [What are hyperparameters?](faq.html.md#what-are-hyperparameters) > * [How do I choose what hyperparameters to use?](faq.html.md#how-do-i-choose-what-hyperparameters-to-use) > * [I have trained a model with the same hyperparameters on the same data multiple times, why do I get a different value for the final loss (cost function)?](faq.html.md#i-have-trained-a-model-with-the-same-hyperparameters-on-the-same-data-multiple-times-why-do-i-get-a-different-value-for-the-final-loss-cost-function) > * [How can I handle run-to-run variability in the networks (states/modes)?](faq.html.md#how-can-i-handle-run-to-run-variability-in-the-networks-states-modes) > * [How do I select the optimum number of HMM states or DyNeMo modes?](faq.html.md#how-do-i-select-the-optimum-number-of-hmm-states-or-dynemo-modes) > * [Is there a recommended default initialization for each model?](faq.html.md#is-there-a-recommended-default-initialization-for-each-model) > * [Can I do static analysis with this package?](faq.html.md#can-i-do-static-analysis-with-this-package) > * [Can I use this package with task data?](faq.html.md#can-i-use-this-package-with-task-data) > * [Can I train an HMM/DyNeMo on EEG data?](faq.html.md#can-i-train-an-hmm-dynemo-on-eeg-data) > * [I’ve encountered a NaN when I tried to train a model? Why did this happen and how can I fix it?](faq.html.md#i-ve-encountered-a-nan-when-i-tried-to-train-a-model-why-did-this-happen-and-how-can-i-fix-it) > * [Why is my loss function increasing when I train a DyNeMo model?](faq.html.md#why-is-my-loss-function-increasing-when-i-train-a-dynemo-model) > * [Post-Hoc Analysis](faq.html.md#post-hoc-analysis) > * [What are the most important summary statistics to use?](faq.html.md#what-are-the-most-important-summary-statistics-to-use) > * [How does the multitaper spectrum calculation work?](faq.html.md#how-does-the-multitaper-spectrum-calculation-work) > * [How does the regression spectrum calculation work?](faq.html.md#how-does-the-regression-spectrum-calculation-work) > * [Statistical Significance Testing](faq.html.md#statistical-significance-testing) > * [Which correction for multiple comparisons should I use?](faq.html.md#which-correction-for-multiple-comparisons-should-i-use) > * [How many permutations do I need?](faq.html.md#how-many-permutations-do-i-need) > * [Why is my smallest p-value 0.001 (or 1 / (n_perm + 1))?](faq.html.md#why-is-my-smallest-p-value-0-001-or-1-n-perm-1) > * [What does a significant cluster mean?](faq.html.md#what-does-a-significant-cluster-mean) > * [Should I test copes or t-statistics?](faq.html.md#should-i-test-copes-or-t-statistics) > * [How do I compare more than two groups?](faq.html.md#how-do-i-compare-more-than-two-groups) > * [How do I compare several conditions measured in the same subjects?](faq.html.md#how-do-i-compare-several-conditions-measured-in-the-same-subjects) > * [How do I report the size of an effect?](faq.html.md#how-do-i-report-the-size-of-an-effect) > * [How do I account for age, sex or other confounds?](faq.html.md#how-do-i-account-for-age-sex-or-other-confounds) > * [My summary statistics contain NaNs. What happens?](faq.html.md#my-summary-statistics-contain-nans-what-happens) > * [How do I make the permutations reproducible?](faq.html.md#how-do-i-make-the-permutations-reproducible) > * [Other](faq.html.md#other) > * [How do I control what osl-dynamics prints?](faq.html.md#how-do-i-control-what-osl-dynamics-prints) > * [I found a bug, what do I do?](faq.html.md#i-found-a-bug-what-do-i-do) If you have a question that’s not listed below, please open an issue on the [GitHub](https://github.com/OHBA-analysis/osl-dynamics/issues). ## Installation ### Do I need a GPU? No, osl-dynamics can be used solely on CPUs, however, using the package on a computer with a GPU will be much faster (you can expect a speed up of ~10x). The GPU use in osl-dynamics is via the TensorFlow package, which is used to create and train the models (HMM, DyNeMo, etc). GPUs are not used in the post-hoc analysis. ### How do I use a GPU? GPU use in this package is via the [TensorFlow](https://www.tensorflow.org) package. GPUs can only be used with GPU-enabled installations of TensorFlow. Whether you’re able to install a GPU-enabled version of TensorFlow depends on your computer (hardware and operating system). The TensorFlow installation [webpage](https://www.tensorflow.org/install/pip) describes how to install TensorFlow with GPU support for various operating systems. If you’re able to install a GPU-enabled version of TensorFlow via the instructions on this website, you will automatically use any GPUs you have. Note for MacOS users, there’s no official TensorFlow package in pip which supports GPU use. You may need to install tensorflow-metal following the instructions [here](https://developer.apple.com/metal/tensorflow-plugin/) to take advantage of your hardware. ## Data ### How do I optimally preprocess my data for training an HMM or DyNeMo? For electrophysiological data we have found preprocessing the sensor-level data by downsampling to 250 Hz and bandpass filtering 1-45 Hz works well. Additionally, we do some bad segment detection based on the variance of non-overlapping windows. Following this, we use a volumetric linearly constrained minimum variance (LCMV) beamformer to estimate source space data. Usually the beamformed (voxel) data is parcellated to ~50 regions of interest and an orthogonalization technique is used to correct for spatial leakage. Additionally, the sign of parcel time courses is adjusted to align different subjects. All of these steps can be done directly within osl-dynamics, see the [MEG Preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md) for a step-by-step walkthrough and the [batch processing scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_preproc) for processing multiple sessions in parallel. Alternatively, the [osl-ephys](https://github.com/OHBA-analysis/osl-ephys) package can also be used for these steps. The OSL workshop had a session on dynamic network modeling. The OSF project hosting workshop materials ([here](https://osf.io/zxb6c/)) has jupyter notebooks with recommended preprocessing and source reconstruction for fitting the HMM/DyNeMo. ### Can I use a structural parcellation (e.g. the AAL or Desikan-Killiany atlas)? Yes, you can. There’s nothing stopping you from using the parcellation you want during source reconstruction. Source reconstruction and parcellation can be done directly within osl-dynamics, see the [MEG Preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md). Alternatively, the [osl-ephys](https://github.com/OHBA-analysis/osl-ephys) package can also be used. You want the number of parcels to be a good amount less than the rank of the sensor space data in order to estimate your parcel time courses well. The rank is at most equal to the number of sensors you have. With Maxfiltered data (e.g. Elekta/MEGIN data), the default rank of the sensor data is ~64, and so it is sensible to require the number of parcels to be less than 64. Even with non-maxfiltered data with hundreds of sensors (e.g. CTF, OPMs) the effective amount of information in the sensor data typically corresponds to a rank of about 100. You can look at the eigenspectrum of your sensor space data to check this. Also note, the requirement to have the number of parcels less than the rank is an absolute requirement if you are using the recommended **symmetric orthogonalization** approach on the parcel time courses to correct for spatial leakage. This is not a deficiency of the symmetric orthogonalization approach but reflects the rank needed to use this more complete spatial leakage correction (it removes so-called inherited or ghost interactions as well) while still being able to estimate parcel time courses unambiguously. ### Why do I need to sign flip my data before training a model? The sign of the off-diagonal elements in the covariance matrix of source reconstructed M/EEG data may not be the same across sessions. I.e. channels i and j maybe positively correlated for one session but negatively correlated for another. The sessions can be aligned by flipping the sign of channel i or j for one of the sessions. This is the ‘sign flipping’. This is important because the HMM/DyNeMo models dynamic changes in the covariance of the data, we do not want dynamics in the covariance simply due to misaligned signs. Note, the sign ambiguity is an identifiability problem in the source reconstruction of M/EEG that cannot be avoided. ### Do I need to prepare my data before training a model? No, strictly speaking you don’t need to prepare your data before training a model. However, you are much more likely to infer a reasonable description of your data if you follow a pipeline that has previously been shown to work. **Therefore, it is recommended that you prepare the data**. There are three common choices for preparing the data: 1. **Just standardize**. Here, all we do is z-score the data (subtract the mean and divide by the standard deviation for each channel individually). Standardization is helpful for the optimization process used to train the models in osl-dynamics. **This is the recommended approach for studying sensor-level M/EEG data or fMRI data**. 2. **Calculate time-delay embedded data, followed by principal component analysis and standardization**. Time-delay embedding is described in the ‘What is time-delay embedding?’ section below. **This is the recommended approach for studying source-space M/EEG data**. 3. **Calculate amplitude envelope data and standardize**. This is common approach for overcoming the dipole sign ambiguity problem in MEG, where the sign of source reconstructed channels can be misaligned cross different subjects or sessions. Here, we apply a Hilbert transform to the ‘raw’ data and apply a short sliding window to smooth the data. This was an approach that was previously common. Nowadays, time-delay embedding is preferred. The [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md) and [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md) tutorials cover how to prepare data. ### What is time-delay embedding? Time-Delay Embedding (TDE) involves adding extra channels containing time-lagged versions of the original data: - For each channel you shift the time series by a fixed amount (forwards or backwards) and add it as an extra channel to the time series data. - You do this for a pre-specified number of lags. **Typically, we use lags of -7,-6,…,6,7** (equivalent to `n_embeddings=15`). This results in an extra 14 channels being added for each original channel. E.g. if you originally had 10 channels and added ±7 lags, you would end up with a time series with 150 channels. The purpose of TDE is to encode spectral (frequency-specific) information in the covariance matrix of the data. The covariance matrix of the TDE data has additional off-diagonal elements which corresponds to the auto-correlation function (this characterizes the spectral properties of the original data). TDE is useful when we want to model transient spectral properties in the data. Usually adding the extra channels results in a very high-dimensional time series, so we typically also apply principal component analysis for dimensionality reduction. **We recommend reducing down to at least twice the number of original channels**. Also see: [Time-Delay Embedding](tutorials_build/1-4_data_time_delay_embedding.html.md). ### How does the choice of number of lags (embeddings) affect the model when doing time-delay embedding? See the ‘What is time-delay embedding’ question for a description of what happens when we perform time-delay embedding (TDE). A choice we have to make is how many lagged versions of each channel we add. The number of lagged channels we add (i.e. the number of embeddings) determines how many points in the auto-correlation function (and therefore power spectrum) we encode into the covariance matrix of the data. I.e. if we include more embeddings, we add more off-diagonal elements into the covariance matrix, which corresponds to specifying more data points in the auto-correlation function and therefore power spectrum. In other words, having more embeddings allows you to be more sensitive to oscillations in your data. The number of embeddings should be chosen for a particular sampling frequency. See the [Time-Delay Embedding tutorial](tutorials_build/1-4_data_time_delay_embedding.html.md) for example code comparing different TDE settings. We recommend 15 embeddings for 250 Hz data and 7 embeddings for 100 Hz data. Note, both of these correspond to an embedding window of roughly 60-70 ms. If your data has a different sampling frequency, choosing `n_embeddings` to give a similar window duration (i.e. `n_embeddings / sampling_frequency` of roughly 60 ms) is a good starting point. ### Why doesn’t the number of time points in my inferred alphas match the original data? The process of preparing the data before training a model can lead to the loss a data points at the start and end of the time series. This occurs when we perform: - Time-delay embedding. Here, we lose `n_embeddings // 2` data points from each end of the time series because we don’t have the necessary lagged data points before and after the time series to specify the value for each channel. - Smoothing after a Hilbert transform. When we prepare amplitude envelope data, we usually apply a smoothing window. The length of the window is specified using the `n_window`. When we smooth the data with the window we lose `n_window // 2` data points from each end of the time series. Note, we have a separate time series for each subject, so we lose these data points from each subject separately. In addition to the data point lost above, before we train a model we divide the time series into sequences. We lose the data points **at the end** that do not form a complete sequence. Note, you can trim data using the `Data.trim_time_series` method, example use: ```default from osl_dynamics.data import Data data = Data(...) data = data.trim_time_series(n_embeddings=..., sequence_length=...) ``` By default this will return a trimmed version of the prepared data. Pass `prepared=False` to get the trimmed original data. ### I run out of memory when training a model. What can I do? First check whether it is the GPU or the RAM that runs out. A GPU out of memory error (`ResourceExhaustedError`) is fixed by reducing the `batch_size` or `sequence_length` in the model’s Config. If it is the RAM, the Data object is holding the whole dataset in memory. Save the prepared data as a TFRecord dataset with `Data.save_tfrecord_dataset` and load it with `osl_dynamics.data.load_tfrecord_dataset`, which streams the data from disk. Alternatively, pass `load_memmaps=True` when creating the Data object to keep the data on disk as memory maps. See the Training on large datasets section of the [HMM training tutorial](tutorials_build/3-2_hmm_training.html.md). The initialization can also be done on a subset of the data by passing `take` (e.g. `take=0.25`) to `random_state_time_course_initialization`. The starting parameters of each initialization are set from a few batches of data (`n_batches=20` by default), so this step is quick even on a large dataset. ### How do I make training reproducible? Call `osl_dynamics.utils.set_random_seed(seed)` before building the model. This seeds Python, NumPy and TensorFlow, which covers the initialization (random subsets, sampled state time courses), the shuffling of the training data and the model weights. Training on a GPU can still differ slightly between runs because some TensorFlow operations are non-deterministic; pass `op_determinism=True` to make them deterministic at the cost of speed. ## Modeling ### What is the Hidden Markov Model (HMM)? See the model description page [here](user_guide/models/hmm.html.md). ### What is Dynamic Network Modes (DyNeMo)? See the model description page [here](user_guide/models/dynemo.html.md). ### What is Dynamic Network States (DyNeStE)? See the model description page [here](user_guide/models/dyneste.html.md). ### What is Multi-Dynamic Network Modes (M-DyNeMo)? See the model description page [here](user_guide/models/mdynemo.html.md). ### What is HIVE (HMM with Integrated Variability Estimation)? See the model description page [here](user_guide/models/hive.html.md). ### What model should I use? See the [Choosing a Model](user_guide/models/index.html.md#choosing-a-model) table on the Models page, which compares the models and when to use each. ### What is the difference between training on amplitude envelope (AE) and time-delay embedded (TDE) data? Both calculating the AE and TDE are referred to as ‘data preparation’ options. See the ‘Do I need to prepare my data before training a model?’ question for a description of how AE and TDE data is calculated. The models in osl-dynamics (HMM and DyNeMo) aim to describe dynamics in the first and second order statistics of the data, i.e. the mean vector and covariance matrix respectively. We calculate AE or TDE data to ensure the mean and covariance of the data contains dynamics we’re interested in. For example, if we are interested in modeling transient events of high amplitude, we can calculate the AE of our original data and fit an HMM learning the mean vector for multiple states. This will help the HMM find states that have differences in the mean amplitude. If we are interested in modeling transient bursts of oscillations (spectral events), we can train on TDE data. Each oscillatory burst will have a unique covariance matrix (oscillations at different frequencies will affect the value of off-diagonal elements in the covariance of TDE data). This will help the HMM find states that have different oscillatory behavior. Note, when we train on TDE data, because the differences we want to model are reflected in the covariance of the data, we don’t need to model the state means (we can just fix them to zero). Whereas, when we train on AE data, the differences we want to model are contained in the mean, so we learn the state means. Also note, once we have inferred a latent description, such as HMM states or DyNeMo modes, we can go back to the original unprepared data (i.e. before the AE/TDE) and re-estimate properties of this time series based on the inferred latent description. This is what’s done when we estimate post-hoc spectra, see the ‘Spectral Analysis’ section in the model descriptions: [HMM](user_guide/models/hmm.html.md) and [DyNeMo](user_guide/models/dynemo.html.md). ### What are hyperparameters? There are two types of parameters in osl-dynamics models: - **Model parameters**. These are parameters that are part of the generative model. These are learnt from the data. E.g. for the HMM, this is the state time course, state means and covariances. - **Hyperparameters**. These are pre-specified parameters that are not learnt from the data. These are the parameters specified in the `Config` object used to create a model. E.g. the number of states/modes, sequence length, batch size, etc. are hyperparameters. ### How do I choose what hyperparameters to use? Unfortunately, many modern machine learning models come with hyperparameters (parameters that are not part of the generative model) which need to be pre-specified. The best approach is to try and few combinations and do the following: - Make sure any conclusions are robust to the choice of hyperparameters. - Use the variational free energy (see the [model descriptions](user_guide/models/index.html.md)) to compare models. Preferably, the variational free energy would be calculated on a hold out validation dataset, which is not used for training. The [`config API`](autoapi/osl_dynamics/config_api/index.html.md#module-osl_dynamics.config_api) has wrapper functions for training an [`HMM`](autoapi/osl_dynamics/config_api/wrappers/train_hmm.html.md#osl_dynamics.config_api.wrappers.train_hmm) or [`DyNeMo`](autoapi/osl_dynamics/config_api/wrappers/train_dynemo.html.md#osl_dynamics.config_api.wrappers.train_dynemo), which pre-specify hyperparameters that have worked well in the past. These might be a good place to start. ### I have trained a model with the same hyperparameters on the same data multiple times, why do I get a different value for the final loss (cost function)? Many modern machine learning models have a problem of **local optima**. When we train a model on complex and noisy data there may be multiple values for the model parameters (see the ‘What are hyperparameters?’ question for the definition of ‘model parameters’) that can lead to similar values for the **cost function**. In our case, the cost function is the **variational free energy** (see the [HMM description](user_guide/models/hmm.html.md) for further details). Additionally, different final values for the cost function can occur due to different initial values for the model parameters and the stochasticity in updating the model parameters during training. Unfortunately, there is no solution to this. With more data this becomes less of a problem. The recommendation is to train a model multiple times and select the model with the best (lowest) variational free energy for further analysis. Preferably the variational free energy would be calculated using a hold out validation dataset rather than the training data. However, it is common just to compare the variational free energy on the training dataset. Different runs can also find different networks (states/modes). See the next question for an alternative way of choosing a run based on the networks it found. ### How can I handle run-to-run variability in the networks (states/modes)? Training a model multiple times on the same data can give different networks: the states/modes come out in a different order and, where the data do not constrain the solution well, some networks can be split or combined differently from run to run. Selecting the run with the lowest variational free energy (see the previous question) is a good default. However, the free energies of different runs are often very similar, in which case the lowest free energy does not tell us which solution the model finds most often. An alternative is to choose a run based on the networks the runs found: 1. Train the model multiple times (e.g. 10-20 runs). 2. Describe each state/mode by its power map, which can be calculated directly from the state/mode covariances (using `osl_dynamics.analysis.post_hoc.raw_covariances` for time-delay embedded data). 3. Group the states/modes of all runs into networks with `osl_dynamics.inference.modes.match_runs`. This also tells us how many runs each network is found in, which is a useful measure of how reproducible each network is. 4. Group runs that found the same set of networks into families with `osl_dynamics.inference.modes.run_families`, and analyze the most typical run (the medoid) of the largest family. If the largest families are equally large, choose the one with the lowest median free energy. `osl_dynamics.inference.modes.select_run` does all of these steps. This selects a run that is representative of the solution the model finds most often. The choice is only as reliable as the family sizes, so train enough runs (e.g. 20) for the most common solution to stand out. It can be used with the HMM and DyNeMo. See [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md) for an example. ### How do I select the optimum number of HMM states or DyNeMo modes? Unfortunately, the number of states/modes in the HMM/DyNeMo needs to be pre-specified. Theoretically, when we do Bayesian inference we can use the **model evidence** to compare models (this include models that differ in terms of the number of states/modes). However, we find with electrophysiological data that the model evidence increases indefinitely with the number of states/modes (tested up to ~40 states/modes). I.e. the model evidence is telling us the optimum number of states/modes is above 40, more states/modes is better. However, using a very high number of states defeats the purpose of obtaining a low-dimensional and interpretable description of the data. **Therefore, we suggest using between 6-14 states/modes. 8 states/modes might be a good initial choice**. We find although this number of states/modes might not give the best description of the data from a Bayesian point of view, it still provides a useful description of the data. Also see the ‘How do I choose what hyperparameters to use?’ question. ### Is there a recommended default initialization for each model? As explained in ‘I have trained a model with the same hyperparameters on the same data multiple times, why do I get a different value for the final loss (cost function)?’, the final value for the cost function (model fit) can be sensitive to the initialization of your model parameters. To help with this model have methods to find good initial values for model parameters before doing the full training. The recommended initialization is different for different models. The recommendations are: - For the HMM use: ```default model.random_state_time_course_initialization(data, n_init=3, n_epochs=1) ``` - For DyNeMo use: ```default model.random_subset_initialization(data, n_init=5, n_epochs=2) ``` ### Can I do static analysis with this package? Yes! See the [static analysis tutorials](tutorials.html.md). ### Can I use this package with task data? Yes! the models contained in osl-dynamics can be applied to task data. **The recommended approach is to preprocess/prepare task data as if it is resting-state data and fit an HMM/DyNeMo to it as normal**. When you have inferred a state/mode time course you can then do post-hoc analysis using the task timings, e.g. by epoching the state/mode time course around an event. Also see: [Dynamic Network Analysis of Electrophysiological Task Data](https://github.com/OHBA-analysis/Gohil2024_NetworkAnalysisOfTaskData). ### Can I train an HMM/DyNeMo on EEG data? Yes! You can train the HMM/DyNeMo on sensor-level or source reconstructed EEG data. Note, the same preparation steps (see ‘Do I need to prepare my data before training a model?’) should be applied to the data irrespective of if it is MEG or EEG data. Also see: [Cho, et al. (2024)](https://onlinelibrary.wiley.com/doi/full/10.1002/hbm.70018). ### I’ve encountered a NaN when I tried to train a model? Why did this happen and how can I fix it? Models in osl-dynamics are trained using ‘stochastic gradient decent’. We believe the NaN values in the loss function arise from a bad update to the model parameters. A training step whose loss or gradients contain a NaN or inf is skipped: the model parameters are not updated and the batch is left out of the loss reported for the epoch. A warning is logged at the end of each epoch in which a step was skipped, and the number of skipped steps in each epoch is saved in the training history (`history["skipped_steps"]`). An occasional skipped step does not affect the model. Training only stops if every step in an epoch was skipped. If many steps are skipped, or training stops, there a few things you can do to help resolve this: - Check your data for any periods of consecutive zeros or NaNs. MaxFilter sets stretches of its output to zero when too many channels are bad; `osl_dynamics.meeg.preproc.detect_flat_segments` marks these as bad (run it before filtering). - Remove bad segments (with abnormally high variance). You can use `osl_dynamics.meeg.preproc.detect_bad_segments` to mark them in the M/EEG data before source reconstruction. - If you are loading fif files, make sure you have specified `Data(..., picks="...", reject_by_annotation="omit")` correctly. - Lower the learning rate and/or increase the batch size. ### Why is my loss function increasing when I train a DyNeMo model? The loss function we use for DyNeMo is the variational free energy: $$ \mathcal{F} = -LL + \eta KL $$ where $\eta$ is the ‘KL annealing factor’. This is a scalar that starts off at zero and increases to one as training progresses. At the start of training we suppress the KL term of the loss function (by setting $\eta$ to zero), which allows us to find the model that maximizes the likelihood (via minimizing the negative log-likelihood term, $-LL$). Then we slowly turn on the KL term by increasing $\eta$, this adds more of the KL term to the loss function which gives the apparent rise. This process is known as **KL annealing**. We typically use KL annealing for the first half of training (set using the `n_kl_annealing_epochs` hyperparameter). After `n_kl_annealing_epochs` of training have occurred then the model is using the full loss function (with $\eta=1$). If we are using early stopping we should make sure we’re only considering epochs after `n_kl_annealing_epochs`. ## Post-Hoc Analysis ### What are the most important summary statistics to use? It is common to look at four summary statistics for dynamics when using the HMM: - The **fractional occupancy**, which is the fraction of total time that is spent in a particular state. - The **mean lifetime**, which is the average duration of a state visit. This is also known as the ‘dwell time’. - The **mean interval**, which is the average duration between successive state visits. - The **switching rate**, which is the average number of visits to a state per second. Summary statistics can be calculated for individual subjects or for a group. See the [HMM Summary Statistics tutorial](tutorials_build/4-3_hmm_summary_stats.html.md) for example code of how to calculate these quantities. Often, we are interested in comparing two groups or conditions. E.g. we might find static alpha (8-12 Hz) power is increased for one group/condition. Let’s speculate there are segments in our data where alpha power bursts occur. This would be identified by the HMM as a state with high alpha power that only activates for particular segments. The increase in alpha power seen for a group/condition can arise in many ways, maybe the alpha bursts are longer in duration, maybe they’re more frequent, maybe the dynamics are unchanged but the alpha state just has more alpha power in it. The different summary statistics can potentially help interpret which of these options it is. Generally, it’s difficult to say whether or not one summary statistic is more important than another. The recommended approach is to calculate all four of the above as a summary of dynamics for each subject/group/condition. ### How does the multitaper spectrum calculation work? See the ‘Spectral Analysis’ section of the [HMM description](user_guide/models/hmm.html.md). ### How does the regression spectrum calculation work? See the [Spectral Analysis](user_guide/spectra.html.md) page, which also describes how to interpret and plot the regression spectra. ## Statistical Significance Testing ### Which correction for multiple comparisons should I use? Use the default maximum statistic (`correction="max_stat"`) for targets without a natural neighbourhood: states, parcels, connections and summary statistics. Use a cluster-based test (`"cluster"`) or TFCE (`"tfce"`) for effects that are extended along time or frequency, such as network responses and spectra. Use FDR (`"fdr"`) when you test very many targets (e.g. a connectivity matrix) and a small fraction of false positives is acceptable. See the [statistics page](user_guide/stats.html.md) for a table and the [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) for a comparison on the same data. ### How many permutations do I need? The p-value from $N$ random permutations is $(1 + b) / (N + 1)$, where $b$ is the number of permuted statistics at least as extreme as the observed one, so the smallest p-value you can get is $1 / (N + 1)$. Use at least 1000 permutations to report p < 0.01 and 10,000 for p < 0.001. The tests are fast (a few seconds for 1000 permutations on typical data), so there is little reason to use fewer. With few subjects every permutation is enumerated and the test is exact; `result.exact` tells you when this happened. ### Why is my smallest p-value 0.001 (or 1 / (n_perm + 1))? Because that is the resolution of a permutation test with `n_perm` permutations, see above. A permutation p-value can never be zero. Increase `n_perm` if you need smaller p-values. ### What does a significant cluster mean? That the data are not exchangeable under the null hypothesis, i.e. there is an effect somewhere, and the cluster points to where it is likely to be. It does not establish that the effect is present at every time point (or parcel) in the cluster, or that it starts and ends where the cluster does: the extent of a cluster depends on the signal-to-noise ratio, the number of subjects and the cluster-forming threshold. Report “a significant response, most pronounced between 100 and 300 ms”, not “a significant response from 100 to 300 ms”. See [Sassenhagen & Draschkow (2019)](https://doi.org/10.1111/psyp.13335). ### Should I test copes or t-statistics? The `metric` argument chooses the statistic whose maximum is taken across targets. T-statistics are the default and the right choice when the targets have different units or variances (e.g. fractional occupancies and lifetimes together). Copes (the raw effect, e.g. the mean response) are the default for [`evoked_response()`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response), where every target has the same units and the t-statistic can be unstable where the variance is near zero. The `hat` argument is another remedy for unstable t-statistics. Cluster-based tests always use t-statistics. ### How do I compare more than two groups? Pass all the group labels to [`group_diff()`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff). With three or more labels it runs an F-test (the GLM form of a one-way ANOVA, with permutations) for any difference between the groups. A significant F-test does not say which groups differ, so follow it with pairwise tests, `groups=(1, 2)` and so on, and correct for the number of pairs you report. For other questions, e.g. patients versus the mean of two control groups, write the contrast yourself with [`DesignConfig`](autoapi/osl_dynamics/stats/DesignConfig.html.md#osl_dynamics.stats.DesignConfig), see the [Custom Designs tutorial](tutorials_build/7-4_custom_designs.html.md). ### How do I compare several conditions measured in the same subjects? Use [`condition_diff()`](autoapi/osl_dynamics/stats/condition_diff.html.md#osl_dynamics.stats.condition_diff) with a `(subjects, conditions, ...)` array. It fits a within-subject GLM (an indicator per condition and per subject) and shuffles the conditions within each subject, so differences between subjects do not count as noise. With three or more conditions it runs an F-test for any difference, like a repeated measures ANOVA; `conditions=(a, b)` tests a pair. For two conditions, [`paired_diff()`](autoapi/osl_dynamics/stats/paired_diff.html.md#osl_dynamics.stats.paired_diff) on the difference gives the same result. ### How do I report the size of an effect? Call `result.effect_size()` on any test result. It returns the effect in the units of the data (the cope, e.g. the group difference), Cohen’s d for t-tests (the effect divided by the residual standard deviation, adjusted for covariates) or partial eta squared for F-tests, each with a confidence interval from a bootstrap over subjects. Report the effect size and its interval for the significant targets alongside the p-value. ### How do I account for age, sex or other confounds? Pass them as `covariates={"age": age, "sex": sex}` to any test. They are added to the GLM as nuisance regressors and regressed out; the permutations use the Freedman-Lane scheme so that the test remains valid with covariates. To test the effect of a covariate itself use [`regression()`](autoapi/osl_dynamics/stats/regression.html.md#osl_dynamics.stats.regression). ### My summary statistics contain NaNs. What happens? A mean lifetime or interval is undefined for a state a subject never visits. Each target is fitted with the subjects that have a value for it, so the subject is only dropped from that state’s test, and a warning reports how many subjects were dropped. Targets whose statistic is undefined (e.g. zero variance) get a NaN p-value. ### How do I make the permutations reproducible? Call [`osl_dynamics.utils.set_random_seed()`](autoapi/osl_dynamics/utils/set_random_seed.html.md#osl_dynamics.utils.set_random_seed) at the top of your script. The permutations are drawn from NumPy’s global random state. ## Other ### How do I control what osl-dynamics prints? osl-dynamics prints progress messages and progress bars. To only print warnings and errors, call: ```default import osl_dynamics osl_dynamics.set_verbosity("WARNING") ``` or set the environment variable `OSL_DYNAMICS_VERBOSITY=WARNING` before running a script. `"INFO"` is the default and `"DEBUG"` also shows where each message came from. Pass `verbose=0` to a model’s `fit`, `get_gamma` or `get_alpha` methods for no progress bars from that call. When training, `verbose=2` shows a single progress bar over the epochs instead of one for each epoch. Messages are printed by the `"osl-dynamics"` logger, so they can also be written to a file: ```default import logging logging.getLogger("osl-dynamics").addHandler(logging.FileHandler("osld.log")) ``` When the output is not a terminal or notebook (e.g. the log of a job on a cluster), progress bars are updated every 30 seconds. This can be changed with the `TQDM_MININTERVAL` environment variable. ### I found a bug, what do I do? Create an issue [here](https://github.com/OHBA-analysis/osl-dynamics/issues) or email [chetan.gohil@ndcn.ox.ac.uk](mailto:chetan.gohil@ndcn.ox.ac.uk). # getting_started.html.md # Getting Started This page provides a quick introduction to osl-dynamics. For installation instructions, see [Install](install/index.html.md). ## Overview osl-dynamics is a Python toolbox for studying dynamic brain networks from neuroimaging data (M/EEG and fMRI). It provides: - **M/EEG processing**: preprocessing, source reconstruction (LCMV beamformer) and parcellation (see [M/EEG Processing](user_guide/meeg.html.md)). - **Generative models** for inferring dynamic brain networks, e.g. the Hidden Markov Model (HMM) and Dynamic Network Modes (DyNeMo) (see [Models](user_guide/models/index.html.md)). - **Post-hoc analysis tools**: spectral analysis, summary statistics, and network visualization. - **Static analysis**: time-averaged power and connectivity analysis. - **Statistical testing**: GLM permutation tests for group and condition comparisons, network responses and regressions, with maximum statistic, cluster-based and TFCE corrections for multiple comparisons, and effect sizes with confidence intervals (see [Statistical Significance Testing](user_guide/stats.html.md)). - **Simulation tools**: for generating synthetic time series data. ## M/EEG Processing If you are starting from raw M/EEG data, osl-dynamics includes a full processing pipeline covering preprocessing, surface extraction, coregistration, source reconstruction (LCMV beamformer), and parcellation. The [M/EEG Processing](user_guide/meeg.html.md) page describes the steps and the software behind them. See the [MEG Preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md) for a step-by-step walkthrough, or the [batch processing scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_preproc) for running multiple sessions in parallel. ## A Typical Workflow Once you have parcellated source-space data (or fMRI data), a typical analysis follows these steps: 1. **Load data**: Load your parcellated (or sensor) M/EEG or fMRI data ([Data tutorials](tutorial_sections/data.html.md)). 2. **Prepare data**: Standardize, and optionally apply time-delay embedding (TDE) and PCA ([Data tutorials](tutorial_sections/data.html.md)). 3. **Train a model**: Fit an HMM, DyNeMo, or DyNeStE to infer dynamic brain states/modes ([Dynamic Modeling tutorials](tutorial_sections/dynamic_modelling.html.md)). 4. **Post-hoc analysis**: Estimate state/mode spectra, compute summary statistics, and visualize networks ([HMM](tutorial_sections/hmm_post_hoc.html.md) and [DyNeMo](tutorial_sections/dynemo_post_hoc.html.md) post-hoc tutorials). 5. **Group analysis**: Compare dynamics across groups or conditions using statistical testing ([Statistical Significance Testing tutorials](tutorial_sections/statistics.html.md)). ## Quick Example Here is a minimal example of training an HMM using the Data API: ```default from osl_dynamics.data import Data from osl_dynamics.models.hmm import Config, Model # Load data data = Data(["subject1.npy", "subject2.npy", ...]) # Prepare data data.prepare({"tde_pca": {"n_embeddings": 15, "n_pca_components": 80}, "standardize": {}}) # Create and train the model config = Config( n_states=8, n_channels=data.n_channels, sequence_length=200, learn_means=False, learn_covariances=True, batch_size=256, learning_rate=0.01, n_epochs=20, ) model = Model(config) model.random_state_time_course_initialization(data, n_init=3, n_epochs=1) model.fit(data) # Get inferred state probabilities gamma = model.get_gamma(data) ``` Statistical significance testing works on any subject-level quantity. For example, to compare the fractional occupancy of each state between two groups of subjects: ```default from osl_dynamics import stats # fo has shape (n_subjects, n_states), assignments is a group label per subject result = stats.group_diff(fo, assignments, n_perm=1000) print(result.pvalues) # corrected for multiple comparisons across states print(result.effect_size()) # Cohen's d with confidence intervals ``` ## Using the Config API For a more streamlined approach, you can use the Config API with a YAML config: ```default from osl_dynamics import run_pipeline config = """ load_data: inputs: training_data prepare: tde_pca: {n_embeddings: 15, n_pca_components: 80} standardize: {} train_hmm: config_kwargs: n_states: 8 learn_means: False learn_covariances: True """ run_pipeline(config, output_dir="results") ``` You can also run this from the command line: ```default osl-dynamics config.yml results ``` where `config.yml` is a YAML file containing the pipeline configuration, e.g.: ```yaml load_data: inputs: training_data prepare: tde_pca: {n_embeddings: 15, n_pca_components: 80} standardize: {} train_hmm: config_kwargs: n_states: 8 learn_means: False learn_covariances: True ``` and `results` is the output directory. The YAML config specifies a pipeline of functions to run. Each top-level key (e.g. `load_data`, `train_hmm`) corresponds to a function in [`osl_dynamics.config_api.wrappers`](autoapi/osl_dynamics/config_api/wrappers/index.html.md#module-osl_dynamics.config_api.wrappers), and each value holds its keyword arguments. Post-hoc analysis steps such as `multitaper_spectra`, `plot_group_tde_hmm_networks` and `compare_groups_hmm_summary_stats` (a group comparison of the summary statistics) can be added in the same way. See the [`wrappers API reference`](autoapi/osl_dynamics/config_api/wrappers/index.html.md#module-osl_dynamics.config_api.wrappers) for the full list of available functions and their arguments. ## What Next? - **Tutorials**: Work through the [tutorials](tutorials.html.md) for detailed examples covering M/EEG processing, data loading, model training, post-hoc analysis and statistical testing, with links to example scripts and workshop materials. - **User Guide**: Read the [User Guide](user_guide/index.html.md) for how the [processing pipeline](user_guide/meeg.html.md), the [models](user_guide/models/index.html.md) and the [statistical tests](user_guide/stats.html.md) work and when to use which. - **FAQ**: Check the [FAQ](faq.html.md) for common questions about preprocessing, choosing a model and its hyperparameters, and interpreting results. - **API reference**: Browse the [API docs](autoapi/index.html.md) for detailed information on all classes and functions. # install/bmrc.html.md # Installing on BMRC (Oxford) On the Biomedical Research Computing (BMRC) cluster, `conda` is available as a software module: ```default module load Miniforge3 ``` and osl-dynamics can be installed with: ```default mamba create -n osld -c conda-forge osl-dynamics conda activate osld ``` The above can be run on the login nodes (`clusterX.bmrc.ox.ac.uk`). On `compg017` you will need to set the following to use conda: ```default unset https_proxy http_proxy no_proxy HTTPS_PROXY HTTP_PROXY NO_PROXY ``` # install/index.html.md # Installation osl-dynamics is available on [conda-forge](https://anaconda.org/conda-forge/osl-dynamics) and [PyPI](https://pypi.org/project/osl-dynamics). ## Conda installation (recommended) We recommend installing osl-dynamics with [Miniforge](https://conda-forge.org/download/), which provides `conda` and `mamba`. If you do not already have it: ```default curl -LO "https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-$(uname)-$(uname -m).sh" bash Miniforge3-$(uname)-$(uname -m).sh rm Miniforge3-$(uname)-$(uname -m).sh ``` Then create an environment with osl-dynamics in it: ```default mamba create -n osld -c conda-forge osl-dynamics conda activate osld ``` This installs osl-dynamics with everything it needs. This includes [MNE-Python](https://mne.tools/stable/index.html) and [TensorFlow](https://www.tensorflow.org/). On Windows, the command above will not work because conda-forge has no TensorFlow for Windows. See [Installing on Windows](install/windows.html.md) instead. ## Pip installation osl-dynamics can be installed from PyPI with: ```default pip install osl-dynamics ``` This does not include TensorFlow. To install it as well: ```default pip install "osl-dynamics[tf]" ``` or, if you have an NVIDIA GPU: ```default pip install "osl-dynamics[tf-cuda]" ``` Note that pip will not install the non-Python libraries that some dependencies need, which is why we recommend conda. ## Platform-specific instructions The instructions above are for Linux and macOS. For Windows and the Oxford BMRC cluster, see: - [Installing on Windows](install/windows.html.md) - [Installing on BMRC (Oxford)](install/bmrc.html.md) ## Install the latest development code (optional) You should only need to do this if you need a feature or fix that has not been released yet. Once you have created the `osld` conda environment (see instructions above) you can install the latest development version on the [GitHub repository](https://github.com/OHBA-analysis/osl-dynamics) with: ```default conda activate osld pip install git+https://github.com/OHBA-analysis/osl-dynamics.git ``` ## Copy the source code (optional) If you want to make your own changes to osl-dynamics, we recommend you work on a fork of the [GitHub repository](https://github.com/OHBA-analysis/osl-dynamics). A fork is your own copy of the repository on GitHub, so you can save your changes there (and share them with others) without needing write access to the main repository. First, create a fork by clicking the ‘Fork’ button at the top right of the [GitHub repository](https://github.com/OHBA-analysis/osl-dynamics) webpage. Then, once you have created the `osld` conda environment (see instructions above), you can install a local copy of your fork into it: ```default git clone https://github.com//osl-dynamics.git conda activate osld cd osl-dynamics pip install -e . ``` where `` is your GitHub username. Now you can run osl-dynamics with your own local changes to the code. To get the latest changes from the main repository, add it as a remote called `upstream`: ```default git remote add upstream https://github.com/OHBA-analysis/osl-dynamics.git ``` Then you can update your copy with: ```default git pull upstream main ``` If you would like your changes to be included in osl-dynamics, push them to your fork and open a pull request on the [GitHub repository](https://github.com/OHBA-analysis/osl-dynamics). ## Test your GPUs are working To check if your GPUs are working: ```default conda activate osld python -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))" ``` This should print a list of the GPUs you have available (or an empty list `[]` if there are none). ## AI assistants (optional) osl-dynamics has a skill for AI assistants. To install it in Claude Code: ```default /plugin install osl-dynamics --marketplace OHBA-analysis/osl-dynamics ``` Claude Code loads the skill automatically when you ask it to write, run or debug osl-dynamics code. For other AI assistants, point them to [llms.txt](https://osl-dynamics.readthedocs.io/en/latest/llms.txt). ## Removing osl-dynamics To remove osl-dynamics simply delete the conda environment: ```default conda env remove -n osld conda clean --all ``` The downloaded data files are cached separately, and can be removed with: ```default rm -rf ~/.cache/osl-files # linux rm -rf ~/Library/Caches/osl-files # macOS ``` # install/windows.html.md # Installing on Windows conda-forge does not provide TensorFlow for Windows, so the full `osl-dynamics` conda package is only available for Linux and macOS. There are two ways to use osl-dynamics on Windows. ## Option 1: WSL (recommended) The [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/install) (WSL) runs Linux inside Windows. With it you can install the full package, including GPU support for training models. To set up WSL, open PowerShell as an administrator and run: ```default wsl --install ``` then restart your computer. Open the Ubuntu app from the Start menu and follow the [conda installation](install/index.html.md#conda-install) instructions in the Ubuntu terminal. If you have an NVIDIA GPU, install the latest NVIDIA driver for Windows; do not install a separate driver inside WSL. conda will install the GPU version of TensorFlow automatically. ## Option 2: native Windows Install [Miniforge](https://conda-forge.org/download/) using the Windows installer, then open the Miniforge Prompt from the Start menu and run: ```default mamba create -n osld -c conda-forge osl-dynamics-base python=3.12 conda activate osld pip install tensorflow==2.19.1 tensorflow-probability==0.25.0 tf-keras==2.19.0 ``` The `osl-dynamics-base` conda package contains everything except TensorFlow, which is installed from PyPI with pip in the last step. Python is set to 3.12 because this is the newest version TensorFlow 2.19.1 supports on Windows. Note that TensorFlow does not support GPUs on native Windows, so models will be trained on the CPU. If you need a GPU, use WSL. # llms-txt.html.md # osl-dynamics > osl-dynamics is a Python toolbox for studying brain dynamics using neuroimaging data (MEG, EEG and fMRI). It provides generative models that decompose data into dynamic functional brain networks, often called brain states or modes, including the Hidden Markov Model (HMM) and Dynamic Network Modes (DyNeMo). It also provides everything needed for a complete analysis: M/EEG preprocessing, source reconstruction and parcellation, data preparation, spectral estimation, power maps, functional connectivity, burst detection, simulation and statistical significance testing. osl-dynamics was developed by the OHBA Methods Group at the University of Oxford. It works with MNE-Python: a typical M/EEG workflow preprocesses, source reconstructs and parcellates the data (all available in `osl_dynamics.meeg`), then models the dynamics of the parcel time courses. Data can be loaded from NumPy (.npy), MATLAB (.mat), text (.txt) or MNE (.fif) files. If you use osl-dynamics, please cite: Gohil, C., Huang, R., Roberts, E., van Es, M. W., Quinn, A. J., Vidaurre, D., and Woolrich, M. W. (2024). osl-dynamics, a toolbox for modeling fast dynamic brain activity. eLife, 12, RP91949. ## Installation - conda (recommended, includes TensorFlow): `mamba create -n osld -c conda-forge osl-dynamics` - pip without TensorFlow: `pip install osl-dynamics` - pip with TensorFlow: `pip install "osl-dynamics[tf]"`, or `pip install "osl-dynamics[tf-cuda]"` for an NVIDIA GPU on Linux TensorFlow is only needed to train models (`osl_dynamics.models`). Data preparation, M/EEG processing, spectral analysis, simulation and statistics work without it. ## Core workflow A typical M/EEG analysis has five steps. For fMRI or sensor-level data, start at step 3 and prepare the data with `{"standardize": {}}` only (fMRI HMMs use `learn_means=True`). ### 1. M/EEG processing (each session) ```python import mne from osl_dynamics.meeg import preproc, rhino, source_recon, parcellation, Session # Sensor-level preprocessing with MNE and osl-dynamics raw = mne.io.read_raw_fif("sub-01_task-rest.fif", preload=True) raw = raw.filter(l_freq=1, h_freq=45).resample(sfreq=250) raw = preproc.detect_bad_segments(raw, picks="mag") raw = preproc.detect_bad_channels(raw, picks="mag") raw.save("derivatives/preprocessed/sub-01_preproc-raw.fif") # Surface extraction (once per subject), coregistration and forward model rhino.extract_surfaces(mri_file="sub-01_T1w.nii.gz", outdir="derivatives/anat_surfaces/sub-01") session = Session( outdir="derivatives/osl", id="sub-01_task-rest", preproc_file="derivatives/preprocessed/sub-01_preproc-raw.fif", surfaces_dir="derivatives/anat_surfaces/sub-01", ) rhino.extract_fiducials_and_headshape_from_fif(session) rhino.coregister_head_and_mri(session) rhino.forward_model(session, model="Single Layer", gridstep=8) # LCMV beamformer, then parcellation with symmetric orthogonalization source_recon.lcmv_beamformer(session, chantypes=["mag", "grad"], rank={"meg": 60}) parcel_data = parcellation.parcellate_lcmv( session, parcellation_file="atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz", orthogonalization="symmetric", ) parcellation.save_as_fif(parcel_data, session.preproc_file, filename="derivatives/osl/sub-01_task-rest/lcmv-parc-raw.fif") ``` `osl_dynamics.meeg.parallel.run` runs a function like this on many sessions in parallel. Without a subject MRI, skip `rhino.extract_surfaces`, use `osl_dynamics.files.mni152_surfaces.directory` as `surfaces_dir` and pass `allow_mri_scaling=True` to `rhino.coregister_head_and_mri`. ### 2. Sign flipping (source-space M/EEG) ```python from osl_dynamics.data import sign_flipping # Align the sign of the parcel time courses across sessions # (parc_fifs are the parcellated fif files from step 1) template_cov, _ = sign_flipping.build_template_mne_raw(parc_fifs) for parc_fif, sflip_fif in zip(parc_fifs, sflip_fifs): sign_flipping.sign_flip_mne_raw(parc_fif, template_cov=template_cov, output_file=sflip_fif) ``` ### 3. Model training ```python from osl_dynamics.data import Data from osl_dynamics.models.hmm import Config, Model # Load parcel time courses: fif files, a directory, a list of files or a list of arrays data = Data(sflip_fifs, picks="misc", reject_by_annotation="omit", sampling_frequency=250) # Time-delay embedding + PCA, then standardize # (n_pca_components is a round number roughly twice the number of channels, e.g. 120 for 52 parcels) data.prepare({ "tde_pca": {"n_embeddings": 15, "n_pca_components": 120}, "standardize": {}, }) # Train a TDE-HMM config = Config( n_states=8, n_channels=data.n_channels, sequence_length=200, learn_means=False, learn_covariances=True, batch_size=256, learning_rate=0.01, n_epochs=20, ) model = Model(config) model.random_state_time_course_initialization(data, n_init=3, n_epochs=1) model.fit(data) model.save("results/model") # reload with osl_dynamics.models.load("results/model") # State probabilities: a list with one (n_samples, n_states) array per session gamma = model.get_gamma(data) ``` ### 4. Post-hoc analysis ```python from osl_dynamics.analysis import spectral, power, connectivity, post_hoc from osl_dynamics.inference import modes parcellation_file = "atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz" # State spectra from the time series before preparation; a Data object is # aligned to gamma automatically (or use data.trim_time_series with arrays) spectra = spectral.multitaper_spectra(data, alpha=gamma, frequency_range=[1, 45]) group = spectra.group_average() p = group.power_maps() # (n_states, n_parcels), change from static power c = group.coherence_networks(percentile=97) # (n_states, n_parcels, n_parcels) power.save(p, parcellation_file=parcellation_file, filename="power_.png") connectivity.save(c, parcellation_file=parcellation_file, filename="coh_.png") # Summary statistics stc = modes.argmax_time_courses(gamma) fo = post_hoc.fractional_occupancies(stc) # (n_sessions, n_states) lt = post_hoc.mean_lifetimes(stc, sampling_frequency=250) intv = post_hoc.mean_intervals(stc, sampling_frequency=250) sr = post_hoc.switching_rates(stc, sampling_frequency=250) ``` ### 5. Statistical significance testing ```python from osl_dynamics import stats # Group difference in each summary statistic, corrected across states # (assignments is a group label for each session) for name, x in {"fo": fo, "lt": lt, "intv": intv, "sr": sr}.items(): result = stats.group_diff(x, assignments, n_perm=1000) print(name, result.pvalues, result.effect_size()) # Group difference in the state power maps, corrected across states and parcels session_p = spectra.power_maps() # (n_sessions, n_states, n_parcels) result = stats.group_diff(session_p, assignments, n_perm=1000) ``` The Config API runs the same pipeline from a YAML file: `osl-dynamics config.yml results`, or `osl_dynamics.run_pipeline(config, output_dir="results")`. Each top-level key is a function in `osl_dynamics.config_api.wrappers`. ## API notes - `Data` keeps data in memory by default and writes nothing to disk. With `load_memmaps=True` it writes memory maps to a subdirectory of `store_dir` (default `./tmp`), which is deleted automatically when the script ends. Don’t call `data.delete_dir()` at the end of a script; it is only needed to free disk space early when using `load_memmaps=True` in a long-running session such as a notebook. - Every model module (`osl_dynamics.models.hmm`, `.dynemo`, `.dyneste`, `.mdynemo`, `.hive`, `.dive`, `.hmm_poisson`, `.hmm_dirichlet`, `.scdynemo`) defines a `Config` dataclass and a `Model` class with `fit`, `train`, `save` and initialization methods. Models with a hidden Markov chain (HMM, HIVE, HMM-Poisson, HMM-Dirichlet) return the state probabilities with `get_gamma`; DyNeMo-family models (DyNeMo, DyNeStE, M-DyNeMo, DIVE, SC-DyNeMo) return the mixing coefficients with `get_alpha` (M-DyNeMo returns `(alpha, beta)`). The Keras model is `model.keras_model`. Models are loaded with `osl_dynamics.models.load`. - HMM-family models infer mutually exclusive states (use `spectral.multitaper_spectra`); DyNeMo-family models infer mixtures of modes (use `spectral.regression_spectra`). - `spectral.welch_spectra`, `spectral.multitaper_spectra` and `spectral.regression_spectra` return `StateSpectra` or `RegressionSpectra` objects (`StaticSpectra` without `alpha`, as do `analysis.static.welch_spectra` and `analysis.static.multitaper_spectra`). They have the attributes `frequencies`, `psd` and `coherence` (and `psd_change` and `coherence_change` for state and regression spectra), and the methods `group_average`, `power_maps`, `coherence_networks`, `decompose`, `plot_psd` and `save`; load with `spectral.Spectra.load`. Arguments after `alpha` are keyword-only. - `osl_dynamics.stats` has the ready-made tests `evoked_response`, `paired_diff`, `group_diff`, `condition_diff` and `regression`, each returning a `TestResult` with `pvalues` and `effect_size()`. Custom designs use `DesignConfig`, `Design` and `GLM` with `MaxStatPermutation` or `ClusterPermutation`. Corrections: `correction="max_stat"` (default), cluster-based, TFCE, or `stats.fdr` / `stats.holm` / `stats.bonferroni` on p-values. - Simulations compose a state model with an observation model: `simulation.Simulation(state_model=simulation.HMM(...), obs_model=simulation.MVN(...), n_samples=...)`. State models: `HMM`, `HSMM`, `HierarchicalHMM`, `MDynHMM`, `MixedSine`, `MixedHSMM`. Observation models: `MVN`, `OscillatoryMVN`, `MDyn_MVN`, `MSess_MVN`, `MAR`, `TDECovs`, `OscillatoryBursts`, `Poisson`, `Dirichlet`. Classes such as `HMM_MVN` and `HSMM_MVN` combine common pairs. - M/EEG processing (`osl_dynamics.meeg`): `preproc`, `rhino` (surface extraction, coregistration, forward model), `source_recon` (LCMV beamformer), `parcellation` (with `orthogonalization="symmetric"`), and `Session` for the files of a session. `preproc.ica_label` only removes artefacts from the channels it is fitted on: use `picks="meg"` for Elekta data so the magnetometers and gradiometers are both cleaned. - Parcellations, masks and surfaces are downloaded from the osl-files repository on first use and cached; refer to them by file name. `osl_dynamics.files.fetch_file`, `fetch_directory` and `fetch_all` download files explicitly (e.g. before working offline). - Spelling is American throughout (e.g. `standardize`, `orthogonalization`, `regularization`). ## Removed APIs Code written for earlier versions may use names that no longer exist: - `osl_dynamics.glm` and `osl_dynamics.analysis.statistics` are replaced by `osl_dynamics.stats`. - Spectra functions no longer return tuples such as `f, psd, coh = spectral.multitaper_spectra(...)`; they return a spectra object with `.frequencies`, `.psd` and `.coherence`. - The `use_tfrecord` argument and the `mask_file` argument are removed. - osl-ephys is no longer required for M/EEG preprocessing and source reconstruction; use `osl_dynamics.meeg`. - Models saved with osl-dynamics 3.0 to 3.9 load with `osl_dynamics.models.load` (the config and weights are converted). For HIVE and DIVE, call `set_regularizers` after loading to include the KL loss of the session deviations in the free energy. - Model API (old → new): - HMM, HIVE, HMM-Poisson, HMM-Dirichlet: `get_alpha` → `get_gamma`. HMM: `dual_estimation(alpha=...)` → `dual_estimation(gamma=...)`. - `get_means_covariances()` → `get_means()` and `get_covariances()`; M-DyNeMo `get_means_stds_corrs()` → `get_means()`, `get_standard_deviations()` and `get_correlations()`. - M-DyNeMo: `get_stds`/`get_corrs`/`set_stds`/`set_corrs` → `get_standard_deviations`/`get_correlations`/`set_standard_deviations`/`set_correlations`; `get_mode_time_courses` → `get_alpha` (returns `(alpha, beta)`), `get_mode_logits` → `get_theta`, `sample_time_courses` → `sample_alpha`. - HIVE, DIVE: `get_group_means`/`get_group_covariances` → `get_means`/`get_covariances`; `get_session_means_covariances()` → `get_session_means()` and `get_session_covariances()`; `get_summed_embeddings` → `get_session_embeddings`; `get_embedding_weights` → `get_label_embeddings`; `set_dev_parameters_initializer` → `set_deviation_parameters`; `set_embeddings_initializer` → `set_embeddings`. - SC-DyNeMo: `get_amplitude`/`get_frequency`/`get_variance` → `get_amplitudes`/`get_frequencies`/`get_variances`. - `set_trainable(layer_names, False)` → `with model.freeze("model_rnn"):` (layer names are attributes of `model.keras_model`, e.g. `obs_model`, `markov_chain`, `inference_rnn`, `model_rnn`). - `model.model` (the Keras model) → `model.keras_model`; each model module’s Keras model class is `KerasModel`; Keras methods are no longer forwarded from the model (use `model.get_weights()`, `model.summary()` or `model.keras_model`). - `fit(kl_annealing_callback=...)` → `fit(kl_annealing=...)`; DyNeStE `fit(gs_annealing_callback=...)` → `fit(gumbel_annealing=...)`; `fit(save_filepath=...)` → `best_filepath` (with `save_best_after`) or `checkpoint_dir` (with `checkpoint_freq`). History keys `ll_loss` → `nll_loss`, `rho` → `ema_decay` and DyNeStE `temperature` → `gumbel_temperature`. `model.compile()` is removed (`fit` compiles the model). `fine_tuning` (HMM, DyNeMo) and DyNeMo `dual_estimation` no longer take `store_dir`. - `GradientMonitoringCallback(loss_indices=...)` → `loss_names`; `CheckpointCallback(save_freq=...)` → `checkpoint_freq`. - `html_summary()`/`latex_summary()` → `summary_table("html")`/`summary_table("latex")`; `multistart_initialization` → `random_subset_initialization(take=1)`; `set_random_state_time_course_initialization` is removed (use `random_state_time_course_initialization`). - `osl_dynamics.models.sc_dynemo` → `osl_dynamics.models.scdynemo`. - `osl_dynamics.inference.tf_ops` → `osl_dynamics.utils.devices` (e.g. `devices.gpu_growth()`); `osl_dynamics.utils.model` → `osl_dynamics.utils.tables`. - `osl_dynamics.models.hmm_poi` → `osl_dynamics.models.hmm_poisson`; `osl_dynamics.simulation.HMM_Poi` → `HMM_Poisson`. - `train(data, n_init=..., stay_prob=...)` → `train(data, init_kwargs={...})`: options for the initialization method go in `init_kwargs`; other keyword arguments go to `fit` (all except `epochs` and the saving options are also passed to the initialization). - `osl_dynamics.models.mod_base`, `inf_mod_base` and `obs_mod` → the `osl_dynamics.models.base` subpackage (`model`, `markov`, `variational`, `configs`, `observation`, `initialization`; all classes importable from `osl_dynamics.models.base`); `osl_dynamics.inference.initializers` and `optimizers` are removed; `KLAnnealingCallback`, `EMADecayCallback` and `GumbelSoftmaxAnnealingCallback` are removed. - Config fields (old → new): `lr_decay` → `learning_rate_decay`, `loss_calc` → `loss_reduction`, `do_kl_annealing` → `kl_annealing`, `do_gs_annealing`/`gs_*`/`*_gs_temperature` → `gumbel_annealing`/`gumbel_*`/`*_gumbel_temperature`, `dev_*` → `deviation_*`, `n_corr_modes` → `n_correlation_modes`, `*stds*`/`*corrs*` → `*standard_deviations*`/`*correlations*`, `inference_rnn`/`model_rnn` → `inference_rnn_type`/`model_rnn_type`. `strategy` and `multiple_dynamics` are removed. ## Documentation Every page is available as Markdown by appending `.md` to its URL. - [Full documentation](https://osl-dynamics.readthedocs.io/en/latest/llms-full.txt): the user guide, FAQ and tutorials as one Markdown file (the API reference is not included). - [Installation](https://osl-dynamics.readthedocs.io/en/latest/install/index.html): conda and pip installation, with separate pages for Windows and the Oxford BMRC cluster. - [Getting started](https://osl-dynamics.readthedocs.io/en/latest/getting_started.html): a typical workflow, a minimal HMM example and the Config API. - [M/EEG processing](https://osl-dynamics.readthedocs.io/en/latest/user_guide/meeg.html): preprocessing, surface extraction, coregistration, source reconstruction, parcellation, orthogonalization and sign flipping. - [Parcellations](https://osl-dynamics.readthedocs.io/en/latest/user_guide/parcellations/index.html): the available parcellation files. - [Models](https://osl-dynamics.readthedocs.io/en/latest/user_guide/models/index.html): HMM, DyNeMo, DyNeStE, M-DyNeMo and HIVE, with figures. - [Spectral analysis](https://osl-dynamics.readthedocs.io/en/latest/user_guide/spectra.html): which spectra function to use for each model, the spectra objects, power maps and coherence networks. - [Statistical significance testing](https://osl-dynamics.readthedocs.io/en/latest/user_guide/stats.html): which test and which correction for multiple comparisons (maximum statistic, cluster-based, TFCE, FDR) to use for each kind of output, covariates and effect sizes. - [Tutorials](https://osl-dynamics.readthedocs.io/en/latest/tutorials.html): step by step walkthroughs covering M/EEG processing, data loading and preparation, time-delay embedding, static analysis, HMM and DyNeMo training, spectra, power maps, connectivity, summary statistics, task analysis and statistical testing. - [FAQ](https://osl-dynamics.readthedocs.io/en/latest/faq.html): guidance on preprocessing, time-delay embedding, choosing parameters, choosing between runs and interpreting results. - [API reference](https://osl-dynamics.readthedocs.io/en/latest/autoapi/index.html): documentation for every module, class and function. ## Examples - [Example scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples): full pipelines for MEG and EEG preprocessing, MEG and fMRI analysis, spectra, static analysis, statistics, simulation, decoding, TINDA and plotting. ## Source and community - [GitHub repository](https://github.com/OHBA-analysis/osl-dynamics) - [PyPI package](https://pypi.org/project/osl-dynamics/) - [conda-forge package](https://anaconda.org/conda-forge/osl-dynamics) - [Paper in eLife](https://elifesciences.org/articles/91949) - [Issue tracker](https://github.com/OHBA-analysis/osl-dynamics/issues) # sg_execution_times.html.md # Computation times **02:54.406** total execution time for 30 files **from all galleries**: | Example | Time | Mem (MB) | |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------|------------| | [DyNeMo: Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md#sphx-glr-tutorials-build-5-2-dynemo-plotting-networks-py) (`tutorials/5-2_dynemo_plotting_networks.py`) | 00:41.398 | 0 | | [DyNeMo: Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md#sphx-glr-tutorials-build-5-1-dynemo-regression-spectra-py) (`tutorials/5-1_dynemo_regression_spectra.py`) | 00:36.878 | 0 | | [HMM: Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md#sphx-glr-tutorials-build-4-2-hmm-plotting-meg-networks-py) (`tutorials/4-2_hmm_plotting_meg_networks.py`) | 00:35.251 | 0 | | [DyNeMo: Mixing Coefficients](tutorials_build/5-3_dynemo_mixing_coefs.html.md#sphx-glr-tutorials-build-5-3-dynemo-mixing-coefs-py) (`tutorials/5-3_dynemo_mixing_coefs.py`) | 00:08.714 | 0 | | [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md#sphx-glr-tutorials-build-3-4-dynemo-selecting-a-run-py) (`tutorials/3-4_dynemo_selecting_a_run.py`) | 00:07.033 | 0 | | [HMM: Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md#sphx-glr-tutorials-build-4-1-hmm-multitaper-spectra-py) (`tutorials/4-1_hmm_multitaper_spectra.py`) | 00:06.716 | 0 | | [Static: Amplitude Envelope Correlation (AEC) Analysis](tutorials_build/2-3_static_aec_analysis.html.md#sphx-glr-tutorials-build-2-3-static-aec-analysis-py) (`tutorials/2-3_static_aec_analysis.py`) | 00:06.546 | 0 | | [Time-Delay Embedding](tutorials_build/1-4_data_time_delay_embedding.html.md#sphx-glr-tutorials-build-1-4-data-time-delay-embedding-py) (`tutorials/1-4_data_time_delay_embedding.py`) | 00:05.868 | 0 | | [Sliding Window Analysis](tutorials_build/3-1_sliding_window_analysis.html.md#sphx-glr-tutorials-build-3-1-sliding-window-analysis-py) (`tutorials/3-1_sliding_window_analysis.py`) | 00:05.162 | 0 | | [Static: Power Analysis](tutorials_build/2-2_static_power_analysis.html.md#sphx-glr-tutorials-build-2-2-static-power-analysis-py) (`tutorials/2-2_static_power_analysis.py`) | 00:04.379 | 0 | | [HMM: Training](tutorials_build/3-2_hmm_training.html.md#sphx-glr-tutorials-build-3-2-hmm-training-py) (`tutorials/3-2_hmm_training.py`) | 00:03.272 | 0 | | [M/EEG: Sign Flipping](tutorials_build/0-2_sign_flipping.html.md#sphx-glr-tutorials-build-0-2-sign-flipping-py) (`tutorials/0-2_sign_flipping.py`) | 00:03.030 | 0 | | [Network Response](tutorials_build/7-3_network_response.html.md#sphx-glr-tutorials-build-7-3-network-response-py) (`tutorials/7-3_network_response.py`) | 00:02.587 | 0 | | [Static: Spectral Analysis](tutorials_build/2-1_static_spectra_analysis.html.md#sphx-glr-tutorials-build-2-1-static-spectra-analysis-py) (`tutorials/2-1_static_spectra_analysis.py`) | 00:01.460 | 0 | | [Statistical Inference](tutorials_build/7-1_statistical_inference.html.md#sphx-glr-tutorials-build-7-1-statistical-inference-py) (`tutorials/7-1_statistical_inference.py`) | 00:01.419 | 0 | | [DyNeMo: Training](tutorials_build/3-3_dynemo_training.html.md#sphx-glr-tutorials-build-3-3-dynemo-training-py) (`tutorials/3-3_dynemo_training.py`) | 00:01.007 | 0 | | [Epoching: Network Response](tutorials_build/6-1_epoching_alpha.html.md#sphx-glr-tutorials-build-6-1-epoching-alpha-py) (`tutorials/6-1_epoching_alpha.py`) | 00:00.957 | 0 | | [HMM: Summary Statistics](tutorials_build/4-3_hmm_summary_stats.html.md#sphx-glr-tutorials-build-4-3-hmm-summary-stats-py) (`tutorials/4-3_hmm_summary_stats.py`) | 00:00.816 | 0 | | [Loading Data](tutorials_build/1-1_data_loading.html.md#sphx-glr-tutorials-build-1-1-data-loading-py) (`tutorials/1-1_data_loading.py`) | 00:00.577 | 0 | | [Group Contrast](tutorials_build/7-2_group_contrast.html.md#sphx-glr-tutorials-build-7-2-group-contrast-py) (`tutorials/7-2_group_contrast.py`) | 00:00.533 | 0 | | [Custom Designs](tutorials_build/7-4_custom_designs.html.md#sphx-glr-tutorials-build-7-4-custom-designs-py) (`tutorials/7-4_custom_designs.py`) | 00:00.496 | 0 | | [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md#sphx-glr-tutorials-build-1-2-data-prepare-meg-py) (`tutorials/1-2_data_prepare_meg.py`) | 00:00.228 | 0 | | [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md#sphx-glr-tutorials-build-1-3-data-prepare-fmri-py) (`tutorials/1-3_data_prepare_fmri.py`) | 00:00.077 | 0 | | [MEG: Preprocessing, Source Reconstruction, Parcellation](tutorials_build/0-1_meg_preprocessing.html.md#sphx-glr-tutorials-build-0-1-meg-preprocessing-py) (`tutorials/0-1_meg_preprocessing.py`) | 00:00.001 | 0 | | [HMM/DyNeMo: Get Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md#sphx-glr-tutorials-build-3-5-hmm-dynemo-get-inf-params-py) (`tutorials/3-5_hmm_dynemo_get_inf_params.py`) | 00:00.000 | 0 | | [Cam-CAN: MEG Batch Processing](tutorials_build/0-3_meg_batch_processing.html.md#sphx-glr-tutorials-build-0-3-meg-batch-processing-py) (`tutorials/0-3_meg_batch_processing.py`) | 00:00.000 | 0 | | [LEMON: EEG Batch Processing](tutorials_build/0-4_eeg_batch_processing.html.md#sphx-glr-tutorials-build-0-4-eeg-batch-processing-py) (`tutorials/0-4_eeg_batch_processing.py`) | 00:00.000 | 0 | | [MNE Sample Data: Bilateral Beamformer](tutorials_build/0-5_mne_sample_data.html.md#sphx-glr-tutorials-build-0-5-mne-sample-data-py) (`tutorials/0-5_mne_sample_data.py`) | 00:00.000 | 0 | | [HMM: fMRI Dual Estimation](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md#sphx-glr-tutorials-build-4-4-hmm-fmri-dual-estimation-py) (`tutorials/4-4_hmm_fmri_dual_estimation.py`) | 00:00.000 | 0 | | [HMM: Plotting fMRI Networks](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md#sphx-glr-tutorials-build-4-5-hmm-plotting-fmri-networks-py) (`tutorials/4-5_hmm_plotting_fmri_networks.py`) | 00:00.000 | 0 | # tutorial_sections/data.html.md # Data Loading data into osl-dynamics and preparing it for modeling: standardization, time-delay embedding and PCA. ![](tutorials_build/images/thumb/sphx_glr_1-1_data_loading_thumb.png) [Loading Data](tutorials_build/1-1_data_loading.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-2_data_prepare_meg_thumb.png) [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-3_data_prepare_fmri_thumb.png) [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-4_data_time_delay_embedding_thumb.png) [Time-Delay Embedding](tutorials_build/1-4_data_time_delay_embedding.html.md) # tutorial_sections/dynamic_modelling.html.md # Dynamic Modeling Inferring dynamic networks: sliding windows, training an HMM or DyNeMo, selecting a run and getting the inferred parameters. ![](tutorials_build/images/thumb/sphx_glr_3-1_sliding_window_analysis_thumb.png) [Sliding Window Analysis](tutorials_build/3-1_sliding_window_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-2_hmm_training_thumb.png) [HMM: Training](tutorials_build/3-2_hmm_training.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-3_dynemo_training_thumb.png) [DyNeMo: Training](tutorials_build/3-3_dynemo_training.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-4_dynemo_selecting_a_run_thumb.png) [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-5_hmm_dynemo_get_inf_params_thumb.png) [HMM/DyNeMo: Get Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md) # tutorial_sections/dynemo_post_hoc.html.md # DyNeMo Post-hoc Analysis Analyzing the modes of a trained DyNeMo: regression spectra, networks and mixing coefficients. ![](tutorials_build/images/thumb/sphx_glr_5-1_dynemo_regression_spectra_thumb.png) [DyNeMo: Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md) ![](tutorials_build/images/thumb/sphx_glr_5-2_dynemo_plotting_networks_thumb.png) [DyNeMo: Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md) ![](tutorials_build/images/thumb/sphx_glr_5-3_dynemo_mixing_coefs_thumb.png) [DyNeMo: Mixing Coefficients](tutorials_build/5-3_dynemo_mixing_coefs.html.md) # tutorial_sections/hmm_post_hoc.html.md # HMM Post-hoc Analysis Analyzing the states of a trained HMM: spectra, networks, summary statistics and fMRI dual estimation. ![](tutorials_build/images/thumb/sphx_glr_4-1_hmm_multitaper_spectra_thumb.png) [HMM: Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-2_hmm_plotting_meg_networks_thumb.png) [HMM: Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-3_hmm_summary_stats_thumb.png) [HMM: Summary Statistics](tutorials_build/4-3_hmm_summary_stats.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-4_hmm_fmri_dual_estimation_thumb.png) [HMM: fMRI Dual Estimation](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-5_hmm_plotting_fmri_networks_thumb.png) [HMM: Plotting fMRI Networks](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md) # tutorial_sections/meeg_processing.html.md # M/EEG Processing From raw sensor recordings to parcellated source-space time courses: preprocessing, surface extraction, coregistration, source reconstruction, parcellation and sign flipping. See the [M/EEG Processing](user_guide/meeg.html.md) page for an overview of the steps. ![](tutorials_build/images/thumb/sphx_glr_0-1_meg_preprocessing_thumb.png) [MEG: Preprocessing, Source Reconstruction, Parcellation](tutorials_build/0-1_meg_preprocessing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-2_sign_flipping_thumb.png) [M/EEG: Sign Flipping](tutorials_build/0-2_sign_flipping.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-3_meg_batch_processing_thumb.png) [Cam-CAN: MEG Batch Processing](tutorials_build/0-3_meg_batch_processing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-4_eeg_batch_processing_thumb.png) [LEMON: EEG Batch Processing](tutorials_build/0-4_eeg_batch_processing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-5_mne_sample_data_thumb.png) [MNE Sample Data: Bilateral Beamformer](tutorials_build/0-5_mne_sample_data.html.md) Also see [Canonical-HMM-Networks](https://github.com/OHBA-analysis/Canonical-HMM-Networks) for start-to-end tutorials with Elekta, CTF, OPM and EEG data. # tutorial_sections/static_analysis.html.md # Static Analysis Time-averaged analysis of MEG data: spectra, power maps and amplitude envelope correlation networks. ![](tutorials_build/images/thumb/sphx_glr_2-1_static_spectra_analysis_thumb.png) [Static: Spectral Analysis](tutorials_build/2-1_static_spectra_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_2-2_static_power_analysis_thumb.png) [Static: Power Analysis](tutorials_build/2-2_static_power_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_2-3_static_aec_analysis_thumb.png) [Static: Amplitude Envelope Correlation (AEC) Analysis](tutorials_build/2-3_static_aec_analysis.html.md) # tutorial_sections/statistics.html.md # Statistical Significance Testing GLM permutation tests for group contrasts, network responses, conditions and custom designs, with the background on the methods. See the [statistics page](user_guide/stats.html.md) for which test and correction to use. ![](tutorials_build/images/thumb/sphx_glr_7-1_statistical_inference_thumb.png) [Statistical Inference](tutorials_build/7-1_statistical_inference.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-2_group_contrast_thumb.png) [Group Contrast](tutorials_build/7-2_group_contrast.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-3_network_response_thumb.png) [Network Response](tutorials_build/7-3_network_response.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-4_custom_designs_thumb.png) [Custom Designs](tutorials_build/7-4_custom_designs.html.md) # tutorial_sections/task_analysis.html.md # Task Analysis Epoching state and mode time courses around events to get network responses. ![](tutorials_build/images/thumb/sphx_glr_6-1_epoching_alpha_thumb.png) [Epoching: Network Response](tutorials_build/6-1_epoching_alpha.html.md) Also see [Dynamic Network Analysis of Electrophysiological Task Data](https://github.com/OHBA-analysis/Gohil2024_NetworkAnalysisOfTaskData) for a full task analysis. # tutorials.html.md # Tutorials The tutorials walk through each stage of an osl-dynamics analysis with real data: processing M/EEG data, loading and preparing data, static (time-averaged) analysis, training the dynamic network models, post-hoc analysis of the inferred networks, task analysis and statistical significance testing. Each tutorial can be downloaded as a Python script or Jupyter notebook from the links at the bottom of its page. If you are new to osl-dynamics, start with the [Getting Started](getting_started.html.md) guide, then follow the tutorials in order. Already have parcellated data? Start with the [Data tutorials](tutorial_sections/data.html.md). ## M/EEG Processing From raw sensor recordings to parcellated source-space time courses: preprocessing, surface extraction, coregistration, source reconstruction, parcellation and sign flipping. See the [M/EEG Processing](user_guide/meeg.html.md) page for an overview of the steps. ![](tutorials_build/images/thumb/sphx_glr_0-1_meg_preprocessing_thumb.png) [MEG: Preprocessing, Source Reconstruction, Parcellation](tutorials_build/0-1_meg_preprocessing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-2_sign_flipping_thumb.png) [M/EEG: Sign Flipping](tutorials_build/0-2_sign_flipping.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-3_meg_batch_processing_thumb.png) [Cam-CAN: MEG Batch Processing](tutorials_build/0-3_meg_batch_processing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-4_eeg_batch_processing_thumb.png) [LEMON: EEG Batch Processing](tutorials_build/0-4_eeg_batch_processing.html.md) ![](tutorials_build/images/thumb/sphx_glr_0-5_mne_sample_data_thumb.png) [MNE Sample Data: Bilateral Beamformer](tutorials_build/0-5_mne_sample_data.html.md) ## Data Loading data into osl-dynamics and preparing it for modeling: standardization, time-delay embedding and PCA. ![](tutorials_build/images/thumb/sphx_glr_1-1_data_loading_thumb.png) [Loading Data](tutorials_build/1-1_data_loading.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-2_data_prepare_meg_thumb.png) [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-3_data_prepare_fmri_thumb.png) [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md) ![](tutorials_build/images/thumb/sphx_glr_1-4_data_time_delay_embedding_thumb.png) [Time-Delay Embedding](tutorials_build/1-4_data_time_delay_embedding.html.md) ## Static Analysis Time-averaged analysis of MEG data: spectra, power maps and amplitude envelope correlation networks. ![](tutorials_build/images/thumb/sphx_glr_2-1_static_spectra_analysis_thumb.png) [Static: Spectral Analysis](tutorials_build/2-1_static_spectra_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_2-2_static_power_analysis_thumb.png) [Static: Power Analysis](tutorials_build/2-2_static_power_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_2-3_static_aec_analysis_thumb.png) [Static: Amplitude Envelope Correlation (AEC) Analysis](tutorials_build/2-3_static_aec_analysis.html.md) ## Dynamic Modeling Inferring dynamic networks: sliding windows, training an HMM or DyNeMo, selecting a run and getting the inferred parameters. ![](tutorials_build/images/thumb/sphx_glr_3-1_sliding_window_analysis_thumb.png) [Sliding Window Analysis](tutorials_build/3-1_sliding_window_analysis.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-2_hmm_training_thumb.png) [HMM: Training](tutorials_build/3-2_hmm_training.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-3_dynemo_training_thumb.png) [DyNeMo: Training](tutorials_build/3-3_dynemo_training.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-4_dynemo_selecting_a_run_thumb.png) [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md) ![](tutorials_build/images/thumb/sphx_glr_3-5_hmm_dynemo_get_inf_params_thumb.png) [HMM/DyNeMo: Get Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md) ## HMM Post-hoc Analysis Analyzing the states of a trained HMM: spectra, networks, summary statistics and fMRI dual estimation. ![](tutorials_build/images/thumb/sphx_glr_4-1_hmm_multitaper_spectra_thumb.png) [HMM: Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-2_hmm_plotting_meg_networks_thumb.png) [HMM: Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-3_hmm_summary_stats_thumb.png) [HMM: Summary Statistics](tutorials_build/4-3_hmm_summary_stats.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-4_hmm_fmri_dual_estimation_thumb.png) [HMM: fMRI Dual Estimation](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md) ![](tutorials_build/images/thumb/sphx_glr_4-5_hmm_plotting_fmri_networks_thumb.png) [HMM: Plotting fMRI Networks](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md) ## DyNeMo Post-hoc Analysis Analyzing the modes of a trained DyNeMo: regression spectra, networks and mixing coefficients. ![](tutorials_build/images/thumb/sphx_glr_5-1_dynemo_regression_spectra_thumb.png) [DyNeMo: Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md) ![](tutorials_build/images/thumb/sphx_glr_5-2_dynemo_plotting_networks_thumb.png) [DyNeMo: Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md) ![](tutorials_build/images/thumb/sphx_glr_5-3_dynemo_mixing_coefs_thumb.png) [DyNeMo: Mixing Coefficients](tutorials_build/5-3_dynemo_mixing_coefs.html.md) ## Task Analysis Epoching state and mode time courses around events to get network responses. ![](tutorials_build/images/thumb/sphx_glr_6-1_epoching_alpha_thumb.png) [Epoching: Network Response](tutorials_build/6-1_epoching_alpha.html.md) ## Statistical Significance Testing GLM permutation tests for group contrasts, network responses, conditions and custom designs, with the background on the methods. See the [statistics page](user_guide/stats.html.md) for which test and correction to use. ![](tutorials_build/images/thumb/sphx_glr_7-1_statistical_inference_thumb.png) [Statistical Inference](tutorials_build/7-1_statistical_inference.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-2_group_contrast_thumb.png) [Group Contrast](tutorials_build/7-2_group_contrast.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-3_network_response_thumb.png) [Network Response](tutorials_build/7-3_network_response.html.md) ![](tutorials_build/images/thumb/sphx_glr_7-4_custom_designs_thumb.png) [Custom Designs](tutorials_build/7-4_custom_designs.html.md) ## Examples Directory Full analysis scripts, including the scripts used to produce the results in the [osl-dynamics paper](https://elifesciences.org/articles/91949), can be found in the [examples directory](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples) of the repository. ## Workshops The [OHBA Methods Group](https://www.psych.ox.ac.uk/research/ohba-analysis-group) organizes teaching workshops for analyzing M/EEG data using [osl-ephys](https://osl-ephys.readthedocs.io/en/latest/) and osl-dynamics. Links to past workshops: - [2023 OSL workshop](https://osf.io/zxb6c/). - [2025 OSL workshop](https://github.com/OHBA-analysis/osl-workshop-2025-dynamics). # tutorials/README.html.md # tutorials_build/0-1_meg_preprocessing.html.md #### NOTE [Go to the end](tutorials_build/0-1_meg_preprocessing.html.md#sphx-glr-download-tutorials-build-0-1-meg-preprocessing-py) to download the full example code. # MEG: Preprocessing, Source Reconstruction, Parcellation This tutorial walks through the full MEG processing pipeline step by step: 1. Preprocessing — Filter, downsample, detect bad segments/channels, ICA artefact rejection. 2. Surface Extraction — Extract skull/scalp surfaces from a structural MRI. 3. Coregistration — Align MEG sensor space to MRI space. 4. Forward Model — Compute the lead field matrix. 5. Source Reconstruction — LCMV beamformer to project sensor data to source space. 6. Parcellation — Reduce voxel data to parcel time courses. The processing code in osl-dynamics is built on top of [MNE-Python](https://mne.tools): > Gramfort, A., Luessi, M., Larson, E., Engemann, D. A., Strohmeier, D., Brodbeck, C., Goj, R., Jas, M., Brooks, T., Parkkonen, L., & Hämäläinen, M. S. (2013). MEG and EEG data analysis with MNE-Python. *Frontiers in Neuroscience*, 7(267), 1–13. [https://doi.org/10.3389/fnins.2013.00267](https://doi.org/10.3389/fnins.2013.00267). ## Prerequisites - [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki) (needed for surface extraction). - [osl-dynamics](https://github.com/OHBA-analysis/osl-dynamics) (this installs [MNE-Python](https://mne.tools/stable/index.html) as a dependency). ## Input Data In this tutorial, we will use data from the [Wakeman-Henson dataset](https://www.nature.com/articles/sdata20151). This is a visual perception task recorded on an Elekta MEG system with a co-registered structural MRI. The data in BIDS format: ```default BIDS/ ├── sub-01/ │ ├── meg/ │ │ └── sub-01_run-01_task-visual_raw_sss.fif │ └── anat/ │ └── sub-01_T1w.nii.gz ├── ... ``` Output is written to `derivatives/`. ## Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```python import os def get_data(name): os.system(f"osf -p by2tc fetch data/{name}.zip") os.system(f"unzip -o {name}.zip") os.remove(f"{name}.zip") return f"Data downloaded to: {name}" # Download the dataset get_data("wakeman_henson_raw_1_subject") ``` ## Setup and Configuration ```python from pathlib import Path import mne import numpy as np %matplotlib inline from osl_dynamics import files from osl_dynamics.meeg import preproc, rhino, source_recon, parcellation, Session ``` Edit the cell below to match your data. ```python # Session info subject = "01" run = "01" task = "visual" id = f"sub-{subject}_run-{run}_task-{task}" # Paths bids_dir = Path("BIDS") raw_file = bids_dir / f"sub-{subject}/meg/sub-{subject}_run-{run}_task-{task}_raw_sss.fif" mri_file = bids_dir / f"sub-{subject}/anat/sub-{subject}_T1w.nii.gz" output_dir = Path("derivatives") qc_dir = Path("qc") # Preprocessing parameters resample_freq = 250 # Hz bandpass = (1, 45) # Hz notch_freqs = [50, 100] # Hz (mains frequency and harmonics) # Source reconstruction parameters gridstep = 8 # dipole grid resolution in mm chantypes = ["mag", "grad"] # Elekta has both magnetometers and gradiometers rank = {"meg": 60} # effective rank after MaxFilter # Parcellation parcellation_file = "atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz" print(f"Session ID: {id}") print(f"Raw file: {raw_file}") print(f"MRI file: {mri_file}") ``` ## Step 1: Preprocessing We clean the sensor-level MEG data by: - Notch filtering to remove mains frequency contamination. - Bandpass filtering to remove slow drifts and high-frequency noise. - Resampling to reduce data size. - Detecting and annotating bad segments (outlier temporal windows). - Detecting bad channels (outlier sensors). ### Load raw data ```python raw = mne.io.read_raw_fif(raw_file, preload=True) ``` ### Filter and resample ```python raw = raw.notch_filter(notch_freqs) raw = raw.filter( l_freq=bandpass[0], h_freq=bandpass[1], method="iir", iir_params={"order": 5, "ftype": "butter"}, ) raw = raw.resample(sfreq=resample_freq) ``` ### Bad segment detection We use the Generalized Extreme Studentized Deviate (G-ESD) algorithm to identify windows with outlier standard deviation. We run this separately for magnetometers and gradiometers, in both standard and `diff` modes (the latter catches segments where the signal changes abruptly within a window). ```python raw = preproc.detect_bad_segments(raw, picks="mag") raw = preproc.detect_bad_segments(raw, picks="mag", mode="diff") raw = preproc.detect_bad_segments(raw, picks="grad") raw = preproc.detect_bad_segments(raw, picks="grad", mode="diff") ``` ### Bad channel detection Channels with outlier standard deviations are marked as bad. ```python raw = preproc.detect_bad_channels(raw, picks="mag") raw = preproc.detect_bad_channels(raw, picks="grad") ``` ### ICA artefact rejection Automatic ICA artefact rejection to remove ECG and EOG artefacts. Two approaches are available: **Option A: ECG/EOG correlation** — Uses MNE-Python’s built-in correlation-based detection. ```python raw, ica, ic_labels = preproc.ica_ecg_eog_correlation(raw, picks="meg") ``` **Option B: MEGNet automatic labeling** — Uses `mne-icalabel` (included in the osl-dynamics conda environments) to classify components with a pre-trained deep learning model. Note, MEGNet was trained on `'mag'` sensor topographies but we’ll pass `'meg'` to include both magnetometers and gradiometers. ```python raw, ica, ic_labels = preproc.ica_label(raw, picks="meg", method="megnet") ``` Save preprocessing QC plots (PSD, sum-of-squares time series, channel standard deviations, ICA component topographies). Check that bad segments, channels, and ICA components are being correctly identified. ```python preproc.save_qc_plots(qc_dir, id, raw, show=True, ica=ica, ic_labels=ic_labels) ``` ### Save preprocessed data ```python preproc_file = output_dir / "preprocessed" / f"{id}_preproc-raw.fif" preproc_file.parent.mkdir(parents=True, exist_ok=True) raw.save(preproc_file, overwrite=True) print(f"Saved: {preproc_file}") ``` ## Step 2: Surface Extraction We extract three surfaces from the structural MRI using FSL BET: - **Brain surface (inskull)** — used for the forward model. - **Inner skull (outskull)** — boundary between the brain cavity and the skull. - **Scalp (outskin)** — used for coregistration. - **Scalp including the nose (outskin_plus_nose)** — only generated if `include_nose=True`. The names in brackets are the ones BET gives the files, which are misleading: `inskull` is the brain surface and `outskull` is the inner skull. These surfaces define the geometry needed for coregistration and source reconstruction. #### NOTE **No structural MRI?** If you don’t have a subject-specific MRI, you can skip this step and use the standard MNI152 brain bundled with osl-dynamics. Set `surfaces_dir = files.mni152_surfaces.directory` in Step 3 and pass `allow_mri_scaling=True` during coregistration. The output plot (`surfaces.png`) overlays the extracted surfaces on the structural MRI: the brain surface in yellow, the inner skull in cyan and the scalp in magenta. Check that each surface matches the corresponding anatomical boundary and lies inside the next. If they don’t, consider using the standard MNI152 brain as a fallback. The MRI is also registered to MNI space, which is how the dipoles and parcels (defined in MNI space) are placed in the subject’s head. By default this is a nonlinear registration with FSL’s FNIRT, which follows the subject’s anatomy more closely than an affine registration and so places the parcels more accurately, at the cost of a few minutes per subject. The `mni_registration.png` plot shows the edges of the MNI152 template (red) on the registered MRI, check they match the anatomy. Its title gives the overlap of the skull-stripped brain with the MNI152 brain mask and the mutual information with the template, for the registration that is used and (in brackets) the other one; these are also saved to `mni_registration.json`. FNIRT increases the mutual information when it works, so if it does not the affine registration is used instead. A warning is printed if the registration looks poor, in which case check the plot. ```python surfaces_dir = str(output_dir / "anat_surfaces" / f"sub-{subject}") rhino.extract_surfaces( mri_file=str(mri_file), outdir=surfaces_dir, include_nose=False, do_mri2mniaxes_xform=False, show=True, ) ``` ## Step 3: Coregistration Coregistration aligns the MEG sensor coordinate system (“head” space) to the MRI coordinate system. We use the Polhemus fiducials (nasion, LPA, RPA) and headshape points recorded during the MEG session, and fit them to the MRI surfaces using the Iterative Closest Point (ICP) algorithm. First, let’s create a `Session`, which holds the paths of all the pipeline output files. ```python session = Session( outdir=str(output_dir / "osl"), id=id, preproc_file=str(preproc_file), surfaces_dir=surfaces_dir, # If using standard brain: surfaces_dir=files.mni152_surfaces.directory ) print(session) ``` ### Extract fiducials and headshape The Polhemus digitization points are stored inside the FIF file. We extract them to text files that RHINO uses for coregistration. ```python rhino.extract_fiducials_and_headshape_from_fif(session) ``` ### Fix stray Polhemus headshape points Sometimes we want to remove some Polhemus headshape points, we have to do this manually. Note, this step has to be adapted to your specific dataset of interest. ```python hs = np.loadtxt(session.coreg.head_headshape_file) nas = np.loadtxt(session.coreg.head_nasion_file) lpa = np.loadtxt(session.coreg.head_lpa_file) rpa = np.loadtxt(session.coreg.head_rpa_file) remove = np.logical_and(hs[1] > max(lpa[1], rpa[1]), hs[2] < nas[2]) hs = hs[:, ~remove] print(f"Overwriting: {session.coreg.head_headshape_file}") np.savetxt(session.coreg.head_headshape_file, hs) ``` ### Run coregistration Key parameters: - `use_nose=False` — Should we use the nose in the coregistration? (the nose is often removed when an MRI is defaced, in this scenario you shouldn’t use the nose). - `allow_mri_scaling=False` — Don’t scale the MRI to fit the headshape. Set `True` if using the MNI152 standard brain, which needs to be scaled to match the subject’s head size. ```python rhino.coregister_head_and_mri( session, use_nose=False, allow_mri_scaling=False, # set True if using MNI152 standard brain show=True, ) ``` The coregistration plot is saved automatically to `session.coreg_dir/coreg.png`. The 3D plot shows the MEG sensors (blue), headshape points (red dots), fiducials, and MRI surfaces. Check that the headshape points sit on the scalp surface and the sensors surround the head correctly. The QC report copies this plot automatically when generated. If the coregistration looks off, you can try: - Removing stray headshape points with `rhino.remove_stray_headshape_points`. - Manually editing the headshape/fiducial text files in `session.coreg_dir`. - Setting `use_nose=False`. ## Step 4: Forward Model The forward model (lead field matrix) describes how a dipole at each source location projects onto the MEG sensors. We use a Single Layer (Single Shell) head model based on the inner skull surface. A dipole is placed at each voxel of the MNI152 brain mask (transformed into the subject’s MRI space), so the dipoles are at the same MNI coordinates for every subject and match the voxels of the parcellation files. - `model="Single Layer"` — Single shell head model (standard for MEG). - `gridstep=8` — 8 mm MNI grid, which matches the 8 mm parcellation files. Smaller values give finer resolution but are slower. ```python rhino.forward_model(session, model="Single Layer", gridstep=gridstep) ``` ## Step 5: Source Reconstruction We use an LCMV (Linearly Constrained Minimum Variance) beamformer to project the sensor data into source space. The beamformer computes a spatial filter for each voxel that passes activity from that location while suppressing interference from elsewhere. Key parameters: - `chantypes=["mag", "grad"]` — Use both magnetometers and gradiometers (Elekta systems). For CTF, use `["mag"]`. - `rank={"meg": 60}` — Effective rank of the data after MaxFilter. Elekta data is typically rank 60-64. The sensor data is read from `session.preproc_file`. The source reconstruction and parcellation functions also accept `data`, a Raw/Epochs object or the path to a fif file, if you want to use different data. ### Compute beamformer weights ```python source_recon.lcmv_beamformer(session, chantypes=chantypes, rank=rank) ``` ## Step 6: Parcellation We reduce the source space to a smaller number of parcel time courses using a brain atlas. This makes the data more manageable for downstream analysis. See the [parcellations page](user_guide/parcellations/index.html.md#parcellations) for the full list of available parcellations. `parcellate_lcmv` assigns each dipole of the forward model to parcels using its MNI coordinate and calculates each parcel time course from the sensor data with the beamformer weights. Bad segments are automatically excluded. - The time course of each parcel is the first principal component of the dipoles in the parcel (weighted by the parcellation). - `orthogonalization="symmetric"` — Apply symmetric orthogonalization to reduce spatial leakage between parcels. ```python parcel_data = parcellation.parcellate_lcmv( session, parcellation_file, orthogonalization="symmetric", ) print(f"Parcel data shape: {parcel_data.shape} (parcels x time)") ``` If you need the voxel time courses (on a regular MNI grid), you can apply the beamformer with `apply_lcmv_beamformer`. These can also be parcellated with `parcellation.parcellate`. To get the time course at a specific MNI coordinate, use `virtual_electrodes`, which computes the beamformer weights for a dipole at the exact location: ```python voxel_data, voxel_coords = source_recon.apply_lcmv_beamformer(session) print(f"Voxel data shape: {voxel_data.shape} (voxels x time)") # Time courses at MNI coordinates (in mm) ve_data = source_recon.virtual_electrodes(session, [[-42, -22, 10], [42, -22, 10]]) ``` ### Save parcellated data We save the parcel time courses as a FIF file. The `extra_chans="stim"` option preserves any stimulus channels from the original recording. ```python parc_fif = str(output_dir / "osl" / id / "lcmv-parc-raw.fif") parcellation.save_as_fif( parcel_data, session.preproc_file, extra_chans="stim", filename=parc_fif, ) print(f"Saved: {parc_fif}") ``` A good sanity check is to plot the PSD of each parcel. We expect to see an alpha peak (~10 Hz) that is strongest in posterior parcels. If this is absent or the spectra look unusual, something may have gone wrong in the pipeline. You can also pass `power_maps=True` to generate band-limited power maps on the cortical surface. ```python parcellation.save_qc_plots(qc_dir, id, parc_fif, parcellation_file, show=True) ``` ## Summary and Next Steps We have completed the full MEG preprocessing pipeline: | Step | Name | Output | |--------|-----------------------|-------------------------------------------------| | 1 | Preprocessing | `derivatives/preprocessed/{id}_preproc-raw.fif` | | 2 | Surface extraction | `derivatives/anat_surfaces/sub-{subject}/` | | 3 | Coregistration | `derivatives/osl/{id}/coreg/` | | 4 | Forward model | `derivatives/osl/{id}/coreg/model-fwd.fif` | | 5 | Source reconstruction | `derivatives/osl/{id}/src/filters-lcmv.h5` | | 6 | Parcellation | `derivatives/osl/{id}/lcmv-parc-raw.fif` | ### Loading the parcellated data The final output can be loaded for downstream analysis: ```default from osl_dynamics.data import Data data = Data(parc_fif, picks="misc", reject_by_annotation="omit") ``` ### Where to go from here - **Canonical HMM analysis** — See [here](https://github.com/OHBA-analysis/Canonical-HMM-Networks) for notebooks applying a canonical HMM to the parcellated data. - **Batch processing** — See the [batch scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_preproc) for processing many sessions in parallel. - **Analysis** — See the [tutorials](tutorials.html.md) page for further tutorials for static and dynamic network analysis. ### Notes on CTF and OPM data This tutorial uses Elekta MEG data. If you are working with different MEG systems (or EEG) see [Canonical-HMM-Networks](https://github.com/OHBA-analysis/Canonical-HMM-Networks). Note: - **CTF:** Use `mne.io.read_raw_ctf()` to load data. Set `chantypes=["mag"]` and adjust `rank` (CTF data is not MaxFiltered, so the rank is typically higher). Fiducials/headshape points may need to be extracted from a `.pos` file rather than the data file — pass `pos_file` to `Session`. - **OPM:** Loading depends on the OPM system. Adjust `chantypes` and `rank` accordingly. **Total running time of the script:** (0 minutes 0.001 seconds) [`Download Jupyter notebook: 0-1_meg_preprocessing.ipynb`](_downloads/4f8e7966337a9da6fa9186c4f829f66a/0-1_meg_preprocessing.ipynb) [`Download Python source code: 0-1_meg_preprocessing.py`](_downloads/f3f1f44b46882bc9b9be720942134092/0-1_meg_preprocessing.py) [`Download zipped: 0-1_meg_preprocessing.zip`](_downloads/09de95b8b78c0d8a1abf069b95bb510e/0-1_meg_preprocessing.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/0-2_sign_flipping.html.md #### NOTE [Go to the end](tutorials_build/0-2_sign_flipping.html.md#sphx-glr-download-tutorials-build-0-2-sign-flipping-py) to download the full example code. # M/EEG: Sign Flipping Source reconstruction leaves the sign of each parcel (channel) time course arbitrary: the same parcel can have opposite polarity in different sessions. This is an identifiability problem in the source reconstruction of M/EEG that cannot be avoided. This matters when we pool sessions to train a model. The HMM and DyNeMo model dynamic changes in the *covariance* of the data — and the sign of the off-diagonal elements of the covariance depends on the (arbitrary) parcel signs. If the signs are not aligned across sessions, the model sees spurious covariance differences that are due to nothing more than a flipped sign. See the [FAQ](faq.html.md) for more. **Sign flipping** removes this ambiguity: for each session we search for the per-parcel `+1`/`-1` vector whose (time-delay embedded) covariance best matches a common **template**, and flip the parcels accordingly. This tutorial covers: 1. Simulating parcellated data. 2. Visualizing the sign ambiguity across sessions. 3. What the template is. 4. Sign flipping with the default template: the median session. 5. Specifying a template, either from the same dataset or from another dataset. 6. Sign flipping arrays and fif files inside a processing pipeline. Note, sign flipping is a *cross-session* step — it aligns sessions to each other — so it is applied to a group of parcellated sessions after preprocessing, source reconstruction and parcellation (see the [MEG Processing tutorial](tutorials_build/0-1_meg_preprocessing.html.md)). ## Simulating parcellated data Rather than download a dataset, we simulate parcellated data for 5 sessions of 38 parcels. Each session is a mix of the *same* underlying spatial sources — so the sessions share a common covariance structure — but we give each session its own random per-parcel signs. This reproduces the situation in parcellated data: the covariance structure is shared across sessions, but the sign of each parcel is arbitrary and differs from session to session. We fix the random seed so the example is reproducible. ```Python import numpy as np from osl_dynamics.data import Data rng = np.random.default_rng(42) n_sessions = 5 n_samples = 8000 n_parcels = 38 # Shared spatial mixing, so every session has the same covariance structure mixing = rng.standard_normal([n_parcels, n_parcels]) arrays = [] for _ in range(n_sessions): sources = rng.standard_normal([n_samples, n_parcels]) parcels = sources @ mixing.T parcels *= rng.choice([-1, 1], size=n_parcels) # arbitrary per-parcel signs arrays.append(parcels.astype(np.float32)) data = Data(arrays) print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 ## Visualizing the sign ambiguity The sign ambiguity shows up in the covariance. We compare sessions using the covariance of the *time-delay embedded* data (adding time-lagged copies of each channel), which is the representation the HMM and DyNeMo are trained on. [`osl_dynamics.data.sign_flipping.calc_cov()`](autoapi/osl_dynamics/data/sign_flipping/calc_cov.html.md#osl_dynamics.data.sign_flipping.calc_cov) computes this covariance for a session, and [`osl_dynamics.data.sign_flipping.calc_corr()`](autoapi/osl_dynamics/data/sign_flipping/calc_corr.html.md#osl_dynamics.data.sign_flipping.calc_corr) measures how similar two covariances are (the correlation of their off-diagonal entries). Passing `mode="abs"` compares the *absolute* values, which is insensitive to the parcel signs. ```Python from osl_dynamics.data import sign_flipping # Settings for the covariance used in the sign-flip search n_embeddings = 15 standardize = True def similarity_matrix(covs, mode="signed"): """Session-by-session similarity of the covariances.""" n = len(covs) matrix = np.zeros([n, n]) for i in range(n): for j in range(n): matrix[i, j] = sign_flipping.calc_corr(covs[i], covs[j], n_embeddings, mode=mode) return matrix # Covariance of the time-delay embedded data for each session ts = data.time_series() # list of (n_samples, n_channels) arrays covs = [sign_flipping.calc_cov(x, n_embeddings, standardize) for x in ts] signed = similarity_matrix(covs) absolute = similarity_matrix(covs, mode="abs") ``` Let’s plot both similarity matrices side by side. ```Python import matplotlib.pyplot as plt def plot_similarity(matrices, titles): fig, axes = plt.subplots(1, len(matrices), figsize=(10, 4.5)) for ax, matrix, title in zip(axes, matrices, titles): im = ax.imshow(matrix, vmin=-1, vmax=1, cmap="RdBu_r") ax.set_title(title) ax.set_xlabel("Session") ax.set_ylabel("Session") ax.set_xticks(range(n_sessions)) ax.set_yticks(range(n_sessions)) fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) fig.tight_layout() plot_similarity( [signed, absolute], ["Signed (sign-sensitive)", "Absolute (sign-invariant)"], ) ``` The **absolute** matrix (right) is high everywhere: the sessions share the same underlying covariance *structure*. The **signed** matrix (left) is mixed — off-diagonal session pairs are weakly or negatively correlated. That difference is exactly the sign ambiguity: the structure is shared, but the signs are not aligned. Sign flipping aligns them. ## The template Because the sign of each parcel is arbitrary, there is no “correct” sign to recover. All we need is for every session to use the *same* sign convention. So we pick a reference covariance — the **template** — and flip the parcels of each session so that its covariance best matches the template. Sessions that all match the same template then match each other. The template only sets which sign convention we end up with, so any covariance with the same structure as our sessions will do. There are two options: - **The default: the median session.** If you do not pass a template, one of the sessions being flipped is used. You do not need anything else, and this is all most analyses need. - **A template you specify.** You pass the template covariance yourself. It can come from the *same* dataset (e.g. a reference session) or from *another* dataset (e.g. the data used to train a pre-trained model). ## Default: the median session We do the sign flipping with the [`Data.align_channel_signs`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data.align_channel_signs) method. Without a template, it ranks the sessions by how similar their covariance is to all the other sessions (using the sign-invariant correlation) and uses the median session as the template. The log says which session was chosen. Every session is then flipped to match it, in place. We pass the same embedding settings as above, so the flips are found on the covariances we just plotted. ```Python data.align_channel_signs(n_embeddings=n_embeddings, standardize=standardize) ``` ```none Calculating covariances: 0%| | 0/5 [00:00 ``` To check the effect, we recompute the signed similarity matrix from the (now flipped) data and compare it with the one before flipping. ```Python covs_flipped = [ sign_flipping.calc_cov(x, n_embeddings, standardize) for x in data.time_series() ] signed_flipped = similarity_matrix(covs_flipped) plot_similarity( [signed, signed_flipped], ["Signed, before flipping", "Signed, after flipping"], ) ``` After flipping, every pair of sessions is positively correlated and the signed matrix looks like the absolute one: the signs are aligned and the sessions are ready to be pooled for training a model. ## Specifying a template The median session is picked from whichever sessions are in the Data object, so the sign convention can change if you rerun with sessions added or removed. Pass your own template when you need the sign convention to be fixed, e.g. - to add more sessions later and keep the signs of the sessions you have already flipped, - to flip sessions one at a time in a processing pipeline (see [Sign flipping arrays]() and [MNE-Python FIF Files]() below): there is no batch of sessions to take a median from, so a template is required, - to match the signs of another dataset, e.g. the data used to train a pre-trained model. The template is the covariance of the time-delay embedded data (see [`calc_cov`](autoapi/osl_dynamics/data/sign_flipping/calc_cov.html.md#osl_dynamics.data.sign_flipping.calc_cov)), built with the same `n_embeddings` and `standardize` settings used for the flipping. Pass it to `align_channel_signs` with `template_cov` (an array, or the path to a `.npy` file). Alternatively, pass a session’s time series with `template_data` and the covariance is computed for you. ### A template from the same dataset The simplest choice is a session from the dataset you are flipping. Here we use session 0 as the reference and save its covariance, so we can reuse the same template every time we run the pipeline. [`sign_flipping.build_template`](autoapi/osl_dynamics/data/sign_flipping/build_template.html.md#osl_dynamics.data.sign_flipping.build_template) is a more robust alternative: it starts from the session most similar to all the others, aligns every session to it, and averages the aligned covariances. A template averaged over sessions is less noisy than any one session. [`sign_flipping.build_template_mne_raw`](autoapi/osl_dynamics/data/sign_flipping/build_template_mne_raw.html.md#osl_dynamics.data.sign_flipping.build_template_mne_raw) does the same from parcellated fif files. ```Python # Start again from the original (unflipped) data data = Data(arrays) # Build the template from a reference session and save it template_cov = sign_flipping.calc_cov(ts[0], n_embeddings, standardize) np.save("template_cov.npy", template_cov) # Correlation of each session with the template *before* flipping before = np.array([sign_flipping.calc_corr(c, template_cov, n_embeddings) for c in covs]) ``` ```none Loading files: 0%| | 0/5 [00:00 We pass the path to the saved template covariance to `align_channel_signs` along with the same embedding settings we used to build it. ```Python data.align_channel_signs( template_cov="template_cov.npy", n_embeddings=n_embeddings, standardize=standardize, ) ``` ```none Calculating covariances: 0%| | 0/5 [00:00 ``` Let’s check the effect. We recompute each session’s covariance from the (now flipped) data and measure its correlation with the template again. ```Python ts_flipped = data.time_series() covs_flipped = [sign_flipping.calc_cov(x, n_embeddings, standardize) for x in ts_flipped] after = np.array([sign_flipping.calc_corr(c, template_cov, n_embeddings) for c in covs_flipped]) print("Correlation with template before:", np.round(before, 3)) print("Correlation with template after: ", np.round(after, 3)) ``` ```none Correlation with template before: [ 1. 0.016 0.115 0.132 -0.002] Correlation with template after: [1. 0.94 0.938 0.94 0.941] ``` The reference session (session 0) is the template, so its correlation is 1 and unchanged. The other sessions move up towards the template after flipping. Let’s plot it. ```Python fig, ax = plt.subplots(figsize=(6, 4)) x = np.arange(n_sessions) width = 0.4 ax.bar(x - width / 2, before, width, label="Before") ax.bar(x + width / 2, after, width, label="After") ax.set_xlabel("Session") ax.set_ylabel("Correlation with template") ax.set_xticks(x) ax.legend() fig.tight_layout() ``` ### A template from another dataset Sometimes the template comes from a *different* dataset, e.g. the template covariance of a pre-trained model, which may have been recorded on another scanner, with different preprocessing, or a different population. You only need this if you want the signs to match that dataset: for an analysis of your own data, a template from the same dataset is enough. An individual session may match a template from another dataset only weakly, and the flip search becomes unreliable: one wrongly flipped parcel in one session is enough to add spurious covariance dynamics. Passing `two_stage=True` splits the problem in two: 1. Build a template from the sessions in the Data object ([`sign_flipping.build_template`](autoapi/osl_dynamics/data/sign_flipping/build_template.html.md#osl_dynamics.data.sign_flipping.build_template), see above). 2. Find the *single* flip vector that aligns this dataset template to the external template. Each session is then aligned to the dataset template and this flip vector is applied on top. Each session only has to match its own dataset, which it does well, and the mismatch between the datasets is absorbed by one flip search on a clean, averaged covariance. The log reports the correlation of the dataset template with the external template, which is a useful summary of how well the new dataset matches the one the template came from. ```python data = Data(arrays) data.align_channel_signs( template_cov="other_dataset_template_cov.npy", n_embeddings=15, standardize=True, two_stage=True, ) ``` With a single session the two approaches are identical. Passing `two_stage=True` without a template aligns the sessions to the dataset template as it is, which is a more robust alternative to the median session. ## Sign flipping arrays In a processing pipeline you often hold a single session’s parcel data in memory as a `(parcels, time)` array — for example straight out of parcellation, before it is saved to a fif. [`sign_flipping.sign_flip`](autoapi/osl_dynamics/data/sign_flipping/sign_flip.html.md#osl_dynamics.data.sign_flipping.sign_flip) flips such an array directly against a template covariance. It returns the flipped data, the per-parcel `+1`/`-1` signs, and the correlation with the template. Here we flip one session against the template we saved earlier, transposing our simulated data to `(parcels, time)`. ```Python # Parcel data for one session, shape (parcels, time) parcel_data = ts[1].T flipped_data, flips, corr = sign_flipping.sign_flip( parcel_data, template_cov="template_cov.npy", n_embeddings=n_embeddings, standardize=standardize, ) print("Correlation with template before flipping:", round(float(before[1]), 3)) print("Correlation with template after flipping: ", round(float(corr), 3)) print("Signs applied:", flips) ``` ```none Sign flipping: flipped 22/38 parcels (template corr 0.940) Correlation with template before flipping: 0.016 Correlation with template after flipping: 0.94 Signs applied: [-1 -1 -1 -1 1 -1 1 -1 1 1 1 1 -1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 -1 -1 1 -1 1 -1 1 -1 -1 -1 1 -1] ``` The correlation jumps from near zero to close to the template, using the same search that [`Data.align_channel_signs`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data.align_channel_signs) runs for every session. ## MNE-Python FIF Files In a batch processing pipeline you often want to sign flip each session’s parcellated fif independently — for example inside `osl_dynamics.meeg.parallel.run`. [`sign_flipping.sign_flip_mne_raw`](autoapi/osl_dynamics/data/sign_flipping/sign_flip_mne_raw.html.md#osl_dynamics.data.sign_flipping.sign_flip_mne_raw) wraps `sign_flip` for this: pass a parcellated fif (a path or an `mne.io.Raw`) and a template covariance (a path or an array), and it reads the parcel data, flips it, and saves the sign-flipped fif. Each file is flipped on its own, so there is no median session to fall back on and you must pass a template. It does not have to come from another dataset: build it from the parcellated fifs of the dataset you are flipping (or a subset of them) with [`sign_flipping.build_template_mne_raw`](autoapi/osl_dynamics/data/sign_flipping/build_template_mne_raw.html.md#osl_dynamics.data.sign_flipping.build_template_mne_raw) and save it. ```python from glob import glob import numpy as np from osl_dynamics.data import sign_flipping parc_fifs = sorted(glob("derivatives/*/lcmv-parc-raw.fif")) # Template from this dataset template_cov, _ = sign_flipping.build_template_mne_raw(parc_fifs, n_jobs=8) np.save("template_cov.npy", template_cov) for parc_fif in parc_fifs: sflip_parc_fif = parc_fif.replace("lcmv-parc-raw.fif", "sflip-lcmv-parc-raw.fif") sign_flipping.sign_flip_mne_raw( parc_fif, template_cov="template_cov.npy", output_file=sflip_parc_fif, ) ``` If you omit the output file, the sign-flipped data is returned as an `mne.io.Raw` object instead of being written to disk: ```default raw = sign_flipping.sign_flip_mne_raw(parc_fif, "template_cov.npy") ``` Only the parcel channels are flipped; every other channel, the annotations and the data in bad segments are kept (bad segments are left out of the covariance). To match a template from another dataset, use the two-stage alignment: find the flips that align the dataset template to the external template, and pass them as `template_flips`: ```python template_flips, corr = sign_flipping.find_flips( template_cov, np.load("other_dataset_template_cov.npy"), n_embeddings=15 ) for parc_fif in parc_fifs: sign_flipping.sign_flip_mne_raw( parc_fif, template_cov=template_cov, output_file=parc_fif.replace("lcmv-parc-raw.fif", "sflip-lcmv-parc-raw.fif"), template_flips=template_flips, ) ``` For EEG, pass `frequency_bands=[(1, 4), (4, 8), (8, 13), (13, 30)]` to `build_template_mne_raw` and `sign_flip_mne_raw`: the flips are then found on the covariances of each band, pooled together, which carry more sign information than the broadband covariance. A template from another dataset must be stacked across the same bands. ## Next steps The sign-flipped data can now be prepared and used to train a model: - [Preparing Data](tutorials_build/1-2_data_prepare_meg.html.md). - [Training an HMM](tutorials_build/3-2_hmm_training.html.md). - [Training DyNeMo](tutorials_build/3-3_dynemo_training.html.md). **Total running time of the script:** (0 minutes 3.030 seconds) [`Download Jupyter notebook: 0-2_sign_flipping.ipynb`](_downloads/8c3bf25762c2a783cd73867e1c0e1946/0-2_sign_flipping.ipynb) [`Download Python source code: 0-2_sign_flipping.py`](_downloads/725123fce857e29440165b798eab5a9f/0-2_sign_flipping.py) [`Download zipped: 0-2_sign_flipping.zip`](_downloads/711d1e82b90ec5f9551789cba4aac88b/0-2_sign_flipping.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/0-3_meg_batch_processing.html.md #### NOTE [Go to the end](tutorials_build/0-3_meg_batch_processing.html.md#sphx-glr-download-tutorials-build-0-3-meg-batch-processing-py) to download the full example code. # Cam-CAN: MEG Batch Processing This tutorial shows how to process a large MEG dataset in batch using osl-dynamics’ parallel processing utilities. We use the [Cam-CAN dataset](https://opendata.mrc-cbu.cam.ac.uk/projects/camcan/) as an example. The pipeline mirrors the single-session tutorial ([MEG Processing](tutorials_build/0-1_meg_preprocessing.html.md)) but wraps each step in a function that is dispatched across sessions using `osl_dynamics.meeg.parallel.run`. ## Prerequisites - [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki) (needed for surface extraction). - [osl-dynamics](https://github.com/OHBA-analysis/osl-dynamics). ## Input Data The Cam-CAN dataset contains resting-state (`rest`), sensorimotor (`smt`) and passive stimulation (`passive`) MEG recordings from ~650 subjects. The raw data has already been MaxFiltered. Each subject also has a structural MRI. The data is organized as: ```default cc700/ ├── meg/ │ └── pipeline/release005/BIDSsep/ │ ├── derivatives_rest/... │ ├── derivatives_smt/... │ └── derivatives_passive/... └── mri/ └── pipeline/release004/BIDS_20190411/anat/ └── sub-*/anat/sub-*_T1w.nii.gz ``` The output of this script is written to `derivatives/`. ## Step 0: Find File Paths First, we locate all raw MEG files and their corresponding T1w structural MRIs and save them to a CSV file. This CSV acts as the session manifest for all subsequent steps. ```python from glob import glob from pathlib import Path import re import pandas as pd # Raw data directory raw_dir = "/path/to/cc700" anat_dir = f"{raw_dir}/mri/pipeline/release004/BIDS_20190411/anat" # Find MaxFiltered MEG files for all three tasks inputs = [] for task in ["rest", "smt", "passive"]: inputs += sorted( glob( f"{raw_dir}/meg/pipeline/release005/BIDSsep" f"/derivatives_{task}/aa/AA_movecomp" f"/aamod_meg_maxfilt_00002/sub-*" f"/mf2pt2_sub-*_ses-{task}_task-{task}_meg.fif" ) ) # Build a table of sessions, keeping only those with a structural MRI rows = [] for fpath in inputs: match = re.search(r"(sub-[A-Za-z0-9]+)_ses-(\w+)_task-(\w+)_meg\.fif", fpath) if match: subject = match.group(1) task = match.group(2) mri_file = f"{anat_dir}/{subject}/anat/{subject}_T1w.nii.gz" if not Path(mri_file).exists(): continue rows.append({ "id": f"{subject}_task-{task}", "subject": subject, "task": task, "raw_file": fpath, "mri_file": mri_file, }) df = pd.DataFrame(rows) print(f"Found {len(df)} sessions from {df['subject'].nunique()} subjects") print(f"Tasks: {df['task'].value_counts().to_dict()}") df.to_csv("sessions.csv", index=False) print("Saved sessions.csv") ``` ## Step 1: Preprocessing We define a function that preprocesses a single session and use `parallel.run` to dispatch it across sessions. Each session is independently: - Notch filtered at 50 and 100 Hz. - Bandpass filtered (0.5–80 Hz, 5th-order Butterworth). - Downsampled to 250 Hz. - Checked for bad segments and channels. - QC plots saved. ```python from pathlib import Path import pandas as pd import mne import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, preproc, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/1_preproc") sessions = pd.read_csv("sessions.csv").to_dict("records") def process_session(session): """Preprocess a single session.""" raw = mne.io.read_raw_fif(session["raw_file"], preload=True) raw = raw.notch_filter([50, 100]) raw = raw.filter( l_freq=0.5, h_freq=80, method="iir", iir_params={"order": 5, "ftype": "butter"}, ) raw = raw.resample(sfreq=250) raw = preproc.detect_bad_segments(raw, picks="mag") raw = preproc.detect_bad_segments(raw, picks="mag", mode="diff") raw = preproc.detect_bad_segments(raw, picks="grad") raw = preproc.detect_bad_segments(raw, picks="grad", mode="diff") raw = preproc.detect_bad_channels(raw, picks="mag") raw = preproc.detect_bad_channels(raw, picks="grad") preproc.save_qc_plots(qc_dir, session["id"], raw) preproc_out_dir = output_dir / "preprocessed" preproc_out_dir.mkdir(parents=True, exist_ok=True) outfile = preproc_out_dir / f"{session['id']}_preproc-raw.fif" raw.save(outfile, overwrite=True) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 2: Surface Extraction Surface extraction only needs to be done once per subject (not per session), so we deduplicate by subject before dispatching. ```python from pathlib import Path import pandas as pd from osl_dynamics.meeg import parallel, rhino, Session output_dir = Path("derivatives") log_dir = Path("logs/2_surfaces") df = pd.read_csv("sessions.csv") subjects = [] for _, row in df.drop_duplicates("subject").iterrows(): subjects.append({ "id": row["subject"], "subject": row["subject"], "mri_file": row["mri_file"], }) def process_subject(subject): """Extract surfaces for a single subject.""" outdir = output_dir / "anat_surfaces" / subject["subject"] rhino.extract_surfaces( mri_file=subject["mri_file"], outdir=str(outdir), include_nose=False, ) if __name__ == "__main__": parallel.run( process_subject, items=subjects, log_dir=log_dir, n_workers=8, ) ``` ## Step 3: Coregistration The coregistration step also includes a dataset-specific function to remove stray Polhemus headshape points. You will likely need to adapt `fix_headshape_points` for your own dataset. ```python from pathlib import Path import numpy as np import pandas as pd from osl_dynamics.meeg import parallel, rhino, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/3_coreg") sessions = pd.read_csv("sessions.csv").to_dict("records") def fix_headshape_points(session_files): coreg = session_files.coreg hs = np.loadtxt(coreg.head_headshape_file) nas = np.loadtxt(coreg.head_nasion_file) lpa = np.loadtxt(coreg.head_lpa_file) rpa = np.loadtxt(coreg.head_rpa_file) # Drop nasion by 4cm and remove headshape points more than 7cm away nas[2] -= 40 distances = np.sqrt( (nas[0] - hs[0]) ** 2 + (nas[1] - hs[1]) ** 2 + (nas[2] - hs[2]) ** 2 ) keep = distances > 70 hs = hs[:, keep] # Remove anything outside of rpa keep = hs[0] < rpa[0] hs = hs[:, keep] # Remove anything outside of lpa keep = hs[0] > lpa[0] hs = hs[:, keep] # Remove headshape points on the neck remove = hs[2] < min(lpa[2], rpa[2]) - 4 hs = hs[:, ~remove] np.savetxt(coreg.head_headshape_file, hs) def process_session(session): """Coregister a single session.""" preproc_file = str(output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif") surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=preproc_file, surfaces_dir=surfaces_dir, ) rhino.extract_fiducials_and_headshape_from_fif(session_files) parallel.log("Fixing headshape points...") fix_headshape_points(session_files) rhino.coregister_head_and_mri(session_files, use_nose=False) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 4: Forward Model and Source Reconstruction This step computes the forward model and LCMV beamformer weights for each session. ```python from pathlib import Path import pandas as pd import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, rhino, source_recon, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/4_source_recon") sessions = pd.read_csv("sessions.csv").to_dict("records") def process_session(session): """Source reconstruct a single session.""" preproc_file = str(output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif") surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=preproc_file, surfaces_dir=surfaces_dir, ) rhino.forward_model(session_files, model="Single Layer", gridstep=8) source_recon.lcmv_beamformer(session_files, chantypes=["mag", "grad"], rank={"meg": 60}) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 5: Parcellation The final step applies the beamformer, parcellates the voxel data, and saves the output. See the [parcellations page](user_guide/parcellations/index.html.md#parcellations) for the full list of available parcellations. ```python from pathlib import Path import pandas as pd import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, parcellation, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/5_parc") sessions = pd.read_csv("sessions.csv").to_dict("records") def process_session(session): """Parcellate a single session.""" preproc_file = str(output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif") surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=preproc_file, surfaces_dir=surfaces_dir, ) parcellation_file = "atlas-DK_nparc-54_space-MNI_res-8x8x8.nii.gz" parcel_data = parcellation.parcellate_lcmv( session_files, parcellation_file=parcellation_file, orthogonalization="symmetric", ) parc_fif = str(output_dir / "osl" / session["id"] / "lcmv-parc-raw.fif") parcellation.save_as_fif( parcel_data, preproc_file, extra_chans="stim", filename=parc_fif, ) parcellation.save_qc_plots( qc_dir, session["id"], parc_fif, parcellation_file ) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Sign Flipping (optional) Source reconstruction leaves the sign of each parcel time course arbitrary, so the same parcel can have opposite polarity in different sessions. Before pooling sessions to train a model we align these signs against a common **template covariance**. Here each session is flipped on its own, so we need the template before processing the sessions: build it once and save it to disk — then every session is flipped to match it. The template usually comes from the same dataset (e.g. a reference session, or [`sign_flipping.build_template_mne_raw`](autoapi/osl_dynamics/data/sign_flipping/build_template_mne_raw.html.md#osl_dynamics.data.sign_flipping.build_template_mne_raw) on the parcellated fifs of a pilot batch); it only needs to come from another dataset if you want to match that dataset’s signs. See the [Sign Flipping tutorial](tutorials_build/0-2_sign_flipping.html.md) for how to build and save `template_cov.npy`. With a saved template, [`sign_flipping.sign_flip`](autoapi/osl_dynamics/data/sign_flipping/sign_flip.html.md#osl_dynamics.data.sign_flipping.sign_flip) flips the `parcel_data` array directly, so we can align the signs just before saving and the fif we write out is already sign aligned. It takes the parcel data (shape `(parcels, time)`) and a template covariance (a path or an array), and returns the flipped data: ```python from osl_dynamics.data import sign_flipping parcel_data = parcellation.parcellate_lcmv(...) # (parcels, time) parcel_data, flips, corr = sign_flipping.sign_flip( parcel_data, template_cov="template_cov.npy", ) parcellation.save_as_fif(parcel_data, preproc_file, extra_chans="stim", filename=parc_fif) ``` If you have already saved the parcellated fifs, you can instead flip them as a separate step with [`sign_flipping.sign_flip_mne_raw`](autoapi/osl_dynamics/data/sign_flipping/sign_flip_mne_raw.html.md#osl_dynamics.data.sign_flipping.sign_flip_mne_raw), which reads a fif (or `mne.io.Raw`) and writes the sign-aligned fif. ## QC Report Each step that is passed `qc_dir` writes `qc/report.html` when it finishes, with what has been saved so far. Open it in a browser. It is a table with one row per session next to the QC plots of the selected session: - The table holds the numbers the steps save: the percentage of bad segments and the number of bad channels (step 1), the overlap and mutual information of the MRI with the MNI152 template after registration (step 2) and the distance of the headshape points from the scalp after coregistration (step 3). Click a column to sort by it, which puts the worst sessions first. Values far from the rest of their column are highlighted. - The tabs show the plots of the selected session: the preprocessing plots (sensor-level PSD first), the extracted surfaces, the registration to MNI space (the red lines are the edges of the MNI152 template, they should follow the anatomy), the coregistration and the PSD of the parcel time courses. - The up/down arrow keys move between sessions and left/right between tabs. With many sessions it is quicker to sort by each metric and look at the plots of the worst sessions than to page through all of them. The report and its plots are all in `qc/`, so that directory can be copied or served on its own. ## Summary Each step can be run as a standalone script. The `parallel.run` utility handles multiprocessing, logging, and error recovery. The end of each session is printed to the screen, with the time it took. Everything else (the output of MNE, osl-dynamics, etc.) is written to a log file for the session in the `logs/` directory — check these if a session fails. Use `parallel.log` in the processing function to print a message to the screen as well, and `parallel.warning` for a session that finishes without everything it was meant to produce. When a step finishes, the number of sessions that were ok, partial (had warnings) and failed (raised an exception) is printed, with the warnings and errors they stopped on. The final parcellated data can be loaded for downstream analysis: ```default from osl_dynamics.data import Data training_data = Data( "derivatives/osl/sub-*/lcmv-parc-raw.fif", picks="misc", reject_by_annotation="omit", ) ``` See the [tutorials](tutorials.html.md) page for static and dynamic network analysis tutorials. **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 0-3_meg_batch_processing.ipynb`](_downloads/f03438a96409ef4550be35404c3e4692/0-3_meg_batch_processing.ipynb) [`Download Python source code: 0-3_meg_batch_processing.py`](_downloads/bfb52827348a223d3a63afcb29a04373/0-3_meg_batch_processing.py) [`Download zipped: 0-3_meg_batch_processing.zip`](_downloads/b46b396feab0e5a9385b52e2c1571a92/0-3_meg_batch_processing.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/0-4_eeg_batch_processing.html.md #### NOTE [Go to the end](tutorials_build/0-4_eeg_batch_processing.html.md#sphx-glr-download-tutorials-build-0-4-eeg-batch-processing-py) to download the full example code. # LEMON: EEG Batch Processing This tutorial shows how to process a large EEG dataset in batch using osl-dynamics’ parallel processing utilities. We use the [LEMON dataset](https://ftp.gwdg.de/pub/misc/MPI-Leipzig_Mind-Brain-Body-LEMON/) as an example. The pipeline mirrors the single-session tutorial ([MEG Processing](tutorials_build/0-1_meg_preprocessing.html.md)) but adapted for EEG data. Each step is wrapped in a function that is dispatched across sessions using `osl_dynamics.meeg.parallel.run`. ## Prerequisites - [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki) (needed for surface extraction). - [osl-dynamics](https://github.com/OHBA-analysis/osl-dynamics). ## Input Data The LEMON dataset contains resting-state EEG recordings from ~200 subjects. Each subject also has a structural MRI (MP2RAGE) and an EEG localizer file (`.mat`) containing digitized electrode positions and fiducials. The data is organized as: ```default lemon/ ├── sub-*/ │ ├── RSEEG/sub-*.vhdr │ └── ses-01/anat/sub-*_ses-01_inv-2_mp2rage.nii.gz └── EEG_MPILMBB_LEMON/EEG_Localizer_BIDS_ID/ └── sub-*/sub-*.mat ``` The output of this script is written to `derivatives/`. ## Step 0: Find File Paths First, we locate all raw EEG files and their corresponding structural MRIs and localizer files, keeping only subjects that have all three. The results are saved to a CSV file that acts as the session manifest for all subsequent steps. ```python from pathlib import Path import pandas as pd # Raw data directory raw_dir = "/path/to/lemon" localizer_dir = f"{raw_dir}/EEG_MPILMBB_LEMON/EEG_Localizer_BIDS_ID" # Get subjects that have localizer data localizer_subjects = set() for loc_dir in sorted(Path(localizer_dir).glob("sub-*")): localizer_subjects.add(loc_dir.name) rows = [] for sub_dir in sorted(Path(raw_dir).glob("sub-*")): subject = sub_dir.name if subject not in localizer_subjects: continue raw_file = sub_dir / "RSEEG" / f"{subject}.vhdr" mri_file = sub_dir / "ses-01" / "anat" / f"{subject}_ses-01_inv-2_mp2rage.nii.gz" loc_file = f"{localizer_dir}/{subject}/{subject}.mat" if not raw_file.exists(): continue if not mri_file.exists(): continue rows.append({ "id": subject, "subject": subject, "raw_file": str(raw_file), "mri_file": str(mri_file), "localizer_file": loc_file, }) df = pd.DataFrame(rows) print(f"Found {len(df)} subjects") df.to_csv("sessions.csv", index=False) print("Saved sessions.csv") ``` ## Step 1: Preprocessing We define a function that preprocesses a single session and use `parallel.run` to dispatch it across sessions. Key differences from MEG preprocessing: - Data is loaded from BrainVision (`.vhdr`) format. - A channel montage is set from the localizer `.mat` file, which contains digitized electrode positions and fiducials. - A synthetic HEOG channel is created from F7 - F8. - The first 15 seconds are cropped (equipment settling time). - Bad channels are detected, interpolated, and an average reference is applied. Each session is independently: - Notch filtered at 50 and 100 Hz. - Bandpass filtered (0.5-80 Hz, 5th-order Butterworth). - Downsampled to 250 Hz. - Checked for bad channels and segments. - Bad channels interpolated. - Average referenced. - QC plots saved. ```python from pathlib import Path import numpy as np import pandas as pd import mne from scipy import io import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, preproc, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/1_preproc") sessions = pd.read_csv("sessions.csv").to_dict("records") def set_channel_montage(raw, localizer_file): """Set channel montage from localizer .mat file.""" X = io.loadmat(localizer_file, simplify_cells=True) ch_pos = {} for i in range(len(X["Channel"]) - 1): # final channel is reference key = X["Channel"][i]["Name"].split("_")[2] if key[:2] == "FP": key = "Fp" + key[2] ch_pos[key] = X["Channel"][i]["Loc"] hp = X["HeadPoints"]["Loc"] nas = np.mean([hp[:, 0], hp[:, 3]], axis=0) lpa = np.mean([hp[:, 1], hp[:, 4]], axis=0) rpa = np.mean([hp[:, 2], hp[:, 5]], axis=0) dig = mne.channels.make_dig_montage( ch_pos=ch_pos, nasion=nas, lpa=lpa, rpa=rpa, ) raw.set_montage(dig) return raw def create_heog(raw): """Create synthetic HEOG channel from F7-F8.""" heog = raw.get_data(picks="F7") - raw.get_data(picks="F8") info = mne.create_info(["HEOG"], raw.info["sfreq"], ["eog"]) raw.add_channels([mne.io.RawArray(heog, info)], force_update_info=True) return raw def process_session(session): """Preprocess a single session.""" raw = mne.io.read_raw_brainvision(session["raw_file"], preload=True) parallel.log("Setting channel montage...") raw = set_channel_montage(raw, session["localizer_file"]) parallel.log("Creating HEOG channel...") raw = create_heog(raw) raw.set_channel_types({"VEOG": "eog", "HEOG": "eog"}) parallel.log("Cropping first 15 seconds...") raw = raw.crop(tmin=15) raw = raw.notch_filter([50, 100]) raw = raw.filter( l_freq=0.5, h_freq=80, method="iir", iir_params={"order": 5, "ftype": "butter"}, ) raw = raw.resample(sfreq=250) raw = preproc.detect_bad_channels(raw, picks="eeg") raw = preproc.detect_bad_segments(raw, picks="eeg") raw = preproc.detect_bad_segments(raw, picks="eeg", mode="diff") parallel.log("Interpolating bad channels...") raw = raw.interpolate_bads() raw = raw.set_eeg_reference(projection=True) preproc.save_qc_plots(qc_dir, session["id"], raw) preproc_out_dir = output_dir / "preprocessed" preproc_out_dir.mkdir(parents=True, exist_ok=True) outfile = preproc_out_dir / f"{session['id']}_preproc-raw.fif" raw.save(outfile, overwrite=True) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 2: Surface Extraction Surface extraction only needs to be done once per subject (not per session), so we deduplicate by subject before dispatching. ```python from pathlib import Path import pandas as pd from osl_dynamics.meeg import parallel, rhino, Session output_dir = Path("derivatives") log_dir = Path("logs/2_surfaces") df = pd.read_csv("sessions.csv") subjects = [] for _, row in df.drop_duplicates("subject").iterrows(): subjects.append({ "id": row["subject"], "subject": row["subject"], "mri_file": row["mri_file"], }) def process_subject(subject): """Extract surfaces for a single subject.""" outdir = output_dir / "anat_surfaces" / subject["subject"] rhino.extract_surfaces( mri_file=subject["mri_file"], outdir=str(outdir), include_nose=False, ) if __name__ == "__main__": parallel.run( process_subject, items=subjects, log_dir=log_dir, n_workers=8, ) ``` ## Step 3: Coregistration The coregistration step includes a dataset-specific function to adjust headshape points and fiducials for EEG coregistration. The LEMON localizer positions need to be shrunk by 5% and the fiducials shifted down and back by 1 cm to account for systematic offsets. You will likely need to adapt `fix_headshape_fiducials` for your own dataset. Note for EEG we pass `include_eeg_as_headshape=True` when extracting fiducials and `use_headshape=False` during coregistration. ```python from pathlib import Path import numpy as np import pandas as pd from osl_dynamics.meeg import parallel, rhino, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/3_coreg") sessions = pd.read_csv("sessions.csv").to_dict("records") def fix_headshape_fiducials(session_files): """Shrink headshape and shift fiducials for EEG coregistration.""" coreg = session_files.coreg hs = np.loadtxt(coreg.head_headshape_file) nas = np.loadtxt(coreg.head_nasion_file) lpa = np.loadtxt(coreg.head_lpa_file) rpa = np.loadtxt(coreg.head_rpa_file) # Shrink headshape points by 5% hs *= 0.95 # Move fiducials down 1cm nas[2] -= 10 lpa[2] -= 10 rpa[2] -= 10 # Move fiducials back 1cm nas[1] -= 10 lpa[1] -= 10 rpa[1] -= 10 parallel.log(f"Overwriting {coreg.head_headshape_file}") np.savetxt(coreg.head_nasion_file, nas) np.savetxt(coreg.head_lpa_file, lpa) np.savetxt(coreg.head_rpa_file, rpa) np.savetxt(coreg.head_headshape_file, hs) def process_session(session): """Coregister a single session.""" preproc_file = output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif" surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=str(preproc_file), surfaces_dir=surfaces_dir, ) rhino.extract_fiducials_and_headshape_from_fif( session_files, include_eeg_as_headshape=True, ) parallel.log("Fixing headshape and fiducials...") fix_headshape_fiducials(session_files) rhino.coregister_head_and_mri( session_files, use_nose=False, use_headshape=False, ) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 4: Forward Model and Source Reconstruction This step computes the forward model and LCMV beamformer weights for each session. Key differences from MEG: - A Triple Layer forward model is used (instead of Single Layer). - The `eeg=True` flag is passed to the forward model. - Only the `eeg` channel type is used for the beamformer. ```python from pathlib import Path import pandas as pd import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, rhino, source_recon, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/4_source_recon") sessions = pd.read_csv("sessions.csv").to_dict("records") def process_session(session): """Source reconstruct a single session.""" preproc_file = str(output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif") surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=preproc_file, surfaces_dir=surfaces_dir, ) rhino.forward_model(session_files, model="Triple Layer", gridstep=8, eeg=True) source_recon.lcmv_beamformer(session_files, chantypes=["eeg"], rank={"eeg": 54}) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## Step 5: Parcellation The final step applies the beamformer, parcellates the voxel data, and saves the output. See the [parcellations page](user_guide/parcellations/index.html.md#parcellations) for the full list of available parcellations. ```python from pathlib import Path import pandas as pd import matplotlib matplotlib.use("Agg") from osl_dynamics.meeg import parallel, parcellation, Session output_dir = Path("derivatives") qc_dir = Path("qc") log_dir = Path("logs/5_parc") sessions = pd.read_csv("sessions.csv").to_dict("records") def process_session(session): """Parcellate a single session.""" preproc_file = str(output_dir / "preprocessed" / f"{session['id']}_preproc-raw.fif") surfaces_dir = str(output_dir / "anat_surfaces" / session["subject"]) session_files = Session( outdir=str(output_dir / "osl"), id=session["id"], preproc_file=preproc_file, surfaces_dir=surfaces_dir, ) parcellation_file = "atlas-DK_nparc-54_space-MNI_res-8x8x8.nii.gz" parcel_data = parcellation.parcellate_lcmv( session_files, parcellation_file=parcellation_file, orthogonalization="symmetric", ) parc_fif = str(output_dir / "osl" / session["id"] / "lcmv-parc-raw.fif") parcellation.save_as_fif( parcel_data, preproc_file, extra_chans="stim", filename=parc_fif, ) parcellation.save_qc_plots( qc_dir, session["id"], parc_fif, parcellation_file ) if __name__ == "__main__": parallel.run( process_session, items=sessions, output_dir=output_dir, log_dir=log_dir, qc_dir=qc_dir, n_workers=8, ) ``` ## QC Report Each step that is passed `qc_dir` writes `qc/report.html` when it finishes, with what has been saved so far. Open it in a browser. It is a table with one row per session next to the QC plots of the selected session: - The table holds the numbers the steps save: the percentage of bad segments and the number of bad channels (step 1), the overlap and mutual information of the MRI with the MNI152 template after registration (step 2) and the distance of the headshape points (here the electrodes) from the scalp after coregistration (step 3). Click a column to sort by it, which puts the worst sessions first. Values far from the rest of their column are highlighted. - The tabs show the plots of the selected session: the preprocessing plots (sensor-level PSD first), the extracted surfaces, the registration to MNI space (the red lines are the edges of the MNI152 template, they should follow the anatomy), the coregistration and the PSD of the parcel time courses. - The up/down arrow keys move between sessions and left/right between tabs. With many sessions it is quicker to sort by each metric and look at the plots of the worst sessions than to page through all of them. The report and its plots are all in `qc/`, so that directory can be copied or served on its own. ## Summary Each step can be run as a standalone script. The `parallel.run` utility handles multiprocessing, logging, and error recovery. The end of each session is printed to the screen, with the time it took. Everything else (the output of MNE, osl-dynamics, etc.) is written to a log file for the session in the `logs/` directory – check these if a session fails. Use `parallel.log` in the processing function to print a message to the screen as well, and `parallel.warning` for a session that finishes without everything it was meant to produce. When a step finishes, the number of sessions that were ok, partial (had warnings) and failed (raised an exception) is printed, with the warnings and errors they stopped on. The final parcellated data can be loaded for downstream analysis: ```default from osl_dynamics.data import Data training_data = Data( "derivatives/osl/sub-*/lcmv-parc-raw.fif", picks="misc", reject_by_annotation="omit", ) ``` See the [tutorials](tutorials.html.md) page for static and dynamic network analysis tutorials. **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 0-4_eeg_batch_processing.ipynb`](_downloads/e250796b3c92b76c8365ff96e1e5386e/0-4_eeg_batch_processing.ipynb) [`Download Python source code: 0-4_eeg_batch_processing.py`](_downloads/14f164094b74222e007b394a8b585204/0-4_eeg_batch_processing.py) [`Download zipped: 0-4_eeg_batch_processing.zip`](_downloads/09a9f10bc97cf201ddbe147c1b8e22bd/0-4_eeg_batch_processing.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/0-5_mne_sample_data.html.md #### NOTE [Go to the end](tutorials_build/0-5_mne_sample_data.html.md#sphx-glr-download-tutorials-build-0-5-mne-sample-data-py) to download the full example code. # MNE Sample Data: Bilateral Beamformer This tutorial performs an ‘OSL-style’ source reconstruction of the publicly available [MNE sample dataset](https://mne.tools/stable/documentation/datasets.html#sample), going from the raw sensor recording to parcellated source-space time courses, then uses the dataset’s auditory task to demonstrate the **bilateral beamformer**: 1. Preprocessing — Filter, downsample, detect bad segments. 2. Structural MRI Conversion — Convert the FreeSurfer MRI to NIfTI for FSL. 3. Surface Extraction — Extract skull/scalp surfaces from the structural MRI. 4. Coregistration — Align MEG sensor space to MRI space with RHINO. 5. Forward Model — Compute the lead field matrix. 6. Source Reconstruction — LCMV beamformer to project sensor data to source space. 7. Parcellation — Reduce voxel data to parcel time courses. 8. Bilateral Beamformer — Joint weights for pairs of bilaterally symmetric dipoles. 9. Evoked Responses — Compare the auditory evoked response from the standard and bilateral beamformer. A standard LCMV beamformer assumes sources are temporally uncorrelated. A source that is correlated with another source is treated as interference to suppress, so its reconstructed amplitude is underestimated. The canonical example is an auditory task: left and right auditory cortex respond simultaneously (and coherently) to a tone, so a standard beamformer partially cancels the bilateral auditory response. The fix is a ‘bilateral beamformer’ (a special case of the multiple constrained source beamformer of [Brookes et al. (2007)](https://doi.org/10.1016/j.neuroimage.2006.09.012)): instead of scanning one dipole at a time, we scan *pairs* of bilaterally symmetric dipoles jointly. The two dipoles’ lead fields are concatenated and a joint set of weights is computed, so neither dipole’s correlated twin is suppressed. The sample dataset is a good way to try the pipeline: it is downloaded with a single line of code and contains an auditory/visual task (auditory tones presented to the left or right ear, and left/right visual field stimuli) recorded on an Elekta Neuromag system, together with the subject’s structural MRI. This tutorial mirrors the more detailed [MEG preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md) — see that tutorial for a fuller explanation of each step (including ICA artefact rejection, which we skip here for brevity). ## Prerequisites - [FSL](https://fsl.fmrib.ox.ac.uk/fsl/fslwiki) (needed for surface extraction). - [osl-dynamics](https://github.com/OHBA-analysis/osl-dynamics). ## Download the dataset MNE-Python downloads the sample dataset (~1.6 GB) for us. By default it is saved to `~/mne_data`. ```python import mne data_path = mne.datasets.sample.data_path() raw_file = data_path / "MEG" / "sample" / "sample_audvis_raw.fif" t1_mgz = data_path / "subjects" / "sample" / "mri" / "T1.mgz" ``` ## Setup ```python import os from pathlib import Path import mne import nibabel as nib import numpy as np import matplotlib.pyplot as plt %matplotlib inline from osl_dynamics.meeg import preproc, rhino, source_recon, parcellation, Session # Session info id = "sample_audvis" # Paths output_dir = Path("derivatives") qc_dir = Path("qc") ``` ## Step 1: Preprocessing We clean the sensor-level MEG data by notch/bandpass filtering, resampling, and detecting bad segments. We keep the stimulus (“stim”) channels so we can epoch the parcellated data later. Note, this recording also contains EEG, which we drop here (the pipeline can source reconstruct EEG, but that requires a different forward model). ```python raw = mne.io.read_raw_fif(raw_file, preload=True) raw = raw.pick(["meg", "stim"]) # Filter and resample raw = raw.notch_filter([60]) # 60 Hz is the US mains frequency raw = raw.filter( l_freq=1, h_freq=45, method="iir", iir_params={"order": 5, "ftype": "butter"}, ) raw = raw.resample(sfreq=250) # Bad segment detection raw = preproc.detect_bad_segments(raw, picks="mag") raw = preproc.detect_bad_segments(raw, picks="mag", mode="diff") raw = preproc.detect_bad_segments(raw, picks="grad") raw = preproc.detect_bad_segments(raw, picks="grad", mode="diff") # Save preprocessed data preproc_file = output_dir / "preprocessed" / f"{id}_preproc-raw.fif" preproc_file.parent.mkdir(parents=True, exist_ok=True) raw.save(preproc_file, overwrite=True) ``` ## Step 2: Structural MRI Conversion The sample dataset provides the structural MRI in FreeSurfer’s `.mgz` format, but the FSL tools used for surface extraction need NIfTI. We convert with nibabel and then fix the sform code: nibabel labels the converted file’s sform as “aligned to another file” (code 2), whereas RHINO requires code 1 (scanner anatomical) or 4 (MNI). ```python smri_file = output_dir / "smri" / "sample-T1.nii.gz" smri_file.parent.mkdir(parents=True, exist_ok=True) nib.save(nib.load(t1_mgz), smri_file) os.system(f"fslorient -setsformcode 1 {smri_file}") ``` ## Step 3: Surface Extraction We extract the brain, inner skull and scalp surfaces from the structural MRI using FSL BET. The output plot (`surfaces.png`) overlays the extracted surfaces on the structural MRI: the brain surface in yellow, the inner skull in cyan and the scalp in magenta — check that each surface matches the corresponding anatomical boundary and lies inside the next. ```python surfaces_dir = str(output_dir / "anat_surfaces" / "sample") rhino.extract_surfaces( mri_file=str(smri_file), outdir=surfaces_dir, include_nose=False, show=True, ) ``` ## Step 4: Coregistration Coregistration aligns the MEG sensor coordinate system (“head” space) to the MRI coordinate system using the digitized fiducials and headshape points stored in the FIF file. First we create a `Session` to keep track of all the pipeline output files. ```python session = Session( outdir=str(output_dir / "osl"), id=id, preproc_file=str(preproc_file), surfaces_dir=surfaces_dir, ) rhino.extract_fiducials_and_headshape_from_fif(session) rhino.coregister_head_and_mri( session, use_nose=False, allow_mri_scaling=False, show=True, ) ``` The coregistration plot is saved to `session.coreg_dir/coreg.png`. Check that the headshape points (red dots) sit on the scalp surface and the sensors surround the head correctly. ## Step 5: Forward Model The forward model (lead field matrix) describes how a dipole at each source location projects onto the MEG sensors. We use a Single Layer (single shell) head model based on the inner skull surface and a dipole at each voxel of the 8 mm MNI152 brain mask (transformed into the subject’s MRI space), so the dipoles are at the same MNI coordinates for every subject and match the voxels of the parcellation files. ```python rhino.forward_model(session, model="Single Layer", gridstep=8) # gridstep in mm ``` ## Step 6: Source Reconstruction We use an LCMV (Linearly Constrained Minimum Variance) beamformer to project the sensor data into source space. Here we compute the beamformer weights (spatial filters), which we apply to the sensor data in the next step. ```python source_recon.lcmv_beamformer(session, chantypes=["mag", "grad"]) ``` #### NOTE A standard LCMV beamformer assumes sources are uncorrelated, and will partially suppress sources that are correlated across hemispheres — such as the bilateral auditory response in this dataset. We will fix this with the bilateral beamformer in Step 8. ## Step 7: Parcellation We reduce the source space to 52 parcel time courses using the Glasser parcellation, and save them as a FIF file. The `extra_chans="stim"` option carries the stimulus channels over to the parcellated data, so we can epoch it later. Note, we use `orthogonalization=None` here (rather than `"symmetric"`, the usual choice — see the [MEG preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md)). Symmetric orthogonalization removes all zero-lag correlations between parcels — which is exactly the correlated bilateral signal we want to study below. Leakage correction should not be used when analyzing zero-lag correlated task responses. ```python parcel_data = parcellation.parcellate_lcmv( session, parcellation_file="atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz", orthogonalization=None, ) print(f"Parcel data shape: {parcel_data.shape} (parcels x time)") parc_fif = str(output_dir / "osl" / id / "lcmv-parc-raw.fif") parcellation.save_as_fif( parcel_data, session.preproc_file, extra_chans="stim", filename=parc_fif, ) ``` As a sanity check, we plot the power spectral density (PSD) of each parcel. We expect ~1/f spectra with an alpha (~10 Hz) peak that is strongest in posterior parcels. ```python parcellation.save_qc_plots( qc_dir, id, parc_fif, "atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz", ) ``` ## Step 8: Bilateral Beamformer Now we repeat the source reconstruction with the bilateral beamformer. We simply pass `use_bilateral_pairs=True`: - Dipoles are mirrored across the midline of the MNI grid and paired with the closest dipole in the opposite hemisphere within the tolerance `bilateral_tol`. Because the dipoles are on an MNI grid, the mirror image of a dipole is exactly on the grid, so almost all pairs are exact mirror images. `bilateral_tol` is the mean absolute difference between the x, y and z coordinates of the mirrored dipoles and defaults to half the grid spacing (here: 8 mm grid, so 4 mm), so a dipole whose mirror image is outside the brain can be paired with a neighboring dipole. - Dipoles within `bilateral_tol_midline` of the midline, and dipoles with no match, are beamformed as usual (defaults to `bilateral_tol`). - Joint weights are computed for each pair by concatenating the two lead fields. We re-point `session.filters_file` first so we don’t overwrite the standard filters. ```python session.filters_file = f"{session.src_dir}/filters-bilateral-lcmv.h5" source_recon.lcmv_beamformer( session, chantypes=["mag", "grad"], use_bilateral_pairs=True, ) parcel_data = parcellation.parcellate_lcmv( session, parcellation_file="atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz", orthogonalization=None, ) bilateral_parc_fif = str(output_dir / "osl" / id / "lcmv-bilateral-parc-raw.fif") parcellation.save_as_fif( parcel_data, session.preproc_file, extra_chans="stim", filename=bilateral_parc_fif, ) ``` The beamformer prints how many pairs were found. To check the pairing, we plot it (saved to `session.src_dir/bilateral_dipoles.png`). Paired dipoles are red and joined by a line, blue dots are midline dipoles, gray circles are unpaired dipoles. ```python source_recon.plot_bilateral_pairs(session, show=True) ``` The bilateral beamformer requires a scalar beamformer (`pick_ori='max-power'` or `'max-power-pre-weight-norm'`, the default). ## Step 9: Evoked Responses The stim channels were carried through to the parcellated FIF files, so we can epoch the parcel data directly. Auditory tones are event IDs 1 (left ear) and 2 (right ear). ```python def epoch_parc(parc_fif): parc_raw = mne.io.read_raw_fif(parc_fif, preload=True) events = mne.find_events(parc_raw, min_duration=0.005) epochs = mne.Epochs( parc_raw, events, event_id={"auditory/left": 1, "auditory/right": 2}, tmin=-0.2, tmax=0.5, baseline=(None, 0), picks="misc", ) return epochs epochs_standard = epoch_parc(parc_fif) epochs_bilateral = epoch_parc(bilateral_parc_fif) ``` We find the parcels closest to left and right primary auditory cortex (MNI approximately (-52, -19, 7) and (52, -19, 7) mm) and compare the evoked response from the two beamformers. Note, beamformer time courses have an arbitrary sign, so we flip each evoked response such that its largest deflection in the M100 window is positive before plotting. ```python # Find the auditory parcels parc = parcellation.Parcellation( "atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz" ) centers = np.array(parc.roi_centers()) left_parcel = np.argmin(np.linalg.norm(centers - [-52, -19, 7], axis=1)) right_parcel = np.argmin(np.linalg.norm(centers - [52, -19, 7], axis=1)) def get_evoked(epochs, parcel): evoked = epochs.get_data().mean(axis=0)[parcel] t = epochs.times m100 = (t >= 0.05) & (t <= 0.15) sign = np.sign(evoked[m100][np.argmax(np.abs(evoked[m100]))]) return sign * evoked fig, axes = plt.subplots(1, 2, figsize=(12, 4)) for ax, parcel, title in [ (axes[0], left_parcel, "Left auditory cortex"), (axes[1], right_parcel, "Right auditory cortex"), ]: ax.plot( epochs_standard.times, get_evoked(epochs_standard, parcel), label="Standard", ) ax.plot( epochs_bilateral.times, get_evoked(epochs_bilateral, parcel), label="Bilateral", ) ax.axvline(0, color="k", lw=0.5) ax.set_xlabel("Time (s)") ax.set_title(title) ax.legend() ``` Both hemispheres show a clear evoked response peaking around 100 ms after the tone (the M100). Crucially, the bilateral beamformer recovers a larger response than the standard beamformer — the amplitude that the standard beamformer suppressed because the two hemispheres’ responses are correlated. ## Virtual Electrodes Parcel time courses summarize large regions. To look at the activity at a specific location we can compute a ‘virtual electrode’: the beamformer weights for a dipole at the exact MNI coordinate (rather than taking the nearest dipole of the 8 mm grid). The weights are computed with the same data covariance and settings as the filters in `session.filters_file` — here the bilateral filters, so each coordinate is paired with its mirror image. Passing an Epochs object gives the virtual electrode time course for each epoch. ```python events = mne.find_events(raw, min_duration=0.005) epochs = mne.Epochs( raw, events, event_id={"auditory/left": 1, "auditory/right": 2}, tmin=-0.2, tmax=0.5, baseline=(None, 0), preload=True, ) ve_data = source_recon.virtual_electrodes( session, [[-52, -19, 7], [52, -19, 7]], data=epochs ) print(f"Virtual electrode data shape: {ve_data.shape} (coords x time x epochs)") fig, ax = plt.subplots(figsize=(6, 4)) for evoked, label in zip(ve_data.mean(axis=-1), ["Left", "Right"]): ax.plot(epochs.times, evoked, label=label) ax.set_xlabel("Time (s)") ax.legend() ``` ## Wrap Up - We source reconstructed the MNE sample dataset with an ‘OSL-style’ pipeline: preprocess, extract surfaces, coregister (RHINO), forward model, LCMV beamformer, parcellate. - A standard LCMV beamformer suppresses correlated sources; for tasks with bilateral responses (auditory in particular) use `use_bilateral_pairs=True`. - The pairing tolerance `bilateral_tol` defaults to half the dipole grid spacing, which is usually what you want. - Use `orthogonalization=None` when analyzing zero-lag correlated responses — symmetric orthogonalization would remove them. - Check the dipole pairing QC plot (`bilateral_dipoles.png`). - Use `source_recon.virtual_electrodes` to get the time course at a specific MNI coordinate. **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 0-5_mne_sample_data.ipynb`](_downloads/b491a4738a156c1a1b595d1f3fa6c656/0-5_mne_sample_data.ipynb) [`Download Python source code: 0-5_mne_sample_data.py`](_downloads/366c7e30482328e9050a430e8a28076f/0-5_mne_sample_data.py) [`Download zipped: 0-5_mne_sample_data.zip`](_downloads/3ae15e8d392a936f04f4c092c8adcfb4/0-5_mne_sample_data.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/1-1_data_loading.html.md #### NOTE [Go to the end](tutorials_build/1-1_data_loading.html.md#sphx-glr-download-tutorials-build-1-1-data-loading-py) to download the full example code. # Loading Data In this tutorial we demonstrate the various options for loading data. This tutorial covers: 1. The Data Class 2. Getting Example Data 3. Loading Data in NumPy Format 4. Loading Data in MATLAB Format 5. Loading Data in fif Format 6. Loading Data in txt Format ## The Data class In osl-dynamics we typically load data using the [`osl_dynamics.data.base.Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data). The Data class has a lot of useful methods that can be used to modify the data. ### Inputs There is one mandatory argument that needs to be passed to the Data class: inputs. This can be: - A path to a directory containing .npy files. Each .npy file should be a subject or session. - A list of paths to .npy, .mat, .fif, or .txt files. Each file should be a subject or session. - A numpy array. The array will be treated as continuous data from the same subject. - A list of numpy arrays. Each numpy array should be the data for a subject or session. ### Data format The data files or numpy arrays should be in the format (n_samples, n_channels), i.e. time by channels. If your data is in (n_channels, n_samples) format, use should also pass time_axis_first=False to the Data class. ### The temporary store directory Note, there is an option to load the data as a [memory map](https://numpy.org/doc/stable/reference/generated/numpy.memmap.html). This allows us to access the data without holding it in memory. To use this feature, pass load_memmaps=True. The Data class creates a directory called tmp which is used for storing the memory map files (for the raw and prepared data). Each Data object writes to its own uniquely named sub-directory of tmp, which is deleted automatically when your script finishes. You can change where these temporary files are written by passing the store_dir argument. We will demonstrate how the Data class is used with example data below. ### Loading data in parallel The Data class has a n_jobs argument that can be used to load multiple data files in parallel. Note, if n_jobs is passed, the Data class will automatically also prepare data in parallel (see [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md) and [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md) for more information regarding data preparation). ## Getting Example Data ### Download the dataset We will download example data hosted on [OSF](https://osf.io/zxb6c/). ```Python import os def get_data(name): os.system(f"osf -p by2tc fetch data/{name}.zip") os.system(f"unzip -o {name}.zip -d {name}") os.remove(f"{name}.zip") return f"Data downloaded to: {name}" # Download the dataset (approximately 6 MB) get_data("example_loading_data") # List the contents of the downloaded directory containing the dataset print("Contents of example_loading_data:") os.listdir("example_loading_data") ``` ```none Contents of example_loading_data: ['txt_format', 'matlab_format', 'fif_format', 'numpy_format'] ``` We can see there are three directories in example_loading_data: - numpy_format, which contains .npy files. - matlab_format, which contains .mat files. - fif_format, which contains directories with .fif files. - txt_format, which contains .txt files. We’ll show how to load data in each of these data types. ## Loading Data in NumPy Format Let’s first list the example_loading_data/numpy_format directory. ```Python os.listdir("example_loading_data/numpy_format") ``` ```none ['array1.npy', 'array0.npy'] ``` We can see there’s two numpy files. These files contain 2D numpy array data. It is in time by channels format. If we wanted to load this data using the numpy package, we could do: ```Python import numpy as np # Just load one of the files X = np.load("example_loading_data/numpy_format/array0.npy") print(X.shape) ``` ```none (6000, 42) ``` ### Importing a numpy array directly If we have already loaded a numpy array and just want to create an osl_dynamics.data.Data object, we can simply pass it to the class: ```Python from osl_dynamics.data import Data data = Data(X) print(data) ``` ```none Loading files: 0%| | 0/1 [00:00 We normally like to keep the data for each subject separate. If we had multiple 2D numpy arrays (one for each subject), we can collate them into a python list and pass that to the Data class: ```Python # Load numpy files X0 = np.load("example_loading_data/numpy_format/array0.npy") X1 = np.load("example_loading_data/numpy_format/array1.npy") # Collate into a list X = [X0, X1] # Create a Data object data = Data(X) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 ### Loading from file Rather than loading the data into memory then creating a Data object, we could load the data directly from the file. ```Python # Just load one of the files data = Data("example_loading_data/numpy_format/array0.npy") print(data) ``` ```none Loading files: 0%| | 0/1 [00:00 We can see the data loaded matches the array shape when we loaded it using numpy. To access the 2D numpy array we can use the time_series() method. ```Python ts = data.time_series() print(ts.shape) ``` ```none (6000, 42) ``` Normally, we would want to load the data for multiple subjects. We could do this in two ways if the data is in numpy format (i.e. .npy). We could pass a list of file paths: ```Python files = [f"example_loading_data/numpy_format/array{i}.npy" for i in [0, 1]] data = Data(files) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 or just pass the path to the directory containing the .npy files: ```Python data = Data("example_loading_data/numpy_format") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 Note, when we have multiple subjects, if we call the time_series() method, we will now get a list of numpy arrays. Each item in the list is the data for each subject. ```Python ts = data.time_series() print(len(ts)) print(ts[0].shape) print(ts[1].shape) ``` ```none 2 (6000, 42) (6000, 42) ``` ## Loading Data in MATLAB Format We will discuss two methods for loading MATLAB files. First, we will load the MATLAB files using public python packages (scipy and mat73), then we’ll show how to pass MATLAB files to the Data class. ### Loading MATLAB files in Python The popular python package SciPy has a function for loading MATLAB files: [scipy.io.loadmat](https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html). Note, this function can only be used to load a newer version of MATLAB files, if you saved your files using v7.3 format, then you need to use [mat73.loadmat](https://github.com/skjerns/mat7.3) to load the file in python. Both of these packages are automatically installed when you install osl-dynamics. Let first see what files we have in the example_loading_data/matlab_format directory. ```Python os.listdir("example_loading_data/matlab_format") ``` ```none ['subject1.mat', 'subject0.mat'] ``` Let’s load the first subject’s data using standard python function. ```Python from scipy.io import loadmat # Load the first subject mat = loadmat("example_loading_data/matlab_format/subject0.mat") print(mat) ``` ```none {'__header__': b'MATLAB 5.0 MAT-file, Platform: MACA64, Created on: Thu May 15 21:24:56 2025', '__version__': '1.0', '__globals__': [], 'T': array([[6000]], dtype=uint16), 'X': array([[ 8.55446529, 6.2701211 , 14.08341885, ..., -3.40541101, 11.97496605, -9.9605751 ], [ 38.68119812, 70.39207458, -24.58280182, ..., -22.34135818, 91.68431854, 31.93983269], [-23.42669296, 58.61187744, 15.04336166, ..., -76.06550598, 17.29451942, -4.01404285], ..., [ -0.60452783, 52.73875809, -38.78281784, ..., 48.0056572 , -14.50024414, 21.15813446], [-15.44007874, 94.75162506, -68.22749329, ..., 26.43334007, -57.44473648, -18.39329338], [-72.70446014, 91.29540253, -74.58401489, ..., -37.10783768, -58.87734604, -23.26953506]])} ``` We can see the loadmat function returns a python dict. We can list the fields using: ```Python mat.keys() ``` ```none dict_keys(['__header__', '__version__', '__globals__', 'T', 'X']) ``` The important field is X, which contains the 2D time series data for this subject. ### Loading MATLAB data into the Data class We can pass the numpy array contained in the X field of the dictionary directly to the Data class: ```Python data = Data(mat["X"]) print(data) ``` ```none Loading files: 0%| | 0/1 [00:00 However, we would prefer to load the data directly from the file. We can do this by passing the file path to the .mat file and the data_field argument to the Data class. ```Python data = Data("example_loading_data/matlab_format/subject0.mat", data_field="X") print(data) ``` ```none Loading files: 0%| | 0/1 [00:00 Note, the default value for the data_field argument is X, so the Data class would still be able to load the data without it being passed. The data_field is useful if the data is contained in a MATLAB in a field with a different name. If we wanted to load multiple data files in MATLAB format we would need to pass a list of file paths. ```Python files = [f"example_loading_data/matlab_format/subject{i}.mat" for i in [0, 1]] data = Data(files) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 ## Loading Data in fif Format Another data format that can be loaded with the Data class is fif files. This format is commonly used in [MNE-Python](https://mne.tools/stable/index.html) and is the data format used in [osl-ephys](https://github.com/OHBA-analysis/osl-ephys). Here, we will load source reconstruct (parcellated) data created with osl-ephys. In osl-ephys, we often have a separate directory for each subject. The fif_format directory contains two directories for different subjects. ```Python os.listdir('example_loading_data/fif_format') ``` ```none ['sub-002_run-01', 'sub-001_run-01'] ``` Let’s see what’s inside sub-001_run-01. ```Python os.listdir('example_loading_data/fif_format/sub-001_run-01') ``` ```none ['sub-001_run-01_sflip_lcmv-parc-raw.fif'] ``` We have a fif file which contains the data for this subject. We could load this with MNE. ```Python import mne raw = mne.io.read_raw_fif("example_loading_data/fif_format/sub-001_run-01/sub-001_run-01_sflip_lcmv-parc-raw.fif") print(raw.info) ``` ```none Opening raw data file example_loading_data/fif_format/sub-001_run-01/sub-001_run-01_sflip_lcmv-parc-raw.fif... Range : 61000 ... 68500 = 244.000 ... 274.000 secs Ready. ``` We can see this particular fif file contains 38 misc channels and 3 stim channels. We’re interested in the misc channels. Let’s load these into the Data class. ```Python data = Data( "example_loading_data/fif_format/sub-001_run-01/sub-001_run-01_sflip_lcmv-parc-raw.fif", picks="misc", reject_by_annotation="omit", ) print(data) ``` ```none Loading files: 0%| | 0/1 [00:00 The reject_by_annotation=”omit” argument is used to make sure we don’t include bad segments. This argument is passed to [Raw.get_data](https://mne.tools/stable/generated/mne.io.Raw.html#mne.io.Raw.get_data) in MNE. To load multiple subjects we can do: ```Python files =[ f"example_loading_data/fif_format/sub-{i:03d}_run-01/sub-{i:03d}_run-01_sflip_lcmv-parc-raw.fif" for i in range(1,3) ] data = Data(files, picks="misc", reject_by_annotation="omit") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 ## Loading Data in txt Format The final data format we will load using the Data class is txt files. FMRI data preprocessed with [FSL](https://fsl.fmrib.ox.ac.uk/fsl/docs/) is in this format. To load this type of data simply pass the list of filenames. ```Python files =[ f"example_loading_data/txt_format/dr_stage1_subject{i:05d}.txt" for i in range(1,3) ] data = Data(files) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 [`Download Jupyter notebook: 1-1_data_loading.ipynb`](_downloads/12f6ef2fa24d2df688be82e8e559c79b/1-1_data_loading.ipynb) [`Download Python source code: 1-1_data_loading.py`](_downloads/172f946d7db233bb7d40b9cbf690d204/1-1_data_loading.py) [`Download zipped: 1-1_data_loading.zip`](_downloads/b90c6d94e968f84a58e18ab13347f9f4/1-1_data_loading.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/1-2_data_prepare_meg.html.md #### NOTE [Go to the end](tutorials_build/1-2_data_prepare_meg.html.md#sphx-glr-download-tutorials-build-1-2-data-prepare-meg-py) to download the full example code. # Preparing M/EEG Data In this tutorial we will go through common ways to prepare M/EEG data. This tutorial covers: 1. Downloading example data 2. Time-Delay Embedding (and Principal Component Analysis) 3. Amplitude Envelope 4. Saving and Loading Prepared Data ## Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name): os.system(f"osf -p by2tc fetch data/{name}.zip") os.system(f"unzip -o {name}.zip -d {name}") os.remove(f"{name}.zip") return f"Data downloaded to: {name}" # Download the dataset (approximately 6 MB) get_data("example_loading_data") # List the contents of the downloaded directory containing the dataset print("Contents of example_loading_data:") os.listdir("example_loading_data") ``` ```none Contents of example_loading_data: ['txt_format', 'matlab_format', 'fif_format', 'numpy_format'] ``` ### Loading the data Now, let’s load the example data into osl-dynamics. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("example_loading_data/numpy_format") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 We can see we have data for two subjects. ## The prepare method The [`osl_dynamics.data.base.Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) class has many methods available for manipulating the data. See the docs for a full list. We will describe two common approaches for preparing the data: - TDE-PCA - Amplitude Envelope. We will use the prepare method to do this. This method takes a dict containing method names to call and arguments to pass to them. ### TDE-PCA Time-delay embedding (TDE) is a process of augmenting a time series with extra channels. These extra channels are time-lagged versions of the original channels. We do this to add extra entries to the covariance matrix of the data which are sensitive to the frequency of oscillations in the data. Here, we demonstrate how to apply this process to data. For further details, including the impact of different parameters, see the [TDE tutorial](tutorials_build/1-4_data_time_delay_embedding.html.md). Performing TDE often results in a very large number of channels. Consequently, Principal Component Analysis (PCA) is often used to reduce the number of channels. Both TDE and PCA can be done in one step using the tde_pca method. We often also want to standardize (z-score) the data before training a model. Both of these steps can be done with the prepare method. ```Python data = Data("example_loading_data/numpy_format") print(data) methods = { "tde_pca": {"n_embeddings": 15, "n_pca_components": 80}, "standardize": {}, } data.prepare(methods) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 We can see the n_samples attribute of our Data object has changed from 12000 to 11972. We have lost 28 samples. This is due to the TDE. We lose n_embeddings // 2 data points from each end of the time series for each subject. In other words, with n_embeddings=15, we lose the first 7 and last 7 data points from each subject. We lose a total of 28 data points because we have 2 subjects. When we perform PCA a pca_components attribute is added to the Data object. This is the (n_raw_channels, n_pca_components) shape array that is used to perform PCA. ```Python pca_components = data.pca_components print(pca_components.shape) ``` ```none (630, 80) ``` ### Amplitude envelope Another approach for preparing data is to calculate the amplitude envelope. Here, we obtain a time series that characterizes the amplitude of oscilations. To prepare amplitude envelope data, we perform a few steps. It’s common to first filter a frequency range of interest before calculating the amplitude envelope. Calculating a moving average has also been found to help smooth the data. Finally, standardization is always recommended for models in osl-dynamics. ```Python data = Data("example_loading_data/numpy_format", sampling_frequency=200) print(data) methods = { "filter": {"low_freq": 7, "high_freq": 13}, # study the alpha-band "amplitude_envelope": {}, "moving_average": {"n_window": 5}, "standardize": {}, } data.prepare(methods) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 When we apply a moving average we lose a few time points from each end of the time series for each subject. We lose n_window // 2 time points, for n_window=5 we lose 2 time points from the start and end. This totals to 4 time points lost for each subject. We can see this looking at the n_samples attribute of the Data object, where we have lost 4 time points for each subject, totaling to 8 time points. ### Accessing the prepared and raw data After preparing the data, the Data.time_series method will return the prepared data. ```Python ts = data.time_series() # ts is a list of subject-specific numpy arrays print(ts[0].shape) ``` ```none (5996, 42) ``` We can see the shape of the data indicates it is the prepared data. The raw data is still accessible by passing prepared=False to the Data.time_series method. ```Python raw = data.time_series(prepared=False) # raw is a list of subject-specific numpy arrays print(raw[0].shape) ``` ```none (6000, 42) ``` ## Saving and Loading Prepared Data ### Saving prepared data For large datasets, preparing the data can sometimes be time consuming. In this case it is useful to save the data after preparing it. Then we can just load the prepared data before training a model. To save prepared data we can use the save method. We simply need to pass the output directory to write the data to. ```Python data.save("prepared_data") ``` ```none Saving data: 0%| | 0/2 [00:00 This method has created a directory called prepared_data. Let’s list its contents. ```Python os.listdir('prepared_data') ``` ```none ['preparation.pkl', 'array1.npy', 'array0.npy'] ``` We can see each subject’s data is saved as a numpy file and there is an additional pickle (.pkl) file which contains information regarding how the data was prepared. ### Loading prepared data We can load the prepared data by simply passing the path to the directory to the Data class. ```Python data = Data("prepared_data") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 If the dataset is too large to fit in memory, you can save it as a TFRecord dataset instead, which can be streamed from disk during training. See the Training on large datasets section of the [HMM training tutorial](tutorials_build/3-2_hmm_training.html.md). ```python data.save_tfrecord_dataset("tfrecords", sequence_length=200) ``` We can see from the number of samples it is the amplitude envelope data that we previously prepared. Note, if we saved data that included PCA in preparation. The pca_components attribute will be loaded from the pickle file when we load data using the Data class. **Total running time of the script:** (0 minutes 0.228 seconds) [`Download Jupyter notebook: 1-2_data_prepare_meg.ipynb`](_downloads/f758560759c8cfc26cc5cbe66dedde53/1-2_data_prepare_meg.ipynb) [`Download Python source code: 1-2_data_prepare_meg.py`](_downloads/5661a09b1b2198fbc17e69d3f7753b9b/1-2_data_prepare_meg.py) [`Download zipped: 1-2_data_prepare_meg.zip`](_downloads/f9733ced6a6470b76dde2d94a1f05f41/1-2_data_prepare_meg.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/1-3_data_prepare_fmri.html.md #### NOTE [Go to the end](tutorials_build/1-3_data_prepare_fmri.html.md#sphx-glr-download-tutorials-build-1-3-data-prepare-fmri-py) to download the full example code. # Preparing fMRI Data In this tutorial we discuss how to prepare fMRI data. This tutorial covers: 1. Preparing group-ICA data 2. Preparing anatomically parcellated data 3. Saving and loading prepared data fMRI data needs to be preprocessed in a particular way to train a dynamic network model (HMM/DyNeMo), see this [paper](https://www.sciencedirect.com/science/article/pii/S1053811922001550) for further details. This is make sure we infer good dynamics (state switching) in the data. We advise training a model on the group-ICA time courses (which are prepared by standardizing the data) or using an anatomical parcellation (which is prepared using a full rank PCA). ## Preparing group-ICA data This is the recommended data to train an HMM/DyNeMo on. ### Deriving subject-specific time series via dual regression This section describes how group ICA time courses can be extracted from preprocessed fMRI data using **dual regression**. This process is applicable to data in both volumetric space and surface space. **1. Input Requirements** Dual regression requires two inputs: the preprocessed subject data and a set of group-level spatial maps (Group ICA) to act as a template. **A. Preprocessed Subject Data** Ensure your subject data has been preprocessed in one of the following formats: - **Volumetric Space:** Standard 4D fMRI nifti files. - **Surface Space:** Data processed using the Human Connectome Project (HCP) surface-based pipeline (CIFTI/GIFTI formats). **B. Group ICA Maps (Spatial Templates)** You must provide a set of group-level spatial maps. These are typically obtained by running group-level Independent Component Analysis (ICA) using FSL MELODIC. These maps function as a “soft parcellation” of the brain, identifying functional networks common across the group. For technical details on generating these maps, refer to the [FSL MELODIC Documentation](https://web.mit.edu/fsl_v5.0.10/fsl/doc/wiki/MELODIC.html). **2. Dual Regression** To derive the final subject-specific time series, you must run dual Regression on your preprocessed data (Input A) using the Group ICA maps (Input B) as the spatial regressors. **Understanding the Output Stages** Dual regression is a two-stage process. **Stage 1: Spatial Regression** In this first stage, the group-level spatial maps (e.g. from UKB or HCP) are regressed into the subject’s 4D dataset. > **Key Output:** The result of Stage 1 is the **Group ICA time courses**. These represent the subject-specific temporal dynamics associated with each group-level spatial component. **Stage 2: Temporal Regression** The time courses from stage 1 are used in the second stage to regress against the subject’s data again to find subject-specific *spatial* maps. > **Note:** if you only require the time series, Stage 1 is your endpoint. **3. Further Reading & Resources** For a comprehensive technical explanation of the mathematical framework behind dual regression, please consult the official FSL documentation and course materials: - [FSL Wiki: Dual Regression Details](https://web.mit.edu/fsl_v5.0.10/fsl/doc/wiki/DualRegression.html#Research_Overview_-_Dual_Regression). - [ICA and Dual Regression (FSL Course)](https://fsl.fmrib.ox.ac.uk/fslcourse/2019_Beijing/lectures/ICA_and_resting_state/ICA_and_Dual_Regression.pdf). ### Example data We will download example data hosted on [OSF](https://osf.io/by2tc/) that we have already calculated dual regression for. ```Python import os def get_data(name): os.system(f"osf -p by2tc fetch data/{name}.zip") os.system(f"unzip -o {name}.zip -d {name}") os.remove(f"{name}.zip") return f"Data downloaded to: {name}" # Download the dataset (approximately 6 MB) get_data("example_loading_data") # List the contents of the downloaded directory containing the dataset print("Contents of example_loading_data:") os.listdir("example_loading_data") ``` ```none Contents of example_loading_data: ['txt_format', 'matlab_format', 'fif_format', 'numpy_format'] ``` Now, let’s load the example data into osl-dynamics. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("example_loading_data/txt_format") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 To prepare the data, all we need to do is standardize it. Let’s use the Data.prepare method to do this. ```Python data.prepare({"standardize": {}}) ``` ```none Standardizing: 0%| | 0/2 [00:00 ``` Note, this is equivalent to data.standardize(). ## Preparing anatomically parcellated data Alternatively, if you have defined regions of interest (ROIs) using an anatomical parcellation and loaded these into osl-dynamics instead of the group-ICA time courses, it is important to apply PCA to infer good dynamics (state switching). Below we apply a full rank PCA to the data. ```Python data.prepare({ "pca": {"n_pca_components": data.n_channels}, "standardize": {}, }) ``` ```none Calculating PCA components: 0%| | 0/2 [00:00 ``` You can access the PCA components via data.pca_components. ## Saving and Loading Prepared Data ### Saving prepared data For large datasets, preparing the data can sometimes be time consuming. In this case it is useful to save the data after preparing it. Then we can just load the prepared data before training a model. To save prepared data we can use the save method. We simply need to pass the output directory to write the data to. ```Python data.save("prepared_data") ``` ```none Saving data: 0%| | 0/2 [00:00 This method has created a directory called prepared_data. Let’s list its contents. ```Python import os os.listdir('prepared_data') ``` ```none ['preparation.pkl', 'array1.npy', 'array0.npy'] ``` We can see each subject’s data is saved as a numpy file and there is an additional pickle (.pkl) file which contains information regarding how the data was prepared. ### Loading prepared data We can load the prepared data by simply passing the path to the directory to the Data class. ```Python data = Data("prepared_data") print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 If the dataset is too large to fit in memory, you can save it as a TFRecord dataset instead, which can be streamed from disk during training. See the Training on large datasets section of the [HMM training tutorial](tutorials_build/3-2_hmm_training.html.md). ```python data.save_tfrecord_dataset("tfrecords", sequence_length=200) ``` Note, if we saved data that included PCA in preparation. The pca_components attribute will be loaded from the pickle file when we load data using the Data class. ## Next steps Once you have loaded and prepared your fMRI data, the next step is to train a dynamic network model. See: - [HMM: Training](tutorials_build/3-2_hmm_training.html.md) - [DyNeMo: Training](tutorials_build/3-3_dynemo_training.html.md) **Total running time of the script:** (0 minutes 0.077 seconds) [`Download Jupyter notebook: 1-3_data_prepare_fmri.ipynb`](_downloads/7153e598368c1761a9649d55173030e1/1-3_data_prepare_fmri.ipynb) [`Download Python source code: 1-3_data_prepare_fmri.py`](_downloads/0f4e0bcb8a60234847905be5afe6ecfe/1-3_data_prepare_fmri.py) [`Download zipped: 1-3_data_prepare_fmri.zip`](_downloads/3c5487c2d095fef58637950812fca6b0/1-3_data_prepare_fmri.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/1-4_data_time_delay_embedding.html.md #### NOTE [Go to the end](tutorials_build/1-4_data_time_delay_embedding.html.md#sphx-glr-download-tutorials-build-1-4-data-time-delay-embedding-py) to download the full example code. # Time-Delay Embedding In this tutorial we will explore the impact of different settings for time-delay embedding (n_embeddings) and the number of principal component analysis (PCA) components (n_pca_components). Time-delay embedding (TDE) is a process of augmenting a time series with extra channels. These extra channels are time-lagged versions of the original channels. We do this to add extra entries to the covariance matrix of the data which are sensitive to the frequency of oscillations in the data. To understand this better, let’s simulate some sinusoidal data. ```Python import numpy as np import matplotlib.pyplot as plt # Simulate data: # - Channel 1: 10 Hz sine wave # - Channel 2: 20 Hz sine wave # - Channel 3: 20 Hz sine wave synchronized with channel 2 but with different amplitude n = 10000 t = np.arange(n) / 200 # we're using a sampling frequency of 200 Hz p = np.random.uniform(0, 2 * np.pi, size=(2,)) # random phases x = np.array([ 1.0 * np.sin(2 * np.pi * 10 * t + p[0]), 1.5 * np.sin(2 * np.pi * 20 * t + p[1]), 0.6 * np.sin(2 * np.pi * 20 * t + p[1]), # same phase as channel 2 ]) # Add some noise x += np.random.normal(0, 0.1, size=x.shape) # Plot first 0.2 s fig, ax = plt.subplots(nrows=3, ncols=1) ax[0].plot(t[:40], x[0,:40], label="Channel 1") ax[1].plot(t[:40], x[1,:40], label="Channel 2") ax[2].plot(t[:40], x[2,:40], label="Channel 3") ax[0].set_ylabel("Channel 1") ax[1].set_ylabel("Channel 2") ax[2].set_ylabel("Channel 3") ax[2].set_xlabel("Time (s)") plt.tight_layout() ``` Let’s plot the covariance of this data. ```Python cov = np.cov(x) plt.matshow(cov) plt.colorbar() ``` ```none ``` The covariance here is a 3x3 matrix because we have 3 channels. The diagonal of this matrix is the variance and reflects the amplitude of each sine wave. The off-diagonal elements reflect the covariance between channels. In this example the covariance between the channels 1 and 2 is close to zero, however there is some covariance between channels 2 and 3 due to the phase synchronization. Let’s see what happens to the covariance matrix when we TDE the data. ```Python from osl_dynamics.data import Data # First load the data into osl-dynamics data = Data(x, time_axis_first=False) print(data) # Perform time-delay embedding data.tde(n_embeddings=5) ``` ```none Loading files: 0%| | 0/1 [00:00 ``` See the [Data loading tutorial](tutorials_build/1-1_data_loading.html.md) for further details regarding how to load data using the [`osl_dynamics.data.base.Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) class. In the above code we chose n_embeddings=5. This means for every original channel, we add n_embeddings - 1 = 4 extra channels. In our three channel example, the operation we do is: $\begin{pmatrix} x(t) \\ y(t) \\ z(t) \end{pmatrix} \rightarrow \begin{pmatrix} x(t-2) \\ x(t-1) \\ x(t) \\ x(t+1) \\ x(t+2) \\ y(t-2) \\ y(t-1) \\ y(t) \\ y(t+1) \\ y(t+2) \\ z(t-2) \\ z(t-1) \\ z(t) \\ z(t+1) \\ z(t+2) \end{pmatrix}$ We should expect a total of n_embeddings \* 3 channels, in our example this is 5 \* 3 = 15. We can verify this by printing the Data object. ```Python print(data) ``` ```none Data id: bea5480d4dcd47d6832fa3cbf0458b44 n_sessions: 1 n_samples: 9996 n_channels: 15 ``` We can see we have 15 channels as expected. Note, we have also lost n_embeddings - 1 = 4 time points (we have 9996 samples when originally we simulated 10000). This is because we don’t have the full window to TDE the time points at the start and end of the time series. Let’s look at the covariance of the TDE data. ```Python cov_tde = np.cov(data.time_series(), rowvar=False) plt.matshow(cov_tde) plt.colorbar() ``` ```none ``` This covariance matrix is 15x15 because we have 15 channels. The blocks on the diagonal of the above matrix represents the covariance of a channel with a time-lagged version of itself - this quantity is known as the **auto**-correlation function. Blocks on the off-diagonal represent the covariance of a channel with a time-lagged version of **another** channel - this quantity is known as the **cross**-correlation function. We can extract an estimate of the auto/cross-correlation function (A/CCF) by taking values from this covariance matrix. osl-dynamics has a function we can use for this: [`osl_dynamics.analysis.post_hoc.autocorr_from_tde_cov()`](autoapi/osl_dynamics/analysis/post_hoc/autocorr_from_tde_cov.html.md#osl_dynamics.analysis.post_hoc.autocorr_from_tde_cov). This function will extract both ACFs and CCFs from a TDE covariance matrix. ```Python from osl_dynamics.analysis import post_hoc, spectral # Extract A/CCFs from the covariance tau, acf = post_hoc.autocorr_from_tde_cov(cov_tde, n_embeddings=5) print(acf.shape) # channels x channels x time lags # Plot ACFs plt.plot(tau, acf[0,0], label="Channel 1") plt.plot(tau, acf[1,1], label="Channel 2") plt.plot(tau, acf[2,2], label="Channel 3") plt.xlabel("Time Lag (Samples)") plt.ylabel("ACF (a.u)") plt.legend() plt.tight_layout() ``` ```none (3, 3, 9) ``` The diagonal of acf represents the ACF, e.g. acf[0,0] is the ACF for for channel 1 (indexed by 0). The off-diagonal of acf represent the CCF, e.g. acf[0,1] is the CCF for channel 1 and 2. The ACF and power spectral density (PSD) form a Fourier pair. This means we can calculate an estimate of the PSD of each channel by Fourier transforming the ACF. Let’s do this using the [`osl_dynamics.analysis.spectral.autocorr_to_spectra()`](autoapi/osl_dynamics/analysis/spectral/autocorr_to_spectra.html.md#osl_dynamics.analysis.spectral.autocorr_to_spectra) function in osl-dynamics. Note, this function will also calculate cross PSD using the CCFs. ```Python # Calculate PSD by Fourier transforming the ACF f, psd, _ = spectral.autocorr_to_spectra(acf, sampling_frequency=200) print(psd.shape) # channels x channels x frequency # Plot plt.plot(f, psd[0,0], label="Channel 1") plt.plot(f, psd[1,1], label="Channel 2") plt.plot(f, psd[2,2], label="Channel 3") plt.xlabel("Frequency (Hz)") plt.ylabel("PSD (a.u)") plt.legend() ``` ```none (3, 3, 33) ``` We can see the 20 Hz peak in the channel 2, which corresponds well to what we simulated. We also see a smaller 20 Hz peak for channel 3. However, we aren’t able to resolve the 10 Hz peak we simulated for channel 1. This was because we didn’t use enough lags to resolve the 10 Hz peak. Note, we can see some ringing, this is due to padding the ACF with zeros (to obtain an integer multiple of 2) before calculating the Fourier transform, we can change the padding via the nfft argument to [`osl_dynamics.analysis.spectral.autocorr_to_spectra()`](autoapi/osl_dynamics/analysis/spectral/autocorr_to_spectra.html.md#osl_dynamics.analysis.spectral.autocorr_to_spectra). Let’s try again with more lags - this will mean we evaluate the ACF for a greater window of time lags, this will result in a higher resolution PSD. ```Python # Redo the TDE on the original data data.tde(n_embeddings=11, use_raw=True) print(data) # Calculate TDE covariance, ACF and PSD cov_tde = np.cov(data.time_series(), rowvar=False) tau, acf = post_hoc.autocorr_from_tde_cov(cov_tde, n_embeddings=11) f, psd, _ = spectral.autocorr_to_spectra(acf, sampling_frequency=200) # Plot fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(10, 3)) ax[0].matshow(cov_tde) ax[1].plot(tau, acf[0,0]) ax[1].plot(tau, acf[1,1]) ax[1].plot(tau, acf[2,2]) ax[1].set_xlabel("Time Lag (Samples)") ax[1].set_ylabel("ACF (a.u.)") ax[2].plot(f, psd[0,0], label="Channel 1") ax[2].plot(f, psd[1,1], label="Channel 2") ax[2].plot(f, psd[2,2], label="Channel 2") ax[2].set_xlabel("Frequency (Hz)") ax[2].set_ylabel("PSD (a.u.)") ax[2].legend() plt.tight_layout() ``` ```none Applying TDE: 0%| | 0/1 [00:00 We can see the ACF extends over a wider range and we’re now able to better model the 10 Hz sine wave in channel 1. We can also see what happens if we change the frequency of the sine wave for channel 1. Let’s simulate a 30 Hz sine wave for channel 1. ```Python # Simulate new data x = np.array([ 1.0 * np.sin(2 * np.pi * 30 * t + p[0]), # 30 Hz 1.5 * np.sin(2 * np.pi * 20 * t + p[1]), 0.6 * np.sin(2 * np.pi * 20 * t + p[1]), # same phase as channel 2 ]) x += np.random.normal(0, 0.15, size=x.shape) data = Data(x, time_axis_first=False) # TDE data.tde(n_embeddings=11) # Calculate TDE covariance, ACF and PSD cov_tde = np.cov(data.time_series(), rowvar=False) tau, acf = post_hoc.autocorr_from_tde_cov(cov_tde, n_embeddings=11) f, psd, _ = spectral.autocorr_to_spectra(acf, sampling_frequency=200) # Plot fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(10, 3)) ax[0].matshow(cov_tde) ax[1].plot(tau, acf[0,0]) ax[1].plot(tau, acf[1,1]) ax[1].plot(tau, acf[2,2]) ax[1].set_xlabel("Time Lag (Samples)") ax[1].set_ylabel("ACF (a.u.)") ax[2].plot(f, psd[0,0], label="Channel 1") ax[2].plot(f, psd[1,1], label="Channel 2") ax[2].plot(f, psd[2,2], label="Channel 2") ax[2].set_xlabel("Frequency (Hz)") ax[2].set_ylabel("PSD (a.u.)") ax[2].legend() plt.tight_layout() ``` ```none Loading files: 0%| | 0/1 [00:00 We can see the covariance of the TDE data, as well as the ACF/PSD has, changed to reflect the frequency of data. The above example shows how TDE leads to covariance matrices that are sensitive to oscillatory frequencies in the original data and how the number of embeddings relates to the frequency resolution that can be modeled. In addition to modeling the frequency of oscillations in an individual channel, we can also model phase synchronization across channels using TDE data. We can see from the above TDE covariance matrix the off-diagonal block for channels 2 and 3 (row 10-20, column 20-30) shows some structure. Let’s plot the CCF for each pair of channels. ```Python plt.plot(tau, acf[0,1], label="Channel 1+2") plt.plot(tau, acf[1,2], label="Channel 2+3") plt.xlabel("Time Lag (Samples)") plt.ylabel("CCF (a.u.)") plt.legend() ``` ```none ``` The structure in the CCF for channels 2 and 3 shows the time-lagged versions of these channels are correlated. Such structure arises from phase synchronization. In contrast, we don’t see any structure for the CCF between channels 1 and 2. This is because we simulated random phases for these channels. Let’s plot the cross PSD for these channels. ```Python plt.plot(f, psd[0,1], label="Channel 1+2") plt.plot(f, psd[1,2], label="Channel 2+3") plt.xlabel("Frequency (Hz)") plt.ylabel("Cross PSD (a.u)") plt.legend() ``` ```none ``` We can see the cross PSD indicates the frequencies which show phase synchronization. In the above examples we have shown how the covariance of TDE data can capture the oscillatory properties (power spectra and frequency-specific coupling) of a time series. ## Impact of different parameters When we apply TDE-PCA, we need to specify the number of embeddings and PCA components. The number of embeddings affects the frequencies we are able to distinguish in the data. To demonstrate we can simulate sinusoidal data and apply TDE. ```Python from osl_dynamics.analysis import spectral def calc_covs_psds(frequencies, n_embeddings, fs): covs = [] psds = [] t = np.arange(1000) / fs for F in frequencies: x = np.sin(2 * np.pi * F * t)[:, np.newaxis] data = Data(x) data.prepare({ "tde": {"n_embeddings": n_embeddings}, "standardize": {}, }) cov = np.cov(data.time_series(), rowvar=False) tau, acf = post_hoc.autocorr_from_tde_cov(cov, n_embeddings=n_embeddings) f, p, _ = spectral.autocorr_to_spectra( acf[np.newaxis, np.newaxis, :], sampling_frequency=fs, ) covs.append(cov) psds.append(p) return covs, psds frequencies = [1, 4, 8, 13, 20, 30, 40] n_embeddings = 5 fs = 250 covs, psds = calc_covs_psds(frequencies, n_embeddings, fs) ``` ```none Loading files: 0%| | 0/1 [00:00 Let’s plot the covariance of the TDE data and corresponding PSD for these different sine waves. ```Python def plot_covs_psds(covs, psds): fig, ax = plt.subplots(nrows=2, ncols=len(psds), figsize=(12,3)) for i in range(len(psds)): ax[0, i].set_title(f"f={frequencies[i]} Hz") ax[0, i].imshow(covs[i]) ax[0, i].axis("off") ax[1, i].plot(f, psds[i]) ax[1, i].set_xlim(1, 45) ax[1, i].set_ylim(0, np.max(psds)) ax[1, i].set_xlabel("Frequency (Hz)") ax[1, 0].set_ylabel("PSD (a.u.)") plt.tight_layout() plot_covs_psds(covs, psds) ``` We can see despite using a small number of embeddings we are sensitive to a changes in a wide range of frequencies. However, we see we strugle to distinguish between low frequencies. We can improve the frequency resolution by increasing the number of embeddings. Let’s do ```Python frequencies = [1, 4, 8, 13, 20, 30, 40] n_embeddings = 11 fs = 250 covs, psds = calc_covs_psds(frequencies, n_embeddings, fs) plot_covs_psds(covs, psds) ``` ```none Loading files: 0%| | 0/1 [00:00 We can see with 11 embeddings, we can get much sharper peaks in the PSD. Note, the sensitivity to different frequencies also depends on the sampling frequency. We advise making the above plots for the sampling frequency you have and ensure you have a high enough number of emebdding to give sufficient frequency resolution. The number of embeddings will also depend on the PCA step that’s normally performed after TDE. The higher the number of embeddings the more PCA components you will need to retain high frequency oscillations. Let’s explore this further using real data. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name): os.system(f"osf -p by2tc fetch data/{name}.zip") os.system(f"unzip -o {name}.zip -d {name}") os.remove(f"{name}.zip") return f"Data downloaded to: {name}" # Download the dataset (approximately 6 MB) get_data("example_loading_data") # List the contents of the downloaded directory containing the dataset print("Contents of example_loading_data:") os.listdir("example_loading_data") ``` ```none Contents of example_loading_data: ['txt_format', 'matlab_format', 'fif_format', 'numpy_format'] ``` Let’s load the data in numpy format. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("example_loading_data/numpy_format", sampling_frequency=250) print(data) ``` ```none Loading files: 0%| | 0/2 [00:00 We can see we have data for two subjects. ### Apply TDE and PCA Both TDE and PCA can be done in one step using the tde_pca method. We often also want to standardize (z-score) the data before training a model. Both of these steps can be done with the prepare method. ```Python methods = { "tde_pca": {"n_embeddings": 15, "n_pca_components": 80}, "standardize": {}, } data.prepare(methods) print(data) ``` ```none Calculating PCA components: 0%| | 0/2 [00:00 We can see the n_samples attribute of our Data object has changed from 147500 to 147472. We have lost 28 samples. This is due to the TDE. We lose n_embeddings // 2 data points from each end of the time series for each subject. In other words, with n_embeddings=15, we lose the first 7 and last 7 data points from each subject. We lose a total of 28 data points because we have 2 subjects. ### Scan different parameters Let calculate the PSD of prepared data using different parameters for TDE-PCA. ```Python def calc_psds(n_time_embeddings, n_pca_components, fs): psds = [] for i, n_tde in enumerate(n_time_embeddings): psds.append([]) for n_pca in n_pca_components: methods = { "tde_pca": {"n_embeddings": n_tde, "n_pca_components": n_pca, "use_raw": True}, "standardize": {}, } data.prepare(methods) spectra = spectral.welch_spectra( data.time_series(concatenate=True), sampling_frequency=fs, frequency_range=[1, 45], cross_spectra=False, ) f = spectra.frequencies p = np.mean(spectra.psd[0], axis=0) # average over channels psds[-1].append(p) return f, psds n_time_embeddings = [7, 11, 15, 19] n_pca_components = [40, 60, 80, 100, 120, 140] fs = 250 f, psds = calc_psds(n_time_embeddings, n_pca_components, fs) ``` ```none Calculating PCA components: 0%| | 0/2 [00:00 Let’s plot the PSD for each set of parameters. ```Python fig, ax = plt.subplots(nrows=1, ncols=len(n_time_embeddings), figsize=(12,3)) for i, n_tde in enumerate(n_time_embeddings): for j, n_pca in enumerate(n_pca_components): ax[i].plot(f, psds[i][j], label=f"{n_pca} PCA") ax[i].set_xlabel("Frequency (Hz)") ax[0].set_ylabel("PSD (a.u.)") ax[0].legend() ``` ```none ``` We see as we increase the number of PCA components, we retrain more high frequency oscillations. It is important to use enough PCA components to keep the frequency range you’re interested in studying. Typically, this is at least twice the number of original channels. Note, it is also important to select enough embeddings to be sensitive to the frequencies you’re interested in based on the simulated data. The best parameters for TDE-PCA depend on your sampling frequency. In the above example, we looked at data at 250 Hz. Usually 15 embeddings and over twice the number of original channels works well. For 100 Hz data, normally 7 embeddings works well. **We advise you make the above plots for your own dataset to select the number of embeddings and PCA components.** **Total running time of the script:** (0 minutes 5.868 seconds) [`Download Jupyter notebook: 1-4_data_time_delay_embedding.ipynb`](_downloads/58fabbed2b9fcd24690c0bd07260d68f/1-4_data_time_delay_embedding.ipynb) [`Download Python source code: 1-4_data_time_delay_embedding.py`](_downloads/d6b5263888f24ae5e600c3b0a7d9215c/1-4_data_time_delay_embedding.py) [`Download zipped: 1-4_data_time_delay_embedding.zip`](_downloads/096c6466fc3e973b8f2d855c97cc834b/1-4_data_time_delay_embedding.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/2-1_static_spectra_analysis.html.md #### NOTE [Go to the end](tutorials_build/2-1_static_spectra_analysis.html.md#sphx-glr-download-tutorials-build-2-1-static-spectra-analysis-py) to download the full example code. # Static: Spectral Analysis MEG data is useful because it has a high temporal resolution. We can take advantage of this by examining the spectral (i.e. frequency) content of the data. In this tutorial we will perform static spectral analysis on source space MEG data. This tutorial covers: 1. Getting the data 2. Calculating spectra for each subject ## Getting the data We will use resting-state MEG data that has already been source reconstructed. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ### Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data", n_jobs=4) print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 For static analysis we just need the time series for the parcellated data. We can access this using the time_series method. ```Python ts = data.time_series() ``` ts a list of numpy arrays. Each numpy array is a (n_samples, n_channels) time series for each subject. ## Subject-Level Analysis In this section, we will ignore the fact this data was collected in a task paradigm and will just aim to study the power spectrum of each subject. ### Calculate power spectra Using the data we just loaded, we want to calculate the power spectra for each channel (ROI) for each subject. We will use the [`osl_dynamics.analysis.static.welch_spectra()`](autoapi/osl_dynamics/analysis/static/welch_spectra.html.md#osl_dynamics.analysis.static.welch_spectra) function to do this. This function implements Welch’s methods for calculating power spectra. To use this function we need to specify at least two arguments: - sampling_frequency. This is to ensure we get the correct frequency axis for the power spectra. - window_length. This is the number of samples in the sliding window. The longer the window the smaller the frequency resolution of the power spectrum. Twice the sampling frequency is generally a good choice for this, which gives a frequency resolution of 0.5 Hz. We can also specify an optional argument: - standardize. This will z-score the data (for each subject separately) before calculate the power spectra. This can be helpful if you want to examine power the fraction of power in a frequency band relative to the total power (across all frequencies) of the subject. ```Python from osl_dynamics.analysis import static spectra = static.welch_spectra( data=ts, sampling_frequency=250, window_length=500, standardize=True, ) print(spectra) ``` ```none Calculating spectra: 0%| | 0/5 [00:00 spectra is a [`StaticSpectra`](autoapi/osl_dynamics/analysis/spectral/StaticSpectra.html.md#osl_dynamics.analysis.spectral.StaticSpectra) object. spectra.frequencies is the frequency axis of the power spectra in Hz and spectra.psd contains the power spectra. It also contains the coherence between channels (spectra.coherence). Calculating power spectra can be time consuming. We will want to use the power spectra many times to make different plots. We don’t want to have to calculate them repeatedly, so often it is convenient to save the spectra so we can load them later (instead of calculating them again). Let’s save the spectra. ```Python os.makedirs("spectra", exist_ok=True) spectra.save("spectra/static.npz") ``` ### Plot the power spectra Let’s first load the power spectra we previously calculated. ```Python import numpy as np from osl_dynamics.analysis import spectral spectra = spectral.Spectra.load("spectra/static.npz") f = spectra.frequencies psd = spectra.psd ``` To understand these arrays it’s useful to print their shape: ```Python print(f.shape) print(psd.shape) ``` ```none (251,) (5, 38, 251) ``` We can see f is a 1D numpy array of length 256. This is the frequency axis of the power spectra. We can see psd is a subjects by channels (ROIs) by frequency array. E.g. psd[0] is a (38, 256) shaped array containing the power spectra for each of the 38 ROIs. Let’s plot the power spectrum for each ROI for the first subject. We will use the [`osl_dynamics.utils.plotting`](autoapi/osl_dynamics/utils/plotting/index.html.md#module-osl_dynamics.utils.plotting) module to do the basic plotting. See the Plotting tutorial for further info. ```Python from osl_dynamics.utils import plotting fig, ax = plotting.plot_line( [f] * psd.shape[1], psd[0], x_label="Frequency (Hz)", y_label="PSD (a.u.)", ) ``` Each line in this plot is a ROI. We can see there’s a lot of activity in the 1-20 Hz range. Let’s zoom into the 1-45 Hz range. ```Python fig, ax = plotting.plot_line( [f] * psd.shape[1], psd[0], x_label="Frequency (Hz)", y_label="PSD (a.u.)", x_range=[1, 45], ) ``` Note, if you wanted to save this as an image you could pass a filename=”.png” argument to this function. All functions in [`osl_dynamics.utils.plotting`](autoapi/osl_dynamics/utils/plotting/index.html.md#module-osl_dynamics.utils.plotting) have this argument. Rather than plotting the power spectrum for each ROI, let’s average over channels to give a single line for each subject. ```Python # Average over channels psd_mean = np.mean(psd, axis=1) # Plot the mean power spectrum for the first subject fig, ax = plotting.plot_line( [f], [psd_mean[0]], x_label="Frequency (Hz)", y_label="PSD (a.u.)", x_range=[1, 45], ) ``` We can add a shaded area around the solid line to give an idea of the variability around the mean. ```Python # Standard deviation around the mean psd_std = np.std(psd, axis=1) # Plot with one sigma shaded fig, ax = plotting.plot_line( [f], [psd_mean[0]], errors=[[psd_mean[0] - psd_std[0]], [psd_mean[0] + psd_std[0]]], x_label="Frequency (Hz)", y_label="PSD (a.u.)", x_range=[1, 45], ) ``` Finally, let’s plot the average power spectrum for each subject in the same figure. ```Python fig, ax = plotting.plot_line( [f] * psd.shape[0], psd_mean, x_label="Frequency (Hz)", y_label="PSD (a.u.)", x_range=[1, 45], ) ``` We can see there’s quite a bit of variation in the static power spectrum for each subject. Some subjects have a pronounced alpha (around 10 Hz) peak. Some subjects have high beta (around 20 Hz) activity, others don’t. **Total running time of the script:** (0 minutes 1.460 seconds) [`Download Jupyter notebook: 2-1_static_spectra_analysis.ipynb`](_downloads/4568d07fe679d48cb51414717fb11a36/2-1_static_spectra_analysis.ipynb) [`Download Python source code: 2-1_static_spectra_analysis.py`](_downloads/b750a48b1d224a3fd216c272b0432c49/2-1_static_spectra_analysis.py) [`Download zipped: 2-1_static_spectra_analysis.zip`](_downloads/59ca7a07eeb3d3773d93b3ac40c192b9/2-1_static_spectra_analysis.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/2-2_static_power_analysis.html.md #### NOTE [Go to the end](tutorials_build/2-2_static_power_analysis.html.md#sphx-glr-download-tutorials-build-2-2-static-power-analysis-py) to download the full example code. # Static: Power Analysis In this tutorial we will perform static power analysis on source space MEG data. This tutorial covers: 1. Getting the data 2. Calculating power from spectra ## Getting the data We will use resting-state MEG data that has already been source reconstructed. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ## Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data", n_jobs=4) print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 For static analysis we just need the time series for the parcellated data. We can access this using the time_series method. ```Python ts = data.time_series() ``` ts a list of numpy arrays. Each numpy array is a (n_samples, n_channels) time series for each subject. ## Calculate spectra First, we calculate the subject-specific power spectra. See the Static Power Spectra Analysis tutorial for more comprehensive description of power spectra analysis. ```Python from osl_dynamics.analysis import static # Calculate power spectra spectra = static.welch_spectra( data=ts, sampling_frequency=250, window_length=500, standardize=True, ) # Save os.makedirs("spectra", exist_ok=True) spectra.save("spectra/static.npz") ``` ```none Calculating spectra: 0%| | 0/5 [00:00 ## Calculate power Let’s first load the power spectra we previously calculated. ```Python from osl_dynamics.analysis import spectral spectra = spectral.Spectra.load("spectra/static.npz") ``` To understand the spectra it’s useful to print the shape of the frequency axis and the power spectra: ```Python print(spectra.frequencies.shape) print(spectra.psd.shape) ``` ```none (251,) (5, 38, 251) ``` We can see spectra.frequencies is a 1D numpy array of length 256. This is the frequency axis of the power spectra. We can see spectra.psd is a subjects by channels (ROIs) by frequency array. E.g. spectra.psd[0] is a (38, 256) shaped array containing the power spectra for each of the 38 ROIs. A useful property of a power spectrum is that the integral over a frequency range gives the power (or equivalently the variance of activity over the frequency range). osl-dynamics has a [`osl_dynamics.analysis.power`](autoapi/osl_dynamics/analysis/power/index.html.md#module-osl_dynamics.analysis.power) module for performing power analyses. Let’s say we are interested in alpha (10 Hz) power. We can calculate alpha power by averaging a power spectrum over a frequency range near 10 Hz. Typically, 8-13 Hz power is referred to as the ‘alpha band’. Other common frequency bands are: - Delta: 1-4 Hz. - Theta: 4-8 Hz. - Beta: 13-30 Hz. - Gamma: 30+ Hz. The power_maps method calculates power from the spectra. Let’s use it to calculate power for the alpha band. ```Python # Calculate power in the alpha band (8-13 Hz) from the spectra p = spectra.power_maps(frequency_range=[8, 13]) ``` Note, if frequency_range is not passed, power_maps will average the power spectrum over all frequencies. Pass method=”integral” to integrate the power spectrum (the variance), or bands=[[1, 4], [4, 8], [8, 13], [13, 30]] to calculate several bands at once. We can print the shape of the p array to help understand what is contained within it. ```Python print(p.shape) ``` ```none (5, 38) ``` From this, we can see it is a subjects by ROIs array. It has averaged the power spectrum for each ROI separately. If we wanted the alpha power at each ROI for the first subject, we would use p[0], which would be a (38,) shaped array. ## Plot power maps We can use [`power.save`](autoapi/osl_dynamics/analysis/power/save.html.md#osl_dynamics.analysis.power.save) to visualize the power maps. Let’s plot the group average. ```Python from osl_dynamics.analysis import power group_p = spectra.group_average().power_maps(frequency_range=[8, 13]) fig, ax = power.save( group_p, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/1 [00:00 Or we can plot power maps for individual subjects, e.g. ```Python fig, ax = power.save( p[:4], # first four parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/4 [00:00 [`Download Jupyter notebook: 2-2_static_power_analysis.ipynb`](_downloads/c31d9fa824daa9fd39c044ad40b68761/2-2_static_power_analysis.ipynb) [`Download Python source code: 2-2_static_power_analysis.py`](_downloads/e22f3a3a6dd40b877129a26756a57741/2-2_static_power_analysis.py) [`Download zipped: 2-2_static_power_analysis.zip`](_downloads/7d31e4d206e81cd1740d35c33d0166b0/2-2_static_power_analysis.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/2-3_static_aec_analysis.html.md #### NOTE [Go to the end](tutorials_build/2-3_static_aec_analysis.html.md#sphx-glr-download-tutorials-build-2-3-static-aec-analysis-py) to download the full example code. # Static: Amplitude Envelope Correlation (AEC) Analysis In this tutorial we will perform static AEC analysis on source space MEG data. This tutorial covers: 1. Getting the data 2. Calculating AEC networks ## Getting the data We will use resting-state MEG data that has already been source reconstructed. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ### Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data", n_jobs=4) print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 For static analysis we just need the time series for the parcellated data. We can access this using the time_series method. ```Python ts = data.time_series() ``` ts a list of numpy arrays. Each numpy array is a (n_samples, n_channels) time series for each subject. ## Calculating AEC Networks Next, we will estimate static networks for each subject. For this we need to define a metric for connectivity between ROIs. There are a lot of options for this. In this tutorial we’ll look at the **amplitude envelope correlation (AEC)**. ### Calculate AEC AEC can be calculated from the parcellated time series directly. First, we need to prepare the parcellated data. Previously we loaded the data using the [`Data class`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data). Fortunately, the Data class has a prepare method that makes this easy. Let’s prepare the data for calculate the AEC network for activity in the alpha band (8-12 Hz). ```Python # Before we can prepare the data we must specify the sampling frequency # (this is needed to bandpass filter the data) data.set_sampling_frequency(250) # Calculate amplitude envelope data for the alpha band (7-13 Hz) methods = { "standardize": {}, "filter": {"low_freq": 7, "high_freq": 13}, "amplitude_envelope": {}, } data.prepare(methods) # Get the amplitude envelope time series for each subject (ts is a list of numpy arrays) ts = data.time_series() ``` ```none Standardizing: 0%| | 0/5 [00:00 Note, other common frequency bands are: - Delta: 1-4 Hz. - Theta: 4-7 Hz. - Beta: 13-30 Hz. - Gamma: 30+ Hz. Next, we want to calculate the correlation between amplitude envelopes. osl-dynamics has the [`analysis.static.functional_connectivity`](autoapi/osl_dynamics/analysis/static/functional_connectivity.html.md#osl_dynamics.analysis.static.functional_connectivity) function for this. ```Python from osl_dynamics.analysis import static # Calculate the correlation between amplitude envelope time series aec = static.functional_connectivity(ts) ``` ```none Calculating FC: 0%| | 0/5 [00:00 We can understand the aec array by printing its shape. ```Python print(aec.shape) ``` ```none (5, 38, 38) ``` We can see it is a subject by ROIs by ROIs array. It contains all pairwise connections between ROIs. ## Visualizing networks A common approach for plotting a network is as a matrix. We can do this with the [`plotting.plot_matrices`](autoapi/osl_dynamics/utils/plotting/plot_matrices.html.md#osl_dynamics.utils.plotting.plot_matrices) function in osl-dynamics. ```Python from osl_dynamics.utils import plotting # Just plot the first 3 fig, ax = plotting.plot_matrices(aec[:3], titles=[f"Subject {i+1}" for i in range(3)]) ``` The diagonal is full of ones and is a lot larger then the off-diagonal values. This means our color scale doesn’t show the off-diagonal structure very well. We can zero the diagonal to improve this. ```Python import numpy as np mat = np.copy(aec) # we don't want to change the original aec array for m in mat: np.fill_diagonal(m, 0) # Just plot first 3 fig, ax = plotting.plot_matrices(mat[:3], titles=[f"Subject {i+1}" for i in range(3)]) ``` We can now see the off-diagonal structure a bit better. We also see there is a lot of variability between subjects. Another way we can visualize the network is a glass brain plot. We can do this using the [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save) function in osl-dynamics. This function is a wrapper for the nilearn function [plot_connectome](https://nilearn.github.io/stable/modules/generated/nilearn.plotting.plot_connectome.html). Let’s use [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save) to plot the first subject’s AEC network. ```Python from osl_dynamics.analysis import connectivity connectivity.save( aec[0], parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/1 [00:00 If we wanted to save the plot to an image file we could pass the filename argument. If we wanted to pass any arguments to nilearn’s [plot_connectome](https://nilearn.github.io/stable/modules/generated/nilearn.plotting.plot_connectome.html) function, we could use the plot_kwargs argument. Let’s pass some extra arguments to [plot_connectome](https://nilearn.github.io/stable/modules/generated/nilearn.plotting.plot_connectome.html) to adjust the color bar and color map. ```Python connectivity.save( aec[0], parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"edge_vmin": 0, "edge_vmax": 0.4, "edge_cmap": "Reds"}, ) ``` ```none Saving images: 0%| | 0/1 [00:00 In the above plot we see every pairwise connection. Often, we’re just interested in the strongest connections - this helps us to avoid interpreting connections that are simply due to noise. Next, let’s see how we threshold the networks. ### Thresholding networks by specifying a percentile We can use the [`connectivity.threshold`](autoapi/osl_dynamics/analysis/connectivity/threshold.html.md#osl_dynamics.analysis.connectivity.threshold) function in osl-dynamics to select the strongest connections. The easiest way to threshold is to pass the percentile argument, let’s select the top 5% of connections. ```Python thres_aec = connectivity.threshold(aec, percentile=95) ``` Note, [`connectivity.threshold`](autoapi/osl_dynamics/analysis/connectivity/threshold.html.md#osl_dynamics.analysis.connectivity.threshold) acts on the connectivity matrix from each subject separately. ### Subject-specific networks Next, let’s plot the AEC network for the first 3 subjects, thresholding the top 5%. ```Python # Keep the top 5% of connections thres_aec = connectivity.threshold(aec, percentile=95) # Plot connectivity.save( thres_aec[:3], parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"edge_vmin": 0, "edge_vmax": 0.5, "edge_cmap": "Reds"}, ) ``` ```none Saving images: 0%| | 0/3 [00:00 We see there is some structure in the networks. We also observed there is significant subject-to-subject variation. ### Group averaged networks Estimating subject-specific connectivity networks is often very noisy. Cleaner networks come out when we average over groups as this removes noise. Let’s plot the group average AEC network. ```Python # Average over the group group_aec = np.mean(aec, axis=0) # Keep the top 5% of connections thres_group_aec = connectivity.threshold(group_aec, percentile=95) # Plot connectivity.save( thres_group_aec, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"edge_vmin": 0, "edge_vmax": 0.5, "edge_cmap": "Reds"}, ) ``` ```none Saving images: 0%| | 0/1 [00:00 Note, we can also plot an AEC network as a 3D glass brain plot using [`connectivity.save_interactive`](autoapi/osl_dynamics/analysis/connectivity/save_interactive.html.md#osl_dynamics.analysis.connectivity.save_interactive). ```Python # Display the network connectivity.save_interactive( thres_group_aec, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/1 [00:00 We can see from the above plot averaging over a large group gives us a cleaner network. This is simply due to the data being noisy which makes estimating networks hard. Averaging over subjects helps remove this noise. In the group average network we can see the strongest connections are in posterior regions as expected. ### Data-driven thresholding Another option is rather than specifying a percentile by hand, we can use a Gaussian Mixture Model (GMM) fit with two components (an ‘on’ and an ‘off’ component) to determine a threshold for selecting connections. The way this works is we fit two Gaussians to the distribution of connections. To understand this, let’s first examine the distribution of connections. ```Python import matplotlib.pyplot as plt def plot_dist(values): """Plots a histogram.""" fig, ax = plt.subplots() n, bins, patches = ax.hist(values.flatten(), bins=50, histtype="step") ax.set_xlabel("AEC") ax.set_ylabel("Number of edges") # Plot distribution of connections plot_dist(group_aec) ``` We see there is a cluster of connections between AEC=0 and 0.4 and another at AEC=1. The AEC=1 connections are on the diagonal of the connectivity matrix. Let’s remove these to examine the distribution of off-diagonal elements, which is what we’re interested in. ```Python # Fill diagonal with nan values # (nan is preferred to zeros because a zeo value will be included in the distribution, nans won't) np.fill_diagonal(group_aec, np.nan) # Note, np.fill_diagonal alters the group_aec array in place, # i.e. we don't need to do aec_mean = np.fill_diagonal(aec_mean, np.nan) # Plot distribution of connections plot_dist(group_aec) ``` We can see there is a peak around AEC=0.05 and a long tail for higher values. We want the connections around the AEC=0.05 peak to be captured by a Gaussian and the long tail to be captured by another Gaussian. Let’s fit a two component Gaussian to this distribution. Fortunately, osl-dynamics has a function to do this for us: [`analysis.connectivity.fit_gmm`](autoapi/osl_dynamics/analysis/connectivity/fit_gmm.html.md#osl_dynamics.analysis.connectivity.fit_gmm). This function returns the threshold (as a percentile) that determines the Gaussian component a connection belongs to. ```Python # Fit a two-component Gaussian mixture model to the connectivity matrix percentile = connectivity.fit_gmm(group_aec, show=True) print("Percentile:", percentile) ``` ```none Percentile: 66.99857752489332 ``` Let’s now use the data-driven threshold to select connections in our network. ```Python # Threshold thres_group_aec = connectivity.threshold(group_aec, percentile=percentile) # Display the network connectivity.save_interactive( thres_group_aec, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"edge_cmap": "Reds", "symmetric_cmap": False}, ) ``` ```none Saving images: 0%| | 0/1 [00:00 We can a lot more connections now. We can be more extreme with the connections we choose by enforcing the likelihood a of a connection belonging to the ‘off’ component is below a certain p-value. For example, if we wanted to show the connections belonging to the ‘on’ GMM component, that had a likelihood of less than 0.01 of belonging to the ‘off’ component, we could do the following: ```Python # Fit a two-component Gaussian mixture model to the connectivity matrix # ensuring the threshold is beyond a p-value of 0.01 of belonging to the off component percentile = connectivity.fit_gmm(group_aec, p_value=0.01, show=True) print("Percentile:", percentile) ``` ```none Percentile: 84.06827880512091 ``` We can see the threshold has moved much more to the right now. Let’s example the network with this threshold. ```Python # Threshold thres_group_aec = connectivity.threshold(group_aec, percentile=percentile) # Display the network connectivity.save_interactive( thres_group_aec, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"edge_cmap": "Reds", "symmetric_cmap": False}, ) ``` ```none Saving images: 0%| | 0/1 [00:00 Note, osl-dynamics has a wrapper function to return the thresholded network directly (so you don’t need to threshold yourself): [`connectivity.gmm_threshold`](autoapi/osl_dynamics/analysis/connectivity/gmm_threshold.html.md#osl_dynamics.analysis.connectivity.gmm_threshold). Using this function, we can threshold connectivity matrix in one line: ```default thres_aec_mean = connectivity.gmm_threshold(aec_mean, p_value=0.01) ``` **Total running time of the script:** (0 minutes 6.546 seconds) [`Download Jupyter notebook: 2-3_static_aec_analysis.ipynb`](_downloads/342c57018a4cb539249d29c814564685/2-3_static_aec_analysis.ipynb) [`Download Python source code: 2-3_static_aec_analysis.py`](_downloads/598b434e4e0fee21221792b374494897/2-3_static_aec_analysis.py) [`Download zipped: 2-3_static_aec_analysis.zip`](_downloads/04911eca7dd678faf724473e1f2026d0/2-3_static_aec_analysis.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/3-1_sliding_window_analysis.html.md #### NOTE [Go to the end](tutorials_build/3-1_sliding_window_analysis.html.md#sphx-glr-download-tutorials-build-3-1-sliding-window-analysis-py) to download the full example code. # Sliding Window Analysis In this tutorial we will use a sliding window technique, which is a common approach for studying network dynamics, to analyze source space MEG data. fMRI data can easily be substituted. This tutorial covers: 1. Getting the Data 2. Estimating Networks using a Sliding Window 3. Clustering the Networks ## Getting the Data We will use resting-state MEG data that has already been source reconstructed. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 70 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ### Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data", n_jobs=4) # Display some summary information print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 For the sliding window analysis we just need the time series for the parcellated data. We can access this using the time_series method. ```Python ts = data.time_series() ``` ## Estimating Networks using a Sliding Window A sliding window network analysis involves: - Taking a segment of your time series, i.e. a window. We need to pre-specify the length of the window. - Estimating a network using the window. - Sliding the window along the time series. - Estimating a network using the new window. - Repeat. This results in a series of networks. Important aspects of this technique are: - A useful advantage of this technique is you can use any metric you like for the pairwise connectivity as long as you can calculate it from the data in a window. - The main limitation of this approach is you have to pre-specify the window length. If you don’t know the time scale of dynamics in the time series, specifying the window length is difficult. - There is a trade-off between having long windows which will lead to an accurate estimate of a network but long temporal specificity, whereas a short window has good temporal specificity but can give noisy estimates of network connections. ### Sliding window connectivity using the Pearson correlation Now that we have loaded the data we want to study, let’s estimate sliding window networks. The first thing we need to do is choose the the metric for connectivity we will use. In this tutorial we’re use the absolute value of the Pearson correlation of the source space time series. osl-dynamics has a function for calculating sliding window networks: [`analysis.connectivity.sliding_window_connectivity`](autoapi/osl_dynamics/analysis/connectivity/sliding_window_connectivity.html.md#osl_dynamics.analysis.connectivity.sliding_window_connectivity). Let’s use this function to calculate dynamics networks. ```Python from osl_dynamics.analysis import connectivity # Calculate the sliding window connectivity swc = connectivity.sliding_window_connectivity(ts, window_length=100, step_size=50, conn_type="corr") ``` ```none Calculating sliding window connectivity: 0%| | 0/5 [00:00 swc is a list of numpy arrays. Each subject has its own numpy array which is a series of connectivity matrices. Let’s concatenate these to give one time series and take the absolute value. ```Python import numpy as np swc_concat = np.concatenate(swc) swc_concat = np.abs(swc_concat) print(swc_concat.shape) ``` ```none (7430, 38, 38) ``` We can see there are a total of 14,520 windows we calculated networks for. Let’s plot the first few networks. We can use the [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save) function to do this. ```Python connectivity.save( swc_concat[:5], parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", threshold=0.95, # only display the top 5% of connections ) ``` ```none Saving images: 0%| | 0/5 [00:00 Clearly, these networks are very noisy. The large number of networks also makes the sliding window networks difficult to interpret. A common next step is to cluster the sliding window networks to give a discrete set of networks. We’ll do this next. ## Clustering the Networks ### K-means clustering The most common approach used for clustering is the K-means algorithm. We will use sci-kit learn’s K-means class to cluster the sliding window connectivities. The documentation for sci-kit learn’s K-means class is [here](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html). First, let’s initiate a K-means object. When we do this we need to specify the number of clusters. We will use 6. ```Python from sklearn.cluster import KMeans # Initiate the K-means class kmeans = KMeans(n_clusters=6, n_init="auto", verbose=0) ``` Next, we need to prepare the input for the K-means algorithm. It requires a set of vectors, which is stored as a 2D numpy array. To convert our connectivity matrices to vectors, we will simply take the upper right triangle. We can do this because we know correlation matrices are symmetric. ```Python # Get indices that correspond to an upper triangle of a matrix # (not including the diagonal) n_channels = swc_concat.shape[-1] i, j = np.triu_indices(n_channels, k=1) # Now let's convert the sliding window connectivity matrices to a series of vectors swc_vectors = swc_concat[:, i, j] ``` We can check this worked by printing the shape of the swc_vectors array. ```Python print(swc_vectors.shape) ``` ```none (7430, 703) ``` We expect the vectors to have 42 \* 41 // 2 = 861 elements (upper triangle of a square matrix), which matches the second dimension. Now we can train the Kmeans algorithm using the fit method. ```Python kmeans.fit(swc_vectors) ``` We can access the cluster centroids using the cluster_centers_ attribute. Let’s see what this gives and print the shape to double check it’s what we expected. ```Python centroids = kmeans.cluster_centers_ print(centroids.shape) ``` ```none (6, 703) ``` We see the first dimension is the number of clusters and the second dimension is the length of the input vectors, which is what we expect. Now, we just need to put the vectors back into ROIs by ROIs form and then we can visualize them as networks. ```Python n_clusters = centroids.shape[0] n_channels = data.n_channels # Convert from a vector to a connectivity matrix kmean_networks = np.empty([n_clusters, n_channels, n_channels]) kmean_networks[:, i, j] = centroids kmean_networks[:, j, i] = centroids ``` Finally, let’s display the Kmeans networks using glass brain plots. ```Python connectivity.save( kmean_networks, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", threshold=0.95, # only display the top 5% of connections ) ``` ```none Saving images: 0%| | 0/6 [00:00 We can see clustering the networks significantly improves them. **Total running time of the script:** (0 minutes 5.162 seconds) [`Download Jupyter notebook: 3-1_sliding_window_analysis.ipynb`](_downloads/71b17583d1db42febd82b2e6fedf7867/3-1_sliding_window_analysis.ipynb) [`Download Python source code: 3-1_sliding_window_analysis.py`](_downloads/280372ca56d4077621ada6735f785161/3-1_sliding_window_analysis.py) [`Download zipped: 3-1_sliding_window_analysis.zip`](_downloads/7d7cc66a52c2d6ca93e8a1f27f8a8e97/3-1_sliding_window_analysis.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/3-2_hmm_training.html.md #### NOTE [Go to the end](tutorials_build/3-2_hmm_training.html.md#sphx-glr-download-tutorials-build-3-2-hmm-training-py) to download the full example code. # HMM: Training This tutorial covers how to train an HMM. We will use MEG data in this tutorial, however, this can easily be substituted with fMRI data. ## Getting the Data We will use resting-state MEG data that has already been source reconstructed and prepared. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. - Prepared using 15 time-delay embeddings and 80 PCA components. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 21 MB) get_data("notts_meguk_giles_prepared_1_subject", rename="prepared_data") ``` ### Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```python from osl_dynamics.data import Data data = Data("prepared_data") print(data) ``` If you run into an out of memory error when training, see the Training on large datasets section below. ## Fitting an HMM ### The Config object First need to specify the [`Config object`](autoapi/osl_dynamics/models/hmm/Config.html.md#osl_dynamics.models.hmm.Config) for the HMM. This is a class that acts as a container for all hyperparameters of a model. The API reference guide lists all the arguments for a Config object. There are a lot of arguments that can be passed to this class, however, a lot of them have good default values you don’t need to change. An important hyperparameters to specify is n_states, which the number of states. We advise starting with something between 6-14 and making sure any results based on the HMM are not critically sensitive to the choice for n_states. In this tutorial, we’ll use 6 states. The sequence_length and batch_size can be chosen to ensure the model fits into memory. ```Python from osl_dynamics.models.hmm import Config # Create a config object config = Config( n_states=6, n_channels=80, sequence_length=200, learn_means=False, learn_covariances=True, batch_size=256, learning_rate=0.01, n_epochs=20, ) ``` **Note**: for fMRI data the sequence_length used is typically much shorter, normally sequence_length=50. ### Building the model With the Config object, we can build a model. ```Python from osl_dynamics.models.hmm import Model model = Model(config) model.summary() ``` ```none HMM: n_states=6, n_channels=80, sequence_length=200 Parameter Details Learned by Count Initial state probabilities (6,) EM update 6 Transition probabilities (6, 6) EM update 36 Means (6, 80) fixed - Covariances (6, 80, 80) gradient descent 19,440 Learned parameters 19,482 Training: batch_size=256, learning_rate=0.01, n_epochs=20, optimizer=adam ``` ### Training the model Note, this step can be time consuming. **Initialization** When training a model it often helps to start with a good initialization. In particular, starting with a good initial value for the state means/covariances helps find a good explanation. The [`hmm.Model`](autoapi/osl_dynamics/models/hmm/Model.html.md#osl_dynamics.models.hmm.Model) class has a few helpful methods for initialization. When training on real data, we recommend using the random_state_time_course_initialization, let’s do this. Usually 3 initializations is enough and you only need to train for a short period, we will use a single epoch. ```python init_history = model.random_state_time_course_initialization(data, n_epochs=1, n_init=3) ``` If you are training on a particularly large dataset, initializing on the full dataset can be slow. In this case, you can pass the take argument to initialize on a random subset of the data. This is the fraction of the dataset to use, e.g. take=0.25 will use a quarter of the data for each initialization. ```python init_history = model.random_state_time_course_initialization(data, n_epochs=1, n_init=3, take=0.25) ``` The starting state covariances of each initialization are set from a few batches of data (n_batches=20 by default), so this step is quick even on a large dataset. Pass n_batches=None to use the whole dataset. The initialization method can also be chosen in the Config with init_method (and n_init, n_init_epochs, init_take) and run with model.initialization(data). To make the initialization and training reproducible, set the random seed before building the model with osl_dynamics.utils.set_random_seed(seed). The init_history variable is dict that contains the training history (e.g. loss, nll_loss, learning_rate, ema_decay) for the best initialization. **Full training** Now, we have found a good initialization, let’s do the full training of the model. We do this using the fit method. ```python history = model.fit(data) ``` The history variable contains the training history of the fit method. ### Training on large datasets By default the Data object holds the data in memory and cuts sequences out of it on the fly, so the only extra memory used during training is the batches in flight. If your dataset does not fit in memory, save the prepared data as a TFRecord dataset, which is streamed from disk during training. This also means the data is only prepared once if you train many models on it. The sequence_length must match the one in the model’s Config. ```python data.save_tfrecord_dataset("tfrecords", sequence_length=200) ``` Then in your training script, load the dataset and pass it to the model in place of the Data object. ```python from osl_dynamics.data import load_tfrecord_dataset dataset = load_tfrecord_dataset("tfrecords", batch_size=config.batch_size) model.random_state_time_course_initialization(dataset, n_epochs=1, n_init=3) model.fit(dataset) ``` This dataset is shuffled for training. To get inferred parameters in time order (e.g. with get_gamma), load an unshuffled dataset with one dataset per session. ```python dataset = load_tfrecord_dataset("tfrecords", batch_size=config.batch_size, shuffle=False, concatenate=False) gamma = model.get_gamma(dataset) ``` The buffer_size argument of load_tfrecord_dataset sets how many sequences are held in memory for shuffling (default 4000); reduce it if you still run out of memory. If you run out of GPU memory rather than RAM, reduce the batch_size or sequence_length in the Config. Alternatively, the Data object can keep the data on disk as memory maps (Data(…, load_memmaps=True)) and read sequences from disk as they are needed, which avoids the extra step of writing TFRecords. ### Saving a trained model As we have just seen, training a model can be time consuming. Therefore, it is often useful to save a trained model so we can load it later. We can do this with the save method. ```python model.save("results/model") ``` This will automatically create a directory containing the trained model weights and config settings used. Note, should we wish to load the trained model we can use: ```python from osl_dynamics.models import load model = load("results/model") ``` It’s also useful to save the variational free energy to compare different runs. ```python import pickle free_energy = model.free_energy(data) history["free_energy"] = free_energy pickle.dump(history, open("results/model/history.pkl", "wb")) ``` **Total running time of the script:** (0 minutes 3.272 seconds) [`Download Jupyter notebook: 3-2_hmm_training.ipynb`](_downloads/740c08d01018b3007fceecfd467456d5/3-2_hmm_training.ipynb) [`Download Python source code: 3-2_hmm_training.py`](_downloads/b1e9ce950830c20aa7acd04204c07755/3-2_hmm_training.py) [`Download zipped: 3-2_hmm_training.zip`](_downloads/8e004e1fddd8b72b9b4bc7230163dc67/3-2_hmm_training.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/3-3_dynemo_training.html.md #### NOTE [Go to the end](tutorials_build/3-3_dynemo_training.html.md#sphx-glr-download-tutorials-build-3-3-dynemo-training-py) to download the full example code. # DyNeMo: Training This tutorial covers how to train a DyNeMo model. We will use MEG data in this tutorial, however, this can easily be substituted with fMRI data. ## Getting the Data We will use resting-state MEG data that has already been source reconstructed and prepared. This dataset is: - Parcellated to 38 regions of interest (ROI). The parcellation file used was atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz. - Downsampled to 250 Hz. - Bandpass filtered over the range 1-45 Hz. - Prepared using 15 time-delay embeddings and 80 PCA components. ### Download the dataset We will download example data hosted on [OSF](https://osf.io/by2tc/). ```python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 21 MB) get_data("notts_meguk_giles_prepared_1_subject", rename="prepared_data") ``` ### Load the data We now load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```python from osl_dynamics.data import Data data = Data("prepared_data") print(data) ``` If you run into an out of memory error when training, see the Training on large datasets section below. ## Fitting DyNeMo ### The Config object Now we have prepared the data, let’s build a model to train. To do this we first need to specify the [`Config object`](autoapi/osl_dynamics/models/dynemo/Config.html.md#osl_dynamics.models.dynemo.Config) for DyNeMo. This is a class that acts as a container for all hyperparameters of a model. The API reference guide lists all the arguments for a Config object. There are a lot of arguments that can be passed to this class, however, a lot of them have good default values you don’t need to change. The important hyperparameters to specify are: - n_modes, the number of modes. Unfortunately, this is a hyperparameters that must be pre-specified. We advise starting with something between 6-12 and making sure any results based on the DyNeMo are not critically sensitive to the choice for n_modes. In this tutorial, we’ll use 6 modes. - sequence_length. This is a continuous segment that represents one training example. DyNeMo utilizes recurrent neural networks (RNNs) which need to be evaluated sequentially. This makes training with very long sequences slow. We advise a sequence length of 200 or less. 100 is often a good choice. - Inference RNN parameters: inference_n_units and inference_normalization. This is the number of units/neurons and the normalization used in the RNN used to infer the mixing coefficients respectively. (The inference RNN outputs the posterior distribution). The values below should work well in most cases. - Model RNN: model_n_units and model_normalization. Same as above but for the model RNN, which is part of the generative model. (The model RNN outputs the prior distribution). The values given below should work well for most cases. - Softmax function parameters: learn_alpha_temperature and initial_alpha_temperature. The softmax transformation is used to ensure the mode mixing coefficients in DyNeMo are positive and sum to one. This transformation has a ‘temperature’ parameter that controls how much mixing occurs. We can learn this temperature from the data by specifying learn_alpha_temperature=True. We recommend doing this with initial_alpha_temperature=1.0. - learn_means and learn_covariances. Typically, if we train on amplitude envelope data we set learn_means and learn_covariances to True, whereas if you’re training on time-delay embedded/PCA data, then we only learn the covariances, i.e. we set learn_means=False. - KL annealing parameters: kl_annealing, kl_annealing_curve, kl_annealing_sharpness, n_kl_annealing_epochs. When we perform variational Bayesian inference we minimize the variational free energy, which consists of two terms: the log-liklihood term and KL divergence term. We slowly turn on the KL divergence term in the loss function as training progresses. This process is known as **KL annealing**. These parameters control how quickly we turn on the KL term. It is recommended you use kl_annealing=True if you don’t use a pretrained model RNN (which will be the majority of cases). The kl_annealing_curve and kl_annealing_sharpness values given below will generally work well for most cases. We find using n_kl_annealing_epochs=n_epochs//2 works well for the duration of KL annealing. - batch_size. You want a large batch size for fast training. However, you will find that holding large batches requires a lot of memory. Therefore, you should pick the largest values that you can hold in memory. We find a batch size of 8-64 works well for neuroimaging data. - learning_rate. On large datasets, we find a lower learning rate leads to a lower final loss. We recommend a value between 1e-2 and 1e-4. We advise training a few values and seeing which produces the lowest loss value. - n_epochs, the number of epochs. This is the number of times you loop through the data. We recommend a value between ~50 for small datasets (<50 subjects). For large datasets (100s of subjects) you could train a model with 10 epochs. You can look at the loss as a function of epochs (see below) to see when the model has stopped improving. You can use this as an indicator for when you can stop training. In general, you can use the final loss value (lower is better) to select a good set of hyperparameters. Note, we want to compare the full loss function (after the KL term has fully turned on), so you should only use the loss after n_kl_annealing_epochs of training have been performed. ```Python from osl_dynamics.models.dynemo import Config config = Config( n_modes=6, n_channels=80, sequence_length=100, inference_n_units=64, inference_normalization="layer", model_n_units=64, model_normalization="layer", learn_alpha_temperature=True, initial_alpha_temperature=1.0, learn_means=False, learn_covariances=True, kl_annealing=True, kl_annealing_curve="tanh", kl_annealing_sharpness=5, n_kl_annealing_epochs=10, batch_size=256, learning_rate=0.01, n_epochs=20, ) ``` ### Building the model With the Config object, we can build a model. ```Python from osl_dynamics.models.dynemo import Model model = Model(config) model.summary() ``` ```none DyNeMo: n_modes=6, n_channels=80, sequence_length=100 Parameter Details Learned by Count Inference RNN bidirectional LSTM, 1 x 64 units, layer normalization gradient descent 76,044 Alpha temperature scalar gradient descent 1 Model RNN LSTM, 1 x 64 units, layer normalization gradient descent 19,084 Means (6, 80) fixed - Covariances (6, 80, 80) gradient descent 19,440 Learned parameters 114,569 Training: batch_size=256, learning_rate=0.01, n_epochs=20, optimizer=adam ``` ### Training the model Note, this step can be time consuming. **Initialization** When training a model it often helps to start with a good initialization. In particular, starting with a good initial value for the mode means/covariances helps find a good solution. The [`dynemo.Model`](autoapi/osl_dynamics/models/dynemo/Model.html.md#osl_dynamics.models.dynemo.Model) class has the random_subset_initialization method that can be used for this. This method train the model for a short period on a small random subset of the data. Let’s use this method to initialize the model. ```python init_history = model.random_subset_initialization(data, n_epochs=2, n_init=5, take=0.25) ``` The take argument is the fraction of the dataset to use for each initialization. If you are training on a particularly large dataset, initializing on the full dataset can be slow, so it is worth reducing this value further, e.g. take=0.1. The initialization method can also be chosen in the Config with init_method and run with model.initialization(data). To make the initialization and training reproducible, set the random seed before building the model with osl_dynamics.utils.set_random_seed(seed). The init_history variable is dict that contains the training history (e.g. loss, nll_loss, kl_loss, learning_rate, kl_factor) for the best initialization. **Full training** Now, we have found a good initialization, let’s do the full training of the model. We do this using the fit method. ```python history = model.fit(data) ``` The history variable contains the training history of the fit method. ### Training on large datasets By default the Data object holds the data in memory and cuts sequences out of it on the fly, so the only extra memory used during training is the batches in flight. If your dataset does not fit in memory, save the prepared data as a TFRecord dataset, which is streamed from disk during training. This also means the data is only prepared once if you train many models on it. The sequence_length must match the one in the model’s Config. ```python data.save_tfrecord_dataset("tfrecords", sequence_length=200) ``` Then in your training script, load the dataset and pass it to the model in place of the Data object. ```python from osl_dynamics.data import load_tfrecord_dataset dataset = load_tfrecord_dataset("tfrecords", batch_size=config.batch_size) model.random_subset_initialization(dataset, n_epochs=2, n_init=5, take=0.25) model.fit(dataset) ``` This dataset is shuffled for training. To get inferred parameters in time order (e.g. with get_alpha), load an unshuffled dataset with one dataset per session. ```python dataset = load_tfrecord_dataset("tfrecords", batch_size=config.batch_size, shuffle=False, concatenate=False) alpha = model.get_alpha(dataset) ``` The buffer_size argument of load_tfrecord_dataset sets how many sequences are held in memory for shuffling (default 4000); reduce it if you still run out of memory. If you run out of GPU memory rather than RAM, reduce the batch_size or sequence_length in the Config. Alternatively, the Data object can keep the data on disk as memory maps (Data(…, load_memmaps=True)) and read sequences from disk as they are needed, which avoids the extra step of writing TFRecords. ### Saving a trained model As we have just seen, training a model can be time consuming. Therefore, it is often useful to save a trained model so we can load it later. We can do this with the save method. ```python model.save("results/model") ``` This will automatically create a directory containing the trained model weights and config settings used. Note, should we wish to load the trained model we can use: ```python from osl_dynamics.models import load model = load("results/model") ``` It’s also useful to save the variational free energy to compare different runs. ```python import pickle free_energy = model.free_energy(data) history["free_energy"] = free_energy pickle.dump(history, open("results/model/history.pkl", "wb")) ``` ## Selecting a Run Training DyNeMo multiple times on the same data can give different networks. The run with the lowest variational free energy is a good default choice. For an alternative based on the networks the runs found, see [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md). **Total running time of the script:** (0 minutes 1.007 seconds) [`Download Jupyter notebook: 3-3_dynemo_training.ipynb`](_downloads/16b788100f4a3963dc6630b47b60900e/3-3_dynemo_training.ipynb) [`Download Python source code: 3-3_dynemo_training.py`](_downloads/d4955db79a975b17d12525289f529c72/3-3_dynemo_training.py) [`Download zipped: 3-3_dynemo_training.zip`](_downloads/adea52ced2e3c7468ffa99888236318f/3-3_dynemo_training.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/3-4_dynemo_selecting_a_run.html.md #### NOTE [Go to the end](tutorials_build/3-4_dynemo_selecting_a_run.html.md#sphx-glr-download-tutorials-build-3-4-dynemo-selecting-a-run-py) to download the full example code. # DyNeMo: Selecting a Run Training DyNeMo several times on the same data can give different networks: the modes come out in a different order and, where the data do not constrain the solution well, some networks can be split or combined differently from run to run. A good default is to analyze the run with the lowest variational free energy. This tutorial covers an alternative, which chooses a run based on the networks the runs found, using only the mode covariances: 1. Download the runs 2. Power maps from the mode covariances 3. Match the modes of different runs 4. Group the runs into families 5. Select a run ## Download the runs In this tutorial, we’ll download the mode covariances of 20 runs of a 6-mode TDE-DyNeMo model from [OSF](https://osf.io/by2tc/). The model was trained on MEG data parcellated with a 38 region parcellation, prepared with 15 time-delay embeddings and 80 PCA components. Each run was trained with the same hyperparameters, the only difference being the random initialization. ```Python import os def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the runs (approximately 3 MB) get_inf_params("tde_dynemo_20_runs", rename="runs") ``` ```none 'Data downloaded to: runs' ``` Let’s load the mode covariances of each run, the PCA components used to prepare the data and the variational free energy of each run. ```Python import numpy as np covariances = np.load("runs/covariances.npy") # (runs, modes, 80, 80) pca_components = np.load("runs/pca_components.npy") # (38 * 15, 80) free_energy = np.load("runs/free_energy.npy") # (runs,) print(covariances.shape) print(pca_components.shape) ``` ```none (20, 6, 80, 80) (570, 80) ``` Did the runs find the same solution? The free energies are very similar: ```Python for run in np.argsort(free_energy): print(f"run {run}: {free_energy[run]:.3f}") ``` ```none run 19: 109.289 run 3: 109.301 run 1: 109.303 run 6: 109.305 run 9: 109.305 run 10: 109.305 run 17: 109.306 run 14: 109.314 run 11: 109.317 run 2: 109.319 run 13: 109.323 run 7: 109.335 run 0: 109.338 run 4: 109.350 run 5: 109.354 run 12: 109.377 run 8: 109.382 run 18: 109.421 run 16: 109.424 run 15: 109.430 ``` The lowest free energy is a reasonable choice, but here the differences between runs are small, so it does not tell us which runs found the same networks or which solution is the most common. Instead, we can compare the networks directly. ## Power maps from the mode covariances To compare runs, we describe each mode by a feature that does not depend on the run: its power map. We can calculate this directly from the mode covariance, without inferring the mode time courses or calculating spectra. The covariances are of the time-delay embedded and PCA-reduced data; [`raw_covariances`](autoapi/osl_dynamics/analysis/post_hoc/raw_covariances.html.md#osl_dynamics.analysis.post_hoc.raw_covariances) takes them back to the parcels, and the diagonal gives the power of each parcel. ```Python from osl_dynamics.analysis import post_hoc raw_covs = post_hoc.raw_covariances( covariances, n_embeddings=15, pca_components=pca_components, zero_lag=True, ) power_maps = np.diagonal(raw_covs, axis1=-2, axis2=-1) # (runs, modes, parcels) print(power_maps.shape) ``` ```none (20, 6, 38) ``` ## Match the modes of different runs Next, we group the modes of all runs into networks with [`match_runs`](autoapi/osl_dynamics/inference/modes/match_runs.html.md#osl_dynamics.inference.modes.match_runs). Each run’s power maps are compared relative to the mean over its modes, and the modes are clustered by the correlation of their maps, never putting two modes of the same run in the same network. The correlation above which two modes count as the same network is found from the data: each mode’s best match in another run is either the same network found again (a correlation close to 1) or a different network, and the threshold is the value that best separates the two. ```Python from osl_dynamics.inference import modes networks, threshold = modes.match_runs(power_maps, return_threshold=True) print(f"threshold: {threshold:.2f}") print(networks) ``` ```none threshold: 0.73 [[ 1 4 7 0 2 5] [ 0 2 3 5 1 4] [ 0 3 1 6 7 2] [ 0 4 7 2 5 1] [ 8 0 2 9 1 3] [ 4 1 2 5 9 0] [ 1 5 3 2 0 4] [10 2 11 0 1 6] [ 1 6 0 12 2 3] [ 1 3 0 5 2 4] [ 0 1 4 2 3 5] [ 3 6 0 1 7 2] [ 8 0 9 1 2 3] [ 0 5 4 3 1 2] [ 1 2 7 6 0 3] [ 1 0 8 2 6 3] [ 1 6 13 0 3 2] [ 7 0 2 1 3 6] [ 8 0 3 14 1 15] [ 4 0 3 5 1 2]] ``` networks gives the network of each mode of each run. Networks are numbered by the number of runs they are found in, most first. Like the modes, they are numbered from 0 in the arrays; we add 1 when printing and plotting. Let’s see how often each network is found. This is a useful measure of how reproducible each network is. ```Python n_runs = len(networks) for network in range(networks.max() + 1): n = np.sum(np.any(networks == network, axis=1)) print(f"Network {network + 1}: found in {n} of {n_runs} runs") ``` ```none Network 1: found in 20 of 20 runs Network 2: found in 20 of 20 runs Network 3: found in 19 of 20 runs Network 4: found in 16 of 20 runs Network 5: found in 9 of 20 runs Network 6: found in 9 of 20 runs Network 7: found in 8 of 20 runs Network 8: found in 6 of 20 runs Network 9: found in 4 of 20 runs Network 10: found in 3 of 20 runs Network 11: found in 1 of 20 runs Network 12: found in 1 of 20 runs Network 13: found in 1 of 20 runs Network 14: found in 1 of 20 runs Network 15: found in 1 of 20 runs Network 16: found in 1 of 20 runs ``` Let’s plot the average power map of the networks found in more than one run. We average the power maps of a network’s modes, after subtracting the mean over modes in each run. ```Python from osl_dynamics.analysis import power relative_maps = power_maps - power_maps.mean(axis=1, keepdims=True) n_found = [np.sum(np.any(networks == k, axis=1)) for k in range(networks.max() + 1)] common = [k for k, n in enumerate(n_found) if n > 1] network_maps = np.array([relative_maps[networks == k].mean(axis=0) for k in common]) fig, ax = power.save( network_maps, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"symmetric_cbar": True}, titles=[f"Network {k + 1} ({n_found[k]} runs)" for k in common], ) ``` ```none Saving images: 0%| | 0/10 [00:00 ## Group the runs into families Runs that found the same set of networks found the same solution. [`run_families`](autoapi/osl_dynamics/inference/modes/run_families.html.md#osl_dynamics.inference.modes.run_families) groups them into families, largest first. ```Python families = modes.run_families(networks) for family in families: print(f"runs {family}: networks {np.sort(networks[family[0]]) + 1}") ``` ```none runs [ 1 6 9 10 13 19]: networks [1 2 3 4 5 6] runs [ 2 11 14 17]: networks [1 2 3 4 7 8] runs [0 3]: networks [1 2 3 5 6 8] runs [ 4 12]: networks [ 1 2 3 4 9 10] runs [5]: networks [ 1 2 3 5 6 10] runs [7]: networks [ 1 2 3 7 11 12] runs [8]: networks [ 1 2 3 4 7 13] runs [15]: networks [1 2 3 4 7 9] runs [16]: networks [ 1 2 3 4 7 14] runs [18]: networks [ 1 2 4 9 15 16] ``` The largest family is the solution the model finds most often. Comparing the networks of different families shows how the solutions differ, e.g. whether a network found as one mode in some runs is split into two in others. Let’s also look at the median free energy of each family. ```Python for family in families: print(f"runs {family}: median free energy {np.median(free_energy[family]):.3f}") ``` ```none runs [ 1 6 9 10 13 19]: median free energy 109.305 runs [ 2 11 14 17]: median free energy 109.316 runs [0 3]: median free energy 109.320 runs [ 4 12]: median free energy 109.364 runs [5]: median free energy 109.354 runs [7]: median free energy 109.335 runs [8]: median free energy 109.382 runs [15]: median free energy 109.430 runs [16]: median free energy 109.424 runs [18]: median free energy 109.421 ``` If the largest families are equally large, we choose the one with the lowest median free energy: among the solutions found equally often, the one that fits the data best. The median over a family is much less noisy than the free energy of a single run. ## Select a run [`select_run`](autoapi/osl_dynamics/inference/modes/select_run.html.md#osl_dynamics.inference.modes.select_run) does all of the above and selects the medoid of the largest family: the run whose modes agree best, on average, with the same networks in the other runs of the family. This is the most typical run of the most common solution. We pass the free energies for the tie-break. ```Python run, info = modes.select_run(power_maps, free_energy=free_energy, return_info=True) print(f"selected run: {run}") print(f"runs in its family: {info['families'][info['family']]}") print(f"typicality: {np.round(info['typicality'], 3)}") ``` ```none selected run: 10 runs in its family: [ 1 6 9 10 13 19] typicality: [0.952 0.968 0.958 0.975 0.964 0.975] ``` Let’s plot the power maps of the selected run. These are the networks we would analyze. Each title gives the network the mode belongs to and the number of runs that network is found in. ```Python fig, ax = power.save( relative_maps[run], parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"symmetric_cbar": True}, titles=[ f"Mode {mode + 1}: network {k + 1} ({n_found[k]} runs)" for mode, k in enumerate(networks[run]) ], ) ``` ```none Saving images: 0%| | 0/6 [00:00 info also contains the networks, the threshold, the number of runs each network is found in, and how well each family’s runs agree and their median free energy. We would now use the selected run for the rest of the analysis, e.g. getting the inferred parameters, see [HMM/DyNeMo: Get Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md). Notes: - **Number of runs.** The choice is only as reliable as the family sizes. With few runs, families are small and often equally large, so the tie-break decides. Train enough runs (e.g. 20) for the most common solution to stand out, and check the family sizes. - **Stability.** To see how stable the choice is, you can repeat the selection on random subsets of the runs (e.g. 16 of the 20, many times) and count how often the same family is chosen. **Total running time of the script:** (0 minutes 7.033 seconds) [`Download Jupyter notebook: 3-4_dynemo_selecting_a_run.ipynb`](_downloads/b38c8636b3fcab6d03f2f0b9a32c6741/3-4_dynemo_selecting_a_run.ipynb) [`Download Python source code: 3-4_dynemo_selecting_a_run.py`](_downloads/1609ef9fedc94fdaa6e342003b92e215/3-4_dynemo_selecting_a_run.py) [`Download zipped: 3-4_dynemo_selecting_a_run.zip`](_downloads/a2046c4892a121fa0e843d4a2c00cdb9/3-4_dynemo_selecting_a_run.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md #### NOTE [Go to the end](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md#sphx-glr-download-tutorials-build-3-5-hmm-dynemo-get-inf-params-py) to download the full example code. # HMM/DyNeMo: Get Inferred Parameters In this tutorial we will get the inferred parameters from a dynamic network model (HMM/DyNeMo). ## Download data and trained model In this tutorial, we’ll download example data and a trained model from [OSF](https://osf.io/by2tc/). Let’s first download the (prepared) data we trained the model on. ```python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 162 MB) get_data("notts_meguk_giles_prepared_5_subjects", rename="prepared_data") ``` Let’s also download a model. In this tutorial, we will download a trained HMM, however, this can be substituted with a DyNeMo model without any other changes being needed. ```python def get_model(name, rename=None): os.system(f"osf -p by2tc fetch trained_models/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Model downloaded to: {rename}" get_model("tde_hmm_notts_meguk_giles", rename="results/model") ``` ## Load Trained Model First we need to load the trained model. ```python from osl_dynamics.models import load model = load("results/model") ``` ## Get the Inferred Parameters ### Latent variables In the HMM, the latent variable is the state probability time course (the marginal posterior), gamma, which we get with the get_gamma method. In DyNeMo, it is the mixing coefficient time course, alpha, which we get with the get_alpha method. Both methods take the (prepared) training data. Let’s first load the training data. ```python from osl_dynamics.data import Data data = Data("prepared_data", n_jobs=4) ``` Now we can get the time courses for each subject. ```python alpha = model.get_gamma(data) # HMM alpha = model.get_alpha(data) # DyNeMo ``` The time courses are a list of numpy arrays, one for each subject. ```python import pickle os.makedirs("results/inf_params", exist_ok=True) pickle.dump(alpha, open("results/inf_params/alp.pkl", "wb")) ``` ### Observation model We can get the inferred state/mode means and covariances with the get_means and get_covariances methods. Note, if we passed learn_means=False in the config, the means will be zero. ```python import numpy as np means = model.get_means() covs = model.get_covariances() np.save("results/inf_params/means.npy", means) np.save("results/inf_params/covs.npy", covs) ``` **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 3-5_hmm_dynemo_get_inf_params.ipynb`](_downloads/c89ec5efb35958510fe13cacab00523e/3-5_hmm_dynemo_get_inf_params.ipynb) [`Download Python source code: 3-5_hmm_dynemo_get_inf_params.py`](_downloads/a04227594cba1eb467dc6bdcf1f13f5d/3-5_hmm_dynemo_get_inf_params.py) [`Download zipped: 3-5_hmm_dynemo_get_inf_params.zip`](_downloads/c97c20365efe6896a38575e852fc015e/3-5_hmm_dynemo_get_inf_params.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/4-1_hmm_multitaper_spectra.html.md #### NOTE [Go to the end](tutorials_build/4-1_hmm_multitaper_spectra.html.md#sphx-glr-download-tutorials-build-4-1-hmm-multitaper-spectra-py) to download the full example code. # HMM: Multitaper Spectra In this tutorial we calculate subject and state-specific multitaper spectra using a trained HMM and **source space** data. Here, we should **not** use the prepared (e.g. TDE-PCA) data. ## Download source data In this tutorial, we’ll download example data from [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ## Download inferred parameters ```Python def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 11 MB) get_inf_params("tde_hmm_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Load the source data We load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data") print(data) ``` ```none Loading files: 0%| | 0/5 [00:00 ### Trim data If we trained on time-delay embedded data we lose a few time points from the start and end of the data. Additionally, when we separate the data into sequences we lose time points from the end of the time series (that do not form a complete sequence). Consequently, we need to trim the source-space data to match the inferred state probabilities (alpha). ```Python trimmed_data = data.trim_time_series(n_embeddings=15, sequence_length=2000) # needs to match values used to prepare the data and build the model ``` If we didn’t do any time-delay embedding and just need to remove time points lost due to separating into sequences we can use: ```default trimmed_data = data.trim_time_series(sequence_length=2000) ``` ## Load the state probabilities To calculate the multitaper spectra, we need the inferred state probabilities. ```Python import pickle alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) ``` alpha is a list of numpy arrays that contains a (n_samples, n_states) time series, which is the state probability at each time point. Each item of the list corresponds to a subject. Let’s double check the number of time points in inferred state probabilities match the source-space data. ```Python for a, x in zip(alpha, trimmed_data): print(a.shape, x.shape) ``` ```none (72000, 8) (72000, 38) (72000, 8) (72000, 38) (74000, 8) (74000, 38) (74000, 8) (74000, 38) (74000, 8) (74000, 38) ``` If the first dimension of these arrays don’t match then the wrong value for n_embeddings or sequence_length was used when we trimmed the data. ## Calculating Subjects/State Spectra ### Power spectra and coherences We want to calculate the power spectrum and coherence of each state. This is done by using standard calculation methods (in our case the multitaper for spectrum estimation) to the time points identified as belonging to a particular state. The [`analysis.spectral.multitaper_spectra`](autoapi/osl_dynamics/analysis/spectral/multitaper_spectra.html.md#osl_dynamics.analysis.spectral.multitaper_spectra) function does this for us. Let’s first run this function, then we’ll discuss its output. ```Python from osl_dynamics.analysis import spectral # Calculate multitaper spectra for each state and subject spectra = spectral.multitaper_spectra( data=trimmed_data, alpha=alpha, sampling_frequency=250, frequency_range=[1, 45], ) print(spectra) ``` ```none Calculating spectra: 0%| | 0/5 [00:00 spectra is a [`StateSpectra`](autoapi/osl_dynamics/analysis/spectral/StateSpectra.html.md#osl_dynamics.analysis.spectral.StateSpectra) object. Its attributes contain the spectra. Let’s print the shape of a few of them. ```Python print(spectra.frequencies.shape) print(spectra.psd.shape) print(spectra.coherence.shape) print(spectra.session_weights.shape) ``` ```none (89,) (5, 8, 38, 89) (5, 8, 38, 38, 89) (5,) ``` frequencies is the frequency axis. psd contains the PSDs and is (subjects, states, channels, frequencies) and coherence contains the pairwise coherences and is (subjects, states, channels, channels, frequencies). session_weights contains the weight of each subject in a group average (the number of samples in each subject divided by the total). The static PSD (static_psd) is the average of the state PSDs weighted by the fractional occupancy of each state, and psd_change is the change in each state’s PSD from the static PSD. See the [Spectral Analysis user guide](user_guide/spectra.html.md) for the other attributes. If the Data object was prepared as it was for training, we can pass it directly instead of the trimmed data: ```default spectra = spectral.multitaper_spectra(data, alpha=alpha, frequency_range=[1, 45]) ``` ### Saving the spectra Calculating the spectra can be time consuming so it is useful to save them. ```Python os.makedirs("results/spectra", exist_ok=True) spectra.save("results/spectra/multitaper.npz") ``` We can load them with: ```default spectra = spectral.Spectra.load("results/spectra/multitaper.npz") ``` **Total running time of the script:** (0 minutes 6.716 seconds) [`Download Jupyter notebook: 4-1_hmm_multitaper_spectra.ipynb`](_downloads/0458bcfd942a6ac16169f993e3b98047/4-1_hmm_multitaper_spectra.ipynb) [`Download Python source code: 4-1_hmm_multitaper_spectra.py`](_downloads/93d49a9e1d0ec98b99b95204ae183a0d/4-1_hmm_multitaper_spectra.py) [`Download zipped: 4-1_hmm_multitaper_spectra.zip`](_downloads/4e331271012c62758195609bbf5aaa25/4-1_hmm_multitaper_spectra.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/4-2_hmm_plotting_meg_networks.html.md #### NOTE [Go to the end](tutorials_build/4-2_hmm_plotting_meg_networks.html.md#sphx-glr-download-tutorials-build-4-2-hmm-plotting-meg-networks-py) to download the full example code. # HMM: Plotting MEG Networks In this tutorial we will plot networks from an HMM trained on source reconstructed MEG data. This tutorial covers: 1. Calculate multitaper spectra 2. PSDs 3. Power maps 4. Coherence networks 5. Coherence maps 6. Coherence vs Power ## Download source data and inferred parameters In this tutorial, we’ll download example data from [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the source data (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") # Download the inferred state probabilities (approximately 11 MB) get_inf_params("tde_hmm_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Calculate multitaper spectra We calculate networks based on multitaper spectra. See the [HMM Multitaper Spectra tutorial](tutorials_build/4-1_hmm_multitaper_spectra.html.md) for details. ```Python import pickle import numpy as np from osl_dynamics.data import Data from osl_dynamics.analysis import spectral # Source data trimmed to match the state probabilities data = Data("source_data") trimmed_data = data.trim_time_series(n_embeddings=15, sequence_length=2000) # State probabilities alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) # Multitaper spectra for each subject and state spectra = spectral.multitaper_spectra( data=trimmed_data, alpha=alpha, sampling_frequency=250, frequency_range=[1, 45], ) print(spectra) ``` ```none Loading files: 0%| | 0/5 [00:00 If you saved the spectra with spectra.save, you can load them with spectral.Spectra.load. ## PSDs We can plot the power spectra to see what oscillations typically occur when a particular state is on. To help us visualize this, we first average over subjects. ```Python group = spectra.group_average() print(group.psd.shape) ``` ```none (8, 38, 89) ``` The group average is weighted by the number of samples in each subject. group.psd is a (states, channels, frequencies) array. The plot_psd method plots the PSD of each state averaged over channels. The shaded area is the standard error over channels. ```Python fig, ax = group.plot_psd(values="psd") ``` The states have similar PSDs. To highlight the differences, we can plot the change in the PSD from the static PSD (the average of the state PSDs weighted by the fractional occupancies). This is the default. ```Python fig, ax = group.plot_psd() ``` ## Power maps The PSD is a function of frequency. To calculate power we need to average over a frequency range. The power_maps method does this. Let’s look at the power across all frequencies for each state. ```Python from osl_dynamics.analysis import power p = group.power_maps(values="psd") print(p.shape) ``` ```none (8, 38) ``` We have a (states, channels) array. Let’s see what the power map for each state looks like. ```Python # Takes a few seconds for the power maps to appear fig, ax = power.save( p, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/8 [00:00 Because the power is always positive and a lot of the states have power in similar regions, all the power maps look similar. To highlight differences we display the change in power from the static power. This is the default. ```Python p = group.power_maps() # Takes a few seconds for the power maps to appear fig, ax = power.save( p, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"symmetric_cbar": True}, ) ``` ```none Saving images: 0%| | 0/8 [00:00 If we were interested in a particular frequency band we could use the frequency_range argument, e.g. frequency_range=[8, 13], or calculate several bands at once with bands=[[1, 4], [4, 8], [8, 13], [13, 30]]. ## Coherence networks Next, let’s visualize the coherence networks. The coherence_networks method averages the coherence over frequency. By default, it gives the change in coherence from the static coherence. ```Python from osl_dynamics.analysis import connectivity c = group.coherence_networks() print(c.shape) ``` ```none (8, 38, 38) ``` We can see c is a (states, channels, channels) array. Coherence networks are often noisy so averaging over a large number of subjects (20+) is typically needed to get clean coherence networks. Let’s have a look at the coherence networks. The [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save) function can be used to display a connectivity matrix (or set of connectivity matrices). ```Python connectivity.save( c, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/8 [00:00 We can see there are a lot of connections. We want to select the most extreme edges. The percentile argument keeps the edges with the largest changes (increases or decreases). Let’s keep the top 3%. ```Python c = group.coherence_networks(percentile=97) connectivity.save( c, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/8 [00:00 ### Non-negative matrix factorization (NNMF) In the above code, we averaged over all frequencies to calculate the power maps and coherence networks. We expect brain activity to occur with phase-locking networks with oscillations at different frequencies. A data-driven approach for finding the frequency bands (referred to as ‘spectral components’) for phase-locked networks is to apply non-negative matrix factorization (NNMF) to the coherence spectra for each subject. The decompose method does this (see [`analysis.spectral.decompose_spectra`](autoapi/osl_dynamics/analysis/spectral/decompose_spectra.html.md#osl_dynamics.analysis.spectral.decompose_spectra)). Let’s use it to separate the coherence spectra into two frequency bands. ```Python wb_comp = spectra.decompose(n_components=2) print(wb_comp.shape) ``` ```none (2, 89) ``` wb_comp refers to ‘wideband component’ because the spectral components cover a wide frequency range (we’ll see this below). If we passed n_components=4, we would find more narrowband components. You can interpret the wb_comp array as weights for how much coherent (phase-locking) activity is occurring at a particular frequency for a particular component. It can be better understood if we plot it. ```Python from osl_dynamics.utils import plotting f = spectra.frequencies plotting.plot_line( [f, f], # we need to repeat twice because we fitted two components wb_comp, x_label="Frequency (Hz)", y_label="Spectral Component", ) ``` ```none (
, ) ``` The blue line is the first spectral component and the orange line is the second component. We can see the NNMF has separated the coherence spectra into two bands, one with a lot of coherence activity below ~22 Hz (blue line) and one above (orange line). In other words, the first spectral component contains coherent activity below 22 Hz and the second contains coherent activity mainly above 22 Hz. Now, instead of averaging the coherence spectra across all frequencies, let’s look at the first spectral component. We pass the spectral components as the bands argument, which weights each frequency using the spectral component. ```Python c = group.coherence_networks(bands=wb_comp, percentile=97) print(c.shape) ``` ```none (2, 8, 38, 38) ``` We can see c is (components, states, channels, channels) array. We’re only interested in the first spectral component. We can plot this by passing a component=0 argument to [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save). ```Python connectivity.save( c, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", component=0, ) ``` ```none Saving images: 0%| | 0/8 [00:00 ## Coherence maps We can display the coherence as a spatial map rather than a graphical network by averaging the edges for each parcel. ```Python c = group.coherence_networks(bands=wb_comp) c_map = connectivity.mean_connections(c) fig, ax = power.save( c_map, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"symmetric_cbar": True}, ) ``` ```none Saving images: 0%| | 0/8 [00:00 ## Coherence vs Power We may be interested in how the coherence relates to power for each state. We can do this by producing scatter plots of coherence vs power. Let’s see how to do this. Let’s first look at the group average for the first spectral component. ```Python # Calculate power mean_p = group.power_maps(values="psd", bands=wb_comp)[0] print(mean_p.shape) # Calculate coherence mean_c = group.coherence_networks(values="coherence", bands=wb_comp)[0] print(mean_c.shape) ``` ```none (8, 38) (8, 38, 38) ``` We have a (n_channels,) array for each state for the power, but a (n_channels, n_channels) array for each state for the coherence. To reduce the coherence down to a 1D array for each state, we can calculate the average pairwise coherence for each channel. We can do this with the [`connectivity.mean_connections`](autoapi/osl_dynamics/analysis/connectivity/mean_connections.html.md#osl_dynamics.analysis.connectivity.mean_connections) function. ```Python mean_c = connectivity.mean_connections(mean_c) print(mean_c.shape) ``` ```none (8, 38) ``` Now we can make a scatter plot of coherence vs power for each state. ```Python fig, ax = plotting.plot_scatter( mean_p, mean_c, labels=[f"State {i}" for i in range(1, mean_p.shape[0] + 1)], x_label="Power (a.u.)", y_label="Coherence", ) ``` We can see the different states have different power/coherence properties. E.g. some states typically have more power/coherence at all parcels. Calling the methods on spectra instead of group gives the power and coherence for each subject. If we average over parcels we get the following. ```Python # Power for each subject, averaged over parcels p = spectra.power_maps(values="psd", bands=wb_comp) mean_p = np.mean(p[:, 0], axis=-1) print(mean_p.shape) # Coherence for each subject, averaged over parcels c = spectra.coherence_networks(values="coherence", bands=wb_comp) mean_c = np.mean(c[:, 0], axis=(-2, -1)) print(mean_c.shape) # Plot fig, ax = plotting.plot_scatter( mean_p, mean_c, x_label="Power (a.u.)", y_label="Coherence", ) ``` ```none (5, 8) (5, 8) ``` Each scatter point is a subject here. We also see different subjects have different power/coherence characteristics. **Total running time of the script:** (0 minutes 35.251 seconds) [`Download Jupyter notebook: 4-2_hmm_plotting_meg_networks.ipynb`](_downloads/f30ccd918fa25bcb3c06c063ddc3bbb6/4-2_hmm_plotting_meg_networks.ipynb) [`Download Python source code: 4-2_hmm_plotting_meg_networks.py`](_downloads/7cce698de2bf9b51bd80ece83c17f2a6/4-2_hmm_plotting_meg_networks.py) [`Download zipped: 4-2_hmm_plotting_meg_networks.zip`](_downloads/a61cc9da2f039e168e6c57829e5d5149/4-2_hmm_plotting_meg_networks.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/4-3_hmm_summary_stats.html.md #### NOTE [Go to the end](tutorials_build/4-3_hmm_summary_stats.html.md#sphx-glr-download-tutorials-build-4-3-hmm-summary-stats-py) to download the full example code. # HMM: Summary Statistics A useful way of characterizing the data is to use statistics that summarize the state time course, these are referred to as ‘summary statistics’. The state time course captures the dynamics in the training data, therefore, summary statistics characterize the dynamics of the data. In this tutorial we calculate summary statistics for dynamics: - Fractional occupancy, which is the fraction of total time spent in a particular state. - Mean lifetime, which is the average duration a state is activate. - Mean interval, which is the average duration between successive state visits. - Switching rate, which is the average number of state activations. ## Download inferred parameters ```Python import os def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 11 MB) get_inf_params("tde_hmm_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Load the inferred state probabilities We first need to load the inferred state probabilities to calculate the summary statistics. ```Python import pickle alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) ``` Let’s also plot the state probabilities for the first few seconds of the first subject to get a feel for what they look like. We can use the [`utils.plotting.plot_alpha`](autoapi/osl_dynamics/utils/plotting/plot_alpha.html.md#osl_dynamics.utils.plotting.plot_alpha) function to do this. ```Python from osl_dynamics.utils import plotting # Plot the state probability time course for the first subject (8 seconds) fig, ax = plotting.plot_alpha(alpha[0], n_samples=2000) ``` When looking at the state probability time course you want to see a good number of transitions between states. The alpha list contains the state probabilities time course for each subject. To calculate summary statistics we first need to hard classify the state probabilities to give a state time course. We can use the [`inference.modes.argmax_time_courses`](autoapi/osl_dynamics/inference/modes/argmax_time_courses.html.md#osl_dynamics.inference.modes.argmax_time_courses) function to do this. ```Python from osl_dynamics.inference import modes # Hard classify the state probabilities stc = modes.argmax_time_courses(alpha) # Plot the state time course for the first subject (8 seconds) fig, ax = plotting.plot_alpha(stc[0], n_samples=2000) ``` We can see this time series is completely binarized, only one state is active at each time point. ## Calculate summary statistics ### Fractional occupancy The [`analysis.post_hoc`](autoapi/osl_dynamics/analysis/post_hoc/index.html.md#module-osl_dynamics.analysis.post_hoc) module in osl-dynamics contains helpful functions for calculating summary statistics. Let’s use the [`analysis.post_hoc.fractional_occupancies`](autoapi/osl_dynamics/analysis/post_hoc/fractional_occupancies.html.md#osl_dynamics.analysis.post_hoc.fractional_occupancies) function to calculate the fractional occupancy of each state for each subject. ```Python from osl_dynamics.analysis import post_hoc # Calculate fractional occupancies fo = post_hoc.fractional_occupancies(stc) print(fo.shape) ``` ```none (5, 8) ``` We can see fo is a (subjects, states) numpy array which contains the fractional occupancy of each state for each subject. To get a feel for how much each state is activated we can print the group average: ```Python import numpy as np print(np.mean(fo, axis=0)) ``` ```none [0.17031502 0.10770698 0.136075 0.03785646 0.15199955 0.16724242 0.06957335 0.15923123] ``` We can see each state shows a significant activation (i.e. non-zero), which gives us confidence in the fit. If only one state is activated, that indicates further preprocessing is likely needed. We can examine the distribution across subjects for each state by creating a violin plot. The [`utils.plotting.plot_violin`](autoapi/osl_dynamics/utils/plotting/plot_violin.html.md#osl_dynamics.utils.plotting.plot_violin) function can be used to do this. ```Python # Plot the distribution of fractional occupancy (FO) across subjects fig, ax = plotting.plot_violin(fo.T, x_label="State", y_label="Fractional Occupancy") ``` We can see there is a lot of variation across subjects. ### Mean Lifetime Next, let’s look at another popular summary statistic, i.e. the mean lifetime. We can calculate this using the [`analysis.post_hoc.mean_lifetimes`](autoapi/osl_dynamics/analysis/post_hoc/mean_lifetimes.html.md#osl_dynamics.analysis.post_hoc.mean_lifetimes) function. ```Python # Calculate mean lifetimes (in seconds) lt = post_hoc.mean_lifetimes(stc, sampling_frequency=250) # Convert to ms lt *= 1000 # Print the group average print(np.mean(lt, axis=0)) # Plot distribution across subjects fig, ax = plotting.plot_violin(lt.T, x_label="State", y_label="Mean Lifetime (ms)") ``` ```none [64.5703925 80.69838401 69.58749073 75.8973731 60.17574585 65.52617621 88.21728058 64.86945622] ``` ### Mean interval Next, let’s look at the mean interval time for each state and subject. We can use the [`analysis.post_hoc.mean_intervals`](autoapi/osl_dynamics/analysis/post_hoc/mean_intervals.html.md#osl_dynamics.analysis.post_hoc.mean_intervals) function in osl-dynamics to calculate this. ```Python # Calculate mean intervals (in seconds) intv = post_hoc.mean_intervals(stc, sampling_frequency=250) # Print the group average print(np.mean(intv, axis=0)) # Plot distribution across subjects fig, ax = plotting.plot_violin(intv.T, x_label="State", y_label="Mean Interval (s)") ``` ```none [0.32125534 0.7271179 0.45446391 2.32690234 0.38967127 0.33346291 1.44239173 0.35297459] ``` ### Switching rate Finally, let’s look at the switching rate for each state and subject. We can use the [`analysis.post_hoc.switching_rates`](autoapi/osl_dynamics/analysis/post_hoc/switching_rates.html.md#osl_dynamics.analysis.post_hoc.switching_rates) function in osl-dynamics to calculate this. ```Python # Calculate the switching rate (Hz) sr = post_hoc.switching_rates(stc, sampling_frequency=250) # Print the group average print(np.mean(sr, axis=0)) # Plot distribution across subjects fig, ax = plotting.plot_violin(sr.T, x_label="State", y_label="Switching Rate (Hz)") ``` ```none [2.60825826 1.30724474 1.97700826 0.47477477 2.42391141 2.54483859 0.8201952 2.48825075] ``` **Total running time of the script:** (0 minutes 0.816 seconds) [`Download Jupyter notebook: 4-3_hmm_summary_stats.ipynb`](_downloads/dce490f9a001c4a27714fae59bc935ed/4-3_hmm_summary_stats.ipynb) [`Download Python source code: 4-3_hmm_summary_stats.py`](_downloads/0771b5b6078d1e3a88df084b419a7e72/4-3_hmm_summary_stats.py) [`Download zipped: 4-3_hmm_summary_stats.zip`](_downloads/1090096c28b8f6a2dd9481f13e986f2f/4-3_hmm_summary_stats.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/4-4_hmm_fmri_dual_estimation.html.md #### NOTE [Go to the end](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md#sphx-glr-download-tutorials-build-4-4-hmm-fmri-dual-estimation-py) to download the full example code. # HMM: fMRI Dual Estimation After training an HMM on fMRI data, we normally want to estimate subject-specific quantities based on the group-level model. We refer to this process as ‘dual estimation’. We estimated subject/static-specific means and covariances. In this tutorial, we show how to do this with osl-dynamics. ## Load trained model First we need to load the trained model. ```python from osl_dynamics.models import load model = load("results/model") ``` ## Load data and state probabilities First we need to load the (prepared) training data. ```python from osl_dynamics.data import Data data = Data("prepared_data") ``` We also need the state probabilities for each subject. ```python import pickle gamma = pickle.load(open("results/inf_params/alp.pkl", "rb")) ``` ## Dual estimation The HMM has a method for dual estimation, which calculates subject/static-specific means/covariances based on the state probabilities. ```python means, covs = model.dual_estimation(data, gamma=gamma) ``` Note, if we haven’t calculated the state probabilities, we can just pass the data: ```python means, covs = model.dual_estimation(data) ``` and it’ll calculate the state probabilities for us. Finally, it’s useful to save these to load later. ```python import os import numpy as np os.makedirs("results/dual_estimates", exist_ok=True) np.save("results/dual_estimates/means.npy", means) np.save("results/dual_estimates/covs.npy", covs) ``` **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 4-4_hmm_fmri_dual_estimation.ipynb`](_downloads/4e68bb6023228c5b2e75801ba5a05ac3/4-4_hmm_fmri_dual_estimation.ipynb) [`Download Python source code: 4-4_hmm_fmri_dual_estimation.py`](_downloads/f63a234a9d551fed56282dfb5d714fb3/4-4_hmm_fmri_dual_estimation.py) [`Download zipped: 4-4_hmm_fmri_dual_estimation.zip`](_downloads/0407cfe1ad9df76c97b253b6ac9ad14e/4-4_hmm_fmri_dual_estimation.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/4-5_hmm_plotting_fmri_networks.html.md #### NOTE [Go to the end](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md#sphx-glr-download-tutorials-build-4-5-hmm-plotting-fmri-networks-py) to download the full example code. # HMM: Plotting fMRI Networks We normally plot networks from an HMM trained on fMRI directly from the dual-estimated means/covariances. This tutorial covers: 1. Load means/covariances 2. Spatial maps 3. Functional connectivity networks Note, we assume a group ICA parcellation was used and the HMM was trained on the ICA time courses. ## Load means/covariances First we need to the dual estimated means and covariances. ```python import numpy as np means = np.load("results/dual_estimates/means.npy") covs = np.load("results/dual_estimates/covs.npy") print(means.shape) print(covs.shape) ``` means is a (subjects, states, channels) array and covariances is a (subjects, states, channels, channels) array. ## Spatial maps ### Volumetric parcellation The spatial activity maps correspond to the means, or if we did not learn a mean, the diagonal of the covs. How we plot the spatial maps depends on how the data was preprocessed. If we used a volumetric parcellation, then we can plot the spatial maps with ```python from osl_dynamics.analysis import power # Calculate a group average group_mean = np.mean(means, axis=0) # Plot fig, ax = power.save( means, parcellation_file="melodic_IC.nii.gz", # this should be the group-ICA spatial maps from FSL plot_kwargs={"views": ["lateral", "medial"]}, ) ``` ### Surface parcellation Alternatively, if we used a surface parcellation, we can use workbench to plot the spatial maps ```python # Save cifti containing the state maps power.independent_components_to_surface_maps( ica_spatial_maps="melodic_IC.dscalar.nii", ic_values=group_mean, output_file="results/inf_params/means.dscalar.nii", ) # Plot workbench.setup("/path/to/workbench/bin_macosxub") workbench.render( img=f"{inf_params_dir}/means.dscalar.nii", gui=False, save_dir="tmp", image_name="plots/means_.png", input_is_cifti=True, ) # Delete temporary directory os.system("rm -r tmp") ``` You can download workbench [here](https://www.humanconnectome.org/software/get-connectome-workbench). If you did not learn the mean, then replace means above with the diagonal of the covariances. ## Functional Connectivity Networks The off-diagonal elements in the covariances corresponds to the functional connectivity. In osl-dynamics, we can only plot these if we used a volumetric parcellation with ```python from osl_dynamics.analysis import connectivity connectivity.save( covs, parcellation_file="melodic_IC.nii.gz", # this should be the group-ICA spatial maps from FSL plot_kwargs={ "edge_cmap": "Reds", "display_mode": "xz", "annotate": False, }, ) ``` **Total running time of the script:** (0 minutes 0.000 seconds) [`Download Jupyter notebook: 4-5_hmm_plotting_fmri_networks.ipynb`](_downloads/8418ef0fcb7fb255d62bfcea70010c6b/4-5_hmm_plotting_fmri_networks.ipynb) [`Download Python source code: 4-5_hmm_plotting_fmri_networks.py`](_downloads/870fad32daec042701f9f2536395df5c/4-5_hmm_plotting_fmri_networks.py) [`Download zipped: 4-5_hmm_plotting_fmri_networks.zip`](_downloads/2e493a29e34e75f42b0c3b5c3a1a7ee8/4-5_hmm_plotting_fmri_networks.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/5-1_dynemo_regression_spectra.html.md #### NOTE [Go to the end](tutorials_build/5-1_dynemo_regression_spectra.html.md#sphx-glr-download-tutorials-build-5-1-dynemo-regression-spectra-py) to download the full example code. # DyNeMo: Regression Spectra In this tutorial we calculate subject and mode-specific spectra using a trained DyNeMo model and **source space** data. Here, we should **not** use the prepared (e.g. TDE-PCA) data. ## Download source data In this tutorial, we’ll download example data from [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") ``` ```none 'Data downloaded to: source_data' ``` ## Download inferred parameters ```Python def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 11 MB) get_inf_params("tde_dynemo_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Load the source data We load the data into osl-dynamics using the Data class. See the [Loading Data tutorial](tutorials_build/1-1_data_loading.html.md) for further details. ```Python from osl_dynamics.data import Data data = Data("source_data") ``` ```none Loading files: 0%| | 0/5 [00:00 ### Trim data When we perform time-delay embedding we lose a few time points from the start and end of the data. Additionally, when we separate the data into sequences we lose time points from the end of the time series (that do not form a complete sequence). Consequently, we need to trim the source-space data to match the inferred state probabilities (alpha). ```Python trimmed_data = data.trim_time_series(n_embeddings=15, sequence_length=200) # needs to match values used to prepare the data and build the model ``` If we didn’t do any time-delay embedding and just need to remove time points lost due to separating into sequences we can use: ```default trimmed_data = data.trim_time_series(sequence_length=200) ``` ## Load the mode mixing coefficients To calculate the mode spectra, we need the inferred mode mixing coefficients. ```Python import pickle alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) ``` alpha is a list of numpy arrays that contains a (n_samples, n_modes) time series, which is the mixing coefficients at each time point. Each item of the list corresponds to a subject. Let’s double check the number of time points in inferred state probabilities match the source-space data. ```Python for a, x in zip(alpha, trimmed_data): print(a.shape, x.shape) ``` ```none (73400, 7) (73400, 38) (72600, 7) (72600, 38) (75600, 7) (75600, 38) (74800, 7) (74800, 38) (74600, 7) (74600, 38) ``` If the first dimension of these arrays don’t match then the wrong value for n_embeddings or sequence_length was used when we trimmed the data. We use the mixing coefficients inferred by DyNeMo directly, not the re-weighted mixing coefficients ([`modes.reweight_alphas`](autoapi/osl_dynamics/inference/modes/reweight_alphas.html.md#osl_dynamics.inference.modes.reweight_alphas)), which are for summary statistics. ## Calculating Subject/Mode Spectra Using the mixing coefficients and source space data, we can calculate the spectral properties of each mode. ### Power spectra and coherences We want to calculate the power spectrum and coherence of each mode. We calculate a spectrogram (time-varying spectra) and fit it as a mixture of the mode spectra weighted by the mixing coefficients. We do this with the [`analysis.spectral.regression_spectra`](autoapi/osl_dynamics/analysis/spectral/regression_spectra.html.md#osl_dynamics.analysis.spectral.regression_spectra) function in osl-dynamics. Let’s first run this function, then we’ll discuss its output. ```Python from osl_dynamics.analysis import spectral # Calculate regression spectra for each mode and subject spectra = spectral.regression_spectra( data=trimmed_data, alpha=alpha, sampling_frequency=250, frequency_range=[1, 45], ) print(spectra) ``` ```none Calculating spectra: 0%| | 0/5 [00:00 We used the default settings: a 4 second window split into 8 sub-windows (2 Hz frequency resolution), moved in 80 ms steps. spectra is a [`RegressionSpectra`](autoapi/osl_dynamics/analysis/spectral/RegressionSpectra.html.md#osl_dynamics.analysis.spectral.RegressionSpectra) object. Its attributes contain the spectra. Let’s print the shape of a few of them. ```Python print(spectra.frequencies.shape) print(spectra.static_psd.shape) print(spectra.psd_coefs.shape) print(spectra.coherence_coefs.shape) print(spectra.session_weights.shape) ``` ```none (45,) (5, 38, 45) (5, 7, 38, 45) (5, 7, 38, 38, 45) (5,) ``` We can see: - frequencies is the frequency axis. - static_psd is (subjects, channels, frequencies). It is the static (time-averaged) PSD, the intercept of the regression. - psd_coefs is (subjects, modes, channels, frequencies). These are the regression coefficients: the change in the PSD from the static PSD for a one standard deviation increase in a mode’s mixing coefficient. They are positive where a mode has more power than the static PSD and negative where it has less. - coherence_coefs is (subjects, modes, channels, channels, frequencies). It is the change in the cross spectrum, normalized by the static power (change in coherence), for a one standard deviation increase in a mode’s mixing coefficient. It includes changes in both coherence and power. - session_weights contains the weight of each subject in a group average. The coefficients of every subject are scaled by the same standard deviation, so the subject-specific spectra can be averaged and compared. See the [Spectral Analysis](user_guide/spectra.html.md) page of the User Guide for how to interpret these outputs and what to plot. If the Data object was prepared as it was for training, we can pass it directly instead of the trimmed data: ```default spectra = spectral.regression_spectra(data, alpha=alpha, frequency_range=[1, 45]) ``` ### Saving the spectra Calculating the spectra can be time consuming so it is useful to save them. ```Python os.makedirs("results/spectra", exist_ok=True) spectra.save("results/spectra/regression.npz") ``` We can load them with: ```default spectra = spectral.Spectra.load("results/spectra/regression.npz") ``` **Total running time of the script:** (0 minutes 36.878 seconds) [`Download Jupyter notebook: 5-1_dynemo_regression_spectra.ipynb`](_downloads/378c2c5e00be22ef7160c2b8af881ce9/5-1_dynemo_regression_spectra.ipynb) [`Download Python source code: 5-1_dynemo_regression_spectra.py`](_downloads/4b3a2fae93b981d28c05bee95d0ace25/5-1_dynemo_regression_spectra.py) [`Download zipped: 5-1_dynemo_regression_spectra.zip`](_downloads/9766eb80d13b9b07fae524d08d01c813/5-1_dynemo_regression_spectra.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/5-2_dynemo_plotting_networks.html.md #### NOTE [Go to the end](tutorials_build/5-2_dynemo_plotting_networks.html.md#sphx-glr-download-tutorials-build-5-2-dynemo-plotting-networks-py) to download the full example code. # DyNeMo: Plotting Networks In this tutorial we will plot networks from a DyNeMo model trained on source reconstructed MEG data. This tutorial covers: 1. Calculate regression spectra 2. PSDs 3. Power maps 4. Coherence networks ## Download source data and inferred parameters In this tutorial, we’ll download example data from [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the source data (approximately 52 MB) get_data("notts_meguk_giles_5_subjects", rename="source_data") # Download the inferred mixing coefficients (approximately 11 MB) get_inf_params("tde_dynemo_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Calculate regression spectra We calculate the networks based on the regression spectra. See the [DyNeMo Regression Spectra tutorial](tutorials_build/5-1_dynemo_regression_spectra.html.md) for details. ```Python import pickle from osl_dynamics.data import Data from osl_dynamics.analysis import spectral # Source data trimmed to match the mixing coefficients data = Data("source_data") trimmed_data = data.trim_time_series(n_embeddings=15, sequence_length=200) # Mixing coefficients alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) # Regression spectra for each subject and mode spectra = spectral.regression_spectra( data=trimmed_data, alpha=alpha, sampling_frequency=250, frequency_range=[1, 45], ) print(spectra) ``` ```none Loading files: 0%| | 0/5 [00:00 If you saved the spectra with spectra.save, you can load them with spectral.Spectra.load. ## PSDs We can plot the power spectra to see what oscillations typically occur when a particular mode is active. We plot the regression coefficients (psd_coefs): the change in the PSD from the static PSD for a one standard deviation increase in a mode’s mixing coefficient. See the [Spectral Analysis](user_guide/spectra.html.md) page of the User Guide for more details. First, we average over subjects. The group average is weighted by the number of samples in each subject. ```Python group = spectra.group_average() print(group.psd_coefs.shape) ``` ```none (7, 38, 45) ``` group.psd_coefs is a (modes, channels, frequencies) array. Now let’s plot the group-average PSD for each mode, averaged over channels. The shaded area is the standard error over channels. ```Python fig, ax = group.plot_psd() ``` ## Power maps Now let’s average the power spectra over frequency to calculate the power. ```Python from osl_dynamics.analysis import power p = group.power_maps() print(p.shape) ``` ```none (7, 38) ``` We can see p is a (modes, channels) array. The power maps are the change in power from the static power: red regions have more power when a mode is active and blue regions have less. ```Python # Display the power maps (takes a few seconds to appear) fig, ax = power.save( p, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", plot_kwargs={"symmetric_cbar": True}, ) ``` ```none Saving images: 0%| | 0/7 [00:00 We can see recognizable functional networks, which gives us confidence in the DyNeMo fit. We also see the networks are more localized than typical HMM states. A DyNeMo fit often has one mode with a small covariance that takes most of the mixing coefficients: its power map is negative everywhere. ## Coherence networks Next, let’s visualize the coherence networks. The coherence_networks method averages the change in coherence (coherence_coefs) over frequency. ```Python c = group.coherence_networks() print(c.shape) ``` ```none (7, 38, 38) ``` We now have a (modes, channels, channels) array. This is the change in the cross spectrum, normalized by the static power (change in coherence), when a mode is active: it includes changes in both coherence and power. Let’s show the 3% of edges with the largest changes (increases or decreases). ```Python from osl_dynamics.analysis import connectivity c = group.coherence_networks(percentile=97) connectivity.save( c, parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", ) ``` ```none Saving images: 0%| | 0/7 [00:00 Red edges are increases and blue edges are decreases. The networks are in the same regions as the changes in power. We expect these networks will improve with more subjects. **Total running time of the script:** (0 minutes 41.398 seconds) [`Download Jupyter notebook: 5-2_dynemo_plotting_networks.ipynb`](_downloads/b920478f7b61cff95350930570a70ab4/5-2_dynemo_plotting_networks.ipynb) [`Download Python source code: 5-2_dynemo_plotting_networks.py`](_downloads/19a9a28f709c8b93472ed60e26fe86fb/5-2_dynemo_plotting_networks.py) [`Download zipped: 5-2_dynemo_plotting_networks.zip`](_downloads/9f1e19c4f3a8dd88fb8fe4dd960a4605/5-2_dynemo_plotting_networks.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/5-3_dynemo_mixing_coefs.html.md #### NOTE [Go to the end](tutorials_build/5-3_dynemo_mixing_coefs.html.md#sphx-glr-download-tutorials-build-5-3-dynemo-mixing-coefs-py) to download the full example code. # DyNeMo: Mixing Coefficients In this tutorial we analyze DyNeMo mixing coefficients. This tutorial covers: 1. Summarizing the mixing coefficient time course 2. Binarizing the mixing coefficient time course ## Download inferred parameters ```Python import os def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 11 MB) get_inf_params("tde_dynemo_notts_meguk_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Summarizing the mixing coefficient time course Let’s start by plotting the mixing coefficients to get a feel for the description provided by DyNeMo. First, we load the inferred mixing coefficients. ```Python import pickle alpha = pickle.load(open("results/inf_params/alp.pkl", "rb")) ``` We can use the [`utils.plotting.plot_alpha`](autoapi/osl_dynamics/utils/plotting/plot_alpha.html.md#osl_dynamics.utils.plotting.plot_alpha) to plot the mixing coefficients. ```Python from osl_dynamics.utils import plotting # Plot the mixing coefficient time course for the first subject (8 seconds) fig, ax = plotting.plot_alpha(alpha[0], n_samples=2000) ``` Plotting the raw values of the mixing coefficients as provided by DyNeMo it gives the impression that one mode dominates, in this case mode 4. However, the model DyNeMo uses is $C_t = \displaystyle\sum_j \alpha_{jt} D_j$, where $\alpha_{jt}$ are the mixing coefficients and $D_j$ are the mode covariances. This means a mode can have a small $\alpha_{jt}$ value but still be a large contributor to the time-varying covariance $C_t$. ### Normalizing the mixing coefficients To account for the difference in mode covariances we can renormalize the mixing coefficients include the ‘size’ of the mode covariances. ```Python import numpy as np from osl_dynamics.inference import modes # Load the inferred mode covariances covs = np.load("results/inf_params/covs.npy") # Renormalize the mixing coefficients norm_alpha = modes.reweight_alphas(alpha, covs) # Plot the renormalized mixing coefficient time course for the first subject (8 seconds) fig, ax = plotting.plot_alpha(norm_alpha[0], n_samples=2000) ``` We can now see each mode has a roughly equal contribution to the total covariance. We can also see fast fluctuations in the relative contribution of each mode. ### Summary Statistics An analogous summary measure to the Hidden Markov Model’s (HMM’s) fractional occupancy is the time average mixing coefficient. This is the average contribution a mode makes to the total covariance. Let’s calculate this for each subject. ```Python mean_norm_alpha = np.array([np.mean(a, axis=0) for a in norm_alpha]) # Print group average print(np.mean(mean_norm_alpha, axis=0)) # Plot distribution over subjects fig, ax = plotting.plot_violin(mean_norm_alpha.T, x_label="Mode", y_label="Mean alpha") ``` ```none [0.08012532 0.154482 0.12553507 0.27031273 0.07950173 0.1233431 0.16669996] ``` Note, we can calculate this using the raw mixing coefficients or the normalized mixing coefficients. We see there is a lot of variability between subjects in terms of this metric. Another summary measure we could calculate for each subject is the standard deviation of the mixing coefficient time course, which can be a measure for how variable the mixing of each modes is. ```Python std_norm_alpha = np.array([np.std(a, axis=0) for a in norm_alpha]) # Print group average print(np.mean(std_norm_alpha, axis=0)) # Plot distribution over subjects fig, ax = plotting.plot_violin(std_norm_alpha.T, x_label="Mode", y_label="Std alpha") ``` ```none [0.05494202 0.0734943 0.06309029 0.0938042 0.03117273 0.06350952 0.0783511 ] ``` Another summary statistic is the kurtosis, which reflects spiking the in mixing coefficient time course. ```Python from scipy import stats kurt_norm_alpha = np.array([stats.kurtosis(a, axis=0) for a in norm_alpha]) # Print group average print(np.mean(kurt_norm_alpha, axis=0)) # Plot distribution over subjects fig, ax = plotting.plot_violin(kurt_norm_alpha.T, x_label="Mode", y_label="Kurt. alpha") ``` ```none [2.8942084 1.4487442 1.1485741 0.04428925 7.8717003 1.7537016 1.9642332 ] ``` ## Binarizing the mixing coefficient time course If we convert the mixing coefficients into a binary time course for each mode (i.e. something similar to the HMM state time courses) we can calculate the usual summary statistics we did for the HMM states (fractional occupancies, lifetimes, intervals). See the [HMM Summary Statistics tutorial](tutorials_build/4-3_hmm_summary_stats.html.md) for further details. We have a couple options for binarizing the mixing coefficient time course: 1. Take the mode with the largest value as ‘on’ while the other modes are ‘off’. This gives a mutually exclusive mode activation time course. 2. Specify a threshold for mode activations. This can be a hand specified threshold or one determined using a data driven approach, such as fitting a Gaussian Mixture Model (GMM). In this case we can have co-activating modes. Let’s have a look at each of these options. ### Binarize with argmax We can use the [`inference.modes.argmax_time_courses`](autoapi/osl_dynamics/inference/modes/argmax_time_courses.html.md#osl_dynamics.inference.modes.argmax_time_courses) function to calculate a mutually exclusive mode activation time course. ```Python from osl_dynamics.inference import modes # Use the mode with the largest value to define mode activations atc = modes.argmax_time_courses(norm_alpha) # Plot the mode activation time course for the first subject (first 8 seconds) fig, ax = plotting.plot_alpha(atc[0], n_samples=2000) ``` With the mode activation time course we can calculate the usual HMM summary statistics like fractional occupancy. ```Python fo = modes.fractional_occupancies(atc) # Print group average print(np.round(np.mean(fo, axis=0), 2)) ``` ```none [0.02 0.11 0.06 0.6 0. 0.05 0.15] ``` We see there is more of an imbalance between mode activations compared to the HMM state description. ### Binarize with a percentile threshold Next, let’s first specify a threshold by hand. Looking at the distribution of mixing coefficients could help us evaluate a good threshold. ```Python import matplotlib.pyplot as plt def plot_hist(alpha, x_label=None): fig, ax = plt.subplots() for i in range(alpha.shape[1]): ax.hist(alpha[:, i], label=f"Mode {i+1}", bins=50, histtype="step") ax.legend() ax.set_xlabel(x_label) # Concatenate the alphas for each subject concat_norm_alpha = np.concatenate(norm_alpha) # Plot their distribution plot_hist(concat_norm_alpha, x_label="Normalized mixing coefficients") ``` We see the distribution of each mode’s mixing coefficients has a long tail. We’re interested in picking out the time points when the mixing coefficients take values in the long tail. We also see the appropriate threshold for each mode is very different. Let’s use the 90th percentile to determine the threshold of each mode. ```Python thres = np.array([np.percentile(a, 90, axis=0) for a in norm_alpha]) ``` We see the threshold varies a lot across the subjects. Now we have the threshold, let’s binarize. ```Python # Binarize the mixing coefficients thres_norm_alpha = [] n_subjects = len(norm_alpha) for na, t in zip(norm_alpha, thres): tna = (na > t).astype(int) thres_norm_alpha.append(tna) # Plot the mode activation time courses for the first subject (first 8 seconds) fig, ax = plotting.plot_separate_time_series(thres_norm_alpha[0], n_samples=2000) ``` When we threshold using a percentile with the group concatenated data, by definition the fractional occupancy equals the percentile. ```Python fo = modes.fractional_occupancies(thres_norm_alpha) # Print group average print(np.mean(fo, axis=0)) ``` ```none [0.1 0.1 0.1 0.1 0.1 0.1 0.1] ``` We see the fractional occupancy for each subject and state is 0.1, which corresponds to the segments with normalized alpha values in the top 10%. In contrast, the lifetimes are interpretable. ```Python mlt = modes.mean_lifetimes(thres_norm_alpha, sampling_frequency=250) # Print group average print(np.mean(mlt, axis=0) * 1000) # in ms ``` ```none [57.99183765 63.96468969 50.31304895 58.06805169 76.01930424 50.89961496 63.0871057 ] ``` We see with a 90th percentile threshold we get lifetimes of around ~50 ms. ### Binarize with a GMM threshold An aternative approach is to use a two-component GMM to identify an on and off component. This involves fitting the two-component GMM to the distribution of mixing coefficients. We can do this with the [`inference.modes.gmm_time_courses`](autoapi/osl_dynamics/inference/modes/gmm_time_courses.html.md#osl_dynamics.inference.modes.gmm_time_courses) function in osl-dynamics. ```Python # Binarize the mixing coefficients using a GMM thres_norm_alpha = modes.gmm_time_courses(norm_alpha) # Plot the mode activation time courses for the first subject (first 8 seconds) plotting.plot_separate_time_series(thres_norm_alpha[0], n_samples=2000) # Display the group average fo = modes.fractional_occupancies(thres_norm_alpha) print(np.mean(fo, axis=0), 2) ``` ```none Fitting GMMs: 0%| | 0/5 [00:00 We can see the GMM thresholds identify more mode activations, which are reflected in the higher fractional occupancies. With a mode activation time course we can do the same analysis we did for the HMM state time courses. See the [HMM Summary Statistics tutorial](tutorials_build/4-3_hmm_summary_stats.html.md) for more details. **Total running time of the script:** (0 minutes 8.714 seconds) [`Download Jupyter notebook: 5-3_dynemo_mixing_coefs.ipynb`](_downloads/0d485c71b10e76aee1f19e672ab0344e/5-3_dynemo_mixing_coefs.ipynb) [`Download Python source code: 5-3_dynemo_mixing_coefs.py`](_downloads/23ea18db6f4bb7f343781c8cddfd140f/5-3_dynemo_mixing_coefs.py) [`Download zipped: 5-3_dynemo_mixing_coefs.zip`](_downloads/14fe0d0ab5ed2f40798602bf20e10224/5-3_dynemo_mixing_coefs.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/6-1_epoching_alpha.html.md #### NOTE [Go to the end](tutorials_build/6-1_epoching_alpha.html.md#sphx-glr-download-tutorials-build-6-1-epoching-alpha-py) to download the full example code. # Epoching: Network Response In this tutorial we will cover how to epoch the inferred state/mode time courses. We will use the functionality in MNE to do this. This requires us to have the continuous training data in .fif format. ## Download source data In this tutorial, we’ll download example data from [OSF](https://osf.io/by2tc/). ```Python import os def get_data(name, rename): os.system(f"osf -p by2tc fetch data/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 88 MB) get_data("wakeman_henson_giles_5_subjects", rename="src") ``` ```none 'Data downloaded to: src' ``` ## Download inferred parameters ```Python def get_inf_params(name, rename): os.system(f"osf -p by2tc fetch inf_params/{name}.zip") os.makedirs(rename, exist_ok=True) os.system(f"unzip -o {name}.zip -d {rename}") os.remove(f"{name}.zip") return f"Data downloaded to: {rename}" # Download the dataset (approximately 17 MB) get_inf_params("tde_hmm_wakeman_henson_giles_5_subjects", rename="results/inf_params") ``` ```none 'Data downloaded to: results/inf_params' ``` ## Convert to mne.io.Raw To epoch the state/mode time courses, we first load the inferred state/mode time courses. These **will not include any bad segments** and will have time points removed due to time-delay embedding and separating into sequences (or other data processing steps). To handle this we will make use of MNE by converting the state/mode time courses to mne.io.Raw format then we will use the usual MNE functions to epoch. ```Python import os import pickle from osl_dynamics.inference import modes # Load inferred state/mode time courses alp = pickle.load(open("results/inf_params/alp.pkl", "rb")) alp = alp[0] # Corresponding fif file containing the parcellated data parc_fif = "src/sub01_run01/sflip_parc-raw.fif" # Convert the state/mode time courses to mne.io.Raw format alp_raw = modes.convert_to_mne_raw(alp, parc_fif, n_embeddings=15) # Save os.makedirs("results/alphas", exist_ok=True) alp_raw.save("results/alphas/sub01_run01_alpha-raw.fif", overwrite=True) ``` ```none Creating RawArray with float64 data, n_channels=8, n_times=124250 Range : 0 ... 124249 = 0.000 ... 496.996 secs Ready. Creating RawArray with float64 data, n_channels=3, n_times=124250 Range : 0 ... 124249 = 0.000 ... 496.996 secs Ready. Writing /home/docs/checkouts/osl-dynamics/checkouts/latest/doc/tutorials/results/alphas/sub01_run01_alpha-raw.fif Closing /home/docs/checkouts/osl-dynamics/checkouts/latest/doc/tutorials/results/alphas/sub01_run01_alpha-raw.fif [done] [PosixPath('/home/docs/checkouts/osl-dynamics/checkouts/latest/doc/tutorials/results/alphas/sub01_run01_alpha-raw.fif')] ``` Note: - If the parcellated data fif file contains a ‘stim’ channel, it will automatically be transferred to the alp_raw object. This is useful because the stim channel will be used to find events. - If you used time-delay embedding or a moving average when you prepared the data, then you need to pass n_embeddings or n_window respectively to convert_to_mne_raw to correctly account for the time points that are trimmed from the data. ## Get the epoched data To get the epoched data (trials) we use the standard MNE approach by first finding the events then epoching. ```Python import mne # Find events events = mne.find_events(alp_raw, min_duration=0.005) # Trigger IDs for events in the task event_ids = {"famous": 6, "unfamiliar": 13, "scrambled": 17} # Pick the channels are correspond to the network time courses alp_raw.pick("misc") # Epoch epochs = mne.Epochs( alp_raw, events, event_ids, tmin=-0.1, tmax=1.0, baseline=None, ) # Get the epoched data data = epochs.get_data() print(data.shape) # Time axis t = epochs.times ``` ```none Finding events on: STI101 296 events found on stim channel STI101 Event IDs: [ 5 6 7 13 14 15 17 18 19 256 261 262 263 269 270 271 273 274 275 4096 4101 4102 4103 4109 4110 4111 4114] Not setting metadata 60 matching events found No baseline correction applied 0 projection items activated Using data from preloaded Raw for 60 events and 276 original time points ... 1 bad epochs dropped (59, 8, 276) ``` We see data is (trials, time, states/modes). This is the trials for this session. Note, when we do .get_data() MNE will automatically drop any epoch that overlaps with a bad segment in the parcellated data fif file. If we want a particular trial type, then we can get it using the normal MNE approach: ```Python famous = epochs["famous"].get_data() print(famous.shape) ``` ```none Using data from preloaded Raw for 10 events and 276 original time points ... (10, 8, 276) ``` ## Statistical significance testing We can average the trials (epochs) for a given subject and do stats to see if there’s a significant response. See the [Network Response](tutorials_build/7-3_network_response.html.md) tutorial for how to do group-level stats on the subject-level network responses. **Total running time of the script:** (0 minutes 0.957 seconds) [`Download Jupyter notebook: 6-1_epoching_alpha.ipynb`](_downloads/547c29cc71730b390eac58ca76c5f4ad/6-1_epoching_alpha.ipynb) [`Download Python source code: 6-1_epoching_alpha.py`](_downloads/87616edcbffc0e18eb43f9a219d3943d/6-1_epoching_alpha.py) [`Download zipped: 6-1_epoching_alpha.zip`](_downloads/61d65b2e03534902e4832d5677d2d6ed/6-1_epoching_alpha.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/7-1_statistical_inference.html.md #### NOTE [Go to the end](tutorials_build/7-1_statistical_inference.html.md#sphx-glr-download-tutorials-build-7-1-statistical-inference-py) to download the full example code. # Statistical Inference This tutorial is an introduction to statistical significance testing with the [`osl_dynamics.stats`](autoapi/osl_dynamics/stats/index.html.md#module-osl_dynamics.stats) subpackage. It covers: 1. Hypothesis testing at every target (parcel, state, time point, etc.). 2. The General Linear Model (GLM) that all the tests are built on. 3. Permutation tests and when they are exact. 4. The multiple comparisons problem and the corrections available: Bonferroni, Holm, FDR, maximum statistic, cluster-based and TFCE. 5. How to choose a correction and how to interpret and report the results. The structure follows the excellent [Statistical inference](https://mne.tools/stable/auto_tutorials/stats-sensor-space/10_background_stats.html) tutorial from MNE-Python, applied to the kind of data osl-dynamics produces. The [FieldTrip](https://www.fieldtriptoolbox.org/tutorial/stats/) statistics tutorials are another very good resource. The practical tutorials that follow show the tests on realistic analyses: [group contrasts](tutorials_build/7-2_group_contrast.html.md), [network responses](tutorials_build/7-3_network_response.html.md) and [custom designs](tutorials_build/7-4_custom_designs.html.md). ## Simulated data We simulate a **network response**: the state (or mode) time course of a dynamic network model epoched around a task event and averaged over trials, for each subject. This gives an array with shape (n_subjects, n_time, n_states). After baseline correction, the question is whether the response differs from zero at each time point and state. The noise is smoothed over time so that neighboring time points are correlated, as they are in real data. A real effect is planted in state 1 (samples 30-60) and a smaller one in state 3 (samples 70-85). ```Python import numpy as np from scipy.ndimage import gaussian_filter1d np.random.seed(42) n_subjects, n_time, n_states = 20, 100, 4 noise = np.random.normal(size=(n_subjects, n_time, n_states)) noise = gaussian_filter1d(noise, sigma=2, axis=1) noise /= noise.std() true_effect = np.zeros((n_time, n_states)) true_effect[30:60, 0] = 0.8 * np.hanning(30) true_effect[70:85, 2] = 0.6 * np.hanning(15) data = noise + true_effect print(data.shape) ``` ```none (20, 100, 4) ``` We call the first dimension the **samples** (here subjects; it could be sessions or trials) and the remaining dimensions the **targets**: here 100 time points x 4 states = 400 targets. Every function in [`osl_dynamics.stats`](autoapi/osl_dynamics/stats/index.html.md#module-osl_dynamics.stats) works with any number of target dimensions. Let’s plot the true effect and the group average, with time on the x-axis and the states on the y-axis. ```Python import matplotlib.pyplot as plt def plot_map(values, title, ax, cmap="RdBu_r", vmax=None, **kwargs): """Plot a (time, states) map.""" vmax = np.nanmax(np.abs(values)) if vmax is None else vmax im = ax.imshow( values.T, aspect="auto", origin="lower", cmap=cmap, vmin=-vmax, vmax=vmax, interpolation="nearest", **kwargs, ) ax.set_yticks(range(n_states)) ax.set_yticklabels([f"State {i + 1}" for i in range(n_states)]) ax.set_xlabel("Time (samples)") ax.set_title(title) return im fig, axes = plt.subplots(1, 2, figsize=(10, 2.8)) plot_map(true_effect, "True effect", axes[0]) plot_map(data.mean(axis=0), "Group average (observed)", axes[1]) fig.tight_layout() ``` ## Hypothesis testing At each target we have 20 values (one per subject) and ask: is their mean different from zero? The **null hypothesis** $H_0$ is that the mean is zero. A **test statistic** measures the evidence against $H_0$; for a mean the natural choice is the t-statistic $$ t = \frac{\bar{x}}{s / \sqrt{n}}, $$ the mean divided by its standard error. The **p-value** is the probability of a statistic at least this extreme if $H_0$ were true. Testing every target separately like this is called a **mass-univariate** analysis. ### The General Linear Model All tests in osl-dynamics are expressed as a General Linear Model (GLM): at every target the data $y$ (one value per sample) is modeled as $$ y = X \beta + \epsilon, $$ where $X$ is the **design matrix** (one row per sample, one column per regressor) and $\beta$ are the regression coefficients. A **contrast** $c$ is a vector of weights over the regressors; the quantity tested is $c^T \beta$, called the **cope** (contrast of parameter estimates). Its variance is the **varcope** and the t-statistic is $\text{cope} / \sqrt{\text{varcope}}$. For a one-sample test the design has a single column of ones and the contrast is `[1]`: the cope is the mean. The high-level functions build the design for you, but we can look at it: ```Python from osl_dynamics import stats design = stats.DesignConfig( features=[{"name": "Mean", "values": np.ones(n_subjects), "feature_type": "constant"}], contrasts=[{"name": "Mean", "values": [1]}], ).create_design() fig, axes = design.plot() ``` The same machinery describes the other questions we ask in osl-dynamics. Comparing two groups uses an indicator column per group and the contrast `[1, -1, 0]` (group 1 minus group 2); testing for an effect of age uses a column of ages and the contrast on that column. Nuisance covariates get extra columns with weight zero in the contrast, so their effect is regressed out: ```Python group = np.repeat([1, 2], n_subjects // 2) age = np.random.normal(45, 10, size=n_subjects) group_design = stats.DesignConfig( features=[ {"name": "Group 1", "values": group == 1, "feature_type": "categorical"}, {"name": "Group 2", "values": group == 2, "feature_type": "categorical"}, {"name": "Age", "values": age, "feature_type": "continuous"}, ], contrasts=[{"name": "Group 1 - Group 2", "values": [1, -1, 0]}], ).create_design() fig, axes = group_design.plot() ``` Continuous regressors are z-scored, so the cope for a continuous regressor is the change in the data per standard deviation of the regressor. ### Parametric test If the noise is Gaussian, the t-statistic follows a Student t-distribution under $H_0$ and the p-value can be read from it. This is the classic parametric t-test. Setting `correction=None` gives the uncorrected parametric p-values: ```Python result = stats.evoked_response(data, correction=None) print(result) ``` ```none TestResult(contrast='Mean', statistic='t', target_dims=(100, 4), correction=None, tail=0, parametric=True, n_significant (p<0.05)=46, min_pvalue=6.835615464068445e-06) ``` Every test returns a [`TestResult`](autoapi/osl_dynamics/stats/TestResult.html.md#osl_dynamics.stats.TestResult). The most useful attributes are `copes` (the effect, here the mean response), `tstats`, `pvalues` and the `significant()` mask, all with the shape of the targets. ```Python fig, axes = plt.subplots(1, 2, figsize=(10, 2.8)) plot_map(result.tstats, "t-statistic", axes[0]) plot_map(result.significant(), "p < 0.05 (uncorrected)", axes[1], cmap="Greys", vmax=1) fig.tight_layout() print("Significant targets:", result.significant().sum(), "of", result.pvalues.size) ``` ```none Significant targets: 46 of 400 ``` The true effects are found, but so are many scattered false positives. We will come back to this. ## Permutation tests The parametric p-value relies on the t-distribution, which assumes Gaussian noise. Summary statistics such as fractional occupancies (bounded between 0 and 1) or lifetimes (skewed) do not satisfy this. **Permutation tests** instead build the null distribution of the statistic from the data itself. The key idea is **exchangeability**: under $H_0$, some rearrangement of the data leaves its distribution unchanged, so the statistic recomputed after that rearrangement is a draw from the null distribution. Repeating this many times gives the null distribution, and the p-value is the fraction of permuted statistics at least as extreme as the observed one. The two rearrangements used in osl-dynamics are: - **Sign flipping**: for a test of a mean (one-sample or paired differences), under $H_0$ each subject’s value is as likely to be positive as negative, so we randomly flip the sign of each subject’s data. This is a *within-subject* test and needs the noise to be symmetric about zero. - **Row shuffling**: for a comparison between groups or a regression on a continuous variable, under $H_0$ the group labels (or covariate values) carry no information, so we shuffle which label goes with which subject. This is a *between-subject* test and needs no distributional assumption at all. The permutation type is chosen automatically from the design. With nuisance covariates, osl-dynamics uses the Freedman-Lane scheme recommended by [Winkler et al. (2014)](https://doi.org/10.1016/j.neuroimage.2014.01.060): the covariates are regressed out, the residuals are permuted, and the full model is refitted. Let’s run per-target permutation tests (still uncorrected) with `parametric=False`: ```Python result_perm = stats.evoked_response( data, correction=None, parametric=False, n_perm=500, metric="tstats" ) ``` ```none Permutations: 0%| | 0/500 [00:00 The null distribution for each target is kept in `result.null`. For a two-tailed test it is the distribution of $|t|$, so we compare it with the folded t-distribution at a target without a true effect: ```Python from scipy import stats as scipy_stats t_index, state = 10, 3 # a target with no true effect null = result_perm.null[:, t_index, state] observed = abs(result_perm.tstats[t_index, state]) fig, ax = plt.subplots(figsize=(6, 3.5)) ax.hist(null, bins=30, density=True, color="tab:gray", label="Permutation null of |t|") t_axis = np.linspace(0, 4, 200) ax.plot( t_axis, 2 * scipy_stats.t.pdf(t_axis, df=n_subjects - 1), "k", label="Folded t-distribution" ) ax.axvline(observed, color="tab:red", label="Observed |t|") ax.set_xlabel("|t|") ax.legend() fig.tight_layout() print("Permutation p =", round(result_perm.pvalues[t_index, state], 3)) print("Parametric p =", round(result.pvalues[t_index, state], 3)) ``` ```none Permutation p = 0.176 Parametric p = 0.144 ``` With Gaussian noise the two agree. With non-Gaussian data only the permutation test is valid. Two practical points: - The p-value from $N$ random permutations is $(1 + b) / (N + 1)$, where $b$ is the number of permuted statistics at least as extreme as the observed one. It can never be zero: the smallest p-value is $1 / (N + 1)$, so use at least 1000 permutations to resolve p = 0.001. - With few samples (up to 9 subjects for a sign-flip test with the default 1000 permutations), every possible permutation is enumerated and the test is **exact**; `result.exact` tells you when this happened. Permutations use NumPy’s global random state, so [`osl_dynamics.utils.set_random_seed()`](autoapi/osl_dynamics/utils/set_random_seed.html.md#osl_dynamics.utils.set_random_seed) makes them reproducible. ## Multiple comparisons We tested 400 targets. At p < 0.05, we expect 5% of the targets with no effect to come out significant by chance: about 20 false positives, which is what the uncorrected map showed. With more targets (every parcel and frequency, every connection in a connectivity matrix) the problem gets worse. There are two ways to define what we want to control: - The **family-wise error rate (FWER)**: the probability of *any* false positive across all the targets. Controlling it at 5% means that in 95% of experiments with no true effect, nothing is declared significant. - The **false discovery rate (FDR)**: the expected *fraction* of the significant targets that are false positives. Controlling it at 5% means that, on average, 5% of what you report is wrong. This is less strict and so more powerful. The `correction` argument of every test selects the correction. We now apply each one to the same data. ### Bonferroni and Holm Bonferroni multiplies every p-value by the number of tests. It controls the FWER but is very conservative when the targets are correlated, as neighboring time points are. Holm’s step-down procedure is a uniformly more powerful version with the same guarantee. ```Python result_bonferroni = stats.evoked_response(data, correction="bonferroni") result_holm = stats.evoked_response(data, correction="holm") ``` ### False discovery rate The Benjamini-Hochberg procedure controls the FDR. It is a good choice when a few false positives are acceptable and the targets are not strongly dependent, e.g. for connectivity matrices with thousands of connections. ```Python result_fdr = stats.evoked_response(data, correction="fdr") ``` ### Maximum statistic permutation test The permutation framework gives a natural FWER correction ([Nichols & Holmes, 2002](https://doi.org/10.1002/hbm.1058)): in each permutation, take the **maximum** statistic over all the targets. The distribution of this maximum is the null distribution of “the largest statistic anywhere in the map by chance”, and a target is significant if its observed statistic exceeds the 95th percentile of it. This accounts for the correlation between targets, so it is less conservative than Bonferroni, and it makes no distributional assumption. It is the default correction in osl-dynamics. ```Python result_max = stats.evoked_response(data, n_perm=500, metric="tstats") print(result_max) ``` ```none Permutations: 0%| | 0/500 [00:00 The `metric` can be `'tstats'` or `'copes'`. Taking the maximum over copes is only valid when all the targets have the same units, as they do for a network response (the default for [`evoked_response()`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response) is `'copes'`); t-statistics are the default everywhere else. The `hat` argument adds a small fraction of the largest variance to every target’s variance, which stops near-zero-variance targets producing huge t-statistics ([Ridgway et al., 2012](https://doi.org/10.1016/j.neuroimage.2011.10.027)). The null distribution of the maximum can be plotted: ```Python fig, ax = result_max.plot_null() ``` ### Cluster-based permutation test The maximum statistic treats every target on its own. But real effects in time (or frequency, or space) are extended: they form **clusters** of neighboring targets. The cluster-based permutation test ([Maris & Oostenveld, 2007](https://doi.org/10.1016/j.jneumeth.2007.03.024)) uses this: 1. Threshold the t-statistics at a **cluster-forming threshold** (by default the critical t at p = 0.05). 2. Group neighboring supra-threshold targets into clusters and sum their t-statistics to give a **cluster statistic**. 3. In each permutation, do the same and record the largest cluster statistic. This is the null distribution. 4. A cluster’s p-value is the fraction of permutations whose largest cluster was at least as big. The neighbors are defined by `cluster_dims`: the target dimensions along which clusters can extend. For a network response that is time (dimension 0 of the targets, the default for [`evoked_response()`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response)). States are not neighbors of each other, so a cluster never spans two states, but the maximum is still taken over all states and the FWER is controlled across the whole map. ```Python result_cluster = stats.evoked_response(data, n_perm=500, correction="cluster") print(result_cluster) for mask, p in zip(result_cluster.clusters, result_cluster.cluster_pvalues): times = np.where(mask.any(axis=1))[0] state_idx = np.where(mask.any(axis=0))[0][0] print(f"State {state_idx + 1}, samples {times[0]}-{times[-1]}: p = {p:.3f}") ``` ```none Permutations: 0%| | 0/500 [00:00 Every target in `result.pvalues` holds the p-value of the cluster it belongs to (1 outside clusters), so `result.significant()` marks the targets in significant clusters. ### Threshold-free cluster enhancement The cluster-forming threshold is arbitrary: a strict threshold finds focal, strong effects and a lenient one finds broad, weak effects. **Threshold-free cluster enhancement** (TFCE, [Smith & Nichols, 2009](https://doi.org/10.1016/j.neuroimage.2008.03.061)) integrates the cluster extent over all thresholds, giving each target an enhanced statistic that is then tested with the maximum statistic. There is no threshold to choose and each target gets its own p-value. ```Python result_tfce = stats.evoked_response(data, n_perm=500, correction="tfce") print(result_tfce) ``` ```none Permutations: 0%| | 0/500 [00:00 ## Comparison Let’s plot which targets each method declares significant. The outline shows the true effect. ```Python results = { "Uncorrected (parametric)": result, "Bonferroni": result_bonferroni, "Holm": result_holm, "FDR": result_fdr, "Maximum statistic": result_max, "Cluster-based": result_cluster, "TFCE": result_tfce, } fig, axes = plt.subplots(2, 4, figsize=(14, 5)) plot_map(true_effect, "True effect", axes[0, 0]) for ax, (name, res) in zip(axes.flat[1:], results.items()): plot_map(res.significant(), f"{name}\n{res.significant().sum()} significant", ax, cmap="Greys", vmax=1) ax.contour(true_effect.T > 0.05, levels=[0.5], colors="tab:red", linewidths=1) fig.tight_layout() ``` What to take from this: - The uncorrected map has false positives scattered everywhere. Never report it alone. - Bonferroni, Holm and the maximum statistic all control the FWER. The maximum statistic is less conservative because it accounts for the correlation between targets, but it still only finds the peak of a weak, extended effect. - FDR finds more of the effect at the cost of a few false positives. - The cluster-based test uses the temporal structure of the effect and recovers the most of it, including the weaker effect in state 3. TFCE sits between the maximum statistic and the cluster-based test here. These two are the standard choices for time courses and spectra. ### Which correction should I use? | Data | Recommended | Also reasonable | |----------------------------------------------------------------------------------|---------------------------------------|---------------------------------------------------------| | Summary statistics (subjects x states), power maps (subjects x states x parcels) | Maximum statistic | FDR; Holm | | Connectivity matrices (subjects x connections) | Maximum statistic | FDR (many connections, some false positives acceptable) | | Network responses (subjects x time x states) | Cluster-based or TFCE along time | Maximum statistic on copes (focal, strong effects) | | Spectra (subjects x states x parcels x frequency) | Cluster-based or TFCE along frequency | Maximum statistic | Use a one-tailed test (`tail=1` or `-1`) only when the direction of the effect was fixed before looking at the data. Use `pooled_dims` when you want to control the FWER within each state separately rather than across all states. ## Interpreting cluster-based results The cluster-based test rejects one null hypothesis: that the data are exchangeable, i.e. that there is no effect anywhere. A significant cluster tells you *that* there is an effect and points to where it is likely to be. It does **not** establish that the effect is present at every target in the cluster, nor that it starts and ends where the cluster does: the cluster’s extent depends on the signal-to-noise ratio, the number of subjects and the cluster-forming threshold. In particular, you cannot claim that an effect “starts at 150 ms” or “is confined to state 3” from a cluster test, see [Sassenhagen & Draschkow (2019)](https://doi.org/10.1111/psyp.13335) and the [FieldTrip FAQ](https://www.fieldtriptoolbox.org/faq/stats/clusterstats_interpretation/). Acceptable: “Network 1 showed a significant response (cluster-based permutation test, p = 0.002), most pronounced between 100 and 300 ms.” Not acceptable: “Network 1 was significantly active from 100 to 300 ms.” The same caveat applies, less strongly, to TFCE: its per-target p-values are still driven by neighboring targets. ## Reporting A results sentence should state the test, the design, the correction, the number of permutations, the tail and what was controlled for. For example: > “Group differences in fractional occupancy were assessed with a GLM permutation test (row-shuffle, 10,000 permutations, two-tailed) with age and sex as covariates, using the maximum t-statistic across states to control the family-wise error rate at 5%.” `print(result)` gives most of these values and `result.summary()` returns them as a dictionary. ## References - Maris, E. & Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. *Journal of Neuroscience Methods*, 164(1), 177-190. - Nichols, T. E. & Holmes, A. P. (2002). Nonparametric permutation tests for functional neuroimaging: a primer with examples. *Human Brain Mapping*, 15(1), 1-25. - Phipson, B. & Smyth, G. K. (2010). Permutation p-values should never be zero. *Statistical Applications in Genetics and Molecular Biology*, 9(1), 39. - Ridgway, G. R. et al. (2012). The problem of low variance voxels in statistical parametric mapping; a new hat avoids a ‘haircut’. *NeuroImage*, 59(3), 2131-2141. - Sassenhagen, J. & Draschkow, D. (2019). Cluster-based permutation tests of MEG/EEG data do not establish significance of effect latency or location. *Psychophysiology*, 56(6), e13335. - Smith, S. M. & Nichols, T. E. (2009). Threshold-free cluster enhancement. *NeuroImage*, 44(1), 83-98. - Winkler, A. M. et al. (2014). Permutation inference for the general linear model. *NeuroImage*, 92, 381-397. **Total running time of the script:** (0 minutes 1.419 seconds) [`Download Jupyter notebook: 7-1_statistical_inference.ipynb`](_downloads/0bfaecc77a3e4ba15065d775aff2a07e/7-1_statistical_inference.ipynb) [`Download Python source code: 7-1_statistical_inference.py`](_downloads/3ba2ab0405fc43d139038d2a16f7306e/7-1_statistical_inference.py) [`Download zipped: 7-1_statistical_inference.zip`](_downloads/696aab3a3bfbeea9a4e212777840de26/7-1_statistical_inference.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/7-2_group_contrast.html.md #### NOTE [Go to the end](tutorials_build/7-2_group_contrast.html.md#sphx-glr-download-tutorials-build-7-2-group-contrast-py) to download the full example code. # Group Contrast In this tutorial we test for differences between groups of subjects with [`stats.group_diff`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff). This covers the most common group-level questions in osl-dynamics: 1. Do the HMM summary statistics differ between groups? 2. Do the state power maps differ between groups? 3. Do the connectivity networks differ between groups? We also cover nuisance covariates, missing values, controlling the family-wise error rate per state and more than two groups. See the [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) for the background. ## Subject-specific features Group-level statistics start from a subject-specific quantity, e.g. the fractional occupancy of each state for each subject (a (subjects, states) array), the state power maps ((subjects, states, parcels)) or the connectivity networks ((subjects, states, parcels, parcels)). The first dimension must be the subjects; the remaining dimensions are the **targets** that are tested. Here, we simulate 30 subjects (the first 10 form group 1, the rest group 2) with 6 states and 38 parcels, and plant a difference in state 2 in a few parcels. ```Python import numpy as np np.random.seed(0) n_subjects, n_states, n_parcels = 30, 6, 38 assignments = np.ones(n_subjects) assignments[10:] = 2 power_maps = np.random.normal(size=(n_subjects, n_states, n_parcels)) power_maps[assignments == 1, 1, :5] += 1.5 ``` ## Comparing two groups [`stats.group_diff`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) fits a GLM with an indicator regressor per group and tests the contrast group 1 minus group 2. By default, it uses a row-shuffle permutation test with the maximum t-statistic across all targets to control the family-wise error rate (FWER). ```Python from osl_dynamics import stats result = stats.group_diff(power_maps, assignments, n_perm=1000) print(result) ``` ```none Permutations: 0%| | 0/1000 [00:00 The result object holds the group difference (copes), the t-statistics and the corrected p-values, each with shape (states, parcels): ```Python print(result.copes.shape, result.pvalues.shape) significant = result.significant() # pvalues < 0.05 print("Significant (state, parcel) pairs:", np.argwhere(significant).tolist()) ``` ```none (6, 38) (6, 38) Significant (state, parcel) pairs: [[1, 2], [1, 3]] ``` The design matrix and contrast that were used can be plotted from the result: ```Python fig, axes = result.glm.design.plot() ``` To plot a power map of the significant differences, zero the non-significant parcels and pass the array to [`power.save`](autoapi/osl_dynamics/analysis/power/save.html.md#osl_dynamics.analysis.power.save) as in the [Static Power Analysis tutorial](tutorials_build/2-2_static_power_analysis.html.md): ```default power_diff = result.copes.copy() power_diff[~result.significant()] = 0 power.save(power_diff, parcellation_file=..., filename="power_diff_.png") ``` ## Nuisance covariates Confounds such as age, sex or head size are passed as `covariates`. They are added to the design as nuisance regressors (z-scored for continuous variables) and regressed out; the permutations account for them with the Freedman-Lane scheme. ```Python age = np.random.normal(45, 12, size=n_subjects) sex = np.random.randint(0, 2, size=n_subjects) # 0/1 indicator result = stats.group_diff( power_maps, assignments, n_perm=1000, covariates={"age": age, "sex": sex} ) fig, axes = result.glm.design.plot() ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Controlling the FWER per state By default, the maximum statistic is taken over all targets (every state and parcel), so the FWER is controlled across the whole array. If you consider each state a separate family of tests, pass `pooled_dims` to take the maximum over the parcels only (target dimension 1). Each state then gets its own null distribution, which is more powerful but does not correct across states. ```Python result_per_state = stats.group_diff(power_maps, assignments, n_perm=1000, pooled_dims=1) print(result_per_state.null.shape) # one null distribution per state ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Summary statistics and missing values HMM summary statistics such as the mean lifetime are undefined (NaN) for a state a subject never visits. Each target is then fitted with the subjects that have a value for it, and a warning reports how many were dropped. ```Python mean_lifetimes = np.random.gamma(shape=5, scale=0.02, size=(n_subjects, n_states)) mean_lifetimes[assignments == 1, 0] *= 1.4 # longer lifetimes for state 1 in group 1 mean_lifetimes[3, 4] = np.nan # subject 4 never visits state 5 result = stats.group_diff(mean_lifetimes, assignments, n_perm=1000) print(result.pvalues.round(3)) ``` ```none Permutations: 0%| | 0/1000 [00:00 Lifetimes are positive and skewed, so the permutation test is preferable to a parametric t-test here. [`plotting.plot_summary_stats_group_diff`](autoapi/osl_dynamics/utils/plotting/plot_summary_stats_group_diff.html.md#osl_dynamics.utils.plotting.plot_summary_stats_group_diff) shows the two groups with stars for the significant states: ```Python from osl_dynamics.utils import plotting fig, ax = plotting.plot_summary_stats_group_diff( name="Mean Lifetime (s)", summary_stats=mean_lifetimes, pvalues=result, assignments=assignments, ) ``` ## Connectivity matrices A connectivity matrix is symmetric, so each connection appears twice. Testing the whole matrix would test every connection twice and halve the effective significance threshold. Use [`array_ops.mat2vec`](autoapi/osl_dynamics/utils/array_ops/mat2vec.html.md#osl_dynamics.utils.array_ops.mat2vec) to extract the upper triangle, test the vector, and [`array_ops.vec2mat`](autoapi/osl_dynamics/utils/array_ops/vec2mat.html.md#osl_dynamics.utils.array_ops.vec2mat) to go back to a matrix for plotting. ```Python from osl_dynamics.utils import array_ops # Simulate (subjects, parcels, parcels) connectivity matrices conn = np.random.normal(size=(n_subjects, n_parcels, n_parcels)) conn = (conn + np.swapaxes(conn, 1, 2)) / 2 conn[assignments == 1, 0, 1] += 2 conn[assignments == 1, 1, 0] += 2 conn_vec = array_ops.mat2vec(conn) # (subjects, n_connections) print(conn_vec.shape) result = stats.group_diff(conn_vec, assignments, n_perm=1000) conn_diff = result.copes.copy() conn_diff[~result.significant()] = 0 conn_diff = array_ops.vec2mat(conn_diff) # (parcels, parcels) print("Significant connections:", np.argwhere(np.triu(conn_diff) != 0).tolist()) ``` ```none (30, 703) Permutations: 0%| | 0/1000 [00:00 The matrix can be plotted with [`connectivity.save`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save). With thousands of connections, the maximum statistic can be conservative; `correction="fdr"` is a reasonable alternative if a small fraction of false positives is acceptable. ## More than two groups When `assignments` has more than two labels and no `groups` are given, [`stats.group_diff`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) tests whether *any* group differs from the others with an **F-test**: the GLM form of a one-way ANOVA, with row-shuffle permutations of all the subjects. An F-statistic has no direction, so the test is always two-tailed and `result.copes` holds the differences between consecutive groups rather than a single effect; `result.stats` gives the F-statistics. ```Python assignments_3 = assignments.copy() assignments_3[-5:] = 3 result = stats.group_diff(power_maps, assignments_3, n_perm=1000) print(result) print("Numerator degrees of freedom:", result.f_dof) ``` ```none Permutations: 0%| | 0/1000 [00:00 A significant F-test says that the groups are not all the same, not which ones differ. Follow it up with pairwise tests by passing the two labels to compare as `groups`. Every group is still modeled, so the residual variance is estimated from all subjects, but only the subjects in the two compared groups are shuffled. ```Python result_12 = stats.group_diff(power_maps, assignments_3, groups=(1, 2), n_perm=1000) print(result_12.contrast) ``` ```none Permutations: 0%| | 0/1000 [00:00 Each pairwise test controls the FWER across the targets on its own. If you report all the pairs, correct for their number as well (e.g. Bonferroni over the three pairs) or restrict yourself to the pairs you had a hypothesis about. Other contrasts (e.g. patients versus the mean of two control groups) can be specified with a custom design, see the [Custom Designs tutorial](tutorials_build/7-4_custom_designs.html.md). ## Effect sizes A p-value says whether an effect is detectable, not how large it is. [`result.effect_size()`](autoapi/osl_dynamics/stats/TestResult.html.md#osl_dynamics.stats.TestResult.effect_size) returns the group difference (the cope, in the units of the data) and Cohen’s d (the difference divided by the residual standard deviation of the GLM, i.e. the pooled standard deviation adjusted for any covariates), each with a confidence interval from a bootstrap over subjects. For an F-test it returns partial eta squared instead of d. ```Python result = stats.group_diff(power_maps, assignments, n_perm=1000) effect = result.effect_size(n_boot=1000) print(effect) for parcel in range(5): lo, hi = effect.d_ci[:, 1, parcel] print(f"State 2, parcel {parcel}: d = {effect.d[1, parcel]:.2f} [{lo:.2f}, {hi:.2f}]") ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Reporting `print(result)` summarizes the test. For example, the analysis above would be reported as: “Power maps were compared between groups with a GLM permutation test (1000 row-shuffle permutations, two-tailed) with age and sex as covariates, using the maximum t-statistic across states and parcels to control the family-wise error rate at 5%. Group 1 had higher power in state 2 (Cohen’s d = 1.1 to 1.6 in the significant parcels, 95% bootstrap confidence intervals in Table 1).” **Total running time of the script:** (0 minutes 0.533 seconds) [`Download Jupyter notebook: 7-2_group_contrast.ipynb`](_downloads/a8c85f372d7d2175efa30856fc024f75/7-2_group_contrast.ipynb) [`Download Python source code: 7-2_group_contrast.py`](_downloads/07dbb943e2c9ad0b57c3c61502e01f99/7-2_group_contrast.py) [`Download zipped: 7-2_group_contrast.zip`](_downloads/5142d31cb2dce39c1f7fc2ea14196df0/7-2_group_contrast.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/7-3_network_response.html.md #### NOTE [Go to the end](tutorials_build/7-3_network_response.html.md#sphx-glr-download-tutorials-build-7-3-network-response-py) to download the full example code. # Network Response In this tutorial we test whether a **network response** is significantly different from zero. A network response is the state (or mode) time course epoched around events of interest and averaged over trials, for each subject (see the [Epoching tutorial](tutorials_build/6-1_epoching_alpha.html.md)). We compare the three corrections for multiple comparisons that suit time courses: the maximum statistic, cluster-based permutations and threshold-free cluster enhancement (TFCE). See the [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) for the background. ## Get the network response The network response for each subject is a (time, networks) array, so for the group it is a (subjects, time, networks) array. It should be **baseline corrected** (the pre-stimulus mean subtracted) so that zero is the null hypothesis. Here we simulate it, with noise that is smooth in time as in real data. ```Python import numpy as np from scipy.ndimage import gaussian_filter1d np.random.seed(0) n_subjects, n_time, n_networks = 20, 250, 6 sampling_frequency = 250 # Hz t = np.arange(n_time) / sampling_frequency - 0.2 # seconds, stimulus at t=0 network_response = np.random.normal(size=(n_subjects, n_time, n_networks)) network_response = gaussian_filter1d(network_response, sigma=3, axis=1) network_response /= network_response.std() # Network 1 responds from 0.12 to 0.32 s, network 2 from 0.32 to 0.4 s network_response[:, 80:130, 0] += 1.5 * np.hanning(50) network_response[:, 130:150, 1] += 1.8 * np.hanning(20) # Baseline correct using the pre-stimulus period network_response -= network_response[:, t < 0].mean(axis=1, keepdims=True) ``` ## Maximum statistic [`stats.evoked_response`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response) fits a GLM with a constant regressor (the mean over subjects) at every time point and network and runs a sign-flip permutation test. The default correction takes the maximum over all time points and networks, so the family-wise error rate (FWER) is controlled across the whole response. ```Python from osl_dynamics import stats result_max = stats.evoked_response(network_response, n_perm=1000) print(result_max) ``` ```none Permutations: 0%| | 0/1000 [00:00 For network responses the maximum is taken over the copes (the mean response) rather than the t-statistics by default, because every target has the same units and the t-statistic can be unstable where the variance is close to zero (e.g. in the baseline window). Pass `metric="tstats"` to change this. [`plotting.plot_evoked_response`](autoapi/osl_dynamics/utils/plotting/plot_evoked_response.html.md#osl_dynamics.utils.plotting.plot_evoked_response) plots the group average with the significant time points marked: ```Python from osl_dynamics.utils import plotting labels = [f"Network {i + 1}" for i in range(n_networks)] fig, ax = plotting.plot_evoked_response( t, network_response.mean(axis=0), result_max, labels=labels, x_label="Time (s)", y_label="Network activation", title="Maximum statistic", ) ``` ## Cluster-based permutation test A response is extended in time, which the maximum statistic ignores. `correction="cluster"` thresholds the t-statistics, groups neighboring supra-threshold time points into clusters (within each network: clusters never span two networks) and tests the summed t-statistic of each cluster against the largest cluster found in each permutation. ```Python result_cluster = stats.evoked_response(network_response, n_perm=1000, correction="cluster") print(result_cluster) for mask, stat, p in zip( result_cluster.clusters, result_cluster.cluster_stats, result_cluster.cluster_pvalues ): network = np.where(mask.any(axis=0))[0][0] times = t[mask.any(axis=1)] print( f"Network {network + 1}: {times[0]:.3f} to {times[-1]:.3f} s, " f"cluster statistic = {stat:.1f}, p = {p:.3f}" ) ``` ```none Permutations: 0%| | 0/1000 [00:00 The cluster-forming threshold defaults to the critical t-value at p = 0.05 and can be changed with `cluster_forming_threshold`. Each time point in `result.pvalues` holds the p-value of its cluster, so the same plotting function marks the significant clusters: ```Python fig, ax = plotting.plot_evoked_response( t, network_response.mean(axis=0), result_cluster, labels=labels, x_label="Time (s)", y_label="Network activation", title="Cluster-based permutation test", ) ``` ## Threshold-free cluster enhancement TFCE avoids choosing a cluster-forming threshold by integrating the cluster extent over all thresholds, and gives each time point its own p-value. ```Python result_tfce = stats.evoked_response(network_response, n_perm=1000, correction="tfce") fig, ax = plotting.plot_evoked_response( t, network_response.mean(axis=0), result_tfce, labels=labels, x_label="Time (s)", y_label="Network activation", title="TFCE", ) ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Comparing the three Let’s count the significant time points for the two networks with a response: ```Python for name, res in [("Max statistic", result_max), ("Cluster", result_cluster), ("TFCE", result_tfce)]: sig = res.significant() print(f"{name:14s} network 1: {sig[:, 0].sum():3d} samples, network 2: {sig[:, 1].sum():3d} samples") ``` ```none Max statistic network 1: 20 samples, network 2: 8 samples Cluster network 1: 30 samples, network 2: 11 samples TFCE network 1: 24 samples, network 2: 6 samples ``` The cluster-based test recovers the most of the extended response in network 1, and TFCE more than the maximum statistic. For the brief response in network 2 the three are closer. The maximum statistic is better suited to focal, strong effects and to targets without a natural neighbourhood (parcels, states). ## Interpreting the clusters A significant cluster shows that the network responds; it does not establish *when* the response starts and ends, because the extent of a cluster depends on the signal-to-noise ratio and the threshold. Report it as “network 1 showed a significant response (cluster-based permutation test, 1000 sign-flip permutations, p = 0.001), most pronounced between 0.12 and 0.32 s”, not as “network 1 was active from 0.12 to 0.32 s”. See the [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) for more on this. ## Comparing conditions Often each subject has a response per condition and the question is whether the responses differ between conditions. For two conditions, pass the difference between the subject-specific responses to [`stats.paired_diff`](autoapi/osl_dynamics/stats/paired_diff.html.md#osl_dynamics.stats.paired_diff). For any number of conditions, [`stats.condition_diff`](autoapi/osl_dynamics/stats/condition_diff.html.md#osl_dynamics.stats.condition_diff) takes a (subjects, conditions, time, networks) array and fits a within-subject GLM: an indicator per condition plus an indicator per subject, so that the differences between subjects are modeled rather than left in the noise. The permutations shuffle the conditions within each subject (the subjects are **exchangeability blocks**). With three or more conditions it runs an F-test for any difference; `conditions=(a, b)` tests a pair. Here we simulate three conditions where the response of network 1 is larger in condition 2, and the subjects differ in their overall response amplitude: ```Python n_conditions = 3 responses = np.random.normal(size=(n_subjects, n_conditions, n_time, n_networks)) responses = gaussian_filter1d(responses, sigma=3, axis=2) responses /= responses.std() responses[:, :, 80:130, 0] += 1.5 * np.hanning(50) responses[:, 2, 80:130, 0] += 2.5 * np.hanning(50) # larger in condition 2 responses += np.random.normal(size=(n_subjects, 1, 1, 1)) # subject amplitude responses -= responses[:, :, t < 0].mean(axis=2, keepdims=True) result_cond = stats.condition_diff(responses, correction="cluster", cluster_dims=0, n_perm=1000) print(result_cond) print("Networks with a condition effect:", np.unique(np.where(result_cond.significant())[1])) ``` ```none Permutations: 0%| | 0/1000 [00:00 `result_cond.stats` holds the F-statistics and `result_cond.copes` the differences between consecutive conditions. The F-test says the conditions differ; which ones differ is a follow-up question: ```Python result_02 = stats.condition_diff(responses, conditions=(2, 0), correction="cluster", cluster_dims=0, n_perm=1000) print(result_02) ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Covariates and groups Nuisance covariates can be passed with the `covariates` argument of the between-subject tests. To compare two groups of subjects use [`stats.group_diff`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) with `correction="cluster"` and `cluster_dims=0` (time). **Total running time of the script:** (0 minutes 2.587 seconds) [`Download Jupyter notebook: 7-3_network_response.ipynb`](_downloads/021618d5382fd1c0c9ea2989c0725d98/7-3_network_response.ipynb) [`Download Python source code: 7-3_network_response.py`](_downloads/b9bb78e596a19a748d68fa2493a948ae/7-3_network_response.py) [`Download zipped: 7-3_network_response.zip`](_downloads/20b2476a0f1d29864d99ff861e707aea/7-3_network_response.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/7-4_custom_designs.html.md #### NOTE [Go to the end](tutorials_build/7-4_custom_designs.html.md#sphx-glr-download-tutorials-build-7-4-custom-designs-py) to download the full example code. # Custom Designs The high-level functions in [`osl_dynamics.stats`](autoapi/osl_dynamics/stats/index.html.md#module-osl_dynamics.stats) cover the common questions: a response against zero ([`evoked_response()`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response)), paired differences ([`paired_diff()`](autoapi/osl_dynamics/stats/paired_diff.html.md#osl_dynamics.stats.paired_diff)), two groups ([`group_diff()`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff)) and the effect of a continuous variable ([`regression()`](autoapi/osl_dynamics/stats/regression.html.md#osl_dynamics.stats.regression)). This tutorial shows how to go beyond them: 1. Testing the effect of a continuous variable such as age. 2. Specifying your own design matrix and contrasts. 3. Parametric tests, one-tailed tests and uncorrected permutation p-values. 4. Cluster-based tests with a custom adjacency (e.g. neighboring parcels). See the [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) for the background. ## Simulated data We simulate fractional occupancies for 40 subjects and 8 states, where the occupancy of state 3 increases with age, and record each subject’s age, sex and group (two patient groups and controls). ```Python import numpy as np np.random.seed(1) n_subjects, n_states = 40, 8 age = np.random.uniform(20, 80, size=n_subjects) sex = np.random.randint(0, 2, size=n_subjects) group = np.random.choice([1, 2, 3], size=n_subjects) # 1 = controls fo = np.random.normal(size=(n_subjects, n_states)) fo[:, 2] += 0.05 * (age - age.mean()) ``` ## Effect of a continuous variable [`stats.regression`](autoapi/osl_dynamics/stats/regression.html.md#osl_dynamics.stats.regression) fits a constant plus the variable of interest (and any nuisance covariates) and tests the slope with a row-shuffle permutation test. The cope is the change in the data per standard deviation of the variable, because continuous regressors are z-scored. ```Python from osl_dynamics import stats result = stats.regression(fo, age, name="Age", covariates={"sex": sex}, n_perm=1000) print(result) print("Slope per SD of age:", result.copes.round(3)) print("Significant states:", np.where(result.significant())[0] + 1) ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Your own design Any GLM can be specified with [`DesignConfig`](autoapi/osl_dynamics/stats/DesignConfig.html.md#osl_dynamics.stats.DesignConfig): a list of regressors (features) and a list of contrasts. Feature types are `'constant'`, `'categorical'` (0/1 indicators) and `'continuous'` (z-scored). Here we compare the two patient groups together against controls with the contrast `[-1, 0.5, 0.5, 0, 0]`, controlling for age and sex: ```Python design = stats.DesignConfig( features=[ {"name": "Controls", "values": group == 1, "feature_type": "categorical"}, {"name": "Patients A", "values": group == 2, "feature_type": "categorical"}, {"name": "Patients B", "values": group == 3, "feature_type": "categorical"}, {"name": "Age", "values": age, "feature_type": "continuous"}, {"name": "Sex", "values": sex, "feature_type": "continuous"}, ], contrasts=[ {"name": "Patients - Controls", "values": [-1, 0.5, 0.5, 0, 0]}, {"name": "Patients A - Patients B", "values": [0, 1, -1, 0, 0]}, ], ).create_design() fig, axes = design.plot() ``` A design is tested with one of the permutation classes. [`MaxStatPermutation`](autoapi/osl_dynamics/stats/MaxStatPermutation.html.md#osl_dynamics.stats.MaxStatPermutation) uses the maximum statistic over the targets; [`ClusterPermutation`](autoapi/osl_dynamics/stats/ClusterPermutation.html.md#osl_dynamics.stats.ClusterPermutation) the cluster-based test. `contrast_index` selects the contrast. The permutation type is chosen from the design (row shuffles for a categorical difference) unless `perm_type` is passed. ```Python perm = stats.MaxStatPermutation(design, contrast_index=0, n_perm=1000) result = perm.fit(fo) print(result) ``` ```none Permutations: 0%| | 0/1000 [00:00 For a differential contrast between categorical regressors, only the subjects in the groups with a non-zero weight are shuffled. Here that is everyone; when comparing two of three groups it is the subjects in those two. ## F-contrasts A t-contrast tests one difference in one direction. An **F-contrast** tests several t-contrasts jointly: is *any* of them non-zero? This is the GLM form of an ANOVA, and it is how [`stats.group_diff`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) handles three or more groups. Here we ask whether the three groups differ at all, controlling for age and sex. The two t-contrasts already in the design span every difference between the three groups, so the F-contrast can be built from them (any set of linearly independent rows spanning the same differences gives the same F-statistic): ```Python design.add_f_contrast( "Any group difference", contrasts=["Patients - Controls", "Patients A - Patients B"], ) result = stats.MaxStatPermutation(design, contrast_index=0, n_perm=1000, statistic="F").fit(fo) print(result) print("F-statistics:", np.round(result.stats, 2)) ``` ```none Permutations: 0%| | 0/1000 [00:00 `statistic="F"` makes `contrast_index` refer to the F-contrasts of the design. An F-test has no direction, so `tail` must be 0 and the permutation statistic is always F. `result.copes` holds the copes of each row of the F-contrast. An F-contrast can also be given directly as a matrix, one t-contrast per row, with `values=[[-1, 0.5, 0.5, 0, 0], [0, 1, -1, 0, 0]]` or in [`DesignConfig`](autoapi/osl_dynamics/stats/DesignConfig.html.md#osl_dynamics.stats.DesignConfig) with `f_contrasts=[{"name": ..., "values": ...}]`. The parametric version is `stats.GLM(design).fit(fo).ftest(0)`. ## Parametric tests [`GLM`](autoapi/osl_dynamics/stats/GLM.html.md#osl_dynamics.stats.GLM) fits the design and returns every regression coefficient, cope and varcope. Its [`test()`](autoapi/osl_dynamics/stats/GLMResult.html.md#osl_dynamics.stats.GLMResult.test) method gives parametric p-values from the t-distribution with an optional Bonferroni, Holm or FDR correction. Use this when the data are approximately Gaussian or you have too few subjects for permutations to be informative. ```Python glm_result = stats.GLM(design).fit(fo) print(glm_result.betas.shape, glm_result.copes.shape) # (features, states), (contrasts, states) result = glm_result.test(contrast_index=0, correction="fdr") print(result) ``` ```none (5, 8) (2, 8) TestResult(contrast='Patients - Controls', statistic='t', target_dims=(8,), correction='fdr', tail=0, parametric=True, n_significant (p<0.05)=0, min_pvalue=0.5855527856165929) ``` The high-level functions give the same with `correction="fdr"` (or `"bonferroni"`, `"holm"`, `None`). With `parametric=False` the uncorrected p-values come from per-target permutations instead and the correction is applied to them, which does not assume Gaussian data. This needs enough permutations for the smallest attainable p-value, $1 / (N + 1)$, to pass the corrected threshold: ```Python result = stats.regression(fo, age, correction="fdr", parametric=False, n_perm=5000) print(result) ``` ```none Permutations: 0%| | 0/5000 [00:00 ## One-tailed tests If the direction of the effect is fixed in advance, `tail=1` tests for a positive effect and `tail=-1` for a negative one. A one-tailed test is more powerful in that direction and blind to the other; it must be decided before looking at the data. ```Python result = stats.regression(fo, age, n_perm=1000, tail=1) print(result.pvalues.round(3)) ``` ```none Permutations: 0%| | 0/1000 [00:00 ## Clusters with a custom adjacency Cluster-based tests connect neighboring indices along `cluster_dims`. For dimensions that are not a lattice, such as parcels or sensors, pass an adjacency matrix: `adjacency={dim: matrix}` where `matrix[i, j]` is non-zero when targets `i` and `j` are neighbors. For sensors, MNE’s [`mne.channels.find_ch_adjacency()`](https://mne.tools/stable/generated/mne.channels.find_ch_adjacency.html#mne.channels.find_ch_adjacency) provides one; for parcels it can be built from the parcel centroids. Here we simulate power maps over time for 12 parcels arranged in a ring, so that parcel `i` is adjacent to `i - 1` and `i + 1`, with an effect in parcels 1-3 from sample 20 to 40: ```Python from scipy import sparse n_time, n_parcels = 60, 12 power = np.random.normal(size=(n_subjects, n_time, n_parcels)) power[:, 20:40, :3] += 0.8 ring = sparse.lil_matrix((n_parcels, n_parcels)) for i in range(n_parcels): ring[i, (i + 1) % n_parcels] = 1 ring[(i + 1) % n_parcels, i] = 1 result = stats.evoked_response( power, n_perm=1000, correction="cluster", cluster_dims=(0, 1), # time and parcels adjacency={1: ring}, # parcels are connected through the ring ) print(result) for mask, p in zip(result.clusters, result.cluster_pvalues): print( f"Samples {np.where(mask.any(axis=1))[0][[0, -1]]}, " f"parcels {np.where(mask.any(axis=0))[0] + 1}: p = {p:.3f}" ) ``` ```none Permutations: 0%| | 0/1000 [00:00 Without `adjacency`, every cluster dimension is a lattice, which is right for time and frequency. Dimensions not in `cluster_dims` (states, modes, unrelated parcels) are never spanned by a cluster, but the maximum is taken over them so the family-wise error rate still covers the whole array. ## Reproducibility Permutations use NumPy’s global random state. Call [`osl_dynamics.utils.set_random_seed()`](autoapi/osl_dynamics/utils/set_random_seed.html.md#osl_dynamics.utils.set_random_seed) at the top of a script to make them reproducible. Results can be saved and reloaded: ```default result.save("age_effect.pkl") result = stats.TestResult.load("age_effect.pkl") ``` **Total running time of the script:** (0 minutes 0.496 seconds) [`Download Jupyter notebook: 7-4_custom_designs.ipynb`](_downloads/b0b516297791a0ed087cacd4d4242e7e/7-4_custom_designs.ipynb) [`Download Python source code: 7-4_custom_designs.py`](_downloads/3fc3736861884b691e1384c4e893772d/7-4_custom_designs.py) [`Download zipped: 7-4_custom_designs.zip`](_downloads/31466abbc528fa63de6b833a48fdd8bc/7-4_custom_designs.zip) [Gallery generated by Sphinx-Gallery](https://sphinx-gallery.github.io) # tutorials_build/sg_execution_times.html.md # Computation times **02:54.406** total execution time for 30 files **from tutorials_build**: | Example | Time | Mem (MB) | |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------|------------| | [DyNeMo: Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md#sphx-glr-tutorials-build-5-2-dynemo-plotting-networks-py) (`5-2_dynemo_plotting_networks.py`) | 00:41.398 | 0 | | [DyNeMo: Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md#sphx-glr-tutorials-build-5-1-dynemo-regression-spectra-py) (`5-1_dynemo_regression_spectra.py`) | 00:36.878 | 0 | | [HMM: Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md#sphx-glr-tutorials-build-4-2-hmm-plotting-meg-networks-py) (`4-2_hmm_plotting_meg_networks.py`) | 00:35.251 | 0 | | [DyNeMo: Mixing Coefficients](tutorials_build/5-3_dynemo_mixing_coefs.html.md#sphx-glr-tutorials-build-5-3-dynemo-mixing-coefs-py) (`5-3_dynemo_mixing_coefs.py`) | 00:08.714 | 0 | | [DyNeMo: Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md#sphx-glr-tutorials-build-3-4-dynemo-selecting-a-run-py) (`3-4_dynemo_selecting_a_run.py`) | 00:07.033 | 0 | | [HMM: Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md#sphx-glr-tutorials-build-4-1-hmm-multitaper-spectra-py) (`4-1_hmm_multitaper_spectra.py`) | 00:06.716 | 0 | | [Static: Amplitude Envelope Correlation (AEC) Analysis](tutorials_build/2-3_static_aec_analysis.html.md#sphx-glr-tutorials-build-2-3-static-aec-analysis-py) (`2-3_static_aec_analysis.py`) | 00:06.546 | 0 | | [Time-Delay Embedding](tutorials_build/1-4_data_time_delay_embedding.html.md#sphx-glr-tutorials-build-1-4-data-time-delay-embedding-py) (`1-4_data_time_delay_embedding.py`) | 00:05.868 | 0 | | [Sliding Window Analysis](tutorials_build/3-1_sliding_window_analysis.html.md#sphx-glr-tutorials-build-3-1-sliding-window-analysis-py) (`3-1_sliding_window_analysis.py`) | 00:05.162 | 0 | | [Static: Power Analysis](tutorials_build/2-2_static_power_analysis.html.md#sphx-glr-tutorials-build-2-2-static-power-analysis-py) (`2-2_static_power_analysis.py`) | 00:04.379 | 0 | | [HMM: Training](tutorials_build/3-2_hmm_training.html.md#sphx-glr-tutorials-build-3-2-hmm-training-py) (`3-2_hmm_training.py`) | 00:03.272 | 0 | | [M/EEG: Sign Flipping](tutorials_build/0-2_sign_flipping.html.md#sphx-glr-tutorials-build-0-2-sign-flipping-py) (`0-2_sign_flipping.py`) | 00:03.030 | 0 | | [Network Response](tutorials_build/7-3_network_response.html.md#sphx-glr-tutorials-build-7-3-network-response-py) (`7-3_network_response.py`) | 00:02.587 | 0 | | [Static: Spectral Analysis](tutorials_build/2-1_static_spectra_analysis.html.md#sphx-glr-tutorials-build-2-1-static-spectra-analysis-py) (`2-1_static_spectra_analysis.py`) | 00:01.460 | 0 | | [Statistical Inference](tutorials_build/7-1_statistical_inference.html.md#sphx-glr-tutorials-build-7-1-statistical-inference-py) (`7-1_statistical_inference.py`) | 00:01.419 | 0 | | [DyNeMo: Training](tutorials_build/3-3_dynemo_training.html.md#sphx-glr-tutorials-build-3-3-dynemo-training-py) (`3-3_dynemo_training.py`) | 00:01.007 | 0 | | [Epoching: Network Response](tutorials_build/6-1_epoching_alpha.html.md#sphx-glr-tutorials-build-6-1-epoching-alpha-py) (`6-1_epoching_alpha.py`) | 00:00.957 | 0 | | [HMM: Summary Statistics](tutorials_build/4-3_hmm_summary_stats.html.md#sphx-glr-tutorials-build-4-3-hmm-summary-stats-py) (`4-3_hmm_summary_stats.py`) | 00:00.816 | 0 | | [Loading Data](tutorials_build/1-1_data_loading.html.md#sphx-glr-tutorials-build-1-1-data-loading-py) (`1-1_data_loading.py`) | 00:00.577 | 0 | | [Group Contrast](tutorials_build/7-2_group_contrast.html.md#sphx-glr-tutorials-build-7-2-group-contrast-py) (`7-2_group_contrast.py`) | 00:00.533 | 0 | | [Custom Designs](tutorials_build/7-4_custom_designs.html.md#sphx-glr-tutorials-build-7-4-custom-designs-py) (`7-4_custom_designs.py`) | 00:00.496 | 0 | | [Preparing M/EEG Data](tutorials_build/1-2_data_prepare_meg.html.md#sphx-glr-tutorials-build-1-2-data-prepare-meg-py) (`1-2_data_prepare_meg.py`) | 00:00.228 | 0 | | [Preparing fMRI Data](tutorials_build/1-3_data_prepare_fmri.html.md#sphx-glr-tutorials-build-1-3-data-prepare-fmri-py) (`1-3_data_prepare_fmri.py`) | 00:00.077 | 0 | | [MEG: Preprocessing, Source Reconstruction, Parcellation](tutorials_build/0-1_meg_preprocessing.html.md#sphx-glr-tutorials-build-0-1-meg-preprocessing-py) (`0-1_meg_preprocessing.py`) | 00:00.001 | 0 | | [HMM/DyNeMo: Get Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md#sphx-glr-tutorials-build-3-5-hmm-dynemo-get-inf-params-py) (`3-5_hmm_dynemo_get_inf_params.py`) | 00:00.000 | 0 | | [Cam-CAN: MEG Batch Processing](tutorials_build/0-3_meg_batch_processing.html.md#sphx-glr-tutorials-build-0-3-meg-batch-processing-py) (`0-3_meg_batch_processing.py`) | 00:00.000 | 0 | | [LEMON: EEG Batch Processing](tutorials_build/0-4_eeg_batch_processing.html.md#sphx-glr-tutorials-build-0-4-eeg-batch-processing-py) (`0-4_eeg_batch_processing.py`) | 00:00.000 | 0 | | [MNE Sample Data: Bilateral Beamformer](tutorials_build/0-5_mne_sample_data.html.md#sphx-glr-tutorials-build-0-5-mne-sample-data-py) (`0-5_mne_sample_data.py`) | 00:00.000 | 0 | | [HMM: fMRI Dual Estimation](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md#sphx-glr-tutorials-build-4-4-hmm-fmri-dual-estimation-py) (`4-4_hmm_fmri_dual_estimation.py`) | 00:00.000 | 0 | | [HMM: Plotting fMRI Networks](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md#sphx-glr-tutorials-build-4-5-hmm-plotting-fmri-networks-py) (`4-5_hmm_plotting_fmri_networks.py`) | 00:00.000 | 0 | # user_guide/index.html.md # User Guide The user guide describes the methods implemented in osl-dynamics: the M/EEG processing pipeline that produces parcel time courses, the generative models for dynamic brain networks, the spectral analysis of their states and modes, and the tools for statistical significance testing. New users should start with the [Getting Started](getting_started.html.md) guide and then work through the [tutorials](tutorials.html.md), which show the methods applied to real data, with links to example scripts and workshop materials. The [FAQ](faq.html.md) covers common questions about data preparation, model training and post-hoc analysis, and the [API reference](autoapi/index.html.md) documents every class and function. * [M/EEG Processing](user_guide/meeg.html.md) * [Software](user_guide/meeg.html.md#software) * [Pipeline](user_guide/meeg.html.md#pipeline) * [References](user_guide/meeg.html.md#references) * [Models](user_guide/models/index.html.md) * [Where the Models Fit in an Analysis](user_guide/models/index.html.md#where-the-models-fit-in-an-analysis) * [States and Modes](user_guide/models/index.html.md#states-and-modes) * [Choosing a Model](user_guide/models/index.html.md#choosing-a-model) * [Spectral Analysis](user_guide/spectra.html.md) * [Calculating spectra](user_guide/spectra.html.md#calculating-spectra) * [Regression spectra](user_guide/spectra.html.md#regression-spectra) * [Multitaper spectra](user_guide/spectra.html.md#multitaper-spectra) * [What to plot](user_guide/spectra.html.md#what-to-plot) * [Statistical Significance Testing](user_guide/stats.html.md) * [Which function?](user_guide/stats.html.md#which-function) * [Which correction?](user_guide/stats.html.md#which-correction) * [Which data?](user_guide/stats.html.md#which-data) # user_guide/meeg.html.md # M/EEG Processing The models in osl-dynamics are trained on **parcel time courses**: one time course per brain region, reconstructed from the sensors. [`osl_dynamics.meeg`](autoapi/osl_dynamics/meeg/index.html.md#module-osl_dynamics.meeg) takes raw recordings all the way there. This page describes the steps and the software behind them; the [MEG Preprocessing tutorial](tutorials_build/0-1_meg_preprocessing.html.md) runs them on one session, the [batch processing tutorials](tutorial_sections/meeg_processing.html.md) on many sessions in parallel. ## Software osl-dynamics combines the standard tools into one pipeline with consistent file handling and quality-control outputs: - [MNE-Python](https://mne.tools) reads the raw data and provides filtering, ICA, the BEM surfaces, the forward model and the core of the LCMV beamformer. Every stage works on MNE [`Raw`](https://mne.tools/stable/generated/mne.io.Raw.html#mne.io.Raw) or [`Epochs`](https://mne.tools/stable/generated/mne.Epochs.html#mne.Epochs) objects, so MNE functions can be mixed in anywhere. - [FSL](https://fsl.fmrib.ox.ac.uk) processes the structural MRI (BET for the surfaces, FLIRT and FNIRT for the MNI registration). Only the surface extraction step needs it, found through `FSLDIR`. - [mne-icalabel](https://mne.tools/mne-icalabel) labels ICA components (MEGNet for MEG, ICLabel for EEG). - Elekta/MEGIN MaxFilter (licensed, optional) for Elekta data, and the adaptive multipole model (AMM) for OPM data. - [osl-files](https://github.com/OHBA-analysis/osl-files) holds the parcellations, masks and templates, downloaded on first use. ## Pipeline Each step reads the files written by the steps before it and writes its own at paths held by a [`Session`](autoapi/osl_dynamics/meeg/Session.html.md#osl_dynamics.meeg.Session), so any step can be rerun on its own and every intermediate file inspected. | Step | What it does | Software | Functions | |-----------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Interference rejection (optional) | Signal space separation of Elekta data, or AMM for OPM data. | MaxFilter, osl-dynamics | [`run_maxfilter()`](autoapi/osl_dynamics/meeg/maxfilter/run_maxfilter.html.md#osl_dynamics.meeg.maxfilter.run_maxfilter), [`apply_amm()`](autoapi/osl_dynamics/meeg/amm/apply_amm.html.md#osl_dynamics.meeg.amm.apply_amm) | | Preprocessing | Filtering, resampling, bad segment and bad channel detection, and ICA rejection of cardiac and ocular artefacts. | MNE-Python, mne-icalabel | [`preproc`](autoapi/osl_dynamics/meeg/preproc/index.html.md#module-osl_dynamics.meeg.preproc) | | Surface extraction | Scalp, inner skull and brain surfaces from the T1 MRI, and the MRI registered to MNI space (affine, then nonlinear if it improves the fit). | FSL | [`extract_surfaces()`](autoapi/osl_dynamics/meeg/rhino/extract_surfaces.html.md#osl_dynamics.meeg.rhino.extract_surfaces) | | Coregistration | RHINO aligns the MEG head coordinates to the MRI: the fiducials first, then the digitized headshape points to the scalp surface. | osl-dynamics | [`coregister_head_and_mri()`](autoapi/osl_dynamics/meeg/rhino/coregister_head_and_mri.html.md#osl_dynamics.meeg.rhino.coregister_head_and_mri) | | Forward model | A single-layer (MEG) or triple-layer (EEG) BEM, with sources on an MNI grid so that every subject has sources at the same coordinates as the parcellation voxels. | MNE-Python | [`forward_model()`](autoapi/osl_dynamics/meeg/rhino/forward_model.html.md#osl_dynamics.meeg.rhino.forward_model) | | Source reconstruction | An LCMV beamformer: a spatial filter per source estimated from the data covariance, with the orientation of maximum power. Filters can be applied to any data from the session or to a single coordinate (virtual electrode). | MNE-Python, osl-dynamics | [`lcmv_beamformer()`](autoapi/osl_dynamics/meeg/source_recon/lcmv_beamformer.html.md#osl_dynamics.meeg.source_recon.lcmv_beamformer), [`apply_lcmv_beamformer()`](autoapi/osl_dynamics/meeg/source_recon/apply_lcmv_beamformer.html.md#osl_dynamics.meeg.source_recon.apply_lcmv_beamformer), [`virtual_electrodes()`](autoapi/osl_dynamics/meeg/source_recon/virtual_electrodes.html.md#osl_dynamics.meeg.source_recon.virtual_electrodes) | | Parcellation | One time course per parcel of an atlas: the first principal component of the parcel’s voxels, computed straight from the sensor data. See the [parcellations page](user_guide/parcellations/index.html.md). | osl-dynamics | [`parcellate_lcmv()`](autoapi/osl_dynamics/meeg/parcellation/parcellate_lcmv.html.md#osl_dynamics.meeg.parcellation.parcellate_lcmv), [`parcellate()`](autoapi/osl_dynamics/meeg/parcellation/parcellate.html.md#osl_dynamics.meeg.parcellation.parcellate) | | Orthogonalization (optional) | Symmetric orthogonalization [1](#id2) removes the zero-lag correlations between parcels caused by spatial leakage, needed for connectivity measures such as amplitude envelope correlation. | osl-dynamics | [`symmetric_orthogonalization()`](autoapi/osl_dynamics/meeg/parcellation/symmetric_orthogonalization.html.md#osl_dynamics.meeg.parcellation.symmetric_orthogonalization), or `orthogonalization="symmetric"` in [`parcellate_lcmv()`](autoapi/osl_dynamics/meeg/parcellation/parcellate_lcmv.html.md#osl_dynamics.meeg.parcellation.parcellate_lcmv) and [`parcellate()`](autoapi/osl_dynamics/meeg/parcellation/parcellate.html.md#osl_dynamics.meeg.parcellation.parcellate) | | Sign flipping | The sign of a beamformed parcel time course is arbitrary and differs between sessions. Each session’s parcels are flipped to match a template covariance, so that sessions can be pooled for group-level models. | osl-dynamics | [`Data.align_channel_signs`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data.align_channel_signs) ([tutorial](tutorials_build/0-2_sign_flipping.html.md)) | | Quality control | PSDs and power maps of the parcel time courses, and an HTML report with one row per session next to its QC plots. | osl-dynamics | [`save_qc_plots()`](autoapi/osl_dynamics/meeg/parcellation/save_qc_plots.html.md#osl_dynamics.meeg.parcellation.save_qc_plots), [`generate_report()`](autoapi/osl_dynamics/meeg/report/generate_report.html.md#osl_dynamics.meeg.report.generate_report) | The output is a FIF file with one channel per parcel, which [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) loads directly. [`run()`](autoapi/osl_dynamics/meeg/parallel/run.html.md#osl_dynamics.meeg.parallel.run) runs any step over many sessions in parallel. ## References * **[1]** Colclough, G. L. et al. (2015). A symmetric multivariate leakage correction for MEG connectomes. NeuroImage, 117, 439-448. # user_guide/models/dynemo.html.md # Dynamic Network Modes (DyNeMo) DyNeMo [2] relaxes two assumptions of the [HMM](user_guide/models/hmm.html.md): - **Mutually exclusive states**: DyNeMo describes the data with a linear mixture of **modes**, so several networks can be active at the same time. - **The Markovian assumption**: DyNeMo uses a recurrent neural network (RNN) as its temporal model, which can capture long-range temporal dependencies. DyNeMo has been used to study resting-state [2] and task [6] MEG data. It can find task responses that the HMM misses, because a mixture can describe networks that overlap in time [6]. | Time course | Modes: the mixing coefficients of each network at each time point | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Observation model | Multivariate normal, with a mean and covariance that are linear mixtures of the mode means and covariances | | Temporal model | Recurrent neural network (LSTM [4] by default) | | Training | Amortized variational inference, a GPU helps | | API | [`Config`](autoapi/osl_dynamics/models/dynemo/Config.html.md#osl_dynamics.models.dynemo.Config), [`Model`](autoapi/osl_dynamics/models/dynemo/Model.html.md#osl_dynamics.models.dynemo.Model) | | Tutorials | [DyNeMo Training](tutorials_build/3-3_dynemo_training.html.md), [Selecting a Run](tutorials_build/3-4_dynemo_selecting_a_run.html.md), [Getting the Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md), [DyNeMo post-hoc analysis](tutorial_sections/dynemo_post_hoc.html.md) | | Examples | [Simulation](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/dynemo_hmm-mvn.py), [Soft mixing](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/dynemo_soft-mixing.py), [Long-range dependencies](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/dynemo_long-range-dep.py), [MEG (TDE-DyNeMo, rest)](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_analysis/tde-dynemo_rest) | ## Generative Model The generative model (joint probability distribution) is $$ p(x_{1:T}, \theta_{1:T}) = p(\theta_1) p(x_1 | \theta_1) \prod_{t=2}^T p(\theta_t | \theta_{1:t-1}) p(x_t | \theta_t), $$ where $x_{1:T}$ is the observed data ($x_1, x_2, ..., x_T$) and $\theta_{1:T}$ is a sequence of latent variables called **logits** ($\theta_1, \theta_2, ..., \theta_T$). The **observation model** is a multivariate normal distribution, $$ p(x_t | \theta_t) = \mathcal{N}(m_t, C_t), $$ whose mean and covariance are **linear mixtures** of the mode means, $\mu_j$, and covariances, $D_j$: $$ m_t = \sum_j \alpha_{jt} \mu_j, \quad C_t = \sum_j \alpha_{jt} D_j. $$ The **mixing coefficients**, $\alpha_{jt}$, are positive and sum to one at each time point because they are a softmax transform of the logits: $$ \alpha_{jt} = \{ \mathrm{softmax}(\theta_t / \tau) \}_j, $$ where $\tau$ is a temperature (`initial_alpha_temperature`, which can also be learned with `learn_alpha_temperature`). A low temperature makes the mixing coefficients closer to a single active mode. The **temporal model** for the logits is a normal distribution, $$ p(\theta_t | \theta_{1:t-1}) = \mathcal{N}(m_{\theta_t}, \mathrm{diag}(\sigma^2_{\theta_t})), $$ whose mean and standard deviation are predicted by a recurrent neural network (the **model RNN**) from all of the previous logits, $\theta_{1:t-1}$, so each logit can depend on the whole history, not just the previous time point. ![image](user_guide/models/images/dynemo-graphical-model.svg) To generate data from DyNeMo, we sample a sequence of logits with the model RNN, transform them into mixing coefficients and sample each data point with a covariance that mixes the mode covariances: ![image](user_guide/models/images/dynemo-generative-process.svg) As with the [HMM](user_guide/models/hmm.html.md), we train on time-delay embedded (TDE) data to find spectrally distinct modes and only learn the covariances (`learn_means=False`). See the [time-delay embedding tutorial](tutorials_build/1-4_data_time_delay_embedding.html.md). ## Training DyNeMo in osl-dynamics [1] infers a posterior distribution for the logits, $q(\theta_t)$, and learns point estimates for the mode means and covariances. It uses **amortized variational inference** [3]: instead of optimizing a separate posterior for each time point, an **inference RNN** learns to predict the posterior from the data. The inference RNN is bidirectional, so the posterior at each time point uses the data before and after it in the sequence, $x_{1:L}$, where $L$ is `sequence_length`: $$ q(\theta_t | x_{1:L}) = \mathcal{N}(m^{\mathrm{inf}}_t, \mathrm{diag}(\sigma^{\mathrm{inf}}_t)^2). $$ The inference RNN, model RNN and observation model are trained together by minimizing the **variational free energy**, $$ \mathcal{F} = -\sum_t \mathbb{E}_{q(\theta_t)} \left[ \log p(x_t | \theta_t) \right] + \sum_t \mathrm{KL} \left[ q(\theta_t | x_{1:L}) \,\|\, p(\theta_t | \theta_{1:t-1}) \right], $$ where the first term is the negative log-likelihood of the data and the second is the Kullback-Leibler (KL) divergence between the posterior and the prior from the model RNN. The expectation is estimated with samples of the logits from the posterior, using the reparameterization trick [3] so that the gradients can pass through the sampling. The parameters take gradient steps (with the Adam optimizer) on batches of sequences. A derivation of the cost function is [`here`](_downloads/337283ed83d45ebf39c072dfdcec53bc/dynemo-cost-function.pdf). Both RNNs only see one sequence at a time, so DyNeMo can’t learn temporal dependencies longer than `sequence_length`. ![image](user_guide/models/images/dynemo-training.svg) With **KL annealing** (`kl_annealing=True`), the KL divergence is multiplied by a factor that increases from 0 to 1 over the first `n_kl_annealing_epochs` epochs. The learning rate is constant during KL annealing and decays afterwards (`learning_rate_decay`). ### Initialization and Hyperparameters We recommend initializing DyNeMo with [`random_subset_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.random_subset_initialization), which trains a few short runs on random subsets of the data and keeps the best. For example: ```default from osl_dynamics.models.dynemo import Config, Model config = Config( n_modes=8, n_channels=data.n_channels, sequence_length=200, inference_n_units=64, inference_normalization="layer", model_n_units=64, model_normalization="layer", learn_means=False, learn_covariances=True, kl_annealing=True, kl_annealing_curve="tanh", kl_annealing_sharpness=10, n_kl_annealing_epochs=10, batch_size=128, learning_rate=0.01, n_epochs=20, ) model = Model(config) model.random_subset_initialization(data, n_init=5, n_epochs=2, take=0.25) model.fit(data) alpha = model.get_alpha(data) ``` where `data` is a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object. [`nfindr_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.nfindr_initialization) is an alternative that starts the mode covariances from the corners of the simplex the windowed data covariances lie in (N-FINDR). Alternatively, [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train) runs the initialization set in the config (`init_method`, `n_init`, `n_init_epochs` and `init_take`) and then `fit`. We recommend training several runs and keeping the one with the lowest free energy ([`model.free_energy`](autoapi/osl_dynamics/models/base/VariationalModelBase.html.md#osl_dynamics.models.base.VariationalModelBase.free_energy), or `best_of` in `model.train`), or the most typical run ([`select_run()`](autoapi/osl_dynamics/inference/modes/select_run.html.md#osl_dynamics.inference.modes.select_run)). See the [Selecting a Run tutorial](tutorials_build/3-4_dynemo_selecting_a_run.html.md). The main hyperparameters are the number of modes (`n_modes`), `sequence_length`, the number of units in the RNNs (`inference_n_units` and `model_n_units`), `n_kl_annealing_epochs`, `batch_size`, `learning_rate` and `n_epochs`. The [FAQ](faq.html.md) discusses how to choose them and what to do if the loss increases during training. ### The Mixing Coefficients After training, [`model.get_alpha`](autoapi/osl_dynamics/models/base/VariationalModelBase.html.md#osl_dynamics.models.base.VariationalModelBase.get_alpha) returns the mixing coefficients for each session, calculated from the mean of the posterior for the logits. Passing `remove_edge_effects=True` uses overlapping sequences to remove the edge effects from splitting the data into sequences. The mode means and covariances are returned by [`get_means()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_means) and [`get_covariances()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_covariances). See the [Getting the Inferred Parameters tutorial](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md). ## Post-hoc Analysis Post-hoc analysis interprets the inferred mixing coefficients: statistics that summarize how each mode is activated, and the spectral properties (power and coherence) of each mode. ### Re-weighting the Mixing Coefficients The mixing coefficients do not account for the size of each mode covariance: a mode with a large covariance contributes more to the data than its mixing coefficient suggests. For the summary statistics, we re-weight the mixing coefficients by the trace of each mode covariance and normalize them to sum to one again with [`reweight_alphas()`](autoapi/osl_dynamics/inference/modes/reweight_alphas.html.md#osl_dynamics.inference.modes.reweight_alphas). The re-weighted mixing coefficients describe how much each mode contributes to the total power at each time point. The spectral analysis uses the mixing coefficients without re-weighting. ### Summary Statistics The (re-weighted) mixing coefficients can be summarized directly, e.g. with their mean, standard deviation or kurtosis (how bursty a mode is) for each session. Alternatively, each mode’s time course can be binarized into ‘on’ and ‘off’ periods by fitting a two-component Gaussian mixture model ([`gmm_time_courses()`](autoapi/osl_dynamics/inference/modes/gmm_time_courses.html.md#osl_dynamics.inference.modes.gmm_time_courses)), after which the [HMM summary statistics](user_guide/models/hmm.html.md) (fractional occupancy, lifetimes, intervals and switching rates) can be calculated. See the [DyNeMo Mixing Coefficients Analysis tutorial](tutorials_build/5-3_dynemo_mixing_coefs.html.md). The statistics can be compared between groups or conditions with the [statistical significance testing](user_guide/stats.html.md) tools. ### Spectral Analysis With TDE data the modes are spectrally distinct. We calculate the spectral properties of each mode with **regression spectra**, a GLM-spectrum [5]: a spectrogram of the data before time-delay embedding (and PCA) is fitted as a mixture of the mode spectra weighted by the mixing coefficients ([`regression_spectra()`](autoapi/osl_dynamics/analysis/spectral/regression_spectra.html.md#osl_dynamics.analysis.spectral.regression_spectra)). The intercept is the static (time-averaged) PSD and the regression coefficients are the change in the PSD from the static PSD for a one standard deviation increase in a mode’s mixing coefficient. Power maps and coherence networks are calculated from the coefficients. See [Spectral Analysis](user_guide/spectra.html.md) for the method and how to interpret and plot the outputs, and the [DyNeMo Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md) and [DyNeMo Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md) tutorials. For fMRI data, the mode means and covariances of each subject can be re-estimated with **dual estimation** ([`dual_estimation()`](autoapi/osl_dynamics/models/dynemo/Model.html.md#osl_dynamics.models.dynemo.Model.dual_estimation)). ### Task Data With task data, the mixing coefficients can be epoched around events to show how each mode responds to a task [6]. See the [Epoching Alphas tutorial](tutorials_build/6-1_epoching_alpha.html.md) and the [Network Response tutorial](tutorials_build/7-3_network_response.html.md) for statistical testing. ## Related Models - [M-DyNeMo](user_guide/models/mdynemo.html.md) has separate mixing coefficients for power and functional connectivity. - [DyNeStE](user_guide/models/dyneste.html.md) uses DyNeMo’s RNN temporal model with mutually exclusive states. - [`DIVE`](autoapi/osl_dynamics/models/dive/index.html.md#module-osl_dynamics.models.dive) adds session embeddings to model inter-session variability, as [HIVE](user_guide/models/hive.html.md) does for the HMM. - [`SC-DyNeMo`](autoapi/osl_dynamics/models/scdynemo/index.html.md#module-osl_dynamics.models.scdynemo) is a single-channel version of DyNeMo. ## References 1. C Gohil, et al., osl-dynamics, a toolbox for modeling fast dynamic brain activity. [eLife, 2024](https://elifesciences.org/articles/91949). 2. C Gohil, et al., Mixtures of large-scale dynamic functional brain network modes. [NeuroImage, 2022](https://doi.org/10.1016/j.neuroimage.2022.119595). 3. D P Kingma, M Welling, Auto-encoding variational Bayes. [arXiv:1312.6114, 2013](https://arxiv.org/abs/1312.6114). 4. S Hochreiter, J Schmidhuber, Long short-term memory. [Neural Computation, 1997](https://doi.org/10.1162/neco.1997.9.8.1735). 5. A J Quinn, et al., The GLM-spectrum: A multilevel framework for spectrum analysis with covariate and confound modelling. [Imaging Neuroscience, 2024](https://doi.org/10.1162/imag_a_00082). 6. C Gohil, et al., Dynamic network analysis of electrophysiological task data. [Imaging Neuroscience, 2024](https://doi.org/10.1162/imag_a_00226). # user_guide/models/dyneste.html.md # Dynamic Network States (DyNeStE) DyNeStE [2] combines the **mutually exclusive states** of the [HMM](user_guide/models/hmm.html.md) with the **recurrent neural network (RNN) temporal model** of [DyNeMo](user_guide/models/dynemo.html.md), which can capture long-range temporal dependencies. On resting-state MEG data, DyNeStE captures long-range temporal structure better than the HMM [2]. | Time course | States: one state is active at each time point | |-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Observation model | Multivariate normal | | Temporal model | Recurrent neural network (LSTM by default) | | Training | Amortized variational inference with the Gumbel-Softmax distribution, a GPU helps | | API | [`Config`](autoapi/osl_dynamics/models/dyneste/Config.html.md#osl_dynamics.models.dyneste.Config), [`Model`](autoapi/osl_dynamics/models/dyneste/Model.html.md#osl_dynamics.models.dyneste.Model) | | Examples | [Simulation](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/dyneste_hmm-mvn.py), [Long-range dependencies](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/dyneste_long-range-dep.py) | ## Generative Model The generative model (joint probability distribution) is $$ p(x_{1:T}, s_{1:T}) = p(s_1) p(x_1 | s_1) \prod_{t=2}^T p(s_t | s_{1:t-1}) p(x_t | s_t), $$ where $x_{1:T}$ is the observed data and $s_{1:T}$ is the sequence of hidden states. The **observation model** is the same as the [HMM](user_guide/models/hmm.html.md)’s, a multivariate normal distribution with a mean, $m_k$, and covariance, $C_k$, for each state: $$ p(x_t | s_t = k) = \mathcal{N}(m_k, C_k). $$ The **temporal model** differs from the HMM’s: the probability of the next state depends on the **whole history** of states, not just the previous state. A recurrent neural network (the **model RNN**) predicts the logits of a categorical distribution from the previous states: $$ p(s_t | s_{1:t-1}) = \mathrm{Cat}(\mathrm{softmax}(\theta^{\mathrm{mod}}_t)). $$ ![image](user_guide/models/images/dyneste-graphical-model.svg) ## Training DyNeStE in osl-dynamics [1] uses **amortized variational inference**, as [DyNeMo](user_guide/models/dynemo.html.md) does. A bidirectional **inference RNN** predicts the posterior for the state at each time point from the data in the sequence, $x_{1:L}$: $$ q(s_t | x_{1:L}) = \mathrm{Cat}(\mathrm{softmax}(\theta^{\mathrm{inf}}_t)). $$ The cost function is the **variational free energy**, the sum of: - the negative **log-likelihood** of the data, $-\sum_t \sum_k q(s_t = k) \log \mathcal{N}(x_t | m_k, C_k)$, which uses the state probabilities directly; - the **KL divergence** between the posterior, $q(s_t | x_{1:L})$, and the prior from the model RNN, $p(s_t | s_{1:t-1})$. The model RNN takes samples of the state sequence from the **Gumbel-Softmax** (or Concrete) distribution [3, 4], a continuous relaxation of the categorical distribution with differentiable samples. Its temperature, $\tau$, controls how close the samples are to one-hot vectors. ![image](user_guide/models/images/dyneste-training.svg)![image](user_guide/models/images/dyneste-gumbel-softmax.svg) The temperature can be annealed during training (`gumbel_annealing=True`), from `initial_gumbel_temperature` to `final_gumbel_temperature` over `n_gumbel_annealing_epochs` epochs. As with DyNeMo, **KL annealing** (`kl_annealing=True`) can be used. ### Initialization and Hyperparameters DyNeStE is initialized with [`random_state_time_course_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.random_state_time_course_initialization) by default (`init_method`). [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train) runs the initialization and then `fit`. The main hyperparameters are the number of states (`n_states`), `sequence_length`, the number of units in the RNNs (`inference_n_units` and `model_n_units`), the Gumbel-Softmax temperatures, `n_kl_annealing_epochs`, `batch_size`, `learning_rate` and `n_epochs`. For example: ```default from osl_dynamics.models.dyneste import Config, Model config = Config( n_states=8, n_channels=data.n_channels, sequence_length=200, inference_n_units=64, inference_normalization="layer", model_n_units=64, model_normalization="layer", learn_means=False, learn_covariances=True, kl_annealing=True, kl_annealing_curve="tanh", kl_annealing_sharpness=10, n_kl_annealing_epochs=20, gumbel_annealing=True, gumbel_annealing_curve="exp", initial_gumbel_temperature=1.0, final_gumbel_temperature=0.06, gumbel_annealing_slope=0.04, n_gumbel_annealing_epochs=40, batch_size=32, learning_rate=0.005, n_epochs=40, ) model = Model(config) model.train(data) alpha = model.get_alpha(data) ``` where `data` is a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object. ## Post-hoc Analysis [`model.get_alpha`](autoapi/osl_dynamics/models/base/VariationalModelBase.html.md#osl_dynamics.models.base.VariationalModelBase.get_alpha) returns the state probabilities, $q(s_t)$. Because DyNeStE infers mutually exclusive states, the post-hoc analysis is the same as for the [HMM](user_guide/models/hmm.html.md): - **Summary statistics** of the state time course, the maximum a posteriori (MAP) estimate of the state at each time point (from [`argmax_time_courses()`](autoapi/osl_dynamics/inference/modes/argmax_time_courses.html.md#osl_dynamics.inference.modes.argmax_time_courses)): fractional occupancy, mean lifetime, mean interval and switching rate. See the [HMM Summary Statistics tutorial](tutorials_build/4-3_hmm_summary_stats.html.md). - **Spectral analysis** with the multitaper ([`multitaper_spectra()`](autoapi/osl_dynamics/analysis/spectral/multitaper_spectra.html.md#osl_dynamics.analysis.spectral.multitaper_spectra)), and power maps and coherence networks from the spectra. See [Spectral Analysis](user_guide/spectra.html.md) and the [HMM Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md) and [HMM Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md) tutorials. The summary statistics can be compared between groups or conditions with the [statistical significance testing](user_guide/stats.html.md) tools. [`sample_alpha()`](autoapi/osl_dynamics/models/dyneste/Model.html.md#osl_dynamics.models.dyneste.Model.sample_alpha) samples state time courses from the trained model RNN, which can be used to check the long-range temporal structure the model has learned, e.g. the distribution of state lifetimes. ## References 1. C Gohil, et al., osl-dynamics, a toolbox for modeling fast dynamic brain activity. [eLife, 2024](https://elifesciences.org/articles/91949). 2. S Cho, R Huang, C Gohil, O Parker Jones, M W Woolrich, Modelling discrete states and long-term dynamics in functional brain networks. [Imaging Neuroscience, 2026](https://doi.org/10.1162/IMAG.a.1237). 3. E Jang, S Gu, B Poole, Categorical reparameterization with Gumbel-Softmax. [arXiv:1611.01144, 2016](https://arxiv.org/abs/1611.01144). 4. C J Maddison, et al., The Concrete distribution: a continuous relaxation of discrete random variables. [arXiv:1611.00712, 2016](https://arxiv.org/abs/1611.00712). # user_guide/models/hive.html.md # HMM with Integrated Variability Estimation (HIVE) HIVE [2] extends the [HMM](user_guide/models/hmm.html.md) to model **variability between sessions** while inferring dynamic networks across a group. The HMM gives every session the same state means and covariances, although sessions from different subjects, scanners or sites differ systematically. HIVE learns an **embedding vector** for each session, a “fingerprint”, that adjusts the group-level state means and covariances to give session-specific ones. Sessions with similar networks have similar embeddings, so the embeddings capture sources of variation across the population (e.g. demographics, scanner or site) [2]. | Time course | States: one state is active at each time point | |-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Observation model | Multivariate normal, with session-specific state means and covariances | | Temporal model | Markovian (transition probability matrix), shared by all sessions | | Training | As the HMM, no GPU needed | | API | [`Config`](autoapi/osl_dynamics/models/hive/Config.html.md#osl_dynamics.models.hive.Config), [`Model`](autoapi/osl_dynamics/models/hive/Model.html.md#osl_dynamics.models.hive.Model) | | Examples | [Simulation](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/hive_hmm-mvn.py) | ## Generative Model The temporal model is the same as the [HMM](user_guide/models/hmm.html.md)’s. The observation model for session $n$ uses session-specific state means and covariances: $$ p(x_t | s_t = k, n) = \mathcal{N}(m^{(n)}_k, C^{(n)}_k). $$ The session-specific parameters are the **group-level** parameters, $m_k$ and $C_k$, shared by all sessions, plus a **deviation** for each session: - Each session has an **embedding vector**, $e_n$ (`embeddings_dim` dimensions). - Each state has a **spatial embedding** (`spatial_embeddings_dim` dimensions), calculated from its group-level mean or covariance. - A multi-layer perceptron (MLP) maps the session and spatial embeddings to the shape of the deviation, which is scaled by a magnitude for each session and state. - The mean deviation is added to the group mean. The covariance deviation is added to the Cholesky factor of the group covariance, which keeps the session covariances positive definite. ![image](user_guide/models/images/hive-graphical-model.svg)![image](user_guide/models/images/hive-embeddings.svg) By default each session has its own embedding. Known information about the sessions can be passed with `session_labels` (a list of [`SessionLabels`](autoapi/osl_dynamics/data/SessionLabels.html.md#osl_dynamics.data.SessionLabels)), e.g. a subject ID so that sessions from the same subject share an embedding, or a categorical (e.g. site) or continuous (e.g. age) variable. The embedding of a session is the sum of the embeddings for each of its labels. ## Training HIVE in osl-dynamics [1] is trained as the [HMM](user_guide/models/hmm.html.md) is: the Baum-Welch algorithm calculates the posterior for the hidden states for each batch, the transition probability matrix is updated with a decaying exponential moving average, and the other parameters (group means and covariances, embeddings and the MLP) take gradient steps. The deviation magnitudes have a posterior distribution (a gamma distribution for each session and state) with a KL divergence term in the cost function, which regularizes the deviations. KL annealing (`kl_annealing=True`) can be used. The default initialization is [`random_state_time_course_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.random_state_time_course_initialization) (`init_method`), and [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train) runs it before `fit`. The data need a session ID label, and [`set_regularizers()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.set_regularizers) must be called before training. For example: ```default import numpy as np from osl_dynamics.models.hive import Config, Model data.add_session_labels("session_id", np.arange(data.n_sessions), "categorical") config = Config( n_states=8, n_channels=data.n_channels, sequence_length=200, n_sessions=data.n_sessions, embeddings_dim=5, spatial_embeddings_dim=2, deviation_n_layers=5, deviation_n_units=32, deviation_activation="tanh", deviation_normalization="layer", deviation_regularizer="l1", deviation_regularizer_factor=0.01, learn_means=False, learn_covariances=True, kl_annealing=True, kl_annealing_curve="tanh", kl_annealing_sharpness=10, n_kl_annealing_epochs=20, batch_size=32, learning_rate=0.001, n_epochs=40, ) model = Model(config) model.set_regularizers(data) model.set_deviation_parameters(data) model.train(data) ``` where `data` is a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object with one array per session. ## Post-hoc Analysis The post-hoc analyses of the [HMM](user_guide/models/hmm.html.md) apply to HIVE’s state time courses: summary statistics and multitaper spectra (see [Spectral Analysis](user_guide/spectra.html.md)). In addition: - [`get_session_embeddings()`](autoapi/osl_dynamics/models/base/SessionMVNMixin.html.md#osl_dynamics.models.base.SessionMVNMixin.get_session_embeddings) returns the embedding of each session, and [`get_label_embeddings()`](autoapi/osl_dynamics/models/base/SessionMVNMixin.html.md#osl_dynamics.models.base.SessionMVNMixin.get_label_embeddings) the embedding of each category of each session label. The embeddings can be plotted (e.g. after PCA) to see how sessions cluster, or related to variables such as age, sex or scanner. - [`get_means()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_means) and [`get_covariances()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_covariances) return the group-level state means and covariances, and [`get_session_means()`](autoapi/osl_dynamics/models/base/SessionMVNMixin.html.md#osl_dynamics.models.base.SessionMVNMixin.get_session_means) and [`get_session_covariances()`](autoapi/osl_dynamics/models/base/SessionMVNMixin.html.md#osl_dynamics.models.base.SessionMVNMixin.get_session_covariances) the session-specific ones, which show how each session differs from the group. ## Related Models [`DIVE`](autoapi/osl_dynamics/models/dive/index.html.md#module-osl_dynamics.models.dive) adds session embeddings to [DyNeMo](user_guide/models/dynemo.html.md) in the same way. ## References 1. C Gohil, et al., osl-dynamics, a toolbox for modeling fast dynamic brain activity. [eLife, 2024](https://elifesciences.org/articles/91949). 2. R Huang, C Gohil, M W Woolrich, Modelling variability in functional brain networks using embeddings. [Imaging Neuroscience, 2026](https://doi.org/10.1162/IMAG.a.1188). # user_guide/models/hmm.html.md # Hidden Markov Model (HMM) The HMM describes a time series as a sequence of visits to a small number of **hidden states**. Each state has its own **observation model**, which describes the data while the state is active, and the order of the states is governed by a **transition probability matrix**. The HMM has been used to study fast transient networks in MEG [4, 9, 11], fMRI [10] and task data [12, 13, 16], and how they change with disease and age [14, 15, 17]. | Time course | States: one state is active at each time point | |-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Observation model | Multivariate normal | | Temporal model | Markovian (transition probability matrix) | | Training | Baum-Welch algorithm with stochastic updates, no GPU needed | | API | [`Config`](autoapi/osl_dynamics/models/hmm/Config.html.md#osl_dynamics.models.hmm.Config), [`Model`](autoapi/osl_dynamics/models/hmm/Model.html.md#osl_dynamics.models.hmm.Model) | | Tutorials | [HMM Training](tutorials_build/3-2_hmm_training.html.md), [Getting the Inferred Parameters](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md), [HMM post-hoc analysis](tutorial_sections/hmm_post_hoc.html.md) | | Examples | [Simulation](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/hmm_hmm-mvn.py), [Simulation (oscillatory, TDE-HMM)](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/hmm_oscillatory-mvn.py), [MEG (TDE-HMM, rest)](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_analysis/tde-hmm_rest), [MEG (TDE-HMM, task)](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_analysis/tde-hmm_task), [MEG (AE-HMM, rest)](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/meg_analysis/ae-hmm_rest), [fMRI](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/fmri) | ## Generative Model A generative model is the joint probability distribution of the observed data and the latent variables. For the HMM it is $$ p(x_{1:T}, s_{1:T}) = p(s_1) p(x_1 | s_1) \prod^T_{t=2} p(s_t | s_{t-1}) p(x_t | s_t), $$ where $x_{1:T}$ is the observed data ($x_1, x_2, ..., x_T$) and $s_{1:T}$ is the sequence of hidden states ($s_1, s_2, ..., s_T$), each of which takes one of $K$ values [2, 3]. The **observation model** is a multivariate normal distribution with a mean, $m_k$, and covariance, $C_k$, for each state: $$ p(x_t | s_t = k) = \mathcal{N}(m_k, C_k). $$ The **temporal model** depends only on the previous state (the **Markovian assumption**), so it is described by a $K \times K$ transition probability matrix, $A$, and initial state probabilities, $\pi$: $$ A_{ij} = p(s_t = j | s_{t-1} = i), \quad \pi_k = p(s_1 = k). $$ Each row of $A$ sums to one. The diagonal elements are the probabilities of staying in a state, so they control how long the states last. ![image](user_guide/models/images/hmm-graphical-model.svg) To generate data from an HMM, we sample a state sequence using the transition probability matrix and then sample each data point from the observation model of the active state: ![image](user_guide/models/images/hmm-generative-process.svg) What the states describe depends on how the data are prepared. With **amplitude envelope** (AE) data, the states differ in their means (`learn_means=True`). With **time-delay embedded** (TDE) data, the covariance of each state contains the power spectrum of each region and the coherence between regions, so the states are spectrally distinct networks and we only learn the covariances (`learn_means=False`). See the [time-delay embedding tutorial](tutorials_build/1-4_data_time_delay_embedding.html.md) and the [FAQ](faq.html.md) for more on AE vs TDE data. ## Training Training (or fitting) the model means inferring the hidden states and the model parameters ($\pi$, $A$, $m_k$, $C_k$) from data. osl-dynamics [1] infers a posterior distribution for the hidden states, $q(s_t)$, and learns point estimates for the parameters. The data are split into sequences of `sequence_length` samples, which are grouped into batches of `batch_size` sequences. For each batch [5]: 1. **E-step**: the Baum-Welch (forward-backward) algorithm [2, 3] calculates the posterior for the hidden states, $q(s_t)$, and for pairs of consecutive states, $q(s_t, s_{t+1})$, given the current parameters. 2. **Observation model update**: the state means and covariances take a gradient step (with the Adam optimizer and `learning_rate`) to minimize the negative log-likelihood of the data, weighted by the posterior, $$ -\sum_t \sum_k q(s_t = k) \log \mathcal{N}(x_t | m_k, C_k). $$ 3. **Markov chain update**: the transition probability matrix and initial state probabilities move towards the estimates from the posterior of this batch, $\hat{A}$ and $\hat{\pi}$: $$ A \leftarrow (1 - \rho) A + \rho \hat{A}, \quad \pi \leftarrow (1 - \rho) \pi + \rho \hat{\pi}. $$ The step size decreases during training: after epoch $e$ (counting from zero), $\rho = (1 + \delta + 100 e / E)^{-\kappa}$, where $E$ is `n_epochs`, $\delta$ is `trans_prob_update_delay` and $\kappa$ is `trans_prob_update_forget`. ![image](user_guide/models/images/hmm-training.svg) The cost function is the **variational free energy**, $$ \mathcal{F} = \mathbb{E}_{q(s_{1:T})} \left[ \log q(s_{1:T}) - \log p(x_{1:T}, s_{1:T}) \right], $$ which [`model.free_energy`](autoapi/osl_dynamics/models/base/MarkovModelBase.html.md#osl_dynamics.models.base.MarkovModelBase.free_energy) calculates. A lower free energy is a better fit, so it can be used to compare runs. A derivation of the cost function is [`here`](_downloads/0d2a42b05b643ec3a7a5590d2f3e33cc/hmm-cost-function.pdf) (note, it uses different symbols to this page). ### Initialization and Hyperparameters We recommend initializing the HMM with [`random_state_time_course_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.random_state_time_course_initialization), which trains a few short runs from random state time courses and keeps the best. For example: ```default from osl_dynamics.models.hmm import Config, Model config = Config( n_states=8, n_channels=data.n_channels, sequence_length=200, learn_means=False, learn_covariances=True, batch_size=256, learning_rate=0.01, n_epochs=20, ) model = Model(config) model.random_state_time_course_initialization(data, n_init=3, n_epochs=1) model.fit(data) gamma = model.get_gamma(data) ``` where `data` is a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object. Alternatively, [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train) runs the initialization set in the config (`init_method`, `n_init`, `n_init_epochs` and `init_take`) and then `fit`. We also recommend training several runs and keeping the one with the lowest free energy (`best_of` in [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train)), or the most typical run ([`select_run()`](autoapi/osl_dynamics/inference/modes/select_run.html.md#osl_dynamics.inference.modes.select_run)). The main hyperparameters are the number of states (`n_states`, 6-14 states is typical), `sequence_length`, `batch_size`, `learning_rate` and `n_epochs`. The [FAQ](faq.html.md) discusses how to choose them. ### The State Time Course After training, [`model.get_gamma`](autoapi/osl_dynamics/models/base/MarkovModelBase.html.md#osl_dynamics.models.base.MarkovModelBase.get_gamma) returns the state probability time course (the marginal posterior), $\gamma_{kt} = q(s_t = k)$, for each session. For a state time course with one state active at each time point, take the most probable state at each time point, the maximum a posteriori (MAP) estimate, with [`argmax_time_courses()`](autoapi/osl_dynamics/inference/modes/argmax_time_courses.html.md#osl_dynamics.inference.modes.argmax_time_courses), or the most probable sequence of states with [`model.get_viterbi_path`](autoapi/osl_dynamics/models/base/MarkovModelBase.html.md#osl_dynamics.models.base.MarkovModelBase.get_viterbi_path). The learned parameters are returned by [`get_means()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_means), [`get_covariances()`](autoapi/osl_dynamics/models/base/MVNMixin.html.md#osl_dynamics.models.base.MVNMixin.get_covariances), [`get_trans_prob()`](autoapi/osl_dynamics/models/base/MarkovModelBase.html.md#osl_dynamics.models.base.MarkovModelBase.get_trans_prob) and [`get_initial_state_probs()`](autoapi/osl_dynamics/models/base/MarkovModelBase.html.md#osl_dynamics.models.base.MarkovModelBase.get_initial_state_probs). See the [Getting the Inferred Parameters tutorial](tutorials_build/3-5_hmm_dynemo_get_inf_params.html.md). ### Canonical HMM Networks Instead of training a new HMM for each study, a pre-trained **canonical HMM** can be used to infer the state time courses for new data [6]. Canonical HMMs with 4-16 states, trained on a large MEG dataset in parcellated source space and in sensor space, are available in the [Canonical-HMM-Networks](https://github.com/OHBA-analysis/Canonical-HMM-Networks) repository. ## Post-hoc Analysis Post-hoc analysis interprets the inferred state time course: statistics that summarize the dynamics of each state, and the spectral properties (power and coherence) of each state. Further analyses (task data, the Fisher kernel and TINDA) are described [below](user_guide/models/hmm.html.md#hmm-further-analyses). ### Summary Statistics Four summary statistics describe the dynamics of each state: - The **fractional occupancy** ([`fractional_occupancies()`](autoapi/osl_dynamics/analysis/post_hoc/fractional_occupancies.html.md#osl_dynamics.analysis.post_hoc.fractional_occupancies)) is the fraction of the total time spent in the state. - The **mean lifetime** ([`mean_lifetimes()`](autoapi/osl_dynamics/analysis/post_hoc/mean_lifetimes.html.md#osl_dynamics.analysis.post_hoc.mean_lifetimes)), also known as the dwell time, is the average duration of a visit to the state. - The **mean interval** ([`mean_intervals()`](autoapi/osl_dynamics/analysis/post_hoc/mean_intervals.html.md#osl_dynamics.analysis.post_hoc.mean_intervals)) is the average time between consecutive visits to the state. - The **switching rate** ([`switching_rates()`](autoapi/osl_dynamics/analysis/post_hoc/switching_rates.html.md#osl_dynamics.analysis.post_hoc.switching_rates)) is the number of visits to the state per second. ![image](user_guide/models/images/hmm-summary-stats.svg) The summary statistics are calculated for each session (or subject) and can be compared between groups or conditions, or related to behavior, with the [statistical significance testing](user_guide/stats.html.md) tools. See the [HMM Summary Statistics tutorial](tutorials_build/4-3_hmm_summary_stats.html.md). ### Spectral Analysis With TDE data the states are spectrally distinct, e.g. a state with high alpha (8-12 Hz) power in occipital regions. The power spectrum and coherence of each state are calculated from the data before time-delay embedding (and PCA) with [`multitaper_spectra()`](autoapi/osl_dynamics/analysis/spectral/multitaper_spectra.html.md#osl_dynamics.analysis.spectral.multitaper_spectra), and power maps and coherence networks are calculated from the spectra. See [Spectral Analysis](user_guide/spectra.html.md) for the method and how to plot the outputs, and the [HMM Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md) and [HMM Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md) tutorials. For fMRI data, the state means and covariances of each subject are re-estimated with **dual estimation** ([`dual_estimation()`](autoapi/osl_dynamics/models/hmm/Model.html.md#osl_dynamics.models.hmm.Model.dual_estimation)). See the [HMM fMRI Dual Estimation](tutorials_build/4-4_hmm_fmri_dual_estimation.html.md) and [HMM Plotting fMRI Networks](tutorials_build/4-5_hmm_plotting_fmri_networks.html.md) tutorials. ## Further Analyses ### Task Data With task data, the state probability time course can be epoched around events to show how the network dynamics respond to a task [12, 16]. See the [Epoching Alphas tutorial](tutorials_build/6-1_epoching_alpha.html.md) and the [Network Response tutorial](tutorials_build/7-3_network_response.html.md) for statistical testing. ### Fisher Kernel The Fisher kernel ([`FisherKernel`](autoapi/osl_dynamics/analysis/fisher_kernel/FisherKernel.html.md#osl_dynamics.analysis.fisher_kernel.FisherKernel)) measures the similarity between subjects from the gradients of the HMM’s log-likelihood with respect to its parameters. It can be used to predict subject traits with kernel methods, such as kernel ridge regression or a support vector machine [7]. A derivation is [`here`](_downloads/87839e9721130199a6598f0469ce21d1/hmm-fisher-kernel.pdf). See the [Fisher kernel example](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/hmm_hmm-mvn_fisher-kernel.py). ### Temporal Interval Network Density Analysis (TINDA) TINDA ([`tinda()`](autoapi/osl_dynamics/analysis/tinda/tinda.html.md#osl_dynamics.analysis.tinda.tinda)) studies the order in which the states occur by asking which states are more likely in the first or second half of the interval between visits to each state. With the HMM, it has shown that large-scale networks activate in a structured cycle [8]. See the [TINDA example scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/tinda). ## References ### Methods 1. C Gohil, et al., osl-dynamics, a toolbox for modeling fast dynamic brain activity. [eLife, 2024](https://elifesciences.org/articles/91949). 2. L R Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition. [Proceedings of the IEEE, 1989](https://doi.org/10.1109/5.18626). 3. C M Bishop, Pattern Recognition and Machine Learning, Chapter 13: Sequential Data. [Springer, 2006](https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/). 4. D Vidaurre, et al., Spectrally resolved fast transient brain states in electrophysiological data. [NeuroImage, 2016](https://www.sciencedirect.com/science/article/pii/S1053811915010691). 5. D Vidaurre, et al., Discovering dynamic brain networks from big data in rest and task. [NeuroImage, 2018](https://www.sciencedirect.com/science/article/pii/S1053811917305487). 6. C Gohil, et al., Canonical hidden Markov model networks for studying M/EEG. [bioRxiv, 2025](https://doi.org/10.1101/2025.10.21.683692). 7. C Ahrends, M W Woolrich, D Vidaurre, Predicting individual traits from models of brain dynamics accurately and reliably using the Fisher kernel. [eLife, 2025](https://elifesciences.org/articles/95125). 8. M W J van Es, et al., Large-scale cortical functional networks are organized in structured cycles. [Nature Neuroscience, 2025](https://doi.org/10.1038/s41593-025-02052-8). ### Applications 1. A Baker, et al., Fast transient networks in spontaneous human brain activity. [eLife, 2014](https://elifesciences.org/articles/01867). 2. D Vidaurre, et al., Brain network dynamics are hierarchically organized in time. [PNAS, 2017](https://doi.org/10.1073/pnas.1705120114). 3. D Vidaurre, et al., Spontaneous cortical activity transiently organises into frequency specific phase-coupling networks. [Nature Communications, 2018](https://doi.org/10.1038/s41467-018-05316-z). 4. A Quinn, et al., Task-evoked dynamic network analysis through hidden Markov modeling. [Frontiers in Neuroscience, 2018](https://doi.org/10.3389/fnins.2018.00603). 5. C Higgins, et al., Replay bursts in humans coincide with activation of the default mode and parietal alpha networks. [Neuron, 2021](https://www.sciencedirect.com/science/article/pii/S0896627320309661). 6. T Sitnikova, et al., Short timescale abnormalities in the states of spontaneous synchrony in the functional neural networks in Alzheimer’s disease. [NeuroImage: Clinical, 2018](https://www.sciencedirect.com/science/article/pii/S2213158218301748). 7. J Van Schependom, et al., Increased brain atrophy and lesion load is associated with stronger lower alpha MEG power in multiple sclerosis patients. [NeuroImage: Clinical, 2021](https://doi.org/10.1016/j.nicl.2021.102632). 8. C Gohil, et al., Dynamic network analysis of electrophysiological task data. [Imaging Neuroscience, 2024](https://doi.org/10.1162/imag_a_00226). 9. C Gohil, et al., Effects of age on resting-state cortical networks. [Human Brain Mapping, 2026](https://doi.org/10.1002/hbm.70516). # user_guide/models/index.html.md # Models osl-dynamics implements several generative models for inferring dynamic functional brain networks from time series data. All of the models share the same interface: a `Config` object sets the hyperparameters, a `Model` object is trained on a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object, and the inferred state or mode time courses are passed to the post-hoc analysis tools in [`osl_dynamics.analysis`](autoapi/osl_dynamics/analysis/index.html.md#module-osl_dynamics.analysis). The [Getting Started](getting_started.html.md) page has a short example. The pages in this section describe each model: the generative model, how it is trained and the post-hoc analysis we recommend. ## Where the Models Fit in an Analysis ![image](user_guide/models/images/pipeline.svg) 1. **Record** M/EEG or fMRI data. 2. **Parcellate** (M/EEG only): source reconstruct the sensor data to give a time course for each brain region (parcel). See [M/EEG Processing](user_guide/meeg.html.md) and the [available parcellations](user_guide/parcellations/index.html.md#parcellations). 3. **Prepare the data** for the model: e.g. time-delay embedding, PCA and standardization for M/EEG, or standardization for fMRI. See the [MEG](tutorials_build/1-2_data_prepare_meg.html.md), [fMRI](tutorials_build/1-3_data_prepare_fmri.html.md) and [time-delay embedding](tutorials_build/1-4_data_time_delay_embedding.html.md) tutorials. 4. **Train a model**, described on the pages in this section. See the [Dynamic Modeling tutorials](tutorial_sections/dynamic_modelling.html.md). 5. **Post-hoc analysis** of the inferred state or mode time courses: summary statistics, spectra and power/coherence networks. See [Spectral Analysis](user_guide/spectra.html.md) and the [HMM](tutorial_sections/hmm_post_hoc.html.md) and [DyNeMo](tutorial_sections/dynemo_post_hoc.html.md) post-hoc tutorials. 6. **Statistics**: compare groups or conditions, or relate the dynamics to behavior. See [Statistical Significance Testing](user_guide/stats.html.md). ## States and Modes The models describe the data with a small number of networks, each with its own mean and covariance (the observation model), and a time course that says when each network is active. There are two kinds of time course: - **States** (HMM, DyNeStE, HIVE) are mutually exclusive: one state is active at each time point. The state probability time course, $\alpha_{kt}$, is the probability that state $k$ is active at time $t$. States give summary statistics directly, such as how long each state lasts. - **Modes** (DyNeMo, M-DyNeMo) mix: the covariance at each time point is a weighted sum of the mode covariances, with the mixing coefficients, $\alpha_{jt}$, as weights. Modes can describe networks that overlap in time. M-DyNeMo has one set of mixing coefficients for power ($\alpha_{jt}$) and another for functional connectivity ($\beta_{jt}$). ![image](user_guide/models/images/states-vs-modes.svg) ## Choosing a Model | Model | Time course | Temporal model | Training | Use when | |---------------------------------------------------------|----------------------------------------|-------------------------------------------|---------------------|-------------------------------------------------------------------------------| | [HMM](user_guide/models/hmm.html.md) | States | Markovian (transition probability matrix) | Fast, no GPU needed | A good default: interpretable summary statistics, e.g. for resting-state data | | [DyNeMo](user_guide/models/dynemo.html.md) | Modes (linear mixture) | Recurrent neural network | Slower, a GPU helps | Networks overlap in time, e.g. task responses | | [DyNeStE](user_guide/models/dyneste.html.md) | States | Recurrent neural network | Slower, a GPU helps | You want states and long-range temporal dependencies | | [M-DyNeMo](user_guide/models/mdynemo.html.md) | Modes, separate for power and FC | Recurrent neural networks | Slower, a GPU helps | Power and functional connectivity may change independently | | [HIVE](user_guide/models/hive.html.md) | States, with session-specific networks | Markovian (transition probability matrix) | Fast, no GPU needed | Sessions differ systematically, e.g. subjects, scanners or sites | The [FAQ](faq.html.md) has more guidance on choosing a model, the number of states/modes and the other hyperparameters. Further models are documented in the API reference only: [`DIVE`](autoapi/osl_dynamics/models/dive/index.html.md#module-osl_dynamics.models.dive) (DyNeMo with embeddings for inter-session variability), [`SC-DyNeMo`](autoapi/osl_dynamics/models/scdynemo/index.html.md#module-osl_dynamics.models.scdynemo) (single-channel DyNeMo), [`HMM-Poisson`](autoapi/osl_dynamics/models/hmm_poisson/index.html.md#module-osl_dynamics.models.hmm_poisson) (an HMM for spike count data) and [`HMM-Dirichlet`](autoapi/osl_dynamics/models/hmm_dirichlet/index.html.md#module-osl_dynamics.models.hmm_dirichlet). There are example scripts for training each model on simulated data in [examples/simulation](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/simulation). * [Hidden Markov Model (HMM)](user_guide/models/hmm.html.md) * [Dynamic Network Modes (DyNeMo)](user_guide/models/dynemo.html.md) * [Dynamic Network States (DyNeStE)](user_guide/models/dyneste.html.md) * [Multi-Dynamic Network Modes (M-DyNeMo)](user_guide/models/mdynemo.html.md) * [HMM with Integrated Variability Estimation (HIVE)](user_guide/models/hive.html.md) # user_guide/models/mdynemo.html.md # Multi-Dynamic Network Modes (M-DyNeMo) M-DyNeMo [2] extends [DyNeMo](user_guide/models/dynemo.html.md) [3] with **separate dynamics for power and functional connectivity (FC)**. DyNeMo describes both with the same mixing coefficients, so a change in a region’s power always comes with a change in its connectivity. M-DyNeMo relaxes this: power and FC have their own modes and mixing coefficients, so one can change without the other. On MEG data, M-DyNeMo found transient power and FC dynamics that are largely uncoupled [2]. | Time course | Two sets of modes: mixing coefficients for power, $\alpha_{jt}$, and for FC, $\beta_{jt}$ | |-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Observation model | Multivariate normal, with a covariance built from a mixture of standard deviations and a mixture of correlations | | Temporal model | Recurrent neural network (LSTM by default) | | Training | Amortized variational inference, a GPU helps | | API | [`Config`](autoapi/osl_dynamics/models/mdynemo/Config.html.md#osl_dynamics.models.mdynemo.Config), [`Model`](autoapi/osl_dynamics/models/mdynemo/Model.html.md#osl_dynamics.models.mdynemo.Model) | | Examples | [Simulation](https://github.com/OHBA-analysis/osl-dynamics/blob/main/examples/simulation/mdynemo_hmm-mvn.py) | ## Generative Model M-DyNeMo separates the covariance at each time point into **standard deviations** (power) and **correlations** (FC), each with its own set of modes and mixing coefficients: $$ p(x_t | \theta^{\alpha}_t, \theta^{\beta}_t) = \mathcal{N}(m_t, C_t), \quad C_t = E_t R_t E_t, $$ where - $E_t = \sum_j \alpha_{jt} E_j$ is a diagonal matrix of standard deviations, a mixture of the **power modes**, $E_j$; - $R_t = \sum_j \beta_{jt} R_j$ is a correlation matrix, a mixture of the **FC modes**, $R_j$; - $m_t = \sum_j \alpha_{jt} \mu_j$ is the mean. The power mixing coefficients, $\alpha_{jt}$, and FC mixing coefficients, $\beta_{jt}$, are softmax transforms of two sets of logits, $\theta^{\alpha}_t$ and $\theta^{\beta}_t$. As in DyNeMo, a recurrent neural network (the **model RNN**) predicts the distribution of the logits at each time point from all of the previous logits of both sets. ![image](user_guide/models/images/mdynemo-graphical-model.svg)![image](user_guide/models/images/mdynemo-generative-process.svg) The number of power modes (`n_modes`) and FC modes (`n_correlation_modes`) can be different. ## Training M-DyNeMo in osl-dynamics [1] is trained in the same way as [DyNeMo](user_guide/models/dynemo.html.md), with **amortized variational inference**: a bidirectional inference RNN predicts the posterior for both sets of logits from the data, and the cost function is the variational free energy, with a KL divergence term for each set of logits. KL annealing (`kl_annealing=True`) can be used. The recommended initialization is [`random_subset_initialization()`](autoapi/osl_dynamics/models/base/InitializationMixin.html.md#osl_dynamics.models.base.InitializationMixin.random_subset_initialization) (the default `init_method`), and [`model.train`](autoapi/osl_dynamics/models/base/ModelBase.html.md#osl_dynamics.models.base.ModelBase.train) runs it before `fit`. The standard deviations, correlations and means are learned if `learn_standard_deviations`, `learn_correlations` and `learn_means` are `True`. They are returned by [`get_means()`](autoapi/osl_dynamics/models/mdynemo/Model.html.md#osl_dynamics.models.mdynemo.Model.get_means), [`get_standard_deviations()`](autoapi/osl_dynamics/models/mdynemo/Model.html.md#osl_dynamics.models.mdynemo.Model.get_standard_deviations) and [`get_correlations()`](autoapi/osl_dynamics/models/mdynemo/Model.html.md#osl_dynamics.models.mdynemo.Model.get_correlations). For example: ```default from osl_dynamics.models.mdynemo import Config, Model config = Config( n_modes=6, n_correlation_modes=6, n_channels=data.n_channels, sequence_length=200, inference_n_units=64, inference_normalization="layer", model_n_units=64, model_normalization="layer", learn_means=False, learn_standard_deviations=True, learn_correlations=True, kl_annealing=True, kl_annealing_curve="tanh", kl_annealing_sharpness=10, n_kl_annealing_epochs=20, batch_size=32, learning_rate=0.01, n_epochs=40, ) model = Model(config) model.train(data) alpha, beta = model.get_alpha(data) ``` where `data` is a [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object. ## Post-hoc Analysis [`model.get_alpha`](autoapi/osl_dynamics/models/mdynemo/Model.html.md#osl_dynamics.models.mdynemo.Model.get_alpha) returns both sets of mixing coefficients: the power mixing coefficients, $\alpha_{jt}$, and the FC mixing coefficients, $\beta_{jt}$. Each set can be analyzed in the same way as the [DyNeMo](user_guide/models/dynemo.html.md) mixing coefficients: - **Re-weighting** with [`reweight_mtc()`](autoapi/osl_dynamics/inference/modes/reweight_mtc.html.md#osl_dynamics.inference.modes.reweight_mtc), which accounts for the size of each mode’s covariance or correlations. - **Summary statistics**, e.g. the mean, standard deviation or kurtosis of the mixing coefficients, or the HMM summary statistics after binarizing them with [`gmm_time_courses()`](autoapi/osl_dynamics/inference/modes/gmm_time_courses.html.md#osl_dynamics.inference.modes.gmm_time_courses). - **Spectral analysis** with the regression spectra ([`regression_spectra()`](autoapi/osl_dynamics/analysis/spectral/regression_spectra.html.md#osl_dynamics.analysis.spectral.regression_spectra)). See [Spectral Analysis](user_guide/spectra.html.md). Comparing the power and FC time courses shows how closely power and FC dynamics are related, e.g. with the correlation between $\alpha_{jt}$ and $\beta_{jt}$. ## References 1. C Gohil, et al., osl-dynamics, a toolbox for modeling fast dynamic brain activity. [eLife, 2024](https://elifesciences.org/articles/91949). 2. R Huang, C Gohil, M W Woolrich, Evidence for transient, uncoupled power and functional connectivity dynamics. [Human Brain Mapping, 2025](https://doi.org/10.1002/hbm.70179). 3. C Gohil, et al., Mixtures of large-scale dynamic functional brain network modes. [NeuroImage, 2022](https://doi.org/10.1016/j.neuroimage.2022.119595). # user_guide/parcellations/aal116.html.md # AAL116 Parcellation This parcellation file is named `atlas-AAL_nparc-116_space-MNI_res-8x8x8.nii.gz`. This parcellation contains the **116 regions** (cortical, subcortical, and cerebellar) from the [Automated Anatomical Labelling](https://www.gin.cnrs.fr/en/tools/aal/) atlas (AAL SPM12). ## Parcels ![AAL116 Parcellation](user_guide/parcellations/aal116.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|--------------------|--------------|-------|-------|-------| | 0 | Precentral | left | -38.9 | -6.8 | 48.3 | | 1 | Precentral | right | 40.5 | -9.9 | 50.2 | | 2 | Frontal_Sup | left | -18.7 | 33.2 | 40 | | 3 | Frontal_Sup | right | 21.4 | 29.1 | 41.9 | | 4 | Frontal_Sup_Orb | left | -16.9 | 46.1 | -14.5 | | 5 | Frontal_Sup_Orb | right | 18 | 46.2 | -14.8 | | 6 | Frontal_Mid | left | -32.9 | 30.7 | 33.8 | | 7 | Frontal_Mid | right | 36.4 | 31 | 32.9 | | 8 | Frontal_Mid_Orb | left | -30.6 | 48.6 | -10.5 | | 9 | Frontal_Mid_Orb | right | 32.8 | 51.1 | -11.2 | | 10 | Frontal_Inf_Oper | left | -48.1 | 11.1 | 17.5 | | 11 | Frontal_Inf_Oper | right | 48.1 | 13.1 | 19.8 | | 12 | Frontal_Inf_Tri | left | -44.7 | 28.3 | 12.6 | | 13 | Frontal_Inf_Tri | right | 48.2 | 28.1 | 13 | | 14 | Frontal_Inf_Orb | left | -35.5 | 29.3 | -13.3 | | 15 | Frontal_Inf_Orb | right | 39.3 | 30.8 | -12.9 | | 16 | Rolandic_Oper | left | -47.3 | -9.9 | 12.7 | | 17 | Rolandic_Oper | right | 51.1 | -8.8 | 13.8 | | 18 | Supp_Motor_Area | left | -5.6 | 3.3 | 58.9 | | 19 | Supp_Motor_Area | right | 8.2 | -1.4 | 59.8 | | 20 | Olfactory | left | -7.9 | 14.3 | -12.2 | | 21 | Olfactory | right | 9.6 | 15 | -12.2 | | 22 | Frontal_Sup_Medial | left | -5.1 | 47.2 | 29.4 | | 23 | Frontal_Sup_Medial | right | 8.5 | 49.1 | 28.4 | | 24 | Frontal_Med_Orb | left | -5.4 | 52 | -9.1 | | 25 | Frontal_Med_Orb | right | 7.8 | 50 | -8.4 | | 26 | Rectus | left | -5.4 | 35.3 | -19.4 | | 27 | Rectus | right | 7.9 | 34.4 | -19.2 | | 28 | Insula | left | -35.4 | 5.5 | 2.2 | | 29 | Insula | right | 38.7 | 5.1 | 0.8 | | 30 | Cingulum_Ant | left | -4.2 | 34.2 | 12.7 | | 31 | Cingulum_Ant | right | 8.1 | 35.6 | 14.7 | | 32 | Cingulum_Mid | left | -5.8 | -16 | 40 | | 33 | Cingulum_Mid | right | 7.6 | -10.2 | 38.6 | | 34 | Cingulum_Post | left | -5.1 | -44.3 | 23.5 | | 35 | Cingulum_Post | right | 6.9 | -42.9 | 20.4 | | 36 | Hippocampus | left | -25.4 | -21.8 | -11.6 | | 37 | Hippocampus | right | 28.9 | -21 | -11.5 | | 38 | ParaHippocampal | left | -21.6 | -17.4 | -21.7 | | 39 | ParaHippocampal | right | 25.1 | -16.3 | -21.7 | | 40 | Amygdala | left | -23.6 | -1.8 | -18.4 | | 41 | Amygdala | right | 27.2 | -0.6 | -18.8 | | 42 | Calcarine | left | -8.1 | -78.6 | 5.4 | | 43 | Calcarine | right | 15.8 | -74.2 | 8 | | 44 | Cuneus | left | -6.9 | -80.1 | 25.8 | | 45 | Cuneus | right | 13 | -80 | 26.3 | | 46 | Lingual | left | -14.9 | -68.8 | -5.9 | | 47 | Lingual | right | 15.9 | -67.7 | -5 | | 48 | Occipital_Sup | left | -16.6 | -84.9 | 26.3 | | 49 | Occipital_Sup | right | 23.8 | -80.9 | 29.3 | | 50 | Occipital_Mid | left | -32.3 | -81.5 | 15.1 | | 51 | Occipital_Mid | right | 36.8 | -80 | 18.2 | | 52 | Occipital_Inf | left | -36.3 | -79.6 | -9 | | 53 | Occipital_Inf | right | 37.8 | -81.7 | -8.9 | | 54 | Fusiform | left | -31.6 | -41.9 | -21.1 | | 55 | Fusiform | right | 33.6 | -41.1 | -20.9 | | 56 | Postcentral | left | -43.2 | -23.5 | 46 | | 57 | Postcentral | right | 40.8 | -26.6 | 50 | | 58 | Parietal_Sup | left | -23.5 | -60.9 | 56.3 | | 59 | Parietal_Sup | right | 25.3 | -59.9 | 59.2 | | 60 | Parietal_Inf | left | -42.9 | -46.6 | 45.2 | | 61 | Parietal_Inf | right | 45.5 | -47.3 | 48.2 | | 62 | SupraMarginal | left | -55.8 | -35 | 28.9 | | 63 | SupraMarginal | right | 56.7 | -32.8 | 32.8 | | 64 | Angular | left | -44.2 | -61.9 | 34.2 | | 65 | Angular | right | 44.5 | -60.6 | 37 | | 66 | Precuneus | left | -7.6 | -57.5 | 45.3 | | 67 | Precuneus | right | 9.8 | -57.1 | 40.9 | | 68 | Paracentral_Lobule | left | -7.9 | -26.9 | 65.2 | | 69 | Paracentral_Lobule | right | 7.3 | -33.8 | 64.1 | | 70 | Caudate | left | -12.3 | 9.7 | 7.8 | | 71 | Caudate | right | 14.5 | 11 | 8.2 | | 72 | Putamen | left | -24.3 | 2.6 | 1.3 | | 73 | Putamen | right | 27.6 | 3.6 | 1.3 | | 74 | Pallidum | left | -18 | -1.3 | -1.2 | | 75 | Pallidum | right | 20.9 | -1 | -1.1 | | 76 | Thalamus | left | -11.3 | -18.8 | 6.8 | | 77 | Thalamus | right | 12.8 | -18.7 | 6.9 | | 78 | Heschl | left | -42.1 | -20.1 | 8.6 | | 79 | Heschl | right | 45.3 | -18.5 | 9.4 | | 80 | Temporal_Sup | left | -52.9 | -22 | 5.7 | | 81 | Temporal_Sup | right | 56.4 | -23.4 | 5.6 | | 82 | Temporal_Pole_Sup | left | -39.4 | 12.3 | -21 | | 83 | Temporal_Pole_Sup | right | 44.2 | 12.7 | -20.1 | | 84 | Temporal_Mid | left | -54.5 | -35.8 | -3.2 | | 85 | Temporal_Mid | right | 55.8 | -38.9 | -2.4 | | 86 | Temporal_Pole_Mid | left | -35.7 | 12.3 | -35.2 | | 87 | Temporal_Pole_Mid | right | 41.1 | 12.1 | -33.4 | | 88 | Temporal_Inf | left | -49.1 | -28.8 | -24.4 | | 89 | Temporal_Inf | right | 52.2 | -32.7 | -22.7 | | 90 | Cerebelum_Crus1 | left | -34 | -68.2 | -30.1 | | 91 | Cerebelum_Crus1 | right | 35.3 | -69.1 | -30.6 | | 92 | Cerebelum_Crus2 | left | -26.4 | -74.6 | -39.3 | | 93 | Cerebelum_Crus2 | right | 29.7 | -72.3 | -40.3 | | 94 | Cerebelum_3 | left | -8.5 | -38.3 | -19.9 | | 95 | Cerebelum_3 | right | 13.3 | -35.6 | -20.7 | | 96 | Cerebelum_4_5 | left | -14.7 | -44.7 | -18.9 | | 97 | Cerebelum_4_5 | right | 17.6 | -44.7 | -19 | | 98 | Cerebelum_6 | left | -22.6 | -60.6 | -23.4 | | 99 | Cerebelum_6 | right | 25 | -60.8 | -24.5 | | 100 | Cerebelum_7b | left | -29.4 | -63.2 | -46.3 | | 101 | Cerebelum_7b | right | 30.6 | -66.1 | -47.9 | | 102 | Cerebelum_8 | left | -24.6 | -56.6 | -48.7 | | 103 | Cerebelum_8 | right | 25.3 | -58.1 | -49.5 | | 104 | Cerebelum_9 | left | -10.2 | -50.5 | -47 | | 105 | Cerebelum_9 | right | 10.1 | -50.9 | -47.6 | | 106 | Cerebelum_10 | left | -20.5 | -38 | -42.8 | | 107 | Cerebelum_10 | right | 25.1 | -38.2 | -43.1 | | 108 | Vermis_1_2 | midline | 1.4 | -40.3 | -21.8 | | 109 | Vermis_3 | midline | 2.1 | -41.6 | -13.5 | | 110 | Vermis_4_5 | midline | 1.9 | -54.5 | -8.4 | | 111 | Vermis_6 | midline | 1.8 | -68.4 | -16.5 | | 112 | Vermis_7 | midline | 1.8 | -73 | -26.2 | | 113 | Vermis_8 | midline | 1.8 | -65.5 | -35.3 | | 114 | Vermis_9 | midline | 1.7 | -56.5 | -36.5 | | 115 | Vermis_10 | midline | 0.5 | -48.1 | -33.2 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-AAL_nparc-116_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Tzourio-Mazoyer, N., Landeau, B., Papathanassiou, D., Crivello, F., Etard, O., Delcroix, N., Mazoyer, B., & Joliot, M. (2002). Automated Anatomical Labeling of Activations in SPM Using a Macroscopic Anatomical Parcellation of the MNI MRI Single-Subject Brain. *NeuroImage*, 15(1), 273-289. https://doi.org/10.1006/nimg.2001.0978 ``` # user_guide/parcellations/aal24.html.md # AAL24 Parcellation This parcellation file is named `atlas-AAL_nparc-24_space-MNI_res-8x8x8.nii.gz`. This is a reduced version of the [AAL116 parcellation](user_guide/parcellations/aal116.html.md), obtained by merging the original [Automated Anatomical Labelling](https://www.gin.cnrs.fr/en/tools/aal/) regions into 24 broad anatomical groups (10 bilateral pairs plus 4 midline regions). ## Parcels ![AAL24 Parcellation](user_guide/parcellations/aal24.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|----------------------|--------------|-------|-------|-------| | 0 | Sensorimotor | left | -31.8 | -12.6 | 48 | | 1 | Sensorimotor | right | 32.7 | -14.9 | 48.8 | | 2 | Lateral Frontal | left | -26.8 | 32.9 | 29.6 | | 3 | Lateral Frontal | right | 30.8 | 31.1 | 30.8 | | 4 | Orbitofrontal | left | -20.7 | 38.7 | -13.4 | | 5 | Orbitofrontal | right | 23 | 39.9 | -13.1 | | 6 | Parietal | left | -29 | -53.3 | 44.1 | | 7 | Parietal | right | 32.3 | -52.1 | 43 | | 8 | Lateral Temporal | left | -47.2 | -26.8 | -11.8 | | 9 | Lateral Temporal | right | 49.5 | -27.8 | -11.2 | | 10 | Occipital | left | -19.5 | -78.6 | 9.9 | | 11 | Occipital | right | 22.7 | -76.3 | 11 | | 12 | Insula | left | -35.4 | 5.5 | 2.2 | | 13 | Insula | right | 38.7 | 5.1 | 0.8 | | 14 | Medial Temporal | left | -23.5 | -17.7 | -16.9 | | 15 | Medial Temporal | right | 26.9 | -16.5 | -17.2 | | 16 | Basal Ganglia | left | -18.5 | 5 | 3.6 | | 17 | Basal Ganglia | right | 21.2 | 6.2 | 3.9 | | 18 | Cerebellum (lateral) | left | -24.4 | -60.9 | -34.8 | | 19 | Cerebellum (lateral) | right | 26.2 | -61.1 | -36 | | 20 | Anterior Cingulate | midline | 1.8 | 34.9 | 13.7 | | 21 | Middle Cingulate | midline | 1 | -18 | 36.5 | | 22 | Thalamus | midline | 0.5 | -18.8 | 6.9 | | 23 | Cerebellar Vermis | midline | 1.8 | -58.6 | -19.5 | Each AAL24 parcel was formed by merging the following AAL116 regions: | Parcel | AAL116 regions | |----------------------|------------------------------------------------------------------------------------------| | Sensorimotor | Precentral, Postcentral, Supp_Motor_Area, Paracentral_Lobule, Rolandic_Oper | | Lateral Frontal | Frontal_Sup, Frontal_Mid, Frontal_Inf_Oper, Frontal_Inf_Tri, Frontal_Sup_Medial | | Orbitofrontal | Frontal_Sup_Orb, Frontal_Mid_Orb, Frontal_Inf_Orb, Frontal_Med_Orb, Rectus, Olfactory | | Parietal | Parietal_Sup, Parietal_Inf, Precuneus, SupraMarginal, Angular | | Lateral Temporal | Temporal_Sup, Temporal_Mid, Temporal_Inf, Temporal_Pole_Sup, Temporal_Pole_Mid, | | | Fusiform, Heschl | | Occipital | Occipital_Sup, Occipital_Mid, Occipital_Inf, Calcarine, Cuneus, Lingual | | Insula | Insula | | Medial Temporal | Hippocampus, ParaHippocampal, Amygdala | | Basal Ganglia | Caudate, Putamen, Pallidum | | Cerebellum (lateral) | Cerebelum_Crus1, Cerebelum_Crus2, Cerebelum_3, Cerebelum_4_5, Cerebelum_6, Cerebelum_7b, | | | Cerebelum_8, Cerebelum_9 | | Anterior Cingulate | Cingulum_Ant | | Middle Cingulate | Cingulum_Mid, Cingulum_Post | | Thalamus | Thalamus | | Cerebellar Vermis | Vermis_3, Vermis_4_5, Vermis_6, Vermis_7, Vermis_8, Vermis_9, Vermis_10 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-AAL_nparc-24_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Tzourio-Mazoyer, N., Landeau, B., Papathanassiou, D., Crivello, F., Etard, O., Delcroix, N., Mazoyer, B., & Joliot, M. (2002). Automated Anatomical Labeling of Activations in SPM Using a Macroscopic Anatomical Parcellation of the MNI MRI Single-Subject Brain. *NeuroImage*, 15(1), 273-289. https://doi.org/10.1006/nimg.2001.0978 ``` # user_guide/parcellations/aal78.html.md # AAL78 Parcellation This parcellation file is named `atlas-AAL_nparc-78_space-MNI_res-8x8x8.nii.gz`. It was previously named `aal_cortical_merged_8mm_stacked.nii.gz` (osl-dynamics accepts both). This parcellation contains the **cortical regions** from the [Automated Anatomical Labelling](https://www.gin.cnrs.fr/en/tools/aal/) atlas. ## Parcels ![AAL78 Parcellation](user_guide/parcellations/aal78.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|--------------------|--------------|-------|-------|-------| | 0 | Amygdala | left | -23.3 | 0.7 | -18.7 | | 1 | Amygdala | right | 26 | 2 | -20 | | 2 | Angular | left | -47.3 | -58.4 | 32.9 | | 3 | Angular | right | 43.4 | -58.6 | 36.3 | | 4 | Calcarine | left | -7.7 | -78.9 | 4.9 | | 5 | Calcarine | right | 14 | -71.7 | 9.1 | | 6 | Cingulum_Ant | left | -7.3 | 37.6 | 11.1 | | 7 | Cingulum_Ant | right | 5 | 38 | 13.3 | | 8 | Cingulum_Mid | left | -9.2 | -12.8 | 39.5 | | 9 | Cingulum_Mid | right | 5.2 | -8.5 | 37.9 | | 10 | Cingulum_Post | left | -6 | -39.1 | 24 | | 11 | Cingulum_Post | right | 5.4 | -40.3 | 17.1 | | 12 | Cuneus | left | -8.1 | -80.1 | 24 | | 13 | Cuneus | right | 11.1 | -79.8 | 25.1 | | 14 | Frontal_Inf_Oper | left | -48.5 | 13 | 19 | | 15 | Frontal_Inf_Oper | right | 47.5 | 15 | 16.5 | | 16 | Frontal_Inf_Orb | left | -36.3 | 30.3 | -14.3 | | 17 | Frontal_Inf_Orb | right | 37.6 | 31.5 | -14.2 | | 18 | Frontal_Inf_Tri | left | -46.3 | 29.4 | 11.6 | | 19 | Frontal_Inf_Tri | right | 47.4 | 30.2 | 12.5 | | 20 | Frontal_Med_Orb | left | -8.7 | 51.3 | -8 | | 21 | Frontal_Med_Orb | right | 5.6 | 55.3 | -8.9 | | 22 | Frontal_Mid | left | -34.7 | 33.2 | 33.1 | | 23 | Frontal_Mid_Orb | left | -30 | 49.4 | -12.3 | | 24 | Frontal_Mid_Orb | right | 32.4 | 53.2 | -12.8 | | 25 | Frontal_Mid | right | 35.5 | 33.4 | 33.3 | | 26 | Frontal_Sup | left | -19.9 | 35.1 | 39.9 | | 27 | Frontal_Sup_Medial | left | -8.2 | 50.8 | 25.5 | | 28 | Frontal_Sup_Medial | right | 6.2 | 51.7 | 28.2 | | 29 | Frontal_Sup_Orb | left | -17.1 | 49.4 | -16.6 | | 30 | Frontal_Sup_Orb | right | 14.7 | 44.4 | -18.4 | | 31 | Frontal_Sup | right | 20.4 | 31.8 | 40.8 | | 32 | Fusiform | left | -34.3 | -39.4 | -21.9 | | 33 | Fusiform | right | 32.6 | -38.7 | -21.5 | | 34 | Heschl | left | -46 | -16.7 | 8 | | 35 | Heschl | right | 42 | -18 | 10.7 | | 36 | Insula | left | -37.5 | 9.7 | 0.8 | | 37 | Insula | right | 36.5 | 9.3 | 1.1 | | 38 | Lingual | left | -16.9 | -69.1 | -8 | | 39 | Lingual | right | 13.9 | -68.3 | -4.3 | | 40 | Occipital_Inf | left | -37.5 | -79.1 | -9.6 | | 41 | Occipital_Inf | right | 35.1 | -79.6 | -11.2 | | 42 | Occipital_Mid | left | -33.9 | -80.8 | 14.1 | | 43 | Occipital_Mid | right | 35.1 | -79.9 | 16.4 | | 44 | Occipital_Sup | left | -17.8 | -83 | 27.8 | | 45 | Occipital_Sup | right | 23.2 | -80.4 | 31.5 | | 46 | ParaHippocampal | left | -24.7 | -14.5 | -23.5 | | 47 | ParaHippocampal | right | 23.2 | -13.2 | -22.4 | | 48 | Paracentral_Lobule | left | -9.7 | -23.6 | 66.7 | | 49 | Paracentral_Lobule | right | 6 | -31.3 | 63.3 | | 50 | Parietal_Inf | left | -44.9 | -47.3 | 45.5 | | 51 | Parietal_Inf | right | 46.9 | -46 | 48.3 | | 52 | Parietal_Sup | left | -26.1 | -58.6 | 56.5 | | 53 | Parietal_Sup | right | 24.8 | -59 | 58.4 | | 54 | Postcentral | left | -43.7 | -23 | 46.8 | | 55 | Postcentral | right | 39.2 | -24.9 | 50.6 | | 56 | Precentral | left | -40.9 | -4.5 | 47.7 | | 57 | Precentral | right | 39.4 | -7.1 | 50.1 | | 58 | Precuneus | left | -10.1 | -55.2 | 45.7 | | 59 | Precuneus | right | 7.7 | -57 | 41.7 | | 60 | Rectus | left | -8.4 | 39.6 | -18.8 | | 61 | Rectus | right | 5.3 | 36.8 | -18.8 | | 62 | Rolandic_Oper | left | -48 | -9.3 | 12.7 | | 63 | Rolandic_Oper | right | 50.5 | -3.9 | 11.7 | | 64 | Supp_Motor_Area | left | -7.9 | 6.8 | 58.6 | | 65 | Supp_Motor_Area | right | 6.4 | 2 | 59.1 | | 66 | SupraMarginal | left | -57.5 | -33.1 | 27.5 | | 67 | SupraMarginal | right | 54.9 | -29.5 | 32 | | 68 | Temporal_Inf | left | -51.1 | -30.4 | -22.8 | | 69 | Temporal_Inf | right | 51.1 | -30.8 | -23.2 | | 70 | Temporal_Mid | left | -56.9 | -31.6 | -4.1 | | 71 | Temporal_Mid | right | 55.1 | -37.5 | -2.5 | | 72 | Temporal_Pole_Mid | left | -36.4 | 14 | -36 | | 73 | Temporal_Pole_Mid | right | 41.4 | 13.4 | -32 | | 74 | Temporal_Pole_Sup | left | -40.4 | 13.8 | -21.2 | | 75 | Temporal_Pole_Sup | right | 41.5 | 15.5 | -21 | | 76 | Temporal_Sup | left | -53.4 | -17.7 | 3.7 | | 77 | Temporal_Sup | right | 55.4 | -19.6 | 4.7 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-AAL_nparc-78_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Tzourio-Mazoyer, N., Landeau, B., Papathanassiou, D., Crivello, F., Etard, O., Delcroix, N., Mazoyer, B., & Joliot, M. (2002). Automated Anatomical Labeling of Activations in SPM Using a Macroscopic Anatomical Parcellation of the MNI MRI Single-Subject Brain. *NeuroImage*, 15(1), 273-289. https://doi.org/10.1006/nimg.2001.0978 ``` # user_guide/parcellations/dk54.html.md # DK54 Parcellation This is a reduced version of the original [DK68 parcellation](user_guide/parcellations/dk68.html.md). ## Parcels ![DK54 Parcellation](user_guide/parcellations/dk54.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|------------------------------------------------------------------|--------------|-------|-------|-------| | 0 | Banks of Superior Temporal Sulcus | left | -50.3 | -44.4 | 6.4 | | 1 | Caudal Anterior Cingulate | left | -9.1 | 16.2 | 25.2 | | 2 | Caudal Middle Frontal | left | -34.7 | 10.9 | 44 | | 3 | Cuneus | left | -6 | -83.7 | 17.7 | | 4 | Entorhinal + Parahippocampal + Temporal Pole | left | -24.6 | -5.5 | -29.7 | | 5 | Fusiform Gyrus | left | -33.2 | -43.9 | -21.5 | | 6 | Inferior Parietal Cortex | left | -40.4 | -66 | 30.2 | | 7 | Inferior Temporal Cortex | left | -50.4 | -35.1 | -22.2 | | 8 | Lateral Occipital Cortex | left | -28.3 | -89 | 1.1 | | 9 | Lateral Orbitofrontal Cortex | left | -23.6 | 30.7 | -15.5 | | 10 | Lingual Gyrus | left | -13.8 | -67.3 | -5.1 | | 11 | Medial Orbitofrontal Cortex | left | -7.6 | 38 | -14.8 | | 12 | Middle Temporal Cortex | left | -56.9 | -27.7 | -11.9 | | 13 | Paracentral Lobule | left | -9.6 | -27.5 | 54.5 | | 14 | Inferior Frontal Gyrus (Pars Opercularis/Orbitalis/Triangularis) | left | -43.6 | 26.6 | 5.2 | | 15 | Pericalcarine Cortex | left | -15.1 | -79.7 | 6.3 | | 16 | Postcentral Gyrus | left | -41.6 | -25 | 47.6 | | 17 | Posterior + Isthmus Cingulate | left | -8.9 | -27.1 | 28.6 | | 18 | Precentral Gyrus | left | -38.6 | -8.7 | 41.2 | | 19 | Precuneus | left | -11.6 | -58.4 | 34.7 | | 20 | Rostral Anterior Cingulate | left | -8 | 36.5 | 3 | | 21 | Rostral Middle Frontal + Frontal Pole | left | -29.7 | 46.3 | 15.2 | | 22 | Superior Frontal Cortex | left | -12.4 | 25.7 | 43.9 | | 23 | Superior Parietal Cortex | left | -21.5 | -62.9 | 48.3 | | 24 | Superior + Transverse Temporal Cortex | left | -49.8 | -13.5 | -2.6 | | 25 | Supramarginal Gyrus | left | -52.2 | -36.9 | 33.1 | | 26 | Insula | left | -33.7 | -4 | 3.4 | | 27 | Banks of Superior Temporal Sulcus | right | 49.3 | -40.9 | 7.3 | | 28 | Caudal Anterior Cingulate | right | 6 | 18.4 | 25.6 | | 29 | Caudal Middle Frontal | right | 35.9 | 10.8 | 44.4 | | 30 | Cuneus | right | 6.6 | -80.9 | 21.1 | | 31 | Entorhinal + Parahippocampal + Temporal Pole | right | 24.9 | -7.1 | -28.1 | | 32 | Fusiform Gyrus | right | 35.6 | -41.6 | -22.1 | | 33 | Inferior Parietal Cortex | right | 44.1 | -60.8 | 30.3 | | 34 | Inferior Temporal Cortex | right | 51.2 | -32.1 | -23.3 | | 35 | Lateral Occipital Cortex | right | 31.7 | -85.4 | 1.4 | | 36 | Lateral Orbitofrontal Cortex | right | 25.1 | 31.6 | -14.5 | | 37 | Lingual Gyrus | right | 14.8 | -65.5 | -4.4 | | 38 | Medial Orbitofrontal Cortex | right | 5.8 | 36.7 | -14.7 | | 39 | Middle Temporal Cortex | right | 58.3 | -26.1 | -12.4 | | 40 | Paracentral Lobule | right | 8.6 | -25.5 | 55.3 | | 41 | Inferior Frontal Gyrus (Pars Opercularis/Orbitalis/Triangularis) | right | 46.8 | 27.4 | 5 | | 42 | Pericalcarine Cortex | right | 15.2 | -78.5 | 7.5 | | 43 | Postcentral Gyrus | right | 44.5 | -19.1 | 43.1 | | 44 | Posterior + Isthmus Cingulate | right | 7 | -27.7 | 26.5 | | 45 | Precentral Gyrus | right | 38.5 | -8.9 | 44.6 | | 46 | Precuneus | right | 10.8 | -56.9 | 36.1 | | 47 | Rostral Anterior Cingulate | right | 6 | 33.2 | 3.6 | | 48 | Rostral Middle Frontal + Frontal Pole | right | 31.3 | 46.2 | 16.2 | | 49 | Superior Frontal Cortex | right | 11.5 | 26.8 | 43.4 | | 50 | Superior Parietal Cortex | right | 24.6 | -59.1 | 51.3 | | 51 | Superior + Transverse Temporal Cortex | right | 52.5 | -7.8 | -6 | | 52 | Supramarginal Gyrus | right | 52.6 | -31.8 | 31.9 | | 53 | Insula | right | 35.1 | -1 | 5 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-DK_nparc-54_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Gohil, C., Kohl, O., & Woolrich, M. (2026). DK54: a reduced version of the Desikan-Killiany parcellation [Data set]. Zenodo. https://doi.org/10.5281/zenodo.18599127 ``` # user_guide/parcellations/dk68.html.md # DK68 Parcellation This parcellation contains a volumetric version of the [Desikan-Killiany (DK)](https://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation) atlas, which is the default atlas used in [FreeSurfer](https://surfer.nmr.mgh.harvard.edu/). ## Parcels ![DK68 Parcellation](user_guide/parcellations/dk68.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|-----------------------------------|--------------|-------|-------|-------| | 0 | Banks of Superior Temporal Sulcus | left | -50.3 | -44.4 | 6.4 | | 1 | Caudal Anterior Cingulate | left | -9.1 | 16.2 | 25.2 | | 2 | Caudal Middle Frontal | left | -34.7 | 10.9 | 44 | | 3 | Cuneus | left | -6 | -83.7 | 17.7 | | 4 | Entorhinal Cortex | left | -24.3 | -4.9 | -32 | | 5 | Fusiform Gyrus | left | -33.2 | -43.9 | -21.5 | | 6 | Inferior Parietal Cortex | left | -40.4 | -66 | 30.2 | | 7 | Inferior Temporal Cortex | left | -50.4 | -35.1 | -22.2 | | 8 | Isthmus Cingulate | left | -9.7 | -42.3 | 20.3 | | 9 | Lateral Occipital Cortex | left | -28.3 | -89 | 1.1 | | 10 | Lateral Orbitofrontal Cortex | left | -23.6 | 30.7 | -15.5 | | 11 | Lingual Gyrus | left | -13.8 | -67.3 | -5.1 | | 12 | Medial Orbitofrontal Cortex | left | -7.6 | 38 | -14.8 | | 13 | Middle Temporal Cortex | left | -56.9 | -27.7 | -11.9 | | 14 | Parahippocampal Gyrus | left | -19.6 | -30.8 | -18.4 | | 15 | Paracentral Lobule | left | -9.6 | -27.5 | 54.5 | | 16 | Pars Opercularis | left | -45.7 | 17.7 | 13.5 | | 17 | Pars Orbitalis | left | -42 | 38 | -12.8 | | 18 | Pars Triangularis | left | -41.8 | 32.1 | 3.4 | | 19 | Pericalcarine Cortex | left | -15.1 | -79.7 | 6.3 | | 20 | Postcentral Gyrus | left | -41.6 | -25 | 47.6 | | 21 | Posterior Cingulate Cortex | left | -8.4 | -17.2 | 34 | | 22 | Precentral Gyrus | left | -38.6 | -8.7 | 41.2 | | 23 | Precuneus | left | -11.6 | -58.4 | 34.7 | | 24 | Rostral Anterior Cingulate | left | -8 | 36.5 | 3 | | 25 | Rostral Middle Frontal | left | -30.9 | 45.2 | 16.4 | | 26 | Superior Frontal Cortex | left | -12.4 | 25.7 | 43.9 | | 27 | Superior Parietal Cortex | left | -21.5 | -62.9 | 48.3 | | 28 | Superior Temporal Cortex | left | -50.7 | -12.3 | -3.9 | | 29 | Supramarginal Gyrus | left | -52.2 | -36.9 | 33.1 | | 30 | Frontal Pole | left | -9.2 | 66 | -6.4 | | 31 | Temporal Pole | left | -28.3 | 12.3 | -36.6 | | 32 | Transverse Temporal Cortex | left | -42.6 | -23.1 | 8 | | 33 | Insula | left | -33.7 | -4 | 3.4 | | 34 | Banks of Superior Temporal Sulcus | right | 49.3 | -40.9 | 7.3 | | 35 | Caudal Anterior Cingulate | right | 6 | 18.4 | 25.6 | | 36 | Caudal Middle Frontal | right | 35.9 | 10.8 | 44.4 | | 37 | Cuneus | right | 6.6 | -80.9 | 21.1 | | 38 | Entorhinal Cortex | right | 23.1 | -3.8 | -33.5 | | 39 | Fusiform Gyrus | right | 35.6 | -41.6 | -22.1 | | 40 | Inferior Parietal Cortex | right | 44.1 | -60.8 | 30.3 | | 41 | Inferior Temporal Cortex | right | 51.2 | -32.1 | -23.3 | | 42 | Isthmus Cingulate | right | 7.2 | -41.6 | 17.6 | | 43 | Lateral Occipital Cortex | right | 31.7 | -85.4 | 1.4 | | 44 | Lateral Orbitofrontal Cortex | right | 25.1 | 31.6 | -14.5 | | 45 | Lingual Gyrus | right | 14.8 | -65.5 | -4.4 | | 46 | Medial Orbitofrontal Cortex | right | 5.8 | 36.7 | -14.7 | | 47 | Middle Temporal Cortex | right | 58.3 | -26.1 | -12.4 | | 48 | Parahippocampal Gyrus | right | 21.7 | -30.6 | -16.6 | | 49 | Paracentral Lobule | right | 8.6 | -25.5 | 55.3 | | 50 | Pars Opercularis | right | 47.6 | 14.9 | 14.3 | | 51 | Pars Orbitalis | right | 44.3 | 41.4 | -11.4 | | 52 | Pars Triangularis | right | 47.7 | 31.7 | 5.7 | | 53 | Pericalcarine Cortex | right | 15.2 | -78.5 | 7.5 | | 54 | Postcentral Gyrus | right | 44.5 | -19.1 | 43.1 | | 55 | Posterior Cingulate Cortex | right | 6.8 | -16.6 | 33.6 | | 56 | Precentral Gyrus | right | 38.5 | -8.9 | 44.6 | | 57 | Precuneus | right | 10.8 | -56.9 | 36.1 | | 58 | Rostral Anterior Cingulate | right | 6 | 33.2 | 3.6 | | 59 | Rostral Middle Frontal | right | 32.3 | 45.4 | 17.3 | | 60 | Superior Frontal Cortex | right | 11.5 | 26.8 | 43.4 | | 61 | Superior Parietal Cortex | right | 24.6 | -59.1 | 51.3 | | 62 | Superior Temporal Cortex | right | 52.9 | -6.9 | -7 | | 63 | Supramarginal Gyrus | right | 52.6 | -31.8 | 31.9 | | 64 | Frontal Pole | right | 6 | 66 | -12 | | 65 | Temporal Pole | right | 29.7 | 13.7 | -35.1 | | 66 | Transverse Temporal Cortex | right | 46 | -22 | 8 | | 67 | Insula | right | 35.1 | -1 | 5 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-DK_nparc-68_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` # user_guide/parcellations/giles38.html.md # Giles38 Parcellation This parcellation file is named `atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz`. It was previously named `fmri_d100_parcellation_with_PCC_reduced_2mm_ss5mm_ds8mm.nii.gz` (osl-dynamics accepts both). This is the original parcellation created by Giles Colclough based on applying ICA to fMRI data from 100 subjects. It is also available at 2 mm as `atlas-Giles_nparc-38_space-MNI_res-2x2x2.nii.gz`, for use with fMRI on the MNI152 2 mm grid. This is `fMRI_parcellation_ds2mm.nii.gz` from [OHBA-analysis/parcellations](https://github.com/OHBA-analysis/parcellations) (whose `fMRI_parcellation_ds8mm.nii.gz` is identical to the 8 mm file here): the same 38 parcels in the same order, before the 5 mm smoothing and downsampling that produced the 8 mm file. The coordinates below are from the 8 mm file. ## Parcels ![Giles38 Parcellation](user_guide/parcellations/giles38.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|-----------------------------------------------------|--------------|-------|-------|-------| | 0 | Primary / Early Visual Cortex (dorsal) | left | -10 | -87.4 | 23.3 | | 1 | Primary / Early Visual Cortex (dorsal) | right | 10.2 | -86.7 | 23.2 | | 2 | Ventral Visual / Fusiform | left | -37.4 | -76.7 | -5 | | 3 | Ventral Visual / Fusiform | right | 37.4 | -76.7 | -5 | | 4 | Inferior Frontal Cortex (ventrolateral) | left | -53 | -9.8 | 29.4 | | 5 | Inferior Frontal Cortex (ventrolateral) | right | 53.7 | -9.8 | 29.4 | | 6 | Lateral / Inferior Temporal Cortex | left | -53.8 | -22.1 | 6.3 | | 7 | Lateral / Inferior Temporal Cortex | right | 54.8 | -22.4 | 6.5 | | 8 | Superior Parietal / Dorsal Parietal | left | -38 | -26.3 | 56.7 | | 9 | Superior Parietal / Dorsal Parietal | right | 38 | -26.1 | 57 | | 10 | Precuneus / Superior Medial Parietal | left | -23.1 | -60.8 | 53.6 | | 11 | Precuneus / Superior Medial Parietal | right | 23.2 | -60.5 | 53.6 | | 12 | Lateral Occipital Cortex | left | -47.2 | -66.9 | 9.1 | | 13 | Lateral Occipital Cortex | right | 46.8 | -67 | 9 | | 14 | Intraparietal / Temporal-Parieto-Occipital junction | left | -36.4 | -74.5 | 37.4 | | 15 | Intraparietal / Temporal-Parieto-Occipital junction | right | 36.5 | -74.2 | 37.6 | | 16 | Anterior Ventral Temporal / Temporal Pole | left | -50.7 | -5.5 | -16.6 | | 17 | Anterior Ventral Temporal / Temporal Pole | right | 51 | -5.1 | -16.8 | | 18 | Supplementary Motor Area / Medial Motor | left | -10.7 | -29.1 | 64.6 | | 19 | Supplementary Motor Area / Medial Motor | right | 10.9 | -29.2 | 64.9 | | 20 | Inferior Parietal (angular / supramarginal) | left | -55.6 | -47 | 33.6 | | 21 | Inferior Parietal (angular / supramarginal) | right | 55.8 | -46.9 | 33.7 | | 22 | Inferior Frontal / Ventrolateral PFC | left | -42.4 | 29.5 | 11.9 | | 23 | Inferior Frontal / Ventrolateral PFC | right | 42.8 | 29.9 | 12 | | 24 | Occipital pole / Primary Visual Cortex (ventral) | left | -19.9 | -94.4 | 6.5 | | 25 | Occipital pole / Primary Visual Cortex (ventral) | right | 20.9 | -93.6 | 6.6 | | 26 | Superior Frontal / Dorsomedial PFC | left | -22.9 | 10 | 56.1 | | 27 | Superior Frontal / Dorsomedial PFC | right | 23 | 10 | 56.1 | | 28 | Superior Dorsolateral Prefrontal Cortex | left | -14.7 | 36.9 | 46.9 | | 29 | Superior Dorsolateral Prefrontal Cortex | right | 14.6 | 37.4 | 46.7 | | 30 | Orbital / Polar Frontal Cortex | left | -31.9 | 52.2 | -4.9 | | 31 | Orbital / Polar Frontal Cortex | right | 32.7 | 51.9 | -5.1 | | 32 | Temporo-parietal junction / posterior STS | left | -57.7 | -47.6 | -1.4 | | 33 | Temporo-parietal junction / posterior STS | right | 58.3 | -47.3 | -1.3 | | 34 | Medial Prefrontal / Anterior Cingulate | left | -20.8 | 54.7 | 19.8 | | 35 | Medial Prefrontal / Anterior Cingulate | right | 20.9 | 55 | 19.8 | | 36 | Posterior Cingulate / Midline Precuneus | midline | 0.5 | -60.4 | 33.8 | | 37 | Anterior Cingulate / Medial Prefrontal (midline) | midline | 0.1 | 44.7 | 10.5 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` # user_guide/parcellations/giles39.html.md # Giles39 Parcellation This parcellation file is named `atlas-Giles_nparc-39_space-MNI_res-8x8x8.nii.gz`. It was previously named `fmri_d100_parcellation_with_PCC_tighterMay15_v2_8mm.nii.gz` (osl-dynamics accepts both). This is a modified version of the [original Giles parcellation](user_guide/parcellations/giles38.html.md) to include the PCC. This parcellation was used in [Quinn et al. (2018)](https://www.frontiersin.org/journals/neuroscience/articles/10.3389/fnins.2018.00603/full). It is also available at 2 mm as `atlas-Giles_nparc-39_space-MNI_res-2x2x2.nii.gz` (previously `fmri_d100_parcellation_with_PCC_tighterMay15_v2_2mm.nii.gz` in osl-ephys). ## Parcels ![Giles39 Parcellation](user_guide/parcellations/giles39.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|------------------------------------------------------------|--------------|-------|-------|-------| | 0 | Primary / Early Visual Cortex (dorsal) | left | -11.8 | -84.1 | 18.7 | | 1 | Primary / Early Visual Cortex (dorsal) | right | 16 | -81 | 19.9 | | 2 | Ventral Visual / Fusiform | left | -34.8 | -72.1 | 0.5 | | 3 | Ventral Visual / Fusiform / Lateral Occipital | right | 34.1 | -65.1 | 0.7 | | 4 | Inferior Frontal / Ventrolateral PFC | left | -50.8 | -11.1 | 31.3 | | 5 | Inferior Frontal / Ventrolateral PFC | right | 51.2 | -9.4 | 31.1 | | 6 | Lateral / Inferior Temporal Cortex | left | -52.9 | -21.6 | 5.6 | | 7 | Lateral / Inferior Temporal Cortex | right | 55.5 | -17.5 | 4.6 | | 8 | Posterior Superior Temporal / TPJ-ish (right-dominant) | right | 47.8 | -50.6 | 44.8 | | 9 | Superior Parietal / Dorsal Parietal | left | -33.8 | -25.7 | 57.1 | | 10 | Precuneus / Superior Medial Parietal | left | -25.6 | -60 | 49.6 | | 11 | Precuneus / Superior Medial Parietal | right | 26.5 | -58.6 | 51.5 | | 12 | Lateral Occipital / Posterior Temporal | left | -46.7 | -62.5 | 3.7 | | 13 | Lateral Occipital / Posterior Temporal | right | 45.7 | -58 | 3.3 | | 14 | Intraparietal / Temporal-Parieto-Occipital junction (TPOJ) | left | -32.4 | -73.3 | 40.2 | | 15 | Anterior Ventral Temporal / Temporal Pole | left | -45.3 | -7.9 | -12.9 | | 16 | Anterior Ventral Temporal / Temporal Pole | right | 41.9 | -2 | -19.7 | | 17 | Supplementary Motor Area / Medial Motor | left | -13.2 | -26.8 | 62.5 | | 18 | Supplementary Motor Area / Medial Motor | right | 15 | -25.8 | 63.2 | | 19 | Posterior Intraparietal / dorsal parietal | right | 32.1 | -68.7 | 31.5 | | 20 | Inferior Parietal / Angular / Supramarginal (right) | right | 57.4 | -31.5 | 38.8 | | 21 | Inferior Parietal / Angular / Supramarginal (left) | left | -55.3 | -47.5 | 27.6 | | 22 | Inferior Parietal / Angular / Supramarginal (right) | right | 56.7 | -41.3 | 29.5 | | 23 | Ventrolateral PFC / Inferior Frontal | left | -30.7 | 26.5 | 13.6 | | 24 | Ventrolateral PFC / Inferior Frontal | right | 42.2 | 27.7 | 8 | | 25 | Occipital pole / Primary Visual Cortex (ventral) | left | -20.4 | -92.3 | 5.8 | | 26 | Occipital pole / Primary Visual Cortex (ventral) | right | 22.9 | -88.7 | 8.4 | | 27 | Lateral Temporal / Middle Temporal (anterior) | left | -22.8 | 18.9 | 43.5 | | 28 | Lateral Temporal / Middle Temporal (anterior) | right | 25.4 | 20.7 | 38.7 | | 29 | Dorsolateral PFC / Superior Frontal | right | 22.1 | 41.4 | 28.5 | | 30 | Dorsolateral PFC / Superior Frontal | left | -15.2 | 36.7 | 42.7 | | 31 | Medial / Orbital frontal cluster | left | -27.5 | 43.4 | 4.9 | | 32 | Lateral frontal cluster | right | 30.5 | 29.1 | 5.8 | | 33 | Inferior Parietal / posterior temporal (left) | left | -52.7 | -49.6 | 10.7 | | 34 | Inferior Parietal / posterior temporal (right) | right | 60.1 | -39.7 | -2.7 | | 35 | Dorsomedial / medial prefrontal | left | -18.9 | 47.5 | 22 | | 36 | Dorsomedial / medial prefrontal | right | 21.8 | 51.6 | 21.6 | | 37 | Posterior Cingulate / Midline Precuneus | midline | 0.4 | -60.1 | 33.9 | | 38 | Anterior Cingulate / Medial Prefrontal (midline) | midline | 0.1 | 44.1 | 10.4 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Giles_nparc-39_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` # user_guide/parcellations/giles42.html.md # Giles42 Parcellation This parcellation file is named `atlas-Giles_nparc-42_space-MNI_res-8x8x8.nii.gz`. It was previously named `fmri_d100_parcellation_with_3PCC_ips_reduced_2mm_ss5mm_ds8mm_adj.nii.gz` (osl-dynamics accepts both). This is a modified version of the [original Giles parcellation](user_guide/parcellations/giles38.html.md) to include the PCC plus 2 other parcels near it. This parcellation was used in [Vidaurre et al. (2018)](https://www.nature.com/articles/s41467-018-05316-z). ## Parcels ![Giles42 Parcellation](user_guide/parcellations/giles42.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|------------------------------------------------------------|--------------|-------|-------|-------| | 0 | Primary / Early Visual Cortex (dorsal) | left | -10 | -87.4 | 23.3 | | 1 | Primary / Early Visual Cortex (dorsal) | right | 10.2 | -86.7 | 23.2 | | 2 | Ventral Visual / Fusiform | left | -37.4 | -76.7 | -5 | | 3 | Ventral Visual / Fusiform | right | 37.4 | -76.7 | -5 | | 4 | Inferior Frontal Cortex (ventrolateral / IFG) | left | -53 | -9.8 | 29.4 | | 5 | Inferior Frontal Cortex (ventrolateral / IFG) | right | 53.7 | -9.8 | 29.4 | | 6 | Lateral / Inferior Temporal Cortex | left | -53.8 | -22.1 | 6.3 | | 7 | Lateral / Inferior Temporal Cortex | right | 54.8 | -22.4 | 6.5 | | 8 | Superior Parietal / Dorsal Parietal | left | -38 | -26.3 | 56.7 | | 9 | Superior Parietal / Dorsal Parietal | right | 38 | -26.1 | 57 | | 10 | Precuneus / Superior Medial Parietal | left | -23.1 | -60.8 | 53.6 | | 11 | Precuneus / Superior Medial Parietal | right | 23.2 | -60.5 | 53.6 | | 12 | Lateral Occipital Cortex | left | -47.2 | -66.9 | 9.1 | | 13 | Lateral Occipital Cortex | right | 46.8 | -67 | 9 | | 14 | Intraparietal / Temporal-Parieto-Occipital junction (TPOJ) | left | -36.4 | -74.5 | 37.4 | | 15 | Intraparietal / Temporal-Parieto-Occipital junction (TPOJ) | right | 36.5 | -74.2 | 37.6 | | 16 | Anterior Ventral Temporal / Temporal Pole | left | -50.7 | -5.5 | -16.6 | | 17 | Anterior Ventral Temporal / Temporal Pole | right | 51 | -5.1 | -16.8 | | 18 | Supplementary Motor Area / Medial Motor | left | -10.7 | -29.1 | 64.6 | | 19 | Supplementary Motor Area / Medial Motor | right | 10.9 | -29.2 | 64.9 | | 20 | Inferior Parietal (angular / supramarginal) | left | -55.6 | -47 | 33.6 | | 21 | Inferior Parietal (angular / supramarginal) | right | 55.8 | -46.9 | 33.7 | | 22 | Ventrolateral PFC / Inferior Frontal (mid-lateral) | left | -42.4 | 29.5 | 11.9 | | 23 | Ventrolateral PFC / Inferior Frontal (mid-lateral) | right | 42.8 | 29.9 | 12 | | 24 | Occipital pole / Primary Visual Cortex (ventral) | left | -19.9 | -94.4 | 6.5 | | 25 | Occipital pole / Primary Visual Cortex (ventral) | right | 20.9 | -93.6 | 6.6 | | 26 | Dorsomedial / Superior Frontal (dorsomedial PFC) | left | -22.9 | 10 | 56.1 | | 27 | Dorsomedial / Superior Frontal (dorsomedial PFC) | right | 23 | 10 | 56.1 | | 28 | Superior Dorsolateral Prefrontal Cortex (dlPFC / SFG) | left | -14.7 | 36.9 | 46.9 | | 29 | Superior Dorsolateral Prefrontal Cortex (dlPFC / SFG) | right | 14.6 | 37.4 | 46.7 | | 30 | Orbital / Polar Frontal Cortex | left | -31.9 | 52.2 | -4.9 | | 31 | Orbital / Polar Frontal Cortex | right | 32.7 | 51.9 | -5.1 | | 32 | Temporo-parietal junction / posterior STS | left | -57.7 | -47.6 | -1.4 | | 33 | Temporo-parietal junction / posterior STS | right | 58.3 | -47.3 | -1.3 | | 34 | Medial Prefrontal / Anterior Cingulate | left | -20.8 | 54.7 | 19.8 | | 35 | Medial Prefrontal / Anterior Cingulate | right | 20.9 | 55 | 19.8 | | 36 | Anterior Cingulate / Medial Prefrontal (midline) | midline | 0.1 | 44.7 | 10.5 | | 37 | Midline Precuneus / Posterior Cingulate | midline | 1.4 | -67.2 | 36.1 | | 38 | Midline Posterior Cingulate / posterior medial cortex | midline | 1.1 | -48.6 | 23.8 | | 39 | Midline Superior Precuneus / dorsal medial parietal | midline | 0.9 | -55.1 | 49 | | 40 | Posterior Cingulate / Posterior Medial Cortex | left | -44.7 | -59.3 | 23.7 | | 41 | Posterior Cingulate / Posterior Medial Cortex | right | 47.4 | -58.7 | 23.7 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Giles_nparc-42_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` # user_guide/parcellations/glasser50.html.md # Glasser50 Parcellation In osl-dynamics, this parcellation file is named `atlas-Glasser_nparc-50_space-MNI_res-8x8x8.nii.gz`, however, this parcellation file was previously named `Glasser50_binary_space-MNI152NLin6_res-8x8x8.nii.gz` (both names will work). This is a reduced version of the [Glasser52 parcellation](user_guide/parcellations/glasser52.html.md). ## Parcels ![Glasser50 Parcellation](user_guide/parcellations/glasser50.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|-------------------------------------------------|--------------|-------|-------|-------| | 0 | Primary and Early Visual Cortex | right | 13.9 | -80.1 | 1 | | 1 | Dorsal Stream Visual Cortex | right | 19.1 | -80.8 | 31.9 | | 2 | Ventral Stream Visual Cortex | right | 29.2 | -57.3 | -16.4 | | 3 | MT+ Complex and Neighboring Visual Areas | right | 43.6 | -71.8 | -0.7 | | 4 | Somatosensory and Motor Cortex | right | 37.7 | -21.8 | 50.1 | | 5 | Supplementary Motor Area | right | 12.9 | -1.1 | 63.8 | | 6 | Cingulate Motor Areas & Area 5 | right | 7.9 | -29.9 | 52.3 | | 7 | Premotor Cortex | right | 42.5 | 1.2 | 40.4 | | 8 | Insular & Frontoparietal Operculum | right | 40.6 | 1.2 | 2.9 | | 9 | Early Auditory Cortex | right | 46.3 | -23.3 | 12.2 | | 10 | Auditory Association Cortex | right | 55.6 | -12.4 | -7.1 | | 11 | Medial Temporal Cortex | right | 27.5 | -21.7 | -23.9 | | 12 | Lateral Temporal Cortex | right | 48.2 | -15.4 | -25.9 | | 13 | Temporal-Parieto-Occipital Junction | right | 54.9 | -46.9 | 12.6 | | 14 | Medial Bank of the Intra-parietal Sulcus | right | 29.6 | -51.6 | 44.6 | | 15 | Superior Medial Parietal Cortex | right | 18.5 | -57.9 | 59.1 | | 16 | Inferior Parietal Cortex Task-Positive Network | right | 57.2 | -29.3 | 35 | | 17 | Inferior Parietal Cortex Task-Negative Network | right | 47.7 | -57.7 | 35 | | 18 | Intraparietal Sulcus & PGP | right | 36 | -71.7 | 31.9 | | 19 | Posterior Cingulate Cortex | right | 8.9 | -55.8 | 27.7 | | 20 | Anterior Cingulate and Medial Prefrontal Cortex | right | 5.2 | 34.2 | 15.3 | | 21 | Orbital and Polar Frontal Cortex | right | 18.5 | 45.8 | -11.8 | | 22 | Inferior Frontal Cortex | right | 45.1 | 32.9 | 2.8 | | 23 | Inferior Dorso-Lateral Prefrontal Cortex | right | 36.7 | 37.3 | 25.6 | | 24 | Superior Dorso-Lateral Prefrontal Cortex | right | 20.8 | 32.9 | 45.4 | | 25 | Primary and Early Visual Cortex | left | -13.9 | -81.5 | 1.3 | | 26 | Dorsal Stream Visual Cortex | left | -21.4 | -82.5 | 29.5 | | 27 | Ventral Stream Visual Cortex | left | -34 | -57.4 | -17.4 | | 28 | MT+ Complex and Neighboring Visual Areas | left | -47 | -69.7 | -2.5 | | 29 | Somatosensory and Motor Cortex | left | -36.2 | -24.7 | 52 | | 30 | Supplementary Motor Area | left | -12.6 | -1.7 | 62.7 | | 31 | Cingulate Motor Areas & Area 5 | left | -10.5 | -28.4 | 51.6 | | 32 | Premotor Cortex | left | -42.7 | -0.7 | 42.5 | | 33 | Insular & Frontoparietal Operculum | left | -43.2 | 0 | 2.9 | | 34 | Early Auditory Cortex | left | -49.1 | -25.9 | 10.6 | | 35 | Auditory Association Cortex | left | -57 | -14.8 | -7.4 | | 36 | Medial Temporal Cortex | left | -30.6 | -22.6 | -24.2 | | 37 | Lateral Temporal Cortex | left | -50.4 | -17.8 | -24.9 | | 38 | Temporal-Parieto-Occipital Junction | left | -55.9 | -52.2 | 13.8 | | 39 | Medial Bank of the Intra-parietal Sulcus | left | -32.7 | -52.2 | 43 | | 40 | Superior Medial Parietal Cortex | left | -19 | -59.7 | 57.2 | | 41 | Inferior Parietal Cortex Task-Positive Network | left | -57.8 | -35.2 | 34.3 | | 42 | Inferior Parietal Cortex Task-Negative Network | left | -47.1 | -63.1 | 33.5 | | 43 | Intraparietal Sulcus & PGP | left | -37 | -71.4 | 31.7 | | 44 | Posterior Cingulate Cortex | left | -8.6 | -52.2 | 29.7 | | 45 | Anterior Cingulate and Medial Prefrontal Cortex | left | -6.1 | 34.8 | 12.2 | | 46 | Orbital and Polar Frontal Cortex | left | -21.2 | 44 | -10.2 | | 47 | Inferior Frontal Cortex | left | -46.4 | 28.4 | 5.6 | | 48 | Inferior Dorso-Lateral Prefrontal Cortex | left | -38.9 | 36.4 | 24.3 | | 49 | Superior Dorso-Lateral Prefrontal Cortex | left | -22.8 | 29.5 | 46.9 | ## Example Code Example code for plotting with this parcellation: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Glasser_nparc-50_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` # user_guide/parcellations/glasser52.html.md # Glasser52 Parcellation In osl-dynamics, this parcellation file is named `atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz`, however, this parcellation file was previously named `Glasser52_binary_space-MNI152NLin6_res-8x8x8.nii.gz` (both names will work). This parcellation was based on the [HCP-MMP](https://pmc.ncbi.nlm.nih.gov/articles/PMC4990127/) atlas. It is also available at 2 mm as `atlas-Glasser_nparc-52_space-MNI_res-2x2x2.nii.gz`, for use with fMRI on the MNI152 2 mm grid. Both come from the same [Zenodo deposit](https://doi.org/10.5281/zenodo.11099418) (Kohl, Woolrich, Nobre and Quinn), where they are named `Glasser52_binary_space-MNI152NLin6_res-{8x8x8,2x2x2}.nii.gz`; the parcels are binary, non-overlapping and in the same order at both resolutions. The coordinates below are from the 8 mm file. ## Parcels ![Glasser52 Parcellation](user_guide/parcellations/glasser52.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|-------------------------------------------------|--------------|-------|-------|-------| | 0 | Primary and Early Visual Cortex | right | 14.5 | -80.5 | -0.4 | | 1 | Dorsal Stream Visual Cortex | right | 19.4 | -81.4 | 30.6 | | 2 | Ventral Stream Visual Cortex | right | 29.9 | -57.6 | -17.7 | | 3 | MT+ Complex and Neighboring Visual Areas | right | 42.2 | -71.5 | 0 | | 4 | Superior Somatosensory and Motor Cortex | right | 23.6 | -29.5 | 61 | | 5 | Inferior Somatosensory and Motor Cortex | right | 49.1 | -13.4 | 38.3 | | 6 | Supplementary Motor Area | right | 12.7 | -2.2 | 62.9 | | 7 | Cingulate Motor Areas & Area 5 | right | 10 | -31.2 | 53.6 | | 8 | Premotor Cortex | right | 40.9 | 0.9 | 41.1 | | 9 | Insular & Frontoparietal Operculum | right | 37.7 | 1.6 | 4 | | 10 | Early Auditory Cortex | right | 40.2 | -27.5 | 13.5 | | 11 | Auditory Association Cortex | right | 55 | -14 | -6.5 | | 12 | Medial Temporal Cortex | right | 25 | -22.1 | -22.1 | | 13 | Lateral Temporal Cortex | right | 48.5 | -16.3 | -25.3 | | 14 | Temporal-Parieto-Occipital Junction | right | 52.1 | -48.1 | 12.3 | | 15 | Medial Bank of the Intra-parietal Sulcus | right | 29.5 | -51 | 43 | | 16 | Superior Medial Parietal Cortex | right | 19.1 | -58.4 | 59.6 | | 17 | Inferior Parietal Cortex Task-Positive Network | right | 56.7 | -29.7 | 35.7 | | 18 | Inferior Parietal Cortex Task-Negative Network | right | 47.4 | -56.1 | 35.8 | | 19 | Intraparietal Sulcus & PGP | right | 36.5 | -71.1 | 32.6 | | 20 | Posterior Cingulate Cortex | right | 10.3 | -55.1 | 26.8 | | 21 | Anterior Cingulate and Medial Prefrontal Cortex | right | 6.1 | 33.8 | 14.2 | | 22 | Orbital and Polar Frontal Cortex | right | 17.1 | 47 | -11.6 | | 23 | Inferior Frontal Cortex | right | 45.4 | 32.5 | 3.8 | | 24 | Inferior Dorso-Lateral Prefrontal Cortex | right | 34.8 | 37.1 | 25.7 | | 25 | Superior Dorso-Lateral Prefrontal Cortex | right | 21 | 31.9 | 45.9 | | 26 | Primary and Early Visual Cortex | left | -16.9 | -82 | -0.9 | | 27 | Dorsal Stream Visual Cortex | left | -21.7 | -84.3 | 27 | | 28 | Ventral Stream Visual Cortex | left | -34.5 | -56 | -18.6 | | 29 | MT+ Complex and Neighboring Visual Areas | left | -45.2 | -70.3 | -1.4 | | 30 | Superior Somatosensory and Motor Cortex | left | -22.6 | -30.4 | 62.8 | | 31 | Inferior Somatosensory and Motor Cortex | left | -48.3 | -18.7 | 41.7 | | 32 | Supplementary Motor Area | left | -14 | -2.7 | 62.7 | | 33 | Cingulate Motor Areas & Area 5 | left | -14.4 | -30.6 | 49.7 | | 34 | Premotor Cortex | left | -40.3 | -1.7 | 43.8 | | 35 | Insular & Frontoparietal Operculum | left | -41.3 | 0.1 | 3.7 | | 36 | Early Auditory Cortex | left | -45.4 | -29.4 | 12.1 | | 37 | Auditory Association Cortex | left | -55.3 | -17.3 | -7.8 | | 38 | Medial Temporal Cortex | left | -27.9 | -22.2 | -22.6 | | 39 | Lateral Temporal Cortex | left | -49.6 | -17.9 | -25.1 | | 40 | Temporal-Parieto-Occipital Junction | left | -53.1 | -54 | 14.5 | | 41 | Medial Bank of the Intra-parietal Sulcus | left | -31.1 | -50 | 41.1 | | 42 | Superior Medial Parietal Cortex | left | -21.3 | -60.5 | 58.2 | | 43 | Inferior Parietal Cortex Task-Positive Network | left | -56.6 | -36.3 | 36.6 | | 44 | Inferior Parietal Cortex Task-Negative Network | left | -45.1 | -63.4 | 35.2 | | 45 | Intraparietal Sulcus & PGP | left | -36.7 | -70 | 30.4 | | 46 | Posterior Cingulate Cortex | left | -11.6 | -49.5 | 28 | | 47 | Anterior Cingulate and Medial Prefrontal Cortex | left | -8.7 | 32 | 11.4 | | 48 | Orbital and Polar Frontal Cortex | left | -21.9 | 46.3 | -8.1 | | 49 | Inferior Frontal Cortex | left | -45.1 | 28.2 | 7.7 | | 50 | Inferior Dorso-Lateral Prefrontal Cortex | left | -37.2 | 36.2 | 25.2 | | 51 | Superior Dorso-Lateral Prefrontal Cortex | left | -23.5 | 28.6 | 45.7 | ## Example Code Example code for plotting with this parcellation: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Kohl, O., Woolrich, M., Nobre, A. C., & Quinn, A. (2023). Glasser52: A parcellation for MEG-Analysis [Data set]. Zenodo. https://doi.org/10.5281/zenodo.10401793 ``` # user_guide/parcellations/index.html.md # Parcellations The parcellation files themselves are in [`parcellation/`](https://github.com/OHBA-analysis/osl-files/tree/main/parcellation). They are downloaded on demand by the OSL packages, so you do not need to fetch them by hand. ## Available Parcellations ### Desikan-Killiany parcellations - [atlas-DK_nparc-68_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/dk68.html.md) - [atlas-DK_nparc-54_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/dk54.html.md) ### Glasser parcellations - [atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/glasser52.html.md) - [atlas-Glasser_nparc-52_space-MNI_res-2x2x2.nii.gz](user_guide/parcellations/glasser52.html.md) - [atlas-Glasser_nparc-50_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/glasser50.html.md) ### Giles parcellations - [atlas-Giles_nparc-42_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/giles42.html.md) - [atlas-Giles_nparc-39_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/giles39.html.md) - [atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/giles38.html.md) - [atlas-Giles_nparc-39_space-MNI_res-2x2x2.nii.gz](user_guide/parcellations/giles39.html.md) - [atlas-Giles_nparc-38_space-MNI_res-2x2x2.nii.gz](user_guide/parcellations/giles38.html.md) ### Schaefer parcellations - [atlas-Schaefer_nparc-100_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/schaefer100.html.md) - [atlas-Schaefer_nparc-100_space-MNI_res-5x5x5.nii.gz](user_guide/parcellations/schaefer100.html.md) - [atlas-Schaefer_nparc-100_space-MNI_res-2x2x2.nii.gz](user_guide/parcellations/schaefer100.html.md) ### AAL parcellations - [atlas-AAL_nparc-116_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/aal116.html.md) - [atlas-AAL_nparc-78_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/aal78.html.md) - [atlas-AAL_nparc-24_space-MNI_res-8x8x8.nii.gz](user_guide/parcellations/aal24.html.md) Parcellation file that have no maintained counterpart are kept under their original names in [`parcellation/legacy/`](https://github.com/OHBA-analysis/osl-files/tree/main/parcellation/legacy). ## Old Naming Note, the parcellation files in osl-dynamics and osl-ephys have been renamed: | New name | Old name | |------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------| | atlas-DK_nparc-68_space-MNI_res-8x8x8.nii.gz | dk_cortical.nii.gz | | atlas-Glasser_nparc-52_space-MNI_res-8x8x8.nii.gz | Glasser52_binary_space-MNI152NLin6_res-8x8x8.nii.gz | | atlas-Glasser_nparc-52_space-MNI_res-2x2x2.nii.gz | Glasser52_binary_space-MNI152NLin6_res-2x2x2.nii.gz | | atlas-Glasser_nparc-50_space-MNI_res-8x8x8.nii.gz | Glasser50_space-MNI152NLin6_res-8x8x8.nii.gz | | atlas-Giles_nparc-42_space-MNI_res-8x8x8.nii.gz | fmri_d100_parcellation_with_3PCC_ips_reduced_2mm_ss5mm_ds8mm_adj.nii.gz | | atlas-Giles_nparc-39_space-MNI_res-8x8x8.nii.gz | fmri_d100_parcellation_with_PCC_tighterMay15_v2_8mm.nii.gz | | atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz | fmri_d100_parcellation_with_PCC_reduced_2mm_ss5mm_ds8mm.nii.gz | | atlas-Giles_nparc-38_space-MNI_res-2x2x2.nii.gz | fMRI_parcellation_ds2mm.nii.gz (in [OHBA-analysis/parcellations](https://github.com/OHBA-analysis/parcellations)) | | atlas-AAL_nparc-78_space-MNI_res-8x8x8.nii.gz | aal_cortical_merged_8mm_stacked.nii.gz | | atlas-Giles_nparc-38_space-MNI_res-8x8x8.nii.gz | fMRI_parcellation_ds8mm.nii.gz (osl-ephys) | | atlas-Giles_nparc-39_space-MNI_res-2x2x2.nii.gz | fmri_d100_parcellation_with_PCC_tighterMay15_v2_2mm.nii.gz (osl-ephys) | | atlas-Schaefer_nparc-100_space-MNI_res-2x2x2.nii.gz | Schaefer2018_100Parcels_7Networks_order_FSLMNI152_2mm_4d.nii.gz (osl-ephys) | | atlas-Schaefer_nparc-100_space-MNI_res-8x8x8.nii.gz | Schaefer2018_100Parcels_7Networks_order_FSLMNI152_2mm_4d_ds8.nii.gz (osl-ephys) | | atlas-SchaeferHarvOxf_nparc-114_space-MNI_res-2x2x2.nii.gz | HarvOxf-sub-Schaefer100-combined-2mm_4d.nii.gz (osl-ephys) | | atlas-SchaeferHarvOxf_nparc-114_space-MNI_res-8x8x8.nii.gz | HarvOxf-sub-Schaefer100-combined-2mm_4d_ds8.nii.gz (osl-ephys) | | atlas-HarvOxfSub_nparc-21_space-MNI_res-2x2x2.nii.gz | HarvardOxford-sub-prob-bin-2mm.nii.gz (osl-ephys) | ## MNI Coordinates The parcellations provided are in MNI space. Obtaining the MNI coordinates of each parcel center, using osl-dynamics: ```python from osl_dynamics.meeg.parcellation import Parcellation filename = 'atlas-Giles_nparc-42_space-MNI_res-8x8x8.nii.gz' parc = Parcellation(filename) mni_coords = parc.roi_centers() ``` # user_guide/parcellations/schaefer100.html.md # Schaefer100 Parcellation This parcellation is a volumetric version of the Schaefer 100-parcel cortical parcellation from [Schaefer et al. (2018)](https://doi.org/10.1093/cercor/bhx179). The parcels are derived from resting-state fMRI functional connectivity gradients. It is also available at 2 mm as `atlas-Schaefer_nparc-100_space-MNI_res-2x2x2.nii.gz` (previously `Schaefer2018_100Parcels_7Networks_order_FSLMNI152_2mm_4d.nii.gz` in osl-ephys; its `_ds8` file is the 8 mm one). ## Parcels ![Schaefer100 Parcellation](user_guide/parcellations/schaefer100.png) Labels and MNI coordinates: | Index | Parcel | Hemisphere | X | Y | Z | |---------|----------------------------------------------------------|--------------|-------|-------|-------| | 0 | Visual 1 | left | -26 | -32 | -20 | | 1 | Visual 2 | left | -28.1 | -74.7 | -12.7 | | 2 | Visual 3 | left | -15.8 | -60.8 | -6.8 | | 3 | Visual 4 | left | -27.6 | -94.3 | -4.2 | | 4 | Visual 5 | left | -6 | -92.8 | -2.5 | | 5 | Visual 6 | left | -12.9 | -63.1 | 5.3 | | 6 | Visual 7 | left | -46 | -71.1 | 12 | | 7 | Visual 8 | left | -25.5 | -88.5 | 20.5 | | 8 | Visual 9 | left | -7.3 | -81.1 | 25.3 | | 9 | Somatomotor 1 | left | -51.2 | -23.2 | 7.6 | | 10 | Somatomotor 2 | left | -38 | -22 | 16 | | 11 | Somatomotor 3 | left | -54.4 | -12.7 | 13.8 | | 12 | Somatomotor 4 | left | -54.6 | -8.9 | 33.1 | | 13 | Somatomotor 5 | left | -40.6 | -23 | 59.1 | | 14 | Somatomotor 6 | left | -12.2 | -27.3 | 63.8 | | 15 | Dorsal Attention Posterior 1 | left | -47.3 | -55.5 | -12.8 | | 16 | Dorsal Attention Posterior 2 | left | -57 | -25.5 | 38.5 | | 17 | Dorsal Attention Posterior 3 | left | -24.6 | -67.8 | 49 | | 18 | Dorsal Attention Posterior 4 | left | -39.1 | -34.6 | 49.1 | | 19 | Dorsal Attention Posterior 5 | left | -6.7 | -62 | 56.7 | | 20 | Dorsal Attention Posterior 6 | left | -23.7 | -52.3 | 66.3 | | 21 | Dorsal Attention Precentral Ventral 1 | left | -48.7 | 6 | 28 | | 22 | Dorsal Attention Frontal Eye Field 1 | left | -25.7 | -4.3 | 59.1 | | 23 | Salience/Ventral Attention Parietal Operculum 1 | left | -57.7 | -38 | 29.3 | | 24 | Salience/Ventral Attention Frontal Operculum/Insula 1 | left | -41 | -1.5 | -5.5 | | 25 | Salience/Ventral Attention Frontal Operculum/Insula 2 | left | -38.7 | 11.5 | 6.5 | | 26 | Salience/Ventral Attention Lateral Prefrontal Cortex 1 | left | -29.4 | 43.6 | 29.1 | | 27 | Salience/Ventral Attention Medial 1 | left | -6.4 | 21.8 | 32 | | 28 | Salience/Ventral Attention Medial 2 | left | -11.1 | -34.4 | 45.8 | | 29 | Salience/Ventral Attention Medial 3 | left | -7.7 | 3.7 | 62.9 | | 30 | Limbic Orbitofrontal Cortex 1 | left | -16 | 30.5 | -20.2 | | 31 | Limbic Temporal Pole 1 | left | -32.8 | -0.6 | -34.6 | | 32 | Limbic Temporal Pole 2 | left | -56.1 | -29.1 | -24 | | 33 | Control Parietal 1 | left | -37 | -54 | 46 | | 34 | Control Lateral Prefrontal Cortex 1 | left | -43.3 | 32.2 | 21 | | 35 | Control Precuneus 1 | left | -10.4 | -73.6 | 38.2 | | 36 | Control Cingulate 1 | left | -6 | -28 | 32 | | 37 | Default Mode Temporal 1 | left | -54.5 | -2.2 | -20.2 | | 38 | Default Mode Temporal 2 | left | -55.3 | -30.4 | -1.8 | | 39 | Default Mode Parietal 1 | left | -56.9 | -51.1 | 10.9 | | 40 | Default Mode Parietal 2 | left | -47.1 | -63.3 | 35.4 | | 41 | Default Mode Prefrontal Cortex 1 | left | -35.6 | 22 | -9.6 | | 42 | Default Mode Prefrontal Cortex 2 | left | -45.5 | 34.5 | -0.9 | | 43 | Default Mode Prefrontal Cortex 3 | left | -6.4 | 46.8 | -2.4 | | 44 | Default Mode Prefrontal Cortex 4 | left | -23 | 60.3 | -2.7 | | 45 | Default Mode Prefrontal Cortex 5 | left | -10.7 | 44.7 | 40.2 | | 46 | Default Mode Prefrontal Cortex 6 | left | -41.2 | 12.7 | 48.5 | | 47 | Default Mode Prefrontal Cortex 7 | left | -25.2 | 18.5 | 51.7 | | 48 | Default Mode Precuneus/Posterior Cingulate 1 | left | -12 | -55 | 12 | | 49 | Default Mode Precuneus/Posterior Cingulate 2 | left | -7.9 | -52.1 | 32 | | 50 | Visual 1 | right | 31 | -29.3 | -21.7 | | 51 | Visual 2 | right | 27.9 | -63.5 | -12.2 | | 52 | Visual 3 | right | 48.5 | -60.2 | -10.5 | | 53 | Visual 4 | right | 22.9 | -93.3 | -4.2 | | 54 | Visual 5 | right | 7.9 | -77.7 | 4.5 | | 55 | Visual 6 | right | 17.1 | -55.9 | 5.2 | | 56 | Visual 7 | right | 36.9 | -82.4 | 17.1 | | 57 | Visual 8 | right | 12.9 | -85.3 | 29.8 | | 58 | Somatomotor 1 | right | 53.3 | -16.3 | 6 | | 59 | Somatomotor 2 | right | 40.5 | -14.7 | 13.8 | | 60 | Somatomotor 3 | right | 58 | -5 | 11 | | 61 | Somatomotor 4 | right | 58 | -4.8 | 28.9 | | 62 | Somatomotor 5 | right | 46.6 | -10.6 | 50.3 | | 63 | Somatomotor 6 | right | 38.8 | -22 | 60.8 | | 64 | Somatomotor 7 | right | 33 | -37 | 63 | | 65 | Somatomotor 8 | right | 10.2 | -24 | 66 | | 66 | Dorsal Attention Posterior 1 | right | 50.6 | -62.3 | 16.3 | | 67 | Dorsal Attention Posterior 2 | right | 51.1 | -23.1 | 41.7 | | 68 | Dorsal Attention Posterior 3 | right | 38.4 | -44.7 | 49.3 | | 69 | Dorsal Attention Posterior 4 | right | 26.5 | -66.4 | 50.4 | | 70 | Dorsal Attention Posterior 5 | right | 13.4 | -52.1 | 65.5 | | 71 | Dorsal Attention Precentral Ventral 1 | right | 48.6 | 9.7 | 27.8 | | 72 | Dorsal Attention Frontal Eye Field 1 | right | 28.4 | -4 | 60 | | 73 | Salience/Ventral Attention Temporal-Occipital-Parietal 1 | right | 58 | -42 | 13.1 | | 74 | Salience/Ventral Attention Temporal-Occipital-Parietal 2 | right | 60.4 | -25.3 | 27.8 | | 75 | Salience/Ventral Attention Frontal Operculum/Insula 1 | right | 41.7 | 7.8 | 0 | | 76 | Salience/Ventral Attention Medial 1 | right | 10 | -30.7 | 45.8 | | 77 | Salience/Ventral Attention Medial 2 | right | 7.3 | 6.1 | 52.4 | | 78 | Limbic Orbitofrontal Cortex 1 | right | 12.4 | 37.3 | -19.3 | | 79 | Limbic Temporal Pole 1 | right | 37.8 | 0.4 | -35.6 | | 80 | Control Parietal 1 | right | 57.3 | -40 | 42.7 | | 81 | Control Parietal 2 | right | 44.5 | -62.5 | 46 | | 82 | Control Lateral Prefrontal Cortex 1 | right | 30.2 | 56.8 | -2.5 | | 83 | Control Lateral Prefrontal Cortex 2 | right | 45.8 | 38.6 | 15.6 | | 84 | Control Lateral Prefrontal Cortex 3 | right | 31.1 | 44.9 | 29.8 | | 85 | Control Lateral Prefrontal Cortex 4 | right | 44.4 | 15.6 | 46 | | 86 | Control Cingulate 1 | right | 3.8 | -28.2 | 32.9 | | 87 | Control Medial Posterior Prefrontal Cortex 1 | right | 4.3 | 25.6 | 32.4 | | 88 | Control Precuneus 1 | right | 9.2 | -62.8 | 42.7 | | 89 | Default Mode Parietal 1 | right | 55.1 | -50.6 | 31.4 | | 90 | Default Mode Temporal 1 | right | 61.9 | -25.6 | -17.5 | | 91 | Default Mode Temporal 2 | right | 52.2 | 5.1 | -16.9 | | 92 | Default Mode Temporal 3 | right | 58.4 | -26.4 | -1.8 | | 93 | Default Mode Ventral Prefrontal Cortex 1 | right | 35.5 | 27.5 | -14.5 | | 94 | Default Mode Ventral Prefrontal Cortex 2 | right | 51.3 | 28.1 | 0.4 | | 95 | Default Mode Dorsal/Medial Prefrontal Cortex 1 | right | 5.2 | 47.1 | 0 | | 96 | Default Mode Dorsal/Medial Prefrontal Cortex 2 | right | 11.5 | 44.7 | 40.4 | | 97 | Default Mode Dorsal/Medial Prefrontal Cortex 3 | right | 27.6 | 22 | 51.6 | | 98 | Default Mode Precuneus/Posterior Cingulate 1 | right | 12 | -56 | 17 | | 99 | Default Mode Precuneus/Posterior Cingulate 2 | right | 4.9 | -51.7 | 32 | ## Example code Plotting with this parcellation, using osl-dynamics: ```python from osl_dynamics.analysis import power power.save( ..., mask_file="MNI152_T1_8mm_brain.nii.gz", parcellation_file="atlas-Schaefer_nparc-100_space-MNI_res-8x8x8.nii.gz", filename="map_.png", ) ``` ## Reference If you use this parcellation, please cite: ```none Schaefer, A., Kong, R., Gordon, E. M., Laumann, T. O., Zuo, X.-N., Holmes, A. J., Eickhoff, S. B., & Yeo, B. T. T. (2018). Local-Global Parcellation of the Human Cerebral Cortex from Intrinsic Functional Connectivity MRI. *Cerebral Cortex*, 28(9), 3095-3114. https://doi.org/10.1093/cercor/bhx179 ``` # user_guide/spectra.html.md # Spectral Analysis After training a model on time-delay embedded (TDE) data, we describe each state or mode by its power spectral density (PSD) and coherence. These are calculated from the parcel time courses before time-delay embedding (and PCA), using the inferred state probabilities or mixing coefficients (`alpha`). | Function | Models | Returns | |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | [`regression_spectra()`](autoapi/osl_dynamics/analysis/spectral/regression_spectra.html.md#osl_dynamics.analysis.spectral.regression_spectra) | All models (states and modes) | [`RegressionSpectra`](autoapi/osl_dynamics/analysis/spectral/RegressionSpectra.html.md#osl_dynamics.analysis.spectral.RegressionSpectra): the static spectrum and the change from the static spectrum for each state/mode | | [`multitaper_spectra()`](autoapi/osl_dynamics/analysis/spectral/multitaper_spectra.html.md#osl_dynamics.analysis.spectral.multitaper_spectra) | Models with states (HMM, DyNeStE, HIVE) | [`StateSpectra`](autoapi/osl_dynamics/analysis/spectral/StateSpectra.html.md#osl_dynamics.analysis.spectral.StateSpectra): the spectrum of each state | | [`welch_spectra()`](autoapi/osl_dynamics/analysis/static/welch_spectra.html.md#osl_dynamics.analysis.static.welch_spectra), [`multitaper_spectra()`](autoapi/osl_dynamics/analysis/static/multitaper_spectra.html.md#osl_dynamics.analysis.static.multitaper_spectra) | No model (static analysis) | [`StaticSpectra`](autoapi/osl_dynamics/analysis/spectral/StaticSpectra.html.md#osl_dynamics.analysis.spectral.StaticSpectra): the spectrum of each session | For examples with real data, see the [HMM Multitaper Spectra](tutorials_build/4-1_hmm_multitaper_spectra.html.md) and [HMM Plotting MEG Networks](tutorials_build/4-2_hmm_plotting_meg_networks.html.md) tutorials (multitaper), and the [DyNeMo Regression Spectra](tutorials_build/5-1_dynemo_regression_spectra.html.md) and [DyNeMo Plotting Networks](tutorials_build/5-2_dynemo_plotting_networks.html.md) tutorials (regression). ## Calculating spectra Pass the [`Data`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data) object used for training and the inferred time course for each session (`model.get_gamma(data)` for the HMM, `model.get_alpha(data)` for DyNeMo): ```python from osl_dynamics.analysis import spectral spectra = spectral.multitaper_spectra(data, alpha=alpha, frequency_range=[1, 45]) spectra = spectral.regression_spectra(data, alpha=alpha, frequency_range=[1, 45]) ``` The data before preparation (time-delay embedding, PCA, etc.) is used, aligned to `alpha`. Arrays of parcel time courses can also be passed, with the same number of samples as `alpha` (see [`Data.trim_time_series`](autoapi/osl_dynamics/data/Data.html.md#osl_dynamics.data.Data.trim_time_series)) and the `sampling_frequency`. The result stores the cross spectra of each session, which can be saved and loaded: ```python spectra.save("multitaper.npz") spectra = spectral.Spectra.load("multitaper.npz") ``` Pass `cross_spectra=False` to only calculate the PSDs (no coherence), e.g. for a large number of channels. ### Quantities Each quantity is an attribute of the result. The first axis is the session. | Quantity | PSD, coherence | Shape | |------------------------------------------------------|----------------------------------|-------------------------------------------------------| | State/mode spectrum, $P_j$ | `psd`, `coherence` | (sessions, states, channels, [channels,] frequencies) | | Static spectrum, $S$ | `static_psd`, `static_coherence` | (sessions, channels, [channels,] frequencies) | | Change from the static spectrum, $P_j - S$ | `psd_change`, `coherence_change` | (sessions, states, channels, [channels,] frequencies) | | Regression coefficients, $\beta_j$ (regression only) | `psd_coefs`, `coherence_coefs` | (sessions, modes, channels, [channels,] frequencies) | | Standard deviation, $\sigma_j$ (regression only) | `sigma` | (modes,) | The frequency axis is `frequencies` and the weight of each session in a group average is `session_weights`. `cross_spectra` gives the complex cross spectra, $\langle \bar{X}_x X_y \rangle$. ## Regression spectra The spectrum at time $t$ is modeled as a mixture of the spectra of each state/mode: $$ P_t(f) = \sum_j \alpha_{jt} P_j(f). $$ [`regression_spectra()`](autoapi/osl_dynamics/analysis/spectral/regression_spectra.html.md#osl_dynamics.analysis.spectral.regression_spectra) calculates a spectrogram $P_t$ (cross spectra in a sliding window of `window_length` samples, each split into `n_sub_windows` Hann-tapered sub-windows), averages `alpha` over the same windows and fits the mixture with least squares, i.e. a [GLM-spectrum](https://doi.org/10.1162/imag_a_00082). The frequency resolution is set by the sub-window length, `window_length / n_sub_windows` samples. The default is a 4 second window with 8 sub-windows (2 Hz resolution) and an 80 ms step. ![image](user_guide/models/images/dynemo-regression-spectra.svg) ### Definitions **Static spectrum** $S$. The time-averaged spectrum of the data, $S = \sum_j \bar{\alpha}_j P_j$, where $\bar{\alpha}_j$ is the mean of `alpha` for mode $j$. This is the intercept of the regression. **Mode spectrum** $P_j$. The spectrum when only state/mode $j$ is active. For the HMM, this is the spectrum of the state. For DyNeMo, the mixing coefficients of a mode rarely approach one, so $P_j$ is an extrapolation that doesn’t typically arise. **Standard deviation** $\sigma_j$. The standard deviation of the windowed `alpha` for mode $j$, averaged over sessions. It is the typical size of the fluctuations in a mode’s `alpha` over the window length. **Coefficients** $\beta_j = \sigma_j (P_j - S)$. The change in the spectrum from the static spectrum for a one standard deviation increase in mode $j$’s `alpha`. $P_j = S + \beta_j / \sigma_j$. **Change in coherence** $C_j$ (`coherence_coefs`). The change in the cross spectrum in the direction of the static cross spectrum, normalized by the static power, for a one standard deviation increase in mode $j$’s `alpha`: $$ C_{jxy} = \frac{\text{Re}(\beta_{jxy} e^{-i\phi_{xy}})}{\sqrt{S_{xx} S_{yy}}}, $$ where $\phi_{xy}$ is the phase of $S_{xy}$. It includes changes in both coherence and power: it increases when the coherence between $x$ and $y$ increases or when the power at $x$ or $y$ increases. The diagonal is the relative change in power, $\beta_{jxx} / S_{xx}$. Positive coefficients mean a mode has more power than the static spectrum and negative coefficients mean less. The changes of all modes balance around the static spectrum, so some modes can be negative everywhere: e.g. a DyNeMo mode with a small covariance that takes most of the mixing coefficients. ### Sessions The coefficients of every session are scaled by the same $\sigma_j$, so session-specific spectra have the same units and can be averaged or compared with [statistical tests](user_guide/stats.html.md). - Calculate the spectra for all the sessions you want to compare in one call. To compare spectra from separate calls or different window settings, use `psd_change` ($\beta_j / \sigma_j$). - Session-specific estimates are noisier for sessions where a mode’s `alpha` varies less than $\sigma_j$. - A mode whose `alpha` is (nearly) constant in a session (e.g. an HMM state that is never visited) has NaN coefficients. [`group_average()`](autoapi/osl_dynamics/analysis/spectral/Spectra.html.md#osl_dynamics.analysis.spectral.Spectra.group_average) ignores them. ## Multitaper spectra [`multitaper_spectra()`](autoapi/osl_dynamics/analysis/spectral/multitaper_spectra.html.md#osl_dynamics.analysis.spectral.multitaper_spectra) estimates the spectrum of each state, $P_j$, directly: 1. Multiply the data by the state probability time course, $\alpha_{jt}$, to keep the time points when state $j$ is active. 2. Split the result into non-overlapping windows. A window twice the sampling frequency gives a frequency resolution of 0.5 Hz. 3. Multiply each window by several tapers (hence the name ‘multitaper’), Fourier transform each tapered window and average the squared magnitudes over the tapers to estimate the PSD of the window. 4. Average the PSDs of the windows. ![image](user_guide/models/images/hmm-spectra.svg) The static spectrum, $S$, is the average of the state spectra weighted by the fractional occupancies (`fractional_occupancies`). A state that is never active in a session has NaN spectra for that session. The multitaper is the recommended method for HMM states. The multitaper spectra have broader peaks and smaller differences between states than the regression spectra. To compare the two methods, use `psd_change` ($P_j - S$) from both. ## What to plot Plot the change from the static spectrum: the coefficients for regression spectra and $P_j - S$ for multitaper spectra. These are the defaults of the methods below. Calculate the group average first: ```python group = spectra.group_average() ``` [`group_average()`](autoapi/osl_dynamics/analysis/spectral/Spectra.html.md#osl_dynamics.analysis.spectral.Spectra.group_average) averages the cross spectra over sessions with `session_weights` (the number of samples in each session), ignoring NaN values. The coherences are calculated from the group-averaged cross spectra. ### PSDs [`plot_psd()`](autoapi/osl_dynamics/analysis/spectral/Spectra.html.md#osl_dynamics.analysis.spectral.Spectra.plot_psd) plots the PSD of each state/mode averaged over parcels, with the standard error over parcels: ```python # Change from the static PSD group.plot_psd(filename="psd_change.png") # PSD of each state with the static PSD group.plot_psd(values="psd", static=True, filename="psd.png") ``` For DyNeMo, $P_j$ is an extrapolation: plot the coefficients. Pass `channels` to plot a subset of parcels. ### Power maps and coherence networks ```python from osl_dynamics.analysis import power, connectivity # Power maps p = group.power_maps() # (states, parcels) power.save(p, parcellation_file=parcellation_file, filename="pow_.png", plot_kwargs={"symmetric_cbar": True}) # Coherence networks: the 3% of edges with the largest changes c = group.coherence_networks(percentile=97) # (states, parcels, parcels) connectivity.save(c, parcellation_file=parcellation_file, filename="coh_.png") ``` - **Power maps.** The change in power from the static power, averaged over frequency (`method="integral"` gives the change in variance). Red is an increase and blue a decrease. Use the change from the static power, not $P_j$, to compare states/modes. - **Coherence networks.** The edges with the largest changes in coherence, increases (red) and decreases (blue). Pass `values` to use another quantity, e.g. `values="psd"` or `values="coherence"`. ### Frequency bands Pass `frequency_range` for one band, or `bands` for several: ```python p = group.power_maps(frequency_range=[8, 13]) # (states, parcels) p = group.power_maps(bands=[[1, 4], [4, 8], [8, 13], [13, 30]]) # (bands, states, parcels) ``` High-frequency activity can make the coherence networks noisy, so the spectra are often separated into frequency bands (‘spectral components’) with non-negative matrix factorization: ```python components = spectra.decompose(n_components=2) # (components, frequencies) p = group.power_maps(bands=components) # (components, states, parcels) c = group.coherence_networks(bands=components, percentile=97) ``` Pass `component=i` to [`save()`](autoapi/osl_dynamics/analysis/power/save.html.md#osl_dynamics.analysis.power.save) and [`save()`](autoapi/osl_dynamics/analysis/connectivity/save.html.md#osl_dynamics.analysis.connectivity.save) to plot component `i`. ### Statistics Use the session-specific spectra (without `group_average`) for [statistical tests](user_guide/stats.html.md). The first axis is the session: ```python from osl_dynamics import stats p = spectra.power_maps(frequency_range=[8, 13]) # (sessions, states, parcels) c = spectra.coherence_networks(frequency_range=[8, 13], vectorize=True) # (sessions, states, edges) result = stats.group_diff(p, assignments) ``` `vectorize=True` returns the upper triangle of each network; [`vec2mat()`](autoapi/osl_dynamics/utils/array_ops/vec2mat.html.md#osl_dynamics.utils.array_ops.vec2mat) converts it back to a matrix. # user_guide/stats.html.md # Statistical Significance Testing [`osl_dynamics.stats`](autoapi/osl_dynamics/stats/index.html.md#module-osl_dynamics.stats) fits a General Linear Model (GLM) at each **target** (parcel, state, connection, time point, frequency) and corrects for the multiple comparisons across targets, by default with permutation tests that make no assumption about the distribution of the data. The [Statistical Inference tutorial](tutorials_build/7-1_statistical_inference.html.md) explains the methods with figures; the [statistics tutorials](tutorial_sections/statistics.html.md) apply them to group contrasts, network responses and custom designs. ## Which function? All tests take an array with the subjects as the first dimension and any number of target dimensions, and return a [`TestResult`](autoapi/osl_dynamics/stats/TestResult.html.md#osl_dynamics.stats.TestResult) with the effect (`copes`), the statistic (`stats`), corrected `pvalues` and a `significant()` mask of the same shape as the targets. | Question | Function | Permutations | |---------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------| | Is a (baseline-corrected) response different from zero? | [`evoked_response()`](autoapi/osl_dynamics/stats/evoked_response.html.md#osl_dynamics.stats.evoked_response) | Sign flip (within subject) | | Is a paired difference (condition A - B) different from zero? | [`paired_diff()`](autoapi/osl_dynamics/stats/paired_diff.html.md#osl_dynamics.stats.paired_diff) | Sign flip (within subject) | | Do two groups differ? | [`group_diff()`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) | Row shuffle (between subject) | | Do three or more groups differ at all? (one-way ANOVA) | [`group_diff()`](autoapi/osl_dynamics/stats/group_diff.html.md#osl_dynamics.stats.group_diff) with all the labels (an F-test); then `groups=(a, b)` for pairwise follow-ups | Row shuffle (between subject) | | Does a quantity change with age, score, etc.? | [`regression()`](autoapi/osl_dynamics/stats/regression.html.md#osl_dynamics.stats.regression) | Row shuffle (between subject) | | Do several conditions measured in the same subjects differ? (repeated measures ANOVA) | [`condition_diff()`](autoapi/osl_dynamics/stats/condition_diff.html.md#osl_dynamics.stats.condition_diff) (an F-test, or a pair with `conditions=(a, b)`) | Row shuffle within each subject (exchangeability blocks) | | Something else (custom contrasts, F-contrasts over several t-contrasts) | [`DesignConfig`](autoapi/osl_dynamics/stats/DesignConfig.html.md#osl_dynamics.stats.DesignConfig) with [`MaxStatPermutation`](autoapi/osl_dynamics/stats/MaxStatPermutation.html.md#osl_dynamics.stats.MaxStatPermutation), [`ClusterPermutation`](autoapi/osl_dynamics/stats/ClusterPermutation.html.md#osl_dynamics.stats.ClusterPermutation) or [`GLM`](autoapi/osl_dynamics/stats/GLM.html.md#osl_dynamics.stats.GLM) | Chosen from the design | Sign-flip tests assume the noise is symmetric about zero, which holds for baseline-corrected responses and paired differences; row-shuffle tests make no distributional assumption. Nuisance covariates are passed to the between-subject functions as `covariates={"age": age, ...}`. Every result has an [`effect_size()`](autoapi/osl_dynamics/stats/TestResult.html.md#osl_dynamics.stats.TestResult.effect_size) method giving Cohen’s d (or partial eta squared for an F-test) with bootstrap confidence intervals. ## Which correction? The `correction` argument selects the correction for multiple comparisons. | `correction` | Controls | Use for | |--------------------------|------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `'max_stat'` (default) | FWER | Targets without a natural neighbourhood: states, parcels, connections, summary statistics. Accounts for the correlation between targets. `pooled_dims` restricts the family, e.g. to the parcels within each state. | | `'cluster'` | FWER | Effects extended along time or frequency (network responses, spectra). Clusters are formed along `cluster_dims`; a custom `adjacency` connects e.g. neighboring parcels. A cluster’s p-value does not establish its exact extent or latency. | | `'tfce'` | FWER | As `'cluster'` without a cluster-forming threshold, with per-target p-values. | | `'fdr'` | FDR | Many targets where a small fraction of false positives is acceptable, e.g. connectivity matrices. Parametric by default; `parametric=False` uses permutation p-values. | | `'bonferroni'`, `'holm'` | FWER | Few, roughly independent targets. Conservative for correlated targets. | | `None` | Nothing | Exploration only. Never report uncorrected p-values alone. | FWER is the family-wise error rate (the probability of any false positive); FDR the false discovery rate (the expected fraction of false positives among the significant targets). ## Which data? | osl-dynamics output | Shape | Recommended | |----------------------------------------------------------------------------------|----------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Summary statistics (fractional occupancy, lifetimes, intervals, switching rates) | (subjects, states) | `group_diff` / `regression`, `'max_stat'`. Undefined lifetimes (NaN) are handled per target. | | State/mode power maps | (subjects, states, parcels) | `group_diff` / `regression`, `'max_stat'`; `pooled_dims=1` to correct within each state. | | Static power maps | (subjects, parcels) | `group_diff` / `regression`, `'max_stat'`. | | Connectivity (AEC, coherence) | (subjects, [states,] parcels, parcels) | Upper triangle with [`mat2vec()`](autoapi/osl_dynamics/utils/array_ops/mat2vec.html.md#osl_dynamics.utils.array_ops.mat2vec), then `'max_stat'` or `'fdr'`; back with [`vec2mat()`](autoapi/osl_dynamics/utils/array_ops/vec2mat.html.md#osl_dynamics.utils.array_ops.vec2mat). | | Network response (epoched state/mode time course) | (subjects, time, states) | `evoked_response`, `'cluster'` or `'tfce'` along time (default), or `'max_stat'` on copes. | | Network response per condition | (subjects, conditions, time, states) | `condition_diff`, `'cluster'` with `cluster_dims=0` (time); `paired_diff` on the difference for two conditions. | | Spectra | (subjects, states, parcels, frequency) | `group_diff`, `'cluster'` with `cluster_dims=2` (frequency). | | DyNeMo mixing coefficient statistics | (subjects, modes) | As summary statistics. | Also see the [FAQ](faq.html.md) and the [example scripts](https://github.com/OHBA-analysis/osl-dynamics/tree/main/examples/statistics).