roiextract 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ name: documentation
2
+
3
+ on: [push, pull_request, workflow_dispatch]
4
+
5
+ permissions:
6
+ contents: write
7
+
8
+ jobs:
9
+ docs:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+
14
+ - name: Install Python
15
+ uses: actions/setup-python@v5
16
+ with:
17
+ python-version: '3.11'
18
+
19
+ - name: Install dependencies
20
+ run: |
21
+ python -m pip install --upgrade pip
22
+ pip install -r requirements_docs.txt
23
+ pip install -e .
24
+
25
+ - name: Sphinx build
26
+ run: |
27
+ make html
28
+
29
+ - name: Move the generated HTML files
30
+ run: |
31
+ cp -a _build/html/ _publish/
32
+
33
+ - name: Deploy to GitHub Pages
34
+ uses: peaceiris/actions-gh-pages@v3
35
+ if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
36
+ with:
37
+ publish_branch: gh-pages
38
+ github_token: ${{ secrets.GITHUB_TOKEN }}
39
+ publish_dir: _publish/
40
+ force_orphan: true
@@ -0,0 +1,19 @@
1
+ # Python
2
+ **/__pycache__/
3
+ **/.ipynb_checkpoints
4
+
5
+ # Build & tools
6
+ build/
7
+ *.egg-info
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+
11
+ # Docs
12
+ _build/
13
+ docs/generated/
14
+
15
+ # Tests
16
+ .coverage
17
+
18
+ # IDEA
19
+ .idea
@@ -0,0 +1,20 @@
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+ repos:
4
+
5
+ - repo: https://github.com/pre-commit/pre-commit-hooks
6
+ rev: v3.2.0
7
+ hooks:
8
+ - id: trailing-whitespace
9
+ - id: end-of-file-fixer
10
+ - id: check-added-large-files
11
+
12
+ - repo: https://github.com/astral-sh/ruff-pre-commit
13
+ # Ruff version.
14
+ rev: v0.1.8
15
+ hooks:
16
+ # Run the linter.
17
+ - id: ruff
18
+ args: [ --fix ]
19
+ # Run the formatter.
20
+ - id: ruff-format
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.0.2 - January 25th, 2024
6
+
7
+ ### Added
8
+
9
+ * Estimation of CTF homogeneity
10
+ * Numerical solution for optimizing a combination of CTF ratio and homogeneity
11
+ * Tests to cover the basic functionality
12
+ * Binary search for suggesting lambda_ based on the desired properties
13
+ * SpatialFilter class for storing the result of the optimization
14
+
15
+ ### Changed
16
+
17
+ * Re-structured the package, split into several files preparing for future extensions (free orientations, data-driven method)
18
+
19
+ ## 0.0.1 - May 8th, 2023
20
+
21
+ ### Added
22
+
23
+ * Analytic solution for a spatial filter that optimizes a combination of CTF ratio and similarity with a template
24
+ * Structured the code as a Python package
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Nikolai Kapralov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,20 @@
1
+ # Minimal makefile for Sphinx documentation
2
+ #
3
+
4
+ # You can set these variables from the command line, and also
5
+ # from the environment for the first two.
6
+ SPHINXOPTS ?=
7
+ SPHINXBUILD ?= sphinx-build
8
+ SOURCEDIR = docs
9
+ BUILDDIR = _build
10
+
11
+ # Put it first so that "make" without argument is like "make help".
12
+ help:
13
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14
+
15
+ .PHONY: help Makefile
16
+
17
+ # Catch-all target: route all unknown targets to Sphinx using the new
18
+ # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19
+ %: Makefile
20
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.3
2
+ Name: roiextract
3
+ Version: 0.0.2
4
+ Summary: Data-independent and data-driven optimization of extraction of ROI time series based on M/EEG
5
+ Project-URL: Homepage, https://github.com/ctrltz/roiextract
6
+ Project-URL: Bug Tracker, https://github.com/ctrltz/roiextract/issues
7
+ Author-email: Nikolai Kapralov <kapralov@cbs.mpg.de>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.7
13
+ Requires-Dist: mne
14
+ Requires-Dist: numpy
15
+ Requires-Dist: scipy
16
+ Description-Content-Type: text/markdown
17
+
18
+ # ROIextract
19
+
20
+ Optimization of extraction of ROI time series based on the cross-talk function (CTF) or source reconstruction of spatial patterns (REC). **Work in progress!**
21
+
22
+ ## Usage
23
+
24
+ Obtain a spatial filter that optimizes CTF properties:
25
+
26
+ ```python
27
+ from roiextract import ctf_optimize_label
28
+
29
+ sf = ctf_optimize_label(fwd, label, template, lambda_)
30
+
31
+ sf, props = ctf_optimize_label(fwd, label, template, lambda_, quantify=True)
32
+
33
+ sf = ctf_optimize_label(fwd, label, template, lambda_='auto', threshold=0.95)
34
+ ```
35
+
36
+ Plot the filter as a topomap:
37
+
38
+ ```python
39
+ sf.plot(info)
40
+ ```
41
+
42
+ Apply it to the data to obtain the time course of activity in the ROI/label:
43
+
44
+ ```python
45
+ label_tc = sf.apply(data)
46
+ ```
47
+
48
+ Estimate the CTF for the filter:
49
+
50
+ ```python
51
+ ctf = sf.get_ctf_fwd(fwd) # ctf is an instance of mne.SourceEstimate
52
+ ```
53
+
54
+ Plot the CTF on the brain surface:
55
+
56
+ ```python
57
+ ctf.plot()
58
+ ```
@@ -0,0 +1,41 @@
1
+ # ROIextract
2
+
3
+ Optimization of extraction of ROI time series based on the cross-talk function (CTF) or source reconstruction of spatial patterns (REC). **Work in progress!**
4
+
5
+ ## Usage
6
+
7
+ Obtain a spatial filter that optimizes CTF properties:
8
+
9
+ ```python
10
+ from roiextract import ctf_optimize_label
11
+
12
+ sf = ctf_optimize_label(fwd, label, template, lambda_)
13
+
14
+ sf, props = ctf_optimize_label(fwd, label, template, lambda_, quantify=True)
15
+
16
+ sf = ctf_optimize_label(fwd, label, template, lambda_='auto', threshold=0.95)
17
+ ```
18
+
19
+ Plot the filter as a topomap:
20
+
21
+ ```python
22
+ sf.plot(info)
23
+ ```
24
+
25
+ Apply it to the data to obtain the time course of activity in the ROI/label:
26
+
27
+ ```python
28
+ label_tc = sf.apply(data)
29
+ ```
30
+
31
+ Estimate the CTF for the filter:
32
+
33
+ ```python
34
+ ctf = sf.get_ctf_fwd(fwd) # ctf is an instance of mne.SourceEstimate
35
+ ```
36
+
37
+ Plot the CTF on the brain surface:
38
+
39
+ ```python
40
+ ctf.plot()
41
+ ```
@@ -0,0 +1,18 @@
1
+ API
2
+ ===
3
+
4
+ .. currentmodule:: roiextract.filter
5
+
6
+ .. autosummary::
7
+ :toctree: generated
8
+
9
+ SpatialFilter
10
+ apply_batch
11
+
12
+
13
+ .. currentmodule:: roiextract.optimize
14
+
15
+ .. autosummary::
16
+ :toctree: generated
17
+
18
+ ctf_optimize
@@ -0,0 +1,57 @@
1
+ # Configuration file for the Sphinx documentation builder.
2
+ #
3
+ # For the full list of built-in configuration values, see the documentation:
4
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html
5
+
6
+ # -- Project information -----------------------------------------------------
7
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
8
+
9
+ project = "ROIextract"
10
+ copyright = "2024, Nikolai Kapralov"
11
+ author = "Nikolai Kapralov"
12
+ release = "0.0.2"
13
+
14
+ # -- General configuration ---------------------------------------------------
15
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
16
+
17
+ extensions = [
18
+ "sphinx.ext.autodoc",
19
+ "sphinx.ext.autosummary",
20
+ "sphinx.ext.duration",
21
+ "sphinx.ext.intersphinx",
22
+ "sphinx.ext.napoleon",
23
+ "sphinx_copybutton",
24
+ ]
25
+
26
+ templates_path = ["_templates"]
27
+ exclude_patterns = []
28
+
29
+
30
+ # -- Options for HTML output -------------------------------------------------
31
+ # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
32
+
33
+ html_theme = "furo"
34
+ html_static_path = ["_static"]
35
+
36
+
37
+ # -- Copybutton settings -----------------------------------------------------
38
+ # https://sphinx-copybutton.readthedocs.io/en/latest/use.html#strip-and-configure-input-prompts-for-code-cells
39
+
40
+ copybutton_exclude = ".linenos, .gp"
41
+
42
+
43
+ # -- Autodoc settings --------------------------------------------------------
44
+
45
+ autodoc_typing_aliases = {
46
+ "ArrayLike": "numpy.typing.ArrayLike",
47
+ }
48
+
49
+
50
+ # -- Intersphinx settings ----------------------------------------------------
51
+
52
+ intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
53
+
54
+
55
+ # -- Napoleon settings -------------------------------------------------------
56
+
57
+ napoleon_numpy_docstring = True
@@ -0,0 +1,28 @@
1
+ .. ROIextract documentation master file, created by
2
+ sphinx-quickstart on Fri Mar 22 22:56:38 2024.
3
+ You can adapt this file completely to your liking, but it should at least
4
+ contain the root `toctree` directive.
5
+
6
+ Welcome to ROIextract's documentation!
7
+ ======================================
8
+
9
+ **ROIextract** is a Python library for extraction of time series of MEG or EEG activity from regions of interest.
10
+ The main focus is on using the *cross-talk function* for quantifying, visualizing and optimizing the remaining field spread.
11
+ Check out the :doc:`usage` section for further information, including how to :ref:`install <installation>` the project.
12
+
13
+ .. note::
14
+
15
+ This project is under active development, current API may still change.
16
+
17
+ .. toctree::
18
+ :maxdepth: 2
19
+ :caption: Contents:
20
+
21
+
22
+ Contents
23
+ --------
24
+
25
+ .. toctree::
26
+
27
+ usage
28
+ api
@@ -0,0 +1,13 @@
1
+ Usage
2
+ =====
3
+
4
+ .. _installation:
5
+
6
+ Installation
7
+ ------------
8
+
9
+ To use ROIextract, first install it using pip in your virtual environment:
10
+
11
+ .. code-block:: console
12
+
13
+ (.venv) $ pip install roiextract
@@ -0,0 +1,35 @@
1
+ @ECHO OFF
2
+
3
+ pushd %~dp0
4
+
5
+ REM Command file for Sphinx documentation
6
+
7
+ if "%SPHINXBUILD%" == "" (
8
+ set SPHINXBUILD=sphinx-build
9
+ )
10
+ set SOURCEDIR=docs
11
+ set BUILDDIR=_build
12
+
13
+ %SPHINXBUILD% >NUL 2>NUL
14
+ if errorlevel 9009 (
15
+ echo.
16
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
17
+ echo.installed, then set the SPHINXBUILD environment variable to point
18
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
19
+ echo.may add the Sphinx directory to PATH.
20
+ echo.
21
+ echo.If you don't have Sphinx installed, grab it from
22
+ echo.https://www.sphinx-doc.org/
23
+ exit /b 1
24
+ )
25
+
26
+ if "%1" == "" goto help
27
+
28
+ %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29
+ goto end
30
+
31
+ :help
32
+ %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33
+
34
+ :end
35
+ popd
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "roiextract"
7
+ version = "0.0.2"
8
+ authors = [
9
+ { name="Nikolai Kapralov", email="kapralov@cbs.mpg.de" }
10
+ ]
11
+ description = "Data-independent and data-driven optimization of extraction of ROI time series based on M/EEG"
12
+ readme = "README.md"
13
+ requires-python = ">=3.7"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "numpy",
21
+ "mne",
22
+ "scipy"
23
+ ]
24
+
25
+ [project.urls]
26
+ "Homepage" = "https://github.com/ctrltz/roiextract"
27
+ "Bug Tracker" = "https://github.com/ctrltz/roiextract/issues"
28
+
29
+ [tool.ruff]
30
+ line-length = 80
31
+ indent-width = 4
@@ -0,0 +1,4 @@
1
+ numpy
2
+ mne
3
+ pre-commit
4
+ scipy
@@ -0,0 +1,3 @@
1
+ furo
2
+ sphinx
3
+ sphinx-copybutton
@@ -0,0 +1,3 @@
1
+ mock
2
+ pytest
3
+ pytest-cov
@@ -0,0 +1,3 @@
1
+ from setuptools import setup
2
+
3
+ setup()
@@ -0,0 +1,6 @@
1
+ try:
2
+ from importlib.metadata import version
3
+
4
+ __version__ = version("roiextract")
5
+ except Exception:
6
+ __version__ = "Failed to determine the version"
@@ -0,0 +1,73 @@
1
+ import numpy as np
2
+
3
+ from numpy.linalg import norm
4
+ from scipy.linalg import eig
5
+
6
+
7
+ def ctf_optimize_ratio_similarity(
8
+ leadfield, template, mask, lambda_, regA=0.001, regB=0.001
9
+ ):
10
+ """
11
+ Optimize a linear combination of similarity with a template CTF and
12
+ within/outside CTF ratio
13
+
14
+ Parameters
15
+ ----------
16
+ leadfield: array_like
17
+ Lead field matrix for dipoles with fixed orientation with shape
18
+ (channels, voxels).
19
+ template: array_like
20
+ Template CTF pattern for voxels with shape (voxels,). Only values
21
+ within the ROI are used.
22
+ mask: array_like
23
+ Voxel mask of the region of interest with shape (voxels,). Contains
24
+ ones and zeros for voxels within and outside ROI, respectively.
25
+ lambda_: float
26
+ If 0, only ratio is optimized. If 1, only similarity. Values in between
27
+ allow tweaking the balance between optimization for similarity or ratio.
28
+ regA, regB: float
29
+ Regularization parameters to ensure that it is possible to calculate the
30
+ inverse matrices.
31
+
32
+ Returns
33
+ -------
34
+ w: array
35
+ Spatial filter produced by the optimization.
36
+
37
+ Raises
38
+ ------
39
+ ValueError
40
+ If the provided lambda_ value is out of [0, 1] range.
41
+ """
42
+ if lambda_ > 1.0 or lambda_ < 0.0:
43
+ raise ValueError("Value of lambda_ should lie in [0, 1] range")
44
+
45
+ # Make sure w0 is a row vector with unit length
46
+ template = np.atleast_1d(np.squeeze(template))
47
+ if template.ndim > 1:
48
+ raise ValueError(
49
+ f"Template weights should be a vector, got "
50
+ f"{template.ndim} dimensions instead"
51
+ )
52
+ template = template / norm(template)
53
+ template = template[np.newaxis, :]
54
+
55
+ # Split lead field matrix into in and out parts
56
+ L_in = leadfield[:, mask]
57
+ L_out = leadfield[:, ~mask]
58
+
59
+ # Solve the generalized eigenvalue problem
60
+ A_rat = L_out @ L_out.T
61
+ A_sim = L_in @ (template.T @ template) @ L_in.T
62
+ A = (1 - lambda_) * A_rat - lambda_ * A_sim
63
+ A_reg = A + regA * np.trace(A) * np.eye(*A.shape) / A.shape[0]
64
+ B = L_in @ L_in.T
65
+ B_reg = B + regB * np.trace(B) * np.eye(*B.shape) / B.shape[0]
66
+ [eigvals, eigvecs] = eig(A_reg, B_reg)
67
+
68
+ # Get the eigenvector that corresponds to the smallest eigenvalue
69
+ w = eigvecs[:, eigvals.argmin()]
70
+ if np.dot(w @ L_in, template.T) < 0:
71
+ w *= -1
72
+
73
+ return w