def get_dataset2(scan_number, do_real=True): ''' Loads ksp data and applies an arc mask, while also converting to magnitude data if required im_ref is not a combined coil image, is size (N, H, W, C) im_us is size (N, H, W, C) ''' data_dir = 'data2/' filename_ref = 'scan' + str(scan_number) + '_ref' filename_mask = 'scan' + str(scan_number) + '_mask' path_ref = data_dir + filename_ref path_mask = data_dir + filename_mask ksp_ref = cfl.readcfl(path_ref) if(do_real): ksp_ref = fft3c(np.abs(ifft3c(ksp_ref))) mask = np.real(cfl.readcfl(path_mask)).astype(np.float32) mask = mask[:, :, :, np.newaxis] # apply mask ksp_us = ksp_ref * mask im_ref = ifft3c(ksp_ref) im_us = ifft3c(ksp_us) if(do_real): im_ref = np.real(im_ref).astype(np.float32) im_us = np.real(im_us).astype(np.float32) return (im_ref, im_us, mask)
def __init__(self, infile, para, TI, outfile): self.infile = sys.argv[1] self.para = sys.argv[2] self.TIfile = sys.argv[3] self.outfile = sys.argv[4] self.oridata = np.array(cfl.readcfl( self.infile).squeeze()) #dim = [x, y, time, slice] self.TI = np.array(cfl.readcfl(self.TIfile).squeeze()) a = np.mean(self.oridata[:, :, -1]) self.oridata = 1.0 * self.oridata / a self.map = self.getmap(np.abs(self.oridata), self.TI) cfl.writecfl(self.outfile, self.map) print("Ellapsed time: " + str(end - start) + " s")
def bart(nargout, cmd, *args): if type(nargout) != int or nargout < 0: print("Usage: bart(<nargout>, <command>, <arguements...>)") return None bart_path = os.environ['TOOLBOX_PATH'] + '/bart ' if not bart_path: if os.path.isfile('/usr/local/bin/bart'): bart_path = '/usr/local/bin' elif os.path.isfile('/usr/bin/bart'): bart_path = '/usr/bin' else: raise Exception('Environment variable TOOLBOX_PATH is not set.') name = tmp.NamedTemporaryFile().name nargin = len(args) infiles = [name + 'in' + str(idx) for idx in range(nargin)] in_str = ' '.join(infiles) for idx in range(nargin): cfl.writecfl(infiles[idx], args[idx]) outfiles = [name + 'out' + str(idx) for idx in range(nargout)] out_str = ' '.join(outfiles) #TODO: Windows option. ERR = os.system(bart_path + '/bart ' + cmd + ' ' + in_str + ' ' + out_str) for elm in infiles: if os.path.isfile(elm + '.cfl'): os.remove(elm + '.cfl') if os.path.isfile(elm + '.hdr'): os.remove(elm + '.hdr') output = [] for idx in range(nargout): elm = outfiles[idx] if not ERR: output.append(cfl.readcfl(elm)) if os.path.isfile(elm + '.cfl'): os.remove(elm + '.cfl') if os.path.isfile(elm + '.hdr'): os.remove(elm + '.hdr') if ERR: raise Exception("Command exited with an error.") if nargout == 1: output = output[0] return output
def bart(cmd='', nargout=0, *args): if not cmd or not nargout: print "Usage: bart <command> <arguments...>"; return None bart_path = os.environ['TOOLBOX_PATH'] + '/bart '; if not bart_path: if os.path.isfile('/usr/local/bin/bart'): bart_path = '/usr/local/bin' elif os.path.isfile('/usr/bin/bart'): bart_path = '/usr/bin' else: raise Exception('Environment variable TOOLBOX_PATH is not set.') name = tmp.NamedTemporaryFile().name nargin = len(args); infiles = [name + 'in' + str(idx) for idx in range(nargin)] in_str = ' '.join(infiles) for idx in range(nargin): cfl.writecfl(infiles[idx], args[idx]) outfiles = [name + 'out' + str(idx) for idx in range(nargout)] out_str = ' '.join(outfiles) #TODO: Windows option. ERR = os.system(bart_path + '/bart ' + cmd + ' ' + in_str + ' ' + out_str); for elm in infiles: if os.path.isfile(elm + '.cfl'): os.remove(elm + '.cfl') if os.path.isfile(elm + '.hdr'): os.remove(elm + '.hdr') output = [] for idx in range(nargout): elm = outfiles[idx] if not ERR: output.append(cfl.readcfl(elm)) if os.path.isfile(elm + '.cfl'): os.remove(elm + '.cfl') if os.path.isfile(elm + '.hdr'): os.remove(elm + '.hdr') if ERR: raise Exception("Command exited with an error.") if nargout == 1: output = output[0] return output
def get_dataset(scan_number): ''' Loads an arc undersampled dataset that is real im_ref is a coil comabined image, is size (N, H, W, 1) im_us is 2x undersampled real images, is size (N, H, W, C) ''' print('loading scan ', scan_number) data_dir = 'data/' filename_ref = 'scan' + str(scan_number) + '_real_ref' filename_us = 'scan' + str(scan_number) + '_real_us' path_ref = data_dir + filename_ref path_us = data_dir + filename_us im_ref = np.real(cfl.readcfl(path_ref)).astype(np.float32) im_us = np.real(cfl.readcfl(path_us)).astype(np.float32) im_ref = im_ref[:, :, :, np.newaxis] # put into format (samples, rows, cols, channels) return (im_ref, im_us)
def plot_traj(traj_file, png_file): traj = cfl.readcfl(traj_file) print('traj dims: ', traj.shape) D = traj.ndim if D < 16: for d in range(D, 16, 1): traj = np.expand_dims(traj, axis=d) assert traj.ndim == 16 N_spk = traj.shape[2] N_eco = traj.shape[5] N_frm = traj.shape[10] fig = plt.gcf() fig.set_size_inches(18.5, 10.5) for nf in range(N_frm): ax = plt.subplot(1, N_frm, nf + 1) for ne in range(N_eco): for ns in range(N_spk): kx = np.squeeze(traj[0, :, ns, 0, 0, ne, 0, 0, 0, 0, nf]) ky = np.squeeze(traj[1, :, ns, 0, 0, ne, 0, 0, 0, 0, nf]) plt.plot(kx.real, ky.real, '.g') plt.axis('off') ax.set_aspect('equal', 'box') plt.text(kx[-1].real, ky[-1].real, str(ns), fontsize=16) plt.savefig(png_file, bbox_inches='tight', dpi=200) plt.close()
r.set_clim((0, r.get_clim()[1])) axes[1].set_title('reconstruction') im = axes[1].imshow(np.fliplr(np.abs(reco).T), origin='lower') im.set_clim(r.get_clim()) axes[2].set_title('difference * 10') diff = axes[2].imshow(np.fliplr((np.abs(ref) - np.abs(reco)).T), origin='lower') diff.set_clim((0, r.get_clim()[1] / 10.)) plt.show() datafile = 'data/unders_2_v8' data = np.ascontiguousarray(cfl.readcfl(datafile).T).squeeze() ncoils, nx, ny = data.shape pattern = rpm.estimate_sampling_pattern(data) data = data[:, pattern].flatten() grid = rp.discrs.UniformGrid((-1, 1, nx), (-1, 1, ny), dtype=np.complex64) bartop = BartNoir(grid, ncoils, pattern) setting = rp.solvers.HilbertSpaceSetting(op=bartop, Hdomain=rp.hilbert.L2, Hcodomain=rp.hilbert.L2) init = bartop.domain.zeros() init_density, init_coils = bartop.domain.split(init) init_density[...] = 1
ax1.set_ylabel(ylabel, fontsize=22) ax1.grid() if (para == "T2"): ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax1.xaxis.set_major_formatter(FormatStrFormatter('%.2f')) plt.xticks(ticks) plt.yticks(ticks) plt.tight_layout() plt.show(block = True) fig.savefig(outfile + ".eps", format='eps', bbox_inches='tight', transparent=True) if __name__ == "__main__": #Error if wrong number of parameters if( len(sys.argv) != 5): print( "Function for ploting estimated quantitative values against references." ) print( "Usage: plot_T1T2_reference.py <infile data> <infile ref> <maptype(T1 or T2)> <outfile>" ) exit() data = np.abs(cfl.readcfl(sys.argv[1]).squeeze()) ref = np.abs(cfl.readcfl(sys.argv[2]).squeeze()) data[np.isnan(data)] = 0 ref[np.isnan(ref)] = 0 Plot(data, ref, sys.argv[3], sys.argv[4])
ax.set_ylabel('Signal') ax.set_title('Temporal Subspace Curves') def array_plot2(ax, arr, rows=4, cols=4): idx = 0 xticks = 6e-3*np.arange(0, len(arr[:,idx]), 1) for idx in range(rows*cols): ax.plot(xticks, np.real(arr[:,idx]),linewidth=2, label=str(idx)) idx += 1 ax.set_xlabel('Time / s') ax.set_ylabel('Signal') ax.set_title('Simulated Dictionary (subset)') #---------------------------------------------------------------# Signal = readcfl("./dicc2") if False: random_index = list(np.random.choice(100000, 7, replace=False)) else: random_index = [18921, 47522, 45034, 14515, 90331, 7023, 74182] Signal1 = Signal[:,random_index] S = readcfl("./S") U = readcfl("./U") U_truc = U[:,0:5]
newcmp = ListedColormap(newcolors) plt.figure() plt.imshow(image, interpolation='nearest', cmap=newcmp, vmin=lowerbound, vmax=upperbound) plt.show() plt.imsave(outfile, image, format="png", cmap=newcmp, vmin=lowerbound, vmax=upperbound) if __name__ == "__main__": #Error if wrong number of parameters if (len(sys.argv) != 6): print("Function for saving quantitative MR maps with colormap") print( "Usage: save_maps.py <input image> <colorbartype(e.g., viridis)> <lowerbound> <upperbound> <outfile>" ) exit() image = np.abs(cfl.readcfl(sys.argv[1]).squeeze()) save_maps(image, sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
from estvar import estvar import matplotlib.pyplot as plt import numpy as np k = 6 r = 24 #var = 1000000 #X = cfl.readcfl('data/knee/noisy') #var = 100 #X = cfl.readcfl('data/brain/noisy') var = 100 X = cfl.readcfl('data/alias/noisy') print("Method 1") est = estvar(X, k, r, 1) print("True variance: %f" % var) print("Estimated noise variance: %f" % est) print("Ratio of estimated over true value: %f" % (est / var)) print("Method 2") est = estvar(X, k, r, 2) print("True variance: %f" % var) print("Estimated noise variance: %f" % est) print("Ratio of estimated over true value: %f" % (est / var)) print("Method 3") est = estvar(X, k, r, 3)
from matplotlib.ticker import FormatStrFormatter color = [ "#348ea9", "#ef4846", "#52ba9b", "#f48b37", "#89c2d4", "#ef8e8d", "#a0ccc5", "#f4b481" ] linestyle = ["-", "--", "-.", ":"] marker = ["o", "^", "s", "8"] import matplotlib.font_manager as font_manager from matplotlib import rcParams mpl.rcParams.update({'font.size': 22}) path = '../utils/LinBiolinum_R.otf' prop = font_manager.FontProperties(fname=path) mpl.rcParams['font.family'] = prop.get_name() import pandas as pd eof_51 = readcfl("EOF_51") eof_91 = readcfl("EOF_91") DPI = 200 #%% int_start = 800 int_end = 3000 t = np.linspace(0, eof_51.shape[0], eof_51.shape[0], endpoint="False") idx = 0 # Plot EOF rows = 2 cols = 1 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(1800 / DPI, 1200 / DPI))
from matplotlib.ticker import FormatStrFormatter color = [ "#348ea9", "#ef4846", "#52ba9b", "#f48b37", "#89c2d4", "#ef8e8d", "#a0ccc5", "#f4b481" ] linestyle = ["-", "--", "-.", ":"] marker = ["o", "^", "s", "8"] import matplotlib.font_manager as font_manager from matplotlib import rcParams mpl.rcParams.update({'font.size': 22}) path = '../utils/LinBiolinum_R.otf' prop = font_manager.FontProperties(fname=path) mpl.rcParams['font.family'] = prop.get_name() import pandas as pd eof_91 = readcfl("EOF_91") eof_21 = readcfl("EOF_21") DPI = 200 #%% int_start = 500 int_end = 5200 t = np.linspace(0, eof_91.shape[0], eof_91.shape[0], endpoint="False") idx = 0 # Plot EOF rows = 2 cols = 1 fig, ax = plt.subplots(nrows=rows, ncols=cols,
def main(out_name, in_name): input = cfl.readcfl(in_name) cfl.writecfl(input, out_name) # cfl.writecfl(out_name, input) return 0
#!/usr/bin/env python3 import numpy as np import cfl import argparse parser = argparse.ArgumentParser(description='Undersample cfl') parser.add_argument('dim', metavar='D', type=int, action='store', help='Dimension') parser.add_argument('acc', metavar='acc', type=int, help='Acceleration factor') parser.add_argument('input', metavar='IN', type=str, help='Input cfl') parser.add_argument('output', metavar='OUT', type=str, help='Output cfl') args = parser.parse_args() in_ = cfl.readcfl(args.input) tmp = np.moveaxis(in_, args.dim, 0) out_ = np.moveaxis(tmp[::args.acc, ...], 0, args.dim) cfl.writecfl(args.output, out_)
# %% def save_pc_img(R, cmap_str, vmin, vmax, png_file, width=None, height=None): full_frame(width,height) plt.imshow(R, interpolation='none', cmap=cmap_str, vmin=vmin,vmax=vmax, aspect='auto') plt.savefig(png_file, bbox_inches='tight', dpi=100, pad_inches=0) plt.close() # %% orig_dir = os.getcwd() # %% MAG = np.flipud(np.squeeze(cfl.readcfl('MAG'))) VEL = np.flipud(np.squeeze(cfl.readcfl('VEL'))) saved_dir='png_moba_flow' pathlib.Path(saved_dir).mkdir(parents=True, exist_ok=True) os.chdir(saved_dir) for n in np.arange(MAG.shape[2]): mag_file = 'MAG_' + str(n).zfill(3) save_pc_img(np.absolute(MAG[:,:,n]), 'gray', 0, 700, mag_file, 4, 4) vel_file = 'VEL_' + str(n).zfill(3) save_pc_img(-VEL[:,:,n].real, 'RdBu_r', -150, 150, vel_file, 4, 4) os.chdir(orig_dir)
import cfl from espirit import espirit, espirit_proj, ifft import matplotlib.pyplot as plt import numpy as np # Load data X = cfl.readcfl('data/knee') x = ifft(X, (0, 1, 2)) # Derive ESPIRiT operator esp = espirit(X, 6, 24, 0.01, 0.9925) # Do projections ip, proj, null = espirit_proj(x, esp) # Figure code esp = np.squeeze(esp) x = np.squeeze(x) ip = np.squeeze(ip) proj = np.squeeze(proj) null = np.squeeze(null) print("Close figures to continue execution...") # Display ESPIRiT operator for idx in range(8): for jdx in range(8): plt.subplot(8, 8, (idx * 8 + jdx) + 1) plt.imshow(np.abs(esp[:, :, idx, jdx]), cmap='gray') plt.axis('off')
import pandas as pd from optparse import OptionParser # Option Parsing parser = OptionParser(description="Plotting.", usage="%prog [-options] <src:k> <src:S> <src:EOF> <src:PCA> <src:osc1> <src:osc2>") parser.add_option("-x", dest="xdims", help="x dimensions x_start:x_end", default="0:1000") parser.add_option("--ylim", dest="ylim", help="y limits noise", default="1") parser.add_option("--y2lim", dest="y2lim", help="y limits other", default="1") parser.add_option("--eof", dest="eof_idx", help="Choose index for EOFs: eof1:eof2:eof3:eof4", default="0:1:2:3") (options, args) = parser.parse_args() k = readcfl(str(args[0])) S = np.real(readcfl(str(args[1])))[:30] EOF = readcfl(str(args[2])) PCA = readcfl(str(args[3])) osc1 = readcfl(str(args[4])) osc2 = readcfl(str(args[5])) typ = readcfl(str(args[6])) xdims = str(options.xdims) ylim = float(options.ylim) y2lim = float(options.y2lim) st, end = [int(k) for k in xdims.split(":")] eof_idx = str(options.eof_idx) eof1, eof2, eof3, eof4 = [int(k) for k in eof_idx.split(":")] DPI = 200
ax1.legend() ax2.plot(TE, (U_phi[:, idx]), linewidth=3, markersize=15) idx += 1 ax1.set_ylabel('Magnitude') ax2.set_xlabel('Time / ms') ax2.set_ylabel('Phase') ax1.set_title('Temporal Subspace Curves') plt.savefig('Figure5B_MGRE-Subspace.eps') # %% signal = cfl.readcfl("mgre_signal_sr") mag, phi = get_signal(signal) print(mag.shape) singular_value = cfl.readcfl("mgre_S") singular_vec = cfl.readcfl("mgre_U") TE = numpy.squeeze(numpy.absolute(cfl.readcfl("TE"))) plot_signal(mag, phi, singular_value, singular_vec, TE)
from matplotlib import rcParams mpl.rcParams.update({'font.size': 22}) path = '../utils/LinBiolinum_R.otf' prop = font_manager.FontProperties(fname=path) mpl.rcParams['font.family'] = prop.get_name() import pandas as pd from optparse import OptionParser # Option Parsing parser = OptionParser( description="Plotting.", usage="%prog [-options] <src:EOF_a> <src:EOF_b> <src:EOF_c> <dst>") (options, args) = parser.parse_args() args = ("EOF_81", "EOF_91", "EOF_101") label = ["W=81", "W=91", "W=101"] dummy = readcfl(str(args[0]))[:, :20] EOF = np.zeros(np.append(dummy.shape, len(args)), dtype="complex") for i in range(len(args)): EOF[..., i] = readcfl(str(args[i]))[:, :20] DPI = 200 def normalize(arr): return arr / np.max(np.abs(arr)) #%% int_start = 0 int_end = 900 t = np.linspace(0, EOF.shape[0], EOF.shape[0], endpoint="False")
def main(args): # create data directories if they don't already exist if not os.path.exists(args.output_path): os.makedirs(args.output_path) if not os.path.exists(os.path.join(args.output_path, 'train')): os.makedirs(os.path.join(args.output_path, 'train')) if not os.path.exists(os.path.join(args.output_path, 'validate')): os.makedirs(os.path.join(args.output_path, 'validate')) if not os.path.exists(os.path.join(args.output_path, 'test')): os.makedirs(os.path.join(args.output_path, 'test')) # determine splits manually for now... train_exams = [ 'Exam2323', 'Exam3330', 'Exam3331', 'Exam3332', 'Exam3410', 'Exam3411', 'Exam3412', 'Exam4873', 'Exam4874', 'Exam4905', 'Exam5003', 'Exam2406' ] val_exams = ['Exam2200', 'Exam5050'] test_exams = [] all_exams = train_exams + val_exams + test_exams # figure out data splits num_train = len(train_exams) num_validate = len(val_exams) num_test = len(test_exams) num_cases = num_train + num_validate + num_test # how many cardiac phases to simulate num_phases_list = [20] for exam_name in all_exams: exam_path = os.path.join(args.input_path, exam_name) series_list = os.listdir(exam_path) if args.verbose: print("Processing %s..." % exam_name) for num_phases in num_phases_list: for series_name in series_list: series_path = os.path.join(exam_path, series_name, 'Phases%d' % num_phases) num_slices = len(glob.glob('%s/ks_*.cfl' % series_path)) kspace = [None] * num_slices maps = [None] * num_slices target = [None] * num_slices if args.verbose: print(" %s (%d slices)..." % (series_name, num_slices)) for sl in range(num_slices): # loading k-space data file_ks = "ks_%02d" % sl ks_slice = cfl.readcfl(os.path.join(series_path, file_ks)) ks_slice = np.transpose(np.squeeze(ks_slice), [0, 1, 3, 2]) # process slice to get images and sensitivity maps kspace[sl], maps[sl], target[sl] = process_slice( ks_slice, args) # Stack volume kspace = np.stack(kspace, axis=0) maps = np.stack(maps, axis=0) target = np.stack(target, axis=0) # Determine path to new hdf5 file if exam_name in train_exams: folder = 'train' elif exam_name in val_exams: folder = 'validate' else: folder = 'test' # write out HDF5 file for entire volume h5_name = "%s_%s_Phases%02d.h5" % (exam_name, series_name, num_phases) filename = os.path.join(args.output_path, folder, h5_name) with h5py.File(filename, 'w') as hf: hf.create_dataset('kspace', data=kspace) hf.create_dataset('maps', data=maps) hf.create_dataset('target', data=target) if args.dbwrite: print('Writing out files to home folder!') cfl.writecfl('/home/sandino/kspace', kspace) cfl.writecfl('/home/sandino/maps', maps) cfl.writecfl('/home/sandino/images', target) return
plt.imshow(R, interpolation='none', cmap=cmap_str, vmin=vmin, vmax=vmax, aspect='auto') plt.savefig(png_file, bbox_inches='tight', dpi=100, pad_inches=0) plt.close() # %% orig_dir = os.getcwd() # %% Water = np.flipud(np.squeeze(cfl.readcfl('RECON_WATER_mask'))) Fat = np.flipud(np.squeeze(cfl.readcfl('RECON_FAT_mask'))) R2S = np.flipud(np.squeeze(cfl.readcfl('RECON_R2S_mask'))) FIELD = np.flipud(np.squeeze(cfl.readcfl('RECON_B0FIELD_mask'))) saved_dir = 'png_moba_wf' pathlib.Path(saved_dir).mkdir(parents=True, exist_ok=True) os.chdir(saved_dir) for n in np.arange(Water.shape[2]): water_file = 'Water_' + str(n).zfill(3) save_img(np.absolute(Water[:, :, n]), 'gray', 0, 1000, water_file, 4, 4) fat_file = 'Fat_' + str(n).zfill(3) save_img(np.absolute(Fat[:, :, n]), 'gray', 0, 1000, fat_file, 4, 4)
from matplotlib import rcParams mpl.rcParams.update({'font.size': 22}) path = '../utils/LinBiolinum_R.otf' prop = font_manager.FontProperties(fname=path) mpl.rcParams['font.family'] = prop.get_name() import pandas as pd from optparse import OptionParser # Option Parsing parser = OptionParser(description="Plotting.", usage="%prog [-options] <img> <eof> <dst>") (options, args) = parser.parse_args() DPI = 200 #%% EOF & Real-time RT = plt.imread(str(args[0])) EOF = np.squeeze(readcfl(str(args[1]))) EOF = EOF / np.max(np.real(EOF)) * 2500 - 120 #%% Respiration belt dt = 2.5 # [ms] sample duration resp = np.loadtxt(str(args[2])) resp_no_trig = resp[ resp != 5000 ] # remove trigger points T_tot = resp.shape[0] * dt Samples_meas = 60900 / dt #%% start = 12637 end = int(start + Samples_meas) resp_ex = resp_no_trig[start:end] #%% # Interpolate xp = np.linspace(0, EOF[:,0].shape[0], resp_ex.shape[0])
plt.rc('legend', fontsize=10) # legend fontsize plt.rc('figure', titlesize=10) # fontsize of the figure title concat = np.concatenate cmap = matplotlib.cm.jet cmap.set_bad(color='pink') cmap = matplotlib.cm.gray cmap.set_bad(color='pink') ########################################################################################## f = lambda x: np.divide(1, x, out=np.zeros_like(x), where=(x != 0)) g = lambda x: np.min(x[np.abs(x) > 0]) h = lambda x: f(np.mean(x[np.abs(x) > 0])) dct = loadmat('../dem_code/res/map_dem.mat') otl = np.abs(readcfl('../data/brain_outline')) msk = np.abs(readcfl('../data/brain_fov')) mskt = concat([concat([msk, msk], axis=0), concat([msk, msk], axis=0)], axis=1) def ic(x): img = x.copy() img[(abs(msk) > 0) & (abs(x) == 0)] = np.inf return img maps = dct['maps'] gfactor1 = dct['gfactor_rx_1_ry_2'] gfactor2 = dct['gfactor_rx_2_ry_2'] igfactor1 = f(gfactor1)