NiBabel

Access a cacophony of neuro-imaging file formats

Previous topic

nibabel.volumeutils.array_to_file

Next topic

nibabel.volumeutils.better_float_of

Reggie -- the one

nibabel.volumeutils.best_write_scale_ftype

nibabel.volumeutils.best_write_scale_ftype(arr, slope=1.0, inter=0.0, default=<type 'numpy.float32'>)

Smallest float type to contain range of arr after scaling

Scaling that will be applied to arr is (arr - inter) / slope.

Note that slope and inter get promoted to 1D arrays for this purpose to avoid the numpy scalar casting rules, which prevent scalars upcasting the array.

Parameters :

arr : array-like

array that will be scaled

slope : array-like, optional

scalar such that output array will be (arr - inter) / slope.

inter : array-like, optional

scalar such that output array will be (arr - inter) / slope

default : numpy type, optional

minimum float type to return

Returns :

ftype : numpy type

Best floating point type for scaling. If no floating point type prevents overflow, return the top floating point type. If the input array arr already contains inf values, return the greater of the input type and the default type.

Examples

>>> arr = np.array([0, 1, 2], dtype=np.int16)
>>> best_write_scale_ftype(arr, 1, 0) is np.float32
True

Specify higher default return value

>>> best_write_scale_ftype(arr, 1, 0, default=np.float64) is np.float64
True

Even large values that don’t overflow don’t change output

>>> arr = np.array([0, np.finfo(np.float32).max], dtype=np.float32)
>>> best_write_scale_ftype(arr, 1, 0) is np.float32
True

Scaling > 1 reduces output values, so no upcast needed

>>> best_write_scale_ftype(arr, np.float32(2), 0) is np.float32
True

Scaling < 1 increases values, so upcast may be needed (and is here)

>>> best_write_scale_ftype(arr, np.float32(0.5), 0) is np.float64
True