fun=chi_star_func, method='TNC', x0=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' ), bounds=None, options=dict(maxiter=1, disp=100)) # print('Your results are: \n '+str(minimization)) # debug chi_arr = minimization['x'].reshape(shape) return chi_arr # ====================================================================== # calling the function: if __name__ == '__main__': begin_time = datetime.datetime.now() chi_arr = chi_star(f=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' )) # saving the results here: save( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs_TNC_one_iter.nii.gz', chi_arr) end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds!'.format(c=time_elapsed))
# ====================================================================== # calling the function: if __name__ == '__main__': begin_time = datetime.datetime.now() chi_arr = chi_star( f=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz') * 100) # saving the results here: i = 0 template = '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs_TNC_nobound_{i}.nii.gz' filepath = template.format_map(locals()) while os.path.isfile(filepath): i += 1 filepath = template.format_map(locals()) save(filepath ,chi_arr) end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds!'.format(c=time_elapsed)) # results for: #options=dict(maxiter=500, disp=500)) # NIT NF F GTG # 0 1 6.250653576944698E+02 3.09316951E+02 # tnc: fscale = 0.045968 # tnc: stepmx = 1000 # 1 5 4.401179716665604E+02 1.66555222E+02 # 2 14 2.333503445130736E+02 2.08673438E+01 # 3 20 2.314651422641286E+02 1.84598353E+01 # 4 26 2.071453779162987E+02 1.81406194E+01
minimization = scipy.optimize.minimize( fun=chi_star_func, method='L-BFGS-B', x0=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' ), bounds=[(l, u) for l, u in zip(lower_bound, upper_bound)], options=dict(maxiter=1000, disp=100)) # print('Your results are: \n '+str(minimization)) # debug chi_arr = minimization['x'].reshape(shape) return chi_arr # ====================================================================== # calling the function: if __name__ == '__main__': begin_time = datetime.datetime.now() chi_arr = chi_star(f=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' )) # saving the results here: save( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs_pretty.nii.gz', chi_arr) end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds!'.format(c=time_elapsed))
# ============================================================================= # calling the function: if __name__ == '__main__': begin_time = datetime.datetime.now() # execute whole function (with two sub-functions) chi = chi_star( f=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' ), chi=load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' )) save( '/home/raid3/vonhof/Documents/Riccard_Data/230317/phantom_32_chi_tfi.nii.gz', chi) end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds.'.format(c=time_elapsed)) # misc: # #save('') #print([x.shape for x in (a,b,c,d,alpha,e,g,h,j,gamma)]) # debug #return [x for x in [beta, gamma]] #print('\n j is: \n'+str(j)) #return [x for x in [alpha,beta, gamma]] #print([x for x in (a,b,c,d,e,g,h,j)]) # debug #print('\n BETA: \n'+str(beta)) #print('\n ALPHA: \n'+str(alpha))
def calculation(chi_star_func,deriv_func, beta_calc=beta): result = chi_star_func(chi=chi, f=f, d=d, W=W, M_G=M_G, lambda_=lambda_) beta_calc = deriv_func(d=d,W=W, P=P, lambda_=lambda_, M_G=M_G, chi=chi, epsilon=epsilon,f=f, alpha=alpha, beta_calc=beta, gamma=gamma) chi_res = scipy.optimize.fmin_ncg(f=chi_star_func, x0=chi, fprime=deriv_func) # xopt is zeroth term return chi_res[0] chi_res = calculation(chi_star_func,deriv_func, beta_calc=beta) return chi_res # ============================================================================= if __name__ == '__main__': begin_time = datetime.datetime.now() # execute whole function (with two sub-functions) chi_res = chi_star(f=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'), chi=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz')) save('/home/raid3/vonhof/Documents/Riccard_Data/230317/phantom_32_chi_ncg_app.nii.gz', chi_res) # todo: save is not the main problem, rest also has a bug somewhere end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds.'.format(c=time_elapsed)) #todo: solve reshape chi thing for wrong shape of stuff # todo: make it work at all #chi_res = chi_star(f=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'), chi=load('/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz'))
def compute_generic(sources, out_dirpath, params=None, opts=None, force=False, verbose=D_VERB_LVL): """ Perform the specified computation on source files. Args: sources (list[str]): Directory containing data files. out_dirpath (str): Directory containing metadata files. params (dict): Parameters associated with the sources. opts (dict): Accepted options: - types (list[str]): List of image types to use for results. - mask: (tuple[tuple[int]): Slicing for each dimension. - adapt_mask (bool): adapt over- or under-sized mask. - dtype (str): data type to be used for the target images. - compute_func (str): function used for the computation. compute_func(images, params, compute_args, compute_kwargs) -> img_list, img_type_list - compute_args (list): additional positional parameters for compute_func - compute_kwargs (dict): additional keyword parameters for compute_func - affine_func (str): name of the function for affine computation: affine_func(affines, affine_args...) -> affine - affine_args (list): additional parameters for affine_func force (bool): Force calculation of output verbose (int): Set level of verbosity. Returns: targets (): See Also: pymrt.computation.sources_generic, pymrt.computation.compute, pymrt.computation.D_OPTS """ # TODO: implement affine_func, affine_args, affine_kwargs? # get the num, name and seq from first source file opts = pmu.merge_dicts(D_OPTS, opts) if params is None: params = {} if opts is None: opts = {} targets = [] info = pmn.parse_filename(sources[0]) if 'ProtocolName' in params: info['name'] = params['ProtocolName'] for image_type in opts['types']: info['type'] = image_type targets.append(os.path.join(out_dirpath, pmn.to_filename(info))) # perform the calculation if pmu.check_redo(sources, targets, force): if verbose > VERB_LVL['none']: print('{}:\t{}'.format('Object', os.path.basename(info['name']))) if verbose >= VERB_LVL['medium']: print('Opts:\t{}'.format(json.dumps(opts))) images, affines = [], [] mask = [(slice(*dim) if dim is not None else slice(None)) for dim in opts['mask']] for source in sources: if verbose > VERB_LVL['none']: print('Source:\t{}'.format(os.path.basename(source))) if verbose > VERB_LVL['none']: print('Params:\t{}'.format(params)) image, affine, header = pmio.load(source, full=True) # fix mask if shapes are different if opts['adapt_mask']: mask = [(mask[i] if i < len(mask) else slice(None)) for i in range(len(image.shape))] images.append(image[mask]) affines.append(affine) if 'compute_func' in opts: compute_func = eval(opts['compute_func']) if 'compute_args' not in opts: opts['compute_args'] = [] if 'compute_kwargs' not in opts: opts['compute_kwargs'] = {} img_list, aff_list, img_type_list, params_list = compute_func( images, affines, params, *opts['compute_args'], **opts['compute_kwargs']) else: img_list, aff_list, img_type_list = zip( *[(img, aff, img_type) for img, aff, img_type in zip( images, affines, itertools.cycle(opts['types']))]) params_list = ({}, ) * len(img_list) for target, target_type in zip(targets, opts['types']): for img, aff, img_type, params in \ zip(img_list, aff_list, img_type_list, params_list): if img_type == target_type: if 'dtype' in opts: img = img.astype(opts['dtype']) if params: for key, val in params.items(): target = pmn.change_param_val(target, key, val) if verbose > VERB_LVL['none']: print('Target:\t{}'.format(os.path.basename(target))) pmio.save(target, img, aff) break return targets
def ext_qsm_as_legacy( images, affines, params, te_label, # b0_label, # th_label, img_types): """ Args: images (): affines (): params (): te_label (): img_types (): Returns: """ # determine correct TE max_te = 25.0 # ms selected = len(params[te_label]) for i, te in enumerate(params[te_label]): if te < max_te: selected = i tmp_dirpath = '/tmp/{}'.format(hashlib.md5(str(params)).hexdigest()) if not os.path.isdir(tmp_dirpath): os.makedirs(tmp_dirpath) tmp_filenames = ('magnitude.nii.gz', 'phase.nii.gz', 'qsm.nii.gz', 'mask.nii.gz') tmp_filepaths = tuple( os.path.join(tmp_dirpath, tmp_filename) for tmp_filename in tmp_filenames) # export temp input if len(images) > 2: images = images[-2:] affines = affines[-2:] for image, affine, tmp_filepath in zip(images, affines, tmp_filepaths): pmio.save(tmp_filepath, image[..., selected], affine) # execute script on temp input cmd = [ 'qsm_as_legacy.py', '--magnitude_input', tmp_filepaths[0], '--phase_input', tmp_filepaths[1], '--qsm_output', tmp_filepaths[2], '--mask_output', tmp_filepaths[3], '--echo_time', str(params[te_label][selected]), # '--field_strength', str(params[b0_label][selected]), # '--angles', str(params[th_label][selected]), '--units', 'ppb' ] pmu.execute(str(' '.join(cmd))) # import temp output img_list, aff_list = [], [] for tmp_filepath in tmp_filepaths[2:]: img, aff, hdr = pmio.load(tmp_filepath, full=True) img_list.append(img) aff_list.append(aff) # clean up tmp files if os.path.isdir(tmp_dirpath): shutil.rmtree(tmp_dirpath) # prepare output type_list = ('qsm', 'mask') params_list = ({'te': params[te_label][selected]}, {}) img_type_list = tuple(img_types[key] for key in type_list) return img_list, aff_list, img_type_list, params_list
chi=chi) return chi # ============================================================================= # calling the function: if __name__ == '__main__': begin_time = datetime.datetime.now() proxy = load( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_phs.nii.gz' ) # execute whole function (with two sub-functions) chi = chi_star(f=proxy, chi=proxy) save( '/home/raid3/vonhof/Documents/Riccardo_Data/230317/phantom_32_chi_appendix.nii.gz', chi) end_time = datetime.datetime.now() time_elapsed = end_time - begin_time print('Time elapsed: {c} seconds.'.format(c=time_elapsed)) # misc: # #save('') #print([x.shape for x in (a,b,c,d,alpha,e,g,h,j,gamma)]) # debug #return [x for x in [beta, gamma]] #print('\n j is: \n'+str(j)) #return [x for x in [alpha,beta, gamma]] #print([x for x in (a,b,c,d,e,g,h,j)]) # debug #print('\n BETA: \n'+str(beta)) #print('\n ALPHA: \n'+str(alpha))
print([x.shape for x in (chi, f, d, M_G, W, lambda_)]) chi = chi.reshape(f.shape) return 0.5*((np.linalg.norm(W* (f - np.fft.ifftn(d * np.fft.fftn(chi))))) ** 2 + lambda_ * np.sum(abs((M_G) * (np.gradient(chi))))) #---------------------------- function use --------------------------------# # x is the solution array, corresponds to chi_star in approach for GN begin_time=datetime.datetime.now() filepath = 'chi.npz' if not os.path.isfile(filepath): minimization = scipy.optimize.minimize(fun=data_input,method='BFGS',x0=matrix_proxy) #minimization = scipy.optimize.minimize(fun=data_input,method='L-BFGS-B',x0=0.) print('Your results are: \n '+str(minimization)) chi_arr = minimization['x'] np.savez(filepath, chi_arr=chi_arr) else: data = np.load(filepath) chi_arr = data['chi_arr'] save( '/home/raid3/vonhof/Documents/Riccardo Data/1703_phantomStuff/phantom_chi_star.nii.gz', chi_arr.reshape(db_zero.shape)) p_proxy = np.ones((128,128,128))*(-1.81266051) chi_star = np.multiply(p_proxy,db_zero) print('The result is of shape: ' +str(chi_star.shape)) print(np.sum(db_zero)/(128*128*128)) print(np.sum(chi_star)/(128*128*128)) print((np.sum(chi_star)/(128*128*128))/(np.sum(db_zero)/(128*128*128))) print(data_input(db_zero)) end_time=datetime.datetime.now() print('{!s}'.format(end_time - begin_time))