pyLQT 1.0.dev7__py3-none-any.whl → 1.0.dev9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyLQT/cli.py +4 -1
- pyLQT/lesion_metrics/grey_matter/metrics.py +6 -9
- pyLQT/lesion_metrics/network/metrics.py +3 -1
- pyLQT/lesion_metrics/utils/configs.py +8 -10
- pyLQT/lesion_metrics/utils/downloads.py +75 -133
- pyLQT/lesion_metrics/utils/registration.py +104 -1
- pyLQT/lesion_metrics/white_matter/metrics.py +82 -128
- pyLQT/lesion_metrics/white_matter/utils.py +17 -15
- pyLQT/pipeline.py +48 -39
- pyLQT/utils/__init__.py +0 -0
- pyLQT/utils/logs.py +40 -0
- {pylqt-1.0.dev7.dist-info → pylqt-1.0.dev9.dist-info}/METADATA +8 -6
- pylqt-1.0.dev9.dist-info/RECORD +25 -0
- pylqt-1.0.dev7.dist-info/RECORD +0 -23
- {pylqt-1.0.dev7.dist-info → pylqt-1.0.dev9.dist-info}/WHEEL +0 -0
- {pylqt-1.0.dev7.dist-info → pylqt-1.0.dev9.dist-info}/entry_points.txt +0 -0
- {pylqt-1.0.dev7.dist-info → pylqt-1.0.dev9.dist-info}/licenses/LICENSE +0 -0
- {pylqt-1.0.dev7.dist-info → pylqt-1.0.dev9.dist-info}/top_level.txt +0 -0
pyLQT/cli.py
CHANGED
|
@@ -43,13 +43,15 @@ def main():
|
|
|
43
43
|
)
|
|
44
44
|
|
|
45
45
|
parser.add_argument(
|
|
46
|
-
"--
|
|
46
|
+
"--sc_distance_threshold",
|
|
47
|
+
type=float,
|
|
47
48
|
default=5.0,
|
|
48
49
|
help='[float (0,inf), default=5.0] Defines threshold for distance filtering of tracts endpoints in structural connectivity computation.'
|
|
49
50
|
)
|
|
50
51
|
|
|
51
52
|
parser.add_argument(
|
|
52
53
|
"--spared_threshold",
|
|
54
|
+
type=float,
|
|
53
55
|
default=0.5,
|
|
54
56
|
help='[float (0,1), default=0.5] Defines threshold for spared parcel-to-parcel connectivity'
|
|
55
57
|
)
|
|
@@ -68,6 +70,7 @@ def main():
|
|
|
68
70
|
tracts_cfg=args.tracts_cfg,
|
|
69
71
|
out_folder=args.out_folder,
|
|
70
72
|
registration_type=args.registration_type,
|
|
73
|
+
sc_distance_threshold=args.sc_distance_threshold,
|
|
71
74
|
spared_threshold=args.spared_threshold,
|
|
72
75
|
delete_tmp=args.delete_tmp,
|
|
73
76
|
)
|
|
@@ -3,8 +3,9 @@ import nibabel as nib
|
|
|
3
3
|
|
|
4
4
|
from nibabel.processing import resample_from_to
|
|
5
5
|
from .utils import compute_parcel_damage
|
|
6
|
+
from pyLQT.utils.logs import log_execution
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
@log_execution
|
|
8
9
|
def get_parcel_damage(
|
|
9
10
|
lesion,
|
|
10
11
|
atlas,
|
|
@@ -44,14 +45,11 @@ def get_parcel_damage(
|
|
|
44
45
|
Returns
|
|
45
46
|
-------
|
|
46
47
|
pandas.DataFrame
|
|
47
|
-
Copy of ``atlas_labels`` with an additional ``out_col``
|
|
48
|
-
|
|
49
|
-
lesion.
|
|
48
|
+
Copy of ``atlas_labels`` with an additional column, defined by ``out_col``
|
|
49
|
+
containing the proportion of each parcel affected by the lesion.
|
|
50
50
|
"""
|
|
51
51
|
|
|
52
|
-
lesion_resampled = resample_from_to(lesion,
|
|
53
|
-
atlas,
|
|
54
|
-
order=1)
|
|
52
|
+
lesion_resampled = resample_from_to(lesion, atlas, order=1)
|
|
55
53
|
|
|
56
54
|
lesion_volume = lesion_resampled.get_fdata()
|
|
57
55
|
atlas_volume = atlas.get_fdata().astype(np.int32)
|
|
@@ -79,5 +77,4 @@ def get_parcel_damage(
|
|
|
79
77
|
if out_path:
|
|
80
78
|
damage_frame.to_csv(out_path / 'parcel_damage_frame.csv', index=False)
|
|
81
79
|
|
|
82
|
-
return damage_frame
|
|
83
|
-
|
|
80
|
+
return damage_frame
|
|
@@ -3,7 +3,9 @@ import networkx as nx
|
|
|
3
3
|
|
|
4
4
|
from scipy.sparse import csr_matrix
|
|
5
5
|
from scipy.sparse.csgraph import shortest_path
|
|
6
|
+
from pyLQT.utils.logs import log_execution
|
|
6
7
|
|
|
8
|
+
@log_execution
|
|
7
9
|
def get_parcel_wise_disconnection_severity(
|
|
8
10
|
structural_connectivity,
|
|
9
11
|
structural_connectivity_disconnected,
|
|
@@ -65,7 +67,7 @@ def get_parcel_wise_disconnection_severity(
|
|
|
65
67
|
|
|
66
68
|
return disconnections_severity, per_spared_connections
|
|
67
69
|
|
|
68
|
-
|
|
70
|
+
@log_execution
|
|
69
71
|
def get_sspl_increase(
|
|
70
72
|
structural_connectivity,
|
|
71
73
|
per_spared_connections,
|
|
@@ -34,7 +34,7 @@ def atlas_cfg_read(atlas_cfg_path):
|
|
|
34
34
|
Name of the atlas.
|
|
35
35
|
- atlas : nibabel.Nifti1Image
|
|
36
36
|
Loaded atlas image.
|
|
37
|
-
-
|
|
37
|
+
- labels : pandas.DataFrame
|
|
38
38
|
DataFrame containing the atlas parcel labels.
|
|
39
39
|
- atlas_space : str
|
|
40
40
|
Space in which the atlas is defined.
|
|
@@ -66,9 +66,6 @@ def tracts_cfg_read(tracts_cfg_path):
|
|
|
66
66
|
- 'tracts_folder':
|
|
67
67
|
path to the folder containing .trk files, relative to
|
|
68
68
|
the folder containing the config file
|
|
69
|
-
- 'references_folder':
|
|
70
|
-
path to the folder containing nifti reference files
|
|
71
|
-
of the tracts, relative to the folder containing the config file
|
|
72
69
|
- 'space':
|
|
73
70
|
standard space name available in templateflow or path
|
|
74
71
|
to reference nifti relative to the folder containing the config file
|
|
@@ -82,20 +79,18 @@ def tracts_cfg_read(tracts_cfg_path):
|
|
|
82
79
|
Name of the tracts.
|
|
83
80
|
- tracts_folder : pathlib.Path
|
|
84
81
|
Path to folder containing .trk tract files.
|
|
85
|
-
- references_folder : pathlib.Path
|
|
86
|
-
Path to folder containing .nii tract reference files.
|
|
87
82
|
- tracts_space : str
|
|
88
|
-
Space in which the tracts are defined
|
|
83
|
+
Space in which the tracts are defined, that can be used as reference when
|
|
84
|
+
loaded.
|
|
89
85
|
"""
|
|
90
86
|
with tracts_cfg_path.open("r") as f:
|
|
91
87
|
tracts_cfg = json.load(f)
|
|
92
88
|
|
|
93
89
|
tracts_name = tracts_cfg.get("name")
|
|
94
90
|
tracts_folder = Path(tracts_cfg_path.parent / tracts_cfg.get("tracts"))
|
|
95
|
-
references_folder = Path(tracts_cfg_path.parent / tracts_cfg.get("references"))
|
|
96
91
|
tracts_space = tracts_cfg.get("space")
|
|
97
92
|
|
|
98
|
-
return tracts_name, tracts_folder,
|
|
93
|
+
return tracts_name, tracts_folder, tracts_space
|
|
99
94
|
|
|
100
95
|
def lesion_cfg_read(lesion_cfg_path: Path):
|
|
101
96
|
"""Read a tracts configuration file and load the associated data.
|
|
@@ -134,4 +129,7 @@ def lesion_cfg_read(lesion_cfg_path: Path):
|
|
|
134
129
|
lesion_folder = Path(lesion_cfg_path.parent / lesion_cfg.get("lesion_folder"))
|
|
135
130
|
lesion_space = lesion_cfg.get("space")
|
|
136
131
|
|
|
137
|
-
return lesion_cohort_name, lesion_folder, lesion_space
|
|
132
|
+
return lesion_cohort_name, lesion_folder, lesion_space
|
|
133
|
+
|
|
134
|
+
if __name__=="__main__":
|
|
135
|
+
atlas_cfg_read(Path('D:/internship_myspace_lab/pyLQT/test_download/Schaefer2018_100Parcels_7Networks_order.csv'))
|
|
@@ -4,111 +4,13 @@ import warnings
|
|
|
4
4
|
import requests
|
|
5
5
|
import shutil
|
|
6
6
|
import gzip
|
|
7
|
+
import re
|
|
7
8
|
import nibabel as nib
|
|
8
9
|
import numpy as np
|
|
9
10
|
import pandas as pd
|
|
10
11
|
|
|
11
12
|
from templateflow import api as tf
|
|
12
13
|
from pathlib import Path
|
|
13
|
-
|
|
14
|
-
def create_tract_list(
|
|
15
|
-
references_folder,
|
|
16
|
-
tracts_folder
|
|
17
|
-
):
|
|
18
|
-
"""Create paired lists of tractogram and reference image paths.
|
|
19
|
-
|
|
20
|
-
Tractograms and their corresponding NIfTI reference images are matched
|
|
21
|
-
based on their relative paths within their respective folders. The
|
|
22
|
-
function also checks that all reference images share the same voxel
|
|
23
|
-
grid and affine.
|
|
24
|
-
|
|
25
|
-
Parameters
|
|
26
|
-
----------
|
|
27
|
-
references_folder : pathlib.Path
|
|
28
|
-
Root directory containing the NIfTI reference images.
|
|
29
|
-
tracts_folder : pathlib.Path
|
|
30
|
-
Root directory containing the tractogram files.
|
|
31
|
-
|
|
32
|
-
Returns
|
|
33
|
-
-------
|
|
34
|
-
tuple[list[pathlib.Path], list[pathlib.Path]]
|
|
35
|
-
Two lists containing:
|
|
36
|
-
|
|
37
|
-
- tracts_pathlist : list[pathlib.Path]
|
|
38
|
-
Paths to the tractogram files.
|
|
39
|
-
- references_pathlist : list[pathlib.Path]
|
|
40
|
-
Paths to the corresponding NIfTI reference images.
|
|
41
|
-
|
|
42
|
-
Only tractograms with a corresponding NIfTI reference are included.
|
|
43
|
-
Warnings are issued for missing pairs and for reference images with
|
|
44
|
-
mismatched grids or affines.
|
|
45
|
-
"""
|
|
46
|
-
trk_paths = sorted(tracts_folder.rglob("*.trk.gz"))
|
|
47
|
-
nifti_paths = sorted(references_folder.rglob("*.nii.gz"))
|
|
48
|
-
|
|
49
|
-
# Check that every TRK has a corresponding NIfTI
|
|
50
|
-
nifti_relatives = {
|
|
51
|
-
p.relative_to(references_folder)
|
|
52
|
-
for p in nifti_paths
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
for trk_path in trk_paths:
|
|
56
|
-
trk_relative = trk_path.relative_to(tracts_folder)
|
|
57
|
-
expected_nifti = Path(
|
|
58
|
-
str(trk_relative).replace(".trk.gz", ".nii.gz")
|
|
59
|
-
)
|
|
60
|
-
|
|
61
|
-
if expected_nifti not in nifti_relatives:
|
|
62
|
-
warnings.warn(f"No NIfTI found for {expected_nifti}")
|
|
63
|
-
|
|
64
|
-
# Check that every NIfTI has a corresponding TRK
|
|
65
|
-
trk_relatives = {
|
|
66
|
-
p.relative_to(tracts_folder)
|
|
67
|
-
for p in trk_paths
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
for nifti_path in nifti_paths:
|
|
71
|
-
nifti_relative = nifti_path.relative_to(references_folder)
|
|
72
|
-
expected_trk = Path(
|
|
73
|
-
str(nifti_relative).replace(".nii.gz", ".trk.gz")
|
|
74
|
-
)
|
|
75
|
-
|
|
76
|
-
if expected_trk not in trk_relatives:
|
|
77
|
-
warnings.warn(f"No TRK found for {expected_trk}")
|
|
78
|
-
|
|
79
|
-
tracts_pathlist = []
|
|
80
|
-
references_pathlist = []
|
|
81
|
-
|
|
82
|
-
for trk_path in trk_paths:
|
|
83
|
-
trk_relative = trk_path.relative_to(tracts_folder)
|
|
84
|
-
|
|
85
|
-
nifti_path = (
|
|
86
|
-
references_folder
|
|
87
|
-
/ Path(str(trk_relative).replace(".trk.gz", ".nii.gz"))
|
|
88
|
-
)
|
|
89
|
-
|
|
90
|
-
if not nifti_path.exists():
|
|
91
|
-
continue
|
|
92
|
-
|
|
93
|
-
tracts_pathlist.append(trk_path)
|
|
94
|
-
references_pathlist.append(nifti_path)
|
|
95
|
-
|
|
96
|
-
# Verify that all NIfTIs are on the same grid
|
|
97
|
-
reference = None
|
|
98
|
-
|
|
99
|
-
# TODO too simple check, should be based on affine with real world coordinates.
|
|
100
|
-
for nifti_path in references_pathlist:
|
|
101
|
-
nifti = nib.nifti1.load(nifti_path)
|
|
102
|
-
|
|
103
|
-
if reference is None:
|
|
104
|
-
reference = nifti
|
|
105
|
-
else:
|
|
106
|
-
if nifti.shape != reference.shape:
|
|
107
|
-
warnings.warn(f"NIfTI grid mismatch: {nifti_path}")
|
|
108
|
-
if not np.allclose(nifti.affine, reference.affine):
|
|
109
|
-
warnings.warn(f"NIfTI affine mismatch: {nifti_path}")
|
|
110
|
-
|
|
111
|
-
return tracts_pathlist, references_pathlist
|
|
112
14
|
|
|
113
15
|
def uncompress_trk_gz(
|
|
114
16
|
trk_path,
|
|
@@ -137,6 +39,77 @@ def uncompress_trk_gz(
|
|
|
137
39
|
|
|
138
40
|
return out_path
|
|
139
41
|
|
|
42
|
+
|
|
43
|
+
def fetch_schaefer_atlas(
|
|
44
|
+
out_folder,
|
|
45
|
+
n_parcel=100,
|
|
46
|
+
n_network=7,
|
|
47
|
+
resolution=1
|
|
48
|
+
):
|
|
49
|
+
if n_parcel not in (100, 200, 300, 400, 500, 600, 700, 800, 900, 1000):
|
|
50
|
+
raise ValueError("Number of parcels must be between 100 and 1000.")
|
|
51
|
+
if n_network not in (7, 17):
|
|
52
|
+
raise ValueError("Number of networks must be 7 or 17.")
|
|
53
|
+
if resolution not in (1, 2):
|
|
54
|
+
raise ValueError("Resolution must be 1 or 2 mm.")
|
|
55
|
+
|
|
56
|
+
base_url = (
|
|
57
|
+
"https://api.github.com/repos/ThomasYeoLab/CBIG/contents/"
|
|
58
|
+
"stable_projects/brain_parcellation/Schaefer2018_LocalGlobal/"
|
|
59
|
+
"Parcellations/MNI"
|
|
60
|
+
)
|
|
61
|
+
response = requests.get(base_url, timeout=30)
|
|
62
|
+
response.raise_for_status()
|
|
63
|
+
files = response.json()
|
|
64
|
+
|
|
65
|
+
prefix = f"Schaefer2018_{n_parcel}Parcels_{n_network}Networks_order"
|
|
66
|
+
atlas_name = f"{prefix}_FSLMNI152_{resolution}mm.nii.gz"
|
|
67
|
+
labels_name = f"{prefix}.txt"
|
|
68
|
+
available = {f["name"]: f for f in files}
|
|
69
|
+
|
|
70
|
+
labels_url = f"{base_url}/freeview_lut"
|
|
71
|
+
response = requests.get(labels_url, timeout=30)
|
|
72
|
+
response.raise_for_status()
|
|
73
|
+
labels_files = {f["name"]: f for f in response.json()}
|
|
74
|
+
|
|
75
|
+
if atlas_name not in available:
|
|
76
|
+
raise FileNotFoundError(f"Atlas not found: {atlas_name}")
|
|
77
|
+
if labels_name not in labels_files:
|
|
78
|
+
raise FileNotFoundError(f"Labels not found: {labels_name}")
|
|
79
|
+
|
|
80
|
+
out_folder = Path(out_folder)
|
|
81
|
+
out_folder.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
|
|
83
|
+
results = {}
|
|
84
|
+
for key, filename, file_info in (("atlas", atlas_name, available[atlas_name]), ("labels", labels_name, labels_files[labels_name])):
|
|
85
|
+
output_path = out_folder / filename
|
|
86
|
+
if not output_path.exists():
|
|
87
|
+
with requests.get(file_info["download_url"], stream=True, timeout=60) as r:
|
|
88
|
+
r.raise_for_status()
|
|
89
|
+
with open(output_path, "wb") as f:
|
|
90
|
+
for chunk in r.iter_content(chunk_size=8192):
|
|
91
|
+
if chunk:
|
|
92
|
+
f.write(chunk)
|
|
93
|
+
results[key] = output_path
|
|
94
|
+
|
|
95
|
+
schaefer_atlas = nib.load(results["atlas"])
|
|
96
|
+
with open(results["labels"], "r") as f:
|
|
97
|
+
schaefer_labels = pd.DataFrame(
|
|
98
|
+
[
|
|
99
|
+
parts[:2]
|
|
100
|
+
for line in f
|
|
101
|
+
if (parts := line.strip().split())
|
|
102
|
+
],
|
|
103
|
+
columns=["Parcel", "Label"]
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
csv_path = results["labels"].with_suffix(".csv")
|
|
107
|
+
schaefer_labels.to_csv(csv_path, index=False)
|
|
108
|
+
schaefer_labels = pd.read_csv(csv_path)
|
|
109
|
+
print(schaefer_labels)
|
|
110
|
+
return schaefer_atlas, schaefer_labels
|
|
111
|
+
|
|
112
|
+
|
|
140
113
|
def default_atlas_download(out_folder: Path):
|
|
141
114
|
atlas_cfg_folder = out_folder / "glasser360_config"
|
|
142
115
|
atlas_cfg_folder.mkdir(parents=True, exist_ok=True)
|
|
@@ -204,9 +177,8 @@ def default_atlas_download(out_folder: Path):
|
|
|
204
177
|
def default_tracts_download(out_folder: Path):
|
|
205
178
|
"""Download the default HCP1065 tractography dataset and create its configuration.
|
|
206
179
|
|
|
207
|
-
The function downloads the HCP1065 average tractograms and
|
|
208
|
-
|
|
209
|
-
file. Existing folders are reused.
|
|
180
|
+
The function downloads the HCP1065 average tractograms and creates a default
|
|
181
|
+
configuration file. Existing folders are reused.
|
|
210
182
|
|
|
211
183
|
Parameters
|
|
212
184
|
----------
|
|
@@ -248,41 +220,11 @@ def default_tracts_download(out_folder: Path):
|
|
|
248
220
|
|
|
249
221
|
zip_path.unlink()
|
|
250
222
|
|
|
251
|
-
references_folder = tracts_cfg_folder / "hcp1065_avg_tracts"
|
|
252
|
-
|
|
253
|
-
if references_folder.exists():
|
|
254
|
-
warnings.warn(
|
|
255
|
-
f"References folder already exists, using it: {references_folder}",
|
|
256
|
-
UserWarning,
|
|
257
|
-
stacklevel=2
|
|
258
|
-
)
|
|
259
|
-
else:
|
|
260
|
-
url = "https://github.com/data-others/atlas/releases/download/hcp1065/hcp1065_avg_tracts_nifti.zip"
|
|
261
|
-
zip_path = out_folder / "hcp1065_avg_tracts_nifti.zip"
|
|
262
|
-
|
|
263
|
-
response = requests.get(url, stream=True, timeout=60)
|
|
264
|
-
response.raise_for_status()
|
|
265
|
-
|
|
266
|
-
with zip_path.open("wb") as f:
|
|
267
|
-
for chunk in response.iter_content(chunk_size=1024*1024):
|
|
268
|
-
if chunk:
|
|
269
|
-
f.write(chunk)
|
|
270
|
-
|
|
271
|
-
with zipfile.ZipFile(zip_path) as zip_file:
|
|
272
|
-
zip_file.extractall(tracts_cfg_folder)
|
|
273
|
-
|
|
274
|
-
zip_path.unlink()
|
|
275
|
-
|
|
276
|
-
extracted_niftis = tracts_cfg_folder / "nifti"
|
|
277
|
-
if extracted_niftis.exists():
|
|
278
|
-
extracted_niftis.rename(references_folder)
|
|
279
|
-
|
|
280
223
|
tracts_name = "HCP1065"
|
|
281
224
|
tracts_space = "MNI152NLin2009aAsym"
|
|
282
225
|
|
|
283
226
|
config = {"name": tracts_name,
|
|
284
227
|
"tracts": "hcp1065_avg_tracts_trk",
|
|
285
|
-
"references": "hcp1065_avg_tracts",
|
|
286
228
|
"space": tracts_space}
|
|
287
229
|
|
|
288
230
|
tracts_cfg = Path(tracts_cfg_folder / "HCP1065_config.json")
|
|
@@ -319,4 +261,4 @@ def get_ref_space_tf(space: str, res: int = 1):
|
|
|
319
261
|
|
|
320
262
|
if __name__=="__main__":
|
|
321
263
|
|
|
322
|
-
|
|
264
|
+
fetch_schaefer_atlas(out_folder='D:/internship_myspace_lab/pyLQT/schaefer_100parcels_17networks', n_network=17)
|
|
@@ -4,6 +4,11 @@ from dipy.align.imwarp import SymmetricDiffeomorphicRegistration
|
|
|
4
4
|
from dipy.align.metrics import CCMetric
|
|
5
5
|
from dipy.align import write_mapping
|
|
6
6
|
|
|
7
|
+
from ants.utils.nibabel_nifti_to_ants import from_nibabel_nifti, to_nibabel_nifti
|
|
8
|
+
import ants
|
|
9
|
+
import nibabel as nib
|
|
10
|
+
|
|
11
|
+
'''
|
|
7
12
|
def register_affine(
|
|
8
13
|
moving,
|
|
9
14
|
static,
|
|
@@ -107,4 +112,102 @@ def register_syn(
|
|
|
107
112
|
if out_path:
|
|
108
113
|
write_mapping(mapping, out_path)
|
|
109
114
|
|
|
110
|
-
return mapping
|
|
115
|
+
return mapping
|
|
116
|
+
'''
|
|
117
|
+
|
|
118
|
+
def register_affine(
|
|
119
|
+
moving,
|
|
120
|
+
static,
|
|
121
|
+
out_path=None
|
|
122
|
+
):
|
|
123
|
+
"""Register a moving image to a static image using affine registration.
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
moving : nibabel.Nifti1Image
|
|
128
|
+
Image to be registered to the static image.
|
|
129
|
+
static : nibabel.Nifti1Image
|
|
130
|
+
Reference image defining the target space.
|
|
131
|
+
out_path : pathlib.Path | None, optional
|
|
132
|
+
Prefix for saving registration transforms. If None, ANTs
|
|
133
|
+
manages the transform output files.
|
|
134
|
+
|
|
135
|
+
Returns
|
|
136
|
+
-------
|
|
137
|
+
dict
|
|
138
|
+
ANTs registration result containing forward and inverse transforms.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
moving_ants = from_nibabel_nifti(moving)
|
|
142
|
+
static_ants = from_nibabel_nifti(static)
|
|
143
|
+
|
|
144
|
+
registration = ants.registration(
|
|
145
|
+
fixed=static_ants,
|
|
146
|
+
moving=moving_ants,
|
|
147
|
+
type_of_transform="Affine",
|
|
148
|
+
aff_metric="mattes",
|
|
149
|
+
aff_sampling=32,
|
|
150
|
+
aff_random_sampling_rate=0.2,
|
|
151
|
+
aff_iterations=(500, 250, 100),
|
|
152
|
+
verbose=False,
|
|
153
|
+
outprefix=str(out_path) if out_path else ""
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
return registration
|
|
157
|
+
|
|
158
|
+
def register_syn(
|
|
159
|
+
moving,
|
|
160
|
+
static,
|
|
161
|
+
out_path=None
|
|
162
|
+
):
|
|
163
|
+
"""Register a moving image to a static image using SyN registration.
|
|
164
|
+
|
|
165
|
+
Parameters
|
|
166
|
+
----------
|
|
167
|
+
moving : nibabel.Nifti1Image
|
|
168
|
+
Image to be registered to the static image.
|
|
169
|
+
static : nibabel.Nifti1Image
|
|
170
|
+
Reference image defining the target space.
|
|
171
|
+
out_path : pathlib.Path | None, optional
|
|
172
|
+
Prefix for saving registration transforms. If None, ANTs
|
|
173
|
+
manages the transform output files.
|
|
174
|
+
|
|
175
|
+
Returns
|
|
176
|
+
-------
|
|
177
|
+
dict
|
|
178
|
+
ANTs registration result containing forward and inverse transforms.
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
moving_ants = from_nibabel_nifti(moving)
|
|
182
|
+
static_ants = from_nibabel_nifti(static)
|
|
183
|
+
|
|
184
|
+
registration = ants.registration(
|
|
185
|
+
fixed=static_ants,
|
|
186
|
+
moving=moving_ants,
|
|
187
|
+
type_of_transform="SyN",
|
|
188
|
+
syn_metric="CC",
|
|
189
|
+
syn_sampling=4,
|
|
190
|
+
reg_iterations=(20, 10, 5),
|
|
191
|
+
verbose=False,
|
|
192
|
+
outprefix=str(out_path) if out_path else ""
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
return registration
|
|
196
|
+
|
|
197
|
+
def apply_registration(
|
|
198
|
+
moving,
|
|
199
|
+
static,
|
|
200
|
+
registration,
|
|
201
|
+
interpolation="linear"
|
|
202
|
+
):
|
|
203
|
+
moving_ants = from_nibabel_nifti(moving)
|
|
204
|
+
static_ants = from_nibabel_nifti(static)
|
|
205
|
+
|
|
206
|
+
transformed = ants.apply_transforms(
|
|
207
|
+
fixed=static_ants,
|
|
208
|
+
moving=moving_ants,
|
|
209
|
+
transformlist=registration["fwdtransforms"],
|
|
210
|
+
interpolator=interpolation
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
return to_nibabel_nifti(transformed)
|
|
@@ -2,159 +2,113 @@ import nibabel as nib
|
|
|
2
2
|
import pandas as pd
|
|
3
3
|
import numpy as np
|
|
4
4
|
|
|
5
|
-
from
|
|
6
|
-
from
|
|
7
|
-
|
|
8
|
-
from
|
|
9
|
-
|
|
5
|
+
from .utils import get_tract, get_streamlines_disconnection
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from time import perf_counter
|
|
8
|
+
from pyLQT.utils.logs import log_execution
|
|
10
9
|
|
|
10
|
+
@log_execution
|
|
11
11
|
def get_tracts_disconnections_severity(
|
|
12
12
|
tracts_path,
|
|
13
|
-
|
|
13
|
+
reference_path,
|
|
14
14
|
lesion,
|
|
15
|
-
disc_tracts_out_path
|
|
16
|
-
disc_frame_out_path
|
|
15
|
+
disc_tracts_out_path=None,
|
|
16
|
+
disc_frame_out_path=None
|
|
17
17
|
):
|
|
18
|
-
|
|
19
|
-
"""Compute the proportion of disconnected streamlines for a list of tracts.
|
|
20
|
-
|
|
21
|
-
Parameters
|
|
22
|
-
----------
|
|
23
|
-
tracts_path : list[pathlib.Path]
|
|
24
|
-
Paths to the tractogram files in order.
|
|
25
|
-
references_path : list[pathlib.Path] | pathlib.Path
|
|
26
|
-
Paths to the NIfTI reference images corresponding to the tractograms.
|
|
27
|
-
If a single path is provided, it is used as the reference for all
|
|
28
|
-
tractograms. If a list, it should be in the same order as tracts_path.
|
|
29
|
-
lesion : nibabel.Nifti1Image
|
|
30
|
-
NIfTI lesion mask. Voxels with values greater than zero are considered
|
|
31
|
-
part of the lesion.
|
|
32
|
-
disc_tracts_out_path : pathlib.Path | None, optional
|
|
33
|
-
Directory where tractograms containing the disconnected streamlines
|
|
34
|
-
are saved. If None, disconnected tractograms are not saved.
|
|
35
|
-
disc_frame_out_path : pathlib.Path | None, optional
|
|
36
|
-
Directory where the resulting CSV file containing the disconnection
|
|
37
|
-
severity for each tract is saved. If None, the results are not saved.
|
|
38
|
-
|
|
39
|
-
Returns
|
|
40
|
-
-------
|
|
41
|
-
pandas.DataFrame
|
|
42
|
-
DataFrame containing the disconnection proportion for each tract,
|
|
43
|
-
together with its tract and pathway (parent directory) names. The ``Discon`` column
|
|
44
|
-
contains the proportion of streamlines intersecting the lesion.
|
|
45
|
-
"""
|
|
46
|
-
|
|
18
|
+
|
|
47
19
|
if disc_tracts_out_path:
|
|
48
20
|
disc_tracts_out_path.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
|
|
49
22
|
disconnections = []
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
23
|
+
|
|
24
|
+
total_start = perf_counter()
|
|
25
|
+
|
|
26
|
+
for i, tract_path in enumerate(tracts_path):
|
|
27
|
+
loop_start = perf_counter()
|
|
28
|
+
|
|
54
29
|
tract_name = tract_path.name.removesuffix(".gz").removesuffix(".trk")
|
|
55
|
-
pathway_name = tract_path.parent.name
|
|
56
|
-
|
|
57
|
-
reference = nib.nifti1.load(reference_path)
|
|
58
|
-
|
|
59
|
-
# grid can differ between lesion and average tracts (due to voxel size notably),
|
|
60
|
-
# resample_from_to shifts/scales the grid of the lesion to match the one of the tract
|
|
61
|
-
lesion_resampled = resample_from_to(lesion,
|
|
62
|
-
reference,
|
|
63
|
-
order=1)
|
|
64
|
-
|
|
65
|
-
lesion_mask = lesion_resampled.get_fdata() > 0
|
|
66
|
-
tract_mask = reference.get_fdata() > 0
|
|
67
|
-
|
|
68
|
-
if not np.any(tract_mask & lesion_mask):
|
|
69
|
-
disconnections.append({
|
|
70
|
-
"Tract": tract_name,
|
|
71
|
-
"Discon": np.round(0.0, 3),
|
|
72
|
-
"Pathway": pathway_name,
|
|
73
|
-
})
|
|
74
|
-
continue
|
|
75
|
-
|
|
76
30
|
if disc_tracts_out_path:
|
|
77
|
-
disconnected_tract_path =
|
|
31
|
+
disconnected_tract_path = (
|
|
32
|
+
disc_tracts_out_path / f"{tract_name}_disconnected.trk"
|
|
33
|
+
)
|
|
78
34
|
else:
|
|
79
35
|
disconnected_tract_path = None
|
|
80
|
-
|
|
81
|
-
tract = get_tract(
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
36
|
+
|
|
37
|
+
tract = get_tract(
|
|
38
|
+
tract_path=tract_path,
|
|
39
|
+
reference_path=reference_path
|
|
40
|
+
)
|
|
41
|
+
disconnected_tract, discon = get_streamlines_disconnection(
|
|
42
|
+
tract=tract,
|
|
43
|
+
lesion=lesion,
|
|
44
|
+
out_path=disconnected_tract_path
|
|
45
|
+
)
|
|
86
46
|
disconnections.append({
|
|
87
47
|
"Tract": tract_name,
|
|
88
|
-
"Discon": np.round(discon, 5)
|
|
89
|
-
"Pathway": pathway_name,
|
|
48
|
+
"Discon": np.round(discon, 5)
|
|
90
49
|
})
|
|
91
|
-
|
|
50
|
+
|
|
51
|
+
print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
52
|
+
f"[{i+1}/{len(tracts_path)}] {tract_path.name} | "
|
|
53
|
+
f"FINISHED | disconnection: {discon:.5f} | elapsed: {perf_counter() - loop_start:.2f}s",
|
|
54
|
+
flush=True)
|
|
55
|
+
|
|
92
56
|
disconnections_frame = pd.DataFrame(disconnections)
|
|
93
|
-
|
|
57
|
+
|
|
94
58
|
if disc_frame_out_path:
|
|
95
59
|
disc_frame_out_path.mkdir(parents=True, exist_ok=True)
|
|
96
60
|
out_csv = disc_frame_out_path / "ratio_discon_tract.csv"
|
|
97
61
|
disconnections_frame.to_csv(out_csv, index=False)
|
|
98
|
-
|
|
99
|
-
return disconnections_frame
|
|
100
62
|
|
|
63
|
+
print(
|
|
64
|
+
f"\n[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
65
|
+
f"ALL TRACTS FINISHED | Total time: {perf_counter() - total_start:.2f}s",
|
|
66
|
+
flush=True
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return disconnections_frame
|
|
101
70
|
|
|
71
|
+
@log_execution
|
|
102
72
|
def get_tracts_disconnections_map(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
out_path
|
|
73
|
+
tdi,
|
|
74
|
+
tdi_disconnected,
|
|
75
|
+
out_path=None
|
|
106
76
|
):
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
tracts : dipy.io.stateful_tractogram.StatefulTractogram
|
|
116
|
-
Tractogram containing all streamlines.
|
|
117
|
-
tracts_disconnected : dipy.io.stateful_tractogram.StatefulTractogram
|
|
118
|
-
Tractogram containing the streamlines disconnected.
|
|
119
|
-
out_path : pathlib.Path | None, optional
|
|
120
|
-
Directory where the TDI images and disconnection map are saved.
|
|
121
|
-
If None, no files are saved.
|
|
122
|
-
|
|
123
|
-
Returns
|
|
124
|
-
-------
|
|
125
|
-
tuple[nibabel.Nifti1Image, nibabel.Nifti1Image, nibabel.Nifti1Image]
|
|
126
|
-
A tuple containing:
|
|
127
|
-
|
|
128
|
-
- disconnections_map : nibabel.Nifti1Image
|
|
129
|
-
Voxel-wise ratio of disconnected to total streamline density.
|
|
130
|
-
- tdi_aggregated : nibabel.Nifti1Image
|
|
131
|
-
Track density image of all streamlines.
|
|
132
|
-
- tdi_disconnected : nibabel.Nifti1Image
|
|
133
|
-
Track density image of disconnected streamlines.
|
|
134
|
-
"""
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if out_path:
|
|
138
|
-
out_path.mkdir(parents=True, exist_ok=True)
|
|
139
|
-
tdi_path = out_path / "tdi.nii.gz"
|
|
140
|
-
tdi_disconnected_path = out_path / "tdi_disconnected.nii.gz"
|
|
141
|
-
else:
|
|
142
|
-
tdi_path = None
|
|
143
|
-
tdi_disconnected_path = None
|
|
144
|
-
|
|
145
|
-
tdi_aggregated = get_tdi(tracts, out_path=tdi_path)
|
|
146
|
-
tdi_disconnected = get_tdi(tracts_disconnected, out_path=tdi_disconnected_path)
|
|
77
|
+
start = perf_counter()
|
|
78
|
+
|
|
79
|
+
print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] Loading TDI data", flush=True)
|
|
80
|
+
|
|
81
|
+
tdi_data = tdi.get_fdata()
|
|
82
|
+
tdi_disconnected_data = tdi_disconnected.get_fdata()
|
|
83
|
+
|
|
84
|
+
print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] Computing disconnection map", flush=True)
|
|
147
85
|
|
|
148
86
|
disconnections_map = np.divide(
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
out=np.zeros_like(
|
|
152
|
-
where=
|
|
87
|
+
tdi_disconnected_data,
|
|
88
|
+
tdi_data,
|
|
89
|
+
out=np.zeros_like(tdi_data, dtype=float),
|
|
90
|
+
where=tdi_data != 0
|
|
153
91
|
)
|
|
154
|
-
|
|
155
|
-
disconnections_map = nib.Nifti1Image(
|
|
156
|
-
|
|
92
|
+
|
|
93
|
+
disconnections_map = nib.Nifti1Image(
|
|
94
|
+
disconnections_map,
|
|
95
|
+
tdi.affine,
|
|
96
|
+
tdi.header
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
print(f"[{datetime.now():%Y-%m-%d %H:%M:%S}] Disconnection map computed", flush=True)
|
|
100
|
+
|
|
157
101
|
if out_path:
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
102
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
nib.nifti1.save(
|
|
104
|
+
disconnections_map,
|
|
105
|
+
out_path / "disconnections_map.nii.gz"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
print(
|
|
109
|
+
f"[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
110
|
+
f"FINISHED | Total time: {perf_counter() - start:.2f}s",
|
|
111
|
+
flush=True
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
return disconnections_map
|
|
@@ -13,7 +13,7 @@ def get_tract(
|
|
|
13
13
|
):
|
|
14
14
|
"""Load a tractogram with the possibility of assigning a new
|
|
15
15
|
NIfTI reference. The reference should be in the same world space
|
|
16
|
-
as the tractogram.
|
|
16
|
+
as the tractogram. The tractogram is then clipped to the reference grid.
|
|
17
17
|
|
|
18
18
|
Parameters
|
|
19
19
|
----------
|
|
@@ -28,18 +28,21 @@ def get_tract(
|
|
|
28
28
|
-------
|
|
29
29
|
dipy.io.stateful_tractogram.StatefulTractogram
|
|
30
30
|
Loaded tractogram, optionally associated with the provided
|
|
31
|
-
reference image.
|
|
31
|
+
reference image, and clipped to its reference space.
|
|
32
32
|
"""
|
|
33
33
|
|
|
34
34
|
tract = load_tractogram(filename=tract_path,
|
|
35
35
|
reference="same",
|
|
36
|
-
bbox_valid_check=False
|
|
36
|
+
bbox_valid_check=False,
|
|
37
|
+
to_space=Space.RASMM,
|
|
38
|
+
trk_header_check=True)
|
|
37
39
|
if reference_path:
|
|
38
40
|
reference = nib.nifti1.load(reference_path)
|
|
39
41
|
tract = StatefulTractogram(tract.streamlines,
|
|
40
42
|
reference=reference,
|
|
41
43
|
space=Space.RASMM)
|
|
42
|
-
|
|
44
|
+
|
|
45
|
+
return clip_tractogram_to_grid(tract)
|
|
43
46
|
|
|
44
47
|
|
|
45
48
|
def get_aggregated_tracts(
|
|
@@ -55,7 +58,7 @@ def get_aggregated_tracts(
|
|
|
55
58
|
Paths to the tractogram files to aggregate.
|
|
56
59
|
reference_path : pathlib.Path | None, optional
|
|
57
60
|
Path to a NIfTI image to use as the reference for all tractograms.
|
|
58
|
-
If not provided, the
|
|
61
|
+
If not provided, the last loaded tractogram is used as the reference.
|
|
59
62
|
out_path : pathlib.Path | None, optional
|
|
60
63
|
Path where the aggregated tractogram should be saved. If None,
|
|
61
64
|
the tractogram is not saved.
|
|
@@ -64,7 +67,7 @@ def get_aggregated_tracts(
|
|
|
64
67
|
-------
|
|
65
68
|
dipy.io.stateful_tractogram.StatefulTractogram
|
|
66
69
|
Aggregated tractogram containing the streamlines from all input
|
|
67
|
-
tractograms
|
|
70
|
+
tractograms.
|
|
68
71
|
"""
|
|
69
72
|
|
|
70
73
|
streamlines = []
|
|
@@ -75,7 +78,7 @@ def get_aggregated_tracts(
|
|
|
75
78
|
reference = None
|
|
76
79
|
|
|
77
80
|
for tract_path in tracts_pathlist:
|
|
78
|
-
tract = get_tract(tract_path,
|
|
81
|
+
tract = get_tract(tract_path, reference_path)
|
|
79
82
|
streamlines.extend(tract.streamlines)
|
|
80
83
|
|
|
81
84
|
if reference is None:
|
|
@@ -84,8 +87,6 @@ def get_aggregated_tracts(
|
|
|
84
87
|
reference,
|
|
85
88
|
space=Space.RASMM)
|
|
86
89
|
|
|
87
|
-
aggregated_tracts = clip_tractogram_to_grid(aggregated_tracts)
|
|
88
|
-
|
|
89
90
|
if out_path:
|
|
90
91
|
save_tractogram(aggregated_tracts,
|
|
91
92
|
out_path,
|
|
@@ -121,10 +122,11 @@ def clip_streamline_to_grid(
|
|
|
121
122
|
)) @ inv_affine.T
|
|
122
123
|
|
|
123
124
|
voxel = voxel[:, :3]
|
|
124
|
-
|
|
125
|
+
voxel_indices = np.floor(voxel + 0.5).astype(int)
|
|
126
|
+
|
|
125
127
|
valid = np.all(
|
|
126
|
-
(
|
|
127
|
-
(
|
|
128
|
+
(voxel_indices >= 0) &
|
|
129
|
+
(voxel_indices < shape),
|
|
128
130
|
axis=1
|
|
129
131
|
)
|
|
130
132
|
|
|
@@ -172,7 +174,7 @@ def get_streamlines_disconnection(
|
|
|
172
174
|
tract,
|
|
173
175
|
lesion,
|
|
174
176
|
out_path=None
|
|
175
|
-
):
|
|
177
|
+
):
|
|
176
178
|
"""Return the streamlines intersecting a lesion and compute the proportion
|
|
177
179
|
of streamlines intersecting this lesion.
|
|
178
180
|
|
|
@@ -235,10 +237,10 @@ def get_tdi(
|
|
|
235
237
|
NIfTI image containing the number of streamlines passing through
|
|
236
238
|
each voxel.
|
|
237
239
|
"""
|
|
238
|
-
|
|
240
|
+
|
|
239
241
|
tdi = density_map(tract.streamlines, tract.affine, tract.space_attributes[1])
|
|
240
242
|
tdi = nib.Nifti1Image(tdi.astype("uint32"), tract.affine)
|
|
241
243
|
if out_path:
|
|
242
244
|
nib.nifti1.save(tdi, out_path)
|
|
243
245
|
|
|
244
|
-
return tdi
|
|
246
|
+
return tdi
|
pyLQT/pipeline.py
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
from pyLQT.lesion_metrics.white_matter.metrics import get_tracts_disconnections_severity, get_tracts_disconnections_map
|
|
2
|
-
from pyLQT.lesion_metrics.white_matter.utils import get_streamlines_disconnection, get_aggregated_tracts, clip_tractogram_to_grid
|
|
2
|
+
from pyLQT.lesion_metrics.white_matter.utils import get_streamlines_disconnection, get_aggregated_tracts, clip_tractogram_to_grid, get_tdi
|
|
3
3
|
from pyLQT.lesion_metrics.network.metrics import get_sspl_increase, get_parcel_wise_disconnection_severity
|
|
4
4
|
from pyLQT.lesion_metrics.network.utils import create_structural_connectivity
|
|
5
5
|
from pyLQT.lesion_metrics.grey_matter.metrics import get_parcel_damage
|
|
6
6
|
from pyLQT.lesion_metrics.utils.configs import atlas_cfg_read, tracts_cfg_read, lesion_cfg_read
|
|
7
|
-
from pyLQT.lesion_metrics.utils.downloads import default_tracts_download, default_atlas_download,
|
|
8
|
-
from pyLQT.lesion_metrics.utils.registration import register_affine, register_syn
|
|
7
|
+
from pyLQT.lesion_metrics.utils.downloads import default_tracts_download, default_atlas_download, uncompress_trk_gz, get_ref_space_tf
|
|
8
|
+
from pyLQT.lesion_metrics.utils.registration import register_affine, register_syn, apply_registration
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
|
|
11
|
-
import numpy as np
|
|
12
11
|
import nibabel as nib
|
|
13
12
|
import shutil
|
|
14
13
|
import tempfile
|
|
@@ -22,7 +21,7 @@ def run_pyLQT(
|
|
|
22
21
|
sc_distance_threshold=5.0,
|
|
23
22
|
spared_threshold=0.5,
|
|
24
23
|
delete_tmp=False,
|
|
25
|
-
):
|
|
24
|
+
):
|
|
26
25
|
"""Run the pyLQT lesion quantification pipeline.
|
|
27
26
|
|
|
28
27
|
Parameters
|
|
@@ -73,7 +72,17 @@ def run_pyLQT(
|
|
|
73
72
|
|
|
74
73
|
lesion_cohort_name, lesion_folder, lesion_space = lesion_cfg_read(lesion_cfg_path)
|
|
75
74
|
atlas_name, atlas, atlas_labels, atlas_space = atlas_cfg_read(atlas_cfg_path)
|
|
76
|
-
tracts_name, tracts_folder,
|
|
75
|
+
tracts_name, tracts_folder, tracts_space = (tracts_cfg_read(tracts_cfg_path))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
tracts_pathlist = []
|
|
79
|
+
for tract_path in tracts_folder.rglob("*"):
|
|
80
|
+
if tract_path.name.endswith((".trk.gz", ".trk")):
|
|
81
|
+
relative_path = tract_path.relative_to(tracts_folder)
|
|
82
|
+
out_path = tmp_folder / f"{tracts_name}_uncompressed" / relative_path.with_suffix("")
|
|
83
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
tracts_pathlist.append(uncompress_trk_gz(tract_path, out_path))
|
|
85
|
+
|
|
77
86
|
|
|
78
87
|
if lesion_space.endswith((".nii.gz", ".nii")):
|
|
79
88
|
lesion_ref_space = nib.load(lesion_space)
|
|
@@ -87,47 +96,42 @@ def run_pyLQT(
|
|
|
87
96
|
|
|
88
97
|
if tracts_space.endswith((".nii.gz", ".nii")):
|
|
89
98
|
tracts_ref_space = nib.load(tracts_space)
|
|
99
|
+
reference_path = tracts_space
|
|
90
100
|
else:
|
|
91
101
|
tracts_ref_space = get_ref_space_tf(tracts_space)
|
|
102
|
+
reference_path = tmp_folder / "tracts_reference.nii.gz"
|
|
103
|
+
nib.save(tracts_ref_space, reference_path)
|
|
92
104
|
|
|
93
105
|
registrator = (register_affine if registration_type == "affine" else register_syn)
|
|
94
106
|
|
|
95
107
|
lesion_tracts_mapping = registrator(lesion_ref_space, tracts_ref_space)
|
|
96
108
|
atlas_tracts_mapping = registrator(atlas_ref_space, tracts_ref_space)
|
|
97
109
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
110
|
+
atlas_trans = apply_registration(
|
|
111
|
+
atlas,
|
|
112
|
+
tracts_ref_space,
|
|
113
|
+
atlas_tracts_mapping,
|
|
114
|
+
interpolation="genericLabel"
|
|
103
115
|
)
|
|
104
116
|
nib.save(atlas_trans, tmp_folder / "atlas_trans.nii.gz")
|
|
105
|
-
|
|
106
|
-
tracts_pathlist_gz, references_pathlist = create_tract_list(
|
|
107
|
-
references_folder=references_folder,
|
|
108
|
-
tracts_folder=tracts_folder,
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
tracts_pathlist = []
|
|
112
|
-
for tract_path in tracts_pathlist_gz:
|
|
113
|
-
relative_path = tract_path.relative_to(tracts_folder)
|
|
114
|
-
out_path = tmp_folder / relative_path.with_suffix("")
|
|
115
|
-
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
116
|
-
|
|
117
|
-
tracts_pathlist.append(uncompress_trk_gz(tract_path, out_path))
|
|
118
|
-
|
|
117
|
+
|
|
119
118
|
aggregated_tracts_path = tmp_folder / "aggregated_tracts.trk"
|
|
120
119
|
aggregated_tracts = get_aggregated_tracts(
|
|
121
120
|
tracts_pathlist=tracts_pathlist,
|
|
121
|
+
reference_path=reference_path,
|
|
122
122
|
out_path=aggregated_tracts_path,
|
|
123
123
|
)
|
|
124
124
|
|
|
125
125
|
structural_connectivity_aggregated = create_structural_connectivity(
|
|
126
126
|
tract=aggregated_tracts,
|
|
127
127
|
atlas_resampled=atlas_trans,
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
128
|
+
threshold=sc_distance_threshold,
|
|
129
|
+
out_path=out_folder / f"{tracts_name}_structural_connectivity.npy"
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
tdi_aggregated_path = out_folder / f"{tracts_name}_tdi_aggregated.nii.gz"
|
|
133
|
+
tdi_aggregated = get_tdi(aggregated_tracts, out_path=tdi_aggregated_path)
|
|
134
|
+
|
|
131
135
|
|
|
132
136
|
for lesion_path in lesion_folder.glob("*.nii*"):
|
|
133
137
|
lesion_name = lesion_path.name.removesuffix(".nii.gz").removesuffix(".nii")
|
|
@@ -138,11 +142,11 @@ def run_pyLQT(
|
|
|
138
142
|
tmp_dir.mkdir(parents=True, exist_ok=True)
|
|
139
143
|
|
|
140
144
|
lesion = nib.load(lesion_path)
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
145
|
+
lesion_trans = apply_registration(
|
|
146
|
+
lesion,
|
|
147
|
+
tracts_ref_space,
|
|
148
|
+
lesion_tracts_mapping,
|
|
149
|
+
interpolation="nearestNeighbor"
|
|
146
150
|
)
|
|
147
151
|
nib.save(lesion_trans, tmp_dir / "lesion_trans.nii.gz")
|
|
148
152
|
|
|
@@ -153,13 +157,18 @@ def run_pyLQT(
|
|
|
153
157
|
out_path=aggregated_tracts_disconnected_path,
|
|
154
158
|
)
|
|
155
159
|
aggregated_tracts_disconnected = clip_tractogram_to_grid(aggregated_tracts_disconnected)
|
|
160
|
+
|
|
161
|
+
(out_dir / "parcel_wise_disconnection_severity").mkdir(parents=True, exist_ok=True)
|
|
156
162
|
structural_connectivity_disconnected = create_structural_connectivity(
|
|
157
163
|
tract=aggregated_tracts_disconnected,
|
|
158
164
|
atlas_resampled=atlas_trans,
|
|
159
|
-
|
|
165
|
+
threshold=sc_distance_threshold,
|
|
166
|
+
out_path=out_dir / "parcel_wise_disconnection_severity" / "structural_connectivity_disconnected.npy"
|
|
160
167
|
)
|
|
161
|
-
|
|
162
|
-
|
|
168
|
+
|
|
169
|
+
(out_dir / "wm_disconnections_map").mkdir(parents=True, exist_ok=True)
|
|
170
|
+
tdi_aggregated_disconnected_path = out_dir / "wm_disconnections_map" / f"{tracts_name}_tdi_disconnected.nii.gz"
|
|
171
|
+
tdi_aggregated_disconnected = get_tdi(aggregated_tracts_disconnected, out_path=tdi_aggregated_disconnected_path)
|
|
163
172
|
|
|
164
173
|
get_parcel_damage(
|
|
165
174
|
lesion=lesion_trans,
|
|
@@ -171,15 +180,15 @@ def run_pyLQT(
|
|
|
171
180
|
|
|
172
181
|
get_tracts_disconnections_severity(
|
|
173
182
|
tracts_path=tracts_pathlist,
|
|
174
|
-
|
|
183
|
+
reference_path=reference_path,
|
|
175
184
|
lesion=lesion_trans,
|
|
176
185
|
disc_tracts_out_path=tmp_dir / "wm_disconnections_severity",
|
|
177
186
|
disc_frame_out_path=out_dir / "wm_disconnections_severity",
|
|
178
187
|
)
|
|
179
188
|
|
|
180
189
|
get_tracts_disconnections_map(
|
|
181
|
-
|
|
182
|
-
|
|
190
|
+
tdi=tdi_aggregated,
|
|
191
|
+
tdi_disconnected=tdi_aggregated_disconnected,
|
|
183
192
|
out_path=out_dir / "wm_disconnections_map",
|
|
184
193
|
)
|
|
185
194
|
|
pyLQT/utils/__init__.py
ADDED
|
File without changes
|
pyLQT/utils/logs.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from functools import wraps
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from time import perf_counter
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def log_execution(func):
|
|
7
|
+
@wraps(func)
|
|
8
|
+
def wrapper(*args, **kwargs):
|
|
9
|
+
|
|
10
|
+
start_time = perf_counter()
|
|
11
|
+
|
|
12
|
+
print(
|
|
13
|
+
f"\n[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
14
|
+
f"STARTED | {func.__name__}",
|
|
15
|
+
flush=True
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
result = func(*args, **kwargs)
|
|
20
|
+
|
|
21
|
+
print(
|
|
22
|
+
f"\n[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
23
|
+
f"FINISHED | {func.__name__} | "
|
|
24
|
+
f"Total time: {perf_counter() - start_time:.2f}s",
|
|
25
|
+
flush=True
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
return result
|
|
29
|
+
|
|
30
|
+
except Exception as e:
|
|
31
|
+
print(
|
|
32
|
+
f"\n[{datetime.now():%Y-%m-%d %H:%M:%S}] "
|
|
33
|
+
f"FAILED | {func.__name__} | "
|
|
34
|
+
f"Error: {e} | "
|
|
35
|
+
f"Elapsed: {perf_counter() - start_time:.2f}s",
|
|
36
|
+
flush=True
|
|
37
|
+
)
|
|
38
|
+
raise
|
|
39
|
+
|
|
40
|
+
return wrapper
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyLQT
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.dev9
|
|
4
4
|
Summary: Python version of LQT from Griffis et al. 2021 (https://www.sciencedirect.com/science/article/pii/S2213158221000838)
|
|
5
5
|
Author-email: Antonin HUDRY <hudryantoninm@gmail.com>
|
|
6
6
|
License-Expression: GPL-3.0-only
|
|
@@ -9,17 +9,19 @@ Classifier: Development Status :: 2 - Pre-Alpha
|
|
|
9
9
|
Classifier: Intended Audience :: Science/Research
|
|
10
10
|
Classifier: Intended Audience :: Healthcare Industry
|
|
11
11
|
Classifier: Programming Language :: Python
|
|
12
|
-
Requires-Python: >=3.
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
13
|
Description-Content-Type: text/markdown
|
|
14
14
|
License-File: LICENSE
|
|
15
|
-
Requires-Dist: numpy
|
|
15
|
+
Requires-Dist: numpy==2.6.4
|
|
16
16
|
Requires-Dist: nibabel>5.0
|
|
17
17
|
Requires-Dist: pandas>3.0
|
|
18
|
+
Requires-Dist: napari[all]
|
|
18
19
|
Requires-Dist: scipy>1.15
|
|
19
20
|
Requires-Dist: requests>2.0
|
|
20
21
|
Requires-Dist: dipy>1.10
|
|
21
22
|
Requires-Dist: templateflow
|
|
22
23
|
Requires-Dist: networkx>=3.6.1
|
|
24
|
+
Requires-Dist: antspyx
|
|
23
25
|
Dynamic: license-file
|
|
24
26
|
|
|
25
27
|
# pyLQT
|
|
@@ -64,20 +66,19 @@ Specifies the atlas NIfTI file, its corresponding label CSV, and its reference s
|
|
|
64
66
|
{
|
|
65
67
|
"name": "glasser360",
|
|
66
68
|
"atlas": "glasser360.nii.gz",
|
|
67
|
-
"
|
|
69
|
+
"labels": "glasser360_labels.csv",
|
|
68
70
|
"space": "MNI152NLin2009cAsym"
|
|
69
71
|
}
|
|
70
72
|
```
|
|
71
73
|
|
|
72
74
|
##### Tractography configuration
|
|
73
75
|
|
|
74
|
-
Specifies the tractography dataset, the folder containing its `.trk`
|
|
76
|
+
Specifies the tractography dataset, the folder containing its `.trk` or `.trk.gz` files, and its reference space.
|
|
75
77
|
|
|
76
78
|
```json
|
|
77
79
|
{
|
|
78
80
|
"name": "HCP1065",
|
|
79
81
|
"tracts": "hcp1065_avg_tracts_trk",
|
|
80
|
-
"references": "hcp1065_avg_tracts",
|
|
81
82
|
"space": "MNI152NLin2009aAsym"
|
|
82
83
|
}
|
|
83
84
|
```
|
|
@@ -104,6 +105,7 @@ pyLQT --lesion_cfg <path/to/lesion_config> --out_folder <path/to/outputs>
|
|
|
104
105
|
| `--tracts_cfg` | `None` | Path to a `.json` file or `None` | Path to the tracts configuration file. |
|
|
105
106
|
| `--out_folder` | — | Path to a directory | Path to the output folder. |
|
|
106
107
|
| `--registration_type` | `syn` | `syn`, `affine` | Registration type used to transform the lesion and atlas from their respective spaces to tract space. |
|
|
108
|
+
|`--sc_distance_threshold` | `5.0` | Float above `0.0` | Threshold for distance filtering of tracts endpoints in structural connectivity computation. |
|
|
107
109
|
| `--spared_threshold` | `0.5` | Float between `0` and `1` | Threshold used to define spared parcel-to-parcel connectivity. |
|
|
108
110
|
| `--delete_tmp` | `True` | `True`, `False` | Whether to delete temporary files generated during processing. |
|
|
109
111
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
pyLQT/__init__.py,sha256=y4DvjD5OqKInZ-wJary448UmEBajl8gNbZv50dgabwI,58
|
|
2
|
+
pyLQT/cli.py,sha256=zoDxM5qHvAn63b7hFBMtXpV4gaR26K0l2aGmn6lgBNg,2231
|
|
3
|
+
pyLQT/pipeline.py,sha256=ZBixWXHwAQ_yOmunB9DDAZ5wNLbukdeaoSWjeuY0XwQ,8820
|
|
4
|
+
pyLQT/lesion_metrics/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
pyLQT/lesion_metrics/grey_matter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
pyLQT/lesion_metrics/grey_matter/metrics.py,sha256=V1N-jsP6gyIjqUSVN2RfImd80FhfKujIx8F2z5hU4f0,2742
|
|
7
|
+
pyLQT/lesion_metrics/grey_matter/utils.py,sha256=czxyAESP0neVCue424L0hon-5Tdbsl0pN0zJHWG5HiQ,840
|
|
8
|
+
pyLQT/lesion_metrics/network/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
pyLQT/lesion_metrics/network/metrics.py,sha256=4pTyuDzsKjUtXRw7Vkhubc4T3pquJH6gE4GiildfZLk,6328
|
|
10
|
+
pyLQT/lesion_metrics/network/utils.py,sha256=UIxyt5f5lAFxjrQm-h8OWJrh5dT7pVtLtg6a5X2TKZM,3756
|
|
11
|
+
pyLQT/lesion_metrics/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
pyLQT/lesion_metrics/utils/configs.py,sha256=O99LXOgt2OOBhsiMvcaQFSQ7_dJbipLp6ljOrIhfub0,4790
|
|
13
|
+
pyLQT/lesion_metrics/utils/downloads.py,sha256=kHAXsUkUy4qJfvrwGlW9oBXSopeqa8i6rZDtYVlUKHA,8777
|
|
14
|
+
pyLQT/lesion_metrics/utils/registration.py,sha256=3nlT5zFjRIrM_hIppiEGplwuFFWHhYjn0yGwz7VHE1k,6085
|
|
15
|
+
pyLQT/lesion_metrics/white_matter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
+
pyLQT/lesion_metrics/white_matter/metrics.py,sha256=0Y3Z0NyrUiFuPWsQwgZPAXViPv_NngznR3dTIAQ9_Tw,3327
|
|
17
|
+
pyLQT/lesion_metrics/white_matter/utils.py,sha256=t4jlRixY6rsHBZt3wu1CDEIHRHvrqQmf_iQb5u24rF0,7507
|
|
18
|
+
pyLQT/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
|
+
pyLQT/utils/logs.py,sha256=KhMEKiTcE8ghTSvXdukIcAVyEhDiSPJfAY-fEFKRxSE,1040
|
|
20
|
+
pylqt-1.0.dev9.dist-info/licenses/LICENSE,sha256=IwGE9guuL-ryRPEKi6wFPI_zOhg7zDZbTYuHbSt_SAk,35823
|
|
21
|
+
pylqt-1.0.dev9.dist-info/METADATA,sha256=zcvEboiMr0B5IanyZOvkexJNW_MR5U9vsXldJDPIFT4,5371
|
|
22
|
+
pylqt-1.0.dev9.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
23
|
+
pylqt-1.0.dev9.dist-info/entry_points.txt,sha256=GHGfSFJ0r77qGtkRMJeCuNj2YHm5aynNxdi3JXxyyCc,41
|
|
24
|
+
pylqt-1.0.dev9.dist-info/top_level.txt,sha256=TwID1Q-SuDZ2HjBLKSwruNTXKrRGgAh16rMZ5pjUk4U,6
|
|
25
|
+
pylqt-1.0.dev9.dist-info/RECORD,,
|
pylqt-1.0.dev7.dist-info/RECORD
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
pyLQT/__init__.py,sha256=y4DvjD5OqKInZ-wJary448UmEBajl8gNbZv50dgabwI,58
|
|
2
|
-
pyLQT/cli.py,sha256=vygYi7RgTPWshEPUuMzo2b34WGnUSkSstEYMwN1Nqbc,2125
|
|
3
|
-
pyLQT/pipeline.py,sha256=ftCeVXENUxAxA4hakIimPpgTwOFf-maPYTSEqlLr2lY,8399
|
|
4
|
-
pyLQT/lesion_metrics/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
-
pyLQT/lesion_metrics/grey_matter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
-
pyLQT/lesion_metrics/grey_matter/metrics.py,sha256=IDMxnitRetgGUgNZRSG2hlmM790iVggvPLOdNPD7wgE,2770
|
|
7
|
-
pyLQT/lesion_metrics/grey_matter/utils.py,sha256=czxyAESP0neVCue424L0hon-5Tdbsl0pN0zJHWG5HiQ,840
|
|
8
|
-
pyLQT/lesion_metrics/network/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
-
pyLQT/lesion_metrics/network/metrics.py,sha256=kEhn7ZTJqI0FtBiGqib9fAC-TRgRMIDrEv5ecO6loZY,6254
|
|
10
|
-
pyLQT/lesion_metrics/network/utils.py,sha256=UIxyt5f5lAFxjrQm-h8OWJrh5dT7pVtLtg6a5X2TKZM,3756
|
|
11
|
-
pyLQT/lesion_metrics/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
-
pyLQT/lesion_metrics/utils/configs.py,sha256=TJ6dg93NlHl8cIQFh0hzbvsEaVhah4c54KABOjkZa-E,4985
|
|
13
|
-
pyLQT/lesion_metrics/utils/downloads.py,sha256=nKYlDdkzySMTGCGkU1SmlHTpADwX_KbUJ8hG357XfXk,10539
|
|
14
|
-
pyLQT/lesion_metrics/utils/registration.py,sha256=rSZbzEPw4K2R-wASXdTeG7_sJAjyaXxwK0emEGbxiQM,3345
|
|
15
|
-
pyLQT/lesion_metrics/white_matter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
16
|
-
pyLQT/lesion_metrics/white_matter/metrics.py,sha256=aBe350-cQIGuqOy08GOeNTD03SP30byVslVAWFVIgRs,6275
|
|
17
|
-
pyLQT/lesion_metrics/white_matter/utils.py,sha256=iuu2-03E4di4Yc2PcxDNEr58xiSd-suSejkfzqN2e5c,7309
|
|
18
|
-
pylqt-1.0.dev7.dist-info/licenses/LICENSE,sha256=IwGE9guuL-ryRPEKi6wFPI_zOhg7zDZbTYuHbSt_SAk,35823
|
|
19
|
-
pylqt-1.0.dev7.dist-info/METADATA,sha256=ajHTKSCY0abLdJunchkm7wMd60JVKZQeVYkegnXfFug,5246
|
|
20
|
-
pylqt-1.0.dev7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
-
pylqt-1.0.dev7.dist-info/entry_points.txt,sha256=GHGfSFJ0r77qGtkRMJeCuNj2YHm5aynNxdi3JXxyyCc,41
|
|
22
|
-
pylqt-1.0.dev7.dist-info/top_level.txt,sha256=TwID1Q-SuDZ2HjBLKSwruNTXKrRGgAh16rMZ5pjUk4U,6
|
|
23
|
-
pylqt-1.0.dev7.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|