Skip to content

Commit

Permalink
Scripts (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelstjean authored Dec 16, 2024
1 parent 3b935f5 commit b2f6cf8
Show file tree
Hide file tree
Showing 17 changed files with 87 additions and 72 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ jobs:

runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand All @@ -36,4 +36,4 @@ jobs:
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
pytest .
6 changes: 3 additions & 3 deletions .github/workflows/pythonpublish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine build
pip install twine build
- name: Build and publish
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
Expand Down
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
*.png
*.csv

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down Expand Up @@ -149,10 +152,8 @@ octave-workspace
# Local History for Visual Studio Code
.history/


## Sublime text


# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [v0.2.2]

- Moved the scripts to a proper entrypoint instead of an added file
- This changes nothing in the way each script is called but just makes it more robust on Windows

## [v0.2.1] - 2023-06-01

- Support for csv files input and output
Expand Down
Binary file modified datasets/af_left_AFD_realigned.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified datasets/pvals_realigned.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified datasets/pvals_unaligned.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
language = 'en'

# The full version, including alpha/beta/rc tags
release = 'v0.2.1'
release = 'v0.2.2'

# If your documentation needs a minimal Sphinx version, state it here.
#
Expand Down
1 change: 0 additions & 1 deletion docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
sphinx >= 5.3.0
sphinx_rtd_theme >= 1.1.1
readthedocs-sphinx-search >= 0.3.2
sphinx-rtd-theme
sphinx-autoapi
myst-parser
14 changes: 7 additions & 7 deletions dpr/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def align_bundles(bundles, percent=15, padding=0., order=1, eps=1e-5, mode='full
shifts[outliers] = 0.
shifts[:, outliers] = 0.

warn('Possible outliers found {}'.format(outliers))
warn(f'Possible outliers found {outliers}')

# use the custom shift patterns
ys = apply_shift(bundles, shifts[original_templater])
Expand All @@ -123,7 +123,7 @@ def resample_bundles_to_same(bundles, num_points=None):
bundles = bundles[None, :]

if bundles.ndim != 2:
error = 'bundles needs to be a 2D array, but is {}D'.format(bundles.ndim)
error = f'bundles needs to be a 2D array, but is {bundles.ndim}D'
raise ValueError(error)

if num_points is None:
Expand Down Expand Up @@ -176,7 +176,7 @@ def flip_fibers(bundles, coordinates, padding=np.nan, template=None):
'''

if coordinates[0].shape[1] != 3:
raise ValueError('coordinates should be Nx3 but is {}'.format(coordinates[0].shape))
raise ValueError(f'coordinates should be Nx3 but is {coordinates[0].shape}')

new_bundles = np.zeros_like(bundles)

Expand All @@ -201,7 +201,7 @@ def flip_fibers(bundles, coordinates, padding=np.nan, template=None):
def truncate(bundles, mode='shortest', trimval=np.nan, axis=0):

if bundles.ndim > 2:
error = 'Number of dimension must be lower than 2, but was {}'.format(bundles.ndim)
error = f'Number of dimension must be lower than 2, but was {bundles.ndim}'
raise ValueError(error)

if mode == 'shortest':
Expand All @@ -211,11 +211,11 @@ def truncate(bundles, mode='shortest', trimval=np.nan, axis=0):
elif isinstance(mode, int):

if mode > 100 or mode < 1:
raise ValueError('mode must be between 1 and 100 {}'.format(mode))
raise ValueError(f'mode must be between 1 and 100 {mode}')

threshold = np.floor(mode * bundles.shape[0] / 100)
else:
raise ValueError('Unrecognized truncation mode {}'.format(mode))
raise ValueError(f'Unrecognized truncation mode {mode}')

if np.isnan(trimval):
indexes = np.isfinite(bundles).sum(axis=axis) >= threshold
Expand Down Expand Up @@ -246,7 +246,7 @@ def filter_pairs(allpairs, mode):
elif mode == 'everything':
func = lambda *_: True # this always return True
else:
error = 'String mismatch, mode was {} of type {}'.format(mode, type(mode))
error = f'String mismatch, mode was {mode} of type {type(mode)}'
raise ValueError(error)

output = []
Expand Down
Empty file added dpr/scripts/__init__.py
Empty file.
6 changes: 0 additions & 6 deletions scripts/dpr → dpr/scripts/dpr.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt

Expand Down Expand Up @@ -153,7 +151,3 @@ def main():

with open(args.output, 'w') as file:
np.savetxt(file, resampled, delimiter=delimiter, fmt='%s')


if __name__ == "__main__":
main()
6 changes: 0 additions & 6 deletions scripts/dpr_make_fancy_graph → dpr/scripts/dpr_make_fancy_graph.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python

import numpy as np

import argparse
Expand Down Expand Up @@ -123,7 +121,3 @@ def main():
coord1_label=args.labelx, coord2_label=args.labely, title=args.title)

fig.savefig(args.output, dpi=args.dpi, bbox_inches='tight')


if __name__ == "__main__":
main()
23 changes: 23 additions & 0 deletions dpr/tests/test_scripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import subprocess
import pytest

from pathlib import Path

cwd = Path(__file__).parents[2] / Path("datasets")
commands_dpr = [
('dpr', 'af_left_AFD.txt', 'af_left_AFD_realigned.txt', '--exploredti', '--do_graph', '-f', '-v', '--points', '75'),
('dpr', 'af_left_AFD.txt', 'af_left_AFD_realigned.csv', '--exploredti', '-f')
]

commands_dpr_graph = [
('dpr_make_fancy_graph', 'af_left_pval_unaligned.txt', 'af_left_coordinates.txt', 'af_left_truncated_coordinates.txt', 'af_left_average_coordinates.txt', '0,2', 'pvals_unaligned.png', '--title', "p-values before realignment", '-f'),
('dpr_make_fancy_graph', 'af_left_pval_realigned.txt', 'af_left_coordinates.txt', 'af_left_truncated_coordinates.txt', 'af_left_average_coordinates.txt', '0,2', 'pvals_realigned.png', '-f', '-v', '--labelx', '"label X"', '--labely', 'Label Y', '--dpi', '100')
]

@pytest.mark.parametrize("command", commands_dpr)
def test_script_dpr(command):
subprocess.run(command, cwd=cwd, check=True)

@pytest.mark.parametrize("command", commands_dpr_graph)
def test_script_dpr_graph(command):
subprocess.run(command, cwd=cwd, check=True)
53 changes: 25 additions & 28 deletions dpr/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,41 +69,38 @@ def draw_fancy_graph(pval, coords1, coords2, truncated_coords1, truncated_coords
if title is None:
title = 'p-values after realignment'

# This is to draw on a white background
with plt.style.context('seaborn-whitegrid'):
fig, ax = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(8, 8))

fig, ax = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(8, 8))
# Draw the full length shadow bundle
for x, y in zip(coords1, coords2):
ax.plot(x, y, color=shadow_cmap, alpha=0.1, zorder=1)

# Draw the full length shadow bundle
for x, y in zip(coords1, coords2):
ax.plot(x, y, color=shadow_cmap, alpha=0.1, zorder=1)
# Draw the original coord, but truncated between rois
for x, y in zip(truncated_coords1, truncated_coords2):
ax.plot(x, y, color=bundle_cmap, alpha=0.3, zorder=2)

# Draw the original coord, but truncated between rois
for x, y in zip(truncated_coords1, truncated_coords2):
ax.plot(x, y, color=bundle_cmap, alpha=0.3, zorder=2)
# Draw the mean coord
x = average1
y = average2
ax.plot(x, y, color=mean_fiber_cmap, zorder=5)

# Draw the mean coord
x = average1
y = average2
ax.plot(x, y, color=mean_fiber_cmap, zorder=5)
# We resample the pvals because the coords may be at the tracking stepsize and the final results at the voxel resolution
old = np.arange(len(pval)) / len(pval)
new = np.arange(len(x)) / len(x)
pval_resampled = np.interp(new, old, pval)

# We resample the pvals because the coords may be at the tracking stepsize and the final results at the voxel resolution
old = np.arange(len(pval)) / len(pval)
new = np.arange(len(x)) / len(x)
pval_resampled = np.interp(new, old, pval)
# This makes everything above the threshold invisible on the final graph
pval_resampled[pval_resampled > pval_threshold] = np.nan
cmap_axis = ax.scatter(x, y, c=pval_resampled, cmap=pval_cmap, zorder=10, marker='.', vmin=0, vmax=pval_threshold)

# This makes everything above the threshold invisible on the final graph
pval_resampled[pval_resampled > pval_threshold] = np.nan
cmap_axis = ax.scatter(x, y, c=pval_resampled, cmap=pval_cmap, zorder=10, marker='.', vmin=0, vmax=pval_threshold)
if draw_colorbar:
colorbar(cmap_axis)

if draw_colorbar:
colorbar(cmap_axis)
ax.axis('equal')
ax.set_xlabel(f"{coord1_label} coordinates (mm)", fontsize=12)
ax.set_ylabel(f"{coord2_label} coordinates (mm)", fontsize=12)

ax.axis('equal')
ax.set_xlabel("{} coordinates (mm)".format(coord1_label), fontsize=12)
ax.set_ylabel("{} coordinates (mm)".format(coord2_label), fontsize=12)

ax.set_title(title, fontsize=20)
fig.tight_layout()
ax.set_title(title, fontsize=20)
fig.tight_layout()

return fig, ax
24 changes: 15 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,25 @@ build-backend = "setuptools.build_meta"

[project]
name = "dpr"
version = '0.2.1'
requires-python = ">=3.7"
dependencies = ['numpy>=1.10',
'scipy>=0.19',
'matplotlib>=2.0']
version = '0.2.2'
requires-python = ">=3.9"
dependencies = ['numpy>=1.15',
'scipy>=1.2',
'matplotlib>=3.0']
description = 'Implementation of "Reducing variability in along-tract analysis with diffusion profile realignment".'
readme = "README.md"
license = {text = "MIT License"}
authors = [
{name = "Samuel St-Jean", email = "[email protected]"}
]
license = { text = "MIT License" }
authors = [{ name = "Samuel St-Jean", email = "[email protected]" }]

[project.scripts]
dpr = "dpr.scripts.dpr:main"
dpr_make_fancy_graph = "dpr.scripts.dpr_make_fancy_graph:main"

[project.urls]
Homepage = "https://github.com/samuelstjean/dpr"
Documentation = "https://dpr.readthedocs.io/en/latest/"
Changelog = "https://github.com/samuelstjean/dpr/blob/master/CHANGELOG.md"

[tool.setuptools]
packages = ["dpr",
"dpr.scripts"]
8 changes: 2 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
from setuptools import setup, find_packages
from setuptools import setup

scripts=['scripts/dpr',
'scripts/dpr_make_fancy_graph']

setup(scripts=scripts,
packages=find_packages())
setup()

0 comments on commit b2f6cf8

Please sign in to comment.