Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENH] add utility function to compute expected value #74

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
10 changes: 10 additions & 0 deletions docs/pipelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,16 @@ As explained before, all pipeline inherit from the `narps_open.pipelines.Pipelin
* `fwhm` : full width at half maximum for the smoothing kernel (in mm) :
* `tr` : repetition time of the fMRI acquisition (equals 1.0s)

## Utility functions

You can find several utility functions in the `narps_open.utils` module.

- raw_data_template
- fmriprep_data_template
- compute_expected_value

Feel free to use them in your pipeline.

## Test your pipeline

First have a look at the [testing topic of the documentation](./docs/testing.md). It explains how testing works for inside project and how you should write the tests related to your pipeline.
Expand Down
53 changes: 51 additions & 2 deletions narps_open/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
#!/usr/bin/python
# coding: utf-8
from __future__ import annotations

""" A set of utils functions for the narps_open package """

from hashlib import sha256
from os import listdir
from os.path import isfile, join, abspath, dirname, realpath, splitext
from os.path import abspath, dirname, isfile, join, realpath, splitext
from pathlib import Path

import pandas as pd
from nibabel import load
from hashlib import sha256


def show_download_progress(count, block_size, total_size):
""" A hook function to be passed to urllib.request.urlretrieve in order to
Expand Down Expand Up @@ -192,3 +196,48 @@ def fmriprep_data_template() -> dict:
)

return {"func_preproc": func_preproc, "confounds_file": confounds_file}


def compute_expected_value(onsets: dict[str, list[float]] | pd.DataFrame | str | Path):
"""Compute expected value regressor for a run.

Parameters
----------
onsets : dict[str, list[float]] | pd.DataFrame | str | Path
Events for a run.
Pathlike TSV file with columns 'gain' and 'loss'.
If a dict, must have keys 'gain' and 'loss'.
If a DataFrame, must have columns 'gain' and 'loss'.

Returns
-------
onsets : pd.DataFrame
Onsets with expected value column added.
"""
# # compute euclidian distance to the indifference line defined by
# # gain twice as big as losses
# % https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
# a = 0.5;
# b = -1;
# c = 0;
# x = onsets{iRun#.gain;
# y = onsets{iRun}.loss;
# dist = abs(a * x + b * y + c) / (a^2 + b^2)^.5;
# onsets{iRun}.EV = dist; % create an "expected value" regressor
a = 0.5
b = -1
c = 0

if isinstance(onsets, (str, Path)):
onsets = pd.read_csv(onsets, sep="\t")

if isinstance(onsets, dict):
onsets = pd.DataFrame(onsets)

x = onsets["gain"]
y = onsets["loss"]

dist = abs(a * x + b * y + c) / (a**2 + b**2) ** 0.5
onsets["EV"] = dist

return onsets
51 changes: 51 additions & 0 deletions narps_open/utils/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from __future__ import annotations

from pathlib import Path

import pandas as pd

# # compute euclidian distance to the indifference line defined by
# # gain twice as big as losses
# % https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
# a = 0.5;
# b = -1;
# c = 0;
# x = onsets{iRun#.gain;
# y = onsets{iRun}.loss;
# dist = abs(a * x + b * y + c) / (a^2 + b^2)^.5;
# onsets{iRun}.EV = dist; % create an "expected value" regressor


def compute_expected_value(onsets: dict[str, list[float]] | pd.DataFrame | str | Path):
"""Compute expected value regressor for a run.

Parameters
----------
onsets : dict[str, list[float]] | pd.DataFrame | str | Path
Events for a run.
Pathlike TSV file with columns 'gain' and 'loss'.
If a dict, must have keys 'gain' and 'loss'.
If a DataFrame, must have columns 'gain' and 'loss'.

Returns
-------
onsets : pd.DataFrame
Onsets with expected value column added.
"""
a = 0.5
b = -1
c = 0

if isinstance(onsets, (str, Path)):
onsets = pd.read_csv(onsets, sep="\t")

if isinstance(onsets, dict):
onsets = pd.DataFrame(onsets)

x = onsets["gain"]
y = onsets["loss"]

dist = abs(a * x + b * y + c) / (a**2 + b**2) ** 0.5
onsets["EV"] = dist

return onsets
55 changes: 40 additions & 15 deletions tests/utils/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,62 @@
"""
from os.path import join

import pandas as pd
from numpy.testing import assert_array_almost_equal
from pytest import mark

from narps_open.utils import (compute_expected_value, hash_dir_images,
hash_image, show_download_progress)
from narps_open.utils.configuration import Configuration
from narps_open.utils import show_download_progress, hash_image, hash_dir_images


class TestUtils:
""" A class that contains all the unit tests for the utils module."""
"""A class that contains all the unit tests for the utils module."""

@staticmethod
@mark.unit_test
def test_show_download_progress(capfd): # using pytest's capfd fixture to get stdout
""" Test the show_download_progress function """

show_download_progress(25,1,100)
def test_show_download_progress(
capfd,
): # using pytest's capfd fixture to get stdout
"""Test the show_download_progress function."""
show_download_progress(25, 1, 100)
captured = capfd.readouterr()
assert captured.out == 'Downloading 25 %\r'
assert captured.out == "Downloading 25 %\r"

show_download_progress(26,2,200)
show_download_progress(26, 2, 200)
captured = capfd.readouterr()
assert captured.out == 'Downloading 26 %\r'
assert captured.out == "Downloading 26 %\r"

show_download_progress(25,50,-1)
show_download_progress(25, 50, -1)
captured = capfd.readouterr()
assert captured.out == 'Downloading ⣽\r'
assert captured.out == "Downloading ⣽\r"

@staticmethod
@mark.unit_test
def test_hash_image():
""" Test the hash_image function """
def test_compute_expected_value(tmp_path):
"""Test the compute_expected_value function."""
onsets = {"gain": [1, 2, 3], "loss": [1, 2, 3]}

computed = compute_expected_value(onsets=onsets)
assert_array_almost_equal(computed["EV"], [0.447, 0.894, 1.342], decimal=3)

df = pd.DataFrame(onsets)
computed = compute_expected_value(onsets=df)
assert_array_almost_equal(computed["EV"], [0.447, 0.894, 1.342], decimal=3)

events_tsv = tmp_path / "events.tsv"
df.to_csv(events_tsv, sep="\t")
computed = compute_expected_value(onsets=events_tsv)
assert_array_almost_equal(computed["EV"], [0.447, 0.894, 1.342], decimal=3)

events_tsv = str(events_tsv)
computed = compute_expected_value(onsets=events_tsv)
assert_array_almost_equal(computed["EV"], [0.447, 0.894, 1.342], decimal=3)

@staticmethod
@mark.unit_test
def test_hash_image():
"""Test the hash_image function."""
# Get test_data for hash
test_image_path = join(
Configuration()['directories']['test_data'],
Expand All @@ -54,8 +80,7 @@ def test_hash_image():
@staticmethod
@mark.unit_test
def test_hash_dir_images():
""" Test the hash_dir_images function """

"""Test the hash_dir_images function."""
# Get test_data for hash
test_path = join(
Configuration()['directories']['test_data'],
Expand Down