Metadata-Version: 2.4
Name: ncrf
Version: 0.5
Summary: add-on module to eelbrain for neural current RF estimation
Author-email: Proloy Das <proloyd94@gmail.com>
Maintainer: Christian Brodbeck
Maintainer-email: Proloy Das <proloyd94@gmail.com>
License-Expression: MIT
Project-URL: documentation, https://proloyd.github.io/neuro-currentRF
Project-URL: homepage, https://github.com/proloyd/neuro-currentRF
Project-URL: source, https://github.com/proloyd/neuro-currentRF
Project-URL: tracker, https://github.com/proloyd/neuro-currentRF/issues
Keywords: meg,eeg,source localization,python
Classifier: Natural Language :: English
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: Unix
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: eelbrain>=0.43.0b3
Requires-Dist: numpy<3,>=1.23
Provides-Extra: all
Requires-Dist: ncrf[style]; extra == "all"
Requires-Dist: ncrf[test]; extra == "all"
Requires-Dist: ncrf[doc]; extra == "all"
Provides-Extra: full
Requires-Dist: ncrf[all]; extra == "full"
Provides-Extra: style
Requires-Dist: codespell[toml]>=2.2.4; extra == "style"
Requires-Dist: ruff>=0.6.0; extra == "style"
Requires-Dist: toml-sort; extra == "style"
Requires-Dist: yamllint; extra == "style"
Provides-Extra: doc
Requires-Dist: dipy; extra == "doc"
Requires-Dist: numpydoc; extra == "doc"
Requires-Dist: furo; extra == "doc"
Requires-Dist: matplotlib; extra == "doc"
Requires-Dist: sphinx-copybutton; extra == "doc"
Requires-Dist: sphinx-design; extra == "doc"
Requires-Dist: sphinx-gallery; extra == "doc"
Requires-Dist: sphinx-issues; extra == "doc"
Requires-Dist: sphinxcontrib-bibtex; extra == "doc"
Requires-Dist: intersphinx_registry; extra == "doc"
Requires-Dist: memory-profiler; extra == "doc"
Provides-Extra: test
Requires-Dist: flake8; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: pytest<8.1.1,>=8.0; extra == "test"
Requires-Dist: pytest-faulthandler; extra == "test"
Requires-Dist: seaborn; extra == "test"
Dynamic: license-file

# Build Status
![test-posix](https://github.com/proloyd/neuro-currentRF/actions/workflows/test-posix.yml/badge.svg)

![test-windows](https://github.com/proloyd/neuro-currentRF/actions/workflows/test-windows.yml/badge.svg)


# NCRF   
The magnetoencephalography (MEG) response to continuous auditory stimuli, such as speech, is commonly described using a linear filter, the auditory temporal response function (TRF). Though components of the sensor level TRFs have been well characterized, the cortical distributions of  the underlying neural responses are not well-understood. In our recent work, we provide a unified framework for determining the TRFs of neural sources directly from the MEG data, by integrating the TRF and distributed forward  source models into one, and casting the joint estimation task as a Bayesian optimization problem. Though the resulting  problem emerges as non-convex, we propose efficient solutions that leverage recent advances in evidence maximization. For more details please refer to [1], [2].

This repository contains the implementation of our direct TRF estimation algorithm in Python.

For code examples using real datasets, see the [Example gallery](https://eelbrain.github.io/neuro-currentRF/auto_examples/index.html).

The optimization algorithm is configurable independently of the forward model.
For a prepared `RegressionData` dataset, the lower-level API is:

```python
from ncrf import ChampLasso, NCRFEstimator

estimator = NCRFEstimator.from_lead_field(lead_field, noise_covariance)
solver = ChampLasso(mu='auto', n_iter=30, n_iterc=10, n_iterf=100)
result = estimator.fit(data, solver)
```

All solvers return a common predictive `NCRF` in `result.model`; training explained variance
is available as `result.scores['explained_variance']`. To score other data,
`result.model.evaluate(data, [explained_variance, l2_error])` predicts once and
returns all requested metrics. Solver-specific state is available as
`result.solver_fit`.


## How to use:
run
```python
result = fit_ncrf(meg, stim, lead_field, noise_covariance, mu='auto', tstop=1.0, basis_stride=2, n_splits=3, scale='l1')
```
to perform a 3-fold cross-validation and then construct the model for 1s long TRF with the regularization weight among the given range that gives least generalization error. The signature of the ``meg`` and ``stim`` could be as follows:

    [        megA (case, sensor, time),                       megB (case, sensor, time),               ...]
    [[featA1 (case, time), featA2 (case, time), ...], [featB1 (case, time), featB2 (case, time), ...], ...]

For more options, please look at the docstring. The learned TRF, `h` can be retrieved using:
```python
h = result.model.h
```

## Results
We applied the algorithm on a subset of MEG data collected from 17 adults (aged 18-27 years) under an auditory task described in the papers. In short, during the task, the participants listened to `1 min` long segments from an audio-book recording of [The Legend of Sleepy Hollow by Washington Irving](https://librivox.org/the-legend-of-sleepy-hollow-by-washington-irving/), narrated by a male speaker. We consider localizing the TRFs using a total of `6 min` data from each participant. MNE-python 0.14 was used in pre-processing the raw data to automatically detect and discard flat channels, remove  extraneous artifacts, and to band-pass filter the data in the range `1 - 80 Hz`. The six `1 min` long data epochs were then down-sampled to `200 Hz`. As the stimulus variable, we used the speech envelope reflecting the momentary acoustic power, by averaging the auditory spectrogram representation (generated using a model of the 
auditory periphery) across the frequency bands, sampled at `200 Hz`.  A volume source space for individual subjects was defined on a 3D regular grid with a resolution of `7 mm` in each direction. The lead-field matrix was then computed by placing free orientation virtual dipoles on the resulting `3322` grid points. The consistent components of our estimated `1 s`-long 3D TRFs across all `17` subjects looks like following:

![Demo](https://user-images.githubusercontent.com/28169943/49410670-bf51c500-f733-11e8-9894-43880aa8d49e.gif)

Isn't that cool? Do expect to see something like that with any other source localization method? If you realize you could use this method on your data, please feel free to use the codes. You can reach me at proloy@umd.edu if you have any issues with the codes. And don't forget to go over the papers/ posters before applying the algorithm. 

## Versioning and releases
The version is derived from git tags by [setuptools_scm](https://setuptools-scm.readthedocs.io); it is not stored in the source. A commit tagged `v0.5.0` builds as `0.5.0`; later commits build as a development version of the next release, e.g. `0.5.1.dev3+g1a2b3c4`. The installed version is available as `ncrf.__version__`.

To release, [create a release on GitHub](https://github.com/Eelbrain/neuro-currentRF/releases/new) with a new tag of the form `v0.5.0`. Publishing the release creates the tag and triggers the `wheels` workflow, which builds and tests the sdist and wheel and publishes them to [PyPI](https://pypi.org/project/ncrf/). Clones need the tags for the version to resolve (`git fetch --tags`); `pip install -e .` must be re-run for `ncrf.__version__` to reflect new tags.

The files involved:

- `pyproject.toml`: declares the version as dynamic and enables setuptools_scm (`[tool.setuptools_scm]`), which computes it from git at build time.
- `ncrf/__init__.py`: reads the version of the installed package from its metadata into `ncrf.__version__`.
- `.git_archival.txt` and `.gitattributes`: let GitHub archive downloads (`.zip`/`.tar.gz`), which have no git history, still carry the tag information.
- `.github/workflows/wheels.yml`: builds, tests and publishes the sdist and wheel; the other workflows check out the full history (`fetch-depth: 0`) so tags are available.
- `docs/conf.py`: takes the documentation version from `ncrf.__version__`.

## References
[1] P. Das, C. Brodbeck, J. Z. Simon, B. Babadi, [Direct Cortical Localization of the MEG Auditory Temporal Response 
Function: a Non-Convex Optimization Approach](https://isr.umd.edu/Labs/CSSL/simonlab/pubs/SFN2018.pdf); Proceedings 
of the 47th Annual Neuroscience Meeting (SfN 2018), Nov. 2-7, San Diego, CA.

[2] P. Das, C. Brodbeck, J. Z. Simon, B. Babadi, [Cortical Localization of the Auditory Temporal Response Function from 
MEG via Non-Convex Optimization](https://isr.umd.edu/Labs/CSSL/simonlab/pubs/Asilomar2018.pdf); 2018 Asilomar Conference
 on Signals, Systems, and Computers, Oct. 28–31, Pacific Grove, CA (invited)

