utils

Bunch of utility functions used throughout the lazyfmri and fmriproc-repositories.

class lazyfmri.utils.BIDSFile[source]

Bases: object

Class to extract BIDS-related components from filenames and paths.

Parameters:

bids_file (str) – Path to the BIDS-compliant file.

`get_bids_basepath()`

Retrieve the BIDS base path.

`get_bids_root()`

Retrieve the BIDS root directory.

`get_bids_workbase()`

Retrieve the BIDS working directory.

`get_bids_workflow()`

Retrieve the workflow name for fMRIPrep.

`get_bids_ids()`

Extract subject, session, task, and run information from filename.

get_bids_basepath(*args)[source]
get_bids_ids(**kwargs)[source]
get_bids_root(*args)[source]
get_bids_workbase(*args)[source]
get_bids_workflow(**kwargs)[source]
class lazyfmri.utils.FindFiles[source]

Bases: object

Class to search for files in a directory based on a specified extension and optional filters.

This class allows recursive search with depth constraints and filtering based on filename patterns.

Parameters:
  • directory (str) – Path to the directory where the search should be performed.

  • extension (str) – File extension to search for (e.g., “.nii”, “.csv”).

  • exclude (str or list, optional) – String or list of substrings to exclude from the search results.

  • maxdepth (int, optional) – Maximum depth of recursion for searching subdirectories. If None, no limit is imposed.

  • filters (str or list, optional) – String or list of substrings to filter the results. Only files matching these filters will be retained.

files

Sorted list of found files that match the search criteria.

Type:

list

`find_files()`

Static method that yields files in a directory matching the given pattern.

static find_files(directory, pattern, maxdepth=None)[source]
lazyfmri.utils.SDT(hits, misses, fas, crs)[source]

Computes Signal Detection Theory (SDT) measures, including d-prime (d’), beta, criterion (c), and area under the d-prime distribution (Ad’), given the number of hits, misses, false alarms, and correct rejections.

Parameters:
  • hits (int) – Number of correct detections (signal present, response “yes”).

  • misses (int) – Number of missed detections (signal present, response “no”).

  • fas (int) – Number of false alarms (signal absent, response “yes”).

  • crs (int) – Number of correct rejections (signal absent, response “no”).

Returns:

A dictionary containing:

  • ’d’ (float): d-prime, a measure of sensitivity.

  • ’beta’ (float): Response bias (β), calculated as

    exp((Z(fa_rate)^2 - Z(hit_rate)^2) / 2).
    
  • ’c’ (float): Criterion (c), calculated as:

    -(Z(hit_rate) + Z(fa_rate)) / 2.
    
  • ’Ad’ (float): Area under the d-prime distribution, equivalent to norm.cdf(d / sqrt(2)).

  • ’hit’ (float): Adjusted hit rate.

  • ’fa’ (float): Adjusted false alarm rate.

Return type:

dict

Notes

  • To prevent infinite values in d-prime calculations, hit and false alarm rates of 0 or 1 are adjusted using a half-increment rule.

  • Z(x) is the inverse cumulative distribution function (probit function) from the standard normal distribution.

  • The function is useful in psychophysics and cognitive neuroscience to quantify detection sensitivity.

References

  • Green, D. M., & Swets, J. A. (1966). Signal detection theory and psychophysics.

  • Macmillan, N. A., & Creelman, C. D. (2004). Detection theory: A user’s guide.

Example

>>> SDT(hits=50, misses=10, fas=5, crs=35)
{'d': 2.05, 'beta': 0.38, 'c': -0.1, 'Ad': 0.977, 'hit': 0.83, 'fa': 0.12}
lazyfmri.utils.ants_to_spm_moco(affine, deg=False, convention='SPM')[source]

SPM output = x [LR], y [AP], z [SI], rx, ry, rz. ANTs employs an LPS system, so y value should be switched

lazyfmri.utils.ants_truncate_intensities(in_file, out_file, lower=0.01, upper=0.99, n_bins=256)[source]
lazyfmri.utils.assemble_fmriprep_wf()[source]

Converts a BOLD file path into a workflow name for fMRIPrep.

Parameters:
  • bold_path (str) – Path to the BOLD file.

  • wf_only (bool, optional) – Whether to return only the workflow name without single_subject_<sub_id>_wf, by default False.

Returns:

Constructed workflow name.

Return type:

str

Example

from lazyfmri.utils import assemble_fmriprep_wf
bold_file = "sub-008_ses-2_task-SRFi_acq-3DEPI_run-1_desc-preproc_bold.nii.gz"
wf_name = assemble_fmriprep_wf(bold_file)
print(wf_name)  # 'single_subject_008_wf/func_preproc_ses_2_task_SRFi_run_1_acq_3DEPI_wf'
wf_name = assemble_fmriprep_wf(bold_file, wf_only=True)
print(wf_name)  # 'func_preproc_ses_2_task_SRFi_run_1_acq_3DEPI_wf'
lazyfmri.utils.calculate_tsnr(data, ax)[source]
class lazyfmri.utils.color[source]

Bases: object

BLUE = '\x1b[34m'
BOLD = '\x1b[1m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
END = '\x1b[0m'
GREEN = '\x1b[32m'
MAGENTA = '\x1b[35m'
PURPLE = '\x1b[95m'
RED = '\x1b[91m'
UNDERLINE = '\x1b[4m'
YELLOW = '\x1b[93m'
lazyfmri.utils.convert2unit()[source]

Normalize a vector to a unit vector.

Parameters:
  • v (numpy.ndarray) – Vector to be normalized.

  • method (str, optional) – Method for normalization (“np” for NumPy, “mesh” for mesh-based normalization), by default “np”.

Returns:

Unit-normalized vector.

Return type:

numpy.ndarray

lazyfmri.utils.convert_to_rgb(color, as_integer=False)[source]
lazyfmri.utils.copy_hdr()[source]

Copy the header of one NIfTI image to another.

Parameters:
  • source_img (str or nibabel.Nifti1Image) – Source image.

  • dest_img (str or nibabel.Nifti1Image) – Target image.

Returns:

Image with the header copied from the source.

Return type:

nibabel.Nifti1Image

Example

from lazyfmri.utils import copy_hdr
new_img = copy_hdr(img1, img2)
lazyfmri.utils.decode(obj)[source]

decode an object

lazyfmri.utils.disassemble_fmriprep_wf()[source]

Parses the workflow folder from fMRIPrep into a filename based on subject-specific components.

Parameters:
  • wf_path (str) – Path to workflow folder.

  • subj_ID (str) – Subject ID to append to prefix.

  • prefix (str, optional) – Prefix for the filename (default is “sub-”).

Returns:

Constructed filename based on workflow parts.

Return type:

str

Example

from lazyfmri.utils import disassemble_fmriprep_wf
wf_dir = "func_preproc_ses_2_task_pRF_run_1_acq_3DEPI_wf"
fname = disassemble_fmriprep_wf(wf_dir, "001")
print(fname)  # 'sub-001_ses-2_task-pRF_acq-3DEPI_run-1'
lazyfmri.utils.filter_for_nans(array)[source]

filter out NaNs from an array

lazyfmri.utils.find_intersection()[source]

Find the intersection coordinates given two functions using Shapely.

Parameters:
  • xx (numpy.ndarray) – array describing the x-axis values

  • curve1 (numpy.ndarray) – array describing the first curve

  • curve2 (numpy.ndarray) – array describing the first curve

Returns:

x,y coordinates where curve1 and curve2 intersect

Return type:

tuple

Raises:

ValueError – if no intersection coordinates could be found

Example

See https://fmriproc.readthedocs.io/en/latest/classes/prf.html#fmriproc.prf.SizeResponse.find_stim_sizes

lazyfmri.utils.find_missing(lst)[source]
lazyfmri.utils.find_nearest()[source]

Find the index and value in an array given a value. You can either choose to have 1 item (the closest) returned, or the 5 nearest items (return_nr=5), or everything you’re interested in (return_nr=”all”)

Parameters:
  • array (numpy.ndarray) – array to search in

  • value (float) – value to search for in array

  • return_nr (int, str, optional) – number of elements to return after searching for elements in array that are close to value. Can either be an integer or a string all

Returns:

  • int – integer representing the index of the element in array closest to value.

  • list – if return_nr > 1, a list of indices will be returned

  • numpy.ndarray – value in array at the index closest to value

lazyfmri.utils.get_file_from_substring()[source]

Finds and returns file(s) in a directory that contain specific substrings in their filenames. Supports multiple search filters and optional exclusions.

This function scans a directory for filenames containing the specified substring(s) (filt). It constructs a binary matrix where each row represents a file, and each column represents a filter. A file is considered a match if all filters exist within its filename.

  • If a single file matches, it returns the file path as a string.

  • If multiple files match, it returns a list of file paths.

  • If no files match, it raises an error or returns None, depending on return_msg.

Parameters:
  • filt (str or list of str) – Substring(s) to match within filenames. Can be a single string or a list of multiple filters.

  • path (str or list) – Path to the directory to search in. Can also be a list of filenames for direct filtering.

  • return_msg (str, optional) – Behavior when no matching files are found: - ‘error’ (default): Raises FileNotFoundError. - None: Returns None instead of raising an error.

  • exclude (str or list of str, optional) – Substring(s) to exclude from matching files. Applied after filtering with filt.

Returns:

  • str – The path to the matching file if a single match is found.

  • list of str – A list of paths if multiple files match the filters.

  • None – If no matches are found and return_msg=None.

Raises:

FileNotFoundError – If no files match the specified filters and return_msg=’error’.

Examples

Find a single file containing a substring:

from lazyfmri.utils import get_file_from_substring

# Search for a file containing "R2" in the /path/to/prf directory
file_path = get_file_from_substring("R2", "/path/to/prf")
print(file_path)
# Output: "/path/to/prf/r2.npy"

Find a file matching multiple filters:

file_path = get_file_from_substring(["gauss", "best_vertices"], "path/to/pycortex/sub-xxx")
print(file_path)
# Output: "/path/to/pycortex/sub-xxx/sub-xxx_model-gauss_desc-best_vertices.csv"

Find multiple matching files:

file_list = get_file_from_substring(["best_vertices"], "path/to/pycortex/sub-xxx")
print(file_list)
# Output:
# [
#   "/path/to/pycortex/sub-xxx/sub-xxx_model-gauss_desc-best_vertices.csv",
#   "/path/to/pycortex/sub-xxx/sub-xxx_model-norm_desc-best_vertices.csv"
# ]

Exclude specific files from the results:

file_list = get_file_from_substring(["best_vertices"], "path/to/pycortex/sub-xxx", exclude="norm")
print(file_list)
# Output:
# [
#   "/path/to/pycortex/sub-xxx/sub-xxx_model-gauss_desc-best_vertices.csv"
# ]
lazyfmri.utils.get_first_existing(dictionary, keys, fallback=None, msg=None)[source]

Return the first existing key from a list in the given dictionary. If none are found, return fallback (if provided), else None.

Parameters:
  • dictionary (dict) – The dictionary to search in.

  • keys (list) – List of keys to check in priority order.

  • fallback (any, optional) – Value to return if none of the keys are found.

  • msg (str, optional) – Extra message in case fallback option is selected

Return type:

value from dictionary or fallback

lazyfmri.utils.get_ids(func_list, bids='task')[source]
lazyfmri.utils.get_unique_ids(df, id=None, sort=True, as_int=False, drop_na=True)[source]
lazyfmri.utils.get_vertex_nr()[source]

Retrieve the number of vertices in the cortical surface for a given subject.

Parameters:
  • subject (str) – Subject ID.

  • as_list (bool, optional) – Whether to return left and right hemisphere vertex counts separately, by default False.

  • debug (bool, optional) – Whether to print debug information, by default False.

  • fs_dir (str, optional) – Path to FreeSurfer subjects directory, by default reads from environment variable SUBJECTS_DIR.

Returns:

Total number of vertices (int) or a list of hemisphere-specific counts if as_list=True.

Return type:

int or list

Raises:

FileNotFoundError – If the surface file is not found.

lazyfmri.utils.launch_itksnap(*args)[source]

Launch ITK-SNAP to view/edit images and wait for the GUI to close.

Parameters:

*args (str) – Arbitrary command-line arguments to pass to ITK-SNAP (e.g., -g <image> -s <segmentation>)

Notes

  • Uses open -W on macOS to block until ITK-SNAP closes.

  • On Linux, subprocess waits by default.

  • On Windows, uses shell execution to block until ITK-SNAP closes.

lazyfmri.utils.make_between_cm(col1, col2, as_list=False, **kwargs)[source]
lazyfmri.utils.make_binary_cm()[source]

This function creates a custom binary colormap using matplotlib based on the RGB code specified. Especially useful if you want to overlay in imshow, for instance. These RGB values will be converted to range between 0-1 so make sure you’re specifying the actual RGB-values. I like https://htmlcolorcodes.com to look up RGB-values of my desired color. The snippet of code used here comes from https://kbkb-wx-python.blogspot.com/2015/12/python-transparent-colormap.html

Parameters:

<color> (tuple, str) –

either hex-code with (!!) ‘#’ or a tuple consisting of:

  • <R> int | red-channel (0-255)

  • <G> int | green-channel (0-255)

  • <B> int | blue-channel (0-255)

Returns:

colormap to be used with plt.imshow

Return type:

matplotlib.colors.LinearSegmentedColormap object

Example

cm = make_binary_cm((232,255,0))
print(cm) # <matplotlib.colors.LinearSegmentedColormap at 0x7f35f7154a30>
cm = make_binary_cm("#D01B47")
print(cm) # <matplotlib.colors.LinearSegmentedColormap at 0x7f35f7154a30>
lazyfmri.utils.make_chicken_csv()[source]

Create a CSV file for ANTs transformation of coordinates.

Parameters:
  • coord (numpy.ndarray) – Array containing (x, y, z) coordinates.

  • input (str, optional) – Input coordinate system (“ras” or “lps”), by default “ras”.

  • output_file (str, optional) – Output file path.

  • vol (float, optional) – Voxel volume, by default 0.343.

Returns:

Path to the created CSV file.

Return type:

str

Example

from lazyfmri.utils import make_chicken_csv
csv_file = make_chicken_csv(
    np.array([-16.239, -67.23, -2.81]),
    output_file="sub-001_space-fs.csv"
)

print(csv_file)  # "sub-001_space-fs.csv"
lazyfmri.utils.make_diverging_cm(neg_color, pos_color, neutral='#f2f2f2', as_list=False, **kwargs)[source]
lazyfmri.utils.make_diverging_list(values, neg_color='#4b3b8f', pos_color='#c24e00', as_hex=True, use_magnitude=True, **kwargs)[source]

Create a diverging color list mapped to values.

Parameters:
  • values (array-like) – Input values (e.g., effects)

  • neg_color (str) – Color for negative values

  • pos_color (str) – Color for positive values

  • as_hex (bool) – Return hex colors (default True)

  • use_magnitude (bool) – If True, assign gradient based on magnitude

Returns:

List of colors aligned with values

Return type:

list

lazyfmri.utils.make_polar_cmap()[source]

Creates a colormap with an extended HSV color spectrum to denote the polar angle in pRF mapping.

Returns:

Custom colormap with a doubled HSV range.

Return type:

matplotlib.colors.ListedColormap

lazyfmri.utils.make_stats_cm(direction, lower_neg=(51, 0, 248), upper_neg=(151, 253, 253), lower_pos=(217, 36, 36), upper_pos=(251, 255, 72), invert=False)[source]
lazyfmri.utils.match_lists_on()[source]

Match two list based on a BIDS-specifier such as ‘sub’, ‘run’, etc. Can be any key that is extracted using linescanning.utils.split_bids_components().

Parameters:
  • ref_list (list) – List to use as reference

  • search_list (list) – List to search for items in ref_list

  • matcher (str, optional) – BIDS-identifier, by default “run”

Returns:

new search_list filtered for items in ref_list

Return type:

list

Example

>>> # Let's say I have functional files for 3 runs
>>> func_file
>>> ['sub-003_ses-3_task-SR_run-3_bold.mat',
>>> 'sub-003_ses-3_task-SR_run-4_bold.mat',
>>> 'sub-003_ses-3_task-SR_run-6_bold.mat']
>>> # and anatomical slices for 5 runs
>>> anat_slices
>>> ['sub-003_ses-3_acq-1slice_run-2_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-3_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-4_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-5_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-6_T1w.nii.gz']
>>> # I can then use `match_list_on` to find the anatomical slices corresponding to the functional files
>>> from linescanning import utils
>>> utils.match_lists_on(func_file, anat_slices, matcher='run')
>>> ['sub-003_ses-3_acq-1slice_run-3_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-4_T1w.nii.gz',
>>> 'sub-003_ses-3_acq-1slice_run-6_T1w.nii.gz']
lazyfmri.utils.multiselect_from_df(df, expression=[])[source]
lazyfmri.utils.pairwise(l1)[source]
lazyfmri.utils.parse_kwargs_to_dict(input_list, delimiter='=')[source]

Parse a string or list of key-value pairs into a dictionary.

Supports automatic type conversion for booleans, numbers, and lists.

Parameters:
  • input_list (str) – A single key=value pair (e.g., “alpha=0.01”) or a comma-separated string of such pairs (e.g., “alpha=0.01,beta=0.5,debug=True”). Values can be lists separated by ‘|’, e.g., “layers=conv|pool|fc”.

  • delimiter (str, optional) – The character used to separate keys from values, by default “=”.

Returns:

Dictionary of parsed key-value pairs with appropriate types.

Return type:

dict

Examples

>>> parse_kwargs_to_dict("alpha=0.01,beta=0.5,debug=True")
{'alpha': 0.01, 'beta': 0.5, 'debug': True}
>>> parse_kwargs_to_dict("layers=conv|pool|fc")
{'layers': ['conv', 'pool', 'fc']}
>>> parse_kwargs_to_dict("use_dropout=False,epochs=10")
{'use_dropout': False, 'epochs': 10}
lazyfmri.utils.percent_change()[source]

Function to convert input data to percent signal change. Two options are current supported: the nilearn method (nilearn=True), where the mean of the entire timecourse if subtracted from the timecourse, and the baseline method (nilearn=False), where the median of baseline is subtracted from the timecourse.

Parameters:
  • ts (numpy.ndarray) – Array representing the data to be converted to percent signal change. Should be of shape (n_voxels, n_timepoints)

  • ax (int) – Axis over which to perform the conversion. If shape (n_voxels, n_timepoints), then ax=1. If shape (n_timepoints, n_voxels), then ax=0.

  • nilearn (bool, optional) – Use nilearn method, by default False

  • baseline (int, list, np.ndarray optional) – Use custom method where only the median of the baseline (instead of the full timecourse) is subtracted, by default 20. Length should be in volumes, not seconds. Can also be a list or numpy array (1d) of indices which are to be considered as baseline. The list of indices should be corrected for any deleted volumes at the beginning.

Returns:

Array with the same size as ts (voxels,time), but with percent signal change.

Return type:

numpy.ndarray

Raises:

ValueError – If ax > 2

lazyfmri.utils.print_cmd_highlight(cmd)[source]

Print a shell command with the executable in bold blue, using the color class.

Parameters:

cmd (str) – The full command string to print.

lazyfmri.utils.read_chicken_csv()[source]

Function to get at least the coordinates from a csv file used with antsApplyTransformsToPoints. (see https://github.com/stnava/chicken for the reason of this function’s name)

Parameters:
  • chicken_file (str) – path-like string pointing to an input file (.csv!)

  • return_type (str) – specify the coordinate system that the output should be in

Returns:

(3,) array containing the coordinate in chicken_file

Return type:

numpy.ndarray

Example

read_chicken_csv(“sub-001_space-fs_desc-lpi.csv”)

lazyfmri.utils.remove_files()[source]

Remove files from a given path that containg a string as extension (ext=True), or at the start of the file (ext=False)

Parameters:
  • path (str) – path to the directory from which we need to remove files

  • string (str) – tag for files we need to remove

  • ext (str, optional) – only remove files containing string that end with ext

lazyfmri.utils.reverse_sign()[source]

Inverts the sign of given values.

Parameters:

x (int, float, list, numpy.ndarray) – Input value(s) to be inverted.

Returns:

Values with inverted sign.

Return type:

Same type as input

Example

from lazyfmri.utils import reverse_sign
print(reverse_sign(5))  # -5
print(reverse_sign(np.array([2, -2340, 2345, 123])))
# array([-2, 2340, -2345, -123])
lazyfmri.utils.round_decimals_down(number: float, decimals: int = 2)[source]

Returns a value rounded down to a specific number of decimal places. see: https://kodify.net/python/math/round-decimals/#round-decimal-places-up-and-down-round

lazyfmri.utils.round_decimals_up(number: float, decimals: int = 2)[source]

Returns a value rounded up to a specific number of decimal places. see: https://kodify.net/python/math/round-decimals/#round-decimal-places-up-and-down-round

lazyfmri.utils.run_shell_wrapper(cmd, msg=None, verb=False)[source]

Execute a shell command with optional verbose logging and error handling.

This function runs a shell command using subprocess, capturing output and printing informative messages. If msg is provided, it will be printed before executing. If the command fails, both stdout and stderr will be printed for debugging.

Parameters:
  • cmd (str) – The full shell command to execute.

  • msg (str, optional) – Message to print before executing the command.

  • verb (bool, default=False) – If True, echo the command being run with highlighting.

Return type:

None

Notes

  • Uses shell=True, so ensure cmd is properly sanitized.

  • Automatically captures and displays stdout/stderr on failure.

  • Intended as a user-friendly wrapper for external CLI tools.

Example

run_shell_wrapper(“fslmaths input.nii.gz -abs output.nii.gz”, msg=”Running FSL abs”)

lazyfmri.utils.select_files_from_bids(inputdir, filters=['acq-MP2RAGE_', 'inv'], get_kws={}, **kwargs)[source]

Selects files from a BIDS-formatted directory using pybids and optional substring filters.

This function wraps around BIDSLayout.get() to retrieve NIfTI files from a BIDS dataset, with optional keyword arguments and substring filtering.

Parameters:
  • inputdir (str) – Path to the BIDS dataset directory or a subfolder (e.g., …/sub-01/anat).

  • filters (str or list of str, optional) – Substrings used to filter the resulting list of files. Only files containing all specified substrings will be returned. If set to None, all matching files are returned. Default is [’acq-MP2RAGE_’, ‘inv’].

  • get_kws (dict, optional) – Additional keyword arguments to pass to BIDSLayout.get(). These are merged with default values for ‘extension’ and ‘return_type’.

  • **kwargs (dict) – Additional keyword arguments passed to the BIDSLayout constructor (e.g., config, database_path).

Returns:

List of file paths that match the specified filters and BIDS selection criteria.

Return type:

list of str

Notes

  • The function defaults to selecting .nii.gz files and returns their full paths.

  • If inputdir ends with “anat”, the BIDS data_type is automatically set to “anat”.

  • If filters is provided, the results are further reduced to only those containing the given substring(s).

lazyfmri.utils.select_from_df()[source]

Selects a subset of a pandas DataFrame based on an expression, index-based selection, or column filtering.

This function provides flexible data selection methods: - Using an expression, which consists of a column name and an operator (e.g., ‘task = “rest”’). - Using indices, which selects columns based on a list, range, or numpy array. - Optionally reindexing the output DataFrame.

Parameters:
  • df (pandas.DataFrame) – The input dataframe.

  • expression (str, list, tuple, optional) – The condition(s) to filter the DataFrame rows. Expressions should be in the format: “column operator value” where operator can be one of: ‘=’, ‘>’, ‘<’, ‘>=’, ‘<=’, ‘!=’. Multiple expressions can be combined with & (logical AND). Example: “task = ‘rest’”, “age > 30”, [“task = ‘rest’”, “&”, “age > 30”].

  • index (bool, optional) – Whether to return the output DataFrame with the same indexing as df. Default is True.

  • indices (list, range, numpy.ndarray, optional) – Specifies column indices to select from df. This can be: - A list of column names or indices. - A range object. - A numpy.ndarray containing column indices. If indices is specified, expression is ignored.

  • match_exact (bool, optional) – If indices is a list of strings, determines how column names are matched: - True (default): Exact matches only. - False: Partial matches (i.e., column names that contain the given strings).

Returns:

A new DataFrame with rows/columns selected based on expression or indices.

Return type:

pandas.DataFrame

Raises:
  • TypeError – If indices is not a tuple, list, or array.

  • ValueError – If an expression does not match any row in df.

Examples

Select rows based on an expression:

import pandas as pd
from lazyfmri.utils import select_from_df

# Create example DataFrame
data = {
    "subject": [1, 2, 3, 4],
    "age": [25, 30, 35, 40],
    "task": ["rest", "active", "rest", "active"]
}
df = pd.DataFrame(data)

# Select rows where task is "rest"
df_filtered = select_from_df(df, expression="task = 'rest'")

print(df_filtered)
# Output:
#    subject  age  task
# 0       1   25  rest
# 2       3   35  rest

Select columns by index range:

df_filtered = select_from_df(df, indices=range(0, 2))
print(df_filtered)
# Output:
#    subject  age
# 0       1   25
# 1       2   30
# 2       3   35
# 3       4   40

Select multiple conditions using AND (`&`):

df_filtered = select_from_df(df, expression=["task = 'rest'", "&", "age > 30"])
print(df_filtered)
# Output:
#    subject  age  task
# 2       3   35  rest
lazyfmri.utils.split_bids_components(fname, entities=False, add_elements=None)[source]
lazyfmri.utils.str2operator(ops)[source]
lazyfmri.utils.string2float()[source]

This function converts a array in string representation to a regular float array. This can happen, for instance, when you’ve stored a numpy array in a pandas dataframe (such is the case with the ‘normal’ vector). It starts by splitting based on empty spaces, filter these, and convert any remaining elements to floats and returns these in an array.

Parameters:

string_array (str) – string to be converted to a valid numpy array with float values

Returns:

array containing elements in float rather than in string representation

Return type:

numpy.ndarray

Example

string2float(’[ -7.42 -92.97 -15.28]’) array([ -7.42, -92.97, -15.28])

lazyfmri.utils.string2list()[source]

Convert a string representation of a list into an actual Python list.

Parameters:
  • string_array (str) – String containing a list representation.

  • make_float (bool, optional) – Whether to convert list elements to float, by default False.

Returns:

Parsed list.

Return type:

list

Example

from lazyfmri.utils import string2list
lst = string2list('[tc,bgfs]')
print(lst)  # ['tc', 'bgfs']
lazyfmri.utils.update_kwargs(kwargs, el, val, force=False)[source]
lazyfmri.utils.validate_cli_inputs(required_keys=None, allow_input_dir=False, docstring=None)[source]

Decorator factory to validate command-line input context before executing the target function.

This decorator checks that all of the keys specified in required_keys are present and non-empty in the context dictionary passed as a keyword argument to the decorated function. If any required key is missing, or if an input directory (if provided) is invalid when allow_input_dir is True, the decorator prints an error message along with a help message (either custom via docstring or the target function’s own docstring) and then exits the script.

Parameters:
  • required_keys (list, optional) – A list of keys that must be present and truthy in the context dictionary.

  • allow_input_dir (bool, optional) – If True, the decorator also accepts a valid “input_dir” key in the context (i.e., a string that is a path to an existing directory) as an alternative to having all the required keys.

  • docstring (str, optional) – A custom help message to display if validation fails. If not provided, the docstring of the decorated function is used.

Returns:

decorator – A decorator that, when applied to a function, validates its context keyword argument before allowing the function to execute.

Return type:

function

Example

@validate_cli_inputs(required_keys=[“R1”, “R2”, “QSM”], allow_input_dir=True,

docstring=”Custom help message or usage instructions.”)

def main(argv, context):

# function body here …

lazyfmri.utils.verbose(msg, verbose, flush=True, highlight=False, **kwargs)[source]