'Export source spaces to nifti or mgz file.
Parameters
fname : str
Name of nifti or mgz file to write.
include_surfaces : bool
If True, include surface source spaces.
include_discrete : bool
If True, include discrete source spaces.
dest : \'mri\' | \'surf\'
If \'mri\' the volume is defined in the coordinate system of the
original T1 image. If \'surf\' the coordinate system of the
FreeSurfer surface is used (Surface RAS).
trans : dict, str, or None
Either a transformation filename (usually made using mne_analyze)
or an info dict (usually opened using read_trans()).
If string, an ending of `.fif` or `.fif.gz` will be assumed to be
in FIF format, any other ending will be assumed to be a text file
with a 4x4 transformation matrix (like the `--trans` MNE-C option.
Must be provided if source spaces are in head coordinates and
include_surfaces and mri_resolution are True.
mri_resolution : bool
If True, the image is saved in MRI resolution
(e.g. 256 x 256 x 256).
use_lut : bool
If True, assigns a numeric value to each source space that
corresponds to a color on the freesurfer lookup table.
verbose : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more).
Notes
This method requires nibabel.'

@verbose
def export_volume(self, fname, include_surfaces=True, include_discrete=True, dest='mri', trans=None, mri_resolution=False, use_lut=True, verbose=None):

    try:
        import nibabel as nib
    except ImportError:
        raise ImportError('This    function    requires    nibabel.')
    coord_frames = np.array([s['coord_frame'] for s in self])
    if (coord_frames == FIFF.FIFFV_COORD_HEAD).all():
        coords = 'head'
        if (mri_resolution and include_surfaces):
            if (trans is None):
                raise ValueError('trans    containing    mri    to    head    transform    must    be    provided    if    mri_resolution    and    include_surfaces    are    true    and    surfaces    are    in    head    coordinates')
        elif (trans is not None):
            logger.info('trans    is    not    needed    and    will    not    be    used    unless    include_surfaces    and    mri_resolution    are    True.')
    elif (coord_frames == FIFF.FIFFV_COORD_MRI).all():
        coords = 'mri'
        if (trans is not None):
            logger.info('trans    is    not    needed    and    will    not    be    used    unless    sources    are    in    head    coordinates.')
    else:
        raise ValueError('All    sources    must    be    in    head    coordinates    or    all    sources    must    be    in    mri    coordinates.')
    logger.info('Reading    FreeSurfer    lookup    table')
    lut = _get_lut()
    src_types = dict(volume=[], surface=[], discrete=[])
    for src in self:
        if (src['type'] == 'vol'):
            src_types['volume'].append(src)
        elif (src['type'] == 'surf'):
            src_types['surface'].append(src)
        elif (src['type'] == 'discrete'):
            src_types['discrete'].append(src)
        else:
            raise ValueError(('Unrecognized    source    type:    %s.' % src['type']))
    inuse = 0
    for (ii, vs) in enumerate(src_types['volume']):
        if ('seg_name' not in vs):
            raise ValueError('Volume    sources    should    be    segments,    not    the    entire    volume.')
        id_ = _get_lut_id(lut, vs['seg_name'], use_lut)
        if (ii == 0):
            if mri_resolution:
                aseg_data = nib.load(vs['mri_file']).get_data()
                shape3d = (vs['mri_height'], vs['mri_depth'], vs['mri_width'])
            else:
                shape3d = vs['shape'][2::(-1)]
        if mri_resolution:
            use = (id_ * (aseg_data == id_).astype(int).ravel('F'))
        else:
            use = (id_ * vs['inuse'])
        inuse += use
    if (np.array(inuse).ndim == 0):
        raise ValueError('Source    spaces    must    contain    at    least    one    volume.')
    assert (len(inuse) == np.prod(shape3d))
    img = inuse.reshape(shape3d).T
    if (include_surfaces or include_discrete):
        if mri_resolution:
            affine = invert_transform(vs['vox_mri_t'])
        else:
            affine = invert_transform(vs['src_mri_t'])
        if (coords == 'head'):
            mri_head_t = _get_trans(trans)[0]
            head_mri_t = invert_transform(mri_head_t)
            affine = combine_transforms(head_mri_t, affine, 'head', 'mri_voxel')
        if include_surfaces:
            surf_names = ['Left-Cerebral-Cortex', 'Right-Cerebral-Cortex']
            for (i, surf) in enumerate(src_types['surface']):
                srf_rr = apply_trans(affine['trans'], surf['rr'])
                (ix_orig, iy_orig, iz_orig) = srf_rr.T.round().astype(int)
                ix_clip = np.maximum(np.minimum(ix_orig, (shape3d[2] - 1)), 0)
                iy_clip = np.maximum(np.minimum(iy_orig, (shape3d[1] - 1)), 0)
                iz_clip = np.maximum(np.minimum(iz_orig, (shape3d[0] - 1)), 0)
                n_diff = np.array(((ix_orig != ix_clip), (iy_orig != iy_clip), (iz_orig != iz_clip))).any(0).sum()
                if (n_diff > 0):
                    warn(('%s    surface    vertices    lay    outside    of    volume    space.    Consider    using    a    larger    volume    space.' % n_diff))
                i = _get_lut_id(lut, surf_names[i], use_lut)
                img[(ix_clip, iy_clip, iz_clip)] = i
        if include_discrete:
            for (i, disc) in enumerate(src_types['discrete']):
                disc_rr = apply_trans(affine['trans'], disc['rr'])
                (ix_orig, iy_orig, iz_orig) = disc_rr.T.astype(int)
                ix_clip = np.maximum(np.minimum(ix_orig, (shape3d[2] - 1)), 0)
                iy_clip = np.maximum(np.minimum(iy_orig, (shape3d[1] - 1)), 0)
                iz_clip = np.maximum(np.minimum(iz_orig, (shape3d[0] - 1)), 0)
                n_diff = np.array(((ix_orig != ix_clip), (iy_orig != iy_clip), (iz_orig != iz_clip))).any(0).sum()
                if (n_diff > 0):
                    warn(('%s    discrete    vertices    lay    outside    of    volume    space.    Consider    using    a    larger    volume    space.' % n_diff))
                img[(ix_clip, iy_clip, iz_clip)] = 1
                if use_lut:
                    logger.info('Discrete    sources    do    not    have    values    on    the    lookup    table.    Defaulting    to    1.')
    if mri_resolution:
        transform = vs['vox_mri_t'].copy()
    else:
        transform = vs['src_mri_t'].copy()
    if (dest == 'mri'):
        transform = combine_transforms(transform, vs['mri_ras_t'], transform['from'], vs['mri_ras_t']['to'])
    affine = transform['trans']
    affine[:3] *= 1000.0
    if fname.endswith(('.nii', '.nii.gz')):
        hdr = nib.Nifti1Header()
        hdr.set_xyzt_units('mm')
        img = nib.Nifti1Image(img, affine, header=hdr)
    elif fname.endswith('.mgz'):
        img = img.astype('float32')
        img = nib.freesurfer.mghformat.MGHImage(img, affine)
    else:
        raise ValueError('Unrecognized    file    extension')
    nib.save(img, fname)
