def func(subject_info, output_path): subject_id = subject_info.subject_id for model_name in model_names: print(subject_id, model_name) starting_point = mdt.fit_model(model_name, subject_info.get_input_data(), output_path + '/' + subject_id) with mdt.config_context(''' processing_strategies: sampling: max_nmr_voxels: 5000 '''): mdt.sample_model(model_name, subject_info.get_input_data(), output_path + '/' + subject_info.subject_id, nmr_samples=nmr_samples[model_name], initialization_data={'inits': starting_point}, store_samples=False) wm_mask = generate_simple_wm_mask(os.path.join(output_path, subject_id, 'Tensor', 'Tensor.FA.nii.gz'), subject_info.get_input_data().mask, threshold=0.3, median_radius=3, nmr_filter_passes=4) mdt.write_nifti(wm_mask, os.path.join(output_path, subject_id, 'wm_mask'))
def correct_mgh_image_position(input_fname, output_fname=None): """The HCP MGH data is ill-positioned for the registration algorithm, this function corrects that.""" header = mdt.load_nifti(input_fname).get_header() data = mdt.load_nifti(input_fname).get_data() if output_fname is None: output_fname = input_fname mdt.write_nifti(data[:, ::-1], output_fname, header)
def run(self, args, extra_args): input_file = os.path.realpath(args.input_file) output_file = os.path.realpath(args.output_file) input_data = load_nifti(input_file).get_data() header = load_nifti(input_file).get_header() noise_covar = calculate_noise_covariance_matrix( input_data, normalize=args.normalize) mdt.write_nifti(noise_covar, header, output_file)
def run(self, args, extra_args): input_file = os.path.realpath(args.input_file) if args.output_file is None: dirname, basename, ext = split_image_path(input_file) output_file = dirname + basename + '_tSNR' + ext else: output_file = os.path.realpath(args.output_file) nifti = mct.load_nifti(input_file) tsnr = calculate_tsnr(nifti.get_data()) mdt.write_nifti(tsnr, output_file, nifti.get_header())
def reconstruct(self, output_directory, volumes=None): output_subdir = output_directory + '/' + self._output_subdir niftis = UnzippedNiftis(self._channels, output_subdir) combined = self._reconstruct(niftis, volumes=volumes) if isinstance(combined, collections.Mapping): for name, data in combined.items(): mdt.write_nifti(data, output_subdir + '/{}.nii.gz'.format(name), niftis[0].get_header()) else: mdt.write_nifti(combined, output_subdir + '/reconstruction.nii.gz', niftis[0].get_header())
def func(subject_info): subject_id = subject_info.subject_id wm_mask = generate_simple_wm_mask(os.path.join( subject_info.data_folder[:-1] + '_output', subject_id, 'Tensor', 'Tensor.FA.nii.gz'), subject_info.get_input_data().mask, threshold=0.3, median_radius=3, nmr_filter_passes=4) mdt.write_nifti( wm_mask, os.path.join(subject_info.data_folder[:-1] + '_output', subject_id, 'wm_mask'))
def combine_weighted_sum(input_channels, weights, output_filename): """Combine all the coils using the given weights. Args: input_channels (list of str): the list with the input channel filenames weights (str or ndarray): the weights to use for the reconstruction. output_filename (str): the output filename """ final_shape = load_nifti(input_channels[0]).shape output = np.zeros(final_shape, dtype=np.float64) if isinstance(weights, str): weights = load_nifti(weights).get_data() for ind, input_channel in enumerate(input_channels): output += weights[..., ind, None] * load_nifti(input_channel).get_data() header = load_nifti(input_channels[0]).get_header() mdt.write_nifti(output, output_filename, header)
def split_write_volumes(input_file, output_dir, axis=-1): """Split and write the given input volume to separate nifti files. Args: input_file (str): the input nifti file to split output_dir (str): the output directory, this will write the split volumes to that directory with the same basename as the input file, with the slice index appended axis (int): the axis to split on """ dirname, basename, extension = split_image_path(input_file) nifti = load_nifti(input_file) data = nifti.get_data() header = nifti.get_header() for ind in range(data.shape[axis]): index = [slice(None)] * len(data.shape) index[axis] = ind mdt.write_nifti(data[index], '{}/{}_{}.nii'.format(output_dir, basename, ind), header)
def create_simulations(protocol_name, model_name): output_pjoin = pjoin.create_extended(protocol_name, model_name) if os.path.exists(output_pjoin()): return else: output_pjoin.make_dirs() model = mdt.get_model(model_name)(volume_selection=False) param_names = model.get_free_param_names() model_config = simulations[model_name] parameters = create_parameter_combinations(10000, [ param_names.index(name) for name in model_config['randomize_parameters'] ], model.get_initial_parameters(), model_config['lower_bounds'], model_config['upper_bounds'], seed=0) if model_config['prepare_params_cube_cb'] is not None: model_config['prepare_params_cube_cb'](parameters) simulated_signals = mdt.simulate_signals( model, mdt.load_protocol(pjoin(protocol_name)), parameters) mdt.write_nifti(parameters[None, :, None, :], output_pjoin('original_parameters.nii')) mdt.write_nifti(simulated_signals[None, :, None, :], output_pjoin('simulated_signals.nii')) for snr in noise_snrs: noisy_signals = mdt.add_rician_noise(simulated_signals, unweighted_signal_height / snr, seed=0) mdt.write_nifti(noisy_signals[None, :, None, :], output_pjoin('noisy_signals_{}.nii'.format(snr))) mdt.create_blank_mask( output_pjoin('noisy_signals_{}.nii'.format(noise_snrs[0])), output_pjoin('mask.nii'))
def run(self, args, extra_args): file_names = [] images = [] for file in args.input_files: globbed = glob.glob(file) if globbed: for fname in globbed: file_names.append(fname) images.append( mdt.load_nifti(os.path.realpath(fname)).get_data()) else: file_names.append(file) images.append( mdt.load_nifti(os.path.realpath(file)).get_data()) if args.verbose: print('') if args.input_4d: images = self._images_3d_to_4d(images) context_dict = {'input': images, 'i': images, 'np': np, 'mdt': mdt} alpha_chars = list('abcdefghjklmnopqrstuvwxyz') for ind, image in enumerate(images): context_dict.update({alpha_chars[ind]: image}) if args.verbose: print('Input {ind} ({alpha}):'.format(ind=ind, alpha=alpha_chars[ind])) print(' name: {}'.format( split_image_path(file_names[ind])[1])) print(' shape: {}'.format(str(image.shape))) if args.verbose: print('') print("Evaluating: '{expr}'".format(expr=args.expr)) if args.as_expression: output = eval(args.expr, context_dict) else: expr = textwrap.dedent(''' def mdt_image_math(): {} output = mdt_image_math() ''').format(args.expr) exec(expr, context_dict) output = context_dict['output'] if args.verbose: print('') if isinstance(output, np.ndarray): print('Output shape: {shape}'.format(shape=str(output.shape))) else: print('Output is single value') print('Output: ') print('') print(output) else: if not args.write_output: print(output) if args.verbose: print('') if args.write_output: if isinstance(output, Sequence): if args.output_file: output_file = os.path.realpath(args.output_file) dirname, basename, ext = split_image_path(output_file) for ind, element in enumerate(output): mdt.write_nifti( element, dirname + basename + '_' + str(ind) + ext, mdt.load_nifti(file_names[0]).header) else: for ind, element in enumerate(output): output_file = os.path.realpath(file_names[ind]) mdt.write_nifti(element, output_file, mdt.load_nifti(file_names[ind]).header) else: if args.output_file: output_file = os.path.realpath(args.output_file) else: output_file = os.path.realpath(file_names[0]) mdt.write_nifti(output, output_file, mdt.load_nifti(file_names[0]).header)