def get_ventricles_max_fodf(data, fa, md, zoom, args): order = find_order_from_nb_coeff(data) sphere = get_sphere('repulsion100') b_matrix = get_b_matrix(order, sphere, args.sh_basis) sum_of_max = 0 count = 0 mask = np.zeros(data.shape[:-1]) if np.min(data.shape[:-1]) > 40: step = 20 else: if np.min(data.shape[:-1]) > 20: step = 10 else: step = 5 # 1000 works well at 2x2x2 = 8 mm^3 # Hence, we multiply by the volume of a voxel vol = (zoom[0] * zoom[1] * zoom[2]) if vol != 0: max_number_of_voxels = old_div(1000 * 8, vol) else: max_number_of_voxels = 1000 all_i = list( range(int(data.shape[0] / 2) - step, int(data.shape[0] / 2) + step)) all_j = list( range(int(data.shape[1] / 2) - step, int(data.shape[1] / 2) + step)) all_k = list( range(int(data.shape[2] / 2) - step, int(data.shape[2] / 2) + step)) for i in all_i: for j in all_j: for k in all_k: if count > max_number_of_voxels - 1: continue if fa[i, j, k] < args.fa_threshold \ and md[i, j, k] > args.md_threshold: sf = np.dot(data[i, j, k], b_matrix.T) sum_of_max += sf.max() count += 1 mask[i, j, k] = 1 logging.debug('Number of voxels detected: {}'.format(count)) if count == 0: logging.warning('No voxels found for evaluation! Change your fa ' 'and/or md thresholds') return 0, mask logging.debug('Average max fodf value: {}'.format(sum_of_max / count)) return sum_of_max / count, mask
def _get_direction_getter(args, mask_data): sh_data = nib.load(args.sh_file).get_data().astype('float64') sphere = HemiSphere.from_sphere(get_sphere(args.sphere)) theta = get_theta(args.theta, args.algo) if args.algo in ['det', 'prob']: if args.algo == 'det': dg_class = DeterministicMaximumDirectionGetter else: dg_class = ProbabilisticDirectionGetter return dg_class.from_shcoeff(shcoeff=sh_data, max_angle=theta, sphere=sphere, basis_type=args.sh_basis, relative_peak_threshold=args.sf_threshold) # Code for type EUDX. We don't use peaks_from_model # because we want the peaks from the provided sh. sh_shape_3d = sh_data.shape[:-1] npeaks = 5 peak_dirs = np.zeros((sh_shape_3d + (npeaks, 3))) peak_values = np.zeros((sh_shape_3d + (npeaks, ))) peak_indices = np.full((sh_shape_3d + (npeaks, )), -1, dtype='int') b_matrix = get_b_matrix(find_order_from_nb_coeff(sh_data), sphere, args.sh_basis) for idx in np.ndindex(sh_shape_3d): if not mask_data[idx]: continue directions, values, indices = get_maximas(sh_data[idx], sphere, b_matrix, args.sf_threshold, 0) if values.shape[0] != 0: n = min(npeaks, values.shape[0]) peak_dirs[idx][:n] = directions[:n] peak_values[idx][:n] = values[:n] peak_indices[idx][:n] = indices[:n] dg = PeaksAndMetrics() dg.sphere = sphere dg.peak_dirs = peak_dirs dg.peak_values = peak_values dg.peak_indices = peak_indices dg.ang_thr = theta dg.qa_thr = args.sf_threshold return dg
def get_maps(data, mask, args, npeaks=5): nufo_map = np.zeros(data.shape[0:3]) afd_map = np.zeros(data.shape[0:3]) afd_sum = np.zeros(data.shape[0:3]) peaks_dirs = np.zeros(list(data.shape[0:3]) + [npeaks, 3]) order = find_order_from_nb_coeff(data) sphere = get_sphere(args.sphere) b_matrix = get_b_matrix(order, sphere, args.sh_basis) for index in ndindex(data.shape[:-1]): if mask[index]: if np.isnan(data[index]).any(): nufo_map[index] = 0 afd_map[index] = 0 else: maximas, afd, _ = get_maximas( data[index], sphere, b_matrix, args.r_threshold, args.at) # sf = np.dot(data[index], B.T) n = min(npeaks, maximas.shape[0]) nufo_map[index] = maximas.shape[0] if n == 0: afd_map[index] = 0.0 nufo_map[index] = 0.0 else: afd_map[index] = afd.max() peaks_dirs[index][:n] = maximas[:n] # sum of all coefficients, sqrt(power spectrum) # sum C^2 = sum fODF^2 afd_sum[index] = np.sqrt(np.dot(data[index], data[index])) # sum of all peaks contributions to the afd # integral of all the lobes. Numerical sum. # With an infinite number of SH, this should == to afd_sum # sf[np.nonzero(sf < args.at)] = 0. # afd_sum[index] = sf.sum()/n*4*np.pi/B.shape[0]x return nufo_map, afd_map, afd_sum, peaks_dirs
def afd_and_rd_sums_along_streamlines(streamlines, fodf_data, fodf_basis, jump): order = find_order_from_nb_coeff(fodf_data) sphere = get_repulsion200_sphere() b_matrix, _, n = get_b_matrix(order, sphere, fodf_basis, return_all=True) legendre0_at_n = lpn(order, 0)[0][n] sphere_norm = np.linalg.norm(sphere.vertices) if sphere_norm == 0: raise ValueError( "Norm of {} triangulated sphere is 0.".format('repulsion200')) afd_sum_map = np.zeros(shape=fodf_data.shape[:-1]) rd_sum_map = np.zeros(shape=fodf_data.shape[:-1]) count_map = np.zeros(shape=fodf_data.shape[:-1]) for streamline in streamlines: for point_idx, (p0, p1) in enumerate(pairwise(streamline)): if point_idx % jump != 0: continue closest_vertex_idx = _nearest_neighbor_idx_on_sphere( p1 - p0, sphere, sphere_norm) if closest_vertex_idx == -1: # Points were identical so skip them continue vox_idx = _get_nearest_voxel_index(p0, p1) b_at_idx = b_matrix[closest_vertex_idx] fodf_at_index = fodf_data[vox_idx] afd_val = np.dot(b_at_idx, fodf_at_index) p_matrix = np.eye(fodf_at_index.shape[0]) * legendre0_at_n rd_val = np.dot(np.dot(b_at_idx.T, p_matrix), fodf_at_index) afd_sum_map[vox_idx] += afd_val rd_sum_map[vox_idx] += rd_val count_map[vox_idx] += 1 return afd_sum_map, rd_sum_map, count_map
def afd_and_rd_sums_along_streamlines(sft, fodf, fodf_basis, length_weighting): """ Compute the mean Apparent Fiber Density (AFD) and mean Radial fODF (radfODF) maps along a bundle. Parameters ---------- sft : StatefulTractogram StatefulTractogram containing the streamlines needed. fodf : nibabel.image fODF with shape (X, Y, Z, #coeffs). #coeffs depend on the sh_order. fodf_basis : string Has to be descoteaux07 or tournier07. length_weighting : bool If set, will weigh the AFD values according to segment lengths. Returns ------- afd_sum_map : np.array AFD map. rd_sum_map : np.array fdAFD map. weight_map : np.array Segment lengths. """ sft.to_vox() sft.to_corner() fodf_data = np.asanyarray(fodf.dataobj) order = find_order_from_nb_coeff(fodf_data) sphere = get_sphere('repulsion724') b_matrix, _, n = get_b_matrix(order, sphere, fodf_basis, return_all=True) legendre0_at_n = lpn(order, 0)[0][n] sphere_norm = np.linalg.norm(sphere.vertices) afd_sum_map = np.zeros(shape=fodf_data.shape[:-1]) rd_sum_map = np.zeros(shape=fodf_data.shape[:-1]) weight_map = np.zeros(shape=fodf_data.shape[:-1]) p_matrix = np.eye(fodf_data.shape[3]) * legendre0_at_n all_crossed_indices = grid_intersections(sft.streamlines) for crossed_indices in all_crossed_indices: segments = crossed_indices[1:] - crossed_indices[:-1] seg_lengths = np.linalg.norm(segments, axis=1) # Remove points where the segment is zero. # This removes numpy warnings of division by zero. non_zero_lengths = np.nonzero(seg_lengths)[0] segments = segments[non_zero_lengths] seg_lengths = seg_lengths[non_zero_lengths] test = np.dot(segments, sphere.vertices.T) test2 = (test.T / (seg_lengths * sphere_norm)).T angles = np.arccos(test2) sorted_angles = np.argsort(angles, axis=1) closest_vertex_indices = sorted_angles[:, 0] # Those starting points are used for the segment vox_idx computations strl_start = crossed_indices[non_zero_lengths] vox_indices = (strl_start + (0.5 * segments)).astype(int) normalization_weights = np.ones_like(seg_lengths) if length_weighting: normalization_weights = seg_lengths / np.linalg.norm( fodf.header.get_zooms()[:3]) for vox_idx, closest_vertex_index, norm_weight in zip( vox_indices, closest_vertex_indices, normalization_weights): vox_idx = tuple(vox_idx) b_at_idx = b_matrix[closest_vertex_index] fodf_at_index = fodf_data[vox_idx] afd_val = np.dot(b_at_idx, fodf_at_index) rd_val = np.dot(np.dot(b_at_idx.T, p_matrix), fodf_at_index) afd_sum_map[vox_idx] += afd_val * norm_weight rd_sum_map[vox_idx] += rd_val * norm_weight weight_map[vox_idx] += norm_weight rd_sum_map[rd_sum_map < 0.] = 0. return afd_sum_map, rd_sum_map, weight_map
def _get_direction_getter(args): odf_data = nib.load(args.in_odf).get_fdata(dtype=np.float32) sphere = HemiSphere.from_sphere(get_sphere(args.sphere)) theta = get_theta(args.theta, args.algo) non_zeros_count = np.count_nonzero(np.sum(odf_data, axis=-1)) non_first_val_count = np.count_nonzero(np.argmax(odf_data, axis=-1)) if args.algo in ['det', 'prob']: if non_first_val_count / non_zeros_count > 0.5: logging.warning('Input detected as peaks. Input should be' 'fodf for det/prob, verify input just in case.') if args.algo == 'det': dg_class = DeterministicMaximumDirectionGetter else: dg_class = ProbabilisticDirectionGetter return dg_class.from_shcoeff( shcoeff=odf_data, max_angle=theta, sphere=sphere, basis_type=args.sh_basis, relative_peak_threshold=args.sf_threshold) elif args.algo == 'eudx': # Code for type EUDX. We don't use peaks_from_model # because we want the peaks from the provided sh. odf_shape_3d = odf_data.shape[:-1] dg = PeaksAndMetrics() dg.sphere = sphere dg.ang_thr = theta dg.qa_thr = args.sf_threshold # Heuristic to find out if the input are peaks or fodf # fodf are always around 0.15 and peaks around 0.75 if non_first_val_count / non_zeros_count > 0.5: logging.info('Input detected as peaks.') nb_peaks = odf_data.shape[-1] // 3 slices = np.arange(0, 15+1, 3) peak_values = np.zeros(odf_shape_3d+(nb_peaks,)) peak_indices = np.zeros(odf_shape_3d+(nb_peaks,)) for idx in np.argwhere(np.sum(odf_data, axis=-1)): idx = tuple(idx) for i in range(nb_peaks): peak_values[idx][i] = np.linalg.norm( odf_data[idx][slices[i]:slices[i+1]], axis=-1) peak_indices[idx][i] = sphere.find_closest( odf_data[idx][slices[i]:slices[i+1]]) dg.peak_dirs = odf_data else: logging.info('Input detected as fodf.') npeaks = 5 peak_dirs = np.zeros((odf_shape_3d + (npeaks, 3))) peak_values = np.zeros((odf_shape_3d + (npeaks, ))) peak_indices = np.full((odf_shape_3d + (npeaks, )), -1, dtype='int') b_matrix = get_b_matrix( find_order_from_nb_coeff(odf_data), sphere, args.sh_basis) for idx in np.argwhere(np.sum(odf_data, axis=-1)): idx = tuple(idx) directions, values, indices = get_maximas(odf_data[idx], sphere, b_matrix, args.sf_threshold, 0) if values.shape[0] != 0: n = min(npeaks, values.shape[0]) peak_dirs[idx][:n] = directions[:n] peak_values[idx][:n] = values[:n] peak_indices[idx][:n] = indices[:n] dg.peak_dirs = peak_dirs dg.peak_values = peak_values dg.peak_indices = peak_indices return dg