# `stats`

## Module: `stats.analysis`

`peak_values`(bundle, peaks, dt, pname, bname, ...) | Peak_values function finds the generalized fractional anisotropy (gfa)
`anatomical_measures`(bundle, metric, dt, ...) | Calculates dti measure (eg: FA, MD) per point on streamlines and
`assignment_map`(target_bundle, model_bundle, ...) | Calculates assignment maps of the target bundle with reference to model bundle centroids.
`buan_profile`(model_bundle, bundle, ...[, ...]) | Create BUAN weighted mean bundle profiles (lite).
`gaussian_weights`(bundle, *[, n_points, ...]) | Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default).
`afq_profile`(data, bundle, affine, *[, ...]) | Calculates a summarized profile of data for a bundle or tract along its length.

## Module: `stats.qc`

`find_qspace_neighbors`(gtab) | Create a mapping of dwi volume index to its nearest neighbor.
`neighboring_dwi_correlation`(dwi_data, gtab, *) | Calculate the Neighboring DWI Correlation (NDC) from dMRI data.

## Module: `stats.sketching`

`count_sketch`(matrixa_name, matrixa_dtype, ...) | Count Sketching algorithm to reduce the size of the matrix.

### peak_values

dipy.stats.analysis.peak_values(bundle, peaks, dt, pname, bname, subject, group_id, ind, dir_name)
  Peak_values function finds the generalized fractional anisotropy (gfa)

    and quantitative anisotropy (qa) values from peaks object (eg: csa) for every point on a streamline used while tracking and saves it in hd5 file.

  Parameters:
    bundle string

      Name of bundle being analyzed

    peaks peaks

      contains peak directions and values

    dt DataFrame

      DataFrame to be populated

    pname string

      Name of the dti metric

    bname string

      Name of bundle being analyzed.

    subject string

      subject number as a string (e.g. 10001)

    group_id integer

      which group subject belongs to 1 patient and 0 for control

    ind integer list

      ind tells which disk number a point belong.

    dir_name string

      path of output directory

### anatomical_measures

dipy.stats.analysis.anatomical_measures(bundle, metric, dt, pname, bname, subject, group_id, ind, dir_name)
  Calculates dti measure (eg: FA, MD) per point on streamlines and

    save it in hd5 file.

  Parameters:
    bundle string

      Name of bundle being analyzed

    metric matrix of float values

      dti metric e.g. FA, MD

    dt DataFrame

      DataFrame to be populated

    pname string

      Name of the dti metric

    bname string

      Name of bundle being analyzed.

    subject string

      subject number as a string (e.g. 10001)

    group_id integer

      which group subject belongs to 1 for patient and 0 control

    ind integer list

      ind tells which disk number a point belong.

    dir_name string

      path of output directory

### assignment_map

dipy.stats.analysis.assignment_map(target_bundle, model_bundle, no_disks)

  Calculates assignment maps of the target bundle with reference to model bundle centroids.

  See [1] for further details about the method.

  Parameters:
    target_bundle Streamlines

      target bundle extracted from subject data in common space

    model_bundle Streamlines

      atlas bundle used as reference

    no_disks integer, optional

      Number of disks used for dividing bundle into disks.

  Returns:
    dist ndarray

      Distance of each target bundle point to its nearest model bundle centroid point.

    indx ndarray

      Assignment map of the target bundle streamline point indices to the model bundle centroid points.

  References

  [1] (1,2)

  Bramsh Qamar Chandio, Shannon Leigh Risacher, Franco Pestilli, Daniel Bullock, Fang-Cheng Yeh, Serge Koudoro, Ariel Rokem, Jaroslaw Harezlak, and Eleftherios Garyfallidis. Bundle analytics, a computational framework for investigating the shapes and profiles of brain pathways across populations. Scientific Reports, 10:17149, October 2020. URL: https://doi.org/10.1038/s41598-020-74054-4, doi:10.1038/s41598-020-74054-4.

### buan_profile

dipy.stats.analysis.buan_profile(model_bundle, bundle, orig_bundle, metric, affine, *, no_disks=100)

  Create BUAN weighted mean bundle profiles (lite).

  See [1] and [2] for further details about the method.

  Parameters:
    model_bundle Streamlines

      The atlas/template bundle used as the along-tract reference. Must be in the same space as `bundle` (common/MNI space).

    bundle Streamlines

      The subject bundle in common space (e.g., MNI). Used for segment assignment against the model centroids.

    orig_bundle Streamlines

      The same subject bundle in native/world (RAS) space. Used for sampling the metric volume. Must correspond point-for-point to `bundle`.

    metric ndarray

      3-D scalar volume (e.g., FA) in the same voxel space as `affine`.

    affine ndarray

      Voxel-to-world affine of the metric volume (as returned by `nib.load(...).affine`). Used to convert `orig_bundle` from world to voxel coordinates for metric interpolation.

    no_disks int, optional

      Number of alongtract segments/disks used for dividing bundle into segments.

  Returns:
    bundle_profile ndarray, shape (no_disks,)

      Inverse-distance-weighted mean metric value for each disk segment. Disks with no valid data points are set to NaN.

  References

  [2]

  Bramsh Qamar Chandio, Julio E Villalon-Reina, Talia M Nir, Sophia I Thomopoulos, Yixue Feng, Sebastian Benavidez, Neda Jahanshad, Jaroslaw Harezlak, Eleftherios Garyfallidis, and Paul M Thompson. Bundle analytics based data harmonization for multi-site diffusion MRI tractometry. In 2024 46th Annual International Conference of the IEEE Engineering in Medicine and Biology Society (EMBC), 1–7. IEEE, 2024. URL: https://doi.org/10.1109/EMBC53108.2024.10782419.

### gaussian_weights

dipy.stats.analysis.gaussian_weights(bundle, *, n_points=100, return_mahalnobis=False, stat=<function mean>)

  Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default).

  Parameters:
    bundle Streamlines

      The streamlines to weight.

    n_points int, optional

      The number of points to resample to. If the `bundle` is an array, this input is ignored.

    return_mahalanobis bool, optional

      Whether to return the Mahalanobis distance instead of the weights.

    stat callable, optional.

      The statistic used to calculate the central tendency of streamlines in each node. Can be one of {np.mean, np.median} or other functions that have similar API.`

  Returns:
    w array of shape (n_streamlines, n_points)

      Weights for each node in each streamline, calculated as its relative inverse of the Mahalanobis distance, relative to the distribution of coordinates at that node position across streamlines.

### afq_profile

dipy.stats.analysis.afq_profile(data, bundle, affine, *, n_points=100, profile_stat=<function average>, orient_by=None, weights=None, **weights_kwarg)

  Calculates a summarized profile of data for a bundle or tract along its length.

  Follows the approach outlined in [3].

  Parameters:
    data 3D volume

      The statistic to sample with the streamlines.

    bundle StreamLines class instance
      The collection of streamlines (possibly already resampled into an array

        for each to have the same length) with which we are resampling. See Note below about orienting the streamlines.

    affine array_like (4, 4)

      The mapping from voxel coordinates to streamline points. The voxel_to_rasmm matrix, typically from a NIFTI file.

    n_points: int, optional

      The number of points to sample along the bundle. Default: 100.

    orient_by: streamline, optional

      A streamline to use as a standard to orient all of the streamlines in the bundle according to.

    weights 1D array or 2D array or callable, optional

      Weight each streamline (1D) or each node (2D) when calculating the tract-profiles. Must sum to 1 across streamlines (in each node if relevant). If callable, this is a function that calculates weights.

    profile_stat callable, optional

      The statistic used to average the profile across streamlines. If weights is not None, this must take weights as a keyword argument. The default, np.average, is the same as np.mean but takes weights as a keyword argument.

    weights_kwarg key-word arguments

      Additional key-word arguments to pass to the weight-calculating function. Only to be used if weights is a callable.

  Returns:
    ndarray a 1D array with the profile of data along the length of

      bundle

  Notes

  Before providing a bundle as input to this function, you will need to make sure that the streamlines in the bundle are all oriented in the same orientation relative to the bundle (use `orient_by_streamline()`).

  References

  [3]

  Jason D. Yeatman, Robert F. Dougherty, Nathaniel J. Myall, Brian A. Wandell, and Heidi M. Feldman. Tract Profiles of White Matter Properties: Automating Fiber-Tract Quantification. PLOS ONE, 7(11):1–15, November 2012. URL: https://doi.org/10.1371/journal.pone.0049790, doi:10.1371/journal.pone.0049790.

### find_qspace_neighbors

dipy.stats.qc.find_qspace_neighbors(gtab)

  Create a mapping of dwi volume index to its nearest neighbor.

  An approximate q-space is used (the deltas are not included). Note that neighborhood is not necessarily bijective. One neighbor is found per dwi volume.

  Parameters:
    gtab: dipy.core.gradients.GradientTable

      Gradient table.

  Returns:
    neighbors: list of tuple

      A list of 2-tuples indicating the nearest q-space neighbor of each dwi volume.

  Examples

      >>> from dipy.core.gradients import gradient_table
      >>> import numpy as np
      >>> gtab = gradient_table(
      ...     np.array([0, 1000, 1000, 2000]),
      ...     bvecs=np.array([
      ...         [1, 0, 0],
      ...         [1, 0, 0],
      ...         [0.99, 0.0001, 0.0001],
      ...         [1, 0, 0]]))
      >>> find_qspace_neighbors(gtab)
      [(1, 2), (2, 1), (3, 1)]

### neighboring_dwi_correlation

dipy.stats.qc.neighboring_dwi_correlation(dwi_data, gtab, *, mask=None)

  Calculate the Neighboring DWI Correlation (NDC) from dMRI data.

  Using a mask is highly recommended, otherwise the FOV will influence the correlations. According to Yeh et al.[4], an NDC less than 0.4 indicates a low quality image.

  Parameters:
    dwi_data 4D ndarray

      dwi data on which to calculate NDC

    gtab dipy.core.gradients.GradientTable

      Gradient table.

    mask 3D ndarray, optional

      Mask of voxels to include in the NDC calculation

  Returns:
    ndc float

      The neighboring DWI correlation

  References

  [4]

  Fang-Cheng Yeh, Islam M. Zaydan, Valerie R. Suski, David Lacomis, R. Mark Richardson, Joseph C. Maroon, and Jessica Barrios-Martinez. Differential tractography as a track-based biomarker for neuronal injury. NeuroImage, 202:116131, 2019. URL: https://doi.org/10.1016/j.neuroimage.2019.116131, doi:10.1016/j.neuroimage.2019.116131.

### count_sketch

dipy.stats.sketching.count_sketch(matrixa_name, matrixa_dtype, matrixa_shape, sketch_rows, tmp_dir)

  Count Sketching algorithm to reduce the size of the matrix.

  Parameters:
    matrixa_name str

      The name of the memmap file containing the matrix A.

    matrixa_dtype dtype

      The dtype of the matrix A.

    matrixa_shape tuple

      The shape of the matrix A.

    sketch_rows int

      The number of rows in the sketch matrix.

    tmp_dir str

      The directory to save the temporary files.

  Returns:
    matrixc_file.name str

      The name of the memmap file containing the sketch matrix.

    matrixc.dtype dtype

      The dtype of the sketch matrix.

    matrixc.shape tuple

      The shape of the sketch matrix.