Models

Module contents

Definition of the app’s models.

Submodules

django_mri.models.common_sequences module

A list of common MRI sequences and their respective DICOM header attributes.

django_mri.models.fields module

Definition of a custom ArrayField subclass.

Copied from https://blogs.gnome.org/danni/2016/03/08/multiple-choice-using-djangos-postgres-arrayfield/.

class django_mri.models.fields.ChoiceArrayField(base_field, size=None, **kwargs)

Bases: django.contrib.postgres.fields.array.ArrayField

A field that allows us to store an array of choices.

Uses Django’s PostgreSQL ArrayField and a MultipleChoiceField for its formfield.

formfield(**kwargs)

Return a django.forms.Field instance for this field.

django_mri.models.help_text module

A module storing strings used to populate the fields’ help_text attributes.

django_mri.models.messages module

A module storing strings used to display messages.

django_mri.models.nifti module

Definition of the NIfTI model.

class django_mri.models.nifti.NIfTI(*args, **kwargs)

Bases: django_extensions.db.models.TimeStampedModel

A model representing a NIfTI file in the database.

b_value

Returns the B-value of DWI scans as calculated by dcm2niix.

See also

Returns:B-value
Return type:List[int]
b_vector

Returns the B-vector of DWI scans as calculated by dcm2niix.

See also

Returns:B-vector
Return type:List[List[float]]
compress(keep_source: bool = False) → pathlib.Path

Compress the associated .nii using gzip, if it isn’t already compressed.

Parameters:keep_source (bool, optional) – Whether to keep a copy of the uncompressed file, by default False
Returns:Path of the compressed (.nii.gz) file
Return type:Path
compressed

Compresses the associated .nii file using gzip if it isn’t and returns its path.

Returns:Compressed .nii.gz file associated with this instance
Return type:Path
get_b_value() → List[int]

Returns the degree of diffusion weighting applied (b-value) for each diffusion direction. This method relies on dcm2niix’s default configuration in which when diffusion-weighted images (DWI) are converted, another file with the same name and a “bval” extension is created alongside.

Hint

For more information, see dcm2niix’s Diffusion Tensor Imaging section of the user guide.

See also

Returns:b-value for each diffusion direction.
Return type:List[int]
get_b_vector() → List[List[float]]

Returns the b-vectors representing the diffusion weighting gradient scheme. This method relies on dcm2niix’s default configuration in which when diffusion-weighted images (DWI) are converted, another file with the same name and a “bvec” extension is created alongside.

Hint

For more information, see dcm2niix’s Diffusion Tensor Imaging section of the user guide.

See also

Returns:b-value for each diffusion direction
Return type:List[List[float]]
get_data() → numpy.ndarray

Uses NiBabel to return the underlying pixel data as a NumPy array.

Returns:Pixel data.
Return type:np.ndarray
get_effective_spacing() → float

Reads the effective echo spacing value extracted by dcm2niix upon conversion.

Returns:Effective echo spacing
Return type:float
get_phase_encoding_direction() → float

Reads the phase encoding direction value extracted by dcm2niix upon conversion.

Returns:Phase encoding direction
Return type:float
get_total_readout_time() → float

Reads the total readout time extracted by dcm2niix upon conversion.

Hint

Total readout time is defined as the time from the center of the first echo to the center of the last (in seconds).

Returns:Total readout time
Return type:float
is_compressed

Whether the associated .nii file is compressed with gzip or not.

Returns:Associated .nii file gzip compression state
Return type:bool
is_raw

Whether the created instance is the product of a direct conversion from some raw format to NIfTI or of a manipulation of the data.

json_data

Reads BIDS sidecar information and caches within a local variable to prevent multiple reads.

See also

Returns:“BIDS sidecar” JSON data
Return type:dict
objects = <django.db.models.manager.Manager object>
path

Path of the .nii file within the application’s media directory.

read_json() → dict

Returns the JSON data generated alognside .nii files generated using dcm2niix’s “BIDS sidecar” option.

Notes

Returns:BIDS sidecar information stored in a JSON file, or {} if the file doesn’t exist
Return type:dict
run_input_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

run_output_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

scan

Accessor to the related object on the reverse side of a one-to-one relation.

In the example:

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Place.restaurant is a ReverseOneToOneDescriptor instance.

uncompress(keep_source: bool = False) → pathlib.Path

Uncompress the associated .nii using gzip, if it isn’t already uncompressed.

Parameters:keep_source (bool, optional) – Whether to keep a copy of the compressed file, by default False
Returns:Path of the uncompressed (.nii) file
Return type:Path
uncompressed

Uncompresses the associated .nii file using gzip if it isn’t and returns its path.

Returns:Uncompressed .nii file associated with this instance
Return type:Path

django_mri.models.scan module

Definition of the Scan model.

class django_mri.models.scan.Scan(*args, **kwargs)

Bases: django_extensions.db.models.TimeStampedModel

A model used to represent an MRI scan independently from the file-format in which it is saved. This model handles any conversions between formats in case they are required, and allows for easy querying of MRI scans based on universal attributes.

added_by

Keeps a record of the user that added this scan.

comments

Any other comments about this scan.

compile_to_bids(bids_path: pathlib.Path)
convert_to_mif() → pathlib.Path

Creates a .mif version of this scan using mrconvert.

Returns:Created file path
Return type:Path
description

Short description of the scan’s acquisition parameters.

dicom

If this instance’s origin is a DICOM file, or it was saved as one, this field stores the association with the appropriate :class`django_dicom.models.series.Series` instance.

dicom_to_nifti(destination: pathlib.Path = None, compressed: bool = True, generate_json: bool = True) → django_mri.models.nifti.NIfTI

Convert this scan from DICOM to NIfTI using _dcm2niix.

Parameters:destination (Path, optional) – The desired path for conversion output (the default is None, which will create the file in some default location)
Raises:AttributeError – If no DICOM series is related to this scan
Returns:A django_mri.NIfTI instance referencing the conversion output
Return type:NIfTI
echo_time

The time between the application of the radio-frequency excitation pulse and the peak of the signal induced in the coil (in milliseconds).

get_bids_destination() → pathlib.Path

Returns the BIDS-compatible destination of this scan’s associated NIfTI file.

Returns:BIDS-compatible NIfTI file destination
Return type:pathlib.Path
get_default_mif_path() → pathlib.Path

Returns the default .mif path for this scan.

Returns:Default .mif path
Return type:Path
get_default_nifti_destination() → pathlib.Path

Returns the default path for a NIfTI version of this scan.

Returns:Default path for NIfTI file
Return type:str
get_default_nifti_dir() → pathlib.Path

Returns the default location for the creation of a NIfTI version of the scan. Currently only conversion from DICOM is supported.

Returns:Default location for conversion output
Return type:str
get_default_nifti_name() → str

Returns the default file name for a NIfTI version of this scan.

Returns:Default file name
Return type:str
infer_sequence_type() → django_mri.models.sequence_type.SequenceType

Tries to infer the sequence type using associated data.

Returns:The inferred sequence type
Return type:SequenceType
infer_sequence_type_from_dicom() → django_mri.models.sequence_type.SequenceType

Returns the appropriate django_mri.SequenceType instance according to the scan’s “ScanningSequence” and “SequenceVariant” header values.

Returns:The inferred sequence type
Return type:SequenceType
institution_name

The institution in which this scan was acquired.

inversion_time

The time between the 180-degree inversion pulse and the following spin-echo (SE) sequence (in milliseconds).

is_updated_from_dicom

Keeps track of whether we’ve updated the instance’s fields from DICOM header data or not.

mif

Returns the .mif version of this scan, creating it if it doesn’t exist.

Returns:.mif file path
Return type:Path

See also

nifti

Returns the associated NIfTI instance if one exists, or tries to create one if it doesn’t.

Returns:Associated NIfTI instance
Return type:NIfTI
number

The relative number of this scan in the session in which it was acquired.

objects = <django_mri.models.managers.scan.ScanManager object>
repetition_time

The time between two successive RF pulses (in milliseconds).

run_input_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

save(*args, **kwargs) → None

Overrides the model’s save() method to provide custom validation.

Hint

For more information, see Django’s documentation on overriding model methods.

sequence_type

Returns the sequence type instance fitting this scan if one exists.

Returns:Inferred sequence type
Return type:SequenceType
spatial_resolution

The spatial resolution of the image in millimeters.

study_groups

Individual scans may be associated with multiple Group instances. This is meant to provide flexibility in managing access to data between researchers working on different studies. The Group model is expected to be specified as STUDY_GROUP_MODEL in the project’s settings.

subject

Associates this scan with some subject. Subjects are expected to be represented by a model specified as SUBJECT_MODEL in the project’s settings.

suggest_subject(subject) → None
time

Acquisition datetime.

update_fields_from_dicom() → None

Sets instance fields from related DICOM series.

Raises:AttributeError – If not DICOM series is related to this scan
warn_subject_mismatch(subject)

Warns the user regarding a mismatch in subject identity.

Parameters:subject (django.db.models.Model) – Suggested subject identity

django_mri.models.sequence_type module

class django_mri.models.sequence_type.SequenceType(*args, **kwargs)

Bases: django_extensions.db.models.TitleDescriptionModel, django_extensions.db.models.TimeStampedModel

The purpose of this model is to provide a title and description for
commonly used sequences, as well as to facilitate queries.

Each particular sequence is defined as a unique combination of DICOM’s “ScanningSequence” and “SequenceVariant” attributes. This model is a wrapper for the known combinations.

objects = <django_mri.models.managers.sequence_type.SequenceTypeManager object>
sequence_definition_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

sequence_definitions