Modules

Affine transformations

Defines classes for affine transformations, rigid body transformations, and orthonormal transformations, and functions for manipulating and calculating inverses of affine transformations.

class fmristats.affines.Affine(affine)

An affine transformation

Affine transformations are stored in homologous coordinates.

Parameters:affine (ndarray, shape (4,4)) – An affine transformation in homologous coordinates.
apply(x)

Apply affine transformation

Will apply the affine transformation to the matrix or vector x.

Parameters:x (ndarray, shape (3,) or (..,3)) – Vector or matrix of (row) vectors.
Returns:The result of the affine applied to the matrix (or vector) x, in particular, it will be of the same shape.
Return type:ndarray
apply_to_index(index)

Apply affine transformation to index

Parameters:index (3-tuple) – 3-tuple of int
Returns:The result of the affine applied to the index.
Return type:ndarray
apply_to_indices(indices)

Apply affine transformation to indices

Parameters:index (3-tuple) – 3-tuple of Slice or Ellipse objects.
Returns:The result of the affine applied to the indices.
Return type:ndarray
aspect(x, y)
Parameters:
  • x (int, either 0,1,2) – x
  • y (int, either 0,1,2) – y
Returns:

The aspect ratio of the respected resolution.

Return type:

float

dot(x)

Matrix multiplication with x

Parameters:x (Affine or Affines) – An affine transformation.
Returns:Output has the same type as x.
Return type:Affines or Affines
euler()

Calculate Euler angles

inv()

Calculates the inverse of an affine transformation

If the affine transformation is rigid, i.e., of the form A⋅x + b with A being a rotation matrix, then a more numerical stable algorithm for calculating the inverse is used than otherwise.

Returns:
Return type:The inverse of the affine transformation.
resolution()

Resolution

The resolution is the length of the base vectors (1,0,0), (0,1,0), and (0,0,1) after being mapped to by this affine transformations. The length of A⋅b, for A being this affine transformation and b being one of the three basis vectors is the norm of A⋅b - A⋅0.

save(file, **kwargs)

Save instance to disk

Parameters:file (str) – A file name.
volume()

Volume of the parallelepiped spanned by the image of the canonical basis

class fmristats.affines.Affines(affines)

Affine transformations

Affine transformations are stored in homologous coordinates.

apply(x)

Apply affine transformations to a vector

Will apply the affine transformations to the vector x.

Parameters:x (ndarray, shape (3,)) – Vector to which the affine transformations are applied
Returns:
Return type:The result of the affine transformations applied to x.
apply_to_index(index)

Apply affine transformation to index

Parameters:index (3-tuple) – 3-tuple of int
Returns:The result of the affine applied to the index.
Return type:ndarray
dot(x)

Matrix multiplication (a.k.a. dot product) with the affines transformation x

This will performe a matrix multiplication of each affine transformation with x.

Parameters:x (Affine) – An affine transformation.
Returns:
Return type:The result of the calculation is again of type Affines.
euler()

Calculate Euler angles for all affine transformations

Notes

This only makes sense, if the affine transformations are rigid.

inv()

Calculates the inverse of an affine transformation

If the affine transformation is rigid, i.e., of the form A⋅x + b with A being a rotation matrix, then a more numerical stable algorithm for calculating the inverse is used than otherwise.

Returns:
Return type:The inverse of the affine transformation.
mean()

Calculates the mean affine transformation

Returns:The mean affine transformation.
Return type:Affine

Notes

Some basic non-Euclidean statistics is used here.

mean_rigid()

Calculates the mean rigid transformation of rigid transformations

Returns:The mean rigid affine transformation.
Return type:Affine

Notes

Some basic non-Euclidean statistics is used here.

mean_within_windows(r=0, skip=None)

Calculates the mean rigid transformation of the rigid transformation within a window of [-r,r] around each transformation.

save(file, **kwargs)

Save instance to disk

Parameters:file (str) – A file name.
fmristats.affines.is_rotation_matrix(a, **kwargs)

Test if a 3x3-matrix is a rotation matrix

Parameters:
  • a (ndarray, shape (n,n)) – an darray
  • **kwargs – parameters passed on to np.close.
Returns:

True or False.

Return type:

bool

Notes

The function assumes that a is square.

fmristats.affines.isclose(x, y, **kwargs)

Test if two affines are close to each other

Parameters:
  • x (Affine) – an affine transformation.
  • y (Affine) – an affine transformation.
  • **kwargs – parameters passed on to np.close.
Returns:

True or False.

Return type:

bool

fmristats.affines.isinverse(x, y, **kwargs)

Test if two affines are inverses of each other

Parameters:
  • x (Affine) – an affine transformation.
  • y (Affine) – an affine transformation.
  • **kwargs – parameters passed on to np.close.
Returns:

True or False.

Return type:

bool

The FMRI Session

Defines a class for FMRI sessions, which allows to define the experimental setting and design, and to set up necessary parameters needed for the statistical analysis of single subject data.

class fmristats.session.Session(name, data, epi_code, spacial_resolution, temporal_resolution, reference)

A FMRI session

Collects attributes which reasonably define a FMRI session, e.g., experimental design, the on- and offsets of the blocks or events of the paradigm, the observed FMRI signals.

Parameters:
  • name (Identifier) – The name or of the FMRI experiment
  • data (array, shape (t,x,y,z)) – The data of observations, where t is the number of scan cycles
  • epi_code (int) – Coded EPI sequence, either one of -3, -2, -1, 1, 2, 3
  • spacial_resolution (ndarray, shape (3,), dtype: float) – Spacial resolution of the image
  • temporal_resolution (float) – Temporal resolution of the image
  • reference (Affine or ndarray, shape (4,4), dtype: float) – The scanner reference
descriptive_statistics()

Descriptive statistics for assessing the quality of the MR-signal on scan cycle level.

descriptive_statistics_detailed()

Descriptive statistics for assessing the quality of the MR-signal on scan level.

save(file, **kwargs)

Save model instance to disk

This will save the current model instance to disk for later use.

Parameters:file (str) – File name.
set_slice_timing(slice_timing=None, interleaved=False)

Set up the slice time information

Parameters:slice_timing (ndarray of float, shape (n,) or (n,x,y,z)) – The time vector indicating the point in time at which a given slice of the acquisition grid has been measured. If slice_timing has shape (n,), all slices of a scan cycle are assumed to have been measured during the same time.
set_stimulus(stimulus)

Set up the stimulus

fmristats.session.create_slice_timing(shape, epi_code, temporal_resolution, interleaved=None)

Creates a time vector from parameters

Parameters:
  • shape (tuple, type: int) –
  • epi_code (int or None) –
  • temporal_resolution (float) – The temporal resolution.
  • interleaved (bool) –
Returns:

The time vector that holds the slices time information. The vector holds the start point of the time at which a particular slice has been measured. If ep is None, slice_time has shape (M,) with M equal to the number of full scan cycles. If ep is int, then slice_time has the same shape as the data.

Return type:

ndarray of float, shape (M,) or (M,N,O,P)

fmristats.session.fmrisetup(session, stimulus)

If a session instance was created using the basic information in a Nifti1 file, this will complete the set-up of the session by providing the rest of the necessary FMRI session information: stimulus design (a.k.a paradigm).

Parameters:
  • session (Session) –
  • stimulus (Stimulus) –

The Reference Maps

Subjects may tend to move their head in the scanner ever so slightly, which means that the tilt and position of the head during the FMRI session may change over time. For this reason, we need to track the subject head in the scanner, i.e. we need to find and estimate its tilt and position at a given time point. Mathematically, head movements are affine transformations (rigid body transformations) that map from a space with a subject-specific coordinate system to the scanner space (or in other words from a coordinate system that is fixed with respect to the subject to a coordinate system that is fixed with respect to the scanner). The subject reference space will always be denoted by \(R\), and the scanner space by \(S\). We may then identify head movements with the maps:

\[ρ_t : R \to S.\]

These maps will be called reference maps: \(ρ_t\) is called the reference map of scan \(t\). Reference maps \(ρ_t\) are functions that map from subject reference space to the location and orientation of the subject brain in the scanner at a given time point.

The inverse of \(ρ_t\) is called the acquisition map of scan \(t\):

\[ρ_t^{-1} : S \to R.\]

Hence, the acquisition map of scan \(t\) maps from scanner space to subject reference space.

class fmristats.reference.ReferenceMaps(name)

Reference maps are functions that map from the subject reference space to the location and orientation of the subject brain in the scanner at a given time point.

Parameters:name (Identifier) – The identifier of the subject
describe()

Give a description of the instance

descriptive_statistics()

Give descriptive statistics of the instance

detect_outlying_scans(sgnf)

Detect outlying scans

Parameters:sgnf (float) – Significance level at which a test for the existence of a outlier is tested.
Returns:True if the particular full scan cycle is considered an outlier.
Return type:ndarray of bool

Notes

Uses the eigenvalues of the pcm method for outlier detection. (Currently only full scan cycles supported.)

The algorithm will mark scan cycles as False which have eigenvalues which differ significantly from the eigenvalues all other scan cycles, as this likely is the result of severe head movement during the measurement of this cycle.

Grubbs’ test is used recursively for the outlier detection. The norm of all three semi axis length and each single semi axis length is tested for outlier separately.

It should simply give you an idea on how severe head movements might have been, and allow you to remove the most obvious outliers.

fit(session, use_raw=True)

Fit head movement

This will fit rigid body transformations to the data, i.e. it will estimate the position and bearing of the head in each scan cycle.

Parameters:
  • session (Session) – The FMRI session data of the subject.
  • use_raw (bool) – Use the raw data or only the data in the foreground.

Notes

The function implements a principle axis method for rigid body tracking.

reset_reference_space(x=None, cycle=None)

This will reset the coordinates system of the reference space

Parameters:
  • x (None or Affine or ndarray, shape (4,4), dtype: float) – An affine transformation or None (default)
  • cycle (None or int) – Index of a scan cycle or None

Notes

This will reset the coordinates system of the subject reference space by moving origin and base vectors to the new position specified by the transformation x. The affine transformation \(x\) goes from this reference space to the new reference space.

\[x : R \to R'.\]

If the affine transformation has the form x(\(x\))= \(Ax+b\), then \(b\) is the new origin and \(A\) defines the new orientation.

If x=None, then x will be set to the inverse of the mean of the acquisition maps. This has the consequence that the new reference space is identical to the average position of the subject head in the scanner. If x=None and cycle is integer \(t_0\), then \(x\) is set to:

\[x = ρ_{t_0}.\]

This has the consequence that the new subject reference space equals the position of the subject head during scan cycle \(t_0\).

References maps are the maps \(ρ_t\) which map from subject reference space to scanner:

\[ρ_t : R \to S.\]

Acquisition maps are the inverses of the maps \(ρ_t\) and map from scanner space to subject reference space:

\[ρ_t^{-1} : S \to R.\]

The new subject reference space \(R'\) is equal to \(R':=x[R]\), and the new acquisition maps are therefore:

\[ρ_t^{'-1} = x ∘ ρ^{-1}_t\]

Then:

\[ρ'_t : R' \to S\]

Warning: Resetting the reference space makes all population maps which have been defined for this subject reference space obsolete. You should thus perform this operation prior to fitting any population maps.

save(file, **kwargs)

Save instance to disk

This will save the instance to disk for later use.

Parameters:file (str) – File name.
set_acquisition_maps(maps)

The subject reference space of the fMRI experiment

This will define the subject reference space of an FMRI experiment.

Parameters:maps (Affines or ndarray, shape (n,4,4), dtype: float) – Acquisition maps. Rigid body transformations that map from scanner space to subject reference space.

Notes

The subject reference space is uniquely defined by these affine transformations.

The Population Space

A population map is a diffeomorphism from a population space to the subject reference space of a FMRI session.

class fmristats.pmap.PopulationMap(diffeomorphism, vb=None, nb=None, vb_background=None, nb_background=None, vb_estimate=None, nb_estimate=None, vb_mask=None, nb_mask=None)

A population map is a diffeomorphism from a population space to the reference space of a FMRI session.

Parameters:
  • diffeomorphism (subclass of Diffeomorphism) – The diffeomorphism ψ that maps from vb (the population space) to nb (the subject space).
  • vb (None, Image or ndarray) – An image in population space.
  • nb (None, Image or ndarray) – An image in subject space.
  • vb_background (None, Image or ndarray) – An image in population space.
  • nb_background (None, Image or ndarray) – An image in subject space.
  • vb_estimate (None, Image or ndarray) – An image in population space.
  • nb_estimate (None, Image or ndarray) – An image in subject space.
  • vb_mask (None, Image or array) – An image in population space.
  • nb_mask (None, Image or array) – An image in subject space.
  • vb_ati (None, Image or array) – An image in population space that will serve as the reference field for the BOLD unit.

Notes

If vb (or any of the other arguments) is an Image, it will be checked whether its reference affine agrees with the reference affine of the diffeomorphism ψ. If vb is an ndarray, its shape must be equal to the shape of the diffeomorphism, as it will then be assumed that they share the same reference affine: the vb’s reference will be set identical to the reference of the diffeomorphism.

If the software which has been used to fit the diffeomorphism creates a warped images of its inputs, they can be stored in vb_estimate and nb_estimate respectively.

There appears to be no clear naming convention for images in vb and nb. Examples for images in vb and nb are input, target, template, reference, moving, fixed, and more: The intuitive meaning of what these images shall represent is often (and not always) clear from the context, but the question which of these images live in vb or nb is ambiguous at best. Say, when fitting a diffeomorphism providing an algorithm with the arguments reference and input (FNIRT) or fixed and moving (ANTS): does the diffeomorphism go from reference to input or vice versa?

save(file, **kwargs)

Save instance to disk

Parameters:file (str) – A file name.
set_nb(image)

Set or reset the image in nb

Parameters:image (Image or ndarray) – The image or data array.
set_nb_background(image)

Set or reset the background image in nb

Parameters:image (Image or ndarray) – The image or data array.
set_nb_estimate(image)

Set or reset the estimate of the image in nb

Parameters:image (Image or ndarray) – The image or data array.
set_nb_mask(image)

Set or reset the estimate of the image in nb

Parameters:image (Image or ndarray) – The image or data array.
set_vb(image)

Set or reset the image in vb

Parameters:image (Image or ndarray) – The image or data array.

Notes

If image is an Image, it will be checked whether its reference agrees with the reference of the diffeomorphism. If image is an ndarray, it must be equal to the shape stored with the diffeomorphism, as it will then be assumed that they share the same reference: the image’s reference will be set identical to the reference of the diffeomorphism.

set_vb_ati(image)

Set or reset the reference field for the BOLD unit.

Parameters:image (Image or ndarray) – The image or data array.

Notes

If image is an Image, it will be checked whether its reference agrees with the reference of the diffeomorphism. If image is an ndarray, it must be equal to the shape stored with the diffeomorphism, as it will then be assumed that they share the same reference: the image’s reference will be set identical to the reference of the diffeomorphism.

set_vb_background(image)

Set or reset the background image in vb

Parameters:image (Image or ndarray) – The image or data array.

Notes

If image is an Image, it will be checked whether its reference agrees with the reference of the diffeomorphism. If image is an ndarray, it must be equal to the shape stored with the diffeomorphism, as it will then be assumed that they share the same reference: the image’s reference will be set identical to the reference of the diffeomorphism.

set_vb_estimate(image)

Set or reset the estimate for the image in vb

Parameters:image (Image or ndarray) – The image or data array.

Notes

If image is an Image, it will be checked whether its reference agrees with the reference of the diffeomorphism. If image is an ndarray, it must be equal to the shape stored with the diffeomorphism, as it will then be assumed that they share the same reference: the image’s reference will be set identical to the reference of the diffeomorphism.

set_vb_mask(image)

Set or reset the estimate for the image in vb

Parameters:image (Image or ndarray) – The image or data array.

Notes

If image is an Image, it will be checked whether its reference agrees with the reference of the diffeomorphism. If image is an ndarray, it must be equal to the shape stored with the diffeomorphism, as it will then be assumed that they share the same reference: the image’s reference will be set identical to the reference of the diffeomorphism.

fmristats.pmap.pmap_scanner(session, reference_maps=None, scan_cycle=None, resolution=2.0, name='scanner')

The identity map

Sets the standard space equal to the coordinate system of the scanner and the diffeomorphism from standard space to subject reference space to different rigid body transformations.

Parameters:
  • session (Session) – A FMRI session
  • reference_maps (None or ReferenceMaps) – Reference Maps
  • scan_cycle (None or int) – Reference scan cycle.
  • resolution (str or float) – Resolution (in units of the session reference, this will likely be milli meter), default 2. If resolution is set to ‘native’ the resolution of the scanner is used.
  • = str (name) – A name for this population map.

Notes

When only studying a single subject, it is possible to set the standard space to an isometric image of the subject’s head, i.e. to a space which preserves distances with respect to the subject.

In other words, for a single subject, the standard space can be set equal to the subject reference space \(R\) or to \(ρ_t[R]\) for any time point \(t\) in the Session.

You may even set \(R\) identical to \(S\) if scanner and subject reference space are reasonable »close«. This may be archived by calling reset_reference_space() of the reference maps. If called without arguments, this will have the effect that the population space is then equal to the mean location of the subject in the scanner.

The Population Map

Defines classes for diffeomorphisms which are not necessarily affine transformations.

class fmristats.diffeomorphisms.AffineTransformation(reference, affine, shape, vb=None, nb=None, name=None)

An affine transformation ψ mapping from a standard space \(M\) to a subject reference space \(R\). It is

\[ψ (x) = A⋅x.\]

for \(x∈M\) and \(A\) an affine transformation.

A point [i,j,k] in the index space of the template in \(M\) maps to the coordinates

\[ψ(reference[i,j,k]) = A ⋅ reference[i,j,k]\]

in the subject reference space.

Parameters:
  • reference (Affine or ndarray, shape (4,4)) – An affine transformation
  • affine (Affine or ndarray, shape (4,4)) – An affine transformation
apply(coordinates)

Apply diffeomorphism to the point at given coordinate

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_index(index)

Apply diffeomorphism to the point with given index

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_indices(indices)

Apply diffeomorphism to the points with given indices

Parameters:index (tuple) – Should be a tuple of slices or ellipses
Returns:
Return type:ndarray
class fmristats.diffeomorphisms.Diffeomorphism(reference, shape, vb=None, nb=None, name=None, metadata=None)

A diffeomorphism ψ from standard space to subject space

Parameters:
  • reference (Affine or ndarray, shape (4,4)) – An affine transformation
  • shape (tuple) – Shape of template data in standard space.
  • vb (None or str or Identifier) – An object that will be used to identify the domain (vb) of this diffeomorphism.
  • nb (None or Identifier) – An object that will be used to identify the image (nb) of this diffeomorphism.
  • name (None or str) – Method that has produced this diffeomorphism.
  • metadata (dict) – If meta data is provided which give information on which data had been used for the fit: which had provided, should be a dict with at least the following fields: {'vb_file': path/which/defined/the/domain, 'nb_file': path/which/defined/the/image,}.

Notes

A reasonable subclass of Diffeomorphism must define the attributes apply_to_index(), apply_to_indices(), and apply().

apply(coordinates)

Apply diffeomorphism to the point at given coordinate

This is the identity; it will return the same coordinates

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_index(index)

Apply diffeomorphism to the point with given index

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_indices(indices)

Apply diffeomorphism to the points with given indices

Parameters:index (tuple) – Should be a tuple of slices or ellipses
Returns:
Return type:ndarray
coordinates()

Coordinates in the image

Returns:
Return type:ndarray
coordinates_domain()

Coordinates in the domain

Returns:
Return type:ndarray
save(file, **kwargs)

Save instance to disk

Parameters:file (str) – A file name.
class fmristats.diffeomorphisms.Displacement(reference, displacement, vb=None, nb=None, name=None)

A diffeomorphism ψ mapping from a population space \(M\) to a subject space $R$. Here, it is

\[ψ (x) = x + δ(x).\]

for a displacement field \(δ\).

A point [i,j,k] in the index space of the template of \(M\) maps to the coordinates

\[ψ(reference[i,j,k]) = reference[i,j,k] + displacement[i,j,k]\]
Parameters:
  • reference (Affine or ndarray, shape (4,4)) – An affine transformation.
  • displacement (ndarray (?,?,?,3)) – A displacement field
  • vb (str or Identifier) – An object that will be used to identify the domain (vb) of this diffeomorphism.
  • nb (str or Identifier) – An object that will be used to identify the image (nb) of this diffeomorphism.
  • metadata (dict) – If meta data is provided which give information on which data had been used for the fit: which had provided, should be a dict with at least the following fields: {'vb_file': path/which/defined/the/domain, 'nb_file': path/which/defined/the/image,}.
apply(coordinates)

Apply diffeomorphism to the point at given coordinate

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray

Notes

There are interpolations at place here, which makes this potentially slow for large queries.

apply_to_index(index)

Apply diffeomorphism to the point with given index

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_indices(indices)

Apply diffeomorphism to the points with given indices

Parameters:index (tuple) – Should be a tuple of slices or ellipses
Returns:
Return type:ndarray
class fmristats.diffeomorphisms.Identity(reference, shape, vb=None, nb=None, name=None)

The identity diffeomorphism ψ.

apply(coordinates)

Apply diffeomorphism to the point at given coordinate

This is the identity; it will return the same coordinates

Parameters:index (tuple) – Should be a tuple of integers.
Returns:
Return type:ndarray
apply_to_index(index)

Apply diffeomorphism to the point with given index

Parameters:index (tuple) – Should be a tuple of integers.
Returns:
Return type:ndarray
apply_to_indices(indices)

Apply diffeomorphism to the points with given indices

Parameters:index (tuple) – Should be a tuple of slices or ellipses.
Returns:
Return type:ndarray
class fmristats.diffeomorphisms.Image(reference, data, name=None)

Holds all information of a 3D-image.

Parameters:
  • reference (Affine or ndarray, shape (4,4)) – An affine transformation that maps indices in the data array to coordinates in Euclidean space.
  • data (np.ndarray) – The data array.
  • name (str or Identifier) – An identifier or name for this image.
components(threshold, component_size=None, direction='lower')

Components of an image

Enumerates (more precisely: labels) the components above or below the given threshold in the image.

Parameters:
  • threshold (float) – The threshold
  • component_size (float) – Minimal volume for a component to be labelled
  • direction (str, 'lower' or 'upper') – Direction of the cut. Default is ‘lower’.
Returns:

  • labelled (Image) – The labelled image
  • labels (list) – The labels in the image

Notes

Please note that the component_size is expected to be given in mm^3 and not as the number of voxels.

describe()

Describe the image

Returns:
Return type:str
detect_peaks(connectivity=3, **kwargs)

Detects the peaks in an image

Takes an image and detect the peaks using a local maximum filter. Returns a boolean mask of the peaks (i.e. 1 when the pixel’s value is the neighbourhood of a maximum and 0 otherwise)

flatten(epi_code, xpic, ypic, slices=None)

Flatten a 3D image into a 2D image

Parameters:epi_code (int) –
Returns:
Return type:ndarray

Notes

Flattens by slicing the 3D image along the axis of the respected EPI code, and stack the slices into a xpic x ypic matrix

get_mask(**kwargs)

Create a mask

Returns:boolean array which is True whenever values in the data are valid.
Return type:ndarray, dtype(bool)
mask(mask=None, inplace=True)

Mask the data array by mask

Parameters:mask (ndarray, dtype(bool)) – An array of bool indicating the foreground
Returns:The same image but with data set to nan outside the mask
Return type:Image
mean()

Calculates the mean value in the image

Notes

Values of 0 or nan will not contribute to the mean signal. If your image img contains 0 values, then im.data.mean() and im.mean() will differ and this is intended.

Returns:float
Return type:mean value of the image
range()

Return the range of values in the image

Notes

Values of 0 or nan will not contribute to the range.

Returns:tuple
Return type:(minimum, maximum)
ravel()

Return a contiguous flattened array of the image

A 1-D array, containing the non-null, and non-nan elements of the input, is returned. Array is a copy of the data.

round()

Round data in the image to integer

Returns:
Return type:Image
save(file, **kwargs)

Save instance to disk

Parameters:file (str) – A file name.
volume()

Calculates the volume occupied by the image

Returns:float
Return type:volume of non-zero values in the image
class fmristats.diffeomorphisms.Warp(reference, warp, vb=None, nb=None, name=None, metadata=None)

A diffeomorphism ψ mapping from a population space \(M\) to a subject space $R$. Here, it is

\[ψ (x) = δ(x).\]

for a warp field \(δ\).

A point [i,j,k] in the index space of the template of \(M\) maps to the coordinates

\[ψ(reference[i,j,k]) = warp[i,j,k]\]

An example: The FSL FNIRT warp coefficients file is saved as a Warp instance.

Parameters:
  • reference (Affine or ndarray, shape (4,4)) – An affine transformation
  • warp (ndarray (..,3)) – A warp field
  • vb (str or Identifier) – An object that will be used to identify the domain (vb) of this diffeomorphism.
  • nb (str or Identifier) – An object that will be used to identify the image (nb) of this diffeomorphism.
  • metadata (dict) – If meta data is provided which give information on which data had been used for the fit: which had provided, should be a dict with at least the following fields: {'vb_file': path/which/defined/the/domain, 'nb_file': path/which/defined/the/image,}.
apply(coordinates)

Apply diffeomorphism to the point at given coordinate

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray

Notes

There are interpolations at place here, which makes this potentially slow for large queries.

apply_to_index(index)

Apply diffeomorphism to the point with given index

Parameters:index (tuple) – Should be a tuple of integers
Returns:
Return type:ndarray
apply_to_indices(indices)

Apply diffeomorphism to the points with given indices

Parameters:index (tuple) – Should be a tuple of slices or ellipses
Returns:
Return type:ndarray

The FMRI Signal Model

Defines a class for the FMRI signal model and its fits.

class fmristats.smodel.Result(coordinates, statistics, population_map, hyperparameters, parameter_dict, value_dict)

Result of a FMRI fitting

Defines a class for the result, i.e., the estimated effect field of an FMRI experiments, fitted by the function attribute of the FMRI class.

Parameters:
  • name (Identifier) – An identifier
  • population_map (PopulationMap) –
  • field (ndarray, shape (,3), dtype: float) – The effect or fitted model parameter field
  • coordinates (ndarray, shape (,3), dtype: float) –
  • hyperparameters (dict) –
  • parameters (dict {str: int}) – The names of the parameters which have been fitted by the signal model in the order of appearance in the model.
get_field(param, value=None)

Extract scalar field

Parameters:
  • param (str) – Check the attribute parameter_dict for possible values of param.
  • value (str) – Check the attribute value_dict for possible values of value. Note that ‘tstatistic’ is also valid and will be calculated from the key point and stderr.
Returns:

The queried field

Return type:

Image

Notes

It only makes sense to combine intercept or activation with point, stderr, and tstatistic, and it only makes sense to combine other with mse (an estimate of sigma-squared) or df (residual degrees of freedom)

mask(mask=True, verbose=False)

Apply mask to parameter fields

norm_to(rf)

Norm the part of the statistics field that has a unit, to a reference field.

Parameters:rf (Image) – The reference field for the unit.
norm_to_ati()

Norm the part of the statistics field that has a unit, to the ati-reference field that is stored in the PopulationMap.

save(file, **kwargs)

Save instance to disk

This will save the current instance to disk for later use.

Parameters:file (str) – File name.
class fmristats.smodel.SignalFit(coordinates, params, cov_params, mse, population_map, hyperparameters, parameter_dict)

Result of a FMRI fitting

Defines a class for the result, i.e., the estimated effect field of an FMRI experiments, fitted by the function attribute of the FMRI class.

get_field(parameter, value=None)

Return the scalar field for the parameter

Parameters:
  • parameter (int or str or list(int) or np.array) – Must int or a key in the parameter_dict.
  • value (str) – The value string can be either point, stderr, or tstatistic.
Returns:

The queried field

Return type:

Image

Notes

The parameter_dict can either contain the position of a parameter in the parameter field or a contrast of parameters in the field. The form can either be a single integer, a list of integers or an arrays. Example: {‘intercept’ : 0, ‘bold_contrast’ : [0,1,0,-1,0,0,0,0,0]}

The counting starts at 0, hence 0 is the first parameter (and typically the intercept), 1 is the second parameter in the design matrix (and typically the first non-constant parameter), and so on.

The value string can be either point, stderr, or tstatistic.

mask(mask=True, verbose=False)

Apply mask to parameter fields

norm_to(reference_field)

Norm the part of the statistics field that has a unit, to a reference field.

Parameters:reference_field (Image) – The reference field for the unit.
norm_to_ati()

Norm the part of the statistics field that has a unit, to the ati-reference field that is stored in the PopulationMap.

save(file, **kwargs)

Save instance to disk

This will save the current instance to disk for later use.

Parameters:file (str) – File name.
class fmristats.smodel.SignalModel(session, reference_maps, population_map, formula='C(task)/C(block, Sum)', parameter=['intercept', 'task'])

The signal model

Parameters:
  • session (Session) – A session (with fitted foreground).
  • reference_maps (ReferenceMaps) – The estimated reference maps.
  • population_map (PopulationMap) – A population map
coordinates()

The coordinate grid of observations

The coordinates in subject reference space of all points at which MR signals have been acquired.

Returns:ndarray, shape (n,x,y,z,3), dtype – […,:3] = coordinates of observation
Return type:float
data_at_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
data_at_index(index)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
data_at_subject_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
design_AT_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
design_AT_index(index)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
design_AT_subject_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
fit(mask=True, verbose=True, backend='numba')

Fit the signal model to data

Parameters:
  • mask (None or bool or str or ndarray, dtype: bool) – string can be one of ‘vb’, ‘vb_background’, ‘foreground’, or ‘vb_estimate’. None defaults to ‘data’. True will take precedence: ‘vb’> ‘vb_background’> ‘vb_estimate’ > ‘foreground’.
  • verbose (bool) – increase output verbosity
Returns:

Result

Return type:

Fitted field.

fit_AT_coordinate(x, **kwargs)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the population space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
fit_AT_index(index, **kwargs)

Fit the signal model to data at specified coordinates

Parameters:index (tuple) – The index at which to fit the model
fit_AT_subject_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:
  • x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
  • formula (str) – A formula.
fit_at_coordinate(x, **kwargs)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the population space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
fit_at_index(index, **kwargs)

Fit the signal model to data at specified coordinates

Parameters:index (tuple) – The index at which to fit the model
fit_at_subject_coordinate(x, formula=None)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:
  • x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
  • formula (str) – A formula.
fit_at_subject_coordinates(coordinates, mask=None, verbose=True, backend='numba')

Fit the signal model to data

Parameters:
  • coordinates (None or ndarray, shape (,3), dtype: float) – The coordinates at which to fit the model
  • verbose (bool) – increase output verbosity
Returns:

Return type:

Result

get_mask(verbose=True)

Creates a data mask

get_observations(include_background=False)

Observation matrix

Returns the array of (un-cleaned) observations

Returns:ndarray, shape (n,x,y,z,9), dtype – […,:3] = coordinates of observation […, 3] = MR signal response […, 4] = time of observation […, 5] = task during time of observation […, 6] = block number during time of observation […, 7] = scan cycle […, 8] = slice number
Return type:float
get_roi(mask=True, verbose=True)

Coordinates and mask

Combines the data mask with other masks to produce a suitable mask for fitting.

Parameters:
  • mask (None or bool or str or ndarray, dtype: bool) – Either one of ‘vb_mask’, ‘vb’, ‘vb_background’, ‘foreground’, or ‘vb_estimate’. If None defaults to ‘data’. True will take precedence: ‘vb_mask’ > ‘vb’ > ‘vb_background’> ‘vb_estimate’ > ‘foreground’.
  • verbose (bool) – Increase output verbosity
Returns:

  • coordinates (ndarray, dtype: float) – Coordinates in standard space.
  • mask (ndarray, dtype: bool) – Mask in standard space. True when within a ROI.

mean_index_affine()

Affine transformation from reference space to the index space of the acquisition grid

Returns:
  • Affine (The affine transformation that maps a coordinate in)
  • reference space to the mean index in the index space of the
  • acquisition grid of the session.
model_AT_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the population space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
model_AT_index(index)

Fit the signal model to data at specified coordinates

Parameters:index (tuple) – The index at which to fit the model
model_AT_subject_coordinate(x)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:
  • x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
  • formula (str) – A formula.
model_at_coordinate(x, **kwargs)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the population space.

Parameters:x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
model_at_index(index, **kwargs)

Fit the signal model to data at specified coordinates

Parameters:index (tuple) – The index at which to fit the model
model_at_subject_coordinate(x, formula=None)

Fit the signal model to data at specified coordinates given with respect to the coordinate system of the subject reference space.

Parameters:
  • x (ndarray, shape (3,), dtype: float) – The coordinates at which to fit the model
  • formula (str) – A formula.
save(file, **kwargs)

Save instance to disk

This will save the current instance to disk for later use.

Parameters:file (str) – File name.
set_data(burn_in=4, demean=False, dropna=True, include_background=False, verbose=True)

Set the observation matrix

This will set the attributes .observations, .valid, .data, and .dataframe.

Notes

The observations are an array of the following shape:

ndarray, shape (n,x,y,z,9), dtype: float
[…,:3] = coordinates of observation […, 3] = the MR signal response […, 4] = time of observation […, 5] = task during time of observation […, 6] = block number during time of observation […, 7] = scan cycle […, 8] = slice number

The data in this array are the basis of all model fits.

set_design(formula=None, parameter=None, return_design_matrix=False, verbose=True)

Set or create the design matrix

This will set the attribute .design, and it will overwrite the attributes .valid, .data, .dataframe, and potentially .formula, and .parameter_dict.

Parameters:
  • design (ndarray, shape (m,n,x,y,z,p) or (m,n,p) or (m,p)) – Design matrix for the m scan cycles with n scans per cycle on the grid x, y, z with p number of parameters
  • formula (None or str) – If X is None, this formula will be used to create the design matrix. If formula is None, the default stored in .formula will be used. Otherwise .formula will be overwritten
  • parameter (list(str)) – A list of parameter names
  • return_design_matrix (bool) – If True, return the design matrix
Returns:

Return type:

None or DesignMatrix

set_design_to(design, hasconst, verbose=True)

Set or create the design matrix

This will set the attribute .design.

Parameters:design (ndarray, shape (m,n,x,y,z,p) or (m,n,p) or (m,p)) – Design matrix for the m scan cycles with n scans per cycle on the grid x, y, z with p number of parameters
Returns:
Return type:None
set_hyperparameters(scale_type='max', factor=3, scale=None, mass=None)

Set the hyperparameter for MB estimation

Set the width of the spatial weighting scheme for MB estimation.

Parameters:
  • scale_type (str) – One of min, max (default), diagonal
  • scale (None or float) – Standard deviation of the Gaussian used to weight observations with respect to distance to point.
  • factor (float) – Controls the centre mass of the Gaussian used to weight observations with respect to distance to point.
  • mass (None or float (optional)) – Centre mass of the Gaussian used to weight observations with respect to distance to point.

Notes

The only hyperparameter you need to set is scale, which is set for you if you set the scale_type.

Factor takes precedence to mass, as I will assume if you are setting the mass, you know what you are doing.

set_stimulus_design(**kwargs)

Create and set the stimulus design of the session

The Sample

Sample

class fmristats.sample.Sample(covariates, statistics, study)

Sampled activation fields of a FMRI study

at_index(index)

Returns the summary statistics at an index

Returns the effect and respective standard error of all subjects in the sample.

Parameters:index (tuple(int)) – The index. A 3-tuple of integers
Returns:
Return type:DataFrame
filter(b=None)

Notes

Here, b should be a slice object, you cannot work with the index of the covariate data frame, but must use integer location indices instead.

save(file, **kwargs)

Save model instance to disk

This will save the current model instance to disk for later use.

Parameters:file (str) – File name.

The FMRI Population Model

Defines a class for the FMRI population model and its fits.

class fmristats.pmodel.PopulationModel(sample, formula=None, design=None)

The FMRI population model

Parameters:
  • sample (Sample) –
  • formula (str) – A formula like object that is understood by patsy.
  • design (ndarray) – If None, will be created from formula Directly specifying a design matrix, i.e., providing design will take precedence from the formula interface.
  • mask (None, bool, ndarray, or str) – If False or None, the population model will be fitted only at points, at which the population model is identifiable. If True or ‘template’, the population model will, additionally, only be fitted at points, at which the template in the population has valid intensities (i.e. > 0 and not NAN). If ‘sample’, the population model will be fitted only at points at which the sample provides valid summary statistics for all fields in the sample.
fit(mask=True)

Fit the model to the data

Returns:
Return type:PopulationResult
save(file, **kwargs)

Save model instance to disk

This will save the current model instance to disk for later use.

Parameters:file (str) – File name.