io
lacuna.io
¶
Input/Output module for loading and saving lesion data.
Provides functions for: - Loading lesion masks from NIfTI files - Loading BIDS datasets - Exporting results to BIDS derivatives format - Saving NIfTI files - Exporting analysis results to CSV/TSV/JSON - Fetching and caching reference datasets (atlases, templates) - Converting connectome data to Lacuna HDF5 format - Downloading and registering connectomes (GSP1000, dTOR985)
BidsError
¶
Bases: LacunaError
Raised when BIDS dataset operations fail.
ConnectomeSource
dataclass
¶
Configuration for a fetchable connectome source.
Source code in src/lacuna/io/downloaders/base.py
article_id = None
class-attribute
instance-attribute
¶
Figshare article ID for API-based downloads.
citation = ''
class-attribute
instance-attribute
¶
Citation text for this connectome dataset.
dataverse_server = 'https://dataverse.harvard.edu'
class-attribute
instance-attribute
¶
Dataverse server URL.
default_batches = 10
class-attribute
instance-attribute
¶
Default number of HDF5 batches (functional only).
description
instance-attribute
¶
User-facing description of the connectome.
display_name
instance-attribute
¶
Human-readable name (e.g., 'GSP1000 Functional Connectome').
download_url = None
class-attribute
instance-attribute
¶
Direct download URL for Figshare files (deprecated, use article_id).
estimated_size_gb = 0.0
class-attribute
instance-attribute
¶
Estimated download size in GB for user information.
mask_url = None
class-attribute
instance-attribute
¶
URL to download brain mask if required.
n_subjects = 0
class-attribute
instance-attribute
¶
Number of subjects in the connectome.
name
instance-attribute
¶
Unique identifier (e.g., 'gsp1000', 'dtor985').
persistent_id = None
class-attribute
instance-attribute
¶
DOI for Dataverse datasets (e.g., 'doi:10.7910/DVN/ILXIKS').
requires_mask = False
class-attribute
instance-attribute
¶
Whether brain mask is needed for processing.
source_type
instance-attribute
¶
Download source requiring specific authentication/handling.
space = 'MNI152NLin6Asym'
class-attribute
instance-attribute
¶
Coordinate space.
type
instance-attribute
¶
Connectome type determining processing pipeline.
FetchConfig
dataclass
¶
Configuration for a connectome fetch operation.
Source code in src/lacuna/io/downloaders/base.py
api_key = None
class-attribute
instance-attribute
¶
Dataverse API key (for GSP1000). Can also use DATAVERSE_API_KEY env var.
batches = 10
class-attribute
instance-attribute
¶
Number of HDF5 batch files for functional connectomes.
connectome
instance-attribute
¶
Connectome name to fetch (e.g., 'gsp1000', 'dtor985').
force = False
class-attribute
instance-attribute
¶
Overwrite existing files and registrations.
keep_original = True
class-attribute
instance-attribute
¶
Keep original downloaded files after processing.
output_dir
instance-attribute
¶
Directory for processed output files.
register = True
class-attribute
instance-attribute
¶
Automatically register connectome after processing.
register_name = None
class-attribute
instance-attribute
¶
Custom name for registration. Defaults to source name (e.g., 'GSP1000').
resume = True
class-attribute
instance-attribute
¶
Resume interrupted downloads.
from_cli_args(args)
classmethod
¶
Create config from CLI arguments.
Source code in src/lacuna/io/downloaders/base.py
get_api_key()
¶
Get API key from config, env var, or config file.
Source code in src/lacuna/io/downloaders/base.py
FetchProgress
dataclass
¶
Progress information for fetch operations.
Source code in src/lacuna/io/downloaders/base.py
bytes_total = 0
class-attribute
instance-attribute
¶
Total bytes for current download.
bytes_transferred = 0
class-attribute
instance-attribute
¶
Bytes transferred in current download.
current_file
instance-attribute
¶
Name of file currently being processed.
download_percent
property
¶
Current file download percentage.
files_completed
instance-attribute
¶
Number of files completed.
files_total
instance-attribute
¶
Total number of files to process.
message = ''
class-attribute
instance-attribute
¶
Human-readable status message.
percent_complete
property
¶
Overall percentage completion.
phase
instance-attribute
¶
Current operation phase.
FetchResult
dataclass
¶
Result of a connectome fetch operation.
Source code in src/lacuna/io/downloaders/base.py
connectome_name
instance-attribute
¶
Name of the fetched connectome.
download_time_seconds = 0.0
class-attribute
instance-attribute
¶
Time spent downloading.
duration_seconds = 0.0
class-attribute
instance-attribute
¶
Total operation time in seconds.
error = None
class-attribute
instance-attribute
¶
Error message if success=False.
output_dir
instance-attribute
¶
Directory containing processed files.
output_files = field(default_factory=list)
class-attribute
instance-attribute
¶
List of created output files.
processing_time_seconds = 0.0
class-attribute
instance-attribute
¶
Time spent processing.
register_name = None
class-attribute
instance-attribute
¶
Name used for registration, or None if not registered.
registered = False
class-attribute
instance-attribute
¶
Whether the connectome was registered.
success
instance-attribute
¶
Whether the operation completed successfully.
warnings = field(default_factory=list)
class-attribute
instance-attribute
¶
Non-fatal warnings encountered.
summary()
¶
Generate human-readable summary.
Source code in src/lacuna/io/downloaders/base.py
batch_export_to_csv(mask_data_list, output_path, analysis_name=None, include_metadata=True)
¶
Export results from multiple SubjectData objects to a single CSV.
Combines results from multiple subjects into one CSV file with each row representing one subject. Ideal for group-level statistical analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data_list
|
list[SubjectData]
|
List of SubjectData objects (typically from batch processing) |
required |
output_path
|
str or Path
|
Output CSV file path |
required |
analysis_name
|
str
|
Specific analysis to export. If None, exports all results. |
None
|
include_metadata
|
bool
|
Include subject metadata as columns |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created CSV file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If list is empty or subjects have no results |
Examples:
>>> from lacuna.io import load_bids_dataset, batch_export_to_csv
>>> from lacuna.analysis import RegionalDamage
>>>
>>> # Load multiple subjects
>>> dataset = load_bids_dataset("bids_dir")
>>> analysis = RegionalDamage()
>>>
>>> # Run analysis on all subjects
>>> results = [analysis.run(lesion) for lesion in dataset.values()]
>>>
>>> # Export to single CSV for group analysis
>>> batch_export_to_csv(results, "group_results.csv")
Notes
- All subjects must have the same analysis results structure
- Missing values are filled with NaN
- Each row represents one subject
- Columns are shared across all subjects
Source code in src/lacuna/io/export.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
batch_export_to_tsv(mask_data_list, output_path, analysis_name=None, include_metadata=True)
¶
Export results from multiple SubjectData objects to a single TSV.
Identical to batch_export_to_csv but uses tab delimiter. TSV is preferred in neuroimaging for BIDS compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data_list
|
list[SubjectData]
|
List of SubjectData objects |
required |
output_path
|
str or Path
|
Output TSV file path |
required |
analysis_name
|
str
|
Specific analysis to export |
None
|
include_metadata
|
bool
|
Include subject metadata as columns |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created TSV file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If list is empty or subjects have no results |
Examples:
>>> from lacuna.io import batch_export_to_tsv
>>>
>>> # Export group results to BIDS-compatible TSV
>>> batch_export_to_tsv(results, "group_results.tsv")
See Also
batch_export_to_csv : CSV batch export
Source code in src/lacuna/io/export.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | |
export_bids_derivatives(subject_data, output_dir, export_lesion_mask=True, export_voxelmaps=True, export_parcel_data=True, export_connectivity=True, export_scalars=True, export_provenance=True, overwrite=False)
¶
Export SubjectData and all its analysis results to BIDS derivatives format.
Exports the full spectrum of results stored in a SubjectData object: - Lesion mask as NIfTI - VoxelMaps (correlation maps, disconnection maps, etc.) as NIfTI - ParcelData (regional values) as TSV - ConnectivityMatrix as TSV - ScalarMetric and other scalars as JSON - Processing provenance as JSON
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject_data
|
SubjectData
|
Processed lesion data with analysis results. |
required |
output_dir
|
str or Path
|
Root directory for derivatives (e.g., 'derivatives/lacuna-v0.1.0'). |
required |
export_lesion_mask
|
bool
|
Save the original lesion mask as NIfTI file. |
True
|
export_voxelmaps
|
bool
|
Save VoxelMap results (e.g., correlation maps, z-maps) as NIfTI files. |
True
|
export_parcel_data
|
bool
|
Save ParcelData results (regional aggregations) as TSV files. |
True
|
export_connectivity
|
bool
|
Save ConnectivityMatrix results as TSV files. |
True
|
export_scalars
|
bool
|
Save ScalarMetric and other scalar results as JSON files. |
True
|
export_provenance
|
bool
|
Save processing provenance as JSON. |
True
|
overwrite
|
bool
|
Overwrite existing files. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created subject derivatives directory. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If output files exist and overwrite=False. |
ValueError
|
If subject_data has no subject_id in metadata. |
Examples:
>>> # Export all results
>>> output_path = export_bids_derivatives(
... subject_data,
... 'derivatives/lacuna-v0.1.0'
... )
>>> print(f"Derivatives saved to: {output_path}")
>>>
>>> # Export only VoxelMaps (NIfTI files)
>>> export_bids_derivatives(
... subject_data,
... 'derivatives/lacuna-v0.1.0',
... export_lesion_mask=False,
... export_parcel_data=False,
... export_connectivity=False,
... export_scalars=False,
... export_provenance=False
... )
Source code in src/lacuna/io/bids.py
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 | |
export_provenance_to_json(mask_data, output_path, indent=2)
¶
Export provenance data to JSON format.
Saves the complete processing history and metadata as a standalone JSON file for reproducibility and audit trails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data
|
SubjectData
|
SubjectData object with provenance data |
required |
output_path
|
str or Path
|
Output JSON file path |
required |
indent
|
int
|
JSON indentation for readability (0 for compact) |
2
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created JSON file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mask_data has no provenance data |
Examples:
>>> from lacuna.io import export_provenance_to_json
>>>
>>> # Export provenance history
>>> export_provenance_to_json(result, "provenance.json")
>>>
>>> # Export compact JSON
>>> export_provenance_to_json(result, "prov.json", indent=0)
Notes
Provenance includes: - Source file paths - Processing steps (transformations, analyses) - Software versions - Timestamps - Parameters used for each operation
Source code in src/lacuna/io/export.py
export_results_to_csv(mask_data, output_path, analysis_name=None, include_metadata=True)
¶
Export analysis results to CSV format.
Converts nested results dictionary to a flat CSV structure suitable for statistical analysis or visualization in external tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data
|
SubjectData
|
SubjectData object with analysis results |
required |
output_path
|
str or Path
|
Output CSV file path |
required |
analysis_name
|
str
|
Specific analysis to export. If None, exports all results. Example: "RegionalDamage", "ParcelAggregation" |
None
|
include_metadata
|
bool
|
Include subject metadata (subject_id, session_id, etc.) as columns |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created CSV file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mask_data has no results or specified analysis not found |
Examples:
>>> from lacuna import SubjectData
>>> from lacuna.analysis import RegionalDamage
>>> from lacuna.io import export_results_to_csv
>>>
>>> lesion = SubjectData.from_nifti("lesion.nii.gz")
>>> analysis = RegionalDamage()
>>> result = analysis.run(lesion)
>>>
>>> # Export all results
>>> export_results_to_csv(result, "results.csv")
>>>
>>> # Export specific analysis
>>> export_results_to_csv(result, "damage.csv", analysis_name="RegionalDamage")
Notes
- Results are flattened: nested dicts become columns with dot notation
- Example: {"ParcelAggregation": {"region1": 0.5}} becomes columns "ParcelAggregation.region1" with value 0.5
- Multiple analyses create multiple columns
- Metadata columns (if included): subject_id, session_id, coordinate_space
Source code in src/lacuna/io/export.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
export_results_to_json(mask_data, output_path, analysis_name=None, include_metadata=True, include_provenance=False, indent=2)
¶
Export analysis results to JSON format.
Creates a JSON file with analysis results, optionally including metadata and provenance. Useful for web applications or further programmatic processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data
|
SubjectData
|
SubjectData object with analysis results |
required |
output_path
|
str or Path
|
Output JSON file path |
required |
analysis_name
|
str
|
Specific analysis to export. If None, exports all results. |
None
|
include_metadata
|
bool
|
Include subject metadata in JSON |
True
|
include_provenance
|
bool
|
Include provenance data in JSON |
False
|
indent
|
int
|
JSON indentation for readability (0 for compact) |
2
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created JSON file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mask_data has no results or specified analysis not found |
Examples:
>>> from lacuna.io import export_results_to_json
>>>
>>> # Export all results with metadata
>>> export_results_to_json(result, "results.json")
>>>
>>> # Export specific analysis with full provenance
>>> export_results_to_json(
... result,
... "damage_full.json",
... analysis_name="RegionalDamage",
... include_provenance=True
... )
>>>
>>> # Compact JSON for web APIs
>>> export_results_to_json(result, "api_response.json", indent=0)
Notes
JSON structure: { "metadata": {...}, # If include_metadata=True "results": {...}, # Analysis results "provenance": {...} # If include_provenance=True }
Source code in src/lacuna/io/export.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
export_results_to_tsv(mask_data, output_path, analysis_name=None, include_metadata=True)
¶
Export analysis results to TSV (tab-separated values) format.
Identical to export_results_to_csv but uses tab delimiter. TSV is preferred in neuroimaging for BIDS compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data
|
SubjectData
|
SubjectData object with analysis results |
required |
output_path
|
str or Path
|
Output TSV file path |
required |
analysis_name
|
str
|
Specific analysis to export. If None, exports all results. |
None
|
include_metadata
|
bool
|
Include subject metadata as columns |
True
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created TSV file |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mask_data has no results or specified analysis not found |
Examples:
>>> from lacuna.io import export_results_to_tsv
>>>
>>> # Export to TSV (BIDS-compatible format)
>>> export_results_to_tsv(result, "results.tsv")
>>>
>>> # Export specific analysis without metadata
>>> export_results_to_tsv(
... result,
... "atlas_only.tsv",
... analysis_name="ParcelAggregation",
... include_metadata=False
... )
See Also
export_results_to_csv : CSV export (identical but comma-delimited)
Source code in src/lacuna/io/export.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
fetch_connectome(name, output_dir, **kwargs)
¶
Generic fetch function that dispatches to specific connectome fetchers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Connectome name ('gsp1000', 'dtor985'). |
required |
output_dir
|
str or Path
|
Directory for output files. |
required |
**kwargs
|
Additional arguments passed to specific fetch function. |
{}
|
Returns:
| Type | Description |
|---|---|
FetchResult
|
Result from the specific fetch operation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If connectome name is not recognized. |
Examples:
>>> from lacuna.io import fetch_connectome
>>> result = fetch_connectome("gsp1000", "/data", api_key="key", batches=50)
Source code in src/lacuna/io/fetch.py
fetch_dtor985(output_dir, *, api_key=None, keep_original=True, register=True, register_name='dTOR985', force=False, progress_callback=None, verbose=False)
¶
Download, convert, and register the dTOR985 structural tractogram.
Downloads the Diffusion Tensor Imaging Open Resource 985-subject tractogram from Figshare in TrackVis (.trk) format, converts to MRtrix3 (.tck) format, and optionally registers for use with StructuralNetworkMapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str or Path
|
Directory for output .tck file. |
required |
api_key
|
str
|
Figshare API key for authenticated downloads. If not provided, uses FIGSHARE_API_KEY environment variable. Get one from https://figshare.com/account/applications. |
None
|
keep_original
|
bool
|
Keep original .trk file after conversion. |
True
|
register
|
bool
|
Automatically register tractogram after processing. |
True
|
register_name
|
str
|
Name for tractogram registration. |
"dTOR985"
|
force
|
bool
|
Overwrite existing files and registrations. |
False
|
progress_callback
|
callable
|
Function called with FetchProgress updates during operation. |
None
|
verbose
|
bool
|
Print informational messages. |
False
|
Returns:
| Type | Description |
|---|---|
FetchResult
|
Result containing output path, registration status, and timing. |
Raises:
| Type | Description |
|---|---|
DownloadError
|
If download fails or API key is missing. |
ProcessingError
|
If .trk to .tck conversion fails. |
Examples:
>>> from lacuna.io import fetch_dtor985
>>> result = fetch_dtor985("/data/connectomes/dtor985", api_key="YOUR_TOKEN")
>>> print(result.output_files[0]) # Path to .tck file
Source code in src/lacuna/io/fetch.py
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | |
fetch_gsp1000(output_dir, *, api_key=None, batches=10, test_mode=False, skip_checksum=False, register=True, register_name='GSP1000', force=False, progress_callback=None, verbose=False)
¶
Download, process, and register the GSP1000 functional connectome.
Downloads the Brain Genomics Superstruct Project 1000-subject resting-state fMRI dataset from Harvard Dataverse, converts to HDF5 batch format, and optionally registers for use with FunctionalNetworkMapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str or Path
|
Directory for output HDF5 batch files. |
required |
api_key
|
str
|
Harvard Dataverse API key. If not provided, looks for DATAVERSE_API_KEY environment variable. |
None
|
batches
|
int
|
Number of HDF5 batch files to create. More batches = lower RAM usage. Recommendations: 4GB RAM → 100, 8GB → 50, 16GB → 25, 32GB+ → 10. |
10
|
test_mode
|
bool
|
If True, downloads only 1 tarball (~2GB) to test the full pipeline. |
False
|
skip_checksum
|
bool
|
Skip checksum verification. Use when Dataverse metadata is outdated. |
False
|
register
|
bool
|
Automatically register connectome after processing. |
True
|
register_name
|
str
|
Name for connectome registration. |
"GSP1000"
|
force
|
bool
|
Overwrite existing files and registrations. |
False
|
progress_callback
|
callable
|
Function called with FetchProgress updates during operation. |
None
|
verbose
|
bool
|
Print informational messages. |
False
|
Returns:
| Type | Description |
|---|---|
FetchResult
|
Result containing output paths, registration status, and timing. |
Raises:
| Type | Description |
|---|---|
AuthenticationError
|
If API key is missing or invalid. |
DownloadError
|
If download fails after retries. |
ProcessingError
|
If NIfTI to HDF5 conversion fails. |
Examples:
>>> from lacuna.io import fetch_gsp1000
>>> result = fetch_gsp1000(
... output_dir="/data/connectomes/gsp1000",
... api_key="your-dataverse-api-key",
... batches=50
... )
>>> print(result.summary())
Source code in src/lacuna/io/fetch.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
fetch_hcp1065(output_dir, *, keep_original=True, register=True, register_name='HCP1065', force=False, progress_callback=None, verbose=False)
¶
Download, merge, and register the HCP1065 structural tractogram.
Downloads the Human Connectome Project 1065-subject averaged tractography atlas from GitHub Releases as a zip of TrackVis (.trk) files, merges all tract files (excluding cranial nerves) into a single MRtrix3 (.tck) file, and optionally registers for use with StructuralNetworkMapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str or Path
|
Directory for output .tck file. |
required |
keep_original
|
bool
|
Keep original .zip file and extracted tracts after merging. |
True
|
register
|
bool
|
Automatically register tractogram after processing. |
True
|
register_name
|
str
|
Name for tractogram registration. |
"HCP1065"
|
force
|
bool
|
Overwrite existing files and registrations. |
False
|
progress_callback
|
callable
|
Function called with FetchProgress updates during operation. |
None
|
verbose
|
bool
|
Print informational messages. |
False
|
Returns:
| Type | Description |
|---|---|
FetchResult
|
Result containing output path, registration status, and timing. |
Raises:
| Type | Description |
|---|---|
DownloadError
|
If download fails. |
ProcessingError
|
If extraction or merging fails. |
Examples:
>>> from lacuna.io import fetch_hcp1065
>>> result = fetch_hcp1065("/data/connectomes/hcp1065")
>>> print(result.output_files[0]) # Path to .tck file
Source code in src/lacuna/io/fetch.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 | |
get_connectome_path(name_or_path)
¶
Resolve a connectome name or path to its file location.
For registered connectomes, looks up path in registry. For paths, validates existence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_or_path
|
str
|
Either a registered connectome name (e.g., "GSP1000") or a direct path to .h5 file or directory. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Resolved path to connectome data. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If connectome cannot be resolved. |
Examples:
>>> path = get_connectome_path("GSP1000") # Registered name
>>> path = get_connectome_path("/data/my_connectome.h5") # Direct path
Source code in src/lacuna/io/fetch.py
get_data_dir()
¶
Get the data cache directory following XDG Base Directory specification.
Priority: 1. LACUNA_DATA_DIR environment variable (explicit user choice) 2. XDG_CACHE_HOME/lacuna (XDG standard) 3. ~/.cache/lacuna (fallback)
Returns:
| Type | Description |
|---|---|
Path
|
Absolute path to data cache directory |
Examples:
>>> import os
>>> os.environ['LACUNA_DATA_DIR'] = '/mnt/nvme/lacuna_data'
>>> data_dir = get_data_dir()
>>> print(data_dir)
PosixPath('/mnt/nvme/lacuna_data')
Source code in src/lacuna/io/fetch.py
get_fetch_status(name)
¶
Get the current status of a connectome (downloaded, processed, registered).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Connectome name ('gsp1000', 'dtor985'). |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Status information including: - downloaded: bool - processed: bool - registered: bool - location: Path | None - size_bytes: int | None |
Source code in src/lacuna/io/fetch.py
gsp1000_to_hdf5(gsp_dir, mask_path, output_dir, subjects_per_chunk=10, *, max_subjects=None, overwrite=False)
¶
Convert GSP1000 functional data to Lacuna-compatible HDF5 chunks.
Scans a directory of functional NIfTI files from the GSP1000 dataset, extracts time-series from within a brain mask, and saves the data into multiple smaller HDF5 chunk files for efficient analysis.
Expected GSP1000 directory structure: gsp_dir/ └── sub-/ └── func/ └── bld001_rest_*_finalmask.nii.gz
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gsp_dir
|
str | Path
|
Path to the GSP1000 dataset directory |
required |
mask_path
|
str | Path
|
Path to MNI152 brain mask (.nii.gz) |
required |
output_dir
|
str | Path
|
Directory where chunk HDF5 files will be saved |
required |
subjects_per_chunk
|
int
|
Number of subjects to include in each chunk file |
10
|
max_subjects
|
int
|
Maximum number of subjects to process. If set, only the first
|
None
|
overwrite
|
bool
|
Whether to overwrite existing chunk files |
False
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
List of created chunk file paths |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If GSP directory or mask file not found |
ValueError
|
If no matching NIfTI files found in GSP directory |
Examples:
>>> chunk_files = gsp1000_to_hdf5(
... gsp_dir="/data/GSP1000",
... mask_path="/data/templates/MNI152_T1_2mm_Brain_Mask.nii.gz",
... output_dir="/data/connectomes/gsp1000_chunks",
... subjects_per_chunk=10
... )
>>> print(f"Created {len(chunk_files)} chunk files")
Notes
- Each chunk file is self-contained with all necessary metadata
- Timeseries are NOT preprocessed (demeaning, variance normalization) to preserve raw data - preprocessing happens during analysis
- HDF5 files use chunking (1, n_timepoints, n_voxels) for efficient subject-wise access
Source code in src/lacuna/io/convert.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
list_fetchable_connectomes()
¶
List all connectomes available for fetching.
Returns:
| Type | Description |
|---|---|
list of ConnectomeSource
|
Available connectome sources with metadata. |
Examples:
>>> from lacuna.io import list_fetchable_connectomes
>>> for source in list_fetchable_connectomes():
... print(f"{source.name}: {source.display_name}")
Source code in src/lacuna/io/fetch.py
load_bids_dataset(bids_root, pattern='*', suffix='_mask.nii.gz', recursive=True, space=None, resolution=None, subjects=None)
¶
Load mask files from a BIDS dataset using pattern matching.
This function finds all files matching the pattern and suffix in the BIDS dataset structure and loads them as SubjectData objects. No external BIDS validation library (pybids) is required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bids_root
|
str or Path
|
Path to BIDS dataset root directory (or any directory containing masks). |
required |
pattern
|
str
|
Glob/fnmatch pattern to filter files. Matched against the full filename (without path). Examples: - "" : All mask files - "CAS001" : All masks for subject CAS001 - "ses-01" : All session 01 masks - "acuteinfarct" : All acute infarct masks - "CAS001ses-01acuteinfarct" : Specific subject, session, and label |
"*"
|
suffix
|
str
|
File suffix to search for. Common options: - "_mask.nii.gz" : Standard BIDS mask suffix - "_mask.nii" : Uncompressed masks - ".nii.gz" : Any NIfTI file |
"_mask.nii.gz"
|
recursive
|
bool
|
If True, search recursively in subdirectories. |
True
|
space
|
str or None
|
Coordinate space for loaded masks. If None, attempts to detect from filename (_space-XXX) or sidecar JSON. If detection fails and space is not provided, a warning is emitted and the file is skipped. Supported spaces: MNI152NLin6Asym, MNI152NLin2009cAsym |
None
|
resolution
|
float or None
|
Voxel resolution in mm. If None, attempts to detect from filename (_res-X) or sidecar JSON. |
None
|
subjects
|
list of str
|
List of subject IDs to include (without 'sub-' prefix). If provided, only files from these subjects will be loaded. This is more efficient than loading all subjects and filtering afterward. |
None
|
Returns:
| Type | Description |
|---|---|
dict of str -> SubjectData
|
Dictionary mapping filenames (without suffix) to SubjectData objects. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If bids_root doesn't exist. |
BidsError
|
If no matching files are found. |
Examples:
Load all masks in a BIDS dataset:
>>> dataset = load_bids_dataset('/data/METAVCI_PSCI_BIDS')
>>> print(f"Loaded {len(dataset)} masks")
Load specific subject:
Load specific session and label:
>>> dataset = load_bids_dataset(
... '/data/METAVCI_PSCI_BIDS',
... pattern="CAS001*ses-01*acuteinfarct"
... )
Load from a specific subject's anat folder:
>>> dataset = load_bids_dataset(
... '/data/METAVCI_PSCI_BIDS/sub-CAS001/ses-01/anat',
... pattern="*WMH*"
... )
Load all WMH masks across all subjects:
Load masks with explicit space (when not in filename):
>>> dataset = load_bids_dataset(
... '/data/METAVCI_PSCI_BIDS',
... pattern="*CAS005*",
... space="MNI152NLin6Asym",
... resolution=2.0
... )
Source code in src/lacuna/io/bids.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
merge_trk_to_tck(source_dir, output_path, *, exclude_patterns=None, overwrite=False)
¶
Merge multiple TrackVis .trk/.trk.gz tractograms into a single MRtrix3 .tck file.
Recursively finds all .trk and .trk.gz files in the source directory, loads their streamlines (excluding files matching specified patterns), and saves them as a single merged .tck tractogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_dir
|
str | Path
|
Directory containing .trk/.trk.gz tract files (searched recursively). |
required |
output_path
|
str | Path
|
Output path for the merged .tck file. |
required |
exclude_patterns
|
list[str]
|
List of patterns to match against file paths for exclusion.
Files whose path contains any of these strings (case-insensitive)
are skipped. Default: |
None
|
overwrite
|
bool
|
Whether to overwrite an existing output file. |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the created .tck file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If source directory not found. |
ValueError
|
If no .trk/.trk.gz files found or output is not .tck format. |
RuntimeError
|
If merging fails. |
Examples:
>>> tck_path = merge_trk_to_tck(
... source_dir="/data/hcp1065_tracts",
... output_path="/data/hcp1065.tck",
... )
Source code in src/lacuna/io/convert.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
save_nifti(mask_data, output_path, save_anatomical=False)
¶
Save lesion mask to NIfTI file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_data
|
SubjectData
|
Lesion data to save. |
required |
output_path
|
str or Path
|
Path for output NIfTI file (e.g., 'lesion.nii.gz'). |
required |
save_anatomical
|
bool
|
Also save anatomical image (if present) to adjacent file. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If output_path doesn't have .nii or .nii.gz extension. |
Examples:
>>> save_nifti(mask_data, 'output/lesion.nii.gz')
>>> save_nifti(mask_data, 'output/lesion.nii.gz', save_anatomical=True)
Source code in src/lacuna/io/bids.py
trk_to_tck(trk_path, output_path, *, overwrite=False)
¶
Convert TrackVis .trk tractogram to MRtrix3 .tck format using nibabel.
This conversion is necessary because StructuralNetworkMapping uses MRtrix3 tools (tckedit, tckmap, mrcalc) which require .tck format. The default dTOR985 tractogram is distributed in .trk format.
Uses nibabel's streamlines module for pure Python conversion without requiring MRtrix3 to be installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trk_path
|
str | Path
|
Path to input TrackVis .trk file (e.g., dTOR985.trk) |
required |
output_path
|
str | Path
|
Output path for MRtrix3 .tck file |
required |
overwrite
|
bool
|
Whether to overwrite existing output file |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to created .tck file |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If trk file not found |
ValueError
|
If input is not .trk or output is not .tck format |
RuntimeError
|
If conversion fails |
Examples:
>>> # Convert dTOR985 tractogram
>>> tck_path = trk_to_tck(
... trk_path="/data/dTOR985.trk",
... output_path="/data/dTOR985.tck"
... )
>>>
>>> # Later use in analysis:
>>> analysis = StructuralNetworkMapping(tractogram_path="/data/dTOR985.tck")
Notes
- Uses nibabel for pure Python conversion (no external dependencies)
- Preserves streamline coordinates and header information
- The .tck file can be much larger than .trk due to format differences
- For dTOR985: expect ~5-10GB .tck file from ~2GB .trk file
See Also
nibabel.streamlines: https://nipy.org/nibabel/reference/nibabel.streamlines.html
Source code in src/lacuna/io/convert.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 | |
validate_bids_derivatives(derivatives_dir, raise_on_error=True)
¶
Validate BIDS derivatives directory structure.
Checks that a derivatives directory follows BIDS specifications: - Has dataset_description.json - SubjectData directories follow naming conventions - Files follow BIDS naming patterns - Required metadata is present
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
derivatives_dir
|
str or Path
|
Path to derivatives directory (e.g., 'derivatives/lacuna-v0.1.0') |
required |
raise_on_error
|
bool
|
If True, raises BidsError on validation failure. If False, returns errors as list. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
Dictionary with validation results: - 'errors': List of error messages (MUST fix) - 'warnings': List of warning messages (SHOULD fix) Empty lists indicate passing validation. |
Raises:
| Type | Description |
|---|---|
BidsError
|
If validation fails and raise_on_error=True |
FileNotFoundError
|
If derivatives_dir doesn't exist |
Examples:
>>> from lacuna.io import validate_bids_derivatives
>>>
>>> # Validate after export
>>> validate_bids_derivatives('derivatives/lacuna-v0.1.0')
{'errors': [], 'warnings': []}
>>>
>>> # Check without raising exceptions
>>> result = validate_bids_derivatives('derivatives/lacuna-v0.1.0', raise_on_error=False)
>>> if result['errors']:
... print(f"Found {len(result['errors'])} errors")
Notes
Validation checks: - dataset_description.json exists and is valid JSON - Contains required fields: Name, BIDSVersion, GeneratedBy - SubjectData directories match pattern: sub-
Source code in src/lacuna/io/bids.py
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 | |