nicom

DICOM reader

csareader

CSA header reader from SPM spec

dicomreaders

dicomwrappers

Classes to wrap DICOM objects and files

dwiparams

Process diffusion imaging parameters

structreader

Stream-like reader for packed data

Module: nicom.ascconv

Parse the “ASCCONV” meta data format found in a variety of Siemens MR files.

AscconvParseError

Error parsing ascconv file

Atom(op, obj_type, obj_id)

Object to hold operation, object type and object identifier

NoValue()

Signals no value present

assign2atoms(assign_ast[, default_class])

Parse single assignment ast from ascconv line into atoms

obj_from_atoms(atoms, namespace)

Return object defined by list atoms in dict-like namespace

parse_ascconv(ascconv_str[, str_delim])

Parse the 'ASCCONV' format from input_str.

Module: nicom.csareader

CSA header reader from SPM spec

CSAError

CSAReadError

get_acq_mat_txt(csa_dict)

get_b_matrix(csa_dict)

get_b_value(csa_dict)

get_csa_header(dcm_data[, csa_type])

Get CSA header information from DICOM header

get_g_vector(csa_dict)

get_ice_dims(csa_dict)

get_n_mosaic(csa_dict)

get_scalar(csa_dict, tag_name)

get_slice_normal(csa_dict)

get_vector(csa_dict, tag_name, n)

is_mosaic(csa_dict)

Return True if the data is of Mosaic type

nt_str(s)

Strip string to first null

read(csa_str)

Read CSA header from string csa_str

Module: nicom.dicomreaders

DicomReadError

mosaic_to_nii(dcm_data)

Get Nifti file from Siemens

read_mosaic_dir(dicom_path[, globber, ...])

Read all Siemens mosaic DICOMs in directory, return arrays, params

read_mosaic_dwi_dir(dicom_path[, globber, ...])

slices_to_series(wrappers)

Sort sequence of slice wrappers into series

Module: nicom.dicomwrappers

Classes to wrap DICOM objects and files

The wrappers encapsulate the capabilities of the different DICOM formats.

They also allow dictionary-like access to named fields.

For calculated attributes, we return None where needed data is missing. It seemed strange to raise an error during attribute processing, other than an AttributeError - breaking the ‘properties manifesto’. So, any processing that needs to raise an error, should be in a method, rather than in a property, or property-like thing.

MosaicWrapper(dcm_data[, csa_header, n_mosaic])

Class for Siemens mosaic format data

MultiframeWrapper(dcm_data)

Wrapper for Enhanced MR Storage SOP Class

SiemensWrapper(dcm_data[, csa_header])

Wrapper for Siemens format DICOMs

Wrapper(dcm_data)

Class to wrap general DICOM files

WrapperError

WrapperPrecisionError

none_or_close(val1, val2[, rtol, atol])

Match if val1 and val2 are both None, or are close

wrapper_from_data(dcm_data)

Create DICOM wrapper from DICOM data object

wrapper_from_file(file_like, *args, **kwargs)

Create DICOM wrapper from file_like object

Module: nicom.dwiparams

Process diffusion imaging parameters

  • q is a vector in Q space

  • b is a b value

  • g is the unit vector along the direction of q (the gradient direction)

Thus:

b = norm(q)

g = q / norm(q)

(norm(q) is the Euclidean norm of q)

The B matrix B is a symmetric positive semi-definite matrix. If q_est is the closest q vector equivalent to the B matrix, then:

B ~ (q_est . q_est.T) / norm(q_est)

B2q(B[, tol])

Estimate q vector from input B matrix B

nearest_pos_semi_def(B)

Least squares positive semi-definite tensor estimation

q2bg(q_vector[, tol])

Return b value and q unit vector from q vector q_vector

Module: nicom.structreader

Stream-like reader for packed data

Unpacker(buf[, ptr, endian])

Class to unpack values from buffer object

Module: nicom.utils

Utilities for working with DICOM datasets

find_private_section(dcm_data, group_no, creator)

Return start element in group group_no given creator name creator

AscconvParseError

class nibabel.nicom.ascconv.AscconvParseError

Bases: Exception

Error parsing ascconv file

__init__(*args, **kwargs)

Atom

class nibabel.nicom.ascconv.Atom(op, obj_type, obj_id)

Bases: object

Object to hold operation, object type and object identifier

An atom represents an element in an expression. For example:

a.b[0].c

has four elements. We call these elements “atoms”.

We represent objects (like a) as dicts for convenience.

The last element (.c) is an op = ast.Attribute operation where the object type (obj_type) of c is not constrained (we can’t tell from the operation what type it is). The obj_id is the name of the object – “c”.

The second to last element [0], is op = ast.Subscript, with object type dict (we know from the subsequent operation .c that this must be an object, we represent the object by a dict). The obj_id is the index 0.

Parameters:
op{‘name’, ‘attr’, ‘list’}

Assignment type. Assignment to name (root namespace), attribute or list element.

obj_type{list, dict, other}

Object type being assigned to.

obj_idstr or int

Key (obj_type is dict) or index (obj_type is list)

__init__(op, obj_type, obj_id)

NoValue

class nibabel.nicom.ascconv.NoValue

Bases: object

Signals no value present

__init__(*args, **kwargs)

assign2atoms

nibabel.nicom.ascconv.assign2atoms(assign_ast, default_class=<class 'int'>)

Parse single assignment ast from ascconv line into atoms

Parameters:
assign_astassignment statement ast

ast derived from single line of ascconv file.

default_classclass, optional

Class that will create an object where we cannot yet know the object type in the assignment.

Returns:
atomslist

List of atoms. See docstring for atoms. Defines left to right sequence of assignment in line_ast.

obj_from_atoms

nibabel.nicom.ascconv.obj_from_atoms(atoms, namespace)

Return object defined by list atoms in dict-like namespace

Parameters:
atomslist

List of atoms

namespacedict-like

Namespace in which object will be defined.

Returns:
obj_rootobject

Namespace such that we can set a desired value to the object defined in atoms with obj_root[obj_key] = value.

obj_keystr or int

Index into list or key into dictionary for obj_root.

parse_ascconv

nibabel.nicom.ascconv.parse_ascconv(ascconv_str, str_delim='"')

Parse the ‘ASCCONV’ format from input_str.

Parameters:
ascconv_strstr

The string we are parsing

str_delimstr, optional

String delimiter. Typically ‘”’ or ‘””’

Returns:
prot_dictOrderedDict

Meta data pulled from the ASCCONV section.

attrsOrderedDict

Any attributes stored in the ‘ASCCONV BEGIN’ line

Raises:
AsconvParseError

A line of the ASCCONV section could not be parsed.

CSAError

class nibabel.nicom.csareader.CSAError

Bases: Exception

__init__(*args, **kwargs)

CSAReadError

class nibabel.nicom.csareader.CSAReadError

Bases: CSAError

__init__(*args, **kwargs)

get_acq_mat_txt

nibabel.nicom.csareader.get_acq_mat_txt(csa_dict)

get_b_matrix

nibabel.nicom.csareader.get_b_matrix(csa_dict)

get_b_value

nibabel.nicom.csareader.get_b_value(csa_dict)

get_csa_header

nibabel.nicom.csareader.get_csa_header(dcm_data, csa_type='image')

Get CSA header information from DICOM header

Return None if the header does not contain CSA information of the specified csa_type

Parameters:
dcm_datadicom.Dataset

DICOM dataset. Should implement __getitem__ and, if initial check for presence of dcm_data[(0x29, 0x10)] passes, should satisfy interface for find_private_section.

csa_type{‘image’, ‘series’}, optional

Type of CSA field to read; default is ‘image’

Returns:
csa_infoNone or dict

Parsed CSA field of csa_type or None, if we cannot find the CSA information.

get_g_vector

nibabel.nicom.csareader.get_g_vector(csa_dict)

get_ice_dims

nibabel.nicom.csareader.get_ice_dims(csa_dict)

get_n_mosaic

nibabel.nicom.csareader.get_n_mosaic(csa_dict)

get_scalar

nibabel.nicom.csareader.get_scalar(csa_dict, tag_name)

get_slice_normal

nibabel.nicom.csareader.get_slice_normal(csa_dict)

get_vector

nibabel.nicom.csareader.get_vector(csa_dict, tag_name, n)

is_mosaic

nibabel.nicom.csareader.is_mosaic(csa_dict)

Return True if the data is of Mosaic type

Parameters:
csa_dictdict

dict containing read CSA data

Returns:
tfbool

True if the dcm_data appears to be of Siemens mosaic type, False otherwise

nt_str

nibabel.nicom.csareader.nt_str(s)

Strip string to first null

Parameters:
sbytes
Returns:
sdashstr

s stripped to first occurrence of null (0)

read

nibabel.nicom.csareader.read(csa_str)

Read CSA header from string csa_str

Parameters:
csa_strstr

byte string containing CSA header information

Returns:
headerdict

header information as dict, where header has fields (at least) type, n_tags, tags. header['tags'] is also a dictionary with one key, value pair for each tag in the header.

DicomReadError

class nibabel.nicom.dicomreaders.DicomReadError

Bases: Exception

__init__(*args, **kwargs)

mosaic_to_nii

nibabel.nicom.dicomreaders.mosaic_to_nii(dcm_data)

Get Nifti file from Siemens

Parameters:
dcm_datadicom.DataSet

DICOM header / image as read by dicom package

Returns:
imgNifti1Image

Nifti image object

read_mosaic_dir

nibabel.nicom.dicomreaders.read_mosaic_dir(dicom_path, globber='*.dcm', check_is_dwi=False, dicom_kwargs=None)

Read all Siemens mosaic DICOMs in directory, return arrays, params

Parameters:
dicom_pathstr

path containing mosaic DICOM images

globberstr, optional

glob to apply within dicom_path to select DICOM files. Default is *.dcm

check_is_dwibool, optional

If True, raises an error if we don’t find DWI information in the DICOM headers.

dicom_kwargsNone or dict

Extra keyword arguments to pass to the pydicom dcmread function.

Returns:
data4D array

data array with last dimension being acquisition. If there were N acquisitions, each of shape (X, Y, Z), data will be shape (X, Y, Z, N)

affine(4,4) array

affine relating 3D voxel space in data to RAS world space

b_values(N,) array

b values for each acquisition. nan if we did not find diffusion information for these images.

unit_gradients(N, 3) array

gradient directions of unit length for each acquisition. (nan, nan, nan) if we did not find diffusion information.

read_mosaic_dwi_dir

nibabel.nicom.dicomreaders.read_mosaic_dwi_dir(dicom_path, globber='*.dcm', dicom_kwargs=None)

slices_to_series

nibabel.nicom.dicomreaders.slices_to_series(wrappers)

Sort sequence of slice wrappers into series

This follows the SPM model fairly closely

Parameters:
wrapperssequence

sequence of Wrapper objects for sorting into volumes

Returns:
seriessequence

sequence of sequences of wrapper objects, where each sequence is wrapper objects comprising a series, sorted into slice order

MosaicWrapper

class nibabel.nicom.dicomwrappers.MosaicWrapper(dcm_data, csa_header=None, n_mosaic=None)

Bases: SiemensWrapper

Class for Siemens mosaic format data

Mosaic format is a way of storing a 3D image in a 2D slice - and it’s as simple as you’d imagine it would be - just storing the slices in a mosaic similar to a light-box print.

We need to allow for this when getting the data and (because of an idiosyncrasy in the way Siemens stores the images) calculating the position of the first voxel.

Adds attributes:

  • n_mosaic : int

  • mosaic_size : int

Initialize Siemens Mosaic wrapper

The Siemens-specific information is in the csa_header, either passed in here, or read from the input dcm_data.

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. If csa_header is None, it should also be possible for to extract a CSA header from dcm_data. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file. A dict should also work.

csa_headerNone or mapping, optional

mapping giving values for Siemens CSA image sub-header.

n_mosaicNone or int, optional

number of images in mosaic. If None, try to get this number from csa_header. If this fails, raise an error

__init__(dcm_data, csa_header=None, n_mosaic=None)

Initialize Siemens Mosaic wrapper

The Siemens-specific information is in the csa_header, either passed in here, or read from the input dcm_data.

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. If csa_header is None, it should also be possible for to extract a CSA header from dcm_data. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file. A dict should also work.

csa_headerNone or mapping, optional

mapping giving values for Siemens CSA image sub-header.

n_mosaicNone or int, optional

number of images in mosaic. If None, try to get this number from csa_header. If this fails, raise an error

get_data()

Get scaled image data from DICOMs

Resorts data block from mosaic to 3D

Returns:
dataarray

array with data as scaled from any scaling in the DICOM fields.

Notes

The apparent image in the DICOM file is a 2D array that consists of blocks, that are the output 2D slices. Let’s call the original array the slab, and the contained slices slices. The slices are of pixel dimension n_slice_rows x n_slice_cols. The slab is of pixel dimension n_slab_rows x n_slab_cols. Because the arrangement of blocks in the slab is defined as being square, the number of blocks per slab row and slab column is the same. Let n_blocks be the number of blocks contained in the slab. There is also n_slices - the number of slices actually collected, some number <= n_blocks. We have the value n_slices from the ‘NumberOfImagesInMosaic’ field of the Siemens private (CSA) header. n_row_blocks and n_col_blocks are therefore given by ceil(sqrt(n_slices)), and n_blocks is n_row_blocks ** 2. Also n_slice_rows == n_slab_rows / n_row_blocks, etc. Using these numbers we can therefore reconstruct the slices from the 2D DICOM pixel array.

image_position()

Return position of first voxel in data block

Adjusts Siemens mosaic position vector for bug in mosaic format position. See dicom_mosaic in doc/theory for details.

Parameters:
None
Returns:
img_pos(3,) array

position in mm of voxel (0,0,0) in Mosaic array

image_shape()

Return image shape as returned by get_data()

is_mosaic = True

MultiframeWrapper

class nibabel.nicom.dicomwrappers.MultiframeWrapper(dcm_data)

Bases: Wrapper

Wrapper for Enhanced MR Storage SOP Class

Tested with Philips’ Enhanced DICOM implementation.

The specification for the Enhanced MR image IOP / SOP began life as DICOM supplement 49, but as of 2016 it is part of the standard. In particular see:

Attributes:
is_multiframeboolean

Identifies dcmdata as multi-frame

framessequence

A sequence of dicom.dataset.Dataset objects populated by the dicom.dataset.Dataset.PerFrameFunctionalGroupsSequence attribute

sharedobject

The first (and only) dicom.dataset.Dataset object from a dicom.dataset.Dataset.SharedFunctionalgroupSequence.

Methods

image_shape(self)

image_orient_patient(self)

voxel_sizes(self)

image_position(self)

series_signature(self)

get_data(self)

Initializes MultiframeWrapper

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file, but a dictionary should also work.

__init__(dcm_data)

Initializes MultiframeWrapper

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file, but a dictionary should also work.

get_data()

Get scaled image data from DICOMs

We return the data as DICOM understands it, first dimension is rows, second dimension is columns

Returns:
dataarray

array with data as scaled from any scaling in the DICOM fields.

image_orient_patient()

Note that this is _not_ LR flipped

image_position()

Return position of first voxel in data block

Parameters:
None
Returns:
img_pos(3,) array

position in mm of voxel (0,0) in image array

image_shape()

The array shape as it will be returned by get_data()

The shape is determined by the Rows DICOM attribute, Columns DICOM attribute, and the set of frame indices given by the FrameContentSequence[0].DimensionIndexValues DICOM attribute of each element in the PerFrameFunctionalGroupsSequence. The first two axes of the returned shape correspond to the rows, and columns respectively. The remaining axes correspond to those of the frame indices with order preserved.

What each axis in the frame indices refers to is given by the corresponding entry in the DimensionIndexSequence DICOM attribute. WARNING: Any axis referring to the StackID DICOM attribute will have been removed from the frame indices in determining the shape. This is because only a file containing a single stack is currently allowed by this wrapper.

References

is_multiframe = True
series_signature()

Signature for matching slices into series

We use signature in self.is_same_series(other).

Returns:
signaturedict

with values of 2-element sequences, where first element is value, and second element is function to compare this value with another. This allows us to pass things like arrays, that might need to be allclose instead of equal

voxel_sizes()

Get i, j, k voxel sizes

SiemensWrapper

class nibabel.nicom.dicomwrappers.SiemensWrapper(dcm_data, csa_header=None)

Bases: Wrapper

Wrapper for Siemens format DICOMs

Adds attributes:

  • csa_header : mapping

  • b_matrix : (3,3) array

  • q_vector : (3,) array

Initialize Siemens wrapper

The Siemens-specific information is in the csa_header, either passed in here, or read from the input dcm_data.

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. If csa_header is None, it should also be possible to extract a CSA header from dcm_data. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file. A dict should also work.

csa_headerNone or mapping, optional

mapping giving values for Siemens CSA image sub-header. If None, we try and read the CSA information from dcm_data. If this fails, we fall back to an empty dict.

__init__(dcm_data, csa_header=None)

Initialize Siemens wrapper

The Siemens-specific information is in the csa_header, either passed in here, or read from the input dcm_data.

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. If csa_header is None, it should also be possible to extract a CSA header from dcm_data. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file. A dict should also work.

csa_headerNone or mapping, optional

mapping giving values for Siemens CSA image sub-header. If None, we try and read the CSA information from dcm_data. If this fails, we fall back to an empty dict.

b_matrix()

Get DWI B matrix referring to voxel space

Parameters:
None
Returns:
B(3,3) array or None

B matrix in voxel orientation space. Returns None if this is not a Siemens header with the required information. We return None if this is a b0 acquisition

is_csa = True
q_vector()

Get DWI q vector referring to voxel space

Parameters:
None
Returns:
q: (3,) array

Estimated DWI q vector in voxel orientation space. Returns None if this is not (detectably) a DWI

series_signature()

Add ICE dims from CSA header to signature

slice_normal()

Wrapper

class nibabel.nicom.dicomwrappers.Wrapper(dcm_data)

Bases: object

Class to wrap general DICOM files

Methods:

  • get_data()

  • get_pixel_array()

  • is_same_series(other)

  • __getitem__ : return attributes from dcm_data

  • get(key[, default]) - as usual given __getitem__ above

Attributes and things that look like attributes:

  • affine : (4, 4) array

  • dcm_data : object

  • image_shape : tuple

  • image_orient_patient : (3,2) array

  • slice_normal : (3,) array

  • rotation_matrix : (3,3) array

  • voxel_sizes : tuple length 3

  • image_position : sequence length 3

  • slice_indicator : float

  • series_signature : tuple

Initialize wrapper

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file, but a dictionary should also work.

__init__(dcm_data)

Initialize wrapper

Parameters:
dcm_dataobject

object should allow ‘get’ and ‘__getitem__’ access. Usually this will be a dicom.dataset.Dataset object resulting from reading a DICOM file, but a dictionary should also work.

property affine

Mapping between voxel and DICOM coordinate system

(4, 4) affine matrix giving transformation between voxels in data array and mm in the DICOM patient coordinate system.

b_matrix = None
b_value()

Return b value for diffusion or None if not available

b_vector()

Return b vector for diffusion or None if not available

get(key, default=None)

Get values from underlying dicom data

get_data()

Get scaled image data from DICOMs

We return the data as DICOM understands it, first dimension is rows, second dimension is columns

Returns:
dataarray

array with data as scaled from any scaling in the DICOM fields.

get_pixel_array()

Return unscaled pixel array from DICOM

image_orient_patient()

Note that this is _not_ LR flipped

image_position()

Return position of first voxel in data block

Parameters:
None
Returns:
img_pos(3,) array

position in mm of voxel (0,0) in image array

image_shape()

The array shape as it will be returned by get_data()

instance_number()

Just because we use this a lot for sorting

is_csa = False
is_mosaic = False
is_multiframe = False
is_same_series(other)

Return True if other appears to be in same series

Parameters:
otherobject

object with series_signature attribute that is a mapping. Usually it’s a Wrapper or sub-class instance.

Returns:
tfbool

True if other might be in the same series as self, False otherwise.

q_vector = None
rotation_matrix()

Return rotation matrix between array indices and mm

Note that we swap the two columns of the ‘ImageOrientPatient’ when we create the rotation matrix. This is takes into account the slightly odd ij transpose construction of the DICOM orientation fields - see doc/theory/dicom_orientaiton.rst.

series_signature()

Signature for matching slices into series

We use signature in self.is_same_series(other).

Returns:
signaturedict

with values of 2-element sequences, where first element is value, and second element is function to compare this value with another. This allows us to pass things like arrays, that might need to be allclose instead of equal

slice_indicator()

A number that is higher for higher slices in Z

Comparing this number between two adjacent slices should give a difference equal to the voxel size in Z.

See doc/theory/dicom_orientation for description

slice_normal()
voxel_sizes()

voxel sizes for array as returned by get_data()

WrapperError

class nibabel.nicom.dicomwrappers.WrapperError

Bases: Exception

__init__(*args, **kwargs)

WrapperPrecisionError

class nibabel.nicom.dicomwrappers.WrapperPrecisionError

Bases: WrapperError

__init__(*args, **kwargs)

none_or_close

nibabel.nicom.dicomwrappers.none_or_close(val1, val2, rtol=1e-05, atol=1e-06)

Match if val1 and val2 are both None, or are close

Parameters:
val1None or array-like
val2None or array-like
rtolfloat, optional

Relative tolerance; see np.allclose

atolfloat, optional

Absolute tolerance; see np.allclose

Returns:
tfbool

True iff (both val1 and val2 are None) or (val1 and val2 are close arrays, as detected by np.allclose with parameters rtol and atal).

Examples

>>> none_or_close(None, None)
True
>>> none_or_close(1, None)
False
>>> none_or_close(None, 1)
False
>>> none_or_close([1,2], [1,2])
True
>>> none_or_close([0,1], [0,2])
False

wrapper_from_data

nibabel.nicom.dicomwrappers.wrapper_from_data(dcm_data)

Create DICOM wrapper from DICOM data object

Parameters:
dcm_datadicom.dataset.Dataset instance or similar

Object allowing attribute access, with DICOM attributes. Probably a dataset as read by pydicom.

Returns:
dcm_wdicomwrappers.Wrapper or subclass

DICOM wrapper corresponding to DICOM data type

wrapper_from_file

nibabel.nicom.dicomwrappers.wrapper_from_file(file_like, *args, **kwargs)

Create DICOM wrapper from file_like object

Parameters:
file_likeobject

filename string or file-like object, pointing to a valid DICOM file readable by pydicom

*argspositional

args to dicom.dcmread command.

**kwargskeyword

args to dicom.dcmread command. force=True might be a likely keyword argument.

Returns:
dcm_wdicomwrappers.Wrapper or subclass

DICOM wrapper corresponding to DICOM data type

B2q

nibabel.nicom.dwiparams.B2q(B, tol=None)

Estimate q vector from input B matrix B

We require that the input B is symmetric positive definite.

Because the solution is a square root, the sign of the returned vector is arbitrary. We set the vector to have a positive x component by convention.

Parameters:
B(3,3) array-like

B matrix - symmetric. We do not check the symmetry.

tolNone or float

absolute tolerance below which to consider eigenvalues of the B matrix to be small enough not to worry about them being negative, in check for positive semi-definite-ness. None (default) results in a fairly tight numerical threshold proportional to the maximum eigenvalue

Returns:
q(3,) vector

Estimated q vector from B matrix B

nearest_pos_semi_def

nibabel.nicom.dwiparams.nearest_pos_semi_def(B)

Least squares positive semi-definite tensor estimation

Reference: Niethammer M, San Jose Estepar R, Bouix S, Shenton M, Westin CF. On diffusion tensor estimation. Conf Proc IEEE Eng Med Biol Soc. 2006;1:2622-5. PubMed PMID: 17946125; PubMed Central PMCID: PMC2791793.

Parameters:
B(3,3) array-like

B matrix - symmetric. We do not check the symmetry.

Returns:
npds(3,3) array

Estimated nearest positive semi-definite array to matrix B.

Examples

>>> B = np.diag([1, 1, -1])
>>> nearest_pos_semi_def(B)
array([[0.75, 0.  , 0.  ],
       [0.  , 0.75, 0.  ],
       [0.  , 0.  , 0.  ]])

q2bg

nibabel.nicom.dwiparams.q2bg(q_vector, tol=1e-05)

Return b value and q unit vector from q vector q_vector

Parameters:
q_vector(3,) array-like

q vector

tolfloat, optional

q vector L2 norm below which q_vector considered to be b_value of zero, and therefore g_vector also considered to zero.

Returns:
b_valuefloat

L2 Norm of q_vector or 0 if L2 norm < tol

g_vectorshape (3,) ndarray

q_vector / b_value or 0 if L2 norma < tol

Examples

>>> q2bg([1, 0, 0])
(1.0, array([1., 0., 0.]))
>>> q2bg([0, 10, 0])
(10.0, array([0., 1., 0.]))
>>> q2bg([0, 0, 0])
(0.0, array([0., 0., 0.]))

Unpacker

class nibabel.nicom.structreader.Unpacker(buf, ptr=0, endian=None)

Bases: object

Class to unpack values from buffer object

The buffer object is usually a string. Caches compiled struct format strings so that repeated unpacking with the same format string should be faster than using struct.unpack directly.

Examples

>>> a = b'1234567890'
>>> upk = Unpacker(a)
>>> upk.unpack('2s') == (b'12',)
True
>>> upk.unpack('2s') == (b'34',)
True
>>> upk.ptr
4
>>> upk.read(3) == b'567'
True
>>> upk.ptr
7

Initialize unpacker

Parameters:
bufbuffer

object implementing buffer protocol (e.g. str)

ptrint, optional

offset at which to begin reads from buf

endianNone or str, optional

endian code to prepend to format, as for unpack endian codes. None (the default) corresponds to the default behavior of struct - assuming system endian unless you specify the byte order specifically in the format string passed to unpack

__init__(buf, ptr=0, endian=None)

Initialize unpacker

Parameters:
bufbuffer

object implementing buffer protocol (e.g. str)

ptrint, optional

offset at which to begin reads from buf

endianNone or str, optional

endian code to prepend to format, as for unpack endian codes. None (the default) corresponds to the default behavior of struct - assuming system endian unless you specify the byte order specifically in the format string passed to unpack

read(n_bytes=-1)

Return byte string of length n_bytes at current position

Returns sub-string from self.buf and updates self.ptr to the position after the read data.

Parameters:
n_bytesint, optional

number of bytes to read. Can be -1 (the default) in which case we return all the remaining bytes in self.buf

Returns:
sbyte string
unpack(fmt)

Unpack values from contained buffer

Unpacks values from self.buf and updates self.ptr to the position after the read data.

Parameters:
fmtstr

format string as for unpack

Returns:
valuestuple

values as unpacked from self.buf according to fmt

find_private_section

nibabel.nicom.utils.find_private_section(dcm_data, group_no, creator)

Return start element in group group_no given creator name creator

Private attribute tags need to announce where they will go by putting a tag in the private group (here group_no) between elements 1 and 0xFF. The element number of these tags give the start of matching information, in the higher tag numbers.

Parameters:
dcm_datadicom dataset

Iterating over dcm_data produces elements with attributes tag, VR, value

group_noint

Group number in which to search

creatorstr or bytes or regex

Name of section - e.g. ‘SIEMENS CSA HEADER’ - or regex to search for section name. Regex used via creator.search(element_value) where element_value is the value of the data element.

Returns:
element_startint

Element number at which named section starts.