예제 #1
0
    def compute(self):
        
        all_data = self.getData('data')
        xml_header = self.getData('ISMRMRDHeader')

        header = ismrmrd.xsd.CreateFromDocument(xml_header)
        enc = header.encoding[0]

        #Parallel imaging factor
        acc_factor = 1
        if enc.parallelImaging:
            acc_factor = enc.parallelImaging.accelerationFactor.kspace_encoding_step_1
        
        # Coil combination
        print "Calculating coil images and CSM"
        coil_images = transform.transform_kspace_to_image(np.squeeze(np.mean(all_data,0)),(1,2))
        (csm,rho) = coils.calculate_csm_walsh(coil_images)
        csm_ss = np.sum(csm * np.conj(csm),0)
        csm_ss = csm_ss + 1.0*(csm_ss < np.spacing(1)).astype('float32')
        
        if acc_factor > 1:
            coil_data = np.squeeze(np.mean(all_data,0))
            
            if self.getVal('Parallel Imaging Method') == 0:
                (unmix,gmap) = grappa.calculate_grappa_unmixing(coil_data, acc_factor,csm=csm)
            elif self.getVal('Parallel Imaging Method') == 1:
                (unmix,gmap) = sense.calculate_sense_unmixing(acc_factor,csm)
            else:
                raise Exception('Unknown parallel imaging method')

        recon = np.zeros((all_data.shape[-4],all_data.shape[-2],all_data.shape[-1]), dtype=np.complex64)
        
        for r in range(0,all_data.shape[-4]):
            recon_data = transform.transform_kspace_to_image(np.squeeze(all_data[r,:,:,:]),(1,2))*np.sqrt(acc_factor)
            if acc_factor > 1:
                recon[r,:,:] = np.sum(unmix * recon_data,0)
            else:
                recon[r,:,:] = np.sum(np.conj(csm) * recon_data,0)

        print "Reconstruction done"
        
        self.setData('recon', recon)
        
        if acc_factor == 1:
            gmap = np.ones((all_data.shape[-2],all_data.shape[-1]),dtype=np.float32)
            
        self.setData('gmap',gmap)

        return 0
예제 #2
0
파일: view.py 프로젝트: zongjg/mr_utils
def view(image,
         load_opts=None,
         is_raw=None,
         is_line=None,
         prep=None,
         fft=False,
         fft_axes=None,
         fftshift=None,
         avg_axis=None,
         coil_combine_axis=None,
         coil_combine_method='walsh',
         coil_combine_opts=None,
         is_imspace=False,
         mag=None,
         phase=False,
         log=False,
         imshow_opts={'cmap': 'gray'},
         montage_axis=None,
         montage_opts={'padding_width': 2},
         movie_axis=None,
         movie_interval=50,
         movie_repeat=True,
         save_npy=False,
         debug_level=logging.DEBUG,
         test_run=False):
    '''Image viewer to quickly inspect data.

    Parameters
    ----------
    image : str or array_like
        Name of the file including the file extension or numpy array.
    load_opts : dict, optional
        Options to pass to data loader.
    is_raw : bool, optional
        Inform if data is raw. Will attempt to guess from extension.
    is_line : bool, optional
        Whether or not this is a line plot (as opposed to image).
    prep : callable, optional
        Lambda function to process the data before it's displayed.
    fft : bool, optional
        Whether or not to perform n-dimensional FFT of data.
    fft_axes : tuple, optional
        Axis to perform FFT over, determines dimension of n-dim FFT.
    fftshift : bool, optional
        Whether or not to perform fftshift. Defaults to True if fft.
    avg_axis : int, optional
        Take average over given set of axes.
    coil_combine_axis : int, optional
        Which axis to perform coil combination over.
    coil_combine_method : {'walsh', 'inati', 'pca'}, optional
        Method to use to combine coils.
    coil_combine_opts : dict, optional
        Options to pass to the coil combine method.
    is_imspace : bool, optional
        Whether or not the data is in image space. For coil combine.
    mag : bool, optional
        View magnitude image. Defaults to True if data is complex.
    phase : bool, optional
        View phase image.
    log : bool, optional
        View log of magnitude data. Defaults to False.
    imshow_opts : dict, optional
        Options to pass to imshow. Defaults to { 'cmap'='gray' }.
    montage_axis : int, optional
        Which axis is the number of images to be shown.
    montage_opts : dict, optional
        Additional options to pass to the skimage.util.montage.
    movie_axis : int, optional
        Which axis is the number of frames of the movie.
    movie_interval : int, optional
        Interval to give to animation frames.
    movie_repeat : bool, optional
        Whether or not to put movie on endless loop.
    save_npy : bool, optional
        Whether or not to save the output as npy file.
    debug_level : logging_level, optional
        Level of verbosity. See logging module.
    test_run : bool, optional
        Doesn't show figure, returns debug object. Mostly for testing.

    Returns
    -------
    data : array_like
        Image data shown in plot.
    dict, optional
        All local variables when test_run=True.

    Raises
    ------
    Exception
        When file type is not in ['dat', 'npy', 'mat', 'h5'].
    ValueError
        When coil combine requested, but fft_axes not set.
    AssertionError
        When Walsh coil combine requested but len(fft_axes) =/= 2.
    ValueError
        When there are too many dimension to display.
    '''

    # Set up logging...
    logging.basicConfig(format='%(levelname)s: %(message)s', level=debug_level)

    # Add some default empty params
    if load_opts is None:
        load_opts = dict()
    if coil_combine_opts is None:
        coil_combine_opts = dict()

    # If the user wants to look at numpy matrix, recognize that
    # filename is the matrix:
    if isinstance(image, np.ndarray):
        logging.info('Image is a numpy array!')
        data = image
    elif isinstance(image, list):
        # If user sends a list, try casting to numpy array
        logging.info('Image is a list, trying to cast as numpy array...')
        data = np.array(image)
    else:
        # Find the file extension
        ext = pathlib.Path(image).suffix

        # If the user says data is raw, then trust the user
        if is_raw or (ext == '.dat'):
            data = load_raw(image, **load_opts)
        elif ext == '.npy':
            data = np.load(image, **load_opts)
        elif ext == '.mat':
            # Help out the user a little bit...  If only one
            # nontrivial key is found then go ahead and assume it's
            # that one
            data = None
            if not list(load_opts):
                keys = mat_keys(image, no_print=True)
                if len(keys) == 1:
                    logging.info(('No key supplied, but one key for'
                                  ' mat dictionary found (%s), using'
                                  ' it...'), keys[0])
                    data = load_mat(image, key=keys[0])

            # If we can't help the user out, just load it as normal
            if data is None:
                data = load_mat(image, **load_opts)
        elif ext == '.h5':
            data = load_ismrmrd(image, **load_opts)
        else:
            raise Exception('File type %s not understood!' % ext)

    # Right off the bat, remove singleton dimensions
    if 1 in data.shape:
        logging.info('Current shape %s: Removing singleton dimensions...',
                     str(data.shape))
        data = data.squeeze()
        logging.info('New shape: %s', str(data.shape))

    # Average out over any axis specified
    if avg_axis is not None:
        data = np.mean(data, axis=avg_axis)

    # Let's collapse the coil dimension using the specified algorithm
    if coil_combine_axis is not None:

        # We'll need to know the fft_axes if the data is in kspace
        if not is_imspace and fft_axes is None:
            msg = ('fft_axes required to do coil combination of '
                   'k-space data!')
            raise ValueError(msg)

        if coil_combine_method == 'walsh':
            msg = 'Walsh only works with 2D images!'
            assert len(fft_axes) == 2, msg
            logging.info('Performing Walsh 2d coil combine across axis %d...',
                         list(range(data.ndim))[coil_combine_axis])

            # We need to do this is image domain...
            if not is_imspace:
                fft_data = np.fft.ifftshift(np.fft.ifftn(data, axes=fft_axes),
                                            axes=fft_axes)
            else:
                fft_data = data

            # walsh expects (coil,y,x)
            fft_data = np.moveaxis(fft_data, coil_combine_axis, 0)
            csm_walsh, _ = calculate_csm_walsh(fft_data, **coil_combine_opts)
            fft_data = np.sum(csm_walsh * np.conj(fft_data),
                              axis=0,
                              keepdims=True)

            # Sum kept the axis where coil used to be so we can rely
            # on fft_axes to be correct when do the FT back to kspace
            fft_data = np.moveaxis(fft_data, 0, coil_combine_axis)

            # Now move back to kspace and squeeze the dangling axis
            if not is_imspace:
                data = np.fft.fftn(np.fft.fftshift(fft_data, axes=fft_axes),
                                   axes=fft_axes).squeeze()
            else:
                data = fft_data.squeeze()

        elif coil_combine_method == 'inati':

            logging.info('Performing Inati coil combine across axis %d...',
                         list(range(data.ndim))[coil_combine_axis])

            # Put things into image space if we need to
            if not is_imspace:
                fft_data = np.fft.ifftshift(np.fft.ifftn(data, axes=fft_axes),
                                            axes=fft_axes)
            else:
                fft_data = data

            # inati expects (coil,z,y,x)
            fft_data = np.moveaxis(fft_data, coil_combine_axis, 0)
            _, fft_data = calculate_csm_inati_iter(fft_data,
                                                   **coil_combine_opts)

            # calculate_csm_inati_iter got rid of the axis, so we
            # need to add it back in so we can use the same fft_axes
            fft_data = np.expand_dims(fft_data, coil_combine_axis)

            # Now move back to kspace and squeeze the dangling axis
            if not is_imspace:
                data = np.fft.fftn(np.fft.fftshift(fft_data, axes=fft_axes),
                                   axes=fft_axes).squeeze()
            else:
                data = fft_data.squeeze()

        elif coil_combine_method == 'pca':
            logging.info('Performing PCA coil combine across axis %d...',
                         list(range(data.ndim))[coil_combine_axis])

            # We don't actually care whether we do this is in kspace
            # or imspace
            if not is_imspace:
                logging.info(('PCA doesn\'t care that image might not be in'
                              'image space.'))

            if 'n_components' not in coil_combine_opts:
                n_components = int(data.shape[coil_combine_axis] / 2)
                logging.info('Deciding to use %d components.', n_components)
                coil_combine_opts['n_components'] = n_components

            data = coil_pca(data,
                            coil_dim=coil_combine_axis,
                            **coil_combine_opts)

        else:
            logging.error('Coil combination method "%s" not supported!',
                          coil_combine_method)
            logging.warning('Attempting to skip coil combination!')

    # Show the image.  Let's also try to help the user out again.  If
    # we have 3 dimensions, one of them is probably a montage or a
    # movie.  If the user didn't tell us anything, it's going to
    # crash anyway, so let's try guessing what's going on...
    if (data.ndim > 2) and (movie_axis is None) and (montage_axis is None):
        logging.info('Data has %d dimensions!', data.ndim)

        # We will always assume that inplane resolution is larger
        # than the movie/montage dimensions

        # If only 3 dims, then one must be montage/movie dimension
        if data.ndim == 3:
            # assume inplane resolution larger than movie/montage dim
            min_axis = np.argmin(data.shape)

            # Assume 10 is the most we'll want to montage
            if data.shape[min_axis] < 10:
                logging.info('Guessing axis %d is montage...', min_axis)
                montage_axis = min_axis
            else:
                logging.info('Guessing axis %d is movie...', min_axis)
                movie_axis = min_axis

        # If 4 dims, guess smaller dim will be montage, larger guess
        # movie
        elif data.ndim == 4:
            montage_axis = np.argmin(data.shape)

            # Consider the 4th dimension as the color channel in
            # skimontage
            montage_opts['multichannel'] = True

            # Montage will go through skimontage which will remove the
            # montage_axis dimension, so find the movie dimension
            #  without the montage dimension:
            tmp = np.delete(data.shape[:], montage_axis)
            movie_axis = np.argmin(tmp)

            logging.info(('Guessing axis %d is montage, axis %d will be '
                          'movie...'), montage_axis, movie_axis)

    # fft and fftshift will require fft_axes.  If the user didn't
    # give us axes, let's try to guess them:
    if (fft or (fftshift is not False)) and (fft_axes is None):
        all_axes = list(range(data.ndim))

        if (montage_axis is not None) and (movie_axis is not None):
            fft_axes = np.delete(
                all_axes, [all_axes[montage_axis], all_axes[movie_axis]])
        elif montage_axis is not None:
            fft_axes = np.delete(all_axes, all_axes[montage_axis])
        elif movie_axis is not None:
            fft_axes = np.delete(all_axes, all_axes[movie_axis])
        else:
            fft_axes = all_axes

        logging.info('User did not supply fft_axes, guessing %s...',
                     str(fft_axes))

    # Perform n-dim FFT across fft_axes if desired
    if fft:
        data = np.fft.fftn(data, axes=fft_axes)

    # Perform fftshift if desired.  If the user does not specify
    # fftshift, if fft is performed, then fftshift will also be
    # performed.  To override this behavior, simply supply
    # fftshift=False in the arguments.  Similarly, to force fftshift
    # even if no fft was performed, supply fftshift=True.
    if fft and (fftshift is None):
        fftshift = True
    elif fftshift is None:
        fftshift = False

    if fftshift:
        data = np.fft.fftshift(data, axes=fft_axes)

    # Take absolute value to view if necessary, must take abs before
    # log
    if np.iscomplexobj(data) or (mag is True) or (log is True):
        data = np.abs(data)

        if log:
            # Don't take log of 0!
            data[data == 0] = np.nan
            data = np.log(data)

    # If we asked for phase, let's work out how we'll do that
    if phase and ((mag is None) or (mag is True)):
        # TODO: figure out which axis to concatenate the phase onto
        data = np.concatenate((data, np.angle(data)), axis=fft_axes[-1])
    elif phase and (mag is False):
        data = np.angle(data)

    # Run any processing before imshow
    if callable(prep):
        data = prep(data)

    # If it's just a line plot, skip all the montage, movie stuff
    if is_line:
        montage_axis = None
        movie_axis = None

    if montage_axis is not None:
        # We can deal with 4 dimensions if we allow multichannel
        if data.ndim == 4 and 'multichannel' not in montage_opts:
            montage_opts['multichannel'] = True

            # When we move the movie_axis to the end, we will need to
            # adjust the montage axis in case we displace it.  We
            # need to move it to the end so skimontage will consider
            # it the multichannel
            data = np.moveaxis(data, movie_axis, -1)
            if movie_axis < montage_axis:
                montage_axis -= 1

        # Put the montage axis in front
        data = np.moveaxis(data, montage_axis, 0)
        try:
            data = skimontage(data, **montage_opts)
        except ValueError:
            # Multichannel might be erronously set
            montage_opts['multichannel'] = False
            data = skimontage(data, **montage_opts)

        if data.ndim == 3:
            # If we had 4 dimensions, we just lost one, so now we
            # need to know where the movie dimension went off to...
            if movie_axis > montage_axis:
                movie_axis -= 1
            # Move the movie axis back, it's no longer the color
            # channel
            data = np.moveaxis(data, -1, movie_axis)

    if movie_axis is not None:
        fig = plt.figure()
        data = np.moveaxis(data, movie_axis, -1)
        im = plt.imshow(data[..., 0], **imshow_opts)

        def updatefig(frame):
            '''Animation function for figure.'''
            im.set_array(data[..., frame])
            return im,  # pylint: disable=R1707

        _ani = animation.FuncAnimation(fig,
                                       updatefig,
                                       frames=data.shape[-1],
                                       interval=movie_interval,
                                       blit=True,
                                       repeat=movie_repeat)

        if not test_run:
            plt.show()
    else:
        if data.ndim == 1 or is_line:
            plt.plot(data)
        elif data.ndim == 2:
            # Just a regular old 2d image...
            plt.imshow(np.nan_to_num(data), **imshow_opts)
        else:
            raise ValueError('%d is too many dimensions!' % data.ndim)

        if not test_run:
            plt.show()

    # Save what we looked at if desired
    if save_npy:
        if ext:
            filename = image
        else:
            filename = 'view-output'
        np.save(filename, data)

    # If we're testing, return all the local vars
    if test_run:
        return locals()
    return data
# -*- coding: utf-8 -*-

#%%
#Basic setup
import numpy as np
from ismrmrdtools import simulation, coils, show

matrix_size = 256
csm = simulation.generate_birdcage_sensitivities(matrix_size)
phan = simulation.phantom(matrix_size)
coil_images = np.tile(phan, (8, 1, 1)) * csm
show.imshow(abs(coil_images), tile_shape=(4, 2))

(csm_est, rho) = coils.calculate_csm_walsh(coil_images)
combined_image = np.sum(csm_est * coil_images, axis=0)

show.imshow(abs(csm_est), tile_shape=(4, 2), scale=(0, 1))
show.imshow(abs(combined_image), scale=(0, 1))
예제 #4
0
        # DON'T DO THIS, STUPID!
        # # phase-cycle correction
        # Imag = np.abs(I[cc, ...])
        # Iphase = np.angle(I[cc, ...]) - np.tile(pcs/2, (N, N, 1)).T
        # I[cc, ...] = Imag*np.exp(1j*Iphase)

    I *= csm_mag
    # view(I.transpose((2, 3, 0, 1)))

    # Estimate the sensitivity maps from coil images
    recons = np.zeros((ncoils, N, N), dtype='complex')
    for cc in range(ncoils):
        recons[cc, ...] = gs_recon(I[cc, ...], pc_axis=0)
    thresh = threshold_li(np.abs(recons))
    mask = np.abs(recons) > thresh
    csm_est, _ = calculate_csm_walsh(recons)

    # This doesn't work as well, still alright, but we knew this about
    # inati
    # csm_est, _ = calculate_csm_inati_iter(recons)

    # # Do the other way: estimate coil sensitivities from phase-cycle
    # csms = np.zeros((npcs, ncoils, N, N))
    # for ii in range(npcs):
    #     csms[ii, ...], _ = calculate_csm_walsh(I[:, ii, ...])
    # csm_est = np.mean(csms, axis=0)

    # # Look at residual phase
    # view(np.rad2deg((np.angle(csm)*mask - (
    #     np.angle(csm_est) - np.pi/2)*mask)))
예제 #5
0
    def process(self, acq, data,*args):

        if self.buffer is None:
            # Matrix size
            eNx = self.enc.encodedSpace.matrixSize.x
            eNy = self.enc.encodedSpace.matrixSize.y
            eNz = self.enc.encodedSpace.matrixSize.z
            rNx = self.enc.reconSpace.matrixSize.x
            rNy = self.enc.reconSpace.matrixSize.y
            rNz = self.enc.reconSpace.matrixSize.z

            # Field of View
            eFOVx = self.enc.encodedSpace.fieldOfView_mm.x
            eFOVy = self.enc.encodedSpace.fieldOfView_mm.y
            eFOVz = self.enc.encodedSpace.fieldOfView_mm.z
            rFOVx = self.enc.reconSpace.fieldOfView_mm.x
            rFOVy = self.enc.reconSpace.fieldOfView_mm.y
            rFOVz = self.enc.reconSpace.fieldOfView_mm.z
        
            channels = acq.active_channels

            if data.shape[1] != rNx:
                raise("Error, Recon gadget expects data to be on correct matrix size in RO direction")
                
            if (rNz != 1):
                rasie("Error Recon Gadget only supports 2D for now")
                
            self.buffer = np.zeros((channels, rNy, rNx),dtype=np.complex64)
            self.samp_mask = np.zeros(self.buffer.shape[1:])
            self.header_proto = ismrmrd.ImageHeader()
            self.header_proto.matrix_size[0] = rNx
            self.header_proto.matrix_size[1] = rNy
            self.header_proto.matrix_size[2] = rNz
            self.header_proto.field_of_view[0] = rFOVx
            self.header_proto.field_of_view[1] = rFOVy
            self.header_proto.field_of_view[0] = rFOVz
        
        #Now put data in buffer
        line_offset = self.buffer.shape[1]/2 - self.enc.encodingLimits.kspace_encoding_step_1.center                                                                                 
        self.buffer[:,acq.idx.kspace_encode_step_1+line_offset,:] = data                                                          
        self.samp_mask[acq.idx.kspace_encode_step_1+line_offset,:] = 1
        
        #If last scan in buffer, do FFT and fill image header
        if acq.isFlagSet(ismrmrd.ACQ_LAST_IN_ENCODE_STEP1) or acq.isFlagSet(ismrmrd.ACQ_LAST_IN_SLICE):
            img_head = copy.deepcopy(self.header_proto)
            img_head.position = acq.position                                                                                                                               
            img_head.read_dir = acq.read_dir                                                                                                                               
            img_head.phase_dir = acq.phase_dir                                                                                                                             
            img_head.slice_dir = acq.slice_dir                                                                                                                             
            img_head.patient_table_position = acq.patient_table_position                                                                                                   
            img_head.acquisition_time_stamp = acq.acquisition_time_stamp                                                                                                   
            img_head.slice = acq.idx.slice
            img_head.channels = 1
            
            scale = self.samp_mask.size/(1.0*np.sum(self.samp_mask[:]));

            #We have not yet calculated unmixing coefficients
            if self.unmix is None:
                self.calib_buffer.append((img_head,self.buffer.copy()))
                self.buffer[:] = 0
                self.samp_mask[:] = 0
                
                if len(self.calib_buffer) >= self.calib_frames:
                    cal_data = np.zeros(self.calib_buffer[0][1].shape, dtype=np.complex64)
                    for c in self.calib_buffer:
                        cal_data = cal_data + c[1]
                        
                    mask = np.squeeze(np.sum(np.abs(cal_data),0))
                    mask = np.ones(mask.shape)*(np.abs(mask)>0.0)
                    target = None #cal_data[0:8,:,:]
                    
                    coil_images = transform.transform_kspace_to_image(cal_data,dim=(1,2))
                    (csm,rho) = coils.calculate_csm_walsh(coil_images)
                    
                    if self.method == 'grappa':
                        self.unmix, self.gmap = grappa.calculate_grappa_unmixing(cal_data, 
                                                                                 self.acc_factor, 
                                                                                 data_mask=mask, 
                                                                                 kernel_size=(4,5), 
                                                                                 csm=csm)
                    elif self.method == 'sense':
                        self.unmix, self.gmap = sense.calculate_sense_unmixing(self.acc_factor, csm)
                    else:
                        raise Exception('Unknown parallel imaging method: ' + str(self.method))
                        
                    for c in self.calib_buffer:
                        recon = transform.transform_kspace_to_image(c[1],dim=(1,2))*np.sqrt(scale)
                        recon = np.squeeze(np.sum(recon * self.unmix,0))
                        self.put_next(c[0], recon,*args)
                        
                return 0
                
            if self.unmix is None:
                raise Exception("We should never reach this point without unmixing coefficients")
                
            recon = transform.transform_kspace_to_image(self.buffer,dim=(1,2))*np.sqrt(scale)
            recon = np.squeeze(np.sum(recon * self.unmix,0))
            self.buffer[:] = 0
            self.samp_mask[:] = 0
            self.put_next(img_head,recon,*args)
        return 0
예제 #6
0
    def process(self, acq, data, *args):

        if self.buffer is None:
            # Matrix size
            eNx = self.enc.encodedSpace.matrixSize.x
            eNy = self.enc.encodedSpace.matrixSize.y
            eNz = self.enc.encodedSpace.matrixSize.z
            rNx = self.enc.reconSpace.matrixSize.x
            rNy = self.enc.reconSpace.matrixSize.y
            rNz = self.enc.reconSpace.matrixSize.z

            # Field of View
            eFOVx = self.enc.encodedSpace.fieldOfView_mm.x
            eFOVy = self.enc.encodedSpace.fieldOfView_mm.y
            eFOVz = self.enc.encodedSpace.fieldOfView_mm.z
            rFOVx = self.enc.reconSpace.fieldOfView_mm.x
            rFOVy = self.enc.reconSpace.fieldOfView_mm.y
            rFOVz = self.enc.reconSpace.fieldOfView_mm.z

            channels = acq.active_channels

            if data.shape[1] != rNx:
                raise (
                    "Error, Recon gadget expects data to be on correct matrix size in RO direction"
                )

            if (rNz != 1):
                rasie("Error Recon Gadget only supports 2D for now")

            self.buffer = np.zeros((channels, rNy, rNx), dtype=np.complex64)
            self.samp_mask = np.zeros(self.buffer.shape[1:])
            self.header_proto = ismrmrd.ImageHeader()
            self.header_proto.matrix_size[0] = rNx
            self.header_proto.matrix_size[1] = rNy
            self.header_proto.matrix_size[2] = rNz
            self.header_proto.field_of_view[0] = rFOVx
            self.header_proto.field_of_view[1] = rFOVy
            self.header_proto.field_of_view[0] = rFOVz

        #Now put data in buffer
        line_offset = self.buffer.shape[
            1] / 2 - self.enc.encodingLimits.kspace_encoding_step_1.center
        self.buffer[:, acq.idx.kspace_encode_step_1 + line_offset, :] = data
        self.samp_mask[acq.idx.kspace_encode_step_1 + line_offset, :] = 1

        #If last scan in buffer, do FFT and fill image header
        if acq.isFlagSet(ismrmrd.ACQ_LAST_IN_ENCODE_STEP1) or acq.isFlagSet(
                ismrmrd.ACQ_LAST_IN_SLICE):
            img_head = copy.deepcopy(self.header_proto)
            img_head.position = acq.position
            img_head.read_dir = acq.read_dir
            img_head.phase_dir = acq.phase_dir
            img_head.slice_dir = acq.slice_dir
            img_head.patient_table_position = acq.patient_table_position
            img_head.acquisition_time_stamp = acq.acquisition_time_stamp
            img_head.slice = acq.idx.slice
            img_head.channels = 1

            scale = self.samp_mask.size / (1.0 * np.sum(self.samp_mask[:]))

            #We have not yet calculated unmixing coefficients
            if self.unmix is None:
                self.calib_buffer.append((img_head, self.buffer.copy()))
                self.buffer[:] = 0
                self.samp_mask[:] = 0

                if len(self.calib_buffer) >= self.calib_frames:
                    cal_data = np.zeros(self.calib_buffer[0][1].shape,
                                        dtype=np.complex64)
                    for c in self.calib_buffer:
                        cal_data = cal_data + c[1]

                    mask = np.squeeze(np.sum(np.abs(cal_data), 0))
                    mask = np.ones(mask.shape) * (np.abs(mask) > 0.0)
                    target = None  #cal_data[0:8,:,:]

                    coil_images = transform.transform_kspace_to_image(cal_data,
                                                                      dim=(1,
                                                                           2))
                    (csm, rho) = coils.calculate_csm_walsh(coil_images)

                    if self.method == 'grappa':
                        self.unmix, self.gmap = grappa.calculate_grappa_unmixing(
                            cal_data,
                            self.acc_factor,
                            data_mask=mask,
                            kernel_size=(4, 5),
                            csm=csm)
                    elif self.method == 'sense':
                        self.unmix, self.gmap = sense.calculate_sense_unmixing(
                            self.acc_factor, csm)
                    else:
                        raise Exception('Unknown parallel imaging method: ' +
                                        str(self.method))

                    for c in self.calib_buffer:
                        recon = transform.transform_kspace_to_image(
                            c[1], dim=(1, 2)) * np.sqrt(scale)
                        recon = np.squeeze(np.sum(recon * self.unmix, 0))
                        self.put_next(c[0], recon, *args)

                return 0

            if self.unmix is None:
                raise Exception(
                    "We should never reach this point without unmixing coefficients"
                )

            recon = transform.transform_kspace_to_image(
                self.buffer, dim=(1, 2)) * np.sqrt(scale)
            recon = np.squeeze(np.sum(recon * self.unmix, 0))
            self.buffer[:] = 0
            self.samp_mask[:] = 0
            self.put_next(img_head, recon, *args)
        return 0
예제 #7
0
from mr_utils import view
from ismrmrdtools.coils import calculate_csm_inati_iter, calculate_csm_walsh

if __name__ == '__main__':

    im0 = np.load('data/20190401_GASP_PHANTOM/set2_gre_tr34_te2_87.npy')
    im0 = np.mean(im0, axis=2)
    im0 = np.moveaxis(im0, -1, 0)

    im1 = np.load('data/20190401_GASP_PHANTOM/set2_gre_tr4_te5_74.npy')
    im1 = np.mean(im1, axis=2)
    im1 = np.moveaxis(im1, -1, 0)

    # Make a field map coil by coil
    fm0 = dual_echo_gre(im0, im1, 2.87e-3, 5.74e-3)
    np.save('data/20190401_GASP_PHANTOM/coil_fm_gre.npy', fm0)
    view(fm0)
    fm0 = np.mean(fm0, axis=0)

    # Coil combine im0 and im1 then get field map
    _, im0cc0 = calculate_csm_inati_iter(im0)
    _, im1cc0 = calculate_csm_inati_iter(im1)
    csm, _ = calculate_csm_walsh(im0)
    im0cc1 = np.sum(np.conj(im0) * csm, axis=0)
    csm, _ = calculate_csm_walsh(im1)
    im1cc1 = np.sum(np.conj(im1) * csm, axis=0)
    fm1 = dual_echo_gre(im0cc0, im1cc0, 2.87e-3, 5.74e-3)
    fm2 = dual_echo_gre(im0cc1, im1cc1, 2.87e-3, 5.74e-3)

    # Compare
    view(np.stack((fm0, fm1, fm2)))
예제 #8
0
def comparison_numerical_phantom(SNR=None):
    '''Compare coil by coil, Walsh method, and Inati iterative method.'''

    true_im = get_true_im_numerical_phantom()
    csms = get_coil_sensitivity_maps()
    params = get_numerical_phantom_params(SNR=SNR)
    pc_vals = params['pc_vals']
    dim = params['dim']
    noise_std = params['noise_std']
    coil_nums = params['coil_nums']

    # We want to solve gs_recon for each coil we have in the pc set
    err = np.zeros((5, len(csms)))
    rip = err.copy()
    for ii, csm in enumerate(csms):

        # I have coil sensitivities, now I need images to apply them to.
        # coil_ims: (pc,coil,x,y)
        coil_ims = np.zeros((len(pc_vals), csm.shape[0], dim, dim),
                            dtype='complex')
        for jj, pc in enumerate(pc_vals):
            im = bssfp_2d_cylinder(dims=(dim, dim), phase_cyc=pc)
            im += 1j * im
            coil_ims[jj, ...] = im * csm
            coil_ims[jj, ...] += np.random.normal(0, noise_std, coil_ims[
                jj, ...].shape) / 2 + 1j * np.random.normal(
                    0, noise_std, coil_ims[jj, ...].shape) / 2

        # Solve the gs_recon coil by coil
        coil_ims_gs = np.zeros((csm.shape[0], dim, dim), dtype='complex')
        for kk in range(csm.shape[0]):
            coil_ims_gs[kk, ...] = gs_recon(*[
                x.squeeze()
                for x in np.split(coil_ims[:, kk, ...], len(pc_vals))
            ])
        coil_ims_gs[np.isnan(coil_ims_gs)] = 0

        # Easy way out: combine all the coils using sos
        im_est_sos = sos(coil_ims_gs)
        # view(im_est_sos)

        # Take coil by coil solution and do Walsh on it to collapse coil dim
        # walsh
        csm_walsh, _ = calculate_csm_walsh(coil_ims_gs)
        im_est_recon_then_walsh = np.sum(csm_walsh * np.conj(coil_ims_gs),
                                         axis=0)
        im_est_recon_then_walsh[np.isnan(im_est_recon_then_walsh)] = 0
        # view(im_est_recon_then_walsh)

        # inati
        csm_inati, im_est_recon_then_inati = calculate_csm_inati_iter(
            coil_ims_gs)

        # Collapse the coil dimension of each phase-cycle using Walsh,Inati
        pc_est_walsh = np.zeros((len(pc_vals), dim, dim), dtype='complex')
        pc_est_inati = np.zeros((len(pc_vals), dim, dim), dtype='complex')
        for jj in range(len(pc_vals)):
            ## Walsh
            csm_walsh, _ = calculate_csm_walsh(coil_ims[jj, ...])
            pc_est_walsh[jj,
                         ...] = np.sum(csm_walsh * np.conj(coil_ims[jj, ...]),
                                       axis=0)
            # view(csm_walsh)
            # view(pc_est_walsh)

            ## Inati
            csm_inati, pc_est_inati[jj, ...] = calculate_csm_inati_iter(
                coil_ims[jj, ...], smoothing=1)
            # pc_est_inati[jj,...] = np.sum(csm_inati*np.conj(coil_ims[jj,...]),axis=0)
            # view(csm_inati)

        # Now solve the gs_recon using collapsed coils
        im_est_walsh = gs_recon(
            *[x.squeeze() for x in np.split(pc_est_walsh, len(pc_vals))])
        im_est_inati = gs_recon(
            *[x.squeeze() for x in np.split(pc_est_inati, len(pc_vals))])

        # view(im_est_walsh)
        # view(im_est_recon_then_walsh)

        # Compute error metrics
        err[0, ii] = compare_nrmse(im_est_sos, true_im)
        err[1, ii] = compare_nrmse(im_est_recon_then_walsh, true_im)
        err[2, ii] = compare_nrmse(im_est_recon_then_inati, true_im)
        err[3, ii] = compare_nrmse(im_est_walsh, true_im)
        err[4, ii] = compare_nrmse(im_est_inati, true_im)

        im_est_sos[np.isnan(im_est_sos)] = 0
        im_est_recon_then_walsh[np.isnan(im_est_recon_then_walsh)] = 0
        im_est_recon_then_inati[np.isnan(im_est_recon_then_inati)] = 0
        im_est_walsh[np.isnan(im_est_walsh)] = 0
        im_est_inati[np.isnan(im_est_inati)] = 0

        rip[0, ii] = ripple_normal(im_est_sos)
        rip[1, ii] = ripple_normal(im_est_recon_then_walsh)
        rip[2, ii] = ripple_normal(im_est_recon_then_inati)
        rip[3, ii] = ripple_normal(im_est_walsh)
        rip[4, ii] = ripple_normal(im_est_inati)

        # view(im_est_inati)

        # # SOS of the gs solution on each individual coil gives us low periodic
        # # ripple accross the phantom, similar to Walsh method:
        # plt.plot(np.abs(true_im[int(dim/2),:]),'--',label='True Im')
        # plt.plot(np.abs(im_est_sos[int(dim/2),:]),'-.',label='SOS')
        # plt.plot(np.abs(im_est_recon_then_walsh[int(dim/2),:]),label='Recon then Walsh')
        # plt.plot(np.abs(im_est_walsh[int(dim/2),:]),label='Walsh then Recon')
        # # plt.plot(np.abs(im_est_inati[int(dim/2),:]),label='Inati')
        # plt.legend()
        # plt.show()

    # # Let's show some stuff
    # plt.plot(coil_nums,err[0,:],'*-',label='SOS')
    # plt.plot(coil_nums,err[1,:],label='Recon then Walsh')
    # plt.plot(coil_nums,err[2,:],label='Walsh then Recon')
    # # plt.plot(coil_nums,err[3,:],label='Inati')
    # plt.legend()
    # plt.show()

    print('SOS RMSE:', np.mean(err[0, :]))
    print('recon then walsh RMSE:', np.mean(err[1, :]))
    print('recon then inati RMSE:', np.mean(err[2, :]))
    print('walsh then recon RMSE:', np.mean(err[3, :]))
    print('inati then recon RMSE:', np.mean(err[4, :]))

    print('SOS ripple:', np.mean(err[0, :]))
    print('recon then walsh ripple:', np.mean(rip[1, :]))
    print('recon then inati ripple:', np.mean(rip[2, :]))
    print('walsh then recon ripple:', np.mean(rip[3, :]))
    print('inati then recon ripple:', np.mean(rip[4, :]))

    view(im_est_recon_then_walsh[int(dim / 2), :])
    view(im_est_recon_then_inati[int(dim / 2), :])
    view(im_est_walsh[int(dim / 2), :])
    view(im_est_inati[int(dim / 2), :])
    # view(im_est_inati)

    # view(np.stack((im_est_recon_then_walsh,im_est_recon_then_inati,im_est_walsh,im_est_inati)))

    return (err)
예제 #9
0
def comparison_knee():
    '''Coil by coil, Walsh method, and Inati iterative method for knee data.'''

    # Load the knee data
    dir = '/home/nicholas/Documents/rawdata/SSFP_SPECTRA_dphiOffset_08022018/'
    files = [
        'meas_MID362_TRUFI_STW_TE3_FID29379',
        'meas_MID363_TRUFI_STW_TE3_dphi_45_FID29380',
        'meas_MID364_TRUFI_STW_TE3_dphi_90_FID29381',
        'meas_MID365_TRUFI_STW_TE3_dphi_135_FID29382',
        'meas_MID366_TRUFI_STW_TE3_dphi_180_FID29383',
        'meas_MID367_TRUFI_STW_TE3_dphi_225_FID29384',
        'meas_MID368_TRUFI_STW_TE3_dphi_270_FID29385',
        'meas_MID369_TRUFI_STW_TE3_dphi_315_FID29386'
    ]
    pc_vals = [0, 45, 90, 135, 180, 225, 270, 315]
    dims = (512, 256)
    num_coils = 4
    num_avgs = 16

    # # Load in raw once, then save as npy with collapsed avg dimension
    # pcs = np.zeros((len(files),dims[0],dims[1],num_coils),dtype='complex')
    # for ii,file in enumerate(files):
    #     pcs[ii,...] = np.mean(load_raw('%s/%s.dat' % (dir,file),use='s2i'),axis=-1)
    # np.save('%s/te3.npy' % dir,pcs)

    # pcs looks like (pc,x,y,coil)
    pcs = np.load('%s/te3.npy' % dir)
    pcs = np.fft.fftshift(np.fft.fft2(pcs, axes=(1, 2)), axes=(1, 2))
    # print(pcs.shape)
    # view(pcs,fft=True,montage_axis=0,movie_axis=3)

    # Do recon then coil combine
    coils0 = np.zeros((pcs.shape[-1], pcs.shape[1], pcs.shape[2]),
                      dtype='complex')
    coils1 = coils0.copy()
    for ii in range(pcs.shape[-1]):
        # We have two sets: 0,90,180,27 and 45,135,225,315
        idx0 = [0, 2, 4, 6]
        idx1 = [1, 3, 5, 7]
        coils0[ii, ...] = gs_recon(*[x.squeeze() for x in pcs[idx0, :, :, ii]])
        coils1[ii, ...] = gs_recon(*[x.squeeze() for x in pcs[idx1, :, :, ii]])
    # Then do the coil combine
    csm_walsh, _ = calculate_csm_walsh(coils0)
    im_est_recon_then_walsh0 = np.sum(csm_walsh * np.conj(coils0), axis=0)
    # view(im_est_recon_then_walsh0)

    csm_walsh, _ = calculate_csm_walsh(coils1)
    im_est_recon_then_walsh1 = np.sum(csm_walsh * np.conj(coils1), axis=0)
    # view(im_est_recon_then_walsh1)

    rip0 = ripple(im_est_recon_then_walsh0)
    rip1 = ripple(im_est_recon_then_walsh1)
    print('recon then walsh: ', np.mean([rip0, rip1]))

    # Now try inati
    csm_inati, im_est_recon_then_inati0 = calculate_csm_inati_iter(coils0,
                                                                   smoothing=5)
    csm_inati, im_est_recon_then_inati1 = calculate_csm_inati_iter(coils1,
                                                                   smoothing=5)
    rip0 = ripple(im_est_recon_then_inati0)
    rip1 = ripple(im_est_recon_then_inati1)
    print('recon then inati: ', np.mean([rip0, rip1]))

    # Now try sos
    im_est_recon_then_sos0 = sos(coils0, axes=0)
    im_est_recon_then_sos1 = sos(coils1, axes=0)
    rip0 = ripple(im_est_recon_then_sos0)
    rip1 = ripple(im_est_recon_then_sos1)
    print('recon then sos: ', np.mean([rip0, rip1]))
    # view(im_est_recon_then_sos)

    ## Now the other way, combine then recon
    pcs0 = np.zeros((2, pcs.shape[0], pcs.shape[1], pcs.shape[2]),
                    dtype='complex')
    pcs1 = pcs0.copy()
    for ii in range(pcs.shape[0]):
        # Walsh it up
        csm_walsh, _ = calculate_csm_walsh(pcs[ii, ...].transpose((2, 0, 1)))
        pcs0[0, ii, ...] = np.sum(csm_walsh * np.conj(pcs[ii, ...].transpose(
            (2, 0, 1))),
                                  axis=0)
        # view(pcs0[ii,...])

        # Inati it up
        csm_inati, pcs0[1, ii,
                        ...] = calculate_csm_inati_iter(pcs[ii, ...].transpose(
                            (2, 0, 1)),
                                                        smoothing=5)

    ## Now perform gs_recon on each coil combined set
    # Walsh
    im_est_walsh_then_recon0 = gs_recon(
        *[x.squeeze() for x in pcs0[0, idx0, ...]])
    im_est_walsh_then_recon1 = gs_recon(
        *[x.squeeze() for x in pcs0[0, idx1, ...]])
    # Inati
    im_est_inati_then_recon0 = gs_recon(
        *[x.squeeze() for x in pcs0[1, idx0, ...]])
    im_est_inati_then_recon1 = gs_recon(
        *[x.squeeze() for x in pcs0[1, idx1, ...]])

    # view(im_est_walsh_then_recon0)
    # view(im_est_walsh_then_recon1)
    view(im_est_inati_then_recon0)
    view(im_est_inati_then_recon1)

    rip0 = ripple(im_est_walsh_then_recon0)
    rip1 = ripple(im_est_walsh_then_recon1)
    print('walsh then recon: ', np.mean([rip0, rip1]))

    rip0 = ripple(im_est_inati_then_recon0)
    rip1 = ripple(im_est_inati_then_recon1)
    print('inati then recon: ', np.mean([rip0, rip1]))
예제 #10
0
def calculate_grappa_unmixing(source_data,
                              acc_factor,
                              kernel_size=(4, 5),
                              data_mask=None,
                              csm=None,
                              regularization_factor=0.001,
                              target_data=None):
    '''Calculates unmixing coefficients for a 2D image using a GRAPPA algorithm

    :param source_data: k-space source data ``[coils, y, x]``
    :param acc_factor: Acceleration factor, e.g. 2
    :param kernel_shape: Shape of the k-space kernel ``(ky-lines, kx-points)`` (default ``(4,5)``)
    :param data_mask: Mask of where calibration data is located in source_data (defaults to all of source_data)
    :param csm: Coil sensitivity map, ``[coil, y, x]`` (used for b1-weighted combining. Will be estimated from calibratino data if not supplied)
    :param regularization_factor: adds tychonov regularization (default ``0.001``)
        - 0 = no regularization
        - set higher for more aggressive regularization.
    :param target_data: If target data differs from source data (defaults to source_data)
    
    :returns unmix: Image unmixing coefficients for a single ``x`` location, ``[coil, y, x]``
    :returns gmap: Noise enhancement map, ``[y, x]``
    '''

    nx = source_data.shape[2]
    ny = source_data.shape[1]
    nc_source = source_data.shape[0]

    if target_data is None:
        target_data = source_data

    if data_mask is None:
        data_mask = np.ones((ny, nx))

    nc_target = target_data.shape[0]

    if csm is None:
        #Assume calibration data is in the middle
        f = np.asarray(
            np.asmatrix(np.hamming(np.max(np.sum(data_mask, 0)))).T *
            np.asmatrix(np.hamming(np.max(np.sum(data_mask, 1)))))
        fmask = np.zeros((source_data.shape[1], source_data.shape[2]),
                         dtype=np.complex64)
        idx = np.argwhere(data_mask == 1)
        fmask[idx[:, 0], idx[:, 1]] = f.reshape(idx.shape[0])
        fmask = np.tile(fmask[None, :, :], (nc_source, 1, 1))
        csm = fftshift(ifftn(ifftshift(source_data * fmask, axes=(1, 2)),
                             axes=(1, 2)),
                       axes=(1, 2))
        (csm, rho) = coils.calculate_csm_walsh(csm)

    kernel = np.zeros(
        (nc_target, nc_source, kernel_size[0] * acc_factor, kernel_size[1]),
        dtype=np.complex64)
    sampled_indices = np.nonzero(data_mask)
    kx_cal = (sampled_indices[1][0], sampled_indices[1][-1])
    ky_cal = (sampled_indices[0][0], sampled_indices[0][-1])

    for s in range(0, acc_factor):
        kernel_mask = np.zeros((kernel_size[0] * acc_factor, kernel_size[1]),
                               dtype=np.int8)
        kernel_mask[s:kernel_mask.shape[0]:acc_factor, :] = 1
        s_data = source_data[:, ky_cal[0]:ky_cal[1], kx_cal[0]:kx_cal[1]]
        t_data = target_data[:, ky_cal[0]:ky_cal[1], kx_cal[0]:kx_cal[1]]
        k = estimate_convolution_kernel(
            s_data,
            kernel_mask,
            regularization_factor=regularization_factor,
            target_data=t_data)
        kernel = kernel + k

    #return kernel

    kernel = kernel[:, :, ::-1, ::
                    -1]  #flip kernel in preparation for convolution

    csm_ss = np.sum(csm * np.conj(csm), 0)
    csm_ss = csm_ss + 1.0 * (csm_ss < np.spacing(1)).astype('float32')

    unmix = np.zeros(source_data.shape, dtype=np.complex64)

    for c in range(0, nc_target):
        kernel_pad = _pad_kernel(kernel[c, :, :, :], unmix.shape)
        kernel_pad = fftshift(ifftn(ifftshift(kernel_pad, axes=(1, 2)),
                                    axes=(1, 2)),
                              axes=(1, 2))
        kernel_pad *= unmix.shape[1] * unmix.shape[2]
        unmix = unmix + (kernel_pad * np.tile(
            np.conj(csm[c, :, :]) / csm_ss, (nc_source, 1, 1)))

    unmix /= acc_factor
    gmap = np.squeeze(np.sqrt(np.sum(abs(unmix)**2, 0))) * np.squeeze(
        np.sqrt(np.sum(abs(csm)**2, 0)))

    return (unmix.astype('complex64'), gmap.astype('float32'))
# -*- coding: utf-8 -*-

#%%
#Basic setup
import time
import numpy as np
from ismrmrdtools import simulation, coils, show

matrix_size = 256
csm = simulation.generate_birdcage_sensitivities(matrix_size)
phan = simulation.phantom(matrix_size)
coil_images = phan[np.newaxis, :, :] * csm
show.imshow(abs(coil_images), tile_shape=(4, 2))

tstart = time.time()
(csm_est, rho) = coils.calculate_csm_walsh(coil_images)
print("Walsh coil estimation duration: {}s".format(time.time() - tstart))
combined_image = np.sum(csm_est * coil_images, axis=0)

show.imshow(abs(csm_est), tile_shape=(4, 2), scale=(0, 1))
show.imshow(abs(combined_image), scale=(0, 1))

tstart = time.time()
(csm_est2, rho2) = coils.calculate_csm_inati_iter(coil_images)
print("Inati coil estimation duration: {}s".format(time.time() - tstart))
combined_image2 = np.sum(csm_est2 * coil_images, axis=0)

show.imshow(abs(csm_est2), tile_shape=(4, 2), scale=(0, 1))
show.imshow(abs(combined_image2), scale=(0, 1))