Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .github/ISSUE_TEMPLATE/bug_report.mdAdded+27
- .github/ISSUE_TEMPLATE/experiment.mdAdded+22
- .github/ISSUE_TEMPLATE/feature_request.mdAdded+19
- .github/PULL_REQUEST_TEMPLATE.mdAdded+15
- .github/workflows/ci.ymlAdded+28
- .gitignoreAdded+17
- CONTRIBUTING.mdAdded+110
- LICENSEAdded+407
- MODEL_CARD.mdAdded+131
- NOTICEAdded+75
- README.md+136-3
- examples/quick_start.pyAdded+72
- pyproject.tomlAdded+85
- src/cortexlab/__init__.pyAdded+20
- src/cortexlab/analysis/__init__.pyAdded+4
- src/cortexlab/analysis/brain_alignment.pyAdded+223
- src/cortexlab/analysis/cognitive_load.pyAdded+276
- src/cortexlab/core/__init__.pyAdded+3
- src/cortexlab/core/attention.pyAdded+117
- src/cortexlab/core/model.pyAdded+288
- src/cortexlab/core/subject.pyAdded+177
- src/cortexlab/data/__init__.pyAdded+15
- src/cortexlab/data/fmri.pyAdded+248
- src/cortexlab/data/loader.pyAdded+318
- src/cortexlab/data/studies/__init__.pyAdded+10
- src/cortexlab/data/studies/algonauts2025.pyAdded+315
- src/cortexlab/data/studies/lahner2024bold.pyAdded+293
- src/cortexlab/data/studies/lebel2023bold.pyAdded+344
- src/cortexlab/data/studies/wen2017.pyAdded+78
- src/cortexlab/data/transforms.pyAdded+273
- src/cortexlab/inference/__init__.pyAdded+4
- src/cortexlab/inference/attribution.pyAdded+93
- src/cortexlab/inference/predictor.pyAdded+392
- src/cortexlab/inference/streaming.pyAdded+158
- src/cortexlab/training/__init__.pyAdded+3
- src/cortexlab/training/experiment.pyAdded+651
- src/cortexlab/training/pl_module.pyAdded+155
- src/cortexlab/viz/__init__.pyAdded+26
- src/cortexlab/viz/base.pyAdded+497
- src/cortexlab/viz/cortical.pyAdded+311
- src/cortexlab/viz/cortical_pv.pyAdded+280
- src/cortexlab/viz/subcortical.pyAdded+311
- src/cortexlab/viz/utils.pyAdded+563
- tests/__init__.pyAdded
- tests/conftest.pyAdded+8
- tests/test_attention.pyAdded+78
- tests/test_attribution.pyAdded+136
- tests/test_brain_alignment.pyAdded+91
- tests/test_cognitive_load.pyAdded+100
- tests/test_model.pyAdded+111
123456789101112131415161718192021222324252627---name: Bug Reportabout: Report something that isn't working correctlytitle: ''labels: bugassignees: ''---
## DescriptionA clear description of the bug.
## Steps to Reproduce1. ...2. ...3. ...
## Expected BehaviorWhat you expected to happen.
## Actual BehaviorWhat actually happened. Include the full error traceback if applicable.
## Environment- OS:- Python version:- PyTorch version:- CortexLab version:12345678910111213141516171819202122---name: Experiment Proposalabout: Propose a research experiment or evaluationtitle: 'Experiment: 'labels: experimentassignees: ''---
## ObjectiveWhat question does this experiment answer?
## MethodStep-by-step description of the experimental setup.
## Data RequirementsWhat datasets or stimuli are needed?
## Expected OutcomeWhat do you expect to find, and why?
## Success CriteriaHow will you know if the experiment succeeded?12345678910111213141516171819---name: Feature Requestabout: Suggest a new feature or enhancementtitle: ''labels: enhancementassignees: ''---
## DescriptionWhat feature would you like to see?
## Use CaseWhy is this useful? What problem does it solve?
## Proposed ApproachIf you have ideas on how to implement this, describe them here.
## Alternatives ConsideredAny alternative solutions you've thought about.123456789101112131415## SummaryBrief description of what this PR does.
## Changes- ...- ...
## Testing- [ ] All existing tests pass (`pytest tests/ -v`)- [ ] Lint passes (`ruff check src/ tests/`)- [ ] New tests added for new functionality- [ ] Tested manually with example script
## Related IssuesCloses #12345678910111213141516171819202122232425262728name: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.10" - run: pip install ruff - run: ruff check src/ tests/
test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.10" - run: pip install -e ".[dev]" - run: pytest tests/ -v --tb=short1234567891011121314151617__pycache__/*.py[cod]*.egg-info/dist/build/.eggs/*.egg.pytest_cache/.ruff_cache/.venv/venv/*.ckpt*.pt*.pthcache/wandb/.env123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110# Contributing to CortexLab
Thanks for your interest in contributing to CortexLab! This guide will help you get started.
## Getting Started
### 1. Fork and clone
```bashgit clone https://github.com/YOUR_USERNAME/cortexlab.gitcd cortexlab```
### 2. Set up the development environment
```bashpython -m venv .venvsource .venv/bin/activate # or .venv\Scripts\activate on Windowspip install -e ".[dev,analysis]"```
### 3. Verify everything works
```bashpytest tests/ -vruff check src/ tests/```
## Development Workflow
1. **Create a branch** from `master` for your work: ```bash git checkout -b feature/your-feature-name ```
2. **Make your changes** - keep commits focused and atomic.
3. **Run tests and lint** before committing: ```bash pytest tests/ -v ruff check src/ tests/ ```
4. **Open a pull request** with a clear description of what you changed and why.
## Project Structure
```src/cortexlab/ core/ Model architecture, attention extraction, subject adaptation data/ Dataset loading, transforms, HCP ROI utilities training/ PyTorch Lightning training pipeline inference/ Predictor, streaming, modality attribution analysis/ Brain-alignment benchmark, cognitive load scorer viz/ Brain surface visualizationtests/ Unit tests (pytest)examples/ Usage examples```
## What to Work On
- Check [issues labeled `good first issue`](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) for beginner-friendly tasks- Check [issues labeled `help wanted`](../../issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) for tasks where we need help- Look at the [experiment issues](../../issues?q=is%3Aissue+is%3Aopen+label%3Aexperiment) if you want to run evaluations
## Code Style
- **Linting**: We use [ruff](https://docs.astral.sh/ruff/) with a 100-character line limit- **Tests**: Write pytest tests for new functionality. Use synthetic data (no real fMRI needed)- **Docstrings**: Use NumPy-style docstrings for public functions- **Imports**: Let ruff sort imports automatically (`ruff check --fix`)
## Writing Tests
Tests use synthetic data and mock objects so you don't need real fMRI datasets or GPU access:
```pythonimport torchfrom neuralset.dataloader import SegmentDataimport neuralset.segments as seg
# Create dummy segments matching batch sizesegments = [seg.Segment(start=float(i), duration=1.0, timeline="test") for i in range(batch_size)]
# Create synthetic batchdata = {"text": torch.randn(batch_size, 2, 32, seq_len), "subject_id": torch.zeros(batch_size, dtype=torch.long)}batch = SegmentData(data=data, segments=segments)```
## Adding New Features
If you're adding a new analysis method or inference capability:
1. Add the implementation in the appropriate subpackage2. Export it from the subpackage's `__init__.py`3. Write tests in `tests/test_yourfeature.py`4. Add a usage example in the README or `examples/`
## Reporting Bugs
When filing a bug report, please include:- Python version and OS- PyTorch version- Steps to reproduce- Full error traceback- What you expected to happen
## Questions?
Open an issue with the `question` label and we'll help out.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the "Licensor." The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131---license: cc-by-nc-4.0library_name: cortexlabtags: - neuroscience - fmri - brain-encoding - multimodal - tribe-v2 - brain-alignment - cognitive-loadlanguage: - enpipeline_tag: other---
# CortexLab
Enhanced multimodal fMRI brain encoding toolkit built on [Meta's TRIBE v2](https://github.com/facebookresearch/tribev2).
CortexLab extends TRIBE v2 with streaming inference, interpretability tools, cross-subject adaptation, brain-alignment benchmarking, and cognitive load scoring.
## What This Repo Contains
This is a **code-only** repository. It does not contain pretrained weights. The pretrained TRIBE v2 model is hosted by Meta at [`facebook/tribev2`](https://huggingface.co/facebook/tribev2).
## Features
| Feature | Description ||---|---|| **Streaming Inference** | Sliding-window real-time predictions from live feature streams || **ROI Attention Maps** | Visualize which brain regions attend to which temporal moments || **Modality Attribution** | Per-vertex importance scores for text, audio, and video || **Cross-Subject Adaptation** | Ridge regression or nearest-neighbour adaptation for new subjects || **Brain-Alignment Benchmark** | Score how "brain-like" any AI model's representations are (RSA, CKA, Procrustes) || **Cognitive Load Scorer** | Predict cognitive demand of media from predicted brain activation patterns |
## Prerequisites
The pretrained TRIBE v2 model uses **LLaMA 3.2-3B** as its text encoder. You must:
1. Accept Meta's LLaMA license at [llama.meta.com](https://llama.meta.com/)2. Request access on [HuggingFace](https://huggingface.co/meta-llama/Llama-3.2-3B)3. Authenticate: `huggingface-cli login`
## Installation
```bashgit clone https://github.com/siddhant-rajhans/cortexlab.gitcd cortexlabpip install -e ".[analysis]"```
## Quick Start
### Inference
```pythonfrom cortexlab.inference.predictor import TribeModel
model = TribeModel.from_pretrained("facebook/tribev2", device="auto")events = model.get_events_dataframe(video_path="clip.mp4")preds, segments = model.predict(events)```
### Brain-Alignment Benchmark
```pythonfrom cortexlab.analysis import BrainAlignmentBenchmark
bench = BrainAlignmentBenchmark(brain_predictions, roi_indices=roi_indices)result = bench.score_model(clip_features, method="rsa")print(f"Alignment: {result.aggregate_score:.3f}")```
### Cognitive Load Scoring
```pythonfrom cortexlab.analysis import CognitiveLoadScorer
scorer = CognitiveLoadScorer(roi_indices)result = scorer.score_predictions(predictions)print(f"Overall load: {result.overall_load:.2f}")```
## Compute Requirements
| Component | VRAM | Notes ||---|---|---|| TRIBE v2 encoder | ~1 GB | Small (1.15M params) || LLaMA 3.2-3B (text) | ~8 GB | Features cached after first run || V-JEPA2 (video) | ~6 GB | Features cached after first run || Wav2Vec-BERT (audio) | ~3 GB | Features cached after first run |
Minimum: 16 GB VRAM GPU for full inference. CPU works but is slow. Analysis tools (benchmark, cognitive load) work with zero GPU on precomputed predictions.
## Architecture
```src/cortexlab/ core/ Model architecture, attention extraction, subject adaptation data/ Dataset loading, transforms, HCP ROI utilities training/ PyTorch Lightning training pipeline inference/ Predictor, streaming, modality attribution analysis/ Brain-alignment benchmark, cognitive load scorer viz/ Brain surface visualization (nilearn, pyvista)```
## License
CC BY-NC 4.0 (non-commercial use only), inherited from TRIBE v2.
This project does not redistribute pretrained weights. Users must download weights directly from [`facebook/tribev2`](https://huggingface.co/facebook/tribev2).
## Citation
If you use CortexLab in your research, please cite the original TRIBE v2 paper:
```bibtex@article{dascoli2026tribe, title={A foundation model of vision, audition, and language for in-silico neuroscience}, author={d'Ascoli, St{\'e}phane and others}, year={2026}}```
## Links
- **GitHub**: [siddhant-rajhans/cortexlab](https://github.com/siddhant-rajhans/cortexlab)- **TRIBE v2**: [facebookresearch/tribev2](https://github.com/facebookresearch/tribev2)- **Pretrained weights**: [facebook/tribev2](https://huggingface.co/facebook/tribev2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475CortexLabCopyright 2026 CortexLab Contributors
This project is a derivative work built upon TRIBE v2 by Meta Platforms, Inc.
================================================================================
TRIBE v2Copyright (c) Meta Platforms, Inc. and affiliates.Licensed under Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)https://github.com/facebookresearch/tribev2
The following source files in this repository are derived from TRIBE v2: - src/cortexlab/core/model.py (modified: added return_attn, compile_backbone) - src/cortexlab/data/loader.py (original: tribev2/utils.py) - src/cortexlab/data/transforms.py (original: tribev2/eventstransforms.py) - src/cortexlab/data/fmri.py (original: tribev2/utils_fmri.py) - src/cortexlab/data/studies/* (original: tribev2/studies/*) - src/cortexlab/training/experiment.py (original: tribev2/main.py) - src/cortexlab/training/pl_module.py (original: tribev2/pl_module.py) - src/cortexlab/inference/predictor.py (original: tribev2/demo_utils.py) - src/cortexlab/viz/* (original: tribev2/plotting/*)
The pretrained model weights are hosted by Meta at: https://huggingface.co/facebook/tribev2
================================================================================
neuralset (v0.0.2)Copyright (c) Meta Platforms, Inc. and affiliates.Licensed under CC BY-NC 4.0
neuraltrain (v0.0.2)Copyright (c) Meta Platforms, Inc. and affiliates.Licensed under CC BY-NC 4.0
================================================================================
Third-party dependencies and their licenses:
PyTorch (torch) - BSD 3-Clause Transformers - Apache 2.0 HuggingFace Hub - Apache 2.0 x_transformers - MIT einops - MIT NumPy - BSD 3-Clause pandas - BSD 3-Clause PyYAML - MIT MoviePy - MIT gTTS - MIT langdetect - Apache 2.0 spaCy - MIT SoundFile - BSD 3-Clause julius - MIT pydantic - MIT requests - Apache 2.0 tqdm - MIT / MPL 2.0 SciPy - BSD 3-Clause nilearn - BSD 3-Clause MNE-Python - BSD 3-Clause PyVista - MIT matplotlib - PSF / BSD PyTorch Lightning - Apache 2.0 Weights & Biases - MIT
================================================================================
LLaMA 3.2-3B (used as text feature extractor by the pretrained TRIBE v2 model)Copyright (c) Meta Platforms, Inc.Licensed under the Meta Llama 3.2 Community License Agreementhttps://llama.meta.com/llama3_2/license/
Users must independently accept Meta's LLaMA license to use the pretrainedTRIBE v2 model for text feature extraction. CortexLab does not redistributeLLaMA weights.123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136---
license: cc-by-nc-4.0
---# CortexLab
Enhanced multimodal fMRI brain encoding toolkit built on [Meta's TRIBE v2](https://github.com/facebookresearch/tribev2).
CortexLab extends TRIBE v2 with streaming inference, interpretability tools, cross-subject adaptation, brain-alignment benchmarking, and cognitive load scoring.
## Features
| Feature | Description ||---|---|| **Streaming Inference** | Sliding-window real-time predictions from live feature streams || **ROI Attention Maps** | Visualize which brain regions attend to which temporal moments || **Modality Attribution** | Per-vertex importance scores for text, audio, and video || **Cross-Subject Adaptation** | Ridge regression or nearest-neighbour adaptation for new subjects || **Brain-Alignment Benchmark** | Score how "brain-like" any AI model's representations are (RSA, CKA, Procrustes) || **Cognitive Load Scorer** | Predict cognitive demand of media from predicted brain activation patterns |
## Prerequisites
The pretrained TRIBE v2 model uses **LLaMA 3.2-3B** as its text encoder. You must accept Meta's LLaMA license before using it:
1. Visit [llama.meta.com](https://llama.meta.com/) and accept the license2. Request access on [HuggingFace](https://huggingface.co/meta-llama/Llama-3.2-3B)3. Authenticate: `huggingface-cli login`
## Installation
```bashpip install -e "."
# With optional dependenciespip install -e ".[plotting]" # Brain visualizationpip install -e ".[training]" # PyTorch Lightning trainingpip install -e ".[analysis]" # RSA/CKA benchmarking (scipy)pip install -e ".[dev]" # Testing and linting```
## Quick Start
### Inference
```pythonfrom cortexlab.inference.predictor import TribeModel
model = TribeModel.from_pretrained("facebook/tribev2", device="auto")events = model.get_events_dataframe(video_path="clip.mp4")preds, segments = model.predict(events)```
### Brain-Alignment Benchmark
```pythonfrom cortexlab.analysis import BrainAlignmentBenchmark
bench = BrainAlignmentBenchmark(brain_predictions, roi_indices=roi_indices)result = bench.score_model(clip_features, method="rsa")print(f"Alignment: {result.aggregate_score:.3f}")print(f"V1 alignment: {result.roi_scores['V1']:.3f}")```
### Cognitive Load Scoring
```pythonfrom cortexlab.analysis import CognitiveLoadScorer
scorer = CognitiveLoadScorer(roi_indices)result = scorer.score_predictions(predictions)print(f"Overall load: {result.overall_load:.2f}")print(f"Visual complexity: {result.visual_complexity:.2f}")print(f"Language processing: {result.language_processing:.2f}")```
### Streaming Inference
```pythonfrom cortexlab.inference import StreamingPredictor
sp = StreamingPredictor(model._model, window_trs=40, step_trs=1, device="cuda")for features in live_feature_stream(): pred = sp.push_frame(features) if pred is not None: visualize(pred) # (n_vertices,)```
### Modality Attribution
```pythonfrom cortexlab.inference import ModalityAttributor
attributor = ModalityAttributor(model._model, roi_indices=roi_indices)scores = attributor.attribute(batch)# scores["text"], scores["audio"], scores["video"] -> (n_vertices,)```
### Cross-Subject Adaptation
```pythonfrom cortexlab.core.subject import SubjectAdapter
adapter = SubjectAdapter.from_ridge(model._model, calibration_loader, regularization=1e-3)new_subject_id = adapter.inject_into_model(model._model)```
## Architecture
```src/cortexlab/ core/ Model architecture, attention extraction, subject adaptation data/ Dataset loading, transforms, HCP ROI utilities training/ PyTorch Lightning training pipeline inference/ Predictor, streaming, modality attribution analysis/ Brain-alignment benchmark, cognitive load scorer viz/ Brain surface visualization (nilearn, pyvista)```
## Development
```bashpip install -e ".[dev]"pytest tests/ -vruff check src/ tests/```
## License
CC BY-NC 4.0 (inherited from TRIBE v2). See [LICENSE](LICENSE) and [NOTICE](NOTICE).
This project is for **non-commercial use only**. The pretrained weights are hosted by Meta at [facebook/tribev2](https://huggingface.co/facebook/tribev2) and are not redistributed by this project.
## Acknowledgements
Built on [TRIBE v2](https://github.com/facebookresearch/tribev2) by Meta FAIR.
> d'Ascoli et al., "A foundation model of vision, audition, and language for in-silico neuroscience", 2026.
See [NOTICE](NOTICE) for full attribution and third-party licenses.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""CortexLab Quick Start Example.
Demonstrates loading a pretrained model, running inference,and using the brain-alignment benchmark and cognitive load scorer."""
import numpy as np
def run_benchmark_demo(): """Demonstrate the brain-alignment benchmark with synthetic data.""" from cortexlab.analysis import BrainAlignmentBenchmark
n_stimuli = 50 model_features = np.random.randn(n_stimuli, 768) # e.g. CLIP features brain_predictions = np.random.randn(n_stimuli, 20484) # fsaverage5 vertices
roi_indices = { "V1": np.arange(0, 100), "MT": np.arange(500, 600), "A1": np.arange(1000, 1100), "Broca": np.arange(2000, 2100), }
bench = BrainAlignmentBenchmark(brain_predictions, roi_indices=roi_indices)
for method in ["rsa", "cka", "procrustes"]: result = bench.score_model(model_features, method=method) print(f"[{method.upper()}] Aggregate: {result.aggregate_score:.4f}") for roi, score in sorted(result.roi_scores.items()): print(f" {roi}: {score:.4f}") print()
def run_cognitive_load_demo(): """Demonstrate the cognitive load scorer with synthetic predictions.""" from cortexlab.analysis import CognitiveLoadScorer
roi_indices = { "46": np.arange(0, 10), "FEF": np.arange(10, 20), "V1": np.arange(100, 120), "V2": np.arange(120, 140), "MT": np.arange(140, 160), "A1": np.arange(200, 220), "LBelt": np.arange(220, 230), "44": np.arange(300, 310), "45": np.arange(310, 320), }
scorer = CognitiveLoadScorer(roi_indices, baseline_activation=0.5)
# Simulate 30 seconds of predictions predictions = np.random.randn(30, 500) * 0.5 # Add high visual activation predictions[:, 100:160] *= 3.0
result = scorer.score_predictions(predictions, tr_seconds=1.0) print(f"Overall cognitive load: {result.overall_load:.2f}") print(f"Visual complexity: {result.visual_complexity:.2f}") print(f"Auditory demand: {result.auditory_demand:.2f}") print(f"Language processing: {result.language_processing:.2f}") print(f"Executive load: {result.executive_load:.2f}") print(f"Timeline points: {len(result.timeline)}")
if __name__ == "__main__": print("=== Brain-Alignment Benchmark ===") run_benchmark_demo()
print("=== Cognitive Load Scorer ===") run_cognitive_load_demo()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485[build-system]requires = ["setuptools>=61.0"]build-backend = "setuptools.build_meta"
[project]name = "cortexlab"version = "0.1.0"description = "Enhanced multimodal fMRI brain encoding toolkit built on TRIBE v2"readme = "README.md"requires-python = ">=3.10"license = {file = "LICENSE"}authors = [{name = "CortexLab Contributors"}]
dependencies = [ "neuralset==0.0.2", "neuraltrain==0.0.2", "torch>=2.5.1,<2.7", "numpy>=2.0", "torchvision>=0.20,<0.22", "x_transformers==1.27.20", "einops", "pyyaml", "moviepy>=2.2.1", "huggingface_hub", "gtts", "langdetect", "spacy", "soundfile", "julius", "transformers", "pydantic", "exca", "requests", "tqdm", "pandas",]
[project.optional-dependencies]plotting = [ "nibabel", "matplotlib", "seaborn", "colorcet", "nilearn", "scipy", "pyvista", "scikit-image", "mne",]training = [ "nibabel", "torchmetrics", "wandb", "lightning",]streaming = [ "av",]analysis = [ "scipy",]dev = [ "pytest", "pytest-cov", "ruff",]
[project.urls]Repository = "https://github.com/siddhant-rajhans/cortexlab"
[tool.setuptools.packages.find]where = ["src"]include = ["cortexlab*"]
[tool.ruff]line-length = 100target-version = "py310"
[tool.ruff.lint]select = ["E", "F", "I", "W"]ignore = ["E501", "F401", "F403", "E402"]
[tool.pytest.ini_options]testpaths = ["tests"]python_files = "test_*.py"1234567891011121314151617181920"""CortexLab - Enhanced multimodal fMRI brain encoding toolkit.
Built on Meta's TRIBE v2 foundation model, CortexLab adds streaminginference, modality attribution, cross-subject adaptation,brain-alignment benchmarking, and cognitive load scoring."""
__version__ = "0.1.0"
from cortexlab.core.model import FmriEncoder, FmriEncoderModelfrom cortexlab.core.attention import AttentionExtractor, attention_to_roi_scoresfrom cortexlab.core.subject import SubjectAdapter
__all__ = [ "FmriEncoder", "FmriEncoderModel", "AttentionExtractor", "attention_to_roi_scores", "SubjectAdapter",]1234from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmarkfrom cortexlab.analysis.cognitive_load import CognitiveLoadScorer
__all__ = ["BrainAlignmentBenchmark", "CognitiveLoadScorer"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Brain-alignment benchmark for comparing AI model representations.
Score how "brain-like" any AI model's internal representations are bycomparing them against TRIBE v2's predicted brain responses usingRepresentational Similarity Analysis (RSA) or Centered KernelAlignment (CKA)."""
from __future__ import annotations
import loggingfrom dataclasses import dataclass, field
import numpy as npimport torch
logger = logging.getLogger(__name__)
@dataclassclass AlignmentResult: """Results from a brain-alignment benchmark run."""
method: str aggregate_score: float roi_scores: dict[str, float] = field(default_factory=dict) n_stimuli: int = 0
def _compute_rdm(features: np.ndarray) -> np.ndarray: """Compute a representational dissimilarity matrix (1 - cosine sim).""" norms = np.linalg.norm(features, axis=1, keepdims=True) norms = np.where(norms > 0, norms, 1.0) normalised = features / norms sim = normalised @ normalised.T return 1.0 - sim
def _rsa_score(model_features: np.ndarray, brain_features: np.ndarray) -> float: """Representational Similarity Analysis via Spearman correlation of RDMs.""" from scipy.stats import spearmanr
rdm_model = _compute_rdm(model_features) rdm_brain = _compute_rdm(brain_features) # Extract upper triangle (excluding diagonal) idx = np.triu_indices(rdm_model.shape[0], k=1) corr, _ = spearmanr(rdm_model[idx], rdm_brain[idx]) return float(corr) if not np.isnan(corr) else 0.0
def _linear_cka(X: np.ndarray, Y: np.ndarray) -> float: """Compute linear Centered Kernel Alignment between two feature matrices.
CKA uses Gram matrices (n x n) so it naturally handles different feature dimensions without truncation. """ n = X.shape[0] # Centre X = X - X.mean(axis=0) Y = Y - Y.mean(axis=0) # Gram matrices (n x n, dimension-independent) XX = X @ X.T # (n, n) YY = Y @ Y.T # (n, n) # HSIC via Gram matrices - works regardless of feature dimensions hsic_xy = np.trace(XX @ YY) / (n - 1) ** 2 hsic_xx = np.trace(XX @ XX) / (n - 1) ** 2 hsic_yy = np.trace(YY @ YY) / (n - 1) ** 2 denom = np.sqrt(hsic_xx * hsic_yy) if denom < 1e-12: return 0.0 return float(hsic_xy / denom)
def _procrustes_score(X: np.ndarray, Y: np.ndarray) -> float: """Procrustes analysis: rotation-invariant shape comparison.
Works with different feature dimensions by truncating to the smaller dimension. """ # Match dimensions by truncating to min(d_x, d_y) min_dim = min(X.shape[1], Y.shape[1]) X = X[:, :min_dim] Y = Y[:, :min_dim] # Centre and scale X = X - X.mean(axis=0) Y = Y - Y.mean(axis=0) norm_x = np.linalg.norm(X) norm_y = np.linalg.norm(Y) if norm_x < 1e-12 or norm_y < 1e-12: return 0.0 X = X / norm_x Y = Y / norm_y # Optimal rotation via SVD M = Y.T @ X U, _, Vt = np.linalg.svd(M, full_matrices=False) R = U @ Vt rotated = Y @ R # Score = 1 - normalized Procrustes distance dist = np.linalg.norm(X - rotated) return float(max(0.0, 1.0 - dist))
_METHODS = { "rsa": _rsa_score, "cka": _linear_cka, "procrustes": _procrustes_score,}
class BrainAlignmentBenchmark: """Benchmark AI model representations against predicted brain responses.
Example ------- >>> bench = BrainAlignmentBenchmark(brain_predictions) >>> result = bench.score_model(clip_features, method="rsa") >>> print(result.aggregate_score) 0.42 """
def __init__( self, brain_predictions: np.ndarray, roi_indices: dict[str, np.ndarray] | None = None, ): """ Parameters ---------- brain_predictions : np.ndarray Array of shape ``(n_stimuli, n_vertices)`` with predicted fMRI responses from TRIBE v2 for a set of stimuli. roi_indices : dict[str, np.ndarray], optional HCP ROI name to vertex index mapping for per-ROI scoring. """ self.brain_predictions = brain_predictions self.roi_indices = roi_indices
@classmethod def from_pretrained( cls, checkpoint_dir: str = "facebook/tribev2", roi_indices: dict[str, np.ndarray] | None = None, **kwargs, ) -> BrainAlignmentBenchmark: """Create a benchmark instance with a loaded TRIBE v2 model.
The model is stored so you can call :meth:`score_model_with_stimuli` to generate brain predictions on the fly. """ instance = cls(brain_predictions=np.array([]), roi_indices=roi_indices) instance._checkpoint_dir = checkpoint_dir instance._model_kwargs = kwargs instance._model = None return instance
def _ensure_model(self): if self._model is None: from cortexlab.inference.predictor import TribeModel
self._model = TribeModel.from_pretrained( self._checkpoint_dir, **self._model_kwargs )
def score_model( self, model_features: np.ndarray, method: str = "rsa", roi_filter: list[str] | None = None, brain_predictions: np.ndarray | None = None, ) -> AlignmentResult: """Score how brain-aligned a set of model features are.
Parameters ---------- model_features : np.ndarray Feature matrix of shape ``(n_stimuli, D)`` extracted from any AI model for the same stimuli used to generate the brain predictions. method : str Comparison method: ``"rsa"``, ``"cka"``, or ``"procrustes"``. roi_filter : list[str], optional If set, only compute alignment for these ROIs. brain_predictions : np.ndarray, optional Override the stored brain predictions.
Returns ------- AlignmentResult """ if method not in _METHODS: raise ValueError(f"Unknown method {method!r}. Choose from {list(_METHODS)}")
brain = brain_predictions if brain_predictions is not None else self.brain_predictions score_fn = _METHODS[method]
if model_features.shape[0] != brain.shape[0]: raise ValueError( f"Stimulus count mismatch: model has {model_features.shape[0]}, " f"brain has {brain.shape[0]}" )
# Aggregate score (full vertex space) aggregate = score_fn(model_features, brain)
# Per-ROI scores roi_scores = {} if self.roi_indices is not None: rois = self.roi_indices if roi_filter: rois = {k: v for k, v in rois.items() if k in roi_filter} for name, vertices in rois.items(): valid = vertices[vertices < brain.shape[1]] if len(valid) < 2: continue roi_brain = brain[:, valid] roi_scores[name] = score_fn(model_features, roi_brain)
return AlignmentResult( method=method, aggregate_score=aggregate, roi_scores=roi_scores, n_stimuli=model_features.shape[0], )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276"""Cognitive load scoring from predicted brain activation patterns.
Maps TRIBE v2's predicted fMRI responses onto cognitive dimensionsusing established HCP MMP1.0 ROI groupings associated with differentcognitive functions."""
from __future__ import annotations
import loggingfrom dataclasses import dataclass, field
import numpy as np
logger = logging.getLogger(__name__)
# HCP MMP1.0 ROI groupings for cognitive dimensions.# Each dimension maps to ROIs known to be involved in that function.COGNITIVE_ROI_MAP: dict[str, list[str]] = { "executive_load": [ # Dorsolateral prefrontal cortex "46", "9-46d", "p9-46v", "a9-46v", "9a", "8Av", "8Ad", "8BL", "8C", # Anterior cingulate cortex "p32pr", "a32pr", "d32", "p24", "a24", # Frontal eye fields "FEF", "PEF", ], "visual_complexity": [ # Early visual "V1", "V2", "V3", "V4", # Ventral stream (object recognition) "FFC", "VVC", "VMV1", "VMV2", "VMV3", # Fusiform "PHA1", "PHA2", "PHA3", # Motion / dorsal "V3A", "V3B", "V6", "V6A", "V7", "MT", "MST", "FST", "V4t", ], "auditory_demand": [ # Primary auditory "A1", "LBelt", "MBelt", "PBelt", "RI", # Auditory association "A4", "A5", "STSdp", "STSda", "STSvp", "STSva", "TA2", ], "language_processing": [ # Broca's area (inferior frontal) "44", "45", "IFJa", "IFJp", "IFSp", "IFSa", # Wernicke's area (posterior temporal) "TPOJ1", "TPOJ2", "TPOJ3", "STV", "PSL", # Angular gyrus / semantic "PGi", "PGs", "PFm", # Temporal pole "TGd", "TGv", "TE1a", "TE1p", "TE2a", "TE2p", ],}
@dataclassclass CognitiveLoadResult: """Result of cognitive load scoring."""
overall_load: float visual_complexity: float auditory_demand: float language_processing: float executive_load: float timeline: list[tuple[float, dict[str, float]]] = field(default_factory=list)
class CognitiveLoadScorer: """Predict cognitive demand of media content from brain activation patterns.
Uses predicted fMRI responses from TRIBE v2 and maps them onto cognitive dimensions via HCP MMP1.0 ROI groupings.
Example ------- >>> scorer = CognitiveLoadScorer(roi_indices) >>> result = scorer.score_predictions(predictions) >>> print(f"Overall load: {result.overall_load:.2f}") """
def __init__( self, roi_indices: dict[str, np.ndarray], cognitive_map: dict[str, list[str]] | None = None, baseline_activation: float | None = None, ): """ Parameters ---------- roi_indices : dict[str, np.ndarray] HCP ROI name to vertex index mapping (from ``get_hcp_labels``). cognitive_map : dict[str, list[str]], optional Override the default cognitive ROI groupings. baseline_activation : float, optional Baseline activation level for normalisation. If None, uses the median activation across all vertices as baseline. """ self.roi_indices = roi_indices self.cognitive_map = cognitive_map or COGNITIVE_ROI_MAP self.baseline = baseline_activation
@classmethod def from_pretrained( cls, checkpoint_dir: str = "facebook/tribev2", **kwargs, ) -> CognitiveLoadScorer: """Create a scorer with a loaded TRIBE v2 model.
Lazily loads the model and ROI indices on first use. """ instance = cls.__new__(cls) instance._checkpoint_dir = checkpoint_dir instance._model_kwargs = kwargs instance._model = None instance.cognitive_map = COGNITIVE_ROI_MAP instance.baseline = None instance.roi_indices = None return instance
def _ensure_model(self): if self._model is None: from cortexlab.data.loader import get_hcp_labels from cortexlab.inference.predictor import TribeModel
self.roi_indices = get_hcp_labels(mesh="fsaverage5") self._model = TribeModel.from_pretrained( self._checkpoint_dir, **self._model_kwargs )
def _get_dimension_activation( self, vertex_data: np.ndarray, dimension: str ) -> float: """Compute mean activation for a cognitive dimension.""" roi_names = self.cognitive_map.get(dimension, []) activations = [] for roi in roi_names: vertices = self.roi_indices.get(roi) if vertices is None: continue valid = vertices[vertices < len(vertex_data)] if len(valid) > 0: activations.append(np.abs(vertex_data[valid]).mean()) if not activations: return 0.0 return float(np.mean(activations))
def score_predictions( self, predictions: np.ndarray, tr_seconds: float = 1.0, ) -> CognitiveLoadResult: """Score predicted brain activations for cognitive load.
Parameters ---------- predictions : np.ndarray Predicted brain activations of shape ``(n_timepoints, n_vertices)``. tr_seconds : float Duration of each TR in seconds (for timeline).
Returns ------- CognitiveLoadResult """ if predictions.ndim == 1: predictions = predictions[np.newaxis, :]
baseline = self.baseline if baseline is None: baseline = float(np.median(np.abs(predictions))) baseline = max(baseline, 1e-8)
dimensions = list(self.cognitive_map.keys()) dim_scores = {d: [] for d in dimensions} timeline = []
for t in range(predictions.shape[0]): vertex_data = predictions[t] t_scores = {} for dim in dimensions: raw = self._get_dimension_activation(vertex_data, dim) normalised = min(raw / baseline, 1.0) if baseline > 0 else 0.0 dim_scores[dim].append(normalised) t_scores[dim] = normalised timeline.append((t * tr_seconds, t_scores))
avg_scores = {d: float(np.mean(v)) if v else 0.0 for d, v in dim_scores.items()} overall = float(np.mean(list(avg_scores.values()))) if avg_scores else 0.0
return CognitiveLoadResult( overall_load=overall, visual_complexity=avg_scores.get("visual_complexity", 0.0), auditory_demand=avg_scores.get("auditory_demand", 0.0), language_processing=avg_scores.get("language_processing", 0.0), executive_load=avg_scores.get("executive_load", 0.0), timeline=timeline, )
def score(self, video_path: str = None, audio_path: str = None, text_path: str = None) -> CognitiveLoadResult: """End-to-end scoring from a media file.
Loads the model, runs inference, and scores the predictions. Exactly one of the path arguments must be provided. """ self._ensure_model() kwargs = {} if video_path: kwargs["video_path"] = video_path elif audio_path: kwargs["audio_path"] = audio_path elif text_path: kwargs["text_path"] = text_path else: raise ValueError("Provide one of video_path, audio_path, or text_path")
events = self._model.get_events_dataframe(**kwargs) predictions, _ = self._model.predict(events, verbose=False) return self.score_predictions(predictions)123from cortexlab.core.model import FmriEncoder, FmriEncoderModel, TemporalSmoothing
__all__ = ["FmriEncoder", "FmriEncoderModel", "TemporalSmoothing"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117"""ROI attention map extraction from the transformer encoder.
Provides :class:`AttentionExtractor`, a context manager that hooks intothe encoder's attention layers and captures per-head attention weightsduring a forward pass. The raw maps can then be projected onto HCPMMP1.0 brain ROIs via :func:`attention_to_roi_scores`."""
from __future__ import annotations
import loggingfrom contextlib import contextmanager
import numpy as npimport torchfrom torch import nn
logger = logging.getLogger(__name__)
@contextmanagerdef AttentionExtractor(encoder: nn.Module): """Context manager that captures attention weights from transformer layers.
Registers forward hooks on every sub-module whose class name contains ``"Attention"`` (case-insensitive). Each hook stores the second element of the output tuple (the attention weights) if the layer returns one, or falls back to a ``_attn_weights`` attribute when present.
Yields ------ attn_maps : list[torch.Tensor] Mutable list that accumulates attention tensors of shape ``(B, heads, T, T)`` as the model runs its forward pass.
Example ------- >>> with AttentionExtractor(model.encoder) as maps: ... out = model(batch) >>> len(maps) # one tensor per attention layer 8 """ attn_maps: list[torch.Tensor] = [] hooks = []
for module in encoder.modules(): if "attention" in module.__class__.__name__.lower():
def _hook(mod, inp, out, store=attn_maps): if isinstance(out, tuple) and len(out) >= 2: second = out[1] if second is not None: if hasattr(second, "post_softmax_attn") and second.post_softmax_attn is not None: store.append(second.post_softmax_attn.detach()) elif hasattr(second, "detach"): store.append(second.detach()) elif hasattr(mod, "_attn_weights") and mod._attn_weights is not None: store.append(mod._attn_weights.detach())
hooks.append(module.register_forward_hook(_hook))
try: yield attn_maps finally: for h in hooks: h.remove()
def attention_to_roi_scores( attn_maps: list[torch.Tensor], roi_indices: dict[str, np.ndarray], predictor_weights: torch.Tensor | None = None,) -> dict[str, np.ndarray]: """Project raw attention maps onto brain ROIs.
Parameters ---------- attn_maps : list[torch.Tensor] Attention tensors from :class:`AttentionExtractor`, each of shape ``(B, heads, T, T)``. roi_indices : dict[str, np.ndarray] Mapping from ROI name to vertex indices (e.g. from :func:`cortexlab.data.loader.get_hcp_labels`). predictor_weights : torch.Tensor, optional Predictor layer weights of shape ``(n_subjects, hidden, n_vertices)`` or ``(hidden, n_vertices)``. When provided, each ROI's temporal profile is weighted by the L2 norm of the predictor weights for its vertices, emphasising ROIs the model attends to more strongly.
Returns ------- dict[str, np.ndarray] Mapping from ROI name to a 1-D temporal importance array of length ``T`` (number of time steps in the attention maps). """ if not attn_maps: return {name: np.array([]) for name in roi_indices}
# Stack layers, average over batch and heads -> (T, T) stacked = torch.stack(attn_maps) # (layers, B, heads, T, T) avg_attn = stacked.mean(dim=(0, 1, 2)) # (T, T) # Per-timestep importance: sum over keys for each query position temporal_importance = avg_attn.sum(dim=-1).cpu().numpy() # (T,)
roi_scores: dict[str, np.ndarray] = {} for name, vertices in roi_indices.items(): if predictor_weights is not None: w = predictor_weights if w.ndim == 3: w = w.mean(dim=0) # average across subjects # Weight = L2 norm of predictor weights for this ROI's vertices roi_weight = w[:, vertices].norm(dim=0).mean().item() else: roi_weight = 1.0 roi_scores[name] = temporal_importance * roi_weight
return roi_scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.## Modified by CortexLab contributors: added return_attn support and# compile_backbone option.
import loggingimport typing as tp
import torchfrom einops import rearrangefrom neuralset.dataloader import SegmentDatafrom neuraltrain.models.base import BaseModelConfigfrom neuraltrain.models.common import Mlp, SubjectLayers, SubjectLayersModelfrom neuraltrain.models.transformer import TransformerEncoderfrom torch import nn
logger = logging.getLogger(__name__)
class TemporalSmoothing(BaseModelConfig): kernel_size: int = 9 sigma: float | None = None
def build(self, dim: int) -> nn.Module:
def gaussian_kernel_1d(kernel_size: int, sigma: float): x = torch.arange(kernel_size) - kernel_size // 2 kernel = torch.exp(-0.5 * (x / sigma) ** 2) kernel = kernel / kernel.sum() return kernel.view(1, 1, -1)
conv = nn.Conv1d( dim, dim, kernel_size=self.kernel_size, padding=self.kernel_size // 2, bias=False, groups=dim, ) if self.sigma is not None: kernel = gaussian_kernel_1d(kernel_size=self.kernel_size, sigma=self.sigma) kernel = kernel.repeat(dim, 1, 1) conv.weight.data = kernel conv.requires_grad = False return conv
class FmriEncoder(BaseModelConfig):
# architecture projector: BaseModelConfig = Mlp(norm_layer="layer", activation_layer="gelu") combiner: Mlp | None = Mlp(norm_layer="layer", activation_layer="gelu") encoder: TransformerEncoder | None = TransformerEncoder() # other hyperparameters time_pos_embedding: bool = True subject_embedding: bool = False subject_layers: SubjectLayers | None = SubjectLayers() hidden: int = 256 max_seq_len: int = 1024 dropout: float = 0.0 extractor_aggregation: tp.Literal["stack", "sum", "cat"] = "cat" layer_aggregation: tp.Literal["mean", "cat"] = "cat" linear_baseline: bool = False modality_dropout: float = 0.0 temporal_dropout: float = 0.0 low_rank_head: int | None = None temporal_smoothing: TemporalSmoothing | None = None # CortexLab additions compile_backbone: bool = False
def model_post_init(self, __context): if self.encoder is not None: for key in ["attn_dropout", "ff_dropout", "layer_dropout"]: setattr(self.encoder, key, self.dropout) if hasattr(self.projector, "dropout"): self.projector.dropout = self.dropout return super().model_post_init(__context)
def build( self, feature_dims: dict[int], n_outputs: int, n_output_timesteps: int ) -> nn.Module: return FmriEncoderModel( feature_dims, n_outputs, n_output_timesteps, config=self, )
class FmriEncoderModel(nn.Module):
def __init__( self, feature_dims: dict[str, tuple[int, int]], n_outputs: int, n_output_timesteps: int, config: FmriEncoder, ): super().__init__() self.config = config self.feature_dims = feature_dims self.n_outputs = n_outputs self.n_output_timesteps = n_output_timesteps self.projectors = nn.ModuleDict() self.pooler = nn.AdaptiveAvgPool1d(n_output_timesteps) hidden = config.hidden for modality, tup in feature_dims.items(): if tup is None: logger.warning( "%s has no feature dimensions. Skipping projector.", modality ) continue else: num_layers, feature_dim = tup input_dim = ( feature_dim * num_layers if config.layer_aggregation == "cat" else feature_dim ) output_dim = ( hidden // len(feature_dims) if config.extractor_aggregation == "cat" else hidden ) self.projectors[modality] = self.config.projector.build( input_dim, output_dim ) input_dim = ( (hidden // len(feature_dims)) * len(feature_dims) if config.extractor_aggregation == "cat" else hidden ) if self.config.combiner is not None: self.combiner = self.config.combiner.build(input_dim, hidden) else: assert ( hidden % len(feature_dims) == 0 ), "hidden must be divisible by the number of modalities if there is no combiner" self.combiner = nn.Identity() if config.low_rank_head is not None: self.low_rank_head = nn.Linear(hidden, config.low_rank_head, bias=False) bottleneck = config.low_rank_head else: bottleneck = hidden self.predictor = config.subject_layers.build( in_channels=bottleneck, out_channels=n_outputs, ) if config.temporal_smoothing is not None: self.temporal_smoothing = config.temporal_smoothing.build(dim=hidden) if not config.linear_baseline: if config.time_pos_embedding: self.time_pos_embed = nn.Parameter( torch.randn(1, config.max_seq_len, hidden) ) if config.subject_embedding: self.subject_embed = nn.Embedding(config.n_subjects, hidden) self.encoder = config.encoder.build(dim=hidden) if config.compile_backbone: self.encoder = torch.compile(self.encoder)
@property def device(self) -> torch.device: return next(self.parameters()).device
def forward( self, batch: SegmentData, pool_outputs: bool = True, return_attn: bool = False, ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]: """Run forward pass.
Parameters ---------- batch : SegmentData Input batch with modality features. pool_outputs : bool Whether to pool temporal outputs to n_output_timesteps. return_attn : bool If True, return (predictions, attention_weights) tuple. Attention weights are collected via hooks on the encoder's attention layers during the forward pass.
Returns ------- torch.Tensor or tuple[torch.Tensor, list[torch.Tensor]] Predictions of shape (B, n_outputs, T), or a tuple of (predictions, attention_maps) when return_attn is True. """ attn_maps = [] hooks = [] if return_attn and hasattr(self, "encoder"): for module in self.encoder.modules(): if "attention" in module.__class__.__name__.lower(): def _hook(mod, inp, out, store=attn_maps): if isinstance(out, tuple) and len(out) >= 2: second = out[1] if second is not None: if hasattr(second, "post_softmax_attn") and second.post_softmax_attn is not None: store.append(second.post_softmax_attn.detach()) elif isinstance(second, torch.Tensor): store.append(second.detach()) elif hasattr(mod, "_attn_weights") and mod._attn_weights is not None: store.append(mod._attn_weights.detach()) hooks.append(module.register_forward_hook(_hook))
x = self.aggregate_features(batch) # B, T, H subject_id = batch.data.get("subject_id", None) if hasattr(self, "temporal_smoothing"): x = self.temporal_smoothing(x.transpose(1, 2)).transpose(1, 2) if not self.config.linear_baseline: x = self.transformer_forward(x, subject_id) x = x.transpose(1, 2) # B, H, T if self.config.low_rank_head is not None: x = self.low_rank_head(x.transpose(1, 2)).transpose(1, 2) x = self.predictor(x, subject_id) # B, O, T if pool_outputs: out = self.pooler(x) # B, O, T' else: out = x
for h in hooks: h.remove()
if return_attn: return out, attn_maps return out
def aggregate_features(self, batch): tensors = [] # get B, T for modality in batch.data.keys(): if modality in self.feature_dims: break x = batch.data[modality] B, T = x.shape[0], x.shape[-1] for modality in self.feature_dims.keys(): if modality not in self.projectors or modality not in batch.data: data = torch.zeros( B, T, self.config.hidden // len(self.feature_dims) ).to(x.device) else: data = batch.data[modality] # B, L, H, T data = data.to(torch.float32) if data.ndim == 3: data = data.unsqueeze(1) # mean over layers if self.config.layer_aggregation == "mean": data = data.mean(dim=1) elif self.config.layer_aggregation == "cat": data = rearrange(data, "b l d t -> b (l d) t") data = data.transpose(1, 2) assert data.ndim == 3 # B, T, D if isinstance(self.projectors[modality], SubjectLayersModel): data = self.projectors[modality]( data.transpose(1, 2), batch.data["subject_id"] ).transpose(1, 2) else: data = self.projectors[modality](data) # B, T, H if self.config.modality_dropout > 0 and self.training: mask = torch.rand(data.shape[0]) < self.config.modality_dropout data[mask, :] = torch.zeros_like(data[mask, :]) tensors.append(data) if self.config.extractor_aggregation == "stack": out = torch.cat(tensors, dim=1) elif self.config.extractor_aggregation == "cat": out = torch.cat(tensors, dim=-1) elif self.config.extractor_aggregation == "sum": out = sum(tensors) if self.config.temporal_dropout > 0 and self.training: for batch_idx in range(out.shape[0]): mask = torch.rand(out.shape[1]) < self.config.temporal_dropout out[batch_idx, mask, :] = torch.zeros_like(out[batch_idx, mask, :]) return out
def transformer_forward(self, x, subject_id=None): x = self.combiner(x) if hasattr(self, "time_pos_embed"): x = x + self.time_pos_embed[:, : x.size(1)] if hasattr(self, "subject_embed"): x = x + self.subject_embed(subject_id) x = self.encoder(x) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177"""Cross-subject adaptation for the fMRI encoder.
Provides :class:`SubjectAdapter` with two strategies for adapting thepre-trained model to a new, unseen subject from a small calibration set:
* **Ridge regression** fits a new predictor head from calibration fMRI.* **Nearest-neighbour** picks the most similar training subject (zero-shot)."""
from __future__ import annotations
import logging
import numpy as npimport torchfrom torch import nnfrom torch.utils.data import DataLoader
logger = logging.getLogger(__name__)
class SubjectAdapter: """Holds new-subject predictor weights ready for injection into a model."""
def __init__(self, weights: torch.Tensor, bias: torch.Tensor | None = None): self._weights = weights # (1, in_channels, n_outputs) self._bias = bias # (1, n_outputs) or None
@classmethod def from_ridge( cls, model: nn.Module, calibration_loader: DataLoader, regularization: float = 1e-3, device: str | torch.device = "cpu", ) -> SubjectAdapter: """Fit a ridge-regression predictor head from calibration data.
Runs the frozen backbone on every batch in *calibration_loader*, collects hidden states and fMRI targets, then solves the normal equations ``W* = (X^T X + lambda I)^{-1} X^T y``.
Parameters ---------- model : nn.Module The :class:`FmriEncoderModel` instance (must be in eval mode). calibration_loader : DataLoader Provides ``(batch, ...)`` where ``batch.data["fmri"]`` contains ground-truth fMRI for the new subject. regularization : float Ridge penalty (lambda). device : str or torch.device Device for computation. """ model.eval() all_hidden, all_targets = [], []
with torch.inference_mode(): for batch in calibration_loader: batch = batch.to(device) x = model.aggregate_features(batch) if hasattr(model, "temporal_smoothing"): x = model.temporal_smoothing(x.transpose(1, 2)).transpose(1, 2) if not model.config.linear_baseline: x = model.transformer_forward(x) x = x.transpose(1, 2) # B, H, T if model.config.low_rank_head is not None: x = model.low_rank_head(x.transpose(1, 2)).transpose(1, 2) # Pool to match target temporal dimension x = model.pooler(x) # B, H, T' target = batch.data["fmri"] # B, V, T'
# Flatten time: (B*T', H) and (B*T', V) B, H, T = x.shape x_flat = x.permute(0, 2, 1).reshape(-1, H) t_flat = target.permute(0, 2, 1).reshape(-1, target.shape[1]) all_hidden.append(x_flat.cpu()) all_targets.append(t_flat.cpu())
X = torch.cat(all_hidden, dim=0).float() # (N, H) Y = torch.cat(all_targets, dim=0).float() # (N, V)
# Ridge regression: W = (X^T X + lambda I)^{-1} X^T Y XtX = X.T @ X reg = regularization * torch.eye(XtX.shape[0]) W = torch.linalg.solve(XtX + reg, X.T @ Y) # (H, V) weights = W.unsqueeze(0) # (1, H, V)
logger.info( "Ridge adapter fitted: %d samples, hidden=%d, vertices=%d", X.shape[0], X.shape[1], Y.shape[1], ) return cls(weights=weights)
@classmethod def from_nearest_neighbor( cls, model: nn.Module, calibration_loader: DataLoader, device: str | torch.device = "cpu", ) -> SubjectAdapter: """Zero-shot adaptation by finding the closest training subject.
Computes a mean hidden-state signature for the new subject and matches it to each training subject's predictor weight signature via cosine similarity.
Parameters ---------- model : nn.Module The :class:`FmriEncoderModel` instance. calibration_loader : DataLoader Provides calibration batches for the new subject. device : str or torch.device Device for computation. """ model.eval() all_hidden = []
with torch.inference_mode(): for batch in calibration_loader: batch = batch.to(device) x = model.aggregate_features(batch) if hasattr(model, "temporal_smoothing"): x = model.temporal_smoothing(x.transpose(1, 2)).transpose(1, 2) if not model.config.linear_baseline: x = model.transformer_forward(x) all_hidden.append(x.mean(dim=(0, 1)).cpu())
new_sig = torch.stack(all_hidden).mean(dim=0) # (H,)
# Compare against each training subject's predictor weights pred_weights = model.predictor.weights # (n_subjects, in_ch, out_ch) n_subjects = pred_weights.shape[0] best_sim, best_idx = -1.0, 0 for i in range(n_subjects): w_sig = pred_weights[i].mean(dim=-1).cpu() # (in_ch,) # Truncate/pad to match dimensions if needed dim = min(w_sig.shape[0], new_sig.shape[0]) sim = torch.nn.functional.cosine_similarity( w_sig[:dim].unsqueeze(0), new_sig[:dim].unsqueeze(0) ).item() if sim > best_sim: best_sim = sim best_idx = i
logger.info( "Nearest-neighbour match: subject %d (cosine sim %.4f)", best_idx, best_sim ) weights = pred_weights[best_idx : best_idx + 1].detach().cpu() bias = None if hasattr(model.predictor, "bias") and model.predictor.bias is not None: bias = model.predictor.bias[best_idx : best_idx + 1].detach().cpu() return cls(weights=weights, bias=bias)
def inject_into_model(self, model: nn.Module) -> int: """Append the adapted weights as a new subject in the predictor.
Returns the integer subject ID assigned to the new subject. """ pred = model.predictor old_weights = pred.weights.data # (n_subjects, in_ch, out_ch) new_weights = self._weights.to(old_weights.device) pred.weights = nn.Parameter( torch.cat([old_weights, new_weights], dim=0) ) new_id = old_weights.shape[0]
if self._bias is not None and hasattr(pred, "bias") and pred.bias is not None: old_bias = pred.bias.data new_bias = self._bias.to(old_bias.device) pred.bias = nn.Parameter(torch.cat([old_bias, new_bias], dim=0))
logger.info("Injected new subject as ID %d", new_id) return new_id123456789101112131415from cortexlab.data.loader import ( MultiStudyLoader, get_hcp_labels, get_hcp_roi_indices, get_topk_rois, summarize_by_roi,)
__all__ = [ "MultiStudyLoader", "get_hcp_labels", "get_hcp_roi_indices", "get_topk_rois", "summarize_by_roi",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import re
import typing as tp
from enum import Enum
import neuralset as ns
import numpy as np
import pydantic
from neuralset.extractors.neuro import FSAVERAGE_SIZES
class _FmriTemplateSpaceSpec(tp.NamedTuple):
id: str
shape: tp.Tuple[int, int, int] | None
class FmriTemplateSpace(Enum):
# MNI - TEMPLATEFLOW (partial)
# We keep only 1mm-resolution variants as res mapping is handled by vol_to_surf
MNI152LIN_RES_01 = _FmriTemplateSpaceSpec("tpl-MNI152Lin_res-01", (181, 217, 181))
MNI152NLIN2009A_ASYM_RES_1 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin2009aAsym_res-1", (197, 233, 189)
)
MNI152NLIN2009A_SYM_RES_1 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin2009aSym_res-1", (197, 233, 189)
)
MNI152NLIN2009C_ASYM_RES_01 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin2009cAsym_res-01", (193, 229, 193)
)
MNI152NLIN2009C_SYM_RES_1 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin2009cSym_res-1", (193, 229, 193)
)
MNI152NLIN6_ASYM_RES_01 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin6Asym_res-01", (182, 218, 182)
)
MNI152NLIN6_SYM_RES_01 = _FmriTemplateSpaceSpec(
"tpl-MNI152NLin6Asym_res-01", (193, 229, 193)
)
MNI305 = _FmriTemplateSpaceSpec("tpl-MNI305", (172, 220, 156))
MNICOLIN27 = _FmriTemplateSpaceSpec("tpl-MNIColin27", (181, 217, 181))
# FSAVERAGE
FSAVERAGE = _FmriTemplateSpaceSpec("fsaverage", (163842,))
FSAVERAGE_6 = _FmriTemplateSpaceSpec("fsaverage6", (40962,))
FSAVERAGE_5 = _FmriTemplateSpaceSpec("fsaverage5", (10242,))
FSAVERAGE_4 = _FmriTemplateSpaceSpec("fsaverage4", (2562,))
FSAVERAGE_3 = _FmriTemplateSpaceSpec("fsaverage3", (642,))
# CIFTI
CIFTI_HCP_FS_LR_32K = _FmriTemplateSpaceSpec("cifti-hcp-fs_LR_32k", (59412,))
CIFTI_HCP_FS_LR_164K = _FmriTemplateSpaceSpec("cifti-hcp-fs_LR_164k", (170494,))
# NATIVE
T1W = _FmriTemplateSpaceSpec("T1w", None)
# OTHER
MNI_UNKNOWN = _FmriTemplateSpaceSpec("MNI_unknown", None) # unknown MNI space
UNKNOWN = _FmriTemplateSpaceSpec("unknown", None) # unknown space
CUSTOM = _FmriTemplateSpaceSpec(
"custom", None
) # custom space e.g. provided by study authors
def is_mni_space(space: FmriTemplateSpace) -> bool:
"""
Check if the given template space is an MNI space.
"""
return space.name.startswith("MNI")
def load_mni_mesh(
template: FmriTemplateSpace,
target_space="fsaverage",
base_path: str | None = None,
) -> dict:
"""
Load MNI surface meshes for both hemispheres and white / pial surfaces.
Parameters
----------
template : FmriTemplateSpace
target_space : str
base_path : str or None
Root directory containing FreeSurfer subjects. If ``None``, reads
from the ``FREESURFER_SUBJECTS_DIR`` environment variable.
Returns
-------
meshes : dict
Dictionary with keys like 'pial_left', 'pial_right', 'white_left', 'white_right'
and values as loaded nilearn surface meshes.
"""
import os
if not re.match(r"^fsaverage[3-6]?$", target_space):
raise ValueError(
f"target_space must be 'fsaverage' or 'fsaverage3/4/5/6', got '{target_space}'"
)
if not is_mni_space(template):
raise ValueError(
f"Template {template.value.id} is required to be an MNI space."
)
if base_path is None:
base_path = os.getenv("FREESURFER_SUBJECTS_DIR")
if base_path is None:
raise EnvironmentError(
"Set the FREESURFER_SUBJECTS_DIR environment variable to the "
"directory containing FreeSurfer subjects, or pass base_path explicitly."
)
from nilearn.surface import load_surf_mesh
mesh_dir = os.path.join(base_path, template.value.id, "surf", "surf_hybrid_mni_gii")
meshes = {}
for surf in ["pial", "white"]:
for hemi in ["left", "right"]:
mesh_path = os.path.join(mesh_dir, f"{hemi[0]}h.{surf}.{target_space}.gii")
meshes[f"{surf}_{hemi}"] = load_surf_mesh(mesh_path)
return meshes
class TribeSurfaceProjector(ns.extractors.neuro.SurfaceProjector):
"""Project data to an fsaverage surface mesh.
For volumetric data, this uses ``nilearn.surface.vol_to_surf`` to project the data to the surface.
For surface data, this simply downsamples the data to the target mesh resolution.
Fields beyond ``mesh`` mirror the keyword arguments of
``nilearn.surface.vol_to_surf`` and are forwarded to it.
Examples
--------
>>> SurfaceProjector(mesh="fsaverage5")
>>> SurfaceProjector(mesh="fsaverage6", radius=5.0, interpolation="nearest")
"""
mesh: str
radius: float = 3.0
interpolation: tp.Literal["linear", "nearest"] = "linear"
kind: tp.Literal["auto", "line", "ball"] = "auto"
n_samples: int | None = None
mask_img: tp.Any | None = None
depth: list[float] | None = None
center_depth: float = 1
extract_fsaverage_from_mni: bool = False
_mesh: tp.Any | None = pydantic.PrivateAttr(default=None)
def model_post_init(self, __context: tp.Any) -> None:
super().model_post_init(__context)
assert (
self.center_depth >= 0 and self.center_depth <= 1
), "center_depth must be between 0 and 1"
if self.mesh not in FSAVERAGE_SIZES:
raise ValueError(f"mesh must be an fsaverage mesh (got {self.mesh!r})")
def get_mesh(self) -> tp.Any:
if self._mesh is None:
if self.extract_fsaverage_from_mni:
mni_template_spec = FmriTemplateSpace["MNI152NLIN2009C_ASYM_RES_01"]
fsaverage = load_mni_mesh(mni_template_spec, self.mesh)
else:
from nilearn import datasets
fsaverage = datasets.fetch_surf_fsaverage(self.mesh)
self._mesh = fsaverage
return self._mesh
def get_intermediate_mesh(
self, hemi: str, center_depth: float = 0.5
) -> tuple[np.ndarray, np.ndarray]:
meshes = self.get_mesh()
surf_mesh, inner_mesh = meshes[f"pial_{hemi}"], meshes[f"white_{hemi}"]
from nilearn.surface import InMemoryMesh
if isinstance(surf_mesh, str):
import nibabel
surf_vertices, surf_faces = nibabel.load(surf_mesh).darrays
inner_vertices, inner_faces = nibabel.load(inner_mesh).darrays
surf_vertices, surf_faces = surf_vertices.data, surf_faces.data
inner_vertices, inner_faces = inner_vertices.data, inner_faces.data
elif isinstance(surf_mesh, InMemoryMesh):
surf_vertices, surf_faces = surf_mesh.coordinates, surf_mesh.faces
inner_vertices, inner_faces = inner_mesh.coordinates, inner_mesh.faces
else:
raise TypeError(f"Unsupported mesh type: {type(surf_mesh)}")
half_vertices = surf_vertices * center_depth + inner_vertices * (
1 - center_depth
)
half_depth_mesh = (half_vertices, surf_faces)
return half_depth_mesh
def apply(self, rec: tp.Any) -> np.ndarray:
if len(rec.shape) == 4:
# 4-D volume data → use nilearn.surface.vol_to_surf
meshes = self.get_mesh()
from nilearn.surface import vol_to_surf
hemis = []
for hemi in ("left", "right"):
if self.center_depth == 1:
surf_mesh = meshes[f"pial_{hemi}"]
else:
surf_mesh = self.get_intermediate_mesh(hemi, self.center_depth)
hemis.append(
vol_to_surf(
rec,
surf_mesh=surf_mesh,
inner_mesh=meshes[f"white_{hemi}"],
radius=self.radius,
interpolation=self.interpolation,
kind=self.kind,
n_samples=self.n_samples,
mask_img=self.mask_img,
depth=self.depth,
)
)
return np.vstack(hemis)
elif len(rec.shape) == 2:
# 2-D surface data → downsample to target mesh resolution
n_vertices = rec.shape[0] // 2
if n_vertices not in list(FSAVERAGE_SIZES.values()) or rec.shape[0] % 2:
msg = f"The detected number of vertices ({rec.shape[0]}) is not in {list(FSAVERAGE_SIZES.values())}"
raise ValueError(msg)
n_vertices_resampled = FSAVERAGE_SIZES.get(self.mesh)
data = rec.get_fdata()
if n_vertices < n_vertices_resampled:
raise NotImplementedError(
f"Cannot upsample from {n_vertices} vertices to {n_vertices_resampled} vertices"
)
if n_vertices > n_vertices_resampled:
left = data[:n_vertices_resampled, :]
right = data[n_vertices : n_vertices + n_vertices_resampled, :]
data = np.concatenate([left, right], axis=0)
return data
else:
raise ValueError(
f"Unexpected shape {rec.shape} (should have 2 or 4 dimensions)"
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
from collections import Counter, OrderedDict, defaultdict
from functools import lru_cache
from pathlib import Path
import exca
import mne
import neuralset as ns
import numpy as np
import pandas as pd
from neuralset.events.study import Chain, Study
from neuralset.events.transforms import EventsBuilder, EventsTransform
from neuralset.extractors.neuro import FSAVERAGE_SIZES
from cortexlab.data.transforms import RemoveDuplicates
FMRI_SPACES = {
"Algonauts2025Bold": "MNI152NLIN2009C_ASYM_RES_01",
"Wen2017": "MNI152NLIN6_ASYM_RES_01",
"Lahner2024Bold": "MNI152NLIN2009C_ASYM_RES_01",
"Lebel2023Bold": "MNI152NLIN2009C_ASYM_RES_01",
"Vanessen2023": "MNI152NLIN6_ASYM_RES_01",
"Aliko2020": "MNICOLIN27",
"Li2022": "MNICOLIN27",
"Nastase2020": "MNI152NLIN2009C_ASYM_RES_01",
}
RECORDING_DURATIONS = {
"Algonauts2025Bold/sub-01": 66.4,
"Algonauts2025Bold/sub-02": 66.4,
"Algonauts2025Bold/sub-03": 66.4,
"Algonauts2025Bold/sub-04": 0,
"Algonauts2025Bold/sub-05": 66.4,
"Algonauts2025Bold/sub-06": 0,
"Lahner2024Bold/1": 6.2,
"Lahner2024Bold/10": 6.2,
"Lahner2024Bold/2": 6.2,
"Lahner2024Bold/3": 6.2,
"Lahner2024Bold/4": 6.2,
"Lahner2024Bold/5": 6.2,
"Lahner2024Bold/6": 6.2,
"Lahner2024Bold/7": 6.2,
"Lahner2024Bold/8": 6.2,
"Lahner2024Bold/9": 6.2,
"Lebel2023Bold/UTS01": 17.9,
"Lebel2023Bold/UTS02": 18.1,
"Lebel2023Bold/UTS03": 18.1,
"Lebel2023Bold/UTS04": 6.2,
"Lebel2023Bold/UTS05": 6.4,
"Lebel2023Bold/UTS06": 6.4,
"Lebel2023Bold/UTS07": 6.4,
"Lebel2023Bold/UTS08": 6.4,
"Wen2017/subject1": 11.7,
"Wen2017/subject2": 11.7,
"Wen2017/subject3": 11.7,
}
class MultiStudyLoader(EventsBuilder):
"""Config for loading multiple studies.
Note that the query and enhancers are shared across all studies.
For example, setting timeline_index == 0 will select the first timeline of each study.
"""
names: str | list[str]
path: str | Path
transforms: list[EventsTransform] | OrderedDict[str, EventsTransform] | None = None
query: str | None = None
studies_to_include: list[str] | None = None
infra_timelines: exca.MapInfra = exca.MapInfra(cluster="processpool", max_jobs=None)
def model_post_init(self, log__: tp.Any) -> None:
super().model_post_init(log__)
if self.studies_to_include is not None:
for name in self.studies_to_include:
if name not in self.names:
raise ValueError(f"Study {name} not found in {self.names}")
self.get_studies() # run this so that studies are registered (in case _run is cached)
@infra_timelines.apply(item_uid=str)
def dummy(self, items: tp.Iterable[str]) -> tp.Iterator[None]:
for item in items:
yield None
def get_studies(self) -> dict[str, Chain]:
studies = {}
if isinstance(self.names, str):
names = [self.names]
else:
names = self.names
for name in names:
studies[name] = Study(
name=name,
path=self.path,
query=self.query,
infra_timelines=self.infra_timelines,
)
return studies
def study_summary(self, apply_query: bool = True) -> pd.DataFrame:
summaries = []
for name, study in self.get_studies().items():
if (
apply_query
and self.studies_to_include is not None
and name not in self.studies_to_include
):
continue
summary = study.study_summary(apply_query=apply_query)
summary.loc[:, "study"] = name
summaries.append(summary)
return pd.concat(summaries, ignore_index=True)
def _run(self) -> pd.DataFrame:
dfs = []
for name, study in self.get_studies().items():
if (
self.studies_to_include is not None
and name not in self.studies_to_include
):
continue
chain = Chain(steps={"study": study, **OrderedDict(self.transforms)})
df = chain.run()
df.loc[:, "study"] = name
dfs.append(df)
out = pd.concat(dfs, ignore_index=True)
return out
def split_segments_by_time(
segments: list[ns.segments.Segment], val_ratio: float, split: str
) -> list[ns.segments.Segment]:
timeline_segments = defaultdict(list)
return_segments = []
for segment in segments:
if len(segment.ns_events) == 0:
continue
timeline = segment.ns_events[0].timeline
timeline_segments[timeline].append(segment)
for timeline, segments in timeline_segments.items():
start = min(segment.start for segment in segments)
stop = max(segment.stop for segment in segments)
split_time = start + (stop - start) * val_ratio
for segment in segments:
if split == "val" and segment.start < split_time:
return_segments.append(segment)
elif split == "train" and segment.start >= split_time:
return_segments.append(segment)
return return_segments
def assign_fmri_space(events: pd.DataFrame, space: str | None = None) -> pd.DataFrame:
assert events.study.nunique() == 1, "Only one study can be assigned at a time"
study_name = events.study.unique()[0]
if study_name not in FMRI_SPACES:
raise ValueError(f"Study {study_name} not found in FMRI_SPACES")
default_space = FMRI_SPACES[study_name]
assigned_space = space or default_space
events.loc[events.type == "Fmri", "space"] = assigned_space
return events
def set_study_in_average_subject_mode(
study: EventsBuilder, trigger_type: str, trigger_field: str = "filepath"
) -> EventsBuilder:
study.transforms["alignevents"] = ns.events.transforms.AlignEvents(
trigger_type=trigger_type, trigger_field=trigger_field, types_to_align="Event"
)
study.transforms["removeduplicates"] = RemoveDuplicates(
subset=["start", "stop", "filepath", "type"]
)
for key in ["chunksounds", "chunkvideos"]:
study.transforms.move_to_end(key)
return study
def get_subject_weights(
subject_id_mapping: dict[str, int],
weigh_by: tp.Literal[
"n_subjects", "speech", "video", "recording_time"
] = "n_subjects",
) -> dict[str, float]:
subject_weights = []
if weigh_by in ["speech", "video"]:
for subject in subject_id_mapping:
if weigh_by == "speech":
weight = int(subject.startswith("Lebel"))
elif weigh_by == "video":
weight = int(subject.startswith("Algonauts"))
subject_weights.append(float(weight))
elif weigh_by == "recording_time":
for subject in subject_id_mapping:
if subject not in RECORDING_DURATIONS:
raise ValueError(f"Subject {subject} not found in RECORDING_DURATIONS")
subject_weights.append(float(RECORDING_DURATIONS[subject]))
elif weigh_by == "n_subjects":
num_subjects_per_study = Counter(
[k.split("/")[0] for k in subject_id_mapping.keys()]
)
for subject in subject_id_mapping:
weight = 1 / num_subjects_per_study[subject.split("/")[0]]
subject_weights.append(float(weight))
else:
raise ValueError(f"Invalid weight type: {weigh_by}")
return subject_weights
@lru_cache
def get_hcp_labels(mesh="fsaverage5", combine=False, hemi="both"):
"""
Get the HCP labels for the fsaverage subject.
"""
if hemi in ["right", "left"]:
subjects_dir = Path(mne.datasets.sample.data_path()) / "subjects"
mne.datasets.fetch_hcp_mmp_parcellation(
subjects_dir=subjects_dir, accept=True, verbose=True, combine=combine
)
name = "HCPMMP1_combined" if combine else "HCPMMP1"
with ns.utils.ignore_all():
labels = mne.read_labels_from_annot(
"fsaverage", name, hemi="both", subjects_dir=subjects_dir
)
label_to_vertices = {}
for label in labels:
name, vertices = label.name, np.array(label.vertices)
if not combine:
name = name[2:]
name = name.replace("_ROI", "") # .replace(" Cortex", "")
if (hemi == "right" and "-lh" in name) or (
hemi == "left" and "-rh" in name
):
continue
name = name.replace("-rh", "").replace("-lh", "")
label_to_vertices[name] = np.array(vertices)
assert sum(len(v) for v in label_to_vertices.values()) == 163842
expected_size = FSAVERAGE_SIZES[mesh]
index_offset = expected_size if hemi == "right" else 0
label_to_vertices = {
k: v[v < expected_size] + index_offset for k, v in label_to_vertices.items()
}
assert sum(len(v) for v in label_to_vertices.values()) == expected_size
return label_to_vertices
else:
assert hemi == "both", f"Invalid hemisphere: {hemi}"
left, right = get_hcp_labels(
mesh=mesh, combine=combine, hemi="left"
), get_hcp_labels(mesh=mesh, combine=combine, hemi="right")
label_to_vertices = {
k: np.concatenate([left[k], right[k]]) for k in left.keys()
}
return label_to_vertices
def get_hcp_vertex_labels(mesh="fsaverage5", combine=False):
labels = get_hcp_labels(mesh, combine)
out = [""] * FSAVERAGE_SIZES[mesh] * 2
for label, vertices in labels.items():
for vertex in vertices:
out[int(vertex)] = label
return out
def get_hcp_roi_indices(rois: str | list[str], hemi="both", mesh="fsaverage5"):
labels = get_hcp_labels(mesh=mesh, combine=False, hemi=hemi)
if isinstance(rois, str):
rois = [rois]
selected_labels = []
for roi in rois:
if roi[-1] == "*":
sel = [label for label in labels.keys() if label.startswith(roi[:-1])]
elif roi[0] == "*":
sel = [label for label in labels.keys() if label.endswith(roi[1:])]
else:
sel = [label for label in labels.keys() if label == roi]
if not sel:
raise ValueError(f"ROI {roi} not found in HCP labels")
selected_labels.extend(sel)
vertex_indices = np.concatenate([labels[label] for label in selected_labels])
return vertex_indices
def summarize_by_roi(data: np.ndarray, hemi="both", mesh="fsaverage5"):
assert data.ndim == 1, "Data must be 1D"
if hemi in ["left", "right", "both"]:
labels = get_hcp_labels(mesh=mesh, combine=False, hemi=hemi)
out = np.array(
[
data[get_hcp_roi_indices(roi, hemi=hemi, mesh=mesh)].mean()
for roi in labels.keys()
]
)
elif hemi == "both_separate":
out = np.concatenate(
[
summarize_by_roi(data, hemi="left", mesh=mesh),
summarize_by_roi(data, hemi="right", mesh=mesh),
]
)
else:
raise ValueError(f"Invalid hemisphere: {hemi}")
return out
def get_topk_rois(data: np.ndarray, hemi="both", mesh="fsaverage5", k=10) -> list[str]:
values = summarize_by_roi(data, hemi=hemi, mesh=mesh)
if hemi == "both_separate":
left_labels = get_hcp_labels(mesh=mesh, combine=False, hemi="left").keys()
right_labels = get_hcp_labels(mesh=mesh, combine=False, hemi="right").keys()
labels = [f"{l}-lh" for l in left_labels] + [f"{l}-rh" for l in right_labels]
else:
labels = get_hcp_labels(mesh=mesh, combine=False, hemi=hemi).keys()
top_k = np.argsort(values)[::-1][:k]
return np.array(labels)[top_k]12345678910# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from .algonauts2025 import Algonauts2025, Algonauts2025Bold
from .lahner2024bold import Lahner2024Bold
from .lebel2023bold import Lebel2023Bold
from .wen2017 import Wen2017123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Algonauts Project 2025 Challenge: fMRI responses to multimodal movie stimuli.
This study is part of the Algonauts Project 2025 Challenge, using a subset of the
Courtois NeuroMod dataset (https://www.cneuromod.ca/). Participants watched naturalistic
video stimuli including episodes from the TV sitcom "Friends" and extractor films while
undergoing fMRI scanning.
Experimental Design:
- 4 participants (sub-01, sub-02, sub-03, sub-05)
- Two stimulus types:
* "Friends" sitcom: 7 seasons, ~175 episodes, segmented into ~5min chunks (a,b,c,d)
* "movie10": 4 extractor films (Bourne, Wolf, Life, Figures) in ~5min chunks
- TR = 1.49 seconds
- Training data: Friends seasons 1-6, all movies
- Test data: Friends season 7
- Some movies shown twice (Life, Figures) for reliability analysis
Data Format:
- Preprocessed fMRI in MNI152NLin2009cAsym space
- Parcellated using Schaefer-1000 atlas (1000 parcels, 7 networks)
- HDF5 format
- Video stimuli provided as .mkv files
- Word-level transcripts with timestamps (.tsv format)
- Includes rich multimodal annotations (speech, text, visual extractors)
Download Requirements:
- Datalad must be installed (pip install datalad)
- Git must be configured
- Dataset cloned from: https://github.com/courtois-neuromod/algonauts_2025.competitors.git
- Moderate dataset size (~several GB)
Note:
This dataset is designed for the Algonauts 2025 Challenge focused on predicting
brain responses to complex, naturalistic multimodal stimuli.
See: https://algonautsproject.com/2025/index.html
"""
import ast
import logging
import typing as tp
from itertools import product
from pathlib import Path
import numpy as np
import pandas as pd
from neuralset.events import study
logger = logging.getLogger(__name__)
class Algonauts2025(study.Study):
_SUBJECTS: tp.ClassVar[list[str]] = ["sub-01", "sub-02", "sub-03", "sub-05"]
_TASKS: tp.ClassVar[list[str]] = ["friends", "movie10"]
_SPACE: tp.ClassVar[str] = "space-MNI152NLin2009cAsym"
_ATLAS: tp.ClassVar[str] = "atlas-Schaefer18_parcel-1000Par7Net"
_FREQUENCY: tp.ClassVar[float] = 1 / 1.49
device: tp.ClassVar[str] = "Fmri"
dataset_name: tp.ClassVar[str] = "Algonauts 2025 Challenge"
url: tp.ClassVar[str] = "https://algonautsproject.com/"
bibtex: tp.ClassVar[
str
] = """
@article{algonauts2025,
url = {https://arxiv.org/abs/2501.00504},
author = {Gifford, Alessandro T. and Bersch, Domenic and St-Laurent, Marie and Pinsard, Basile and Boyle, Julie and Bellec, Lune and Oliva, Aude and Roig, Gemma and Cichy, Radoslaw M.},
keywords = {Neurons and Cognition (q-bio.NC), FOS: Biological sciences, FOS: Biological sciences},
title = {The Algonauts Project 2025 Challenge: How the Human Brain Makes Sense of Multimodal Movies},
publisher = {arXiv},
year = {2025},
copyright = {Creative Commons Attribution 4.0 International},
doi={https://doi.org/10.48550/arXiv.2501.00504},
url={https://arxiv.org/abs/2501.00504}
}
"""
description: tp.ClassVar[str] = (
'Subset of Courtois NeuroMod dataset (boyle2020) with fMRI recordings of subjects watching videos of a popular sitcom ("Friends") for Algonauts 2025'
)
requirements: tp.ClassVar[tuple[str, ...]] = (
"datalad>=0.19.5",
"moviepy",
)
_info: tp.ClassVar[study.StudyInfo] = study.StudyInfo(
num_timelines=1588,
num_subjects=4,
num_events_in_query=1700,
event_types_in_query={"Fmri", "Video", "Word", "Text"},
data_shape=(1000, 592),
frequency=0.671,
fmri_spaces=("custom",),
)
def _download(self) -> None:
raise NotImplementedError("Download method not implemented yet")
def iter_timelines(self) -> tp.Iterator[dict[str, tp.Any]]:
for subject in self._SUBJECTS:
for task in self._TASKS:
if task == "friends":
season_episode_chunk = range(1, 8), range(1, 26), "abcd"
for season, episode, chunk in product(*season_episode_chunk):
tl = dict(
subject=subject,
task=task,
movie=f"s{season:02d}",
chunk=f"e{episode:02d}{chunk}",
run=0,
)
stim_path = self._get_transcript_filepath(tl)
if (
(season == 5 and episode == 20 and chunk == "a")
or (season == 4 and episode == 1 and chunk == "a")
or (season == 6 and episode == 3 and chunk == "a")
or (season == 4 and episode == 13 and chunk == "b")
or (season == 4 and episode == 1 and chunk == "b")
):
continue
if stim_path.exists():
yield tl
elif task == "movie10":
movie_chunk_run = (
["bourne", "wolf", "life", "figures"],
range(1, 18),
[1, 2],
)
for movie, chunk, run in product(*movie_chunk_run): # type: ignore
if movie in ["bourne", "wolf"] and run == 2:
continue
tl = dict(
subject=subject,
task=task,
movie=movie,
chunk=str(chunk),
run=run,
)
stim_path = self._get_transcript_filepath(tl)
if stim_path.exists():
yield tl
def _get_transcript_filepath(self, timeline: dict[str, tp.Any]) -> Path:
tl = timeline
base = (
self.path
/ "download/algonauts_2025.competitors/stimuli/transcripts"
/ tl["task"]
)
if tl["task"] == "friends":
return base / f"s{tl['movie'][-1]}/friends_{tl['movie']}{tl['chunk']}.tsv"
elif tl["task"] == "movie10":
return (
base / f"{tl['movie']}/movie10_{tl['movie']}{int(tl['chunk']):02d}.tsv"
)
raise ValueError(f"Unknown task: {tl['task']}")
def _get_movie_filepath(self, timeline: dict[str, tp.Any]) -> Path:
tl = timeline
base = (
self.path
/ "download/algonauts_2025.competitors/stimuli/movies"
/ tl["task"]
)
if tl["task"] == "friends":
return base / f"s{tl['movie'][-1]}/friends_{tl['movie']}{tl['chunk']}.mkv"
elif tl["task"] == "movie10":
return base / f"{tl['movie']}/{tl['movie']}{int(tl['chunk']):02d}.mkv"
raise ValueError(f"Unknown task: {tl['task']}")
def _get_fmri_filepath(self, timeline: dict[str, tp.Any]) -> Path:
tl = timeline
subj_dir = (
self.path
/ "download/algonauts_2025.competitors/fmri"
/ tl["subject"]
/ "func"
)
stem = f"{tl['subject']}_task-{tl['task']}_{self._SPACE}_{self._ATLAS}"
suffix = "_desc-s123456_bold.h5" if tl["task"] == "friends" else "_bold.h5"
return subj_dir / f"{stem}{suffix}"
def _load_fmri(self, timeline: dict[str, tp.Any]) -> tp.Any:
import h5py
tl = timeline
fmri_file = self._get_fmri_filepath(timeline)
fmri = h5py.File(fmri_file, "r")
if tl["task"] == "friends":
key = f"{tl['movie'][1:]}{tl['chunk']}"
else:
key = f"{tl['movie']}{int(tl['chunk']):02d}"
if tl["movie"] in ["life", "figures"]:
key += f"_run-{tl['run']}"
selected_key = [key_ for key_ in fmri.keys() if key in key_]
if len(selected_key) != 1:
logger.error(
"key=%s, selected=%s, available=%s",
key,
selected_key,
list(fmri.keys()),
)
raise ValueError(f"Multiple or no keys found, {key}, {list(fmri.keys())}")
fmri = fmri[selected_key[0]]
data = fmri[:].astype(np.float32)
import nibabel
obj = nibabel.Nifti2Image(data.T, affine=np.eye(4))
return obj
def _get_split(self, timeline: dict[str, tp.Any]) -> str:
tl = timeline
if tl["task"] == "friends":
if int(tl["movie"][-1]) in range(1, 7):
return "train"
elif int(tl["movie"][-1]) == 7:
return "test"
return "train"
def _get_fmri_event(self, timeline: dict[str, tp.Any]) -> dict[str, tp.Any]:
"""Return fmri event dict"""
info = study.SpecialLoader(method=self._load_fmri, timeline=timeline).to_json()
return dict(type="Fmri", filepath=info, start=0, frequency=self._FREQUENCY)
def _load_timeline_events(self, timeline: dict[str, tp.Any]) -> pd.DataFrame:
all_events = []
if (timeline["task"], timeline["movie"]) != ("friends", "s07"):
all_events.append(self._get_fmri_event(timeline))
movie_filepath = self._get_movie_filepath(timeline)
movie_event = dict(type="Video", filepath=str(movie_filepath), start=0)
all_events.append(movie_event)
transcript_path = self._get_transcript_filepath(timeline)
transcript_df = pd.read_csv(transcript_path, sep="\t")
word_events = []
for _, row in transcript_df.iterrows():
words = ast.literal_eval(row["words_per_tr"])
starts = ast.literal_eval(row["onsets_per_tr"])
durations = ast.literal_eval(row["durations_per_tr"])
for word, start, duration in zip(words, starts, durations):
event = dict(
type="Word",
text=word,
start=start,
duration=duration,
stop=start + duration,
language="english",
)
word_events.append(event)
if word_events:
word_df = pd.DataFrame(word_events)
text = " ".join(word_df["text"].tolist())
text_event = dict(
type="Text",
text=text,
start=word_df["start"].min(),
duration=word_df["stop"].max() - word_df["start"].min(),
stop=word_df["stop"].max(),
language="english",
)
all_events.append(text_event)
all_events.extend(word_events)
events_df = pd.DataFrame(all_events)
events_df["split"] = self._get_split(timeline)
events_df.loc[events_df.type.isin(["Word", "Sentence", "Text"]), "modality"] = (
"heard"
)
return events_df
class Algonauts2025Bold(Algonauts2025):
_info: tp.ClassVar[study.StudyInfo] = study.StudyInfo(
num_timelines=1588,
num_subjects=4,
num_events_in_query=1700,
event_types_in_query={"Fmri", "Video", "Word", "Text"},
data_shape=(76, 90, 71, 592),
frequency=0.671,
fmri_spaces=("T1w", "MNI152NLin2009cAsym"),
)
def _download(self) -> None:
raise NotImplementedError("Download method not implemented yet")
def _get_fmri_event(self, timeline: dict[str, tp.Any]) -> dict[str, tp.Any]:
"""Return fmri event dict using fmriprep finder"""
tl = timeline
if tl["task"] == "friends":
task_str = f"{tl['movie']}{tl['chunk']}"
else:
task_str = f"{tl['movie']}{int(tl['chunk']):02d}"
subj_dir = self.path / "download" / f"{tl['task']}.fmriprep" / tl["subject"]
task_pattern = f"*_task-{task_str}_*"
for session_dir in sorted(subj_dir.iterdir()):
if not session_dir.name.startswith("ses-"):
continue
func_dir = session_dir / "func"
if func_dir.exists() and list(func_dir.glob(task_pattern + ".nii.gz")):
fp = func_dir / task_pattern
return dict(
type="Fmri",
filepath=fp,
layout="fmriprep",
start=0,
frequency=self._FREQUENCY,
)
raise FileNotFoundError(f"No fMRI file found for {tl}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""BOLD Moments: 3T fMRI responses to short naturalistic videos.
This study provides 3T BOLD fMRI data from 10 participants viewing brief (3-second)
naturalistic video clips. The dataset is designed to study neural responses to
dynamic visual events and includes rich metadata and annotations. The test set's high
repetition count (10 reps) enables reliability analysis and within-subject
generalization studies.
Experimental Design:
- 3T fMRI recordings (TR = 1.75 seconds)
- 10 participants
- 4 functional scanning sessions per subject (sessions 2-5)
- Two sets of stimuli:
* Training set: 1,000 unique 3-second video clips (10 runs)
* Test set: 102 unique 3-second video clips (3 runs, 10 repetitions each)
- Paradigm: passive viewing of naturalistic video clips
- Oddball trials included for attention monitoring (excluded from analysis)
Data Format:
- BIDS-compliant dataset structure
- fMRIPrep preprocessed data (version B recommended by authors)
- Available in multiple spaces:
* MNI152NLin2009cAsym (volumetric)
* T1w (subject-native volumetric)
* fsaverage (cortical surface, 163842 vertices per hemisphere)
* fsnative (subject-specific cortical surface)
- Pre-computed GLM betas available for fsaverage space
- Video stimuli
- Event annotations:
* LLM-generated captions for middle frames of each video
Download Requirements:
- openneuro-py for fMRI data download
- Stimuli downloaded from boldmomentsdataset.csail.mit.edu
- Moderate dataset size (~several GB)
- moviepy required for video processing
"""
import json
import pickle as pkl
import typing as tp
from pathlib import Path
import nibabel
import numpy as np
import pandas as pd
from neuralset.events import study
from neuralset.utils import get_bids_filepath, get_masked_bold_image, read_bids_events
class Lahner2024Bold(study.Study):
device: tp.ClassVar[str] = "Fmri"
dataset_name: tp.ClassVar[str] = "BOLD Moments"
bibtex: tp.ClassVar[
str
] = """
@article{Lahner2024,
title = {Modeling short visual events through the BOLD moments video fMRI dataset and metadata},
volume = {15},
ISSN = {2041-1723},
url = {http://dx.doi.org/10.1038/s41467-024-50310-3},
DOI = {10.1038/s41467-024-50310-3},
number = {1},
journal = {Nature Communications},
publisher = {Springer Science and Business Media LLC},
author = {Lahner, Benjamin and Dwivedi, Kshitij and Iamshchinina, Polina and Graumann, Monika and Lascelles, Alex and Roig, Gemma and Gifford, Alessandro Thomas and Pan, Bowen and Jin, SouYoung and Ratan Murty, N. Apurva and Kay, Kendrick and Oliva, Aude and Cichy, Radoslaw},
year = {2024},
month = jul
}
"""
licence: tp.ClassVar[str] = "CC0"
description: tp.ClassVar[str] = (
"BOLD Moments: 3T fMRI from 10 participants viewing 1,000+ brief "
"(3-second) naturalistic videos"
)
requirements: tp.ClassVar[tuple[str, ...]] = ("moviepy==2.0.0.dev2",)
_info: tp.ClassVar[study.StudyInfo] = study.StudyInfo(
num_timelines=520,
num_subjects=10,
num_events_in_query=76,
event_types_in_query={"Fmri", "Video"},
data_shape=(62, 77, 61, 238),
frequency=0.571,
fmri_spaces=("custom",),
)
NUM_SUBJECTS: tp.ClassVar[int] = 10
NUM_RUNS_PER_SPLIT: tp.ClassVar[dict[str, int]] = {"train": 10, "test": 3}
DERIVATIVES_FOLDER: tp.ClassVar[str] = "download/derivatives/versionB/fmriprep"
SPACES: tp.ClassVar[tuple[str, ...]] = (
"MNI152NLin2009cAsym",
"T1w",
"fsaverage",
"fsnative",
)
N_TRIALS_TRAIN: tp.ClassVar[int] = 1000
N_TRIALS_TEST: tp.ClassVar[int] = 102
N_VOLUMES_TRAIN: tp.ClassVar[int] = 238
N_VOLUMES_TEST: tp.ClassVar[int] = 268
TR_FMRI_S: tp.ClassVar[float] = 1.75
def _download(self) -> None:
raise NotImplementedError("Download method not implemented yet")
def _validate_downloaded_data(self) -> None:
postfixs = [
"_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz",
"_space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz",
"_hemi-R_space-fsaverage_bold.func.gii",
"_hemi-L_space-fsaverage_bold.func.gii",
]
for tl in self.iter_timelines():
subj, ses, split, run = tl["subject"], tl["session"], tl["split"], tl["run"]
for postfix in postfixs:
fp = self.path / (
f"sub-{subj:02d}/ses-{ses:02d}/func/sub-{subj:02d}"
f"_ses-{ses:02d}_task-{split}_run-{run:01d}{postfix}"
)
if not fp.exists():
msg = f"{fp} is missing. Please download again"
raise RuntimeError(msg)
for subj in range(1, self.NUM_SUBJECTS + 1):
betas_root = (
self.path / "download/derivatives/versionB/fsaverage/GLM/"
f"sub-{subj:02}/prepared_betas/"
)
for split in ("train", "test"):
for hemi in ("left", "right"):
fp = (
betas_root / f"sub-{subj:02}_organized_betas_task-{split}"
f"_hemi-{hemi}_normalized.pkl"
)
if not fp.exists():
msg = f"{fp} is missing. Please download again"
raise RuntimeError(msg)
with fp.open("rb") as f:
prepared_betas = pkl.load(f)
betas = prepared_betas[0]
n_trials = (
self.N_TRIALS_TEST
if split == "test"
else self.N_TRIALS_TRAIN
)
n_reps = 10 if split == "test" else 3
betas_shape = (n_trials, n_reps, 163842)
if betas.shape != betas_shape:
msg = f"Expected {betas_shape}, got {betas.shape}"
raise RuntimeError(msg)
stims = prepared_betas[1]
if len(stims) != n_trials:
msg = f"Expected {n_trials} stimuli, got {len(stims)}"
raise RuntimeError(msg)
root = self.path / "stimuli/stimulus_set/stimuli/"
for split in ("train", "test"):
num_expected = (
self.N_TRIALS_TRAIN if split == "train" else self.N_TRIALS_TEST
)
num_found = len(list((root / split).iterdir()))
if num_found != num_expected:
msg = f"Expecting {num_expected} stimuli for split {split}"
msg += f" but found {num_found}. Please download again"
raise RuntimeError(msg)
def iter_timelines(self) -> tp.Iterator[dict[str, tp.Any]]:
for subj in range(1, self.NUM_SUBJECTS + 1):
for ses in (2, 3, 4, 5):
for split, n_runs in self.NUM_RUNS_PER_SPLIT.items():
for run in range(1, n_runs + 1):
yield dict(subject=subj, session=ses, split=split, run=run)
def _load_timeline_events(self, timeline: dict[str, tp.Any]) -> pd.DataFrame:
tl = dict(timeline)
split = tl.pop("split")
info = study.SpecialLoader(method=self._load_raw, timeline=timeline).to_json()
n_vols = self.N_VOLUMES_TRAIN if split == "train" else self.N_VOLUMES_TEST
fmri = {
"filepath": info,
"type": "Fmri",
"start": 0.0,
"frequency": 1.0 / self.TR_FMRI_S,
"duration": n_vols * self.TR_FMRI_S,
}
bids_events_df_fp = get_bids_filepath(
root_path=self.path / "download",
filetype="events",
data_type="Fmri",
run_padding="01",
task=split,
**tl,
)
bids_events_df = read_bids_events(bids_events_df_fp)
bids_events_df = bids_events_df[bids_events_df.trial_type != "oddball"]
ns_events_df = self._get_ns_img_events_df(bids_events_df, timeline)
return pd.concat([pd.DataFrame([fmri]), ns_events_df], axis=0)
def _load_raw(
self, timeline: dict[str, tp.Any], space: str = "MNI152NLin2009cAsym"
) -> nibabel.Nifti2Image | nibabel.Nifti1Image:
if space in ["MNI152NLin2009cAsym", "T1w"]:
return get_masked_bold_image(*self._get_bold_images(timeline, space))
elif space in ["fsnative", "fsaverage"]:
return self._get_fs(timeline, space)
msg = f"{space} is not supported."
raise ValueError(msg)
def _get_ns_img_events_df(
self, bids_events_df: pd.DataFrame, timeline: dict[str, tp.Any]
) -> pd.DataFrame:
path_to_stimuli = self.path / "stimuli/stimulus_set/stimuli"
annot_path = (
self.path
/ "download/derivatives/stimuli_metadata/llm_frame_annotations.json"
)
with annot_path.open("r", encoding="utf8") as f:
middle_frame_captions = json.load(f)
bids_events = bids_events_df.to_dict("records")
ns_events = []
for bids_event in bids_events:
fp = Path(bids_event["stim_file"])
filepath = str(path_to_stimuli / fp)
captions = "\n".join(next(iter(middle_frame_captions[fp.stem].values())))
ns_event = dict(
type="Video",
start=bids_event["onset"],
filepath=filepath,
middle_frame_captions=captions,
)
ns_events.append(ns_event)
return pd.DataFrame(ns_events)
def _get_bold_images(self, timeline: dict[str, tp.Any], space: str):
timeline = dict(timeline)
timeline["task"] = timeline.pop("split")
kwargs = {
"root_path": self.path / self.DERIVATIVES_FOLDER,
"data_type": "Fmri",
"space": space,
"run_padding": "01",
**timeline,
}
bold = nibabel.load(get_bids_filepath(**kwargs, filetype="bold"), mmap=True)
mask = nibabel.load(
get_bids_filepath(**kwargs, filetype="bold_mask"), mmap=True
)
return (bold, mask)
def _get_fs(
self, timeline: dict[str, tp.Any], space: str = "fsaverage"
) -> nibabel.Nifti2Image:
tl = timeline
if space not in ["fsaverage", "fsnative"]:
msg = f"{space} is not supported. " "Only surfaces 'fsaverage' "
msg += "and 'fsnative' are supported for Lahner2024Bold."
raise ValueError(msg)
data = []
n_volumes = (
self.N_VOLUMES_TRAIN if tl["split"] == "train" else self.N_VOLUMES_TEST
)
for hemi in ("L", "R"):
fp = (
self.path
/ self.DERIVATIVES_FOLDER
/ f"sub-{int(tl['subject']):02}/ses-{tl['session']:02}"
/ f"func/sub-{int(tl['subject']):02}_ses-{tl['session']:02}_task-{tl['split']}"
f"_run-{tl['run']}_hemi-{hemi}_space-{space}_bold.func.gii"
)
hemi_data = nibabel.load(fp, mmap=True).darrays # type: ignore
if len(hemi_data) != n_volumes:
msg = f"Expected {n_volumes} volumes, got {len(hemi_data)}"
raise RuntimeError(msg)
if space == "fsaverage" and hemi_data[0].data.shape != (163842,):
msg = f"Expected shape (163842,), got {hemi_data[0].data.shape}"
raise RuntimeError(msg)
np_data = np.stack([darray.data for darray in hemi_data], -1)
data.append(np_data)
data = np.concatenate(data, axis=0)
return nibabel.Nifti2Image(data, np.eye(4))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Natural language fMRI dataset: 3T fMRI responses to spoken narrative stories.
This dataset provides fMRI data from participants listening to natural spoken
narratives (stories) during 3T scanning. The stimuli include various narrative
audio stories with detailed word-level and phoneme-level annotations. The dataset
is designed for studying natural language processing in the brain.
Experimental Design:
- 3T fMRI recordings (TR = 2.0 seconds)
- 8 subjects (UTS01-UTS08)
- Subjects 1-3: 82 stories across 20 sessions (extended dataset)
- Subjects 4-8: 26-27 stories across 6 sessions
- Paradigm: passive listening to naturalistic spoken narratives
* Audio narratives with 10-second blank period before story onset
* Test story: "wheretheressmoke" (with 10 runs)
* Training stories: diverse narrative content
- Localizer tasks included: AudioMotorLocalizer, AuditoryLocalizer,
CategoryLocalizer, MotorLocalizer
Data Format:
- BIDS-compliant dataset structure (OpenNeuro ds003020)
- Two preprocessing versions available (see Study Classes below)
- Audio files: WAV format
- Event annotations (from TextGrid files)
* Word-level timing and text
* Phoneme-level timing and text
* Audio file paths
Study Classes:
1. **Lebel2023Bold**: Uses deepprep preprocessing pipeline
- Available spaces: T1w, MNI152NLin6Asym, fsaverage, fsnative
- 432 timelines (all sessions/runs)
- Full BIDS structure with multiple space outputs
2. **LebelProcessed2023Bold**: Uses authors' custom HDF5 preprocessing
- Custom cortical surface registration
- 200 timelines (aggregated by subject x task)
- Data stored in HDF5 format (.hf5 files)
- Custom voxel selection and masking
Download Requirements:
- OpenNeuro dataset: ds003020
- Dataset includes both raw fMRI data and preprocessed derivatives
- Audio stimuli (.wav files) and TextGrid annotations included
- Deepprep derivatives for Lebel2023Bold
- HDF5 preprocessed data for LebelProcessed2023Bold
- Python packages:
* nltk (v3.8.1) for TextGrid parsing
* nltk_contrib (from GitHub) for TextGrid file format
* soundfile (>=0.13.1) for audio handling
* h5py (>=3.10.0) for HDF5 files (LebelProcessed2023Bold only)
* pycortex (for cortical surface visualization, LebelProcessed2023Bold only)
Issues and Considerations:
- Subject UTS02: Different scan location and protocol, no localizer data
- Subject UTS04: Missing "life.hf5" story scan
- Subject UTS05: Low visual acuity, presented auditory cues
- UTS01/ses-7/treasureisland: Corrupted NIfTI file, automatically skipped
- Preprocessed data has additional 20s removed from beginning
- Original preprocessing: https://github.com/HuthLab/deep-fMRI-dataset
"""
import logging
import typing as tp
from pathlib import Path
import numpy as np
import pandas as pd
from neuralset.events import study
logger = logging.getLogger(__name__)
_DEFAULT_BAD_WORDS = frozenset(
[
"sentence_start",
"sentence_end",
"br",
"lg",
"ls",
"ns",
"sp",
"{BR}",
"{LG}",
"{LS}",
"{NS}",
"{SP}",
]
)
_ANAT_TASKS = [
"AudioMotorLocalizer",
"AuditoryLocalizer",
"CategoryLocalizer",
"MotorLocalizer",
]
SUBJECTS = [f"UTS{i:02d}" for i in range(1, 9)]
def _get_audio_file(path: Path | str, task: str) -> Path:
path = Path(path)
return path / f"stimuli/{task}.wav"
def _get_audio_text_file(path: Path | str, task: str) -> Path:
path = Path(path)
return path / f"derivative/TextGrids/{task}.TextGrid"
def _create_audio_events(path: Path | str, task: str) -> list[dict]:
events = []
dl_path = Path(path)
audio_text_file_name = _get_audio_text_file(dl_path, task)
audio_wav_file_name = _get_audio_file(dl_path, task)
split = "train" if task != "wheretheressmoke" else "test"
events.append(
dict(
start=0.0,
type="Audio",
language="english",
filepath=str(audio_wav_file_name),
split=split,
)
)
from nltk_contrib.textgrid import TextGrid
data = audio_text_file_name.read_text(encoding="utf-8")
fid = TextGrid(data)
for _, tier in enumerate(fid):
for recording in tier.simple_transcript:
start, stop, text = recording
if text != "" and text not in _DEFAULT_BAD_WORDS:
if tier.nameid == "phone":
tier_type = "Phoneme"
elif tier.nameid == "word":
tier_type = "Word"
else:
msg = "Tier must either be phone or word but tier.nameid is %s"
logger.warning(msg, tier.nameid)
events.append(
dict(
start=float(start),
text=text.lower(),
duration=float(stop) - float(start),
type=tier_type,
language="english",
filepath=str(audio_wav_file_name),
split=split,
)
)
return events
def _get_preprocessed_responses(
path: Path | str, task: str, subject: str
) -> np.ndarray:
output = _get_response(Path(path), [task], subject)
return output
def _get_hf5_path(path: Path | str, subject: str, task: str) -> Path | None:
path = Path(path).resolve()
hf5_path = path / "derivative" / "preprocessed_data" / subject / f"{task}.hf5"
if hf5_path.exists():
return hf5_path
return None
def _get_tasks(path: Path) -> list[str]:
path = Path(path).resolve()
dl_path = path / "stimuli"
tasks = []
for fp in dl_path.glob("*.wav"):
tasks.append(fp.stem)
return tasks
def _get_response(path: Path | str, stories, subject) -> np.ndarray:
"""Get the subject"s fMRI response for stories."""
import h5py
path = Path(path).resolve()
base_path = path / f"download/ds003020/derivative/preprocessed_data/{subject}"
resp = []
for story in stories:
resp_path = base_path / f"{story}.hf5"
hf = h5py.File(resp_path, "r")
resp.extend(hf["data"][:])
hf.close()
return np.array(resp)
class Lebel2023Bold(study.Study):
device: tp.ClassVar[str] = "Fmri"
licence: tp.ClassVar[str] = "CC0"
description: tp.ClassVar[str] = (
"Natural language fMRI: 3T fMRI responses from 8 subjects listening to "
"spoken narrative stories. Deepprep preprocessing with multiple output spaces "
"(T1w, MNI152NLin6Asym, fsaverage, fsnative). 432 timelines with word and "
"phoneme-level annotations. Test story: 'wheretheressmoke'."
)
bibtex: tp.ClassVar[
str
] = """
@article{lebel2023natural,
title={A natural language fMRI dataset for voxelwise encoding models},
author={LeBel, Amanda and Wagner, Lauren and Jain, Shailee and Adhikari-Desai, Aneesh and Gupta, Bhavin and Morgenthal, Allyson and Tang, Jerry and Xu, Lixiang and Huth, Alexander G},
journal={Scientific Data},
volume={10},
number={1},
pages={555},
year={2023},
publisher={Nature Publishing Group UK London},
doi={https://doi.org/10.1038/s41597-023-02437-z},
url={https://www.nature.com/articles/s41597-023-02437-z}
}
@dataset{lebel2023bold,
title={A natural language fMRI dataset for voxelwise encoding models},
author={LeBel, Amanda and Wagner, Lauren and Jain, Shailee and Adhikari-Desai, Aneesh and
Gupta, Bhavin and Morgenthal, Alyssa and Tang, Jerry and Xu, Lixiang and Huth, Alexander G},
year={2023},
publisher={OpenNeuro},
doi={10.18112/openneuro.ds003020.v2.2.0},
url={https://openneuro.org/datasets/ds003020}
}
"""
requirements: tp.ClassVar[tuple[str, ...]] = (
"nltk==3.8.1",
"git+https://github.com/nltk/nltk_contrib.git@683961c53f0c122b90fe2d039fe795e0a2b3e997",
"soundfile>=0.13.1",
)
_info: tp.ClassVar[study.StudyInfo] = study.StudyInfo(
num_timelines=432,
num_subjects=8,
num_events_in_query=9199,
event_types_in_query={"Fmri", "Audio", "Word", "Phoneme"},
data_shape=(57, 65, 56, 363),
frequency=0.5,
fmri_spaces=("T1w", "MNI152NLin6Asym", "fsaverage", "fsnative"),
)
TR_FMRI_S: tp.ClassVar[float] = 2.0
DERIVATIVES_FOLDER: tp.ClassVar[str] = "download/ds003020-fmriprep"
def model_post_init(self, __context: tp.Any) -> None:
super().model_post_init(__context)
self.infra_timelines.version = "v3.4"
def _download(self) -> None:
raise NotImplementedError("Download method not implemented yet")
def iter_timelines(self) -> tp.Iterator[dict[str, tp.Any]]:
"""
Iterate over the different recording timelines:
e.g. subjects x sessions in order with fmri runs
"""
dl_dir = self.path / "download/ds003020"
if not dl_dir.exists():
raise RuntimeError(f"Missing folder {dl_dir}")
for subject in SUBJECTS:
sessions = 20 if subject in ["UTS01", "UTS02", "UTS03"] else 6
for sess in range(1, sessions + 1):
sess_dir = dl_dir / f"sub-{subject}" / f"ses-{sess}" / "func"
tasks = [task.name for task in sess_dir.glob("*_bold.nii.gz")]
tasks = sorted({task.split("_")[2].split("-")[1] for task in tasks})
for task in tasks:
if task.startswith(tuple(_ANAT_TASKS)):
continue
if subject == "UTS01" and sess == 7 and task == "treasureisland":
msg = "Skipping subject=UTS01, session=7, task=treasureisland as nii.gz is corrupted."
logger.warning(msg)
continue
runs = (
list(range(1, 11)) + [None]
if task == "wheretheressmoke"
else [None]
)
for run in runs:
run_infix = f"_run-{run}" if run is not None else ""
filename = f"sub-{subject}_ses-{sess}_task-{task}{run_infix}_bold.nii.gz"
bids_path = sess_dir / filename
if not bids_path.exists():
continue
audio_text_file = _get_audio_text_file(path=dl_dir, task=task)
if not audio_text_file.exists():
raise RuntimeError(
f"Missing audio text file: {audio_text_file}"
)
audio_file = _get_audio_file(path=dl_dir, task=task)
if not audio_file.exists():
raise RuntimeError(f"Missing audio file: {audio_file}")
yield dict(
subject=subject, session=str(sess), task=task, run=run
)
def _load_timeline_events(self, timeline: dict[str, tp.Any]) -> pd.DataFrame:
"""Reads the events of a given timeline"""
task = timeline["task"]
freq = 1.0 / self.TR_FMRI_S
events = _create_audio_events(self.path / "download/ds003020", task)
subject, session, task, run = (
timeline["subject"],
timeline["session"],
timeline["task"],
timeline["run"],
)
run_substr = f"_run-{run}" if run is not None else ""
fp = (
self.path
/ self.DERIVATIVES_FOLDER
/ f"sub-{subject}/ses-{session}/func"
/ f"sub-{subject}_ses-{session}_task-{task}{run_substr}_*"
)
events.append(
dict(
type="Fmri",
start=0.0,
filepath=fp,
layout="fmriprep",
frequency=freq,
split="train" if task != "wheretheressmoke" else "test",
)
)
out = pd.DataFrame(events)
out.loc[out.type != "Fmri", "start"] += 10
out["task"] = task
out.loc[out.type != "Fmri", "modality"] = "heard"
return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import typing as tp
from pathlib import Path
import pandas as pd
from neuralset.events import study
def _get_nii_file(path: Path | str, subject: str, seg: str, fmri_run: int) -> Path:
path = Path(path)
seg_dir = path / subject / "fmri" / seg
nii = seg_dir / "mni" / f"{seg}_{fmri_run}_mni.nii.gz"
# Outrageously, some test files have a different
# naming convention...
if not nii.exists():
nii = seg_dir / "mni" / f"{seg}_{fmri_run}.mni.nii.gz"
assert nii.exists(), f"Missing file {nii} for {subject!r} and {seg!r}"
return nii
def _get_video_file(path: Path | str, seg: str) -> Path:
path = Path(path)
return path / f"stimuli/{seg}.mp4"
class Wen2017(study.Study):
device: tp.ClassVar[str] = "Fmri"
licence: tp.ClassVar[str] = "CC-BY 0"
url: tp.ClassVar[str] = "https://academic.oup.com/cercor/article/28/12/4136/4560155"
TR_FMRI_S: tp.ClassVar[float] = 2.0 # don't rely on nifti header
def _download(self) -> None:
raise NotImplementedError("Download method not implemented yet")
def iter_timelines(self) -> tp.Iterator[dict[str, tp.Any]]:
base = self.path / "download" / "video_fmri_dataset"
for subject_dir in base.iterdir():
subject = subject_dir.name
if not subject.startswith("subject") or not subject_dir.is_dir():
continue
for seg_dir in (subject_dir / "fmri").iterdir():
seg = seg_dir.name
is_train = seg.startswith("seg")
is_test = seg.startswith("test")
if not (is_train or is_test):
continue
file = _get_video_file(base, seg)
if not file.exists():
raise FileNotFoundError(f"Missing video file: {file}")
fmri_runs = range(1, 3) if is_train else range(1, 11)
for run_ in fmri_runs:
nii = _get_nii_file(base, subject, seg, run_)
if not nii.exists():
raise FileNotFoundError(f"Missing nii file: {nii}")
yield dict(subject=subject, seg=seg, run=run_)
def _load_timeline_events(self, timeline: dict[str, tp.Any]) -> pd.DataFrame:
import nibabel
tl = timeline
base = self.path / "download" / "video_fmri_dataset"
video_file = _get_video_file(base, tl["seg"])
nii_file = _get_nii_file(base, tl["subject"], tl["seg"], tl["run"])
nii: tp.Any = nibabel.load(nii_file, mmap=True)
freq = 1.0 / self.TR_FMRI_S
dur = nii.shape[-1] / freq
fmri = dict(
type="Fmri", start=0, filepath=nii_file, frequency=freq, duration=dur
)
return pd.DataFrame([dict(type="Video", start=0, filepath=video_file), fmri])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import logging
import os
import typing as tp
import warnings
from pathlib import Path
import exca
import neuralset.events.etypes as ev
import pandas as pd
import torch
logger = logging.getLogger(__name__)
from neuralset.events.transforms import EventsTransform
from neuralset.events.transforms.utils import DeterministicSplitter
from tqdm import tqdm
SPLIT_ATTRIBUTES = {
"Algonauts2025Bold": "chunk",
"Algonauts2025": "chunk",
"Lebel2023Bold": "task",
"Nastase2020": "story",
"Wen2017": "seg",
"Wenvtwo2017": "run",
"Lahner2024Bold": "timeline",
"Vanessen2023": "run",
"Aliko2020": "task",
"Li2022": "run",
}
def assign_splits(
events: pd.DataFrame, splitter: tp.Callable[str, str]
) -> pd.DataFrame:
assert events.study.nunique() == 1, "Only one study can be assigned at a time"
study_name = events.study.unique()[0]
split_by = SPLIT_ATTRIBUTES[study_name]
events["split_attr"] = events[split_by].astype(str)
values = events["split_attr"].unique()
# check that all rows have split attr assigned
unassigned_event_types = events[events.split_attr.isna()].type.unique().tolist()
if len(unassigned_event_types) > 0:
msg = f"Study {study_name}: The following events do not have a split assigned and will be removed: {unassigned_event_types}"
if any(
[
name.capitalize() in unassigned_event_types
for name in ["Fmri", "Video", "Audio", "Word"]
]
):
raise ValueError(msg)
else:
events = events[~events.type.isin(unassigned_event_types)]
warnings.warn(msg)
splits = [splitter(value) for value in values]
if splits and "val" not in splits:
splits[-1] = "val" # need at least one val split
val_to_split = dict(zip(values, splits))
events["split"] = events["split_attr"].map(val_to_split)
return events
class SplitEvents(EventsTransform):
val_ratio: float
def _run(self, events: pd.DataFrame) -> pd.DataFrame:
splitter = DeterministicSplitter(
ratios={"train": 1 - self.val_ratio, "val": self.val_ratio}, seed=42
)
tmp = []
for _, study_events in events.groupby("study"):
study_events = assign_splits(study_events, splitter)
tmp.append(study_events)
events = pd.concat(tmp)
return events
class ExtractWordsFromAudio(EventsTransform):
"""
Language is hard-coded because auto-detection in performed on first 30s of audio, which can be empty e.g. for movies.
"""
language: str = "english"
overwrite: bool = False
@staticmethod
def _get_transcript_from_audio(wav_filename: Path, language: str) -> pd.DataFrame:
import json
import os
import subprocess
import tempfile
language_codes = dict(
english="en", french="fr", spanish="es", dutch="nl", chinese="zh"
)
if language not in language_codes:
raise ValueError(f"Language {language} not supported")
device = "cuda" if torch.cuda.is_available() else "cpu"
compute_type = "float16"
with tempfile.TemporaryDirectory() as output_dir:
logger.info("Running whisperx via uvx...")
cmd = [
"uvx",
"whisperx",
str(wav_filename),
"--model",
"large-v3",
"--language",
language_codes[language],
"--device",
device,
"--compute_type",
compute_type,
"--batch_size",
"16",
"--align_model",
"WAV2VEC2_ASR_LARGE_LV60K_960H" if language == "english" else "",
"--output_dir",
output_dir,
"--output_format",
"json",
]
cmd = [c for c in cmd if c] # remove empty args
env = {k: v for k, v in os.environ.items() if k != "MPLBACKEND"}
result = subprocess.run(cmd, capture_output=True, text=True, env=env)
if result.returncode != 0:
raise RuntimeError(f"whisperx failed:\n{result.stderr}")
json_path = Path(output_dir) / f"{wav_filename.stem}.json"
transcript = json.loads(json_path.read_text())
words = []
for i, segment in enumerate(transcript["segments"]):
sentence = segment["text"]
sentence = sentence.replace('"', "")
for word in segment["words"]:
if "start" not in word:
continue
word_dict = {
"text": word["word"].replace('"', ""),
"start": word["start"],
"duration": word["end"] - word["start"],
"sequence_id": i,
"sentence": sentence,
}
words.append(word_dict)
transcript = pd.DataFrame(words)
return transcript
def _run(self, events: pd.DataFrame) -> pd.DataFrame:
if "Word" in events.type.unique():
logger.warning("Words already present in the events dataframe, skipping")
return events
audio_events = events.loc[events.type == "Audio"]
transcripts = {}
for wav_filename in tqdm(
audio_events.filepath.unique(),
total=len(audio_events.filepath.unique()),
desc="Extracting words from audio",
):
wav_filename = Path(wav_filename)
transcript_filename = wav_filename.with_suffix(".tsv")
if transcript_filename.exists() and not self.overwrite:
try:
transcript = pd.read_csv(transcript_filename, sep="\t")
except pd.errors.EmptyDataError:
transcript = pd.DataFrame()
logger.warning(f"Empty transcript file {transcript_filename}")
else:
transcript = self._get_transcript_from_audio(
wav_filename, self.language
)
transcript.to_csv(transcript_filename, sep="\t", index=False)
logger.info(f"Wrote transcript to {transcript_filename}")
transcripts[str(wav_filename)] = transcript
all_transcripts = []
for audio_event in audio_events.itertuples():
transcript = copy.deepcopy(transcripts[audio_event.filepath])
if len(transcript) == 0:
continue
for k, v in audio_event._asdict().items():
if k in (
"frequency",
"filepath",
"type",
"start",
"duration",
"offset",
):
continue
transcript.loc[:, k] = v
transcript["type"] = "Word"
transcript["language"] = self.language
transcript["start"] += audio_event.start + audio_event.offset
all_transcripts.append(transcript)
if all_transcripts:
events = pd.concat([events, pd.concat(all_transcripts)], ignore_index=True)
else:
logger.warning("No transcripts found, skipping")
return events
class CreateVideosFromImages(EventsTransform):
fps: int = 10
remove_images: bool = True
infra: exca.MapInfra = exca.MapInfra(cluster="processpool")
@infra.apply(
item_uid=lambda image_event: f"{image_event.filepath}_{image_event.duration}"
)
def create_video(self, image_events: list[ev.Image]) -> tp.Iterator[ev.Video]:
for image_event in image_events:
image_filepath = Path(image_event.filepath)
video_filepath = (
Path(self.infra.uid_folder(create=True))
/ f"{image_filepath.stem}_{image_event.duration}.mp4"
)
from moviepy import ImageClip
video_filepath.parent.mkdir(parents=True, exist_ok=True)
clip = ImageClip(str(image_filepath), duration=image_event.duration)
with (
open(os.devnull, "w") as devnull,
contextlib.redirect_stdout(devnull),
contextlib.redirect_stderr(devnull),
):
clip.write_videofile(
video_filepath, codec="libx264", audio=False, fps=self.fps
)
video_event = ev.Video.from_dict(
image_event.to_dict()
| {
"type": "Video",
"filepath": str(video_filepath),
"frequency": self.fps,
}
)
yield video_event
def _run(self, events: pd.DataFrame) -> pd.DataFrame:
images = events.loc[events.type == "Image"]
image_events = []
for image in tqdm(
images.itertuples(), total=len(images), desc="Extracting image events"
):
image_events.append(ev.Image.from_dict(image._asdict()))
video_events = [
video_event.to_dict() for video_event in self.create_video(image_events)
]
events = pd.concat([events, pd.DataFrame(video_events)], ignore_index=True)
if self.remove_images:
events = events.loc[events.type != "Image"]
return events.reset_index(drop=True)
class RemoveDuplicates(EventsTransform):
subset: str | tp.Sequence[str] = "filepath"
def _run(self, events: pd.DataFrame) -> pd.DataFrame:
events = events.drop_duplicates(subset=self.subset)
return events1234from cortexlab.inference.attribution import ModalityAttributorfrom cortexlab.inference.streaming import StreamingPredictor
__all__ = ["ModalityAttributor", "StreamingPredictor"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Modality importance scoring via ablation.
:class:`ModalityAttributor` measures how much text, audio, and videoeach contribute to the predicted brain response at every vertex bycomparing the full prediction against predictions with each modalityzeroed out."""
from __future__ import annotations
import logging
import numpy as npimport torchfrom neuralset.dataloader import SegmentData
logger = logging.getLogger(__name__)
class ModalityAttributor: """Score per-vertex importance of each input modality.
Uses an ablation approach: for each modality, zero out its features and measure the change in predicted brain activation. Larger changes mean the modality matters more for that vertex.
Parameters ---------- model : torch.nn.Module A :class:`FmriEncoderModel` instance. roi_indices : dict[str, np.ndarray], optional If provided, also compute per-ROI summary scores. """
def __init__( self, model: torch.nn.Module, roi_indices: dict[str, np.ndarray] | None = None, ): self.model = model self.roi_indices = roi_indices
def attribute(self, batch: SegmentData) -> dict[str, np.ndarray]: """Compute modality importance scores for a single batch.
Parameters ---------- batch : SegmentData Input batch containing features for all modalities.
Returns ------- dict[str, np.ndarray] Keys are modality names (e.g. ``"text"``, ``"audio"``, ``"video"``) mapped to importance arrays of shape ``(n_vertices,)``. If *roi_indices* was provided, additional keys like ``"text_roi"`` map ROI names to scalar scores. """ self.model.eval() modalities = [m for m in self.model.feature_dims if m in batch.data]
with torch.inference_mode(): baseline = self.model(batch).detach() # (B, V, T) baseline_mean = baseline.mean(dim=(0, 2)).cpu().numpy() # (V,)
scores: dict[str, np.ndarray] = {}
for mod in modalities: ablated_data = {k: v.clone() for k, v in batch.data.items()} ablated_data[mod] = torch.zeros_like(ablated_data[mod]) ablated_batch = SegmentData(data=ablated_data, segments=batch.segments)
with torch.inference_mode(): ablated_pred = self.model(ablated_batch).detach() ablated_mean = ablated_pred.mean(dim=(0, 2)).cpu().numpy()
importance = np.abs(baseline_mean - ablated_mean) scores[mod] = importance
if self.roi_indices is not None: roi_scores = {} for roi_name, vertices in self.roi_indices.items(): valid = vertices[vertices < len(importance)] roi_scores[roi_name] = float(importance[valid].mean()) if len(valid) > 0 else 0.0 scores[f"{mod}_roi"] = roi_scores
# Normalise so modality scores sum to 1 at each vertex total = sum(scores[m] for m in modalities) total = np.where(total > 0, total, 1.0) for mod in modalities: scores[f"{mod}_normalised"] = scores[mod] / total
return scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""TribeModel for inference and utilities for building event DataFrames."""
import logging
import typing as tp
from pathlib import Path
import numpy as np
import pandas as pd
import pydantic
import requests
import torch
import yaml
from einops import rearrange
from exca import ConfDict, TaskInfra
from tqdm import tqdm
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.handlers:
_handler = logging.StreamHandler()
_handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
logger.addHandler(_handler)
from neuralset.events.transforms import (
AddContextToWords,
AddSentenceToWords,
AddText,
ChunkEvents,
ExtractAudioFromVideo,
RemoveMissing,
)
from neuralset.events.utils import standardize_events
from cortexlab.data.transforms import ExtractWordsFromAudio
from cortexlab.training.experiment import TribeExperiment
VALID_SUFFIXES: dict[str, set[str]] = {
"text_path": {".txt"},
"audio_path": {".wav", ".mp3", ".flac", ".ogg"},
"video_path": {".mp4", ".avi", ".mkv", ".mov", ".webm"},
}
def download_file(url: str, path: str | Path) -> Path:
"""Download a file from *url* and save it to *path*.
Raises ``requests.HTTPError`` on non-2xx responses.
"""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with requests.get(url, stream=True, timeout=30) as r:
r.raise_for_status()
with open(path, "wb") as f:
for chunk in r.iter_content(chunk_size=128 * 1024):
if chunk:
f.write(chunk)
logger.info(f"Downloaded {url} -> {path}")
return path
def get_audio_and_text_events(
events: pd.DataFrame, audio_only: bool = False
) -> pd.DataFrame:
"""Run the audio/video-to-text pipeline on an events DataFrame.
Extracts audio from video, chunks long clips, transcribes words, and
attaches sentence/context annotations. Set *audio_only* to ``True``
to skip the transcription and text stages.
"""
transforms = [
ExtractAudioFromVideo(),
ChunkEvents(event_type_to_chunk="Audio", max_duration=60, min_duration=30),
ChunkEvents(event_type_to_chunk="Video", max_duration=60, min_duration=30),
]
if not audio_only:
transforms.extend(
[
ExtractWordsFromAudio(),
AddText(),
AddSentenceToWords(max_unmatched_ratio=0.05),
AddContextToWords(
sentence_only=False, max_context_len=1024, split_field=""
),
RemoveMissing(),
]
)
events = standardize_events(events)
for transform in transforms:
events = transform(events)
return standardize_events(events)
class TextToEvents(pydantic.BaseModel):
"""Convert raw text to an events DataFrame via text-to-speech + transcription.
The text is synthesised to audio with gTTS, then processed through
:func:`get_audio_and_text_events` to obtain word-level events.
"""
text: str
infra: TaskInfra = TaskInfra()
def model_post_init(self, __context: tp.Any) -> None:
if self.infra.folder is None:
raise ValueError("A folder must be specified to save the audio file.")
@infra.apply()
def get_events(self) -> pd.DataFrame:
from gtts import gTTS
from langdetect import detect
audio_path = Path(self.infra.uid_folder(create=True)) / "audio.mp3"
lang = detect(self.text)
tts = gTTS(self.text, lang=lang)
tts.save(str(audio_path))
logger.info(f"Wrote TTS audio to {audio_path}")
audio_event = {
"type": "Audio",
"filepath": str(audio_path),
"start": 0,
"timeline": "default",
"subject": "default",
}
return get_audio_and_text_events(pd.DataFrame([audio_event]))
class TribeModel(TribeExperiment):
"""High-level inference wrapper around :class:`TribeExperiment`.
Provides a simple ``from_pretrained`` / ``predict`` interface for
generating fMRI-like brain-activity predictions from text, audio,
or video inputs.
Typical usage::
model = TribeModel.from_pretrained("facebook/tribev2")
events = model.get_events_dataframe(video_path="clip.mp4")
preds, segments = model.predict(events)
"""
cache_folder: str = "./cache"
remove_empty_segments: bool = True
@classmethod
def from_pretrained(
cls,
checkpoint_dir: str | Path,
checkpoint_name: str = "best.ckpt",
cache_folder: str | Path = None,
cluster: str = None,
device: str = "auto",
config_update: dict | None = None,
) -> "TribeModel":
"""Load a trained model from a checkpoint directory or HuggingFace Hub repo.
``checkpoint_dir`` can be either a local path containing
``config.yaml`` and ``<checkpoint_name>``, or a HuggingFace Hub
repo id (e.g. ``"facebook/tribev2"``).
Parameters
----------
checkpoint_dir:
Local directory or HuggingFace Hub repo id that contains
``config.yaml`` and the checkpoint file.
checkpoint_name:
Filename of the checkpoint inside *checkpoint_dir*.
cache_folder:
Directory used to cache extracted features. Created if it
does not exist. Defaults to ``"./cache"`` when ``None``.
cluster:
Cluster backend forwarded to feature-extractor infra
(``"auto"`` by default).
device:
Torch device string. ``"auto"`` selects CUDA when available.
config_update:
Optional dictionary of config overrides applied after the
YAML config is loaded.
Returns
-------
TribeModel
A ready-to-use model instance with weights loaded in eval mode.
"""
if cache_folder is not None:
Path(cache_folder).mkdir(parents=True, exist_ok=True)
if device == "auto":
device = "cuda" if torch.cuda.is_available() else "cpu"
checkpoint_dir = Path(checkpoint_dir)
if checkpoint_dir.exists():
config_path = checkpoint_dir / "config.yaml"
ckpt_path = checkpoint_dir / checkpoint_name
else:
from huggingface_hub import hf_hub_download
repo_id = str(checkpoint_dir)
config_path = hf_hub_download(repo_id, "config.yaml")
ckpt_path = hf_hub_download(repo_id, checkpoint_name)
with open(config_path, "r") as f:
config = ConfDict(yaml.load(f, Loader=yaml.UnsafeLoader))
for modality in ["text", "audio", "video"]:
config[f"data.{modality}_feature.infra.folder"] = cache_folder
config[f"data.{modality}_feature.infra.cluster"] = cluster
for param in [
"infra.workdir",
"data.study.infra_timelines",
"data.neuro.infra",
"data.image_feature.infra",
]:
config.pop(param)
config["data.study.path"] = "."
config["average_subjects"] = True
config["checkpoint_path"] = str(config["infra.folder"]) + f"/{checkpoint_name}"
config["cache_folder"] = (
str(cache_folder) if cache_folder is not None else "./cache"
)
if config_update is not None:
config.update(config_update)
xp = cls(**config)
logger.info(f"Loading model from {ckpt_path}")
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True, mmap=True)
build_args = ckpt["model_build_args"]
state_dict = {
k.removeprefix("model."): v for k, v in ckpt["state_dict"].items()
}
del ckpt
model = xp.brain_model_config.build(**build_args)
model.load_state_dict(state_dict, strict=True, assign=True)
del state_dict
model.to(device)
model.eval()
xp._model = model
return xp
def get_events_dataframe(
self,
text_path: str | None = None,
audio_path: str | None = None,
video_path: str | None = None,
) -> pd.DataFrame:
"""Build an events DataFrame from exactly one input source.
Parameters
----------
text_path:
Path to a ``.txt`` file. The text is converted to speech, then
transcribed back to produce word-level events.
audio_path:
Path to an audio file (``.wav``, ``.mp3``, ``.flac``, ``.ogg``).
video_path:
Path to a video file (``.mp4``, ``.avi``, ``.mkv``, ``.mov``,
``.webm``).
Returns
-------
pd.DataFrame
Standardised events DataFrame with columns such as ``type``,
``filepath``, ``start``, ``duration``, ``timeline``, and
``subject``.
Raises
------
ValueError
If zero or more than one path is provided, or if the file
extension does not match the expected suffixes.
FileNotFoundError
If the specified file does not exist.
"""
provided = {
name: value
for name, value in [
("text_path", text_path),
("audio_path", audio_path),
("video_path", video_path),
]
if value is not None
}
if len(provided) != 1:
raise ValueError(
f"Exactly one of text_path, audio_path, video_path must be "
f"provided, got: {list(provided.keys()) or 'none'}"
)
name, value = next(iter(provided.items()))
path = Path(value)
suffix = path.suffix.lower()
if suffix not in VALID_SUFFIXES[name]:
raise ValueError(
f"{name} must end with one of {sorted(VALID_SUFFIXES[name])}, "
f"got '{suffix}'"
)
if not path.is_file():
raise FileNotFoundError(f"{name} does not exist: {path}")
if text_path is not None:
text = path.read_text(encoding="utf-8")
if not text.strip():
raise ValueError(f"Text file is empty: {path}")
return TextToEvents(
text=text,
infra={"folder": self.cache_folder, "mode": "retry"},
).get_events()
event_type = "Audio" if audio_path is not None else "Video"
event = {
"type": event_type,
"filepath": str(path),
"start": 0,
"timeline": "default",
"subject": "default",
}
return get_audio_and_text_events(pd.DataFrame([event]))
def predict(
self, events: pd.DataFrame, verbose: bool = True
) -> tuple[np.ndarray, list]:
"""Run inference on an events DataFrame and return per-TR predictions.
Each batch is split into segments of length ``data.TR``. When
``remove_empty_segments`` is ``True`` (the default), segments that
contain no events are discarded.
Parameters
----------
events:
Events DataFrame, typically produced by
:meth:`get_events_dataframe`.
verbose:
If ``True`` (default), display a ``tqdm`` progress bar.
Returns
-------
preds : np.ndarray
Array of shape ``(n_kept_segments, n_vertices)`` with the
predicted brain activity.
all_segments : list
Corresponding segment objects aligned with *preds*.
Raises
------
RuntimeError
If the model has not been loaded via :meth:`from_pretrained`.
"""
if self._model is None:
raise RuntimeError(
"TribeModel must be instantiated via the .from_pretrained method"
)
model = self._model
loader = self.data.get_loaders(events=events, split_to_build="all")["all"]
preds, all_segments = [], []
n_samples, n_kept = 0, 0
with torch.inference_mode():
for batch in tqdm(loader, disable=not verbose):
batch = batch.to(model.device)
batch_segments = []
for segment in batch.segments:
for t in np.arange(0, segment.duration - 1e-2, self.data.TR):
batch_segments.append(
segment.copy(offset=t, duration=self.data.TR)
)
if self.remove_empty_segments:
keep = np.array([len(s.ns_events) > 0 for s in batch_segments])
else:
keep = np.ones(len(batch_segments), dtype=bool)
n_kept += keep.sum()
n_samples += len(batch_segments)
batch_segments = [s for i, s in enumerate(batch_segments) if keep[i]]
y_pred = model(batch).detach().cpu().numpy()
y_pred = rearrange(y_pred, "b d t -> (b t) d")[keep]
preds.append(y_pred)
all_segments.extend(batch_segments)
preds = np.concatenate(preds)
if len(all_segments) != preds.shape[0]:
raise ValueError(
f"Number of samples: {preds.shape[0]} != {len(all_segments)}"
)
logger.info(
"Predicted %d / %d segments (%.1f%% kept)",
n_kept,
n_samples,
100.0 * n_kept / max(n_samples, 1),
)
return preds, all_segments123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158"""Real-time sliding-window fMRI prediction from live feature streams.
:class:`StreamingPredictor` buffers pre-extracted feature tensors one TRat a time and emits cortical-surface predictions once the context windowis full. Designed for BCI pipelines where features arrive continuouslyfrom upstream extractor models."""
from __future__ import annotations
import loggingimport threadingfrom collections import deque
import numpy as npimport torchfrom neuralset.dataloader import SegmentData
logger = logging.getLogger(__name__)
class StreamingPredictor: """Sliding-window predictor for real-time fMRI inference.
Operates at the *feature level* -- the caller must provide pre-extracted tensors from running extractor models (e.g. Wav2Vec2, V-JEPA2, LLaMA).
Parameters ---------- model : torch.nn.Module A :class:`FmriEncoderModel` instance in eval mode. window_trs : int Number of TRs that form the context window. step_trs : int Emit a prediction every *step_trs* frames. tr_seconds : float Duration of one TR in seconds. modalities : list[str] Expected modality keys (e.g. ``["text", "audio", "video"]``). device : str or torch.device Device for inference. """
def __init__( self, model: torch.nn.Module, window_trs: int = 40, step_trs: int = 1, tr_seconds: float = 1.0, modalities: list[str] | None = None, device: str | torch.device = "cpu", ): self.model = model self.window_trs = window_trs self.step_trs = step_trs self.tr_seconds = tr_seconds self.modalities = modalities or list(model.feature_dims.keys()) self.device = torch.device(device) self._buffer: deque[dict[str, torch.Tensor]] = deque(maxlen=window_trs) self._frames_since_emit = 0 self._lock = threading.Lock()
@classmethod def from_cortexlab_model( cls, cortexlab_model, window_trs: int = 40, step_trs: int = 1, tr_seconds: float = 1.0, device: str = "cuda", ) -> StreamingPredictor: """Create from a loaded CortexLab/TribeModel inference wrapper.""" return cls( model=cortexlab_model._model, window_trs=window_trs, step_trs=step_trs, tr_seconds=tr_seconds, device=device, )
def push_frame( self, features: dict[str, torch.Tensor] ) -> np.ndarray | None: """Push one TR's worth of features and maybe get a prediction.
Parameters ---------- features : dict[str, torch.Tensor] Mapping from modality name to feature tensor. Each tensor should have shape ``(n_layers, D)`` or ``(D,)``.
Returns ------- np.ndarray or None Prediction of shape ``(n_vertices,)`` if a prediction was emitted, otherwise ``None``. """ with self._lock: normalised: dict[str, torch.Tensor] = {} for mod in self.modalities: t = features.get(mod) if t is None: # Zero-fill missing modality dims = self.model.feature_dims.get(mod) if dims is not None: num_layers, feat_dim = dims t = torch.zeros(num_layers, feat_dim) else: continue if t.ndim == 1: t = t.unsqueeze(0) # (D,) -> (1, D) normalised[mod] = t self._buffer.append(normalised) self._frames_since_emit += 1
if len(self._buffer) < self.window_trs: return None if self._frames_since_emit < self.step_trs: return None
self._frames_since_emit = 0 return self._predict()
def _predict(self) -> np.ndarray: """Run inference on the current buffer contents.""" batch_data: dict[str, torch.Tensor] = {} for mod in self.modalities: frames = [] for frame in self._buffer: if mod in frame: frames.append(frame[mod]) if frames: # Stack: (T, L, D) -> (L, D, T) -> (1, L, D, T) stacked = torch.stack(frames, dim=0) # (T, L, D) stacked = stacked.permute(1, 2, 0).unsqueeze(0) # (1, L, D, T) batch_data[mod] = stacked.to(self.device)
import neuralset.segments as seg dummy_segments = [seg.Segment(start=0.0, duration=float(self.window_trs * self.tr_seconds), timeline="stream")] batch = SegmentData(data=batch_data, segments=dummy_segments) with torch.inference_mode(): pred = self.model(batch, pool_outputs=True) # (1, V, T') return pred[0, :, -1].cpu().numpy() # (V,) -- last timestep
def flush(self) -> list[np.ndarray]: """Force-emit predictions for any remaining buffered frames.""" with self._lock: results = [] if len(self._buffer) >= self.window_trs: results.append(self._predict()) return results
def reset(self) -> None: """Clear the buffer and reset the step counter.""" with self._lock: self._buffer.clear() self._frames_since_emit = 0123from cortexlab.training.pl_module import BrainModule
__all__ = ["BrainModule"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Defines the main classes used in the experiment.
We suggest the following structure:
- `Data`: configures dataset and extractors to return DataLoaders
- `Trainer`: creates the deep learning model and exposes a `fit` and `test` methods
- `TribeExperiment`: main class that defines the experiment to run by using `Data` and `Trainer`
"""
import gc
import logging
import os
import typing as tp
from pathlib import Path
import neuralset as ns
import numpy as np
import pandas as pd
import pydantic
import torch
import yaml
from exca import ConfDict, TaskInfra
from neuralset.events.etypes import EventTypesHelper
from neuralset.events.utils import standardize_events
from neuraltrain.losses import BaseLoss
from neuraltrain.metrics import BaseMetric
from neuraltrain.models import BaseModelConfig
from neuraltrain.models.common import SubjectLayers
from neuraltrain.optimizers.base import BaseOptimizer
from neuraltrain.utils import BaseExperiment, WandbLoggerConfig
from torch import nn
from torch.utils.data import DataLoader
from cortexlab.data.transforms import * # register custom events transforms in neuralset
from cortexlab.core.model import * # register custom models in neuraltrain
from cortexlab.data.studies import * # register studies
from cortexlab.data.loader import (
MultiStudyLoader,
set_study_in_average_subject_mode,
split_segments_by_time,
)
from cortexlab.data.fmri import * # register TribeSurfaceProjector
# Configure logger
LOGGER = logging.getLogger(__name__)
_handler = logging.StreamHandler()
_formatter = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s", "%H:%M:%S")
_handler.setFormatter(_formatter)
if not LOGGER.handlers:
LOGGER.addHandler(_handler)
LOGGER.setLevel(logging.INFO)
def _free_extractor_model(extractor: ns.extractors.BaseExtractor) -> None:
"""Delete cached GPU model from an extractor after its features are cached.
Extractors lazily load models onto GPU during ``prepare`` and keep them
in ``_model``. Since results are persisted to disk, the model is no
longer needed afterwards and this frees VRAM for subsequent extractors.
"""
targets = [extractor]
if hasattr(extractor, "image"):
targets.append(extractor.image)
for target in targets:
for attr in ("_model",):
obj = getattr(target, attr, None)
if isinstance(obj, torch.nn.Module):
try:
delattr(target, attr)
except Exception:
pass
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
class Data(pydantic.BaseModel):
"""Handles configuration and creation of DataLoaders from dataset and extractors."""
model_config = pydantic.ConfigDict(extra="forbid")
study: MultiStudyLoader
# features
neuro: ns.extractors.BaseExtractor
text_feature: ns.extractors.BaseExtractor | None = None
image_feature: ns.extractors.BaseExtractor | None = None
audio_feature: ns.extractors.BaseExtractor | None = None
video_feature: ns.extractors.BaseExtractor | None = None
subject_id: ns.extractors.LabelEncoder = ns.extractors.LabelEncoder(
event_field="subject", allow_missing=True, aggregation="first"
)
frequency: float | None = None
features_to_use: list[
tp.Literal["text", "audio", "video", "image", "context", "flow", "music"]
]
features_to_mask: list[
tp.Literal["text", "audio", "video", "image", "context", "flow", "music"]
] = []
n_layers_to_use: int | None = None
layers_to_use: list[float] | None = None
layer_aggregation: tp.Literal["group_mean", "mean"] | None = "group_mean"
# Dataset
duration_trs: int = 40
overlap_trs_train: int = 0
overlap_trs_val: int | None = None
batch_size: int = 64
num_workers: int | None = None
shuffle_train: bool = True
shuffle_val: bool = False
stride_drop_incomplete: bool = False
split_segments_by_time: bool = False
def model_post_init(self, __context):
super().model_post_init(__context)
layers_to_use = None
if self.n_layers_to_use is not None or self.layers_to_use is not None:
assert not (
self.n_layers_to_use is not None and self.layers_to_use is not None
), "Only one of n_layers_to_use or layers_to_use can be specified"
if self.n_layers_to_use is not None:
layers_to_use = np.linspace(0, 1, self.n_layers_to_use).tolist()
else:
layers_to_use = self.layers_to_use
for modality in self.features_to_use:
extractor = getattr(self, f"{modality}_feature")
if hasattr(extractor, "layers"):
setattr(extractor, "layer_aggregation", self.layer_aggregation)
if layers_to_use is not None:
setattr(extractor, "layers", layers_to_use)
if hasattr(extractor, "image") and hasattr(extractor.image, "layers"):
setattr(extractor.image, "layer_aggregation", self.layer_aggregation)
if layers_to_use is not None:
setattr(extractor.image, "layers", layers_to_use)
if self.frequency is not None:
for modality in self.features_to_use:
extractor = getattr(self, f"{modality}_feature")
if hasattr(extractor, "frequency"):
setattr(extractor, "frequency", self.frequency)
@property
def TR(self) -> float:
return 1 / self.neuro.frequency
def get_events(self) -> pd.DataFrame:
events = self.study.run()
events = events[events.type != "Sentence"]
cols = ["index", "subject", "timeline"]
event_summary = (
events.reset_index().groupby(["study", "split", "type"])[cols].nunique()
)
LOGGER.info("Event summary: \n%s", event_summary)
return events
def get_loaders(
self,
events: pd.DataFrame | None = None,
split_to_build: tp.Literal["train", "val", "all"] | None = None,
) -> tuple[dict[str, DataLoader], int]:
if events is None:
events = self.get_events()
else:
events = standardize_events(events)
extractors = {}
for modality in self.features_to_use:
extractors[modality] = getattr(self, f"{modality}_feature")
if "Fmri" in events.type.unique():
extractors["fmri"] = self.neuro
dummy_events = []
for timeline_name, timeline in events.groupby("timeline"):
if "split" in timeline.columns:
splits = timeline.split.dropna().unique()
assert (
len(splits) == 1
), f"Timeline {timeline_name} has multiple splits: {splits}"
split = splits[0]
else:
split = "all"
dummy_event = {
"type": "CategoricalEvent",
"timeline": timeline_name,
"start": timeline.start.min(),
"duration": timeline.stop.max() - timeline.start.min(),
"split": split,
"subject": timeline.subject.unique()[0],
}
dummy_events.append(dummy_event)
events = pd.concat([events, pd.DataFrame(dummy_events)])
events = standardize_events(events)
extractors["subject_id"] = self.subject_id
features_to_remove = set()
for extractor_name, extractor in extractors.items():
event_types = EventTypesHelper(extractor.event_types).names
if not any(
[event_type in events.type.unique() for event_type in event_types]
):
features_to_remove.add(extractor_name)
for extractor_name in features_to_remove:
del extractors[extractor_name]
LOGGER.warning(
"Removing extractor %s as there are no corresponding events",
extractor_name,
)
for name, extractor in extractors.items():
LOGGER.info("Preparing extractor: %s", name)
extractor.prepare(events)
_free_extractor_model(extractor)
# Prepare dataloaders
loaders = {}
if split_to_build is None:
splits = ["train", "val"]
else:
splits = [split_to_build]
for split in splits:
LOGGER.info("Building dataloader for split %s", split)
if split == "all" or self.split_segments_by_time:
split_sel = [True] * len(events)
shuffle = False
overlap_trs = self.overlap_trs_train
else:
split_sel = events.split == split
if split not in events.split.unique():
shuffle = False
else:
shuffle = (
self.shuffle_train if split == "train" else self.shuffle_val
)
if split == "val":
overlap_trs = self.overlap_trs_val or self.overlap_trs_train
else:
overlap_trs = self.overlap_trs_train
sel = np.array(split_sel)
segments = ns.segments.list_segments(
events[sel],
triggers=events[sel].type == "CategoricalEvent",
stride=(self.duration_trs - overlap_trs) * self.TR,
duration=self.duration_trs * self.TR,
stride_drop_incomplete=self.stride_drop_incomplete,
)
if self.split_segments_by_time:
LOGGER.info(f"Total number of segments: {len(segments)}")
segments = split_segments_by_time(
segments,
val_ratio=self.study.transforms["split"].val_ratio,
split=split,
)
LOGGER.info(f"# {split} segments: {len(segments)}")
if len(segments) == 0:
LOGGER.warning("No events found for split %s", split)
continue
dataset = ns.dataloader.SegmentDataset(
extractors=extractors,
segments=segments,
remove_incomplete_segments=False,
)
dataloader = dataset.build_dataloader(
shuffle=shuffle,
num_workers=self.num_workers,
batch_size=self.batch_size,
)
loaders[split] = dataloader
return loaders
class TribeExperiment(BaseExperiment):
"""Defines the main experiment pipeline including data loading and training/evaluation."""
model_config = pydantic.ConfigDict(extra="forbid")
data: Data
# Reproducibility
seed: int | None = 33
# Model
brain_model_config: BaseModelConfig
# Loss
loss: BaseLoss
# Optimization
optim: BaseOptimizer
# Metrics
metrics: list[BaseMetric]
monitor: str = "val/pearson"
# Weights & Biases
wandb_config: WandbLoggerConfig | None = None
# Hardware
accelerator: str = "gpu"
# Optim
n_epochs: int | None = 10
max_steps: int = -1
patience: int | None = None
limit_train_batches: int | None = None
accumulate_grad_batches: int = 1
# Others
enable_progress_bar: bool = True
log_every_n_steps: int | None = None
fast_dev_run: bool = False
save_checkpoints: bool = True
checkpoint_filename: str = "best"
resize_subject_layer: bool = False
freeze_backbone: bool = False
# Eval
average_subjects: bool = False
checkpoint_path: str | None = None
load_checkpoint: bool = True
test_only: bool = False
# Internal properties
_trainer: tp.Any = None
_model: tp.Any = None
_logger: tp.Any = None
# Others
infra: TaskInfra = TaskInfra(version="1")
def model_post_init(self, __context: tp.Any) -> None:
super().model_post_init(__context)
if self.infra.folder is None:
msg = "infra.folder needs to be specified to save the results."
raise ValueError(msg)
# Update Trainer parameters based on infra
self.infra.tasks_per_node = self.infra.gpus_per_node
self.infra.slurm_use_srun = True if self.infra.gpus_per_node > 1 else False
if self.infra.gpus_per_node > 1:
self.metrics = [m for m in self.metrics if m.name not in ["TopkAcc"]]
self.data.batch_size = self.data.batch_size // self.infra.gpus_per_node
if self.accumulate_grad_batches > 1:
self.data.batch_size = self.data.batch_size // self.accumulate_grad_batches
if (
not (self.checkpoint_path and self.load_checkpoint)
) or self.resize_subject_layer:
study_summary = self.data.study.study_summary()
self.data.subject_id.predefined_mapping = {
subject: i for i, subject in enumerate(study_summary.subject.unique())
}
self.brain_model_config.subject_layers.n_subjects = (
study_summary.subject.nunique()
)
if isinstance(self.brain_model_config.projector, SubjectLayers):
self.brain_model_config.projector.n_subjects = (
study_summary.subject.nunique()
)
if self.average_subjects:
study_name = self.data.study.names
self.brain_model_config.subject_layers.average_subjects = True
self.brain_model_config.subject_layers.n_subjects = 0
if isinstance(self.brain_model_config.projector, SubjectLayers):
self.brain_model_config.projector.average_subjects = True
self.data.neuro.aggregation = "mean"
self.data.subject_id.predefined_mapping = None
if isinstance(study_name, str):
LOGGER.debug(f"Setting study {study_name} in average subject mode")
trigger_type = (
"Video" if study_name in ["Wen2017", "Allen2022Bold"] else "Audio"
)
self.data.study = set_study_in_average_subject_mode(
self.data.study, trigger_type=trigger_type, trigger_field="filepath"
)
else:
pass
# LOGGER.warning(
# "Cannot set study in average subject mode with multiple studies"
# )
def _get_checkpoint_path(self) -> Path | None:
if self.checkpoint_path:
assert Path(
self.checkpoint_path
).exists(), f"Checkpoint path {self.checkpoint_path} does not exist."
checkpoint_path = Path(self.checkpoint_path)
else:
checkpoint_path = Path(self.infra.folder) / "last.ckpt"
if not checkpoint_path.exists():
checkpoint_path = None
return checkpoint_path
def _init_module(self, model: nn.Module) -> tp.Any:
from cortexlab.training.pl_module import BrainModule
checkpoint_path = self._get_checkpoint_path()
if (
self.load_checkpoint
and checkpoint_path is not None
and not self.resize_subject_layer
):
LOGGER.info(f"Loading model from {checkpoint_path}")
init_fn = BrainModule.load_from_checkpoint
init_kwargs = {"checkpoint_path": checkpoint_path, "strict": False}
else:
init_fn = BrainModule
init_kwargs = {}
metrics = {
split + "/" + metric.log_name: metric.build()
for metric in self.metrics
for split in ["val", "test"]
}
metrics = nn.ModuleDict(metrics)
pl_module = init_fn(
model=model,
loss=self.loss.build(),
optim_config=self.optim,
metrics=metrics,
config=ConfDict(self.model_dump()),
**init_kwargs,
)
if self.resize_subject_layer:
LOGGER.info("Resizing subject layer")
checkpoint = torch.load(checkpoint_path)
state_dict = checkpoint["state_dict"]
weights = state_dict["model.predictor.weights"]
_, in_channels, out_channels = weights.shape
n_subjects = self.brain_model_config.subject_layers.n_subjects
if self.brain_model_config.subject_layers.subject_dropout:
n_subjects += 1
if "model.predictor.bias" in state_dict:
bias = state_dict["model.predictor.bias"]
new_bias = torch.nn.Parameter(torch.zeros(n_subjects, out_channels))
new_bias.data[:] = bias.mean(dim=0).repeat(n_subjects, 1)
state_dict["model.predictor.bias"] = new_bias
if self.freeze_backbone:
for param in pl_module.parameters():
param.requires_grad = False
for param in pl_module.model.predictor.parameters():
param.requires_grad = True
if (
self.brain_model_config.low_rank_head is not None
and self.brain_model_config.low_rank_head != in_channels
):
r = self.brain_model_config.low_rank_head
if "model.low_rank_head.weight" in state_dict:
W1, W2 = (
state_dict["model.low_rank_head.weight"].cpu(),
state_dict["model.predictor.weights"].mean(dim=0).cpu(),
)
prod = torch.matmul(W1.t(), W2)
else:
prod = state_dict["model.predictor.weights"].mean(dim=0).cpu()
U, S, V = torch.svd(prod)
U = U[:, :r]
S = S[:r]
V = V[:, :r]
state_dict["model.low_rank_head.weight"] = U.t()
state_dict["model.predictor.weights"] = torch.matmul(
torch.diag(S), V.t()
).repeat(n_subjects, 1, 1)
if "model.predictor.bias" in state_dict:
state_dict["model.low_rank_head.bias"] = torch.zeros(r)
for param in pl_module.model.low_rank_head.parameters():
param.requires_grad = True
else:
state_dict["model.predictor.weights"] = weights.mean(dim=0).repeat(
n_subjects, 1, 1
)
pl_module.load_state_dict(state_dict, strict=False)
return pl_module
def _setup_trainer(
self, train_loader: DataLoader, override_n_devices: int | None = None
) -> tp.Any:
import lightning.pytorch as pl
from lightning.pytorch.callbacks import (
EarlyStopping,
LearningRateMonitor,
ModelCheckpoint,
)
batch = next(iter(train_loader))
feature_dims = {}
for modality in self.data.features_to_use:
if (
modality in batch.data and modality not in self.data.features_to_mask
): # B, L, D, T
if batch.data[modality].ndim == 4:
feature_dims[modality] = (
batch.data[modality].shape[1],
batch.data[modality].shape[2],
)
elif batch.data[modality].ndim == 3:
feature_dims[modality] = (
1,
batch.data[modality].shape[1],
)
else:
raise ValueError(
f"Unexpected number of dimensions for modality {modality}: {batch.data[modality].ndim}"
)
else:
feature_dims[modality] = None
if "fmri" in batch.data: # read from fmri config
fmri = batch.data["fmri"]
n_outputs = fmri.shape[1]
for metric in self.metrics:
if hasattr(metric, "kwargs") and "num_outputs" in metric.kwargs:
metric.kwargs["num_outputs"] = n_outputs
else: # read from neuro config
if hasattr(self.data.neuro.projection, "mesh"):
from neuralset.extractors.neuro import FSAVERAGE_SIZES
n_outputs = 2 * FSAVERAGE_SIZES[self.data.neuro.projection.mesh]
else:
raise ValueError(
f"Could not determine number of outputs for neuro extractor {self.data.neuro}"
)
brain_model = self.brain_model_config.build(
feature_dims=feature_dims,
n_outputs=n_outputs,
n_output_timesteps=self.data.duration_trs,
)
LOGGER.info("Extractor dims: %s", feature_dims)
input_data = brain_model.aggregate_features(batch)
LOGGER.info("Input shapes: %s", input_data.shape)
LOGGER.info("Target shapes: %s", n_outputs)
_ = brain_model(batch)
total_params = sum(p.numel() for p in brain_model.parameters())
LOGGER.info(f"Total parameters: {total_params}")
self._model = self._init_module(brain_model)
if self.monitor == "val/pearson":
mode = "max"
else:
mode = "min"
callbacks = [
LearningRateMonitor(logging_interval="epoch"),
]
if self.patience is not None:
callbacks.append(
EarlyStopping(monitor=self.monitor, mode=mode, patience=self.patience)
)
if self.save_checkpoints:
callbacks.append(
ModelCheckpoint(
save_last=True,
save_top_k=1,
dirpath=self.infra.folder,
filename=self.checkpoint_filename,
monitor=self.monitor,
mode=mode,
save_on_train_epoch_end=True,
)
)
trainer = pl.Trainer(
strategy="auto" if self.infra.gpus_per_node == 1 else "fsdp",
devices=override_n_devices or self.infra.gpus_per_node,
accelerator=self.accelerator,
max_epochs=self.n_epochs,
max_steps=self.max_steps,
limit_train_batches=self.limit_train_batches,
enable_progress_bar=self.enable_progress_bar,
log_every_n_steps=self.log_every_n_steps,
fast_dev_run=self.fast_dev_run,
callbacks=callbacks,
logger=self._logger,
enable_checkpointing=self.save_checkpoints,
accumulate_grad_batches=self.accumulate_grad_batches,
)
self._trainer = trainer
return trainer
def fit(self, train_loader: DataLoader, valid_loader: DataLoader) -> None:
self._trainer.fit(
model=self._model,
train_dataloaders=train_loader,
val_dataloaders=valid_loader,
ckpt_path=self._get_checkpoint_path(),
)
def test(self, test_loader: DataLoader) -> None:
if self.checkpoint_path:
ckpt_path = self.checkpoint_path
else:
if self.save_checkpoints:
ckpt_path = Path(self.infra.folder) / "best.ckpt"
else:
ckpt_path = None
self._trainer.test(
self._model,
dataloaders=test_loader,
ckpt_path=ckpt_path,
)
def setup_run(self):
if self.infra.cluster and self.infra.status() != "not submitted":
for out_type in ["stdout", "stderr"]:
old_path = Path(getattr(self.infra.job().paths, out_type))
new_path = Path(self.infra.folder) / f"log.{out_type}"
try:
if new_path.exists():
os.remove(new_path)
os.symlink(
old_path,
new_path,
)
except Exception:
pass
config_path = Path(self.infra.folder) / "config.yaml"
os.makedirs(self.infra.folder, exist_ok=True)
with open(config_path, "w") as outfile:
yaml.dump(
self.model_dump(),
outfile,
indent=4,
default_flow_style=False,
sort_keys=False,
)
@infra.apply
def run(self):
import lightning.pytorch as pl
self.setup_run()
self._logger = (
self.wandb_config.build(
save_dir=self.infra.folder,
xp_config=self.model_dump(),
id=f"{self.wandb_config.group}-{self.infra.uid().split('-')[-1]}",
)
if self.wandb_config
else None
)
if self.seed is not None:
pl.seed_everything(self.seed, workers=True)
np.random.seed(self.seed)
torch.manual_seed(self.seed)
loaders = self.data.get_loaders(
split_to_build="val" if self.test_only else None
)
self._setup_trainer(next(iter(loaders.values())))
if not self.test_only:
self.fit(loaders["train"], loaders["val"])
self.test(loaders["val"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Custom lightning module that wraps a pytorch model.
"""
import typing as tp
from pathlib import Path
import lightning.pytorch as pl
from einops import rearrange
from neuralset.dataloader import SegmentData
from neuraltrain.optimizers import BaseOptimizer
from torch import nn
from torchmetrics import Metric
class BrainModule(pl.LightningModule):
"""Torch-lightning module for fMRI encoding model training."""
def __init__(
self,
model: nn.Module,
loss: nn.Module,
optim_config: BaseOptimizer,
metrics: dict[str, Metric],
checkpoint_path: Path | None = None,
config: dict[str, tp.Any] | None = None,
) -> None:
super().__init__()
self.model = model
self.checkpoint_path = checkpoint_path
self.config = config
# Optimizer
self.optim_config = optim_config
self.loss = loss
self.metrics = metrics
def forward(self, batch):
return self.model(batch)
def on_save_checkpoint(self, checkpoint):
checkpoint["model_build_args"] = {
"feature_dims": self.model.feature_dims,
"n_outputs": self.model.n_outputs,
"n_output_timesteps": self.model.n_output_timesteps,
}
def _run_step(
self, batch: SegmentData, batch_idx, step_name, dataloader_idx: int = 0
):
y_true = batch.data["fmri"] # B, D, T
y_pred = self.forward(batch) # B, D, T
if step_name == "val":
y_true = y_true[:, :, self.config["data.overlap_trs_val"] :]
y_pred = y_pred[:, :, self.config["data.overlap_trs_val"] :]
subject_ids_flat = batch.data["subject_id"].repeat_interleave(
y_pred.shape[2], 0
)
y_pred_flat = rearrange(y_pred, "b d t -> (b t) d")
y_true_flat = rearrange(y_true, "b d t -> (b t) d")
if not self.config["data.stride_drop_incomplete"]:
bad_indices = (y_true_flat == 0).all(dim=1)
y_pred_flat = y_pred_flat[~bad_indices]
y_true_flat = y_true_flat[~bad_indices]
subject_ids_flat = subject_ids_flat[~bad_indices]
loss = self.loss(y_pred_flat, y_true_flat).mean()
log_kwargs = {
"on_step": True if step_name == "train" else False,
"on_epoch": True,
"logger": True,
"prog_bar": True,
"batch_size": y_pred.shape[0],
}
self.log(
f"{step_name}/loss",
loss,
**log_kwargs,
)
# Compute metrics
for metric_name, metric in self.metrics.items():
if metric_name.startswith(step_name):
if "grouped" in metric.__class__.__name__.lower():
metric.update(y_pred_flat, y_true_flat, groups=subject_ids_flat)
else:
if "retrieval" in metric_name:
metric.update(y_pred.mean(dim=-1), y_true.mean(dim=-1))
else:
metric.update(y_pred_flat, y_true_flat)
self.log(
metric_name,
metric,
**log_kwargs,
)
return loss, y_pred.detach().cpu(), y_true.detach().cpu()
def on_val_or_test_epoch_end(self, step_name: str) -> None:
for metric_name, metric in self.metrics.items():
if metric_name.startswith(step_name):
if "grouped" in metric.__class__.__name__.lower():
subject_id_to_name = {
v: k
for k, v in self.config[
"data.subject_id.predefined_mapping"
].items()
}
metric_dict = {
metric_name + "/" + subject_id_to_name[int(k)]: v
for k, v in metric.compute().items()
}
self.log_dict(metric_dict)
metric.reset()
def on_validation_epoch_end(self) -> None:
self.on_val_or_test_epoch_end("val")
return super().on_validation_epoch_end()
def on_test_epoch_end(self) -> None:
self.on_val_or_test_epoch_end("test")
return super().on_test_epoch_end()
def training_step(self, batch: SegmentData, batch_idx):
loss, _, _ = self._run_step(batch, batch_idx, step_name="train")
return loss
def validation_step(self, batch: SegmentData, batch_idx, dataloader_idx: int = 0):
_, y_pred, y_true = self._run_step(
batch, batch_idx, step_name="val", dataloader_idx=dataloader_idx
)
return y_pred, y_true
def test_step(self, batch: SegmentData, batch_idx, dataloader_idx: int = 0):
_, y_pred, y_true = self._run_step(
batch, batch_idx, step_name="test", dataloader_idx=dataloader_idx
)
return y_pred, y_true
def configure_optimizers(self):
optim_config = self.optim_config.copy()
unfrozen_params = [p for p in self.parameters() if p.requires_grad]
if self.config["max_steps"] > 0:
total_steps = self.config["max_steps"]
else:
total_steps = self.trainer.estimated_stepping_batches
optimizer = optim_config.build(unfrozen_params, total_steps=total_steps)
return optimizer1234567891011121314151617181920212223242526# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from .base import BasePlotBrain
from .cortical import PlotBrainNilearn
from .cortical_pv import PlotBrainPyvista
from .subcortical import get_subcortical_roi_indices, plot_subcortical
from .utils import (
combine_mosaics,
convert_ax_to_2d,
convert_ax_to_3d,
get_cmap,
get_pval_stars,
label_ax,
move_ax,
plot_colorbar,
plot_rgb_colorbar,
saturate_colors,
set_title,
shrink_ax,
)
PlotBrain = PlotBrainPyvista123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import typing as tpfrom functools import lru_cache
import matplotlibimport nibabel as nibimport numpy as npimport pydanticfrom neuralset.extractors.neuro import FSAVERAGE_SIZESfrom nilearn import datasets, image, maskers, surfacefrom scipy.spatial import cKDTree
cached_fetch_surf_fsaverage = lru_cache(datasets.fetch_surf_fsaverage)
class BasePlotBrain(pydantic.BaseModel): mesh: ( tp.Literal["fsaverage3", "fsaverage4", "fsaverage5", "fsaverage6", "fsaverage7"] | None ) = "fsaverage5" inflate: bool | tp.Literal["half"] = "half" bg_map: tp.Literal["sulcal", "curvature", "thresholded"] = "sulcal" hemisphere_gap: float = 0 atlas_name: str | None = None atlas_dim: int | None = None vol_to_surf_kwargs: dict | None = None model_config = pydantic.ConfigDict(extra="forbid")
VIEW_DICT: tp.ClassVar[dict] = {}
def model_post_init(self, __context: tp.Any) -> None: self._mesh = self.get_mesh()
# ------------------------------------------------------------------ # Axes helpers # ------------------------------------------------------------------
def get_axarr_and_views(self, axes, views): if isinstance(axes, dict): axes = {k: self._convert_ax(ax) for k, ax in axes.items()} if all(k in self.VIEW_DICT for k in axes): views, axarr = zip(*axes.items()) else: axarr = list(axes.values()) elif isinstance(axes, (list, np.ndarray)): axarr = axes elif isinstance(axes, matplotlib.axes.Axes): axarr = [axes] assert len(views) == len( axarr ), f"Number of views and axes must match, got {len(views)} and {len(axarr)}" return views, axarr
def _convert_ax(self, ax): """Hook for subclasses that need to convert axes (e.g. 3D -> 2D).""" return ax
# ------------------------------------------------------------------ # Atlas / volume-to-surface helpers # ------------------------------------------------------------------
def get_atlas(self): if not hasattr(self, "_atlas"): if self.atlas_name == "schaefer_2018": atlas = datasets.fetch_atlas_schaefer_2018(n_rois=self.atlas_dim) elif self.atlas_name == "difumo": atlas = datasets.fetch_atlas_difumo(dimension=self.atlas_dim) self._atlas = atlas return self._atlas
@property def atlas_masker(self): if not hasattr(self, "_atlas_masker"): atlas = self.get_atlas() if self.atlas_name == "schaefer_2018": atlas_masker = maskers.NiftiLabelsMasker(labels_img=atlas["maps"]) elif self.atlas_name == "difumo": atlas_masker = maskers.NiftiMapsMasker(maps_img=atlas["maps"]) atlas_masker.fit() self._atlas_masker = atlas_masker return self._atlas_masker
def atlas_to_surf(self, signals, img_threshold: float | None = None): signals_nii = self.signals_to_nii(signals) return self.vol_to_surf(signals_nii, img_threshold=img_threshold)
def vol_to_surf(self, signals_nii, img_threshold: float | None = None): vol_to_surf_kwargs = self.vol_to_surf_kwargs or {} if img_threshold is not None: signals_nii = image.threshold_img( signals_nii, threshold=img_threshold, copy=False, copy_header=True, ) fsaverage = cached_fetch_surf_fsaverage(mesh=self.mesh) hemis = [ surface.vol_to_surf( signals_nii, surf_mesh=fsaverage[f"pial_{hemi}"], kind="ball", **vol_to_surf_kwargs, ) for hemi in ("left", "right") ] return np.concatenate(hemis)
def signals_to_nii(self, signals): out = self.atlas_masker.inverse_transform(signals) if isinstance(self.atlas_masker, maskers.NiftiMapsMasker): data = out.get_fdata() lo, hi = signals.min(), signals.max() data = (data - data.min()) / (data.max() - data.min()) data = data * (hi - lo) + lo out = nib.Nifti1Image(data, out.affine, out.header) return out
# ------------------------------------------------------------------ # Mesh loading (eager – called once in model_post_init) # ------------------------------------------------------------------
def get_mesh(self) -> dict: """Load mesh geometry and background maps for both hemispheres.
Returns a dict with keys ``'left'``, ``'right'``, ``'both'``, each mapping to ``{'coords': array, 'faces': array, 'bg_map': array}``. The ``'both'`` entry has hemisphere_gap applied. """ fs_out = cached_fetch_surf_fsaverage(self.mesh)
out = {} for hemi in ("left", "right"): infl_out_xyz, _ = nib.load(getattr(fs_out, f"infl_{hemi}")).darrays pial_xyz, faces = nib.load(getattr(fs_out, f"pial_{hemi}")).darrays
alpha = 0.5 jr_xyz = infl_out_xyz.data * alpha + (1 - alpha) * pial_xyz.data if self.inflate == "half": coords = jr_xyz elif self.inflate is True: coords = infl_out_xyz.data elif self.inflate is False: coords = pial_xyz.data
bg_key = "curv" if self.bg_map == "curvature" else "sulc" bg_map = nib.load(getattr(fs_out, f"{bg_key}_{hemi}")).darrays[0].data if self.bg_map == "thresholded": bg_map = 1.0 * (bg_map > -0.10) bg_map[-1] = -5 bg_map[-2] = 2.0 if hemi == "left": coords[:, 0] = coords[:, 0] - coords[:, 0].max() - self.hemisphere_gap else: coords[:, 0] = coords[:, 0] - coords[:, 0].min() + self.hemisphere_gap
out[hemi] = dict(coords=coords, faces=faces.data, bg_map=bg_map)
out["both"] = dict( coords=np.r_[out["left"]["coords"], out["right"]["coords"]], faces=np.r_[ out["left"]["faces"], out["right"]["faces"] + out["left"]["faces"].max() + 1, ], bg_map=np.r_[out["left"]["bg_map"], out["right"]["bg_map"]], )
return out
# ------------------------------------------------------------------ # Stat-map upsampling (lazy – called per data array) # ------------------------------------------------------------------
def get_stat_map(self, data: np.ndarray) -> dict: """Split vertex data into hemispheres, upsampling if needed.
Returns ``{'left': array, 'right': array, 'both': array}``. """ in_mesh = None for name, size in FSAVERAGE_SIZES.items(): if data.shape[0] // 2 == size: in_mesh = name break if in_mesh is None: raise ValueError(f"Incoherent number of vertices: {data.shape[0]}")
left = data[: len(data) // 2] right = data[len(data) // 2 :]
if in_mesh != self.mesh: fs_in = cached_fetch_surf_fsaverage(in_mesh) fs_out = cached_fetch_surf_fsaverage(self.mesh) resampled = {} for hemi, values in (("left", left), ("right", right)): infl_in_xyz, _ = nib.load(getattr(fs_in, f"infl_{hemi}")).darrays infl_out_xyz, _ = nib.load(getattr(fs_out, f"infl_{hemi}")).darrays tree = cKDTree(infl_in_xyz.data) distances, indices = tree.query(infl_out_xyz.data, k=5) if "int" in data.dtype.name: # get most frequent resampled[hemi] = np.apply_along_axis( lambda x: np.bincount(x).argmax(), axis=1, arr=values[indices] ) else: distances = np.where(distances == 0, 1e-12, distances) weights = 1 / distances weights = weights / weights.sum(axis=1, keepdims=True) resampled[hemi] = np.sum(values[indices] * weights, axis=1) left, right = resampled["left"], resampled["right"]
return dict(left=left, right=right, both=np.r_[left, right])
def get_hemis(self, data: np.ndarray) -> dict: """Convenience: combine ``self._mesh`` geometry with stat-map data.""" stat_maps = self.get_stat_map(data) out = {} for hemi in ("left", "right", "both"): m = self._mesh[hemi] out[hemi] = dict( stat_map=stat_maps[hemi], surf_mesh=(m["coords"], m["faces"]), bg_map=m["bg_map"], hemi=hemi, ) return out
# ------------------------------------------------------------------ # Multi-timestep plotting # ------------------------------------------------------------------
def plot_timesteps( self, neuro: np.ndarray | dict[str, np.ndarray], segments=None, *, plot_every_k_timesteps: int = 1, trues=None, norm_percentile=None, show_stimuli=False, views: str | dict[str, str] = "left", timestamps: list[float] | None = None, **kwargs, ): import matplotlib.pyplot as plt from tqdm import tqdm
from cortexlab.viz.utils import robust_normalize
TEXT_KEY, SOUND_KEY, VIDEO_KEY = "Text", "Audio", "Video"
if isinstance(neuro, np.ndarray): neuro = {"Brain reponse": neuro} assert all( v.ndim == 2 for v in neuro.values() ), "Neuro must be a dictionary of 2D arrays" if isinstance(views, dict): assert all( key in views.keys() for key in neuro.keys() ), f"Views keys {views.keys()} do not match neuro keys {neuro.keys()}" total_n_timesteps = len(list(neuro.values())[0]) assert ( total_n_timesteps % plot_every_k_timesteps == 0 ), f"Total number of timesteps {total_n_timesteps} must be divisible by plot_every_k_timesteps {plot_every_k_timesteps}" neuro = {k: v[::plot_every_k_timesteps] for k, v in neuro.items()} n_timesteps = len(list(neuro.values())[0]) if timestamps is None: timestamps = range( 0, n_timesteps * plot_every_k_timesteps, plot_every_k_timesteps ) else: assert ( len(timestamps) == n_timesteps ), f"Number of timestamps {len(timestamps)} must match number of timesteps {n_timesteps}" if norm_percentile is not None: neuro = { k: robust_normalize(v, percentile=norm_percentile) for k, v in neuro.items() }
mosaic = [[f"{k}_{i}" for i in range(n_timesteps)] for k in neuro] height_ratios = [1 for _ in neuro] if show_stimuli: from cortexlab.viz.utils import get_clip
has_image = any(get_clip(segment) is not None for segment in segments) stimuli_mosaic = [ [SOUND_KEY] * n_timesteps, [TEXT_KEY] * n_timesteps, ] stimuli_height_ratios = [0.3, 0.3] if has_image: stimuli_mosaic = [ [f"{VIDEO_KEY}_{i}" for i in range(n_timesteps)] ] + stimuli_mosaic stimuli_height_ratios = [0.7] + stimuli_height_ratios mosaic = stimuli_mosaic + mosaic height_ratios = stimuli_height_ratios + height_ratios
fig, axes = plt.subplot_mosaic( mosaic, height_ratios=height_ratios, figsize=(2.5 * n_timesteps, 2 * sum(height_ratios)), gridspec_kw={"wspace": 0.0, "hspace": 0}, ) for k, ax in axes.items(): if ( k.startswith(TEXT_KEY) or k.startswith(SOUND_KEY) or k.startswith(VIDEO_KEY) ): fig.delaxes(ax) axes[k] = fig.add_subplot(ax.get_subplotspec())
for i in tqdm(range(n_timesteps), desc="Plotting..."): for j, (key, value) in enumerate(neuro.items()): self.plot_surf( value[i], axes=axes[f"{key}_{i}"], views=views[key] if isinstance(views, dict) else views, **kwargs, ) if j == len(neuro) - 1: title = ( f"t={timestamps[i]}s" if timestamps is not None else f"t={i}s" ) fig.text( 0.5, -0.1, title, transform=axes[f"{key}_{i}"].transAxes, ha="center", va="center", )
if show_stimuli: self.plot_stimuli( segments, axes, plot_every_k_timesteps=plot_every_k_timesteps )
first_neuro_keys = [key + "_0" for key in list(neuro.keys())] left, full_width = ( axes[first_neuro_keys[0]].get_position().x0, fig.get_figwidth(), ) for key, label in zip( first_neuro_keys + [TEXT_KEY, SOUND_KEY, f"{VIDEO_KEY}_0"], list(neuro.keys()) + [TEXT_KEY, SOUND_KEY, VIDEO_KEY], ): if key not in axes: continue pos = axes[key].get_position() fig.text( left, (pos.y0 + pos.y1) / 2, label + "\n\n\n", rotation="vertical", va="center", ha="center", transform=fig.transFigure, ) return fig
@staticmethod def plot_stimuli( segments, axes, plot_every_k_timesteps=1, ): import matplotlib.pyplot as plt
from cortexlab.viz.utils import get_audio, get_clip
TEXT_KEY, SOUND_KEY, VIDEO_KEY = "Text", "Audio", "Video"
audio = get_audio( segments[0], stop_offset=(len(segments) - 1) * segments[0].duration ) soundarray = audio.to_soundarray().mean(axis=1) axes[SOUND_KEY].plot(soundarray, color="k") axes[SOUND_KEY].set_xlim(0, len(soundarray)) axes[SOUND_KEY].axis("off") axes[TEXT_KEY].axis("off") full_start, full_duration = ( segments[0].start, len(segments) * segments[0].duration, )
for i, segment in enumerate(segments): if f"{VIDEO_KEY}_0" in axes and i % plot_every_k_timesteps == 0: ax_idx = i // plot_every_k_timesteps img = get_clip(segment).get_frame(0) margin = img.shape[1] * 0.0 ax = axes[f"{VIDEO_KEY}_{ax_idx}"] im = ax.imshow(img) patch = plt.matplotlib.patches.FancyBboxPatch( (0, 0), img.shape[1], img.shape[0], boxstyle="round,pad=0,rounding_size=200", transform=ax.transData, clip_on=False, facecolor="none", edgecolor="none", ) ax.add_patch(patch) im.set_clip_path(patch) ax.set_xlim(-margin, img.shape[1] + margin) ax.set_ylim(img.shape[0] + margin, -margin) ax.axis("off") events = segment.events words = events[events.type == "Word"] for word in words.itertuples(): if word.start < full_start: continue axes[TEXT_KEY].text( (word.start - full_start) / full_duration, 0.5, word.text, color="k", transform=axes[TEXT_KEY].transAxes, ha="center", va="center", rotation=45, fontsize=10, )
def plot_timesteps_mp4( self, neuro, filepath, *, segments=None, suptitle=None, interpolated_fps=None, norm_percentile=100, **plot_kwargs, ): import subprocess from pathlib import Path
import matplotlib.pyplot as plt from tqdm import tqdm
filepath = Path(filepath) tmp_dir = filepath.parent / "tmp" tmp_dir.mkdir(parents=True, exist_ok=True) for i in tqdm(range(len(neuro)), desc="Plotting..."): out_fig, ax = plt.subplots(1, 1, figsize=(3, 3)) self.plot_surf( neuro[i], axes=[ax], **plot_kwargs, ) title = suptitle or f"t = {i}s" out_fig.suptitle(title, fontsize=14, fontweight="bold") if segments: from cortexlab.viz.utils import get_text
words = " ".join(get_text(segments[i]).split(" ")[-8:]) out_fig.text(0.1, 0.92, words, fontsize=9, ha="left", va="top") tmp_fig = tmp_dir / f"tmp_{i:05d}.png" out_fig.savefig(tmp_fig, dpi=300) plt.close(out_fig) cmd = [ "ffmpeg", "-y", "-framerate", str(1), "-i", f"{str(tmp_dir)}/tmp_%05d.png", ] if interpolated_fps is not None: cmd.append("-vf") cmd.append(f"minterpolate=fps={interpolated_fps}") cmd.extend( [ "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p", str(filepath), ] ) subprocess.run(cmd)
# ------------------------------------------------------------------ # Rendering (subclasses must implement) # ------------------------------------------------------------------
def plot_surf(self, *args, **kwargs): raise NotImplementedError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import typing as tpfrom pathlib import Path
import matplotlibimport matplotlib.pyplot as pltimport numpy as npfrom neuralset.extractors.neuro import FSAVERAGE_SIZESfrom nilearn.datasets import load_fsaveragefrom nilearn.plotting import plot_surf_roi, plot_surf_stat_map
from cortexlab.data.loader import get_hcp_roi_indices
from .base import BasePlotBrainfrom .utils import get_cmap, get_scalar_mappable, robust_normalize, saturate_colors
VIEW_DICT = { "left": (0, 180), "right": (0, 0), "medial_left": (0, 0), "medial_right": (0, 180), "dorsal": (90, 0), "ventral": (-90, 0), "anterior": (0, 90), "posterior": (0, -90), "posterior_left": (0, -135), "posterior_right": (0, -45), "posterior_ventral": (-45, -90), "posterior_ventral_left": (-10, -135),}
class PlotBrainNilearn(BasePlotBrain):
VIEW_DICT: tp.ClassVar[dict] = VIEW_DICT
def get_fig_axes(self, views): if isinstance(views, str): views = [views] n_rows, n_cols = (1, len(views)) if len(views) <= 4 else (2, len(views) // 2) fig, axarr = plt.subplots( n_rows, n_cols, figsize=(2 * n_cols, 2 * n_rows), subplot_kw={"projection": "3d"}, gridspec_kw={"wspace": 0, "hspace": -0.2}, ) if len(views) == 1: axarr = [axarr] else: axarr = axarr.flatten() return fig, axarr
def plot_surf( self, signals: np.ndarray, norm_percentile=None, colorbar_title: str | None = None, alpha_cmap: tp.Tuple[float, float] | None = None, axes: tp.Any | None = None, colorbar_kwargs: dict | None = None, views: str | list[str] | list[tuple[int, int]] = "left", annotated_rois: list[str] | None = None, vmin: float | None = None, vmax: float | None = None, symmetric_cbar: bool = False, threshold: float | None = None, cmap: str = "hot", colorbar: bool = False, ): if isinstance(views, str): views = [views] if axes is None: fig, axarr = self.get_fig_axes(views=views) else: views, axarr = self.get_axarr_and_views(axes, views) fig = None
if self.atlas_name is not None: signals = self.atlas_to_surf(signals) elif signals.ndim == 3: signals = self.vol_to_surf(signals) assert ( signals.shape[0] // 2 in FSAVERAGE_SIZES.values() ), f"Incoherent number of vertices: {signals.shape[0]}" if norm_percentile is not None: signals = robust_normalize(signals, percentile=norm_percentile) hemis = self.get_hemis(signals) if str(signals.dtype).startswith("int"): plot_fn = plot_surf_roi for k in hemis: hemis[k]["roi_map"] = hemis[k].pop("stat_map") sm = None else: plot_fn = plot_surf_stat_map cmap = get_cmap(cmap, alpha_cmap=alpha_cmap) sm = get_scalar_mappable( signals, cmap, vmin=vmin, vmax=vmax, threshold=threshold, symmetric_cbar=symmetric_cbar, ) for i, (view, ax) in enumerate(zip(views, axarr)): selected_hemi = ( "left" if view in ["left", "medial_left"] else "right" if view in ["right", "medial_right"] else "both" ) if isinstance(view, str): view = VIEW_DICT[view] plot_kwargs = { "axes": ax, "view": view, "figure": fig, "bg_on_data": ( False if (alpha_cmap is not None or plot_fn == plot_surf_roi) else True ), "cmap": cmap, "vmin": vmin, "vmax": vmax, "threshold": threshold, "colorbar": False, } if plot_fn == plot_surf_stat_map: plot_kwargs["symmetric_cbar"] = symmetric_cbar plot_fn(**hemis[selected_hemi], **plot_kwargs) if annotated_rois is not None: self.annotate_rois(ax, annotated_rois, hemi=selected_hemi) ax.set_box_aspect(None, zoom=1.4)
if colorbar: if fig is None: cbar = plt.colorbar( sm, format="{x:0.2f}", label=colorbar_title, ax=axarr[-1], **colorbar_kwargs if colorbar_kwargs is not None else {}, shrink=0.5, ) else: cb_ax = fig.add_axes([0.9, 0.2, 0.02, 0.6]) cbar = fig.colorbar( sm, format="{x:0.2f}", label=colorbar_title, cax=cb_ax, **colorbar_kwargs if colorbar_kwargs is not None else {}, ) return sm
def plot_surf_rgb( self, signals: tp.List[np.ndarray], alpha_signals: np.ndarray | None = None, norm_percentile=95, alpha_bg=0, cmap: tp.Literal["rgb", "rgb_argmax", "tab10"] = "rgb", saturation_factor: None | float = None, save_path: str | None = None, axes: tp.List[matplotlib.axes.Axes] | None = None, views: list[str] | list[tuple[int, int]] = ["left"], bg_on_data=False, ): if isinstance(views, str): views = [views] if axes is None: fig, axarr = self.get_fig_axes(views=views) else: views, axarr = self.get_axarr_and_views(axes, views) fig = None
fsaverage_meshes = load_fsaverage(mesh=self.mesh) if self.atlas_name is not None: signals = [self.atlas_to_surf(signal) for signal in signals] elif signals[0].ndim == 4: signals = [self.vol_to_surf(signal) for signal in signals] for signal in signals: assert ( signal.shape[0] // 2 in FSAVERAGE_SIZES.values() ), f"Incoherent number of vertices: {signal.shape[0]//2}" hemis = [self.get_hemis(signal) for signal in signals] if alpha_signals is not None: alpha_hemis = self.get_hemis(alpha_signals) data = dict() for selected_hemis in ("left", "right", "both"): vertices, faces = hemis[0][selected_hemis]["surf_mesh"] colors = np.stack( [hemi[selected_hemis]["stat_map"] for hemi in hemis], axis=1 ) if cmap.startswith("rgb"): if len(signals) == 2: colors = np.concatenate( [colors, np.zeros((colors.shape[0], 1))], axis=1 ) assert colors.shape[1] == 3 if "argmax" in cmap: colors = robust_normalize(colors, axis=1, percentile=100) func = np.vectorize(lambda color: 0 if color < 1 else 1) colors = func(colors) if norm_percentile is not None: colors = robust_normalize( colors, percentile=norm_percentile, two_sided=False ) if saturation_factor is not None: colors = saturate_colors(colors, saturation_factor) colors = np.concatenate([colors, np.ones((colors.shape[0], 1))], axis=1) else: indices = np.argmax(colors, axis=1) cm = get_cmap(cmap) colors = cm(indices - 1) colors[indices == 0, :3] = np.zeros_like(colors[indices == 0, :3]) if alpha_signals is not None: alpha = alpha_hemis[selected_hemis]["stat_map"] alpha_bg = 1 - alpha[:, None]
bg = hemis[0][selected_hemis]["bg_map"] cmap_bg = plt.get_cmap("gray_r") bg = robust_normalize(bg, percentile=100) bg = cmap_bg(bg) if bg_on_data: colors[:, :3] = colors[:, :3] * bg[:, :3] else: colors[:, :3] = colors[:, :3] * (1 - alpha_bg) + bg[:, :3] * alpha_bg face_colors = np.mean(colors[faces], axis=1) data[selected_hemis] = dict( vertex_colors=colors, face_colors=face_colors, vertices=vertices, faces=faces, )
for view, ax in zip(views, axarr): selected_hemis = ( "left" if "left" in view else "right" if "right" in view else "both" ) colors = data[selected_hemis]["face_colors"] vertices = data[selected_hemis]["vertices"] faces = data[selected_hemis]["faces"]
p3dcollec = ax.plot_trisurf( vertices[:, 0], vertices[:, 1], vertices[:, 2], triangles=faces, linewidth=0.1, antialiased=False, color="white", ) ax.set_box_aspect(None, zoom=1.4) limits = [vertices.min(), vertices.max()] ax.set_xlim(*limits) ax.set_ylim(*limits) p3dcollec.set_facecolors(colors) ax.set_axis_off() ax.view_init(*VIEW_DICT[view]) if save_path is not None: save_path = Path(save_path) save_path.parent.mkdir(parents=True, exist_ok=True) np.save(save_path.with_suffix(".npy"), colors)
return data["both"]["vertex_colors"]
def save_gif(self, ax, save_path: str | None = None): import matplotlib.animation as animation
if save_path is None: save_path = "rgb_animation.gif"
angles = np.linspace(0, 360, 100, endpoint=False)
def animate(i): ax.view_init(elev=0, azim=angles[i]) return (ax,)
from matplotlib.animation import FuncAnimation
ani = FuncAnimation(ax.figure, animate, frames=len(angles), interval=30) writer = animation.PillowWriter(fps=30, bitrate=1800) ani.save(save_path, writer=writer)
def annotate_rois( self, ax, rois: str | list[str] | dict[str, list[str]], hemi: str = "left", **kwargs, ): if isinstance(rois, str): rois = [rois] assert hemi in ["left", "right"] data = np.zeros(2 * FSAVERAGE_SIZES[self.mesh]) vertices = self.get_hemis(data)["both"]["surf_mesh"][0] if hemi == "left": vertices = vertices[: FSAVERAGE_SIZES[self.mesh]] else: vertices = vertices[FSAVERAGE_SIZES[self.mesh] :] for roi in rois: vertex_indices = get_hcp_roi_indices(roi, mesh=self.mesh, hemi=hemi) roi_center = vertices[vertex_indices].mean(axis=0) roi_name = rois[roi] if isinstance(rois, dict) else roi ax.text(roi_center[0], roi_center[1], roi_center[2], roi_name, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import tempfileimport typing as tp
import matplotlib.pyplot as pltimport numpy as npimport pyvista as pvfrom neuralset.extractors.neuro import FSAVERAGE_SIZES
from cortexlab.data.loader import get_hcp_roi_indices
from .base import BasePlotBrainfrom .utils import ( convert_ax_to_2d, get_cmap, get_scalar_mappable, robust_normalize, saturate_colors, tight_crop,)
VIEW_DICT = { "ventral": ([0, 0, -1], [1, 0, 0]), "dorsal": ([0, 0, 1], [0, 1, 0]), "left": ([-1, 0, 0], [0, 0, 1]), "right": ([1, 0, 0], [0, 0, 1]), "anterior": ([0, 1, 0], [0, 0, -1]), "posterior": ([0, -1, 0], [0, 0, 1]), "medial_left": ([1, 0, 0], [0, 0, 1]), "medial_right": ([-1, 0, 0], [0, 0, 1]), "posterior_left": ([-1, 0, 0], [0, 0, 1]), "posterior_right": ([-1, 0, 0], [0, 0, 1]),}
class PlotBrainPyvista(BasePlotBrain):
dpi: int = 3000 bg_darkness: float = 0 ambient: float = 0.3 w_pad: float = 0.03 h_pad: float = 0.03
VIEW_DICT: tp.ClassVar[dict] = VIEW_DICT
def _convert_ax(self, ax): return convert_ax_to_2d(ax)
def annotate_rois( self, pl: pv.Plotter, rois: str | list[str] | dict[str, str], hemi: str = "left", **kwargs, ): if isinstance(rois, str): rois = [rois] hemis = ["left", "right"] if hemi == "both" else [hemi] n = FSAVERAGE_SIZES[self.mesh] for h in hemis: verts = self._mesh[h]["coords"] for roi in rois: idx = get_hcp_roi_indices(roi, mesh=self.mesh, hemi=h) if h == "right": idx = np.array(idx) - n center = verts[idx].mean(axis=0) name = rois[roi] if isinstance(rois, dict) else roi pl.add_point_labels( center.reshape(1, 3), [name], shape_opacity=0, **kwargs, )
def plot_surf( self, data, axes, views="left", alpha_cmap=None, vmin: float | None = None, vmax: float | None = None, symmetric_cbar: bool = False, threshold: float | None = None, cmap: str = "hot", norm_percentile: float | None = None, annotated_rois: str | list[str] | dict | None = None, annotated_rois_kwargs: dict | None = None, ): if norm_percentile is not None: data = robust_normalize(data, percentile=norm_percentile) if isinstance(views, str): views = [views] views, axes = self.get_axarr_and_views(axes, views) cmap = get_cmap(cmap, alpha_cmap=alpha_cmap) sm = get_scalar_mappable( data, cmap, vmin=vmin, vmax=vmax, threshold=threshold, symmetric_cbar=symmetric_cbar, )
stat_maps = self.get_stat_map(data)
for ax, view in zip(axes, views): selected_hemi = ( "left" if view in ["left", "medial_left"] else "right" if view in ["right", "medial_right"] else "both" ) mesh = self._mesh[selected_hemi] vertices, faces = mesh["coords"], mesh["faces"] stat_map = stat_maps[selected_hemi]
rgba = sm.to_rgba(stat_map) bg_map = mesh["bg_map"] bg_norm = (bg_map - bg_map.min()) / (bg_map.max() - bg_map.min() + 1e-8) bg_rgb = 1 - np.column_stack( [self.bg_darkness + bg_norm * (1 - self.bg_darkness)] * 3 ) colors = rgba[:, 3:4] * rgba[:, :3] + (1 - rgba[:, 3:4]) * bg_rgb
pv_faces = np.column_stack([np.full(len(faces), 3), faces])
ax_size = ax.get_position() pl = pv.Plotter( window_size=[ int(ax_size.width * self.dpi), int(ax_size.height * self.dpi), ], off_screen=True, )
surf = pv.PolyData(vertices, pv_faces) surf.point_data["colors"] = colors pl.add_mesh( surf, scalars="colors", rgb=True, smooth_shading=True, ambient=self.ambient, )
pl.set_background("white") vec, up = VIEW_DICT[view] pl.view_vector(vec, viewup=up) if annotated_rois is not None: self.annotate_rois( pl, annotated_rois, **(annotated_rois_kwargs or {}), ) with tempfile.NamedTemporaryFile(suffix=".png") as tmp: img = pl.screenshot(tmp.name, return_img=True) img = tight_crop(img, w_pad=self.w_pad, h_pad=self.h_pad) pl.clear() ax.axis("off") ax.imshow(img, aspect="equal")
return sm
def plot_surf_rgb( self, signals: tp.List[np.ndarray], alpha_signals: np.ndarray | None = None, norm_percentile=95, alpha_bg=0, cmap: tp.Literal["rgb", "rgb_argmax", "tab10"] = "rgb", saturation_factor: None | float = None, axes=None, views: list[str] = ["left"], bg_on_data=False, ): if isinstance(views, str): views = [views] views, axes = self.get_axarr_and_views(axes, views)
if self.atlas_name is not None: signals = [self.atlas_to_surf(signal) for signal in signals] elif signals[0].ndim == 4: signals = [self.vol_to_surf(signal) for signal in signals]
hemis = [self.get_hemis(signal) for signal in signals] if alpha_signals is not None: alpha_hemis = self.get_hemis(alpha_signals)
data = dict() for selected_hemis in ("left", "right", "both"): stat_maps = [hemi[selected_hemis]["stat_map"] for hemi in hemis] colors = np.stack(stat_maps, axis=1)
if cmap.startswith("rgb"): if len(signals) == 2: colors = np.concatenate( [colors, np.zeros((colors.shape[0], 1))], axis=1 ) assert colors.shape[1] == 3 if "argmax" in cmap: colors = robust_normalize(colors, axis=1, percentile=100) colors = (colors >= 1).astype(float) if norm_percentile is not None: colors = robust_normalize( colors, percentile=norm_percentile, two_sided=False ) if saturation_factor is not None: colors = saturate_colors(colors, saturation_factor) colors = np.concatenate([colors, np.ones((colors.shape[0], 1))], axis=1) else: indices = np.argmax(colors, axis=1) cm = get_cmap(cmap) colors = cm(indices - 1) colors[indices == 0, :3] = 0
if alpha_signals is not None: alpha = alpha_hemis[selected_hemis]["stat_map"] alpha_bg = 1 - alpha[:, None]
bg = hemis[0][selected_hemis]["bg_map"] cmap_bg = plt.get_cmap("gray_r") bg = robust_normalize(bg, percentile=100) bg = cmap_bg(bg) if bg_on_data: colors[:, :3] = colors[:, :3] * bg[:, :3] else: colors[:, :3] = colors[:, :3] * (1 - alpha_bg) + bg[:, :3] * alpha_bg
mesh = self._mesh[selected_hemis] data[selected_hemis] = dict( vertex_colors=colors, vertices=mesh["coords"], faces=mesh["faces"], )
for ax, view in zip(axes, views): selected_hemis = ( "left" if "left" in view else "right" if "right" in view else "both" ) d = data[selected_hemis]
pv_faces = np.column_stack([np.full(len(d["faces"]), 3), d["faces"]])
ax_size = ax.get_position() pl = pv.Plotter( window_size=[ int(ax_size.width * self.dpi), int(ax_size.height * self.dpi), ], off_screen=True, )
surf = pv.PolyData(d["vertices"], pv_faces) surf.point_data["colors"] = d["vertex_colors"][:, :3] pl.add_mesh( surf, color="black", scalars="colors", rgb=True, smooth_shading=True, ambient=0.3, )
vec, up = VIEW_DICT[view] pl.view_vector(vec, viewup=up) with tempfile.NamedTemporaryFile(suffix=".png") as tmp: img = pl.screenshot( tmp.name, return_img=True, transparent_background=True ) img = tight_crop(img, w_pad=self.w_pad, h_pad=self.h_pad) pl.clear() ax.axis("off") ax.imshow(img, aspect="equal")
return data["both"]["vertex_colors"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import copyimport tempfileimport typing as tpfrom functools import lru_cache
import matplotlib.pyplot as pltimport nibabel as nibimport numpy as npimport pyvista as pvimport seaborn as snsfrom nilearn import datasetsfrom nilearn.surface import vol_to_surffrom scipy.ndimage import gaussian_filterfrom skimage import measure
from cortexlab.viz.utils import ( get_cmap, get_scalar_mappable, robust_normalize, tight_crop,)
@lru_cache()def get_subcortical_mask(): atlas = datasets.fetch_atlas_harvard_oxford("sub-maxprob-thr50-2mm") excluded = ["Cortex", "White", "Stem", "Background"] selected_indices = [ i for i, label in enumerate(atlas.labels) if any([exc.lower() in label.lower() for exc in excluded]) ] mask_data = atlas.maps.get_fdata() mask_data[np.isin(mask_data, selected_indices)] = 0 mask = nib.Nifti1Image(mask_data, atlas.maps.affine, atlas.maps.header) return mask
def get_subcortical_labels(with_hemi: bool = False): excluded = ["Cortex", "White", "Stem", "Background"] labels = [ label for label in cached_ho_atlas().labels if not any([exc.lower() in label.lower() for exc in excluded]) ] if not with_hemi: labels = list( set( [ label.replace("Left ", "") for label in labels if label.startswith("Left ") ] ) ) return labels
@lru_cachedef cached_ho_atlas(resolution: tp.Literal["1mm", "2mm"] = "1mm"): return datasets.fetch_atlas_harvard_oxford(f"sub-maxprob-thr50-{resolution}")
def get_subcortical_roi_indices(roi: str): subcortical_mask = copy.deepcopy(get_subcortical_mask()) data = subcortical_mask.get_fdata() data = data[data > 0] ho_sub = cached_ho_atlas(resolution="2mm") labels = ho_sub.labels sel_labels = [label for label in labels if roi.lower() in label.lower()] assert sel_labels, f"ROI {roi} not found in atlas" sel_indices = [labels.index(label) for label in sel_labels] voxel_indices = np.where(np.isin(data, sel_indices))[0] return voxel_indices
def voxel_to_mesh(voxel_scores, label, resolution): subcortical_mask = copy.deepcopy(get_subcortical_mask()) data = subcortical_mask.get_fdata() data[data > 0] = voxel_scores nii = nib.Nifti1Image(data, subcortical_mask.affine, subcortical_mask.header) roi_mask = get_mask(label, resolution) mesh = get_mesh(label, resolution) return nii_to_mesh(nii, mesh, mask_img=roi_mask)
def nii_to_mesh(nii, mesh, mask_img=None): vertices = mesh.points faces = mesh.faces.reshape(-1, 4)[:, 1:] vertex_vals = vol_to_surf( nii, surf_mesh=(vertices, faces), mask_img=mask_img, kind="line", depth=np.linspace(-3, 0, 40), interpolation="linear", ) return vertex_vals
@lru_cache()def get_mask(label: str, resolution: tp.Literal["1mm", "2mm"] = "1mm"): # fetch Harvard-Oxford subcortical atlas ho_sub = cached_ho_atlas(resolution=resolution) img = ho_sub.maps if label == "Cerebellum": raise NotImplementedError( "Cerebellum atlas (Diedrichsen 2009) is not yet supported. " "Provide the atlas path manually." ) img = nib.load(file) mask = img.get_fdata() > 0 # merge all lobules automatically elif label == "Brain-Stem": # subcortical, return hemisphere-specific mesh (default: right) idx = ho_sub.labels.index(label) mask = img.get_fdata() == idx else: if "Left" in label or "Right" in label: idx = ho_sub.labels.index(label) mask = img.get_fdata() == idx else: # merge left + right left_idx = ho_sub.labels.index("Left " + label) right_idx = ho_sub.labels.index("Right " + label) data = img.get_fdata() mask = (data == left_idx) | (data == right_idx)
nii_mask = nib.Nifti1Image(mask.astype(float), img.affine, img.header)
return nii_mask
@lru_cache()def get_mesh(label: str, resolution: tp.Literal["1mm", "2mm"]): """ Returns a PyVista mesh for a given label. For 'Cerebellum', 'Cerebral Cortex', and 'Brain-Stem', left and right hemispheres are joined. For other subcortical labels, returns separate left/right meshes. """
if label == "Cerebral Cortex": fsaverage = datasets.fetch_surf_fsaverage("fsaverage7") nii = nib.load(fsaverage.pial_left) verts = nii.darrays[0].data faces = nii.darrays[1].data faces_pv = np.hstack([np.full((faces.shape[0], 1), 3), faces]).astype(np.int32) mesh = pv.PolyData(verts, faces_pv) return mesh
nii_mask = get_mask(label, resolution)
# smooth the mask slightly volume = gaussian_filter(nii_mask.get_fdata().astype(float), sigma=1)
# marching cubes verts, faces, normals, values = measure.marching_cubes(volume, level=0.9) # Convert voxel coordinates to world/MNI coordinates affine = nii_mask.affine verts = nib.affines.apply_affine(affine, verts)
# convert faces to PyVista format faces_pv = np.hstack([np.full((faces.shape[0], 1), 3), faces]).astype(np.int32)
# create PyVista mesh mesh = pv.PolyData(verts, faces_pv)
# smooth the mesh mesh = mesh.smooth(n_iter=50, relaxation_factor=0.01)
return mesh
def plot_subcortical( ax, *, colors: dict = None, voxel_scores: np.ndarray = None, average_per_roi: bool = False, norm_percentile: int = None, show_cortex: bool = False, show_brain_stem: bool = False, show_cerebellum: bool = False, explode: float = 0.5, resolution: tp.Literal["1mm", "2mm"] = "1mm", show_scalar_bar: bool = False, zoom: float = 1.3, azimuth: float = 15, elevation: float = -10, intensity: float = 1.5, vmin: float | None = None, vmax: float | None = None, symmetric_cbar: bool = False, threshold: float | None = None, cmap: str = "hot", alpha_cmap: tuple[float, float] = None, **plot_kwargs,): assert (colors is not None) ^ ( voxel_scores is not None ), "Either colors voxel_scores must be provided" labels = get_subcortical_labels(with_hemi=True) if colors is not None: assert isinstance(colors, dict), "Colors must be a dictionary" if voxel_scores is not None: assert voxel_scores.ndim in [1, 2], "voxel_scores must be a 1D or 2D array" if average_per_roi: for label in labels: indices = get_subcortical_roi_indices(label) voxel_scores[indices] = voxel_scores[indices].mean() if norm_percentile: voxel_scores = robust_normalize(voxel_scores, percentile=norm_percentile) if show_cerebellum: labels.append("Cerebellum") if show_cortex: labels.append("Cerebral Cortex") if show_brain_stem: labels.append("Brain-Stem") plotter = pv.Plotter(lighting="none") rgb = False cmap = get_cmap(cmap, alpha_cmap=alpha_cmap) sm = get_scalar_mappable( voxel_scores, cmap, vmin=vmin, vmax=vmax, threshold=threshold, symmetric_cbar=symmetric_cbar, ) for label in labels: mesh = get_mesh(label, resolution) if label in ["Cerebral Cortex", "Brain-Stem"]: color = plt.cm.gray(0.8) else: if colors is not None: color = colors[label] scalars = None else: assert voxel_scores is not None color = plt.cm.gray(0.8) if voxel_scores.ndim == 1: scalars = voxel_to_mesh(voxel_scores, label, resolution) scalars = sm.to_rgba(scalars) rgb = True elif voxel_scores.ndim == 2: assert voxel_scores.shape[0] == 3 scalars = np.stack( [ voxel_to_mesh(voxel_scores, label, resolution) for voxel_scores in voxel_scores ], axis=1, ) rgb = True exploded_points = copy.deepcopy(mesh.points) if label == "Cerebral Cortex": exploded_points[:, 0] = ( exploded_points[:, 0] + explode * exploded_points[:, 0].mean() ) else: exploded_points[:, 2] = ( exploded_points[:, 2] + explode * exploded_points.mean(axis=0)[2] ) exploded_mesh = pv.PolyData(exploded_points, mesh.faces) plotter.add_mesh( exploded_mesh, color=color, scalars=scalars, rgb=rgb, show_scalar_bar=show_scalar_bar, ) plotter.window_size = [300, 300] plotter.camera.zoom(zoom) plotter.camera.azimuth = azimuth plotter.camera.elevation = elevation light = pv.Light(intensity=intensity) light.set_headlight() plotter.add_light(light)
with tempfile.NamedTemporaryFile(suffix=".png") as tmp: img = plotter.screenshot(tmp.name, return_img=True) img = tight_crop(img) ax.imshow(img) ax.axis("off") return sm
if __name__ == "__main__":
labels = get_subcortical_labels(with_hemi=False) palette = sns.color_palette("Set1", n_colors=len(labels)) colors = { f"{hemi} {label}": palette[i] for i, label in enumerate(labels) for hemi in ["Left", "Right"] } plotter = plot_subcortical( colors=colors, average_per_roi=True, cmap="fire", show_cerebellum=False, explode=1, resolution="1mm", zoom=1.3, ) plt.show()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import re
from functools import reduce
import colorcet
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap
def robust_normalize(
array, axis=None, percentile=99, clip=True, final_range=None, two_sided=True
):
"""Normalize the input array using statistics robust to outliers."""
hi = np.percentile(array, percentile, axis=axis, keepdims=True)
if two_sided:
lo = np.percentile(array, 100 - percentile, axis=axis, keepdims=True)
else:
lo = np.min(array, axis=axis, keepdims=True)
out = (array - lo) / (hi - lo)
if clip:
out = np.clip(out, 0, 1)
if final_range is not None:
if final_range == "original":
final_range = (lo, hi)
out = out * (final_range[1] - final_range[0]) + final_range[0]
return out
def get_scalar_mappable(
data,
cmap,
vmin=None,
vmax=None,
symmetric_cbar=False,
threshold=None,
alpha_cmap=None,
):
vmin = vmin if vmin is not None else np.nanmin(data)
vmax = vmax if vmax is not None else np.nanmax(data)
if symmetric_cbar:
vmin, vmax = -vmax, vmax
sm = get_thresholded_sm(vmin, vmax, threshold=threshold, cmap=cmap)
return sm
def get_thresholded_sm(vmin, vmax, threshold=None, cmap=None):
if cmap is None:
cmap = matplotlib.cm.get_cmap("hot")
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
cmaplist = [cmap(i) for i in range(cmap.N)]
# set colors to gray for absolute values < threshold
if threshold is not None:
istart = int(norm(-threshold, clip=True) * (cmap.N - 1))
istop = int(norm(threshold, clip=True) * (cmap.N - 1))
for i in range(istart, istop):
cmaplist[i] = (0.5, 0.5, 0.5, 1.0)
our_cmap = LinearSegmentedColormap.from_list("Custom cmap", cmaplist, cmap.N)
sm = plt.cm.ScalarMappable(cmap=our_cmap, norm=norm)
# fake up the array of the scalar mappable.
sm._A = []
return sm
def get_pval_stars(pval: float):
if pval < 0.0005:
return "***"
elif pval < 0.005:
return "**"
elif pval < 0.05:
return "*"
else:
return ""
def saturate_colors(rgb: np.ndarray, factor: float):
"""
rgb: tuple/list/array of (R, G, B) in 0-1 range
factor: >1 boosts saturation, 1 leaves unchanged, 0 makes gray
"""
rgb = np.array(rgb, dtype=float)
# Compute luminance (perceptual gray)
# Using Rec.709 coefficients for a fairly natural grayscale
grayscale_coeffs = np.array([0.2126, 0.7152, 0.0722])
if rgb.ndim == 1:
lum = np.dot(grayscale_coeffs, rgb)
elif rgb.ndim == 2:
lum = np.dot(grayscale_coeffs, rgb.T)
lum = lum[:, None].repeat(3, axis=1)
else:
raise ValueError(f"Invalid number of dimensions: {rgb.ndim}")
# Pull or push the channels relative to gray
new_rgb = lum + factor * (rgb - lum)
# Clamp to 0–1
new_rgb = np.clip(new_rgb, 0, 1)
return new_rgb
def get_alpha_cmap(cmap, threshold: float = 0, scale: float = 1, symmetric=False):
"""
Takes a cmap and makes it transparent below a threshold.
Transparency is linearly scaled between threshold and threshold + scale.
"""
assert 0 <= threshold <= 1
from matplotlib.colors import ListedColormap
n_points = 1024
new_cmap = cmap(np.linspace(0, 1, n_points))
alpha = np.zeros_like(new_cmap[:, 3])
# zeros before min, ramp 0 to 1 between min and max, 1 after max
min_idx = int(threshold * (n_points - 1))
max_idx = int((threshold + scale) * (n_points - 1))
ramp = np.linspace(0, 1, max_idx - min_idx)
alpha[min_idx : min(max_idx, n_points)] = ramp[: min(max_idx, n_points) - min_idx]
alpha[min(max_idx, n_points) :] = 1
# alpha[max_idx:] = 1
if symmetric:
alpha = np.concatenate([alpha[::-2], alpha[::2]])
new_cmap[:, 3] = alpha
new_cmap = ListedColormap(new_cmap)
return new_cmap
def get_cmap(
cmap_name: str | matplotlib.colors.Colormap,
alpha_cmap: tuple[float, float] | None = None,
):
if isinstance(cmap_name, str):
cmap = (
getattr(matplotlib.cm, cmap_name, None)
or getattr(sns.cm, cmap_name, None)
or getattr(colorcet.cm, cmap_name, None)
)
else:
cmap = cmap_name
if not cmap:
raise ValueError(f"Invalid cmap: {cmap}")
if alpha_cmap is not None:
threshold, scale = alpha_cmap
cmap = get_alpha_cmap(
cmap,
threshold=threshold,
scale=scale,
symmetric=(cmap_name in ["seismic", "bwr"]),
)
return cmap
def convert_ax_to_3d(ax):
if hasattr(ax, "view_init"):
return ax
pos = ax.get_position()
# subplotspec = ax.get_subplotspec()
ax3d = ax.figure.add_axes(pos, projection="3d")
# ax3d.set_position(pos)
ax.remove()
return ax3d
def convert_ax_to_2d(ax):
pos = ax.get_position()
ax2d = ax.figure.add_axes(pos)
ax.remove()
return ax2d
def lcm(a, b):
return a * b // math.gcd(a, b) if a and b else max(a, b)
def _lcm_list(lst):
return reduce(lcm, lst, 1)
def _repeat_chars(line, times):
return "".join(c * times for c in line)
def _transpose(block):
if not block:
return []
max_len = max(len(row) for row in block)
block = [row.ljust(max_len) for row in block]
return ["".join(block[r][c] for r in range(len(block))) for c in range(max_len)]
def _check_unique_letters(*blocks):
"""
Ensure all blocks have unique letters across blocks.
Raises an AssertionError if any letter appears in more than one block.
"""
unique = set()
for i, block in enumerate(blocks, 1):
letters = set(block.replace("\n", ""))
assert not (
letters & unique
), f"Duplicate letters found in block {i}: {letters & unique}"
unique.update(letters)
def _format_block(mosaic: str) -> str:
return mosaic.replace(" ", "").lstrip("\n").rstrip("\n")
def combine_mosaics(*blocks, ratio=None, orient="v"):
if len(blocks) < 2:
raise ValueError("Need at least two blocks to combine")
_check_unique_letters(*blocks)
blocks = [_format_block(block) for block in blocks]
# Normalize input
blocks_lines = [block.split("\n") for block in blocks]
# Normalize ratio
if ratio is None:
ratios = [1.0] * len(blocks_lines)
else:
try:
ratios = list(ratio)
if len(ratios) != len(blocks_lines):
raise ValueError
except Exception:
ratios = [float(ratio)] * len(blocks_lines)
# Transpose if horizontal
transposed = False
if orient == "v":
blocks_lines = [_transpose(b) for b in blocks_lines]
transposed = True
# Horizontal expansion (columns)
cols_list = [max(len(line) for line in b) if b else 0 for b in blocks_lines]
Lw = _lcm_list(cols_list)
blocks_expanded = []
for b, c, r in zip(blocks_lines, cols_list, ratios):
b = [line.ljust(c) for line in b]
h = max(1, int(round(Lw / c * r)))
blocks_expanded.append([_repeat_chars(line, h) for line in b])
# Vertical expansion (rows)
rows_list = [len(b) for b in blocks_expanded]
Lh = _lcm_list(rows_list)
blocks_tiled = []
for b, r in zip(blocks_expanded, ratios):
v = max(1, int(round(Lh / len(b))))
blocks_tiled.append([line for line in b for _ in range(v)])
# Combine all blocks
combined = ["".join(lines) for lines in zip(*blocks_tiled)]
# Transpose back if needed
if transposed:
combined = _transpose(combined)
return _format_block("\n".join(combined))
def plot_colorbar(
ax,
sm=None,
cmap=colorcet.cm.fire,
vmin=0,
vmax=1,
label="R",
label_orientation="vertical",
orientation="vertical",
**kwargs,
):
# Hide the axis background, ticks, and spines
ax.set_frame_on(False)
ax.set_xticks([])
ax.set_yticks([])
# Create a ScalarMappable for the colorbar
if sm is None:
norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
sm = matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap)
sm.set_array([]) # Required for colorbar
# Draw the colorbar inside the given axis
cbar = plt.colorbar(sm, cax=ax, orientation=orientation, **kwargs)
# Set the label if provided
if label is not None:
rotation = 0 if label_orientation == "horizontal" else 90
cbar.set_label(label, rotation=rotation, labelpad=5)
# Add border by setting the color and linewidth of all spines
rect = matplotlib.patches.Rectangle(
(0, 0),
1,
1,
transform=cbar.ax.transAxes,
fill=False,
edgecolor="k",
linewidth=0.5,
clip_on=False,
)
# cbar.ax.add_patch(rect)
return cbar
def shrink_ax(ax, shrink=0.1, horizontally=True, vertically=True):
pos = ax.get_position()
# shrink from all sides
horizontal_shrink = pos.width * shrink if horizontally else 0
vertical_shrink = pos.height * shrink if vertically else 0
new_pos = [
pos.x0 + horizontal_shrink / 2,
pos.y0 + vertical_shrink / 2,
pos.width - horizontal_shrink,
pos.height - vertical_shrink,
]
ax.set_position(new_pos)
def move_ax(ax, x=0, y=0):
pos = ax.get_position()
up = y * pos.height
right = x * pos.width
new_pos = [
pos.x0 + right,
pos.y0 + up,
pos.width,
pos.height,
]
ax.set_position(new_pos)
def label_ax(
ax,
label,
x_offset=0,
y_offset=0.03,
fontsize=14,
fontweight="bold",
facecolor="none",
edgecolor="none",
):
pos = ax.get_position()
fig = ax.get_figure()
fig.text(
pos.x0 + x_offset,
pos.y1 + y_offset,
label,
fontsize=fontsize,
fontweight=fontweight,
ha="center",
va="center",
)
def set_title(axes, title, x_offset=0, y_offset=0, **kwargs):
if not isinstance(axes, list):
axes = [axes]
centers = [(ax.get_position().x0 + ax.get_position().x1) / 2 for ax in axes]
x = np.mean(centers)
x = x + x_offset
y = axes[0].get_position().y1 + y_offset
fig = axes[0].get_figure()
if not "ha" in kwargs:
kwargs["ha"] = "center"
if not "va" in kwargs:
kwargs["va"] = "top"
fig.text(x, y, title, **kwargs)
def tight_crop(img, bg_color=(255, 255, 255), tol=5, w_pad=0, h_pad=0):
if img.shape[2] == 4: # alpha channel exists
alpha = img[..., 3]
ys, xs = np.where(alpha > 0)
else:
bg = np.array(bg_color)
mask = np.any(np.abs(img[..., :3] - bg) > tol, axis=2)
ys, xs = np.where(mask)
if len(xs) == 0:
return img # nothing found
left, right, bottom, top = xs.min(), xs.max(), ys.min(), ys.max()
w_pad = int(w_pad * (right - left))
h_pad = int(h_pad * (top - bottom))
left, bottom = max(0, left - w_pad), max(0, bottom - h_pad)
right, top = min(img.shape[1], right + w_pad), min(img.shape[0], top + h_pad)
return img[bottom : top + 1, left : right + 1]
def plot_rgb_colorbar(n_cubes=4, alpha=1, labels=["Text", "Audio", "Video"]):
# Use a dark background to make the colors pop
# plt.style.use('dark_background')
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111, projection="3d", proj_type="persp", focal_length=0.15)
x = np.linspace(0, 1, n_cubes)
y = np.linspace(0, 1, n_cubes)
z = np.linspace(0, 1, n_cubes)
X, Y, Z = np.meshgrid(x, y, z)
X, Y, Z = np.ravel(X), np.ravel(Y), np.ravel(Z)
colors = np.array([X, Y, Z]).T
size = 0.2
for i in range(len(X)):
ax.bar3d(
X[i] - size / 2,
Y[i] - size / 2,
Z[i] - size / 2,
size,
size,
size,
color=colors[i],
alpha=alpha,
edgecolor="none",
)
# --- AXIS ARROWS (QUINVERS) ---
# We extend the arrows past the data (to 1.4) to show direction clearly
arrow_props = dict(arrow_length_ratio=0.1, linewidth=1, pivot="tail")
ax.quiver(0, 0, 0, 1.4, 0, 0, color="k", **arrow_props)
ax.quiver(0, 0, 0, 0, 1.4, 0, color="k", **arrow_props)
ax.quiver(0, 0, 0, 0, 0, 1.4, color="k", **arrow_props)
# --- LABELS ---
# Positioning labels at the tips of the arrows
pos = 1.5
ax.text(pos, 0, 0, labels[0], color="red", fontweight="bold", ha="center", va="top")
ax.text(
0, pos, 0, labels[1], color="green", fontweight="bold", ha="center", va="top"
)
ax.text(0, 0, pos, labels[2], color="blue", fontweight="bold", ha="center")
# Remove all background clutter
ax.set_axis_off()
ax.set_facecolor((0, 0, 0, 0)) # Transparent pane
# view_init: Azimuth -45 degrees keeps the origin cube (black) at the front
# ax.view_init(elev=-40, azim=-135)
ax.view_init(elev=45, azim=-135 + 180)
ax.set_box_aspect(None, zoom=0.85)
return fig
def get_rainbow_brain(mesh="fsaverage5", hemi="both"):
import matplotlib.colors as mcolors
from nilearn.datasets import fetch_surf_fsaverage
from nilearn.surface import load_surf_mesh
fsaverage = fetch_surf_fsaverage(mesh=mesh)
sphere_l, _ = load_surf_mesh(fsaverage["sphere_left"])
sphere_r, _ = load_surf_mesh(fsaverage["sphere_right"])
if hemi == "both":
coords = np.concatenate([sphere_l, sphere_r], axis=0)
else:
coords = sphere_l if hemi == "left" else sphere_r
x, y, z = coords.T
# SYMMETRY LOGIC:
# On fsaverage, +x is Right, -x is Left.
# To make them symmetric, we take the absolute value of X
# or flip the X for the right hemisphere so that 'lateral' is always
# the same direction relative to the color wheel.
x_mapped = x if hemi == "left" else -x
# Hue based on Longitude (using the corrected X)
phi = np.arctan2(y, x_mapped)
hues = (phi + np.pi) / (2 * np.pi)
# Value based on Elevation (Z) to make it more distinct
# (Optional: adds a slight brightness gradient from bottom to top)
z_norm = (z - z.min()) / (z.max() - z.min() + 1e-8)
vals = np.clip(0.8 + (z_norm * 0.3), 0, 1)
hsv = np.stack([hues, np.ones_like(hues) * 0.9, vals], axis=1)
return mcolors.hsv_to_rgb(hsv)
# ---------------------------------------------------------------------------
# Segment helpers (moved from analyses/utils.py)
# ---------------------------------------------------------------------------
def has_video(segment) -> bool:
return any(e.__class__.__name__ == "Video" for e in segment.ns_events)
def has_audio(segment) -> bool:
return any(e.__class__.__name__ == "Audio" for e in segment.ns_events)
def get_clip(segment, start_offset=0, stop_offset=0):
from moviepy import VideoFileClip
if not has_video(segment):
return None
video = [e for e in segment.ns_events if e.__class__.__name__ == "Video"][0]
clip = VideoFileClip(video.filepath)
true_start = video.start - video.offset
clip = clip.subclipped(
max(segment.start + start_offset - true_start, 0),
min(segment.stop + stop_offset - true_start, clip.duration),
)
return clip
def get_audio(segment, start_offset=0, stop_offset=0):
from moviepy import AudioFileClip
if not has_audio(segment):
return None
audio = [e for e in segment.ns_events if e.__class__.__name__ == "Audio"][0]
clip = AudioFileClip(audio.filepath)
true_start = audio.start - audio.offset
clip = clip.subclipped(
max(segment.start + start_offset - true_start, 0),
min(segment.stop + stop_offset - true_start, clip.duration),
)
return clip
def get_words(segment, filter=(0, 1), remove_punctuation=True, remove_stopwords=False):
start, duration = segment.start, segment.duration
clean = (
(lambda x: re.sub(r"[^\w\s]", "", x)) if remove_punctuation else (lambda x: x)
)
words = [
clean(e.text.lower())
for e in segment.ns_events
if e.__class__.__name__ == "Word"
and filter[0] <= (e.start - start) / duration <= filter[1]
]
if remove_stopwords:
from stopwords import get_stopwords
words = [w for w in words if w not in get_stopwords("english")]
return words
def get_text(segment, **kwargs) -> str:
return " ".join(get_words(segment, **kwargs))
if __name__ == "__main__":
fig = plot_rgb_colorbar()
plt.show()12345678"""Shared test utilities."""
import neuralset.segments as seg
def make_segments(n): """Create n dummy segments for SegmentData construction.""" return [seg.Segment(start=float(i), duration=1.0, timeline="test") for i in range(n)]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Tests for ROI attention extraction."""
from unittest.mock import MagicMock
import numpy as npimport pytestimport torch
class TestAttentionExtractor: def test_context_manager_returns_list(self): from cortexlab.core.attention import AttentionExtractor
encoder = torch.nn.TransformerEncoder( torch.nn.TransformerEncoderLayer(d_model=32, nhead=4, batch_first=True), num_layers=2, ) with AttentionExtractor(encoder) as maps: x = torch.randn(2, 10, 32) _ = encoder(x)
assert isinstance(maps, list)
def test_hooks_cleaned_up(self): from cortexlab.core.attention import AttentionExtractor
encoder = torch.nn.TransformerEncoder( torch.nn.TransformerEncoderLayer(d_model=32, nhead=4, batch_first=True), num_layers=2, ) with AttentionExtractor(encoder) as _maps: x = torch.randn(1, 5, 32) _ = encoder(x)
# Hooks should be cleaned up after exiting context assert isinstance(_maps, list)
class TestAttentionToRoiScores: def test_basic_roi_scores(self): from cortexlab.core.attention import attention_to_roi_scores
# Simulate 2 layers of attention maps: (B=1, heads=4, T=10, T=10) attn_maps = [torch.randn(1, 4, 10, 10) for _ in range(2)] roi_indices = { "V1": np.array([0, 1, 2]), "MT": np.array([5, 6]), } scores = attention_to_roi_scores(attn_maps, roi_indices)
assert "V1" in scores assert "MT" in scores assert scores["V1"].shape == (10,) assert scores["MT"].shape == (10,)
def test_with_predictor_weights(self): from cortexlab.core.attention import attention_to_roi_scores
attn_maps = [torch.randn(1, 4, 10, 10)] roi_indices = { "V1": np.array([0, 1]), "A1": np.array([3, 4]), } # Predictor weights: (hidden=32, n_vertices=10) weights = torch.randn(32, 10) scores = attention_to_roi_scores(attn_maps, roi_indices, predictor_weights=weights)
assert "V1" in scores assert "A1" in scores
def test_empty_attn_maps(self): from cortexlab.core.attention import attention_to_roi_scores
roi_indices = {"V1": np.array([0, 1])} scores = attention_to_roi_scores([], roi_indices)
assert "V1" in scores assert len(scores["V1"]) == 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Tests for modality attribution."""
from unittest.mock import MagicMock
import numpy as npimport pytestimport torch
from tests.conftest import make_segments
def _make_mock_model(n_vertices=100): """Create a mock model for attribution testing.""" model = MagicMock() model.feature_dims = {"text": (2, 32), "audio": (2, 32), "video": (2, 32)} model.eval = MagicMock()
call_count = [0]
def fake_forward(batch, **kwargs): call_count[0] += 1 B = 2 # Make text-ablated predictions differ more to simulate importance if torch.all(batch.data.get("text", torch.ones(1)) == 0): return torch.ones(B, n_vertices, 10) * 0.5 elif torch.all(batch.data.get("audio", torch.ones(1)) == 0): return torch.ones(B, n_vertices, 10) * 0.8 elif torch.all(batch.data.get("video", torch.ones(1)) == 0): return torch.ones(B, n_vertices, 10) * 0.9 return torch.ones(B, n_vertices, 10) * 1.0
model.side_effect = fake_forward model.return_value = torch.ones(2, n_vertices, 10) # Override __call__ to use our function model.__class__ = type("MockModel", (), { "__call__": staticmethod(fake_forward), "feature_dims": {"text": (2, 32), "audio": (2, 32), "video": (2, 32)}, "eval": lambda self: None, }) # Simpler approach: just use a plain class class FakeModel: feature_dims = {"text": (2, 32), "audio": (2, 32), "video": (2, 32)} def eval(self): pass def __call__(self, batch, **kwargs): return fake_forward(batch, **kwargs) return FakeModel()
class TestModalityAttributor: def test_ablation_basic(self): from neuralset.dataloader import SegmentData
from cortexlab.inference.attribution import ModalityAttributor
model = _make_mock_model() attributor = ModalityAttributor(model)
data = { "text": torch.randn(2, 2, 32, 20), "audio": torch.randn(2, 2, 32, 20), "video": torch.randn(2, 2, 32, 20), "subject_id": torch.zeros(2, dtype=torch.long), } batch = SegmentData(data=data, segments=make_segments(2)) scores = attributor.attribute(batch)
assert "text" in scores assert "audio" in scores assert "video" in scores assert scores["text"].shape == (100,)
def test_text_most_important(self): from neuralset.dataloader import SegmentData
from cortexlab.inference.attribution import ModalityAttributor
model = _make_mock_model() attributor = ModalityAttributor(model)
data = { "text": torch.randn(2, 2, 32, 20), "audio": torch.randn(2, 2, 32, 20), "video": torch.randn(2, 2, 32, 20), "subject_id": torch.zeros(2, dtype=torch.long), } batch = SegmentData(data=data, segments=make_segments(2)) scores = attributor.attribute(batch)
# Text ablation causes the biggest change (1.0 -> 0.5 = 0.5 diff) assert scores["text"].mean() > scores["audio"].mean() assert scores["audio"].mean() > scores["video"].mean()
def test_normalised_scores_sum_to_one(self): from neuralset.dataloader import SegmentData
from cortexlab.inference.attribution import ModalityAttributor
model = _make_mock_model() attributor = ModalityAttributor(model)
data = { "text": torch.randn(2, 2, 32, 20), "audio": torch.randn(2, 2, 32, 20), "video": torch.randn(2, 2, 32, 20), "subject_id": torch.zeros(2, dtype=torch.long), } batch = SegmentData(data=data, segments=make_segments(2)) scores = attributor.attribute(batch)
total = scores["text_normalised"] + scores["audio_normalised"] + scores["video_normalised"] np.testing.assert_allclose(total, 1.0, atol=1e-6)
def test_with_roi_indices(self): from neuralset.dataloader import SegmentData
from cortexlab.inference.attribution import ModalityAttributor
roi_indices = { "V1": np.array([0, 1, 2, 3, 4]), "MT": np.array([10, 11, 12]), } model = _make_mock_model() attributor = ModalityAttributor(model, roi_indices=roi_indices)
data = { "text": torch.randn(2, 2, 32, 20), "audio": torch.randn(2, 2, 32, 20), "video": torch.randn(2, 2, 32, 20), "subject_id": torch.zeros(2, dtype=torch.long), } batch = SegmentData(data=data, segments=make_segments(2)) scores = attributor.attribute(batch)
assert "text_roi" in scores assert "V1" in scores["text_roi"] assert "MT" in scores["text_roi"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091"""Tests for the brain-alignment benchmark."""
import numpy as npimport pytest
class TestBrainAlignmentBenchmark: def _make_data(self, n_stimuli=20, model_dim=64, n_vertices=100): model_features = np.random.randn(n_stimuli, model_dim) brain_predictions = np.random.randn(n_stimuli, n_vertices) return model_features, brain_predictions
def test_rsa_returns_score(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() bench = BrainAlignmentBenchmark(brain_pred) result = bench.score_model(model_feat, method="rsa") assert -1.0 <= result.aggregate_score <= 1.0 assert result.method == "rsa" assert result.n_stimuli == 20
def test_cka_returns_score(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() bench = BrainAlignmentBenchmark(brain_pred) result = bench.score_model(model_feat, method="cka") assert isinstance(result.aggregate_score, float) assert result.method == "cka"
def test_procrustes_returns_score(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() bench = BrainAlignmentBenchmark(brain_pred) result = bench.score_model(model_feat, method="procrustes") assert isinstance(result.aggregate_score, float)
def test_identical_features_high_score(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
data = np.random.randn(30, 50) bench = BrainAlignmentBenchmark(data) result = bench.score_model(data, method="cka") assert result.aggregate_score > 0.95
def test_roi_scores(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() roi_indices = { "V1": np.array([0, 1, 2, 3, 4]), "MT": np.array([10, 11, 12, 13, 14]), } bench = BrainAlignmentBenchmark(brain_pred, roi_indices=roi_indices) result = bench.score_model(model_feat, method="rsa") assert "V1" in result.roi_scores assert "MT" in result.roi_scores
def test_roi_filter(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() roi_indices = { "V1": np.array([0, 1, 2]), "MT": np.array([10, 11]), "A1": np.array([20, 21]), } bench = BrainAlignmentBenchmark(brain_pred, roi_indices=roi_indices) result = bench.score_model(model_feat, method="rsa", roi_filter=["V1", "A1"]) assert "V1" in result.roi_scores assert "A1" in result.roi_scores assert "MT" not in result.roi_scores
def test_stimulus_count_mismatch_raises(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat = np.random.randn(10, 32) brain_pred = np.random.randn(20, 100) bench = BrainAlignmentBenchmark(brain_pred) with pytest.raises(ValueError, match="Stimulus count mismatch"): bench.score_model(model_feat, method="rsa")
def test_unknown_method_raises(self): from cortexlab.analysis.brain_alignment import BrainAlignmentBenchmark
model_feat, brain_pred = self._make_data() bench = BrainAlignmentBenchmark(brain_pred) with pytest.raises(ValueError, match="Unknown method"): bench.score_model(model_feat, method="banana")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""Tests for the cognitive load scorer."""
import numpy as npimport pytest
def _make_roi_indices(): """Create minimal ROI indices for testing.""" return { # Executive "46": np.array([0, 1]), "FEF": np.array([2, 3]), "p32pr": np.array([4]), # Visual "V1": np.array([10, 11, 12]), "V2": np.array([13, 14]), "MT": np.array([15, 16]), # Auditory "A1": np.array([20, 21, 22]), "LBelt": np.array([23]), # Language "44": np.array([30, 31]), "45": np.array([32, 33]), "TPOJ1": np.array([34]), }
class TestCognitiveLoadScorer: def test_basic_scoring(self): from cortexlab.analysis.cognitive_load import CognitiveLoadScorer
roi_indices = _make_roi_indices() scorer = CognitiveLoadScorer(roi_indices)
# Create predictions with 50 vertices, 10 timepoints predictions = np.random.randn(10, 50) result = scorer.score_predictions(predictions)
assert 0.0 <= result.overall_load <= 1.0 assert 0.0 <= result.visual_complexity <= 1.0 assert 0.0 <= result.auditory_demand <= 1.0 assert 0.0 <= result.language_processing <= 1.0 assert 0.0 <= result.executive_load <= 1.0
def test_timeline_length(self): from cortexlab.analysis.cognitive_load import CognitiveLoadScorer
roi_indices = _make_roi_indices() scorer = CognitiveLoadScorer(roi_indices)
predictions = np.random.randn(15, 50) result = scorer.score_predictions(predictions, tr_seconds=1.5)
assert len(result.timeline) == 15 # Check timeline timestamps assert result.timeline[0][0] == 0.0 assert abs(result.timeline[1][0] - 1.5) < 1e-6
def test_single_timepoint(self): from cortexlab.analysis.cognitive_load import CognitiveLoadScorer
roi_indices = _make_roi_indices() scorer = CognitiveLoadScorer(roi_indices)
predictions = np.random.randn(50) # 1D input result = scorer.score_predictions(predictions)
assert len(result.timeline) == 1 assert 0.0 <= result.overall_load <= 1.0
def test_high_visual_activation(self): from cortexlab.analysis.cognitive_load import CognitiveLoadScorer
roi_indices = _make_roi_indices() scorer = CognitiveLoadScorer(roi_indices, baseline_activation=0.1)
# Create predictions with very high activation in visual ROIs predictions = np.zeros((5, 50)) for roi in ["V1", "V2", "MT"]: predictions[:, roi_indices[roi]] = 10.0
result = scorer.score_predictions(predictions) # Visual complexity should be highest (capped at 1.0 due to normalization) assert result.visual_complexity > 0.5
def test_custom_cognitive_map(self): from cortexlab.analysis.cognitive_load import CognitiveLoadScorer
roi_indices = {"V1": np.array([0, 1, 2]), "A1": np.array([3, 4])} custom_map = { "visual_complexity": ["V1"], "auditory_demand": ["A1"], } scorer = CognitiveLoadScorer(roi_indices, cognitive_map=custom_map)
predictions = np.random.randn(5, 10) result = scorer.score_predictions(predictions)
assert result.executive_load == 0.0 # Not in custom map assert result.language_processing == 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Tests for the core FmriEncoder model."""
from unittest.mock import MagicMock
import pytestimport torch
def _make_model(hidden=256, n_outputs=100, n_timesteps=10, modalities=None): """Build a small FmriEncoderModel for testing.""" from neuraltrain.models.transformer import TransformerEncoder
from cortexlab.core.model import FmriEncoder
if modalities is None: modalities = {"text": (2, 32), "audio": (2, 32), "video": (2, 32)}
config = FmriEncoder( hidden=hidden, max_seq_len=128, dropout=0.0, modality_dropout=0.0, temporal_dropout=0.0, linear_baseline=False, encoder=TransformerEncoder(depth=2, heads=4), ) model = config.build( feature_dims=modalities, n_outputs=n_outputs, n_output_timesteps=n_timesteps, ) return model
def _make_segments(n): """Create dummy segments for SegmentData.""" import neuralset.segments as seg return [seg.Segment(start=float(i), duration=1.0, timeline="test") for i in range(n)]
def _make_batch(modalities, batch_size=2, seq_len=20): """Create a synthetic SegmentData-like batch.""" from neuralset.dataloader import SegmentData
data = {} for name, (n_layers, feat_dim) in modalities.items(): data[name] = torch.randn(batch_size, n_layers, feat_dim, seq_len) data["subject_id"] = torch.zeros(batch_size, dtype=torch.long) return SegmentData(data=data, segments=_make_segments(batch_size))
class TestFmriEncoderModel: def test_forward_shape(self): modalities = {"text": (2, 32), "audio": (2, 32)} model = _make_model(modalities=modalities) batch = _make_batch(modalities) out = model(batch) assert out.shape == (2, 100, 10), f"Expected (2, 100, 10), got {out.shape}"
def test_forward_no_pool(self): modalities = {"text": (2, 32)} model = _make_model(modalities=modalities) batch = _make_batch(modalities) out = model(batch, pool_outputs=False) assert out.shape[0] == 2 assert out.shape[1] == 100
def test_return_attn(self): modalities = {"text": (2, 32)} model = _make_model(modalities=modalities) batch = _make_batch(modalities) result = model(batch, return_attn=True) assert isinstance(result, tuple) out, attn_maps = result assert out.shape == (2, 100, 10) # attn_maps may be empty if the transformer doesn't expose weights assert isinstance(attn_maps, list)
def test_missing_modality_zeros(self): modalities = {"text": (2, 32), "audio": (2, 32)} model = _make_model(modalities=modalities) # Only provide text, not audio from neuralset.dataloader import SegmentData data = {"text": torch.randn(2, 2, 32, 20), "subject_id": torch.zeros(2, dtype=torch.long)} batch = SegmentData(data=data, segments=_make_segments(2)) out = model(batch) assert out.shape == (2, 100, 10)
def test_modality_dropout_training(self): modalities = {"text": (2, 32), "audio": (2, 32)} from neuraltrain.models.transformer import TransformerEncoder
from cortexlab.core.model import FmriEncoder config = FmriEncoder( hidden=256, max_seq_len=128, modality_dropout=0.5, encoder=TransformerEncoder(depth=2, heads=4), ) model = config.build(feature_dims=modalities, n_outputs=100, n_output_timesteps=10) model.train() batch = _make_batch(modalities) out = model(batch) assert out.shape == (2, 100, 10)
def test_linear_baseline(self): modalities = {"text": (2, 32)} from cortexlab.core.model import FmriEncoder config = FmriEncoder(hidden=256, linear_baseline=True) model = config.build(feature_dims=modalities, n_outputs=100, n_output_timesteps=10) batch = _make_batch(modalities) out = model(batch) assert out.shape == (2, 100, 10).github/ISSUE_TEMPLATE/bug_report.mdAdded+27
.github/ISSUE_TEMPLATE/experiment.mdAdded+22
.github/ISSUE_TEMPLATE/feature_request.mdAdded+19
.github/PULL_REQUEST_TEMPLATE.mdAdded+15
.github/workflows/ci.ymlAdded+28
.gitignoreAdded+17
CONTRIBUTING.mdAdded+110
LICENSEAdded+407
MODEL_CARD.mdAdded+131
NOTICEAdded+75
README.md+136-3
examples/quick_start.pyAdded+72
pyproject.tomlAdded+85
src/cortexlab/__init__.pyAdded+20
src/cortexlab/analysis/__init__.pyAdded+4
src/cortexlab/analysis/brain_alignment.pyAdded+223
src/cortexlab/analysis/cognitive_load.pyAdded+276
src/cortexlab/core/__init__.pyAdded+3
src/cortexlab/core/attention.pyAdded+117
src/cortexlab/core/model.pyAdded+288
src/cortexlab/core/subject.pyAdded+177
src/cortexlab/data/__init__.pyAdded+15
src/cortexlab/data/fmri.pyAdded+248
src/cortexlab/data/loader.pyAdded+318
src/cortexlab/data/studies/__init__.pyAdded+10
src/cortexlab/data/studies/algonauts2025.pyAdded+315
src/cortexlab/data/studies/lahner2024bold.pyAdded+293
src/cortexlab/data/studies/lebel2023bold.pyAdded+344
src/cortexlab/data/studies/wen2017.pyAdded+78
src/cortexlab/data/transforms.pyAdded+273
src/cortexlab/inference/__init__.pyAdded+4
src/cortexlab/inference/attribution.pyAdded+93
src/cortexlab/inference/predictor.pyAdded+392
src/cortexlab/inference/streaming.pyAdded+158
src/cortexlab/training/__init__.pyAdded+3
src/cortexlab/training/experiment.pyAdded+651
src/cortexlab/training/pl_module.pyAdded+155
src/cortexlab/viz/__init__.pyAdded+26
src/cortexlab/viz/base.pyAdded+497
src/cortexlab/viz/cortical.pyAdded+311
src/cortexlab/viz/cortical_pv.pyAdded+280
src/cortexlab/viz/subcortical.pyAdded+311
src/cortexlab/viz/utils.pyAdded+563
tests/__init__.pyAdded
tests/conftest.pyAdded+8
tests/test_attention.pyAdded+78
tests/test_attribution.pyAdded+136
tests/test_brain_alignment.pyAdded+91
tests/test_cognitive_load.pyAdded+100
tests/test_model.pyAdded+111