Metadata-Version: 2.5
Name: osl-signflip
Version: 0.1.0
Summary: Fast, reproducible sign-flipping for source-reconstructed M/EEG parcel time series via Z2 synchronisation.
Project-URL: Homepage, https://github.com/OHBA-analysis/osl-signflip
Project-URL: Issues, https://github.com/OHBA-analysis/osl-signflip/issues
Author-email: SungJun Cho <sungjun.cho@ndcn.ox.ac.uk>
License-Expression: MIT
License-File: LICENSE
Keywords: EEG,MEG,Z2 synchronization,belief propagation,dipole sign ambiguity,electrophysiology,neuroimaging,neuroscience,semidefinite programming,sign flipping,source reconstruction
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.9
Requires-Dist: joblib>=1.3
Requires-Dist: numpy>=1.20
Requires-Dist: tqdm
Provides-Extra: all
Requires-Dist: mne>=1.0; extra == 'all'
Requires-Dist: pytest; extra == 'all'
Requires-Dist: ruff; extra == 'all'
Provides-Extra: dev
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Provides-Extra: mne
Requires-Dist: mne>=1.0; extra == 'mne'
Description-Content-Type: text/markdown

# OHBA Software Library: Sign-Flipping Toolbox

[![Tests](https://github.com/OHBA-analysis/osl-signflip/actions/workflows/tests.yml/badge.svg)](https://github.com/OHBA-analysis/osl-signflip/actions/workflows/tests.yml)
[![Python](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/OHBA-analysis/osl-signflip/blob/main/pyproject.toml)
[![License](https://img.shields.io/badge/license-MIT-green)](https://github.com/OHBA-analysis/osl-signflip/blob/main/LICENSE)

**Fast, reproducible sign-flipping for source-reconstructed M/EEG data.**

🙋‍♂️ Please email SungJun Cho at sungjun.cho@ndcn.ox.ac.uk or simply raise [GitHub Issues](https://github.com/OHBA-analysis/osl-signflip/issues) if you have any questions or concerns.

## Table of Contents

- [Overview](#-overview)
- [Installation](#-installation)
- [Quick Start](#️-quick-start)
- [Tutorial](#-tutorial)
- [A Note on the Global Sign](#-a-note-on-the-global-sign)
- [Reproducing the Paper](#-reproducing-the-paper)
- [Citation](#-citation)
- [License](#-license)

## 💡 Overview

Source reconstruction of MEG/EEG data with unconstrained or data-driven source orientations leaves each parcel
time course with an arbitrary sign that can differ between recording sessions. `osl-signflip` aligns these signs
to a common template session so that group-level analyses (averaging, functional connectivity, network models)
are not distorted.

It casts sign-flipping as a **Z₂ synchronization** problem (equivalent to finding the ground state of an Ising
model) and solves it with:

| Method | `method=` | Notes |
| :-- | :-- | :-- |
| Semidefinite programming relaxation | `"sdp"` (default) | Recommended. Seeded and insensitive to the seed. |
| Spectral synchronization | `"spectral"` | Deterministic. |
| Loopy belief propagation | `"belief_propagation"` | Deterministic. |
| Random search | `"random"` | The stochastic baseline used by existing pipelines. |

The first three are followed by greedy refinement of the exact objective and run **roughly 160 to more than 2,000
times faster** than random search while giving equally good or better solutions.

## 📌 Installation

`osl-signflip` requires Python 3.9 or later (tested on Python 3.9–3.13).

```bash
pip install osl-signflip            # core (NumPy, tqdm, and joblib only)
pip install "osl-signflip[mne]"     # + helpers for MNE-Python Raw/Epochs and .fif files
```

To install it from source instead (e.g., for development):

```bash
git clone https://github.com/OHBA-analysis/osl-signflip.git
cd osl-signflip
pip install -e ".[mne,dev]"   # install osl-signflip in editable mode
pytest                        # run its test suite
```

## ⚡️ Quick Start

```python
import osl_signflip as oslsf

flips, metrics, template, data_flipped = oslsf.align_signs(
    data, n_embeddings=15, method="sdp", apply=True, n_jobs=8
)
# data: list of (n_samples, n_parcels) arrays, one per session
```

`flips[s]` is a vector of ±1 per parcel for session `s`, and `metrics[s]` tracks the correlation between the
session and template covariances (first entry: before flipping; last entry: after). The template is selected
automatically; to choose it yourself, pass `template=` (the index of a session in `data`, or the time series of
another session) or `template_cov=` (a precomputed template covariance). `n_jobs` sets the number of parallel
worker processes (`-1` uses all CPU cores).

To work directly with covariances, e.g. when aligning new sessions to an existing template:

```python
cov = oslsf.compute_covariance(x, n_embeddings=15)
flips, metrics = oslsf.find_flips(cov, template_cov, n_embeddings=15, method="sdp")
```

With parcellated `.fif` files (MNE-Python `Raw`/`Epochs` with parcel channels named `parcel_X`, as written by
`osl-ephys`), one call loads each file, finds the flips, and saves the sign-flipped data. Each worker handles one
file at a time, so only a few sessions are held in memory:

```python
from osl_signflip import io

flips, metrics, template = io.sign_flip_files(
    ["sub-01_parc-raw.fif", "sub-02_parc-raw.fif", ...],              # input files
    ["sub-01_sflip_parc-raw.fif", "sub-02_sflip_parc-raw.fif", ...],  # output files
    n_embeddings=15, method="sdp", n_jobs=16,
)
```

Here, `template=` can be the index of an input file or the path to any template file.

## 📚 Tutorial

The [sign-flipping tutorial](https://github.com/OHBA-analysis/osl-signflip/blob/main/tutorials/sign_flipping_tutorial.ipynb) demonstrates the complete workflow using parcellated MEG data from the Wakeman–Henson dataset, which is downloaded automatically.

The tutorial covers:

1. **Sign flipping:** Apply all four methods using `align_signs()` and `io.sign_flip_files()`.
2. **Performance evaluation:** Compare alignment quality and agreement across methods.
3. **Runtime benchmarking:** Evaluate the computational efficiency of each method.

## 🧭 A Note on the Global Sign

Sign-flipping uses covariances, which cannot distinguish a flip vector `f` from its global negation `-f`
(flipping every parcel of a session leaves its covariance unchanged). `osl-signflip` therefore fixes the global
sign by convention, ensuring that the output is reproducible.

## 📄 Reproducing the Paper

This repository also contains the scripts that reproduce the analyses and figures of the accompanying paper
(evaluated on the LEMON, Cam-CAN, and Wakeman-Henson datasets). See
[`scripts/README.md`](https://github.com/OHBA-analysis/osl-signflip/blob/main/scripts/README.md) for the
requirements and instructions.

## 📝 Citation

If you use `osl-signflip`, please cite the accompanying paper (citation to be added). Citation metadata is also
available in [`CITATION.cff`](https://github.com/OHBA-analysis/osl-signflip/blob/main/CITATION.cff).
