nicom
¶
DICOM reader
CSA header reader from SPM spec |
|
Classes to wrap DICOM objects and files |
|
Process diffusion imaging parameters |
|
Stream-like reader for packed data |
Module: nicom.ascconv
¶
Parse the “ASCCONV” meta data format found in a variety of Siemens MR files.
Error parsing ascconv file |
|
|
Object to hold operation, object type and object identifier |
|
Signals no value present |
|
Parse single assignment ast from ascconv line into atoms |
|
Return object defined by list atoms in dict-like namespace |
|
Parse the 'ASCCONV' format from input_str. |
Module: nicom.csareader
¶
CSA header reader from SPM spec
|
|
|
|
|
|
|
Get CSA header information from DICOM header |
|
|
|
|
|
|
|
|
|
|
|
|
|
Return True if the data is of Mosaic type |
|
Strip string to first null |
|
Read CSA header from string csa_str |
Module: nicom.dicomreaders
¶
|
Get Nifti file from Siemens |
|
Read all Siemens mosaic DICOMs in directory, return arrays, params |
|
|
|
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.
|
Class for Siemens mosaic format data |
|
Wrapper for Enhanced MR Storage SOP Class |
|
Wrapper for Siemens format DICOMs |
|
Class to wrap general DICOM files |
|
Match if val1 and val2 are both None, or are close |
|
Create DICOM wrapper from DICOM data object |
|
Create DICOM wrapper from file_like object |
Module: nicom.dwiparams
¶
Process diffusion imaging parameters
q
is a vector in Q spaceb
is a b valueg
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)
|
Estimate q vector from input B matrix B |
Least squares positive semi-definite tensor estimation |
|
|
Return b value and q unit vector from q vector q_vector |
Module: nicom.structreader
¶
Stream-like reader for packed data
|
Class to unpack values from buffer object |
Module: nicom.utils
¶
Utilities for working with DICOM datasets
|
Return start element in group group_no given creator name creator |
AscconvParseError
¶
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 anop = ast.Attribute
operation where the object type (obj_type) ofc
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]
, isop = 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
¶
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 foratoms
. 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
¶
CSAReadError
¶
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 ofdcm_data[(0x29, 0x10)]
passes, should satisfy interface forfind_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
¶
mosaic_to_nii¶
- nibabel.nicom.dicomreaders.mosaic_to_nii(dcm_data)¶
Get Nifti file from Siemens
- Parameters:
- dcm_data
dicom.DataSet
DICOM header / image as read by
dicom
package
- dcm_data
- Returns:
- img
Nifti1Image
Nifti image object
- img
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
read_file
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
xn_slice_cols
. The slab is of pixel dimensionn_slab_rows
xn_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. Letn_blocks
be the number of blocks contained in the slab. There is alson_slices
- the number of slices actually collected, some number <=n_blocks
. We have the valuen_slices
from the ‘NumberOfImagesInMosaic’ field of the Siemens private (CSA) header.n_row_blocks
andn_col_blocks
are therefore given byceil(sqrt(n_slices))
, andn_blocks
isn_row_blocks ** 2
. Alson_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 thedicom.dataset.Dataset.PerFrameFunctionalGroupsSequence
attribute- sharedobject
The first (and only)
dicom.dataset.Dataset
object from adicom.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
C.7.6.16 Multi-Frame Functional Groups Module: http://dicom.nema.org/medical/dicom/current/output/pdf/part03.pdf#sect_C.7.6.16
C.7.6.17 Multi-Frame Dimension Module: http://dicom.nema.org/medical/dicom/current/output/pdf/part03.pdf#sect_C.7.6.17
Diagram of DimensionIndexSequence and DimensionIndexValues: http://dicom.nema.org/medical/dicom/current/output/pdf/part03.pdf#figure_C.7.6.17-1
- 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 aWrapper
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
¶
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_data
dicom.dataset.Dataset
instance or similar Object allowing attribute access, with DICOM attributes. Probably a dataset as read by
pydicom
.
- dcm_data
- Returns:
- dcm_w
dicomwrappers.Wrapper
or subclass DICOM wrapper corresponding to DICOM data type
- dcm_w
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.read_file
command.- **kwargskeyword
args to
dicom.read_file
command.force=True
might be a likely keyword argument.
- Returns:
- dcm_w
dicomwrappers.Wrapper
or subclass DICOM wrapper corresponding to DICOM data type
- dcm_w
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 usingstruct.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 ofstruct
- assuming system endian unless you specify the byte order specifically in the format string passed tounpack
- __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 ofstruct
- assuming system endian unless you specify the byte order specifically in the format string passed tounpack
- read(n_bytes=-1)¶
Return byte string of length n_bytes at current position
Returns sub-string from
self.buf
and updatesself.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 updatesself.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 attributestag
,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)
whereelement_value
is the value of the data element.
- dcm_datadicom
- Returns:
- element_startint
Element number at which named section starts