pyLQT 1.0.dev8__tar.gz → 1.0.dev10__tar.gz

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.
Files changed (31) hide show
  1. {pylqt-1.0.dev8/src/pyLQT.egg-info → pylqt-1.0.dev10}/PKG-INFO +9 -6
  2. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/README.md +4 -3
  3. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/pyproject.toml +5 -3
  4. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/cli.py +2 -0
  5. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/grey_matter/metrics.py +3 -3
  6. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/network/metrics.py +3 -1
  7. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/utils/configs.py +8 -10
  8. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/utils/downloads.py +75 -133
  9. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/utils/registration.py +104 -1
  10. pylqt-1.0.dev10/src/pyLQT/lesion_metrics/white_matter/metrics.py +114 -0
  11. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/white_matter/utils.py +17 -15
  12. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/pipeline.py +30 -29
  13. pylqt-1.0.dev10/src/pyLQT/utils/__init__.py +0 -0
  14. pylqt-1.0.dev10/src/pyLQT/utils/logs.py +40 -0
  15. {pylqt-1.0.dev8 → pylqt-1.0.dev10/src/pyLQT.egg-info}/PKG-INFO +9 -6
  16. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT.egg-info/SOURCES.txt +3 -1
  17. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT.egg-info/requires.txt +3 -1
  18. pylqt-1.0.dev8/src/pyLQT/lesion_metrics/white_matter/metrics.py +0 -142
  19. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/LICENSE +0 -0
  20. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/setup.cfg +0 -0
  21. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/__init__.py +0 -0
  22. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/__init__.py +0 -0
  23. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/grey_matter/__init__.py +0 -0
  24. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/grey_matter/utils.py +0 -0
  25. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/network/__init__.py +0 -0
  26. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/network/utils.py +0 -0
  27. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/utils/__init__.py +0 -0
  28. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT/lesion_metrics/white_matter/__init__.py +0 -0
  29. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT.egg-info/dependency_links.txt +0 -0
  30. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT.egg-info/entry_points.txt +0 -0
  31. {pylqt-1.0.dev8 → pylqt-1.0.dev10}/src/pyLQT.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyLQT
3
- Version: 1.0.dev8
3
+ Version: 1.0.dev10
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.10
12
+ Requires-Python: >=3.11
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
- Requires-Dist: numpy<2.0
15
+ Requires-Dist: numpy>2.0
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
- "atlas_labels": "glasser360_labels.csv",
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` files, the folder containing its reference NIfTI files, and its reference space.
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
 
@@ -122,6 +124,7 @@ pyLQT relies on the following libraries:
122
124
  - `dipy`
123
125
  - `templateflow`
124
126
  - `networkx`
127
+ - `antspyx`
125
128
 
126
129
 
127
130
  ## Links
@@ -40,20 +40,19 @@ Specifies the atlas NIfTI file, its corresponding label CSV, and its reference s
40
40
  {
41
41
  "name": "glasser360",
42
42
  "atlas": "glasser360.nii.gz",
43
- "atlas_labels": "glasser360_labels.csv",
43
+ "labels": "glasser360_labels.csv",
44
44
  "space": "MNI152NLin2009cAsym"
45
45
  }
46
46
  ```
47
47
 
48
48
  ##### Tractography configuration
49
49
 
50
- Specifies the tractography dataset, the folder containing its `.trk` files, the folder containing its reference NIfTI files, and its reference space.
50
+ Specifies the tractography dataset, the folder containing its `.trk` or `.trk.gz` files, and its reference space.
51
51
 
52
52
  ```json
53
53
  {
54
54
  "name": "HCP1065",
55
55
  "tracts": "hcp1065_avg_tracts_trk",
56
- "references": "hcp1065_avg_tracts",
57
56
  "space": "MNI152NLin2009aAsym"
58
57
  }
59
58
  ```
@@ -80,6 +79,7 @@ pyLQT --lesion_cfg <path/to/lesion_config> --out_folder <path/to/outputs>
80
79
  | `--tracts_cfg` | `None` | Path to a `.json` file or `None` | Path to the tracts configuration file. |
81
80
  | `--out_folder` | — | Path to a directory | Path to the output folder. |
82
81
  | `--registration_type` | `syn` | `syn`, `affine` | Registration type used to transform the lesion and atlas from their respective spaces to tract space. |
82
+ |`--sc_distance_threshold` | `5.0` | Float above `0.0` | Threshold for distance filtering of tracts endpoints in structural connectivity computation. |
83
83
  | `--spared_threshold` | `0.5` | Float between `0` and `1` | Threshold used to define spared parcel-to-parcel connectivity. |
84
84
  | `--delete_tmp` | `True` | `True`, `False` | Whether to delete temporary files generated during processing. |
85
85
 
@@ -98,6 +98,7 @@ pyLQT relies on the following libraries:
98
98
  - `dipy`
99
99
  - `templateflow`
100
100
  - `networkx`
101
+ - `antspyx`
101
102
 
102
103
 
103
104
  ## Links
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  name = "pyLQT"
7
7
  keywords = ["LQT", "lqt", "lesion", "brain", ""]
8
- version = "1.0.dev8"
8
+ version = "1.0.dev10"
9
9
  authors = [
10
10
  {name="Antonin HUDRY", email="hudryantoninm@gmail.com"},
11
11
  ]
@@ -19,16 +19,18 @@ classifiers = [
19
19
  ]
20
20
 
21
21
  readme = "README.md"
22
- requires-python = ">=3.10"
22
+ requires-python = ">=3.11"
23
23
  dependencies = [
24
- "numpy<2.0",
24
+ "numpy>2.0",
25
25
  "nibabel>5.0",
26
26
  "pandas>3.0",
27
+ "napari[all]",
27
28
  "scipy>1.15",
28
29
  "requests>2.0",
29
30
  "dipy>1.10",
30
31
  "templateflow",
31
32
  "networkx>=3.6.1",
33
+ "antspyx",
32
34
  ]
33
35
 
34
36
  license = "GPL-3.0-only"
@@ -44,12 +44,14 @@ def main():
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
  )
@@ -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,
@@ -76,5 +77,4 @@ def get_parcel_damage(
76
77
  if out_path:
77
78
  damage_frame.to_csv(out_path / 'parcel_damage_frame.csv', index=False)
78
79
 
79
- return damage_frame
80
-
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
- - atlas_labels : pandas.DataFrame
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, references_folder, tracts_space
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 their
208
- corresponding NIfTI reference images and creates a default configuration
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
- default_atlas_download(Path("D:/internship_myspace_lab/pyLQT/test_download_atlas"))
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)
@@ -0,0 +1,114 @@
1
+ import nibabel as nib
2
+ import pandas as pd
3
+ import numpy as np
4
+
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
9
+
10
+ @log_execution
11
+ def get_tracts_disconnections_severity(
12
+ tracts_path,
13
+ reference_path,
14
+ lesion,
15
+ disc_tracts_out_path=None,
16
+ disc_frame_out_path=None
17
+ ):
18
+
19
+ if disc_tracts_out_path:
20
+ disc_tracts_out_path.mkdir(parents=True, exist_ok=True)
21
+
22
+ disconnections = []
23
+
24
+ total_start = perf_counter()
25
+
26
+ for i, tract_path in enumerate(tracts_path):
27
+ loop_start = perf_counter()
28
+
29
+ tract_name = tract_path.name.removesuffix(".gz").removesuffix(".trk")
30
+ if disc_tracts_out_path:
31
+ disconnected_tract_path = (
32
+ disc_tracts_out_path / f"{tract_name}_disconnected.trk"
33
+ )
34
+ else:
35
+ disconnected_tract_path = None
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
+ )
46
+ disconnections.append({
47
+ "Tract": tract_name,
48
+ "Discon": np.round(discon, 5)
49
+ })
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
+
56
+ disconnections_frame = pd.DataFrame(disconnections)
57
+
58
+ if disc_frame_out_path:
59
+ disc_frame_out_path.mkdir(parents=True, exist_ok=True)
60
+ out_csv = disc_frame_out_path / "ratio_discon_tract.csv"
61
+ disconnections_frame.to_csv(out_csv, index=False)
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
70
+
71
+ @log_execution
72
+ def get_tracts_disconnections_map(
73
+ tdi,
74
+ tdi_disconnected,
75
+ out_path=None
76
+ ):
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)
85
+
86
+ disconnections_map = np.divide(
87
+ tdi_disconnected_data,
88
+ tdi_data,
89
+ out=np.zeros_like(tdi_data, dtype=float),
90
+ where=tdi_data != 0
91
+ )
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
+
101
+ if out_path:
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
- return tract
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 first loaded tractogram is used as the reference.
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, clipped to the reference image grid.
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, reference)
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
- (voxel >= 0) &
127
- (voxel < shape),
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
@@ -4,8 +4,8 @@ from pyLQT.lesion_metrics.network.metrics import get_sspl_increase, get_parcel_w
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, create_tract_list, uncompress_trk_gz, get_ref_space_tf
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
11
  import nibabel as nib
@@ -21,7 +21,7 @@ def run_pyLQT(
21
21
  sc_distance_threshold=5.0,
22
22
  spared_threshold=0.5,
23
23
  delete_tmp=False,
24
- ):
24
+ ):
25
25
  """Run the pyLQT lesion quantification pipeline.
26
26
 
27
27
  Parameters
@@ -72,7 +72,17 @@ def run_pyLQT(
72
72
 
73
73
  lesion_cohort_name, lesion_folder, lesion_space = lesion_cfg_read(lesion_cfg_path)
74
74
  atlas_name, atlas, atlas_labels, atlas_space = atlas_cfg_read(atlas_cfg_path)
75
- tracts_name, tracts_folder, references_folder, tracts_space = (tracts_cfg_read(tracts_cfg_path))
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
+
76
86
 
77
87
  if lesion_space.endswith((".nii.gz", ".nii")):
78
88
  lesion_ref_space = nib.load(lesion_space)
@@ -86,38 +96,29 @@ def run_pyLQT(
86
96
 
87
97
  if tracts_space.endswith((".nii.gz", ".nii")):
88
98
  tracts_ref_space = nib.load(tracts_space)
99
+ reference_path = tracts_space
89
100
  else:
90
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)
91
104
 
92
105
  registrator = (register_affine if registration_type == "affine" else register_syn)
93
106
 
94
107
  lesion_tracts_mapping = registrator(lesion_ref_space, tracts_ref_space)
95
108
  atlas_tracts_mapping = registrator(atlas_ref_space, tracts_ref_space)
96
109
 
97
- atlas_trans_volume = atlas_tracts_mapping.transform(atlas.get_fdata(), interpolation="nearest")
98
- atlas_trans = nib.Nifti1Image(
99
- atlas_trans_volume,
100
- tracts_ref_space.affine,
101
- tracts_ref_space.header,
110
+ atlas_trans = apply_registration(
111
+ atlas,
112
+ tracts_ref_space,
113
+ atlas_tracts_mapping,
114
+ interpolation="genericLabel"
102
115
  )
103
116
  nib.save(atlas_trans, tmp_folder / "atlas_trans.nii.gz")
104
-
105
- tracts_pathlist_gz, references_pathlist = create_tract_list(
106
- references_folder=references_folder,
107
- tracts_folder=tracts_folder,
108
- )
109
-
110
- tracts_pathlist = []
111
- for tract_path in tracts_pathlist_gz:
112
- relative_path = tract_path.relative_to(tracts_folder)
113
- out_path = tmp_folder / f"{tracts_name}_uncompressed" / relative_path.with_suffix("")
114
- out_path.parent.mkdir(parents=True, exist_ok=True)
115
-
116
- tracts_pathlist.append(uncompress_trk_gz(tract_path, out_path))
117
-
117
+
118
118
  aggregated_tracts_path = tmp_folder / "aggregated_tracts.trk"
119
119
  aggregated_tracts = get_aggregated_tracts(
120
120
  tracts_pathlist=tracts_pathlist,
121
+ reference_path=reference_path,
121
122
  out_path=aggregated_tracts_path,
122
123
  )
123
124
 
@@ -141,11 +142,11 @@ def run_pyLQT(
141
142
  tmp_dir.mkdir(parents=True, exist_ok=True)
142
143
 
143
144
  lesion = nib.load(lesion_path)
144
- lesion_trans_volume = lesion_tracts_mapping.transform(lesion.get_fdata(), interpolation="linear")
145
- lesion_trans = nib.Nifti1Image(
146
- lesion_trans_volume,
147
- tracts_ref_space.affine,
148
- tracts_ref_space.header,
145
+ lesion_trans = apply_registration(
146
+ lesion,
147
+ tracts_ref_space,
148
+ lesion_tracts_mapping,
149
+ interpolation="nearestNeighbor"
149
150
  )
150
151
  nib.save(lesion_trans, tmp_dir / "lesion_trans.nii.gz")
151
152
 
@@ -179,7 +180,7 @@ def run_pyLQT(
179
180
 
180
181
  get_tracts_disconnections_severity(
181
182
  tracts_path=tracts_pathlist,
182
- references_path=references_pathlist,
183
+ reference_path=reference_path,
183
184
  lesion=lesion_trans,
184
185
  disc_tracts_out_path=tmp_dir / "wm_disconnections_severity",
185
186
  disc_frame_out_path=out_dir / "wm_disconnections_severity",
File without changes
@@ -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.dev8
3
+ Version: 1.0.dev10
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.10
12
+ Requires-Python: >=3.11
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
- Requires-Dist: numpy<2.0
15
+ Requires-Dist: numpy>2.0
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
- "atlas_labels": "glasser360_labels.csv",
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` files, the folder containing its reference NIfTI files, and its reference space.
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
 
@@ -122,6 +124,7 @@ pyLQT relies on the following libraries:
122
124
  - `dipy`
123
125
  - `templateflow`
124
126
  - `networkx`
127
+ - `antspyx`
125
128
 
126
129
 
127
130
  ## Links
@@ -23,4 +23,6 @@ src/pyLQT/lesion_metrics/utils/downloads.py
23
23
  src/pyLQT/lesion_metrics/utils/registration.py
24
24
  src/pyLQT/lesion_metrics/white_matter/__init__.py
25
25
  src/pyLQT/lesion_metrics/white_matter/metrics.py
26
- src/pyLQT/lesion_metrics/white_matter/utils.py
26
+ src/pyLQT/lesion_metrics/white_matter/utils.py
27
+ src/pyLQT/utils/__init__.py
28
+ src/pyLQT/utils/logs.py
@@ -1,8 +1,10 @@
1
- numpy<2.0
1
+ numpy>2.0
2
2
  nibabel>5.0
3
3
  pandas>3.0
4
+ napari[all]
4
5
  scipy>1.15
5
6
  requests>2.0
6
7
  dipy>1.10
7
8
  templateflow
8
9
  networkx>=3.6.1
10
+ antspyx
@@ -1,142 +0,0 @@
1
- import nibabel as nib
2
- import pandas as pd
3
- import numpy as np
4
-
5
- from nibabel.processing import resample_from_to
6
- from .utils import get_tract, get_streamlines_disconnection
7
-
8
- from pathlib import Path
9
-
10
-
11
- def get_tracts_disconnections_severity(
12
- tracts_path,
13
- references_path,
14
- lesion,
15
- disc_tracts_out_path = None,
16
- disc_frame_out_path = None
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
-
47
- if disc_tracts_out_path:
48
- disc_tracts_out_path.mkdir(parents=True, exist_ok=True)
49
- disconnections = []
50
- if isinstance(references_path, Path):
51
- references_path = [references_path] * len(tracts_path)
52
- for tract_path, reference_path in zip(tracts_path, references_path):
53
-
54
- 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
- if disc_tracts_out_path:
77
- disconnected_tract_path = disc_tracts_out_path / f"{tract_name}_disconnected.trk"
78
- else:
79
- disconnected_tract_path = None
80
-
81
- tract = get_tract(tract_path=tract_path, reference_path=reference_path)
82
- disconnected_tract, discon = get_streamlines_disconnection(tract=tract,
83
- lesion=lesion,
84
- out_path=disconnected_tract_path)
85
-
86
- disconnections.append({
87
- "Tract": tract_name,
88
- "Discon": np.round(discon, 5),
89
- "Pathway": pathway_name,
90
- })
91
-
92
- disconnections_frame = pd.DataFrame(disconnections)
93
-
94
- if disc_frame_out_path:
95
- disc_frame_out_path.mkdir(parents=True, exist_ok=True)
96
- out_csv = disc_frame_out_path / "ratio_discon_tract.csv"
97
- disconnections_frame.to_csv(out_csv, index=False)
98
-
99
- return disconnections_frame
100
-
101
-
102
- def get_tracts_disconnections_map(
103
- tdi,
104
- tdi_disconnected,
105
- out_path = None
106
- ):
107
- """Compute a voxel-wise tracts disconnection map.
108
-
109
- The disconnection map is computed as the ratio of the tract density
110
- of disconnected streamlines to the tract density of all streamlines.
111
- Voxels with no streamlines are not considered.
112
-
113
- Parameters
114
- ----------
115
- tdi : nibabel.Nifti1Image
116
- Tract density image of the tractogram.
117
- tdi_disconnected : nibabel.Nifti1Image
118
- Tract density image of the disconnected tractogram
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
- nibabel.Nifti1Image
126
- Voxel-wise ratio of disconnected to total streamline density.
127
- """
128
-
129
- disconnections_map = np.divide(
130
- tdi_disconnected.get_fdata(),
131
- tdi.get_fdata(),
132
- out=np.zeros_like(tdi.get_fdata(), dtype=float),
133
- where=tdi.get_fdata() != 0
134
- )
135
-
136
- disconnections_map = nib.Nifti1Image(disconnections_map, tdi.affine, tdi.header)
137
-
138
- if out_path:
139
- out_path.mkdir(parents=True, exist_ok=True)
140
- nib.nifti1.save(disconnections_map, (out_path / "disconnections_map.nii.gz"))
141
-
142
- return disconnections_map
File without changes
File without changes