def show_weighted_tractography(folder_name, vec_vols, s_list, bundle_short, direction, downsamp=1): s_img = rf'{folder_name}\streamlines\ax_fa_corr_{bundle_short}_{direction}.png' if downsamp != 1: vec_vols = vec_vols[::downsamp] s_list = s_list[::downsamp] vec_vols.append(1) vec_vols.append(-1) cmap = create_colormap(np.asarray(vec_vols), name='seismic') vec_vols = vec_vols[:-2] cmap = cmap[:-2] print(min(vec_vols), max(vec_vols)) #w_actor = actor.line(s_list, vec_vols, linewidth=1.2, lookup_colormap=cmap) w_actor = actor.line(s_list, cmap, linewidth=1.2) r = window.Scene() #r.SetBackground(*window.colors.white) r.add(w_actor) #r.add(bar) window.show(r) r.set_camera(r.camera_info()) window.record(r, out_path=s_img, size=(800, 800))
def update_surface(x, y, equation, cmap_name='viridis'): # z is the function F i.e. F(x, y, t) z = eval(equation) xyz = np.vstack([x, y, z]).T # creating the colormap v = np.copy(z) v /= np.max(np.abs(v), axis=0) colors = colormap.create_colormap(v, name=cmap_name) return xyz, colors
def _generate_color_for_vertices(self, sf): """ Get array of all vertices colors. """ if self.global_cm: if self.colormap is None: raise IOError("if global_cm=True, colormap must be defined.") else: all_colors = create_colormap(sf.ravel(), self.colormap) * 255 elif self.colormap is not None: if isinstance(self.colormap, str): # Map ODFs values [min, max] to [0, 1] for each ODF range_sf = sf.max(axis=-1) - sf.min(axis=-1) rescaled = sf - sf.min(axis=-1, keepdims=True) rescaled[range_sf > 0] /= range_sf[range_sf > 0][..., None] all_colors =\ create_colormap(rescaled.ravel(), self.colormap) * 255 else: all_colors = np.tile(np.array(self.colormap).reshape(1, 3), (sf.shape[0]*sf.shape[1], 1)) else: all_colors = np.tile(np.abs(self.vertices)*255, (len(sf), 1)) return all_colors.astype(np.uint8)
def _odf_slicer_mapper(odfs, affine=None, mask=None, sphere=None, scale=2.2, norm=True, radial_scale=True, opacity=1., colormap='plasma', global_cm=False): """ Helper function for slicing spherical fields Parameters ---------- odfs : ndarray 4D array of spherical functions affine : array 4x4 transformation array from native coordinates to world coordinates mask : ndarray 3D mask sphere : Sphere a sphere scale : float Distance between spheres. norm : bool Normalize `sphere_values`. radial_scale : bool Scale sphere points according to odf values. opacity : float Takes values from 0 (fully transparent) to 1 (opaque) colormap : None or str If None then white color is used. Otherwise the name of colormap is given. Matplotlib colormaps are supported (e.g., 'inferno'). global_cm : bool If True the colormap will be applied in all ODFs. If False it will be applied individually at each voxel (default False). Returns --------- mapper : vtkPolyDataMapper Spheres mapper """ if mask is None: mask = np.ones(odfs.shape[:3]) ijk = np.ascontiguousarray(np.array(np.nonzero(mask)).T) if len(ijk) == 0: return None if affine is not None: ijk = np.ascontiguousarray(apply_affine(affine, ijk)) faces = np.asarray(sphere.faces, dtype=int) vertices = sphere.vertices all_xyz = [] all_faces = [] all_ms = [] for (k, center) in enumerate(ijk): m = odfs[tuple(center.astype(np.int))].copy() if norm: m /= np.abs(m).max() if radial_scale: xyz = vertices * m[:, None] else: xyz = vertices.copy() all_xyz.append(scale * xyz + center) all_faces.append(faces + k * xyz.shape[0]) all_ms.append(m) all_xyz = np.ascontiguousarray(np.concatenate(all_xyz)) all_xyz_vtk = numpy_support.numpy_to_vtk(all_xyz, deep=True) all_faces = np.concatenate(all_faces) all_faces = np.hstack((3 * np.ones((len(all_faces), 1)), all_faces)) ncells = len(all_faces) all_faces = np.ascontiguousarray(all_faces.ravel(), dtype='i8') all_faces_vtk = numpy_support.numpy_to_vtkIdTypeArray(all_faces, deep=True) if global_cm: all_ms = np.ascontiguousarray(np.concatenate(all_ms), dtype='f4') points = vtk.vtkPoints() points.SetData(all_xyz_vtk) cells = vtk.vtkCellArray() cells.SetCells(ncells, all_faces_vtk) if colormap is not None: if global_cm: cols = create_colormap(all_ms.ravel(), colormap) else: cols = np.zeros((ijk.shape[0], ) + sphere.vertices.shape, dtype='f4') for k in range(ijk.shape[0]): tmp = create_colormap(all_ms[k].ravel(), colormap) cols[k] = tmp.copy() cols = np.ascontiguousarray(np.reshape( cols, (cols.shape[0] * cols.shape[1], cols.shape[2])), dtype='f4') vtk_colors = numpy_support.numpy_to_vtk( np.asarray(255 * cols), deep=True, array_type=vtk.VTK_UNSIGNED_CHAR) vtk_colors.SetName("Colors") polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(cells) if colormap is not None: polydata.GetPointData().SetScalars(vtk_colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) return mapper
def structural_plotting(conn_matrix, uatlas, streamlines_mni, template_mask, interactive=False): """ :param conn_matrix: :param uatlas: :param streamlines_mni: :param template_mask: :param interactive: :return: """ import nibabel as nib import numpy as np import networkx as nx import os import pkg_resources from nibabel.affines import apply_affine from fury import actor, window, colormap, ui from dipy.tracking.utils import streamline_near_roi from nilearn.plotting import find_parcellation_cut_coords from nilearn.image import resample_to_img from pynets.thresholding import normalize from pynets.nodemaker import mmToVox ch2better_loc = pkg_resources.resource_filename( "pynets", "templates/ch2better.nii.gz") # Instantiate scene r = window.Renderer() # Set camera r.set_camera(position=(-176.42, 118.52, 128.20), focal_point=(113.30, 128.31, 76.56), view_up=(0.18, 0.00, 0.98)) # Load atlas rois atlas_img = nib.load(uatlas) atlas_img_data = atlas_img.get_data() # Collapse list of connected streamlines for visualization streamlines = nib.streamlines.load(streamlines_mni).streamlines parcels = [] i = 0 for roi in np.unique(atlas_img_data)[1:]: parcels.append(atlas_img_data == roi) i = i + 1 # Add streamlines as cloud of 'white-matter' streamlines_actor = actor.line(streamlines, colormap.create_colormap(np.ones( [len(streamlines)]), name='Greys_r', auto=True), lod_points=10000, depth_cue=True, linewidth=0.2, fake_tube=True, opacity=1.0) r.add(streamlines_actor) # Creat palette of roi colors and add them to the scene as faint contours roi_colors = np.random.rand(int(np.max(atlas_img_data)), 3) parcel_contours = [] i = 0 for roi in np.unique(atlas_img_data)[1:]: include_roi_coords = np.array(np.where(atlas_img_data == roi)).T x_include_roi_coords = apply_affine(np.eye(4), include_roi_coords) bool_list = [] for sl in streamlines: bool_list.append( streamline_near_roi(sl, x_include_roi_coords, tol=1.0, mode='either_end')) if sum(bool_list) > 0: print('ROI: ' + str(i)) parcel_contours.append( actor.contour_from_roi(atlas_img_data == roi, color=roi_colors[i], opacity=0.2)) else: pass i = i + 1 for vol_actor in parcel_contours: r.add(vol_actor) # Get voxel coordinates of parcels and add them as 3d spherical centroid nodes [coords, labels] = find_parcellation_cut_coords(atlas_img, background_label=0, return_labels=True) coords_vox = [] for i in coords: coords_vox.append(mmToVox(atlas_img.affine, i)) coords_vox = list(set(list(tuple(x) for x in coords_vox))) # Build an edge list of 3d lines G = nx.from_numpy_array(normalize(conn_matrix)) for i in G.nodes(): nx.set_node_attributes(G, {i: coords_vox[i]}, labels[i]) G.remove_nodes_from(list(nx.isolates(G))) G_filt = nx.Graph() fedges = filter(lambda x: G.degree()[x[0]] > 0 and G.degree()[x[1]] > 0, G.edges()) G_filt.add_edges_from(fedges) coord_nodes = [] for i in range(len(G.edges())): edge = list(G.edges())[i] [x, y] = edge x_coord = list(G.nodes[x].values())[0] x_label = list(G.nodes[x].keys())[0] l_x = actor.label(text=str(x_label), pos=x_coord, scale=(1, 1, 1), color=(50, 50, 50)) r.add(l_x) y_coord = list(G.nodes[y].values())[0] y_label = list(G.nodes[y].keys())[0] l_y = actor.label(text=str(y_label), pos=y_coord, scale=(1, 1, 1), color=(50, 50, 50)) r.add(l_y) coord_nodes.append(x_coord) coord_nodes.append(y_coord) c = actor.line([(x_coord, y_coord)], window.colors.coral, linewidth=100 * (float(G.get_edge_data(x, y)['weight'])) ^ 2) r.add(c) point_actor = actor.point(list(set(coord_nodes)), window.colors.grey, point_radius=0.75) r.add(point_actor) # Load glass brain template and resample to MNI152_2mm brain template_img = nib.load(ch2better_loc) template_target_img = nib.load(template_mask) res_brain_img = resample_to_img(template_img, template_target_img) template_img_data = res_brain_img.get_data().astype('bool') template_actor = actor.contour_from_roi(template_img_data, color=(50, 50, 50), opacity=0.05) r.add(template_actor) # Show scene if interactive is True: window.show(r, size=(600, 600), reset_camera=False) else: fig_path = os.path.dirname(streamlines_mni) + '/3d_connectome_fig.png' window.record(r, out_path=fig_path, size=(600, 600)) return
win_callback.win_size = current_size win_callback.panel = panel # Load atlas rois atlas_img = nib.load(atlas) dims = atlas_img.shape zooms = atlas_img.get_header().get_zooms() atlas_img_data = atlas_img.get_data() # Collapse list of connected streamlines for visualization streamlines = nib.streamlines.load(streamlines_mni).streamlines parcels = [atlas_img_data==roi for roi in np.unique(atlas_img_data)[1:]] # Add streamlines as cloud of 'white-matter' streamlines_actor = actor.line(streamlines, colormap.create_colormap(np.ones([len(streamlines)]), name='Greys_r', auto=True), lod_points=10000, depth_cue=True, linewidth=0.2, fake_tube=True, opacity=1.0) scene.add(streamlines_actor) visible_callback.streamlines_actor = streamlines_actor # Creat palette of roi colors and add them to the scene as faint contours roi_colors = np.random.rand(int(np.max(atlas_img_data)), 3) parcel_contours = [] # i = 0 # for roi in np.unique(atlas_img_data)[1:]: # include_roi_coords = np.array(np.where(atlas_img_data==roi)).T # x_include_roi_coords = apply_affine(np.eye(4), include_roi_coords) # bool_list = [] # for sl in streamlines: # bool_list.append(streamline_near_roi(sl, x_include_roi_coords, tol=1.0, mode='either_end')) # if sum(bool_list) > 0: