mne_bids/write.py
def write_anat(image, bids_path, landmarks=None, deface=False, overwrite=False,
               verbose=None):
    """Put anatomical MRI data into a BIDS format.

    Given an MRI scan, format and store the MR data according to BIDS in the
    correct location inside the specified :class:`mne_bids.BIDSPath`. If a
    transformation matrix is supplied, this information will be stored in a
    sidecar JSON file.

    .. note:: To generate the JSON sidecar with anatomical landmark
              coordinates ("fiducials"), you need to pass the landmarks via
              the ``landmarks`` parameter. :func:`mne_bids.get_anat_landmarks`
              may be useful for getting the ``landmarks``.

    Parameters
    ----------
    image : path-like | NibabelImageObject
        Path to an MRI scan (e.g. T1w) of the subject. Can be in any format
        readable by nibabel. Can also be a nibabel image object of an
        MRI scan. Will be written as a .nii.gz file.
    bids_path : BIDSPath
        The file to write. The :class:`mne_bids.BIDSPath` instance passed here
        **must** have the ``root`` and ``subject`` attributes set.
        The suffix is assumed to be ``'T1w'`` if not present. It can
        also be ``'FLASH'``, for example, to indicate FLASH MRI.
    landmarks : mne.channels.DigMontage | str | None
        The montage or path to a montage with landmarks that can be
        passed to provide information for defacing. Landmarks can be determined
        from the head model using `mne coreg` GUI, or they can be determined
        from the MRI using freeview.  If ``None`` and no ``trans`` parameter
        is passed, no sidecar JSON file will be created.
    deface : bool | dict
        If False, no defacing is performed.
        If True, deface with default parameters.
        `trans` and `raw` must not be `None` if True.
        If dict, accepts the following keys:

        - `inset`: how far back in voxels to start defacing
          relative to the nasion (default 5)

        - `theta`: is the angle of the defacing shear in degrees relative
          to vertical (default 15).

    overwrite : bool
        Whether to overwrite existing files or data in files.
        Defaults to False.
        If overwrite is True, any existing files with the same BIDS parameters
        will be overwritten with the exception of the `participants.tsv` and
        `scans.tsv` files. For these files, parts of pre-existing data that
        match the current data will be replaced.
        If overwrite is False, no existing data will be overwritten or
        replaced.
    %(verbose)s

    Returns
    -------
    bids_path : BIDSPath
        Path to the written MRI data.
    """
    if not has_nibabel():  # pragma: no cover
        raise ImportError('This function requires nibabel.')
    import nibabel as nib

    write_sidecar = landmarks is not None

    if deface and landmarks is None:
        raise ValueError('`landmarks` must be provided to deface the image')

    # Check if the root is available
    if bids_path.root is None:
        raise ValueError('The root of the "bids_path" must be set. '
                         'Please use `bids_path.update(root="<root>")` '
                         'to set the root of the BIDS folder to read.')
    # create a copy
    bids_path = bids_path.copy()

    # BIDS demands anatomical scans have no task associated with them
    bids_path.update(task=None)

    # XXX For now, only support writing a single run.
    bids_path.update(run=None)

    # this file is anat
    if bids_path.datatype is None:
        bids_path.update(datatype='anat')

    # default to T1w
    if not bids_path.suffix:
        bids_path.update(suffix='T1w')

    #  data is compressed Nifti
    bids_path.update(extension='.nii.gz')

    # create the directory for the MRI data
    bids_path.directory.mkdir(exist_ok=True, parents=True)

    # Try to read our MRI file and convert to MGH representation
    image_nii = _load_image(image)

    # Check if we have necessary conditions for writing a sidecar JSON
    if write_sidecar:
        if isinstance(landmarks, str):
            landmarks, coord_frame = read_fiducials(landmarks)
            landmarks = np.array([landmark['r'] for landmark in
                                  landmarks], dtype=float)  # unpack
        else:
            # Prepare to write the sidecar JSON, extract MEG landmarks
            coords_dict, coord_frame = _get_fid_coords(landmarks.dig)
            landmarks = np.asarray((coords_dict['lpa'],
                                    coords_dict['nasion'],
                                    coords_dict['rpa']))

        # check if coord frame is supported
        if coord_frame not in (FIFF.FIFFV_MNE_COORD_MRI_VOXEL,
                               FIFF.FIFFV_MNE_COORD_RAS):
            raise ValueError(f'Coordinate frame not supported: {coord_frame}')

        # convert to voxels from scanner RAS to voxels
        if coord_frame == FIFF.FIFFV_MNE_COORD_RAS:
            # Make MGH image for header properties
            img_mgh = nib.MGHImage(image_nii.dataobj, image_nii.affine)
            landmarks = _mri_scanner_ras_to_mri_voxels(
                landmarks * 1e3, img_mgh)

        # Write sidecar.json
        img_json = dict()
        img_json['AnatomicalLandmarkCoordinates'] = \
            {'LPA': list(landmarks[0, :]),
             'NAS': list(landmarks[1, :]),
             'RPA': list(landmarks[2, :])}
        fname = bids_path.copy().update(extension='.json')
        if op.isfile(fname) and not overwrite:
            raise IOError('Wanted to write a file but it already exists and '
                          '`overwrite` is set to False. File: "{}"'
                          .format(fname))
        _write_json(fname, img_json, overwrite)

        if deface:
            image_nii = _deface(image_nii, landmarks, deface)

    # Save anatomical data
    if op.exists(bids_path):
        if overwrite:
            os.remove(bids_path)
        else:
            raise IOError(f'Wanted to write a file but it already exists and '
                          f'`overwrite` is set to False. File: "{bids_path}"')

    nib.save(image_nii, bids_path.fpath)

    return bids_path
Put anatomical MRI data into a BIDS format.

    Given an MRI scan, format and store the MR data according to BIDS in the
    correct location inside the specified :class:`mne_bids.BIDSPath`. If a
    transformation matrix is supplied, this information will be stored in a
    sidecar JSON file.

    .. note:: To generate the JSON sidecar with anatomical landmark
              coordinates ("fiducials"), you need to pass the landmarks via
              the ``landmarks`` parameter. :func:`mne_bids.get_anat_landmarks`
              may be useful for getting the ``landmarks``.

    Parameters
    ----------
    image : path-like | NibabelImageObject
        Path to an MRI scan (e.g. T1w) of the subject. Can be in any format
        readable by nibabel. Can also be a nibabel image object of an
        MRI scan. Will be written as a .nii.gz file.
    bids_path : BIDSPath
        The file to write. The :class:`mne_bids.BIDSPath` instance passed here
        **must** have the ``root`` and ``subject`` attributes set.
        The suffix is assumed to be ``'T1w'`` if not present. It can
        also be ``'FLASH'``, for example, to indicate FLASH MRI.
    landmarks : mne.channels.DigMontage | str | None
        The montage or path to a montage with landmarks that can be
        passed to provide information for defacing. Landmarks can be determined
        from the head model using `mne coreg` GUI, or they can be determined
        from the MRI using freeview.  If ``None`` and no ``trans`` parameter
        is passed, no sidecar JSON file will be created.
    deface : bool | dict
        If False, no defacing is performed.
        If True, deface with default parameters.
        `trans` and `raw` must not be `None` if True.
        If dict, accepts the following keys:

        - `inset`: how far back in voxels to start defacing
          relative to the nasion (default 5)

        - `theta`: is the angle of the defacing shear in degrees relative
          to vertical (default 15).

    overwrite : bool
        Whether to overwrite existing files or data in files.
        Defaults to False.
        If overwrite is True, any existing files with the same BIDS parameters
        will be overwritten with the exception of the `participants.tsv` and
        `scans.tsv` files. For these files, parts of pre-existing data that
        match the current data will be replaced.
        If overwrite is False, no existing data will be overwritten or
        replaced.
    %(verbose)s

    Returns
    -------
    bids_path : BIDSPath
        Path to the written MRI data.
    
Put anatomical MRI data into a BIDS format.
Given an MRI scan, format and store the MR data according to BIDS in the
correct location inside the specified :class:`mne_bids.BIDSPath`. If a
transformation matrix is supplied, this information will be stored in a
sidecar JSON file.

: To generate the JSON sidecar with anatomical landmark
coordinates ("fiducials"), you need to pass the landmarks via
the ``landmarks`` parameter.

Parameters

image : path-like | NibabelImageObject
Path to an MRI scan  of the subject. Can be in any format
readable by nibabel. Can also be a nibabel image object of an
MRI scan. Will be written as a .nii.gz file.
bids_path : BIDSPath
The file to write.

`inset`: how far back in voxels to start defacing
relative to the nasion (default 5)

`theta`: is the angle of the defacing shear in degrees relative
to vertical (default 15).

overwrite : bool
Whether to overwrite existing files or data in files.
Defaults to False.
If overwrite is True, any existing files with the same BIDS parameters
will be overwritten with the exception of the `participants.tsv` and
`scans.tsv` files. For these files, parts of pre-existing data that
match the current data will be replaced.
If overwrite is False, no existing data will be overwritten or
replaced.
%(verbose)s

Returns

bids_path : BIDSPath
Path to the written MRI data.
Put anatomical MRI data into a BIDS format . Given an MRI scan format and store the MR data according to BIDS in the correct location inside the specified : class : ` mne_bids . BIDSPath ` . If a transformation matrix is supplied this information will be stored in a sidecar JSON file . : To generate the JSON sidecar with anatomical landmark coordinates ( " fiducials " ) you need to pass the landmarks via the ` ` landmarks ` ` parameter . Parameters image : path - like | NibabelImageObject Path to an MRI scan of the subject . Can be in any format readable by nibabel . Can also be a nibabel image object of an MRI scan . Will be written as a . nii . gz file . bids_path : BIDSPath The file to write . ` inset ` : how far back in voxels to start defacing relative to the nasion ( default 5 ) ` theta ` : is the angle of the defacing shear in degrees relative to vertical ( default 15 ) . overwrite : bool Whether to overwrite existing files or data in files . Defaults to False . If overwrite is True any existing files with the same BIDS parameters will be overwritten with the exception of the ` participants . tsv ` and ` scans . tsv ` files . For these files parts of pre - existing data that match the current data will be replaced . If overwrite is False no existing data will be overwritten or replaced . % ( verbose ) s Returns bids_path : BIDSPath Path to the written MRI data .
def write_anat(image, bids_path, landmarks=None, deface=False, overwrite=False,
               verbose=None):
    if not has_nibabel():  
        raise ImportError('This function requires nibabel.')
    import nibabel as nib
    write_sidecar = landmarks is not None
    if deface and landmarks is None:
        raise ValueError('`landmarks` must be provided to deface the image')
    if bids_path.root is None:
        raise ValueError('The root of the "bids_path" must be set. '
                         'Please use `bids_path.update(root="<root>")` '
                         'to set the root of the BIDS folder to read.')
    bids_path = bids_path.copy()
    bids_path.update(task=None)
    bids_path.update(run=None)
    if bids_path.datatype is None:
        bids_path.update(datatype='anat')
    if not bids_path.suffix:
        bids_path.update(suffix='T1w')
    bids_path.update(extension='.nii.gz')
    bids_path.directory.mkdir(exist_ok=True, parents=True)
    image_nii = _load_image(image)
    if write_sidecar:
        if isinstance(landmarks, str):
            landmarks, coord_frame = read_fiducials(landmarks)
            landmarks = np.array([landmark['r'] for landmark in
                                  landmarks], dtype=float)  
        else:
            coords_dict, coord_frame = _get_fid_coords(landmarks.dig)
            landmarks = np.asarray((coords_dict['lpa'],
                                    coords_dict['nasion'],
                                    coords_dict['rpa']))
        if coord_frame not in (FIFF.FIFFV_MNE_COORD_MRI_VOXEL,
                               FIFF.FIFFV_MNE_COORD_RAS):
            raise ValueError(f'Coordinate frame not supported: {coord_frame}')
        if coord_frame == FIFF.FIFFV_MNE_COORD_RAS:
            img_mgh = nib.MGHImage(image_nii.dataobj, image_nii.affine)
            landmarks = _mri_scanner_ras_to_mri_voxels(
                landmarks * 1e3, img_mgh)
        img_json = dict()
        img_json['AnatomicalLandmarkCoordinates'] = \
            {'LPA': list(landmarks[0, :]),
             'NAS': list(landmarks[1, :]),
             'RPA': list(landmarks[2, :])}
        fname = bids_path.copy().update(extension='.json')
        if op.isfile(fname) and not overwrite:
            raise IOError('Wanted to write a file but it already exists and '
                          '`overwrite` is set to False. File: "{}"'
                          .format(fname))
        _write_json(fname, img_json, overwrite)
        if deface:
            image_nii = _deface(image_nii, landmarks, deface)
    if op.exists(bids_path):
        if overwrite:
            os.remove(bids_path)
        else:
            raise IOError(f'Wanted to write a file but it already exists and '
                          f'`overwrite` is set to False. File: "{bids_path}"')
    nib.save(image_nii, bids_path.fpath)
    return bids_path
def write_anat ( image , bids_path , landmarks = None , deface = False , overwrite = False , verbose = None ) : if not has_nibabel ( ) : raise ImportError ( 'This function requires nibabel.' ) import nibabel as nib write_sidecar = landmarks is not None if deface and landmarks is None : raise ValueError ( '`landmarks` must be provided to deface the image' ) if bids_path . root is None : raise ValueError ( 'The root of the "bids_path" must be set. ' 'Please use `bids_path.update(root="<root>")` ' 'to set the root of the BIDS folder to read.' ) bids_path = bids_path . copy ( ) bids_path . update ( task = None ) bids_path . update ( run = None ) if bids_path . datatype is None : bids_path . update ( datatype = 'anat' ) if not bids_path . suffix : bids_path . update ( suffix = 'T1w' ) bids_path . update ( extension = '.nii.gz' ) bids_path . directory . mkdir ( exist_ok = True , parents = True ) image_nii = _load_image ( image ) if write_sidecar : if isinstance ( landmarks , str ) : landmarks , coord_frame = read_fiducials ( landmarks ) landmarks = np . array ( [ landmark [ 'r' ] for landmark in landmarks ] , dtype = float ) else : coords_dict , coord_frame = _get_fid_coords ( landmarks . dig ) landmarks = np . asarray ( ( coords_dict [ 'lpa' ] , coords_dict [ 'nasion' ] , coords_dict [ 'rpa' ] ) ) if coord_frame not in ( FIFF . FIFFV_MNE_COORD_MRI_VOXEL , FIFF . FIFFV_MNE_COORD_RAS ) : raise ValueError ( f'Coordinate frame not supported: {coord_frame}' ) if coord_frame == FIFF . FIFFV_MNE_COORD_RAS : img_mgh = nib . MGHImage ( image_nii . dataobj , image_nii . affine ) landmarks = _mri_scanner_ras_to_mri_voxels ( landmarks * 1e3 , img_mgh ) img_json = dict ( ) img_json [ 'AnatomicalLandmarkCoordinates' ] = { 'LPA' : list ( landmarks [ 0 , : ] ) , 'NAS' : list ( landmarks [ 1 , : ] ) , 'RPA' : list ( landmarks [ 2 , : ] ) } fname = bids_path . copy ( ) . update ( extension = '.json' ) if op . isfile ( fname ) and not overwrite : raise IOError ( 'Wanted to write a file but it already exists and ' '`overwrite` is set to False. File: "{}"' . format ( fname ) ) _write_json ( fname , img_json , overwrite ) if deface : image_nii = _deface ( image_nii , landmarks , deface ) if op . exists ( bids_path ) : if overwrite : os . remove ( bids_path ) else : raise IOError ( f'Wanted to write a file but it already exists and ' f'`overwrite` is set to False. File: "{bids_path}"' ) nib . save ( image_nii , bids_path . fpath ) return bids_path
Put anatomical MRI data into a BIDS format.
Put anatomical MRI data into a BIDS format .
"""Put anatomical MRI data into a BIDS format.

    Given an MRI scan, format and store the MR data according to BIDS in the
    correct location inside the specified :class:`mne_bids.BIDSPath`. If a
    transformation matrix is supplied, this information will be stored in a
    sidecar JSON file.

    .. note:: To generate the JSON sidecar with anatomical landmark
              coordinates ("fiducials"), you need to pass the landmarks via
              the ``landmarks`` parameter. :func:`mne_bids.get_anat_landmarks`
              may be useful for getting the ``landmarks``.

    Parameters
    ----------
    image : path-like | NibabelImageObject
        Path to an MRI scan (e.g. T1w) of the subject. Can be in any format
        readable by nibabel. Can also be a nibabel image object of an
        MRI scan. Will be written as a .nii.gz file.
    bids_path : BIDSPath
        The file to write. The :class:`mne_bids.BIDSPath` instance passed here
        **must** have the ``root`` and ``subject`` attributes set.
        The suffix is assumed to be ``'T1w'`` if not present. It can
        also be ``'FLASH'``, for example, to indicate FLASH MRI.
    landmarks : mne.channels.DigMontage | str | None
        The montage or path to a montage with landmarks that can be
        passed to provide information for defacing. Landmarks can be determined
        from the head model using `mne coreg` GUI, or they can be determined
        from the MRI using freeview.  If ``None`` and no ``trans`` parameter
        is passed, no sidecar JSON file will be created.
    deface : bool | dict
        If False, no defacing is performed.
        If True, deface with default parameters.
        `trans` and `raw` must not be `None` if True.
        If dict, accepts the following keys:

        - `inset`: how far back in voxels to start defacing
          relative to the nasion (default 5)

        - `theta`: is the angle of the defacing shear in degrees relative
          to vertical (default 15).

    overwrite : bool
        Whether to overwrite existing files or data in files.
        Defaults to False.
        If overwrite is True, any existing files with the same BIDS parameters
        will be overwritten with the exception of the `participants.tsv` and
        `scans.tsv` files. For these files, parts of pre-existing data that
        match the current data will be replaced.
        If overwrite is False, no existing data will be overwritten or
        replaced.
    %(verbose)s

    Returns
    -------
    bids_path : BIDSPath
        Path to the written MRI data.
    """ # pragma: no cover # Check if the root is available # create a copy # BIDS demands anatomical scans have no task associated with them # XXX For now, only support writing a single run. # this file is anat # default to T1w #  data is compressed Nifti # create the directory for the MRI data # Try to read our MRI file and convert to MGH representation # Check if we have necessary conditions for writing a sidecar JSON # unpack # Prepare to write the sidecar JSON, extract MEG landmarks # check if coord frame is supported # convert to voxels from scanner RAS to voxels # Make MGH image for header properties # Write sidecar.json # Save anatomical data
image
bids_path
landmarks
deface
overwrite
verbose