core
lacuna.core
¶
Core data structures and utilities for the lesion decoding toolkit.
AnalysisError
¶
Bases: LacunaError, RuntimeError
Raised when analysis computation fails.
BIDSValidationError
¶
Bases: LacunaError, ValueError
Raised when BIDS dataset structure is invalid.
ConnectivityMatrix
dataclass
¶
Bases: DataContainer
Result container for connectivity matrices.
Stores a single connectivity matrix with optional region labels.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
matrix |
ndarray
|
Connectivity matrix (N x N) |
region_labels |
list of str, optional
|
Labels for matrix rows/columns |
matrix_type |
(str, optional)
|
Type of connectivity ("structural", "functional") |
metadata |
dict
|
Additional metadata about the output |
Examples:
>>> import numpy as np
>>> # Create a structural connectivity matrix
>>> conn_matrix = np.array([
... [1.0, 0.8, 0.3],
... [0.8, 1.0, 0.5],
... [0.3, 0.5, 1.0]
... ])
>>> conn = ConnectivityMatrix(
... name="structural_connectivity",
... matrix=conn_matrix,
... region_labels=["V1", "V2", "MT"],
... matrix_type="structural"
... )
>>> print(conn.summary())
structural_connectivity: 3x3, type=structural
Source code in src/lacuna/core/data_types.py
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 | |
__post_init__()
¶
Initialize and validate matrix.
Source code in src/lacuna/core/data_types.py
__repr__()
¶
Return string representation.
get_data()
¶
summary()
¶
Get a summary description of this result.
CoordinateSpaceError
¶
Bases: LacunaError, ValueError
Raised when operations require specific coordinate space.
DataContainer
¶
Bases: ABC
Abstract base class for unified data type containers.
This is the base class for all data container types. It provides common functionality for metadata management and a consistent interface for accessing data.
Subclasses implement specific data types: - VoxelMap: For 3D/4D brain maps (functional connectivity, disconnection) - ParcelData: For region-level aggregated data (atlas-based analysis) - ConnectivityMatrix: For connectivity matrices - SurfaceMesh: For surface-based data (vertices, faces) - Tractogram: For tractography streamlines - ScalarMetric: For summary statistics, scalars, and other data
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this data container (e.g., "rmap", "zmap") |
metadata |
dict
|
Additional metadata about the data |
data_type |
str
|
Type identifier for the container (set by subclasses) |
Examples:
Subclasses are used to store analysis results:
>>> # VoxelMap for brain maps
>>> voxel_result = VoxelMap(
... name="rmap",
... data=nifti_img,
... space="MNI152NLin6Asym",
... resolution=2.0
... )
>>> print(voxel_result.summary())
>>> # ParcelData for region-level data
>>> parcel_result = ParcelData(
... name="damage_scores",
... data={"V1": 0.8, "V2": 0.6},
... aggregation_method="mean"
... )
>>> top_regions = parcel_result.get_top_regions(n=5)
Source code in src/lacuna/core/data_types.py
__init__(name, metadata=None)
¶
Initialize base data container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name/identifier for this container |
required |
metadata
|
dict
|
Additional metadata about the data |
None
|
Source code in src/lacuna/core/data_types.py
__repr__()
¶
get_data(**kwargs)
abstractmethod
¶
Get the primary data from this result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Subclass-specific options for data retrieval |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The primary data (type depends on subclass) |
Source code in src/lacuna/core/data_types.py
summary()
abstractmethod
¶
Get a summary description of this result.
Returns:
| Type | Description |
|---|---|
str
|
Human-readable summary |
EmptyMaskError
¶
Bases: ValidationError
Raised when a mask contains no non-zero voxels.
Source code in src/lacuna/core/exceptions.py
LacunaError
¶
NiftiLoadError
¶
Bases: LacunaError, IOError
Raised when NIfTI file loading fails.
ParcelData
dataclass
¶
Bases: DataContainer
Result container for atlas-based region aggregation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
data |
dict
|
Dictionary mapping ROI identifiers to values |
region_labels |
list of str, optional
|
Ordered list of region label names (from atlas metadata) |
parcel_names |
list of str, optional
|
Names of atlases used in the analysis |
aggregation_method |
(str, optional)
|
Method used for aggregation (e.g., "mean", "percent") |
metadata |
dict
|
Additional metadata about the output |
Examples:
>>> # Create parcel data from atlas-based analysis
>>> parcel_data = ParcelData(
... name="damage_scores",
... data={
... "Visual_V1": 0.85,
... "Motor_Primary": 0.42,
... "Prefrontal_DLPFC": 0.15
... },
... parcel_names=["Schaefer100"],
... aggregation_method="percent"
... )
>>> # Get top damaged regions
>>> top = parcel_data.get_top_regions(n=2)
>>> print(top)
{'Visual_V1': 0.85, 'Motor_Primary': 0.42}
Source code in src/lacuna/core/data_types.py
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 | |
__post_init__()
¶
__repr__()
¶
Return string representation.
get_data(atlas_filter=None)
¶
Get ROI data, optionally filtered by atlas name.
Source code in src/lacuna/core/data_types.py
get_top_regions(n=10, ascending=False)
¶
Get top N regions by value.
summary()
¶
Get a summary description of this result.
Source code in src/lacuna/core/data_types.py
Pipeline
¶
Declarative analysis workflow definition.
Pipeline allows defining a sequence of analyses that will be run in order on each subject. It supports batch processing with configurable parallelization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable name for the pipeline |
None
|
description
|
str
|
Description of what the pipeline does |
None
|
Examples:
>>> from lacuna.analysis import RegionalDamage, FunctionalNetworkMapping, ParcelAggregation
>>> from lacuna import Pipeline
>>> # Define pipeline
>>> pipeline = Pipeline(name="Standard Lesion Analysis")
>>> pipeline.add(RegionalDamage())
>>> pipeline.add(FunctionalNetworkMapping())
>>> pipeline.add(ParcelAggregation(parc_names=["Schaefer100"]))
>>> # Get workflow description
>>> print(pipeline.describe())
Pipeline: Standard Lesion Analysis
Steps:
1. RegionalDamage
2. FunctionalNetworkMapping (atlas=schaefer100)
3. ParcelAggregation (parc_names=['Schaefer100'])
Source code in src/lacuna/core/pipeline.py
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 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 | |
__len__()
¶
add(analysis, name=None)
¶
Add an analysis step to the pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analysis
|
BaseAnalysis
|
The analysis module to add |
required |
name
|
str
|
Human-readable name for this step |
None
|
Returns:
| Type | Description |
|---|---|
Pipeline
|
Self for method chaining |
Source code in src/lacuna/core/pipeline.py
describe()
¶
Get a human-readable description of the pipeline.
Returns:
| Type | Description |
|---|---|
str
|
Multi-line description of the pipeline |
Source code in src/lacuna/core/pipeline.py
run(data, verbose=False)
¶
Run the pipeline on a single subject.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
SubjectData
|
Input data to process |
required |
verbose
|
bool
|
If True, print progress messages. If False, run silently. |
False
|
Returns:
| Type | Description |
|---|---|
SubjectData
|
Processed data with all analysis results |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a SubjectData instance |
Source code in src/lacuna/core/pipeline.py
run_batch(data_list, n_jobs=-1, show_progress=True, parallel=True)
¶
Run the pipeline on multiple subjects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_list
|
list of SubjectData
|
List of subjects to process |
required |
n_jobs
|
int
|
Number of parallel jobs (-1 uses all CPUs) |
-1
|
show_progress
|
bool
|
Show progress bar |
True
|
parallel
|
bool
|
Whether to process subjects in parallel |
True
|
Returns:
| Type | Description |
|---|---|
list of SubjectData or ParcelData
|
Processed data for each subject |
Source code in src/lacuna/core/pipeline.py
ProvenanceError
¶
Bases: LacunaError, RuntimeError
Raised when provenance tracking encounters issues.
ScalarMetric
dataclass
¶
Bases: DataContainer
Result container for miscellaneous data.
This class handles summary statistics, scalar values, metadata, and any other data that doesn't fit into specific result types.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
data |
Any
|
The data (can be scalar, dict, list, etc.) |
data_type |
(str, optional)
|
Type description (e.g., "scalar", "summary_stats", "metadata") |
metadata |
dict
|
Additional metadata about the output |
Source code in src/lacuna/core/data_types.py
__post_init__()
¶
Initialize base class and infer data_type if needed.
Source code in src/lacuna/core/data_types.py
__repr__()
¶
get_data()
¶
summary()
¶
Get a summary description of this result.
Source code in src/lacuna/core/data_types.py
SpatialMismatchError
¶
Bases: ValidationError
Raised when spatial properties (affine, shape) don't match.
SubjectData
¶
Central data container for a single research participant's mask-based analysis.
This class encapsulates binary mask image data, spatial metadata, subject identifiers, processing provenance, and analysis results. It enforces immutability-by-convention: transformations should return new instances rather than modifying in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_img
|
Nifti1Image
|
Binary mask (3D only, values must be 0 or 1). |
required |
space
|
str
|
Coordinate space identifier (e.g., 'MNI152NLin6Asym'). If not provided, must be in metadata dict. |
None
|
resolution
|
float
|
Spatial resolution in millimeters (e.g., 1.0, 2.0). If not provided, must be in metadata dict. |
None
|
metadata
|
dict
|
Additional subject metadata (e.g., session info, patient ID). 'subject_id' defaults to "sub-unknown" if not provided. Note: Direct kwargs (space, resolution) override metadata dict values. |
None
|
provenance
|
list of dict
|
Processing history (for deserialization only). |
None
|
results
|
dict
|
Analysis results (for deserialization only). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If space or resolution is not provided (via kwargs or metadata dict), if mask_img is not 3D, or if mask_img is not binary (0/1 values only). |
Attributes:
| Name | Type | Description |
|---|---|---|
mask_img |
Nifti1Image
|
The binary mask image (read-only). |
affine |
ndarray
|
4x4 affine transformation matrix (read-only). |
space |
str
|
Coordinate space identifier (e.g., 'MNI152NLin6Asym'). |
resolution |
float
|
Spatial resolution in millimeters. |
metadata |
ImmutableDict
|
SubjectData and session metadata (read-only view). |
provenance |
list
|
Processing history (read-only view). |
results |
dict
|
Analysis results (read-only view, nested structure). |
Examples:
Recommended: Direct kwargs for space and resolution¶
>>> mask_data = SubjectData(
... mask_img,
... space="MNI152NLin6Asym",
... resolution=2,
... metadata={"subject_id": "sub-001"}
... )
>>> print(f"Volume: {mask_data.get_volume_mm3()} mm³")
>>> print(f"Space: {mask_data.space}")
>>> print(f"Resolution: {mask_data.resolution}mm")
Source code in src/lacuna/core/subject_data.py
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 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 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 494 495 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 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 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 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 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 | |
affine
property
¶
4x4 affine transformation matrix (voxel to world).
is_empty_mask
property
¶
Whether the mask contains no non-zero voxels.
mask_img
property
¶
Binary mask image.
metadata
property
¶
SubjectData and session metadata (read-only view).
Returns an immutable dictionary that prevents modifications with clear error messages. To update metadata, create a new SubjectData instance with the desired metadata.
Returns:
| Type | Description |
|---|---|
ImmutableDict
|
Read-only view of metadata. Raises TypeError on modification attempts. |
Examples:
provenance
property
¶
Processing history (immutable view).
resolution
property
¶
results
property
¶
Analysis results (immutable view).
Returns dict mapping analysis namespace to result dict. Result dict maps result names to result objects.
Access pattern: results['AnalysisName']['result_name']
space
property
¶
__getattr__(name)
¶
Enable attribute-based access to analysis results.
Allows accessing results via mask_data.AnalysisName instead of
mask_data.results['AnalysisName'].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Analysis namespace (e.g., "ParcelAggregation", "RegionalDamage") |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Result dictionary for the requested analysis |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If the attribute doesn't exist in results |
Examples:
>>> # After running ParcelAggregation:
>>> mask_data.ParcelAggregation["Schaefer100"]
ParcelData(...)
>>> # Equivalent to:
>>> mask_data.results["ParcelAggregation"]["Schaefer100"]
ParcelData(...)
Source code in src/lacuna/core/subject_data.py
add_provenance(record)
¶
Create new SubjectData with additional provenance record.
This method follows immutability-by-convention: it returns a new instance with the updated provenance history rather than modifying the current instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
dict
|
Provenance record (from create_provenance_record() or compatible dict). Must contain 'function', 'parameters', 'timestamp', and 'version' keys. |
required |
Returns:
| Type | Description |
|---|---|
SubjectData
|
New instance with appended provenance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If record is missing required fields. |
Examples:
>>> from lacuna.core.provenance import create_provenance_record
>>> prov = create_provenance_record(
... function="lacuna.analysis.RegionalDamage",
... version="0.1.0"
... )
>>> result = mask_data.add_provenance(prov)
>>> len(result.provenance) == len(mask_data.provenance) + 1
True
Source code in src/lacuna/core/subject_data.py
add_result(namespace, results)
¶
Create new SubjectData with additional analysis results.
This method follows immutability-by-convention: it returns a new instance with the updated results rather than modifying the current instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Result namespace (e.g., 'FunctionalNetworkMapping', 'ParcelAggregation'). Should match the analysis module name for clarity. |
required |
results
|
dict[str, Any]
|
Analysis results as a dict mapping result names to result objects. For single result: {"result_name": result_object} For multiple results (e.g., multi-atlas): {"Schaefer100": roi_result1, "Tian": roi_result2} |
required |
Returns:
| Type | Description |
|---|---|
SubjectData
|
New instance with added results. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If namespace already exists in results. |
Examples:
>>> # Single result
>>> results = {"default": VoxelMapResult(...)}
>>> lesion_with_results = lesion.add_result("VolumeAnalysis", results)
>>> "VolumeAnalysis" in lesion_with_results.results
True
>>>
>>> # Multi-atlas results
>>> results = {"Schaefer100": roi_result1, "Tian": roi_result2}
>>> lesion_with_results = lesion.add_result("ParcelAggregation", results)
>>> lesion_with_results.results["ParcelAggregation"]["Schaefer100"]
ParcelData(...)
Source code in src/lacuna/core/subject_data.py
copy()
¶
Create a deep copy of this SubjectData instance.
Returns:
| Type | Description |
|---|---|
SubjectData
|
Independent copy with same data. |
Examples:
Source code in src/lacuna/core/subject_data.py
from_dict(data, mask_img)
classmethod
¶
Deserialize from dictionary + NIfTI image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Output from to_dict(). |
required |
mask_img
|
Nifti1Image
|
Mask image (loaded separately). |
required |
Returns:
| Type | Description |
|---|---|
SubjectData
|
Reconstructed object. |
Examples:
>>> data = mask_data.to_dict()
>>> mask_img = nib.load("mask.nii.gz")
>>> mask_restored = SubjectData.from_dict(data, mask_img)
Source code in src/lacuna/core/subject_data.py
from_nifti(mask_path, space=None, resolution=None, metadata=None)
classmethod
¶
Load mask data from NIfTI file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_path
|
str or Path
|
Path to mask NIfTI file. |
required |
space
|
str
|
Coordinate space identifier (e.g., 'MNI152NLin6Asym'). If not provided, will attempt auto-detection from image header/filename. |
None
|
resolution
|
float
|
Spatial resolution in millimeters (e.g., 1.0, 2.0). If not provided, will attempt auto-detection from image header/filename. |
None
|
metadata
|
dict
|
Additional subject metadata (e.g., session info). 'subject_id' auto-generated from filename if not provided. |
None
|
Returns:
| Type | Description |
|---|---|
SubjectData
|
Loaded mask data object. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file path doesn't exist. |
NiftiLoadError
|
If image fails to load or validate. |
ValueError
|
If 'space' or 'resolution' cannot be determined. |
Examples:
>>> mask_data = SubjectData.from_nifti(
... "mask.nii.gz",
... space="MNI152NLin6Asym",
... resolution=2.0
... )
>>> mask_data = SubjectData.from_nifti(
... "mask.nii.gz",
... space="MNI152NLin6Asym",
... resolution=2.0,
... metadata={"subject_id": "sub-001", "session": "baseline"}
... )
Source code in src/lacuna/core/subject_data.py
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 494 495 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 | |
get_coordinate_space()
¶
Get current coordinate space from metadata.
Returns:
| Type | Description |
|---|---|
str
|
Coordinate space identifier (e.g., 'MNI152NLin6Asym'). |
Examples:
Source code in src/lacuna/core/subject_data.py
get_result(analysis, pattern=None, unwrap=True)
¶
Get result by analysis name with optional glob pattern filtering.
This method provides a convenient way to access results using glob patterns for flexible filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
analysis
|
str
|
Analysis namespace (e.g., "ParcelAggregation", "FunctionalNetworkMapping"). |
required |
pattern
|
str
|
Glob pattern to match result keys (e.g., "rmap",
"atlas-Schaefer*"). Supports fnmatch-style wildcards:
- |
None
|
unwrap
|
bool
|
If True, call |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If analysis namespace not found, or if no results match pattern. |
Examples:
>>> # Get by glob pattern
>>> z_map = subject.get_result("FunctionalNetworkMapping", pattern="*zmap*")
>>> # Get unwrapped data directly (nibabel image instead of VoxelMap)
>>> corr_img = subject.get_result(
... "FunctionalNetworkMapping", pattern="*rmap*", unwrap=True
... )
>>> corr_img.shape # Access numpy array directly
(91, 109, 91)
See Also
results : Property for accessing all results. lacuna.core.keys.build_result_key : Build key from components. lacuna.core.keys.parse_result_key : Parse key into components.
Source code in src/lacuna/core/subject_data.py
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 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 | |
get_volume_mm3()
¶
Calculate mask volume in cubic millimeters.
Returns:
| Type | Description |
|---|---|
float
|
Total mask volume (sum of non-zero voxels * voxel volume). |
Examples:
Source code in src/lacuna/core/subject_data.py
to_dict()
¶
Serialize to JSON-compatible dictionary (excludes image data).
Returns:
| Type | Description |
|---|---|
dict
|
Metadata, provenance, and results (no NIfTI arrays). |
Examples:
Source code in src/lacuna/core/subject_data.py
validate()
¶
Validate data integrity.
Checks that affine is invertible, image is 3D, and spatial properties are consistent.
Returns:
| Type | Description |
|---|---|
bool
|
True if all checks pass. |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If mask is empty or has suspicious properties. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If critical invariants violated. |
Examples:
Source code in src/lacuna/core/subject_data.py
SurfaceMesh
dataclass
¶
Bases: DataContainer
Result container for surface-based data.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
vertices |
ndarray
|
Vertex coordinates (N x 3) |
faces |
ndarray
|
Triangle faces (M x 3, indices into vertices) |
vertex_data |
(ndarray, optional)
|
Per-vertex values (N,) - e.g., correlation, thickness |
hemisphere |
(str, optional)
|
Hemisphere identifier ("L", "R", "both") |
surface_type |
(str, optional)
|
Type of surface (e.g., "pial", "white", "inflated") |
metadata |
dict
|
Additional metadata about the output |
Source code in src/lacuna/core/data_types.py
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 | |
__post_init__()
¶
Initialize and validate surface data.
Source code in src/lacuna/core/data_types.py
__repr__()
¶
get_data()
¶
get_mesh()
¶
summary()
¶
Get a summary description of this result.
Source code in src/lacuna/core/data_types.py
Tractogram
dataclass
¶
Bases: DataContainer
Result container for tractography streamlines.
Primary storage is path-based. Optionally stores streamlines in memory for immediate access. Use nibabel or dipy to load tractograms from disk.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
tractogram_path |
Path
|
Path to saved tractogram file (.tck, .trk) |
streamlines |
(list or ndarray, optional)
|
Optional in-memory streamlines, each as (N_points, 3) array |
metadata |
dict
|
Additional metadata about the output |
Source code in src/lacuna/core/data_types.py
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 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | |
__post_init__()
¶
Initialize and validate tractogram data.
Source code in src/lacuna/core/data_types.py
__repr__()
¶
Return string representation.
get_data()
¶
Get tractogram data.
Returns:
| Type | Description |
|---|---|
streamlines or path
|
Returns in-memory streamlines if available, otherwise returns path. Use nibabel.streamlines.load() to load from path. |
Examples:
>>> result = Tractogram(name="tracts", tractogram_path=Path("tracts.tck"))
>>> data = result.get_data() # Returns Path
>>> # Load with nibabel:
>>> import nibabel as nib
>>> tractogram = nib.streamlines.load(str(data))
Source code in src/lacuna/core/data_types.py
save(output_path)
¶
Save tractogram to disk by copying the source file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path
|
Destination file path. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the saved file. |
Source code in src/lacuna/core/data_types.py
summary()
¶
Get a summary description of this result.
ValidationError
¶
Bases: LacunaError, ValueError
Raised when data validation fails.
VoxelMap
dataclass
¶
Bases: DataContainer
Result container for voxel-level brain maps.
This class stores voxel-level analysis outputs (e.g., functional connectivity maps, structural disconnection maps) in their native computation space.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name/identifier for this result |
data |
Nifti1Image
|
Brain map in its computation space |
space |
str
|
Coordinate space identifier (e.g., 'MNI152NLin6Asym') |
resolution |
float
|
Resolution in mm (e.g., 1.0, 2.0) |
metadata |
dict
|
Additional metadata about the output |
Examples:
>>> import nibabel as nib
>>> import numpy as np
>>> # Create a sample brain map
>>> data = np.random.randn(91, 109, 91)
>>> img = nib.Nifti1Image(data, np.eye(4) * 2)
>>> voxel_map = VoxelMap(
... name="functional_connectivity",
... data=img,
... space="MNI152NLin6Asym",
... resolution=2.0,
... metadata={"seed": "PCC"}
... )
>>> print(voxel_map.summary())
functional_connectivity: (91, 109, 91) voxels, space=MNI152NLin6Asym, resolution=2.0mm
Source code in src/lacuna/core/data_types.py
analyze(data, *, steps, n_jobs=1, show_progress=True, verbose=False)
¶
Run an analysis pipeline defined by a steps dictionary.
This function provides a flexible interface for running analysis workflows.
The steps dictionary defines which analyses to run and their parameters.
Analyses are executed in the order they appear in the dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
SubjectData or list of SubjectData
|
Input data to analyze. Single subject or batch of subjects. |
required |
steps
|
dict[str, dict | None]
|
Analysis steps to run. Keys are analysis class names (must match exactly), values are dicts of kwargs for that analysis, or None for defaults. Available analyses (use Required parameters vary by analysis: - FunctionalNetworkMapping requires "connectome_name" - StructuralNetworkMapping requires "connectome_name" - Others have sensible defaults |
required |
n_jobs
|
int
|
Number of parallel jobs for batch processing. Use -1 for all CPUs. |
1
|
show_progress
|
bool
|
Show tqdm progress bar during batch processing. |
True
|
verbose
|
bool
|
If True, print progress messages. If False, run silently. |
True
|
Returns:
| Type | Description |
|---|---|
SubjectData or list of SubjectData
|
Analyzed data with results. If input was a list, returns a list.
Results are stored in |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not SubjectData or list of SubjectData. |
KeyError
|
If an analysis name in steps is not recognized. |
ValueError
|
If required parameters are missing for an analysis. |
Examples:
Basic usage with RegionalDamage defaults:
>>> from lacuna import analyze, SubjectData
>>> result = analyze(mask_data, steps={"RegionalDamage": None})
With functional network mapping (connectome_name is required):
>>> result = analyze(
... mask_data,
... steps={
... "RegionalDamage": None,
... "FunctionalNetworkMapping": {"connectome_name": "GSP1000"},
... }
... )
With custom parameters:
>>> result = analyze(
... mask_data,
... steps={
... "RegionalDamage": {"parcel_names": ["schaefer2018parcels100networks7"]},
... "FunctionalNetworkMapping": {
... "connectome_name": "GSP1000",
... "method": "boes",
... },
... }
... )
Batch processing with parallelization:
>>> results = analyze(
... [subject1, subject2, subject3],
... steps={"FunctionalNetworkMapping": {"connectome_name": "GSP1000"}},
... n_jobs=-1,
... show_progress=True,
... )
Source code in src/lacuna/core/pipeline.py
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 443 444 445 446 447 448 449 450 451 452 | |
build_result_key(atlas, source, desc=None)
¶
Build a BIDS-style result key from components.
Creates a structured key string in the format:
atlas-{atlas}_source-{source}[_desc-{desc}]
The desc component is optional and automatically omitted when source is InputMask/SubjectData (the mask itself is the primary data, no additional description needed).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atlas
|
str
|
Atlas/parcellation name (e.g., "Schaefer100", "Tian_S4"). |
required |
source
|
str
|
Source analysis class name (e.g., "SubjectData", "FunctionalNetworkMapping"). Will be converted to appropriate source abbreviation (e.g., SubjectData -> InputMask). |
required |
desc
|
str
|
Description/key within the source (e.g., "rmap"). Ignored for InputMask source (automatically omitted). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
BIDS-style result key. |
Examples:
>>> build_result_key("Schaefer100", "FunctionalNetworkMapping", "rmap")
'atlas-Schaefer100_source-FunctionalNetworkMapping_desc-rmap'
>>> build_result_key("tian2020parcels16", "SubjectData", "maskimg")
'atlas-tian2020parcels16_source-InputMask'
>>> build_result_key("schaefer2018parcels200networks7", "RegionalDamage", "damagescore")
'atlas-schaefer2018parcels200networks7_source-RegionalDamage_desc-damagescore'
Source code in src/lacuna/core/keys.py
check_spatial_match(img1, img2, check_shape=True, check_affine=True, atol=0.001)
¶
Check if two images have matching spatial properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img1
|
Nifti1Image
|
First image. |
required |
img2
|
Nifti1Image
|
Second image. |
required |
check_shape
|
bool
|
Check if shapes match. |
True
|
check_affine
|
bool
|
Check if affines match (within tolerance). |
True
|
atol
|
float
|
Absolute tolerance for affine comparison (in mm). |
1e-3
|
Returns:
| Type | Description |
|---|---|
bool
|
True if images match spatially. |
Raises:
| Type | Description |
|---|---|
SpatialMismatchError
|
If spatial properties don't match. |
Examples:
>>> import nibabel as nib
>>> lesion = nib.load("lesion.nii.gz")
>>> anat = nib.load("anatomical.nii.gz")
>>> check_spatial_match(lesion, anat)
Source code in src/lacuna/core/validation.py
create_provenance_record(function, parameters, version, output_space=None)
¶
Create a provenance record for a transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
str
|
Fully qualified function name (e.g., 'lacuna.analysis.RegionalDamage'). |
required |
parameters
|
dict
|
Function parameters (must be JSON-serializable). |
required |
version
|
str
|
Package version at time of execution. |
required |
output_space
|
str
|
Resulting coordinate space (if spatial operation). |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Provenance record with function, parameters, timestamp, version. |
Raises:
| Type | Description |
|---|---|
ProvenanceError
|
If parameters are not JSON-serializable. |
Examples:
>>> record = create_provenance_record(
... function="lacuna.analysis.RegionalDamage",
... parameters={"parcel_names": ["schaefer2018parcels100networks7"]},
... version="0.1.0",
... )
>>> record['function']
'lacuna.analysis.RegionalDamage'
Source code in src/lacuna/core/provenance.py
ensure_ras_plus(img)
¶
Ensure image is in RAS+ orientation (nilearn standard).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Nifti1Image
|
Input image (any orientation). |
required |
Returns:
| Type | Description |
|---|---|
Nifti1Image
|
Image reoriented to RAS+ (if necessary). |
Notes
RAS+ means: - First axis: Right to Left - Second axis: Anterior to Posterior - Third axis: Superior to Inferior
Examples:
Source code in src/lacuna/core/validation.py
get_source_abbreviation(class_name)
¶
Validate and return the source name for an analysis class.
This function validates that the class name is a known analysis type and returns the appropriate source abbreviation for result keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
class_name
|
str
|
Analysis class name (e.g., "FunctionalNetworkMapping", "SubjectData"). |
required |
Returns:
| Type | Description |
|---|---|
str
|
The source abbreviation for use in result keys. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If class_name is not a known analysis class. |
Examples:
>>> get_source_abbreviation("FunctionalNetworkMapping")
'FunctionalNetworkMapping'
>>> get_source_abbreviation("SubjectData")
'InputMask'
Source code in src/lacuna/core/keys.py
merge_provenance(base_provenance, new_provenance)
¶
Merge two provenance lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_provenance
|
list
|
Base provenance history. |
required |
new_provenance
|
list
|
New provenance to append. |
required |
Returns:
| Type | Description |
|---|---|
list
|
Merged provenance list (ordered chronologically). |
Source code in src/lacuna/core/provenance.py
parse_result_key(key)
¶
Parse a BIDS-style result key into its components.
Extracts key-value pairs from a structured key string in the format:
atlas-{atlas}_source-{source}[_desc-{desc}]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
BIDS-style result key to parse. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dictionary with parsed components. Keys are "atlas", "source", "desc". Missing components will not be present in the returned dict. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If key is empty or has invalid format. |
Examples:
>>> parse_result_key("atlas-Schaefer100_source-FunctionalNetworkMapping_desc-rmap")
{'atlas': 'Schaefer100', 'source': 'FunctionalNetworkMapping', 'desc': 'rmap'}
Source code in src/lacuna/core/keys.py
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 | |
validate_affine(affine)
¶
Validate an affine transformation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
affine
|
(ndarray, shape(4, 4))
|
Affine matrix to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If affine is invalid. |
Source code in src/lacuna/core/validation.py
validate_nifti_image(img, require_3d=True, check_affine=True)
¶
Validate NIfTI image properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Nifti1Image
|
Image to validate. |
required |
require_3d
|
bool
|
Raise error if image is not 3D. |
True
|
check_affine
|
bool
|
Verify affine matrix is invertible. |
True
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails. |
Examples:
Source code in src/lacuna/core/validation.py
validate_provenance_record(record)
¶
Validate a provenance record structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
dict
|
Provenance record to validate. |
required |
Raises:
| Type | Description |
|---|---|
ProvenanceError
|
If record structure is invalid. |