Metadata-Version: 2.5
Name: ndx-hed
Version: 0.3.0
Summary: NWB extension for HED data
Project-URL: Homepage, https://github.com/hed-standard/ndx-hed
Project-URL: Documentation, https://www.hedtags.org/ndx-hed
Project-URL: Bug Tracker, https://github.com/hed-standard/ndx-hed/issues
Project-URL: Discussions, https://github.com/orgs/hed-standard/discussions
Project-URL: Changelog, https://github.com/hed-standard/ndx-hed/CHANGELOG.md
Author-email: Kay Robbins <kay.robbins@utsa.edu>, Ryan Ly <rly@lbl.gov>, Oliver Ruebel <oruebel@lbl.gov>, Ian Callanan <ianrcallanan@gmail.com>
License: BSD-3
License-File: LICENSE.txt
Keywords: NWB,NeurodataWithoutBorders,ndx-extension,nwb-extension
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Requires-Dist: hdmf>=6.2.0
Requires-Dist: hedtools>=1.3.0
Requires-Dist: pynwb>=4.2.0
Provides-Extra: dev
Requires-Dist: coverage>=7.5.4; extra == 'dev'
Requires-Dist: mdformat-myst>=0.1.5; extra == 'dev'
Requires-Dist: mdformat>=0.7.0; extra == 'dev'
Requires-Dist: pre-commit>=3.5.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest-subtests>=0.12.0; extra == 'dev'
Requires-Dist: pytest>=8.3.3; extra == 'dev'
Requires-Dist: python-dateutil>=2.8.2; extra == 'dev'
Requires-Dist: ruff>=0.16.0; extra == 'dev'
Requires-Dist: typos>=1.29.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: hdmf-docutils>=0.4.7; extra == 'docs'
Requires-Dist: myst-parser[linkify]>=3.0.1; extra == 'docs'
Requires-Dist: sphinx-autodoc-typehints<3.12.1,>=3.0.0; extra == 'docs'
Requires-Dist: sphinx-book-theme>=1.1.3; extra == 'docs'
Requires-Dist: sphinx-copybutton>=0.5.2; extra == 'docs'
Requires-Dist: sphinx-design>=0.6.1; extra == 'docs'
Requires-Dist: sphinx<10.0,>=9.0.0; extra == 'docs'
Provides-Extra: test
Requires-Dist: coverage>=7.5.4; extra == 'test'
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
Requires-Dist: pytest-subtests>=0.12.0; extra == 'test'
Requires-Dist: pytest>=8.3.3; extra == 'test'
Requires-Dist: python-dateutil>=2.8.2; extra == 'test'
Description-Content-Type: text/markdown

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.13142816.svg)](https://doi.org/10.5281/zenodo.13142816) [![PyPI version](https://badge.fury.io/py/ndx-hed.svg)](https://badge.fury.io/py/ndx-hed) [![codecov](https://codecov.io/gh/hed-standard/ndx-hed/branch/main/graph/badge.svg)](https://codecov.io/gh/hed-standard/ndx-hed)

# ndx-hed extension for NWB

[**Neurodata Without Borders (NWB)**](https://www.nwb.org/) is a data standard for organizing neurophysiology data. NWB is used extensively as the data representation for single cell and animal recordings as well as human neuroimaging modalities such as IEEG. NWB organizes all of the data from one recording session into a single file.

[HED (Hierarchical Event Descriptors)](https://www.hedtags.org) is a system of standardized vocabularies and supporting tools that allows fine-grained annotation of data. HED annotations can now be used in NWB to provide HED annotations for any NWB dynamic table.

The [HED integration for NWB](https://www.hedtags.org/ndx-hed/) gives a quickstart, examples and the API reference. The [NWB annotation quickstart](https://www.hedtags.org/hed-resources/NWBAnnotationQuickstart.html) gives a brief overview of how to get started.

## Installation

**Python:**

```bash
pip install -U ndx-hed
```

**Matlab:** The Matlab extension is under development.

## Quick start

```python
from pynwb import NWBFile
from ndx_hed import HedLabMetaData, HedTags
from datetime import datetime

# Create NWB file with HED metadata
nwbfile = NWBFile(
    session_description="Example session with HED annotations",
    identifier="example_session_001",
    session_start_time=datetime.now(),
)

# Add HED schema metadata (required). A library schema merged with its partner is
# "8.5.0,score_2.2.0"; schemas in separate namespaces are a list, ["8.5.0", "sc:score_2.2.0"].
hed_metadata = HedLabMetaData(hed_schema_version="8.5.0")
nwbfile.add_lab_meta_data(hed_metadata)

# Add HED column to trials table
nwbfile.add_trial_column(name="HED", col_cls=HedTags, data=[], description="HED annotations for trials")

# Add trials with HED annotations
nwbfile.add_trial(start_time=0.0, stop_time=1.0, HED="Experimental-trial, (Sensory-event, Visual-presentation)")
```

## Main classes

The ndx-hed extension provides four classes:

| Class                 | Purpose                                               | Use Cases                                           |
| --------------------- | ----------------------------------------------------- | --------------------------------------------------- |
| **HedLabMetaData**    | HED schema specification and lab-specific definitions | Required for all HED validation                     |
| **HedTags**           | Row-specific HED annotations                          | Row-specific tags in any DynamicTable               |
| **HedValueVector**    | Column-wide HED templates                             | Shared annotations with value placeholders (#)      |
| **HedDurationVector** | The EventsTable duration column with a HED template   | Durations whose value is part of the annotation (#) |

## HED annotation rules

HED annotations in NWB follow a small set of rules so that a table's HED can be assembled and validated consistently:

1. A `HedTags` column must be named `HED`. Because column names within a table are unique, a `DynamicTable` therefore holds at most one `HedTags` column.
2. A `HedTags` column inside a `MeaningsTable` supplies categorical (per-value) HED for the annotated column. In any other `DynamicTable` it supplies per-row HED for that table.
3. A `HedValueVector` column carries one HED template with a single `#` placeholder that applies to every value in the column. It may have any name and is identified by its type.
4. A `HedValueVector` may not appear in a `MeaningsTable` (a value template has no meaning for categorical values); `HedNWBValidator.validate_table` reports one as `MEANINGS_VALUE_VECTOR_INVALID`.
5. The `duration` column of an `EventsTable` carries HED as a `HedDurationVector`: the core `DurationVectorData` with a template, validated as a `HedValueVector` is (for example `(Duration/# s, (Sensory-event))`). An `onset` column carries no HED, and `duration` cannot be categorical.

## Examples

The `examples/` directory contains comprehensive runnable examples:

- **[01_basic_hed_classes.py](examples/01_basic_hed_classes.py)** - Introduction to the three main classes
- **[02_trials_with_hed.py](examples/02_trials_with_hed.py)** - Adding HED to trials table
- **[03_events_table_integration.py](examples/03_events_table_integration.py)** - Integration with the PyNWB core EventsTable
- **[04_bids_conversion.py](examples/04_bids_conversion.py)** - Converting BIDS events to NWB with HED
- **[05_hed_validation.py](examples/05_hed_validation.py)** - Comprehensive validation examples
- **[06_complete_workflow.py](examples/06_complete_workflow.py)** - End-to-end workflow demonstration
- **[07_hed_definitions.py](examples/07_hed_definitions.py)** - Custom HED definitions usage

Run any example:

```bash
cd examples
python 01_basic_hed_classes.py
```

Or run all examples:

```bash
cd examples
python run_all_examples.py
```

## Integration with NWB events

The ndx-hed extension works seamlessly with the PyNWB core `EventsTable` (NWBEP001, PyNWB >= 4.2.0) to provide comprehensive event annotation capabilities. HED annotations can be incorporated in three ways:

1. **Direct HED column** - Event-specific annotations
2. **HedValueVector columns** - Shared annotations with value placeholders
3. **Categorical columns with MeaningsTable** - Category-based annotations

See [examples/03_events_table_integration.py](examples/03_events_table_integration.py) for detailed demonstrations.

## BIDS compatibility

[**BIDS (Brain Imaging Data Structure)**](https://bids.neuroimaging.io/index.html) is a data standard for organizing neuroimaging and behavioral data from an entire experiment. The standard uses JSON files called "sidecars" to store metadata associated with its tabular files.

The ndx-hed extension provides utilities to convert between BIDS events files and NWB `EventsTable` format:

```python
from ndx_hed.utils.bids2nwb import extract_meanings, get_events_table, get_bids_tabular
import pandas as pd
import json

# Convert BIDS to EventsTable
bids_events_file_path = "Your_events_path_here.tsv"
bids_sidecar_file_path = "Your_json_sidecar_path_here.json"
events_df = pd.read_csv(bids, sep="\t")
json_data = json.load(bids_sidecar_file_path)
meanings = extract_meanings(bids_sidecar_file_path)
events_table = get_events_table("task_events", "Task events", events_df, meanings)

# Convert EventsTable to BIDS
bids_df, sidecar_dict = get_bids_tabular(events_table)
```

See [examples/04_bids_conversion.py](examples/04_bids_conversion.py) for complete examples.

## HED validation

Creating HED annotations for NWB data and saving these annotations as part of an `NWBFile` does not mean the annotations are valid. HED validation is performed to ensure they conform to the HED schema:

```python
from ndx_hed import HedLabMetaData
from ndx_hed.utils.hed_nwb_validator import HedNWBValidator

# Create validator and validate entire file
hed_metadata = HedLabMetaData(hed_schema_version="8.5.0")
validator = HedNWBValidator(hed_metadata)

# Assume nwbfile has already been created
issues = validator.validate_file(nwbfile)

if not issues:
    print("All HED annotations are valid!")
```

`validate_file` validates every `DynamicTable` (except `MeaningsTable`) by assembling each row's full HED annotation (its per-row HED column, its categorical HED from any `MeaningsTable`, and its value templates) and validating with the HED tools. Tables that are time-anchored (have an `onset` column, such as an `EventsTable`) are validated as a timeline, so temporal HED (onset/offset/duration scopes across rows) is checked; other tables are validated per row. A `MeaningsTable` is validated as part of the table whose column it annotates, not on its own.

See [examples/05_hed_validation.py](examples/05_hed_validation.py) for comprehensive validation examples.

## Additional resources

- [HED specification](https://www.hedtags.org/hed-specification)
- [HED python tools](https://github.com/hed-standard/hed-python)
- [NWB documentation](https://pynwb.readthedocs.io/)

## Contributing

Contributions are welcome! Feel free to submit issues or pull requests.
