Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 21 additions & 25 deletions .spin/cmds.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Custom spin commands for trx-python development."""

import glob
import os
from pathlib import Path
import shutil
import subprocess
import sys
Expand Down Expand Up @@ -223,35 +223,32 @@ def docs(_clean, open_browser):
open_browser : bool
If True, open documentation in browser after building.
"""
import os

docs_dir = "docs"
docs_dir = Path("docs")

if _clean:
click.echo("Cleaning build directory...")
build_dir = os.path.join(docs_dir, "_build")
if os.path.exists(build_dir):
build_dir = docs_dir / "_build"
if build_dir.exists():
shutil.rmtree(build_dir)

# Clean sphinx-gallery generated files
gallery_dir = os.path.join(docs_dir, "source", "auto_examples")
if os.path.exists(gallery_dir):
gallery_dir = docs_dir / "source" / "auto_examples"
if gallery_dir.exists():
click.echo("Cleaning sphinx-gallery generated files...")
shutil.rmtree(gallery_dir)

# Clean sphinx-gallery execution times file
sg_times = os.path.join(docs_dir, "source", "sg_execution_times.rst")
if os.path.exists(sg_times):
sg_times = docs_dir / "source" / "sg_execution_times.rst"
if sg_times.exists():
os.remove(sg_times)

click.echo("Building documentation...")
cmd = ["make", "-C", docs_dir, "html"]
cmd = ["make", "-C", str(docs_dir), "html"]
result = run(cmd, capture=False, check=False)

if result == 0:
index_path = os.path.abspath(
os.path.join(docs_dir, "_build", "html", "index.html")
)
index_path = (docs_dir / "_build" / "html" / "index.html").resolve()
click.echo("\nDocs built successfully!")
click.echo(f"Open: {index_path}")

Expand All @@ -270,27 +267,26 @@ def clean(): # noqa: C901

# Clean TRX temp directory
trx_tmp_dir = os.getenv("TRX_TMPDIR", tempfile.gettempdir())
if os.path.exists(trx_tmp_dir):
temp_files = glob.glob(os.path.join(trx_tmp_dir, "trx_*"))
for temp_dir in temp_files:
if os.path.isdir(temp_dir):
click.echo(f"Removing temporary directory: {temp_dir}")
shutil.rmtree(temp_dir)
if trx_tmp_dir.exists():
for temp_name in trx_tmp_dir.glob("trx_*"):
if temp_name.is_dir():
click.echo(f"Removing temporary directory: {temp_name}")
shutil.rmtree(temp_name)

# Clean build artifacts
for build_pattern in ["build", "dist", "*.egg-info"]:
for path in glob.glob(build_pattern):
if os.path.isdir(path):
for path in Path(".").glob(build_pattern):
if path.is_dir():
click.echo(f"Removing build directory: {path}")
shutil.rmtree(path)
elif os.path.isfile(path):
elif path.is_file():
click.echo(f"Removing build file: {path}")
os.remove(path)
path.unlink()

# Clean Python cache
for cache_dir in ["**/__pycache__", "**/.pytest_cache"]:
for path in glob.glob(cache_dir, recursive=True):
if os.path.isdir(path):
for path in Path(".").glob(cache_dir):
if path.is_dir():
click.echo(f"Removing cache directory: {path}")
shutil.rmtree(path)

Expand Down
3 changes: 2 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import warnings
import os
from datetime import datetime as dt
from pathlib import Path

# -- Version information -----------------------------------------------------
# Get version from environment variable (set by CI) or package
Expand Down Expand Up @@ -191,5 +192,5 @@ def _validate_reference_urls(urls, timeout=5):
'gallery_dirs': 'auto_examples',
'within_subsection_order': 'NumberOfCodeLinesSortKey',
'reference_url': _validate_reference_urls(_reference_urls),
'default_thumb_file': os.path.join(os.path.dirname(__file__), '..', '_static', 'trx_logo.png'),
'default_thumb_file': str(Path(__file__).parent / '..' / '_static' / 'trx_logo.png'),
}
4 changes: 1 addition & 3 deletions examples/plot_dps_dpv.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
#
# Let's load a TRX file and explore its metadata.

import os

import numpy as np

from trx.fetcher import fetch_data, get_home, get_testing_files_dict
Expand All @@ -49,7 +47,7 @@
# Download test data
fetch_data(get_testing_files_dict(), keys="gold_standard.zip")
trx_home = get_home()
trx_path = os.path.join(trx_home, "gold_standard", "gs.trx")
trx_path = trx_home / "gold_standard" / "gs.trx"

# Load the TRX file
tgm = load(trx_path)
Expand Down
4 changes: 1 addition & 3 deletions examples/plot_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@
#
# Let's load a TRX file that contains group information.

import os

import numpy as np

from trx.fetcher import fetch_data, get_home, get_testing_files_dict
Expand All @@ -45,7 +43,7 @@
# Download test data
fetch_data(get_testing_files_dict(), keys="gold_standard.zip")
trx_home = get_home()
trx_path = os.path.join(trx_home, "gold_standard", "gs.trx")
trx_path = trx_home / "gold_standard" / "gs.trx"

# Load the TRX file
tgm = load(trx_path)
Expand Down
7 changes: 3 additions & 4 deletions examples/plot_read_write_trx.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
# Let's start by loading an existing TRX file. First, we need to download
# some test data.

import os
import tempfile

from trx.fetcher import fetch_data, get_home, get_testing_files_dict
Expand All @@ -33,7 +32,7 @@
# Download test data
fetch_data(get_testing_files_dict(), keys="gold_standard.zip")
trx_home = get_home()
trx_path = os.path.join(trx_home, "gold_standard", "gs.trx")
trx_path = trx_home / "gold_standard" / "gs.trx"

# Load the TRX file
tgm = load(trx_path)
Expand Down Expand Up @@ -109,10 +108,10 @@

with tempfile.TemporaryDirectory() as tmpdir:
# Save as TRX file (zip archive)
output_path = os.path.join(tmpdir, "output.trx")
output_path = tmpdir / "output.trx"
save(tgm, output_path)
print(f"Saved TRX file to: {output_path}")
print(f"File size: {os.path.getsize(output_path)} bytes")
print(f"File size: {output_path.stat().st_size} bytes")

# Reload to verify
reloaded = load(output_path)
Expand Down
15 changes: 8 additions & 7 deletions trx/fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import hashlib
import logging
import os
from pathlib import Path
import shutil
import urllib.request

Expand All @@ -24,13 +25,13 @@ def get_home():

Returns
-------
str
Path
Path to the TRX home directory.
"""
if "TRX_HOME" in os.environ:
trx_home = os.environ["TRX_HOME"]
trx_home = Path(os.environ["TRX_HOME"])
else:
trx_home = os.path.join(os.path.expanduser("~"), ".tee_ar_ex")
trx_home = Path("~").expanduser() / ".tee_ar_ex"
return trx_home


Expand Down Expand Up @@ -132,7 +133,7 @@ def fetch_data(files_dict, keys=None): # noqa: C901
"""
trx_home = get_home()

if not os.path.exists(trx_home):
if not trx_home.exists():
os.makedirs(trx_home)

if keys is None:
Expand All @@ -147,10 +148,10 @@ def fetch_data(files_dict, keys=None): # noqa: C901
expected_sha = None
else:
url, expected_md5, expected_sha = file_entry
full_path = os.path.join(trx_home, fname)
full_path = trx_home / fname

logging.info(f"Downloading {fname} to {trx_home}")
if not os.path.exists(full_path):
if not full_path.exists():
urllib.request.urlretrieve(url, full_path)

actual_md5 = md5sum(full_path)
Expand All @@ -169,5 +170,5 @@ def fetch_data(files_dict, keys=None): # noqa: C901
)

if fname.endswith(".zip"):
dst_dir = os.path.join(trx_home, fname[:-4])
dst_dir = trx_home / fname[:-4]
shutil.unpack_archive(full_path, extract_dir=dst_dir, format="zip")
20 changes: 13 additions & 7 deletions trx/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import logging
import os
from pathlib import Path
import sys
import tempfile

Expand Down Expand Up @@ -32,26 +33,30 @@ def get_trx_tmp_dir():
"""
if os.getenv("TRX_TMPDIR") is not None:
if os.getenv("TRX_TMPDIR") == "use_working_dir":
trx_tmp_dir = os.getcwd()
trx_tmp_dir = str(Path.cwd())
else:
trx_tmp_dir = os.getenv("TRX_TMPDIR")
else:
trx_tmp_dir = tempfile.gettempdir()

if sys.version_info[1] >= 10:
return tempfile.TemporaryDirectory(
tmp_dir = tempfile.TemporaryDirectory(
dir=trx_tmp_dir, prefix="trx_", ignore_cleanup_errors=True
)
else:
return tempfile.TemporaryDirectory(dir=trx_tmp_dir, prefix="trx_")
tmp_dir = tempfile.TemporaryDirectory(dir=trx_tmp_dir, prefix="trx_")

# Keep the TemporaryDirectory instance, but provide a Path-compatible name
tmp_dir.name = Path(tmp_dir.name)
return tmp_dir


def load_sft_with_reference(filepath, reference=None, bbox_check=True, from_space=None):
"""Load a tractogram as a StatefulTractogram with an explicit reference.

Parameters
----------
filepath : str
filepath : str or Path
Path to the tractogram file (.trk, .tck, .fib, .vtk, .dpy).
reference : str or nibabel.Nifti1Image, optional
Reference image used for formats without embedded affine information.
Expand Down Expand Up @@ -81,7 +86,7 @@ def load_sft_with_reference(filepath, reference=None, bbox_check=True, from_spac
from dipy.io.streamline import load_tractogram

# Force the usage of --reference for all file formats without an header
_, ext = os.path.splitext(filepath)
ext = "".join(Path(filepath).suffixes)
if ext == ".trk":
if reference is not None and reference != "same":
logging.warning(f"Reference is discarded for this file format {filepath}.")
Expand Down Expand Up @@ -122,7 +127,7 @@ def load(tractogram_filename, reference=None, from_space=None):
import trx.trx_file_memmap as tmm

in_ext = split_name_with_gz(tractogram_filename)[1]
if in_ext != ".trx" and not os.path.isdir(tractogram_filename):
if in_ext != ".trx" and not tractogram_filename.is_dir():
tractogram_obj = load_sft_with_reference(
tractogram_filename, reference, bbox_check=False, from_space=from_space
)
Expand All @@ -140,7 +145,7 @@ def save(tractogram_obj, tractogram_filename, bbox_valid_check=False):
tractogram_obj : TrxFile or StatefulTractogram
Tractogram to persist. Non-TRX inputs are converted to StatefulTractogram
before saving to non-TRX formats.
tractogram_filename : str
tractogram_filename : str or Path
Destination file name. ``.trx`` will be saved using the TRX writer; all
other extensions are handled by ``dipy.save_tractogram``.
bbox_valid_check : bool, optional
Expand All @@ -153,6 +158,7 @@ def save(tractogram_obj, tractogram_filename, bbox_valid_check=False):
The function writes to disk and returns ``None``. Returns ``None``
immediately when ``dipy`` is unavailable.
"""
tractogram_filename = Path(tractogram_filename)
if not dipy_available:
logging.error(
"Dipy library is missing, cannot use functions related "
Expand Down
Loading
Loading