Name | neurostates JSON |
Version |
0.1.2
JSON |
| download |
home_page | None |
Summary | Neurostates is a tool for analyzing patterns of functional connectivity in EEG and fMRI. |
upload_time | 2025-04-07 23:13:24 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.9 |
license | Copyright (c) 2024, Della Bella, Gabriel; Rodriguez, Natalia
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. |
keywords |
brain
functional
connectivity
eeg
fmri
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# NeuroStates
<img src="https://raw.githubusercontent.com/dellabellagabriel/neurostates/main/res/logo_final.png" alt="logo" width="20%">
[](https://github.com/dellabellagabriel/neurostates/actions/workflows/CI.yml)
[](https://neurostates.readthedocs.io/en/latest/)
[](https://www.tldrlegal.com/l/bsd3)
**NeuroStates** is a Python package for detecting recurrent functional connectivity patterns (also known as brain states) and estimating their ocurrence probabilities in EEG and fMRI.
# Install
Before installing, make sure you have the following:
- Python 3.9 or later.
- pip (Python's package installer).
- A virtual environment (optional, but recommended).
From PyPI repo, simply run:
```bash
pip install neurostates
```
You can install it in development mode by running:
```bash
pip install -e .
```
# Basic Usage
## Load data
We load two groups of subjects — controls and patients — where each subject's data is a time series of brain activity (e.g., from fMRI or EEG).
It must be of size `(subjects x regions x time)`.
```python
import numpy as np
import scipy.io as sio
group_controls = sio.loadmat("path/to/control/data")["ts"]
group_patients = sio.loadmat("path/to/patient/data")["ts"]
groups = {
"controls": group_controls,
"patients": group_patients
}
print(f"Control group shape (subjects, regions, time): {group_controls.shape}")
print(f"Patient group shape (subjects, regions, time): {group_patients.shape}")
```
```
Control group shape (subjects, regions, time): (10, 90, 500)
Patient group shape (subjects, regions, time): (10, 90, 500)
```
## Build the pipeline
Neurostates implements a `scikit-learn`-compatible pipeline that includes all of the important steps required for brain state analysis.
The pipeline includes:
- A sliding window that segments the time series
- Dynamic connectivity estimation (e.g., Pearson, cosine similarity, Spearman’s R, or a custom metric)
- Concatenation of all matrices across subjects
- Clustering using KMeans to extract brain states
```python
from sklearn.cluster import KMeans
from sklearn.pipeline import Pipeline
from neurostates.core.clustering import Concatenator
from neurostates.core.connectivity import DynamicConnectivityGroup
from neurostates.core.window import SecondsWindowerGroup
brain_state_pipeline = Pipeline(
[
(
"windower",
SecondsWindowerGroup(length=20, step=5, sample_rate=1)
),
(
"connectivity",
DynamicConnectivityGroup(method="pearson")
),
(
"preclustering",
Concatenator()
),
(
"clustering",
KMeans(n_clusters=3, random_state=42)
),
]
)
```
Then you can use the `fit_transform()` method to transform your input data and get the centroids (brain states):
```python
brain_state_pipeline.fit_transform(groups)
brain_states = brain_state_pipeline["clustering"].cluster_centers_
# Originally brain_states will be a 3 by 8100 matrix.
# We reshape them to get the matrix structure back
brain_states = brain_states.reshape(3, 90, 90)
```
And you can plot them like so:
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 3)
ax[0].imshow(brain_states[0], vmin=-0.5, vmax=1)
ax[0].set_title("state 1")
ax[0].set_ylabel("regions")
ax[0].set_xlabel("regions")
ax[1].imshow(brain_states[1], vmin=-0.5, vmax=1)
ax[1].set_title("state 2")
ax[2].imshow(brain_states[2], vmin=-0.5, vmax=1)
ax[2].set_title("state 3")
plt.show()
```
<img src="https://github.com/dellabellagabriel/neurostates/raw/main/res/states.png" alt="logo" width="50%">
You can also access intermediate results from the pipeline, such as the windowed timeseries or the connectivity matrices:
```python
connectivity_matrices = brain_state_pipeline["connectivity"].dict_of_groups_
print(f"Connectivity matrices has keys: {connectivity_matrices.keys()}")
print(f"Control has size: {connectivity_matrices['controls'].shape}")
```
```
Connectivity matrices has keys: dict_keys(['controls', 'patients'])
Control has size (subjects, windows, regions, regions): (10, 97, 90, 90)
```
## Compute brain state frequencies
To evaluate how often each brain state occurs for each subject, we use the `Frequencies` transformer:
```python
from neurostates.core.classification import Frequencies
frequencies = Frequencies(
centroids=brain_state_pipeline["clustering"].cluster_centers_
)
freqs = frequencies.transform(connectivity_matrices)
print(f"freqs has keys: {freqs.keys()}")
print(f"Control has size (subjects, states): {freqs['controls'].shape}")
```
```
freqs has keys: dict_keys(['controls', 'patients'])
Control has size (subjects, states): (10, 3)
```
Finally, you can plot the frequency of each brain state in the data:
```python
fig, ax = plt.subplots(1, 3, figsize=(8, 4))
ax[0].boxplot(
[freqs["controls"][:, 0], freqs["patients"][:, 0]],
labels=["controls", "patients"]
)
ax[0].set_ylabel("frequency")
ax[0].set_title("state 1")
ax[1].boxplot(
[freqs["controls"][:, 1], freqs["patients"][:, 1]],
labels=["controls", "patients"]
)
ax[1].set_title("state 2")
ax[2].boxplot(
[freqs["controls"][:, 2], freqs["patients"][:, 2]],
labels=["controls", "patients"]
)
ax[2].set_title("state 3")
plt.show()
```
<img src="https://github.com/dellabellagabriel/neurostates/raw/main/res/frequencies.png" alt="logo" width="50%">
# Documentation
If you want to see the full documentation please visit [https://neurostates.readthedocs.io/en/latest/index.html](https://neurostates.readthedocs.io/en/latest/).
# License
Neurostates is under The 3-Clause BSD License
This license allows unlimited redistribution for any purpose as long as its copyright notices and the license's disclaimers of warranty are maintained.
# Contact Us
If you have any questions, feel free to check out our Github issues or write us an email to: dellabellagabriel@gmail.com or natirodriguez114@gmail.com
Raw data
{
"_id": null,
"home_page": null,
"name": "neurostates",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "brain, functional, connectivity, eeg, fmri",
"author": null,
"author_email": "Gabriel Della Bella <dellabellagabriel@gmail.com>, Natalia Rodriguez <natirodriguez114@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/bc/79/034f06d5ca1db21f17f6bc5ff9a6f4f3016a928bdb4a60ddc4c089418d97/neurostates-0.1.2.tar.gz",
"platform": null,
"description": "# NeuroStates\n\n<img src=\"https://raw.githubusercontent.com/dellabellagabriel/neurostates/main/res/logo_final.png\" alt=\"logo\" width=\"20%\">\n\n[](https://github.com/dellabellagabriel/neurostates/actions/workflows/CI.yml)\n[](https://neurostates.readthedocs.io/en/latest/)\n[](https://www.tldrlegal.com/l/bsd3)\n\n**NeuroStates** is a Python package for detecting recurrent functional connectivity patterns (also known as brain states) and estimating their ocurrence probabilities in EEG and fMRI.\n\n# Install\nBefore installing, make sure you have the following:\n- Python 3.9 or later.\n- pip (Python's package installer).\n- A virtual environment (optional, but recommended).\n\nFrom PyPI repo, simply run:\n```bash\npip install neurostates\n```\nYou can install it in development mode by running:\n```bash\npip install -e .\n```\n\n# Basic Usage\n## Load data\n\nWe load two groups of subjects \u2014 controls and patients \u2014 where each subject's data is a time series of brain activity (e.g., from fMRI or EEG). \nIt must be of size `(subjects x regions x time)`.\n\n```python\nimport numpy as np\nimport scipy.io as sio\n\ngroup_controls = sio.loadmat(\"path/to/control/data\")[\"ts\"]\ngroup_patients = sio.loadmat(\"path/to/patient/data\")[\"ts\"]\n\ngroups = {\n \"controls\": group_controls,\n \"patients\": group_patients\n}\n\nprint(f\"Control group shape (subjects, regions, time): {group_controls.shape}\")\nprint(f\"Patient group shape (subjects, regions, time): {group_patients.shape}\")\n```\n\n```\nControl group shape (subjects, regions, time): (10, 90, 500) \nPatient group shape (subjects, regions, time): (10, 90, 500)\n```\n\n## Build the pipeline\n\nNeurostates implements a `scikit-learn`-compatible pipeline that includes all of the important steps required for brain state analysis. \nThe pipeline includes:\n\n- A sliding window that segments the time series \n- Dynamic connectivity estimation (e.g., Pearson, cosine similarity, Spearman\u2019s R, or a custom metric) \n- Concatenation of all matrices across subjects \n- Clustering using KMeans to extract brain states \n\n```python\nfrom sklearn.cluster import KMeans\nfrom sklearn.pipeline import Pipeline\n\nfrom neurostates.core.clustering import Concatenator\nfrom neurostates.core.connectivity import DynamicConnectivityGroup\nfrom neurostates.core.window import SecondsWindowerGroup\n\nbrain_state_pipeline = Pipeline(\n [\n (\n \"windower\",\n SecondsWindowerGroup(length=20, step=5, sample_rate=1)\n ),\n (\n \"connectivity\",\n DynamicConnectivityGroup(method=\"pearson\")\n ),\n (\n \"preclustering\",\n Concatenator()\n ),\n (\n \"clustering\",\n KMeans(n_clusters=3, random_state=42)\n ),\n ]\n)\n```\n\nThen you can use the `fit_transform()` method to transform your input data and get the centroids (brain states):\n\n```python\nbrain_state_pipeline.fit_transform(groups)\nbrain_states = brain_state_pipeline[\"clustering\"].cluster_centers_\n\n# Originally brain_states will be a 3 by 8100 matrix.\n# We reshape them to get the matrix structure back\nbrain_states = brain_states.reshape(3, 90, 90)\n```\n\nAnd you can plot them like so:\n\n```python\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 3)\nax[0].imshow(brain_states[0], vmin=-0.5, vmax=1)\nax[0].set_title(\"state 1\")\nax[0].set_ylabel(\"regions\")\nax[0].set_xlabel(\"regions\")\n\nax[1].imshow(brain_states[1], vmin=-0.5, vmax=1)\nax[1].set_title(\"state 2\")\n\nax[2].imshow(brain_states[2], vmin=-0.5, vmax=1)\nax[2].set_title(\"state 3\")\n\nplt.show()\n```\n\n<img src=\"https://github.com/dellabellagabriel/neurostates/raw/main/res/states.png\" alt=\"logo\" width=\"50%\">\n\nYou can also access intermediate results from the pipeline, such as the windowed timeseries or the connectivity matrices:\n\n```python\nconnectivity_matrices = brain_state_pipeline[\"connectivity\"].dict_of_groups_\nprint(f\"Connectivity matrices has keys: {connectivity_matrices.keys()}\")\nprint(f\"Control has size: {connectivity_matrices['controls'].shape}\")\n```\n\n```\nConnectivity matrices has keys: dict_keys(['controls', 'patients']) \nControl has size (subjects, windows, regions, regions): (10, 97, 90, 90)\n```\n\n## Compute brain state frequencies\n\nTo evaluate how often each brain state occurs for each subject, we use the `Frequencies` transformer:\n\n```python\nfrom neurostates.core.classification import Frequencies\n\nfrequencies = Frequencies(\n centroids=brain_state_pipeline[\"clustering\"].cluster_centers_\n)\nfreqs = frequencies.transform(connectivity_matrices)\n\nprint(f\"freqs has keys: {freqs.keys()}\")\nprint(f\"Control has size (subjects, states): {freqs['controls'].shape}\")\n```\n\n```\nfreqs has keys: dict_keys(['controls', 'patients']) \nControl has size (subjects, states): (10, 3)\n```\n\nFinally, you can plot the frequency of each brain state in the data:\n\n```python\nfig, ax = plt.subplots(1, 3, figsize=(8, 4))\n\nax[0].boxplot(\n [freqs[\"controls\"][:, 0], freqs[\"patients\"][:, 0]],\n labels=[\"controls\", \"patients\"]\n)\nax[0].set_ylabel(\"frequency\")\nax[0].set_title(\"state 1\")\n\nax[1].boxplot(\n [freqs[\"controls\"][:, 1], freqs[\"patients\"][:, 1]],\n labels=[\"controls\", \"patients\"]\n)\nax[1].set_title(\"state 2\")\n\nax[2].boxplot(\n [freqs[\"controls\"][:, 2], freqs[\"patients\"][:, 2]],\n labels=[\"controls\", \"patients\"]\n)\nax[2].set_title(\"state 3\")\n\nplt.show()\n```\n\n<img src=\"https://github.com/dellabellagabriel/neurostates/raw/main/res/frequencies.png\" alt=\"logo\" width=\"50%\">\n\n# Documentation\nIf you want to see the full documentation please visit [https://neurostates.readthedocs.io/en/latest/index.html](https://neurostates.readthedocs.io/en/latest/).\n\n# License\nNeurostates is under The 3-Clause BSD License\n\nThis license allows unlimited redistribution for any purpose as long as its copyright notices and the license's disclaimers of warranty are maintained.\n\n# Contact Us\nIf you have any questions, feel free to check out our Github issues or write us an email to: dellabellagabriel@gmail.com or natirodriguez114@gmail.com\n",
"bugtrack_url": null,
"license": "Copyright (c) 2024, Della Bella, Gabriel; Rodriguez, Natalia\n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.",
"summary": "Neurostates is a tool for analyzing patterns of functional connectivity in EEG and fMRI.",
"version": "0.1.2",
"project_urls": null,
"split_keywords": [
"brain",
" functional",
" connectivity",
" eeg",
" fmri"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "73fc006dfe05da1e4bd7d9f3755ade9824b8fc4a7434efad4ff5e0378f31c250",
"md5": "c759434ac6f969ea936e130f8b3ec750",
"sha256": "cde90fad17cd5b06e5f9f9abfe5a6112f60fc6c202735d6bc9f8ded782ca2466"
},
"downloads": -1,
"filename": "neurostates-0.1.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "c759434ac6f969ea936e130f8b3ec750",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 13219,
"upload_time": "2025-04-07T23:13:23",
"upload_time_iso_8601": "2025-04-07T23:13:23.092484Z",
"url": "https://files.pythonhosted.org/packages/73/fc/006dfe05da1e4bd7d9f3755ade9824b8fc4a7434efad4ff5e0378f31c250/neurostates-0.1.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "bc79034f06d5ca1db21f17f6bc5ff9a6f4f3016a928bdb4a60ddc4c089418d97",
"md5": "c8227edc803739b4802f970e31f01c11",
"sha256": "1c903fba08bd31253e8dccffd9a3d5e75cd79884af68f1f4fa36b5f014b7fc7c"
},
"downloads": -1,
"filename": "neurostates-0.1.2.tar.gz",
"has_sig": false,
"md5_digest": "c8227edc803739b4802f970e31f01c11",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 12316,
"upload_time": "2025-04-07T23:13:24",
"upload_time_iso_8601": "2025-04-07T23:13:24.867320Z",
"url": "https://files.pythonhosted.org/packages/bc/79/034f06d5ca1db21f17f6bc5ff9a6f4f3016a928bdb4a60ddc4c089418d97/neurostates-0.1.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-04-07 23:13:24",
"github": false,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"lcname": "neurostates"
}