def setUp(self): """ Get the data from the server. """ self.images = [get_sample_data(dataset_name="mri-slice-nifti")] print("[info] Image loaded for test: {0}.".format( [im.data.shape for im in self.images])) self.mask = get_sample_data("mri-mask").data self.names = ["BsplineWaveletTransformATrousAlgorithm"] print("[info] Found {0} transformations.".format(len(self.names))) self.nb_scales = [4] self.nb_iter = 10
def setUp(self): """ Setup common variables to be used in tests: num_iter : Number of iterations images : Ground truth images to test with, obtained from server mask : MRI fourier space mask decimated_wavelets : Decimated wavelets to test with undecimated_wavelets : Undecimated wavelets to test with optimizers : Different optimizers to test with nb_scales : Number of scales test_cases : holds the final test cases """ self.num_iter = 40 # TODO getting images from net slows down these tests, # we would prefer to rather use random complex data. self.images = [get_sample_data(dataset_name="mri-slice-nifti")] print("[info] Image loaded for test: {0}.".format( [im.data.shape for im in self.images])) self.mask = get_sample_data("mri-mask").data # From WaveletN self.decimated_wavelets = ['sym8'] # From WaveletUD2, tested only for analysis formulation self.undecimated_wavelets = [24] self.recon_type = ['cartesian', 'non-cartesian'] self.optimizers = ['fista', 'condatvu', 'pogm'] self.nb_scales = [4] self.test_cases = list( product( self.images, self.nb_scales, self.optimizers, self.recon_type, self.decimated_wavelets, )) self.test_cases += list( product( self.images, self.nb_scales, ['condatvu'], self.recon_type, self.undecimated_wavelets, ))
def setUp(self): """ Get the data from the server. """ self.mr_image = get_sample_data(dataset_name="multiresolution") self.images = [ get_sample_data(dataset_name="mri-slice-nifti"), get_sample_data(dataset_name="astro-ngc2997") ] self.deconv_images = [ get_sample_data(dataset_name="astro-galaxy"), get_sample_data(dataset_name="astro-psf") ] print("[info] Image loaded for test: {0}.".format( [i.data.shape for i in self.images])) transforms_struct = pysap.wavelist(["isap-2d", "isap-3d"]) transforms_names = (transforms_struct["isap-2d"] + transforms_struct["isap-3d"]) self.transforms = [ pysap.load_transform(name) for name in transforms_names ] print("[info] Found {0} transformations.".format(len(self.transforms))) self.nb_scales = [3] # [2, 3, 4] self.nb_iter = 10
def setUp(self): """ Get the data from the server. """ self.images = [ # get_sample_data(dataset_name="astro-fits"), get_sample_data(dataset_name="mri-slice-nifti") ] print("[info] Image loaded for test: {0}.".format( [i.data.shape for i in self.images])) self.transforms = [ pysap.load_transform(name) for name in pysap.AVAILABLE_TRANSFORMS ] print("[info] Found {0} transformations.".format(len(self.transforms))) self.nb_scales = [3] # [2, 3, 4] self.nb_iter = 10
# Package import from modopt.math.metrics import ssim from mri.operators import FFT, WaveletN from mri.operators.utils import convert_mask_to_locations from mri.reconstructors import SingleChannelReconstructor from pysap.data import get_sample_data import pysap # Third party import from modopt.opt.linear import Identity from modopt.opt.proximity import SparseThreshold import numpy as np # Loading input data and convert it into a single channel using Sum-Of-Squares image = get_sample_data('3d-pmri') image.data = np.sqrt(np.sum(np.abs(image.data)**2, axis=0)) # Obtain K-Space Cartesian Mask mask = get_sample_data("2d-poisson-disk-mask") mask.data = np.repeat(np.expand_dims(mask.data, axis=-1), image.shape[-1], axis=-1) # View Input # image.show() # mask.show() ############################################################################# # Generate the kspace # -------------------
print(pysap.configure.info()) ############################################################################# # Import astronomical data # ------------------------ # # The package provides a common interface to import and visualize astronomical # FITS dataset. It also embeds a set of toy dataset that will be used during # this tutorial: import pysap from pprint import pprint from pysap.data import get_sample_data image = get_sample_data("astro-fits") print(image.shape, image.spacing, image.data_type) pprint(image.metadata) print(image.data.dtype) image.show() ############################################################################# # Import neuroimaging data # ------------------------ # # The package provides a common interface to import and visualize neuroimaging # NIFTI dataset. It also embeds a set of toy dataset that will be used during # this tutorial: import pysap from pprint import pprint
# Package import from mri.operators import FFT, WaveletN from mri.operators.utils import convert_mask_to_locations from mri.reconstructors import SelfCalibrationReconstructor import pysap from pysap.data import get_sample_data # Third party import from modopt.math.metrics import ssim from modopt.opt.linear import Identity from modopt.opt.proximity import SparseThreshold import numpy as np # Loading input data cartesian_ref_image = get_sample_data('2d-pmri') image = pysap.Image(data=np.sqrt(np.sum(cartesian_ref_image.data**2, axis=0))) # Obtain MRI cartesian mask mask = get_sample_data("cartesian-mri-mask") kspace_loc = convert_mask_to_locations(mask.data) # View Input # image.show() # mask.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquisition mask, we retrospectively # undersample the k-space using a cartesian acquisition mask
# Package import import pysap from pysap.data import get_sample_data from mri.numerics.fourier import NFFT from mri.numerics.reconstruct import sparse_rec_fista from mri.numerics.reconstruct import sparse_rec_condatvu from mri.numerics.utils import generate_operators from mri.numerics.utils import convert_mask_to_locations # Third party import import numpy as np import scipy.fftpack as pfft # Loading input data image = get_sample_data("mri-slice-nifti") image.data += np.random.randn(*image.shape) * 20. mask = get_sample_data("mri-mask") image.show() mask.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquistion mask, we generate the acquisition # measurments, the observed kspace. # We then reconstruct the zero order solution. # Get the locations of the kspace samples and the associated observations kspace_loc = convert_mask_to_locations(mask.data)
from mri.operators import Stacked3DNFFT, WaveletN from mri.operators.utils import convert_locations_to_mask, \ gridded_inverse_fourier_transform_stack, get_stacks_fourier, \ convert_mask_to_locations from mri.reconstructors import SingleChannelReconstructor import pysap from pysap.data import get_sample_data # Third party import from modopt.math.metrics import ssim from modopt.opt.linear import Identity from modopt.opt.proximity import SparseThreshold import numpy as np # Loading input data image = get_sample_data('3d-pmri') image = pysap.Image(data=np.sqrt(np.sum(np.abs(image.data)**2, axis=0))) # Reducing the size of the volume for faster computation image.data = image.data[:, :, 48:-48] # Obtain MRI non-cartesian sampling plane mask_radial = get_sample_data("mri-radial-samples") # Tiling the plane on the z-direction # sampling_z = np.ones(image.shape[2]) # no sampling sampling_z = np.random.randint(2, size=image.shape[2]) # random sampling sampling_z[22:42] = 1 Nz = sampling_z.sum() # Number of acquired plane z_locations = np.repeat(convert_mask_to_locations(sampling_z),
def test_gridsearch_single_channel(self): """Test Gridsearch script in mri.scripts for single channel reconstruction this is a test of sanity and not if the reconstruction is right. """ image = get_sample_data('2d-mri') mask = np.ones(image.shape) kspace_loc = convert_mask_to_locations(mask) fourier_op = NonCartesianFFT(samples=kspace_loc, shape=image.shape) kspace_data = fourier_op.op(image.data) # Define the keyword dictionaries based on convention metrics = { 'ssim': { 'metric': ssim, 'mapping': { 'x_new': 'test', 'y_new': None }, 'cst_kwargs': { 'ref': image, 'mask': None }, 'early_stopping': True, }, } linear_params = { 'init_class': WaveletN, 'kwargs': { 'wavelet_name': 'sym8', 'nb_scale': 4, } } regularizer_params = { 'init_class': SparseThreshold, 'kwargs': { 'linear': Identity(), 'weights': [0, 1e-5], } } optimizer_params = { # Just following convention 'kwargs': { 'optimization_alg': 'fista', 'num_iterations': 10, 'metrics': metrics, } } # Call the launch grid function and obtain results raw_results, test_cases, key_names, best_idx = launch_grid( kspace_data=kspace_data, fourier_op=fourier_op, linear_params=linear_params, regularizer_params=regularizer_params, optimizer_params=optimizer_params, reconstructor_kwargs={'gradient_formulation': 'synthesis'}, reconstructor_class=SingleChannelReconstructor, compare_metric_details={'metric': 'ssim'}, n_jobs=self.n_jobs, verbose=1, ) # In this test we dont undersample the kspace so the # reconstruction is indeed with mu=0, ie best_idx=0 np.testing.assert_equal(best_idx, 0) np.testing.assert_allclose( raw_results[best_idx][0], image, atol=1e-7, )
# Third party import import numpy as np import scipy.fftpack as pfft import matplotlib.pyplot as plt ############################################################################# # Load the database to train the dictionary # ----------------------------------------- # # The database should be a list of list of 2D MRI images grouped by subjects. # In this tutorial, the database contains only brain images. # Besides, all images have same size and all subjects have the same # number of slices. dataset = get_sample_data("dict-learn-dataset") training_set = dataset.data print("[info]: # subjects: {0}, # images per subject: {1}," " image shape: ({2},{3})".format(len(training_set), len(training_set[0]), len(training_set[0][0]), len(training_set[0][0][0]))) ############################################################################# # Learning the dictionary # ----------------------- # # The dictionary parameters are first set: the number of components/atoms, # the regularization term (of the Lasso) and the patch size. # Some other parameters like the number of iterations, the batch size and # the number of cpu running can be tuned to faster the procedure.
# from pysap.plugins.mri.parallel_mri.gradient import Grad2D_pMRI_synthesis from pysap.plugins.mri.parallel_mri.extract_sensitivity_maps import get_Smaps # Third party import import numpy as np import scipy.fftpack as pfft from scipy.io import loadmat import matplotlib.pyplot as plt # Loading input data image_name = '/home/loubnaelgueddari/Data'\ '/meas_MID41_CSGRE_ref_OS1_FID14687.mat' k_space_ref = loadmat(image_name)['ref'] k_space_ref /= np.linalg.norm(k_space_ref) Smaps, SOS = get_Smaps(k_space_ref, (512, 512), mode='FFT') mask = get_sample_data("mri-mask") # mask.show() image = pysap.Image(data=np.abs(SOS), metadata=mask.metadata) image.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquistion mask, we generate the acquisition # measurments, the observed kspace. # We then reconstruct the zero order solution. # Generate the subsampled kspace Sl = prod_over_maps(Smaps, SOS) kspace_data = function_over_maps(pfft.fft2, Sl)
------------------- Import functions from PySAP and ModOpt. """ import numpy as np from pysap import Image from pysap.data import get_sample_data from pysap.plugins.astro.denoising.denoise import denoise from modopt.signal.noise import add_noise ############################################################################# # Load the image of galaxy NGC2997 galaxy = get_sample_data('astro-ngc2997') ############################################################################# # Show the clean galaxy image # galaxy.show() ############################################################################# # Generate noisy observation # -------------------------- # # Convolve the image with a point spread function (PSF) using the `convolve` # function. Then add random Gaussian noise with standard deviation 0.0005 # using the `add_noise` function. obs_data = add_noise(galaxy.data, sigma=100)
from pysap.data import get_sample_data from pysap.numerics.linear import Wavelet2 from pysap.numerics.fourier import NFFT2 from pysap.numerics.reconstruct import sparse_rec_fista from pysap.numerics.reconstruct import sparse_rec_condatvu from pysap.numerics.gradient import Gradient_pMRI from pysap.numerics.proximity import Threshold from pysap.plugins.mri.parallel_mri.extract_sensitivity_maps import ( extract_k_space_center_and_locations, get_Smaps) from pysap.plugins.mri.reconstruct.utils import normalize_frequency_locations # Third party import import numpy as np # Loading input data Il = get_sample_data("2d-pmri").data.astype("complex128") SOS = np.squeeze(np.sqrt(np.sum(np.abs(Il)**2, axis=0))) Smaps = np.asarray([Il[channel] / SOS for channel in range(Il.shape[0])]) kspace_loc = normalize_frequency_locations( get_sample_data("mri-radial-samples").data) image = pysap.Image(data=np.abs(SOS)) image.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquistion mask, we generate the acquisition # measurments, the observed kspace. # We then reconstruct the zero order solution.
from mri.operators import NonCartesianFFT, WaveletUD2 from mri.operators.utils import convert_locations_to_mask, \ gridded_inverse_fourier_transform_nd from mri.operators.fourier.utils import estimate_density_compensation from mri.reconstructors import SingleChannelReconstructor import pysap from pysap.data import get_sample_data # Third party import from modopt.math.metrics import ssim from modopt.opt.linear import Identity from modopt.opt.proximity import SparseThreshold import numpy as np # Loading input data image = get_sample_data('2d-mri') # Obtain MRI non-cartesian mask and estimate the density compensation radial_mask = get_sample_data("mri-radial-samples") kspace_loc = radial_mask.data density_comp = estimate_density_compensation(kspace_loc, image.shape) ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquisition mask, we retrospectively # undersample the k-space using a radial acquisition mask # We then reconstruct using adjoint with and without density compensation # Get the locations of the kspace samples and the associated observations
----------------- The example galaxy image is convolved with the example PSF and random noise is added simulating an observation with SNR~5. """ import numpy as np from pysap import Image from pysap.data import get_sample_data from pysap.plugins.astro.deconvolve.deconvolve import sparse_deconv_condatvu from modopt.signal.noise import add_noise from modopt.math.convolve import convolve # Load the example images galaxy = get_sample_data('astro-galaxy') psf = get_sample_data('astro-psf') # Show the clean galaxy image galaxy.show() # Generate a noisy observed image obs_data = add_noise(convolve(galaxy.data, psf.data), sigma=0.0005) image_obs = Image(data=np.abs(obs_data)) image_obs.show() # Deconvolve the observed image deconv_data = sparse_deconv_condatvu(obs_data, psf.data, n_iter=3000) image_rec = Image(data=np.abs(deconv_data)) image_rec.show()
from mri.operators import NonCartesianFFT, WaveletN from mri.reconstructors import SelfCalibrationReconstructor from mri.reconstructors.utils.extract_sensitivity_maps import get_Smaps from mri.operators.utils import convert_locations_to_mask, \ gridded_inverse_fourier_transform_nd import pysap from pysap.data import get_sample_data # Third party import from modopt.math.metrics import ssim from modopt.opt.linear import Identity from modopt.opt.proximity import SparseThreshold import numpy as np # Loading input data cartesian_ref_image = get_sample_data('2d-pmri') image = pysap.Image(data=np.sqrt(np.sum(cartesian_ref_image.data**2, axis=0))) # Obtain MRI cartesian mask mask = get_sample_data("mri-radial-samples") kspace_loc = mask.data # View Input # image.show() # mask.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquisition mask, we retrospectively