def PlotSkeleton(seg_name, plot_type='node', out_res=(30, 48, 48)): print('Read skeletons') skeletons = ReadSkeletons(seg_name, skeleton_algorithm='thinning', downsample_resolution=out_res, read_edges=True) print('Plot skeletons') node_list = skeletons[1].get_nodes() nodes = np.stack(node_list).astype(float) junction_idx = skeletons[1].get_junctions() junctions = nodes[junction_idx, :] ends = skeletons[1].get_ends() jns_ends = np.vstack([junctions, ends]) IX, IY, IZ = 2, 1, 0 ipv.figure() if plot_type == 'nodes': nodes = ipv.scatter(nodes[:,IX], nodes[:,IY], nodes[:,IZ], \ size=0.5, marker='sphere', color='blue') elif plot_type == 'edges': edges = skeletons[1].get_edges().astype(float) for e1, e2 in edges: if not ((e1[IX] == e2[IX]) and (e1[IY] == e2[IY]) and (e1[IZ] == e2[IZ])): ipv.plot([e1[IX], e2[IX]], [e1[IY], e2[IY]], [e1[IZ], e2[IZ]], \ color='blue') jns = ipv.scatter(jns_ends[:,IX], jns_ends[:,IY], jns_ends[:,IZ], \ size=0.85, marker='sphere', color='red') ipv.pylab.style.axes_off() ipv.pylab.style.box_off() ipv.save(seg_name + '_skel.html')
def plot_annulus( self, detector1, detector2, projection="astro degrees mollweide", ax=None, radius=None, center=None, threeD=True, **kwargs, ): if not threeD: if ax is None: skw_dict = create_skw_dict(projection, center, radius) fig, ax = plt.subplots(subplot_kw=skw_dict) else: fig = ax.get_figure() # compute the annulus for this set of detectors cart_vec, spherical_vec, theta = self.calculate_annulus( detector1, detector2) if not threeD: circle = SphericalCircle( spherical_vec, theta, vertex_unit=u.deg, resolution=5000, # edgecolor=color, fc="none", transform=ax.get_transform("icrs"), **kwargs, ) ax.add_patch(circle) return fig else: # get all the threeD point xyz = get_3d_circle(spherical_vec, theta, radius=self._grb_radius, resolution=1000) ipv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], **kwargs)
def spherical_galaxy_orbit(orbit_x, orbit_y, orbit_z, N_stars=100, sigma_r=1, orbit_visible=False, orbit_line_interpolate=5, N_star_orbits=10, color=[255, 220, 200], size_star=1, scatter_kwargs={}): """Create a fake galaxy around the points orbit_x/y/z with N_stars around it""" if orbit_line_interpolate > 1: x = np.linspace(0, 1, len(orbit_x)) x_smooth = np.linspace(0, 1, len(orbit_x) * orbit_line_interpolate) kind = 'quadratic' orbit_x_line = scipy.interpolate.interp1d(x, orbit_x, kind)(x_smooth) orbit_y_line = scipy.interpolate.interp1d(x, orbit_y, kind)(x_smooth) orbit_z_line = scipy.interpolate.interp1d(x, orbit_z, kind)(x_smooth) else: orbit_x_line = orbit_x orbit_y_line = orbit_y orbit_z_line = orbit_z line = ipv.plot(orbit_x_line, orbit_y_line, orbit_z_line, visible=orbit_visible) x = np.repeat(orbit_x, N_stars).reshape((-1, N_stars)) y = np.repeat(orbit_y, N_stars).reshape((-1, N_stars)) z = np.repeat(orbit_z, N_stars).reshape((-1, N_stars)) xr, yr, zr = np.random.normal(0, scale=sigma_r, size=(3, N_stars)) # + r = np.sqrt(xr**2 + yr**2 + zr**2) for i in range(N_stars): a = np.linspace(0, 1, x.shape[0]) * 2 * np.pi * N_star_orbits xo = r[i] * np.sin(a) yo = r[i] * np.cos(a) zo = a * 0 xo, yo, zo = np.dot(_randomSO3(), [xo, yo, zo]) #print(x.shape, xo.shape) x[:, i] += xo y[:, i] += yo z[:, i] += zo sprite = ipv.scatter(x, y, z, texture=radial_sprite((64, 64), color), marker='square_2d', size=size_star, **scatter_kwargs) with sprite.material.hold_sync(): sprite.material.blending = pythreejs.BlendingMode.CustomBlending sprite.material.blendSrc = pythreejs.BlendFactors.SrcColorFactor sprite.material.blendDst = pythreejs.BlendFactors.OneFactor sprite.material.blendEquation = 'AddEquation' sprite.material.transparent = True sprite.material.depthWrite = False sprite.material.alphaTest = 0.1 return sprite, line
def hpo_animate(particles, particleSizes, particleColors, paramRanges, nTimesteps=1): nParticles = particles.shape[1] colorStack = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .9 colorStackLines = np.ones((nTimesteps, nTimesteps * nParticles, 4)) * .5 for iTimestep in range(nTimesteps): colorStack[iTimestep, :, 0:3] = numpy.matlib.repmat(particleColors[0, :, :], nTimesteps, 1) colorStackLines[iTimestep, :, 0:3] = numpy.matlib.repmat(particleColors[0, :, :], nTimesteps, 1) colorStackLines[iTimestep, :, 3] = .6 # alpha ipv.figure() pplot = ipv.scatter(particles[0:nTimesteps, :, 0], particles[0:nTimesteps, :, 1], particles[0:nTimesteps, :, 2], marker='sphere', size=particleSizes, color=colorStack[:, :, :]) for iParticle in range(nParticles): plines = ipv.plot(particles[0:nTimesteps, iParticle, 0], particles[0:nTimesteps, iParticle, 1], particles[0:nTimesteps, iParticle, 2], color=colorStackLines[:, iParticle, :]) ipv.animation_control([pplot], interval=600) ipv.xlim(paramRanges[0][1] - .5, paramRanges[0][2] + .5) ipv.ylim(paramRanges[1][1] - .1, paramRanges[1][2] + .1) ipv.zlim(paramRanges[2][1] - .1, paramRanges[2][2] + .1) ipv.show()
def viz_particle_trails(swarm, topN=None, globalBestIndicatorFlag=True, tabbedPlot=False): startTime = time.time() targetMedianParticleSize = 3 nTreesDescaler = np.median(swarm.nTreesHistory) / targetMedianParticleSize minParticleSize = 2.5 maxParticleSize = 10 ipvFig = ipv.figure(width=ipvPlotWidth, height=ipvPlotHeight) # find top performing particles to show additional detail [ size scaled based on nTrees ] if topN is None: topN = swarm.nParticles topN = np.max((1, topN)) particleMaxes = {} for key, iParticle in swarm.particles.items(): if len(iParticle.testDataPerfHistory): particleMaxes[key] = max(iParticle.testDataPerfHistory) else: particleMaxes[key] = 0 sortedParticles = pd.DataFrame.from_dict( particleMaxes, orient='index').sort_values(by=0, ascending=False) topParticles = sortedParticles.index[0:np.min((np.max((topN, 1)), swarm.nParticles))] for iParticle in range(swarm.nParticles): if len(swarm.particles[iParticle].posHistory): particlePosHistory = np.matrix( swarm.particles[iParticle].posHistory) # plot markers along the particle's journey over the epoch sequence if iParticle in topParticles: # draw top particles with their unique color and scaled by the number of trees sortedIndex = np.where(topParticles == iParticle)[0][0] particleColor = rapidsColorsHex[sortedIndex % nRapidsColors] particleSizes = {} for iEval in range(swarm.particles[iParticle].nEvals): particleSizes[iEval] = np.clip( swarm.particles[iParticle].nTreesHistory[iEval] / nTreesDescaler, minParticleSize, maxParticleSize) #import pdb; pdb.set_trace() ipv.scatter(particlePosHistory[:, 0].squeeze(), particlePosHistory[:, 1].squeeze(), particlePosHistory[:, 2].squeeze(), size=np.array(list(particleSizes.values())), marker='sphere', color=particleColor, grow_limits=False) else: # draw non-top particle locations in gray particleColor = (.7, .7, .7, .9) ipv.scatter(particlePosHistory[:, 0].squeeze(), particlePosHistory[:, 1].squeeze(), particlePosHistory[:, 2].squeeze(), size=1.5, marker='sphere', color=particleColor, grow_limits=False) # plot line trajectory [ applies to both top and non-top particles ] ipv.plot(particlePosHistory[:, 0].squeeze(), particlePosHistory[:, 1].squeeze(), particlePosHistory[:, 2].squeeze(), color=particleColor) # draw an intersecting set of lines/volumes to indicate the location of the best particle / parameter-set if globalBestIndicatorFlag: bestXYZ = np.matrix(swarm.globalBest['params']) ipv.scatter(bestXYZ[:, 0], bestXYZ[:, 1], bestXYZ[:, 2], color=rapidsColorsHex[1], size=3, marker='box') data = np.ones((100, 2, 2)) xSpan = np.clip( (swarm.paramRanges[0][2] - swarm.paramRanges[0][1]) / 200, .007, 1) ySpan = np.clip( (swarm.paramRanges[1][2] - swarm.paramRanges[1][1]) / 200, .007, 1) zSpan = np.clip( (swarm.paramRanges[2][2] - swarm.paramRanges[2][1]) / 200, .007, 1) xMin = swarm.globalBest['params'][0] - xSpan xMax = swarm.globalBest['params'][0] + xSpan yMin = swarm.globalBest['params'][1] - ySpan yMax = swarm.globalBest['params'][1] + ySpan zMin = swarm.globalBest['params'][2] - zSpan zMax = swarm.globalBest['params'][2] + zSpan ipv.volshow(data=data.T, opacity=.15, level=[0.25, 0., 0.25], extent=[[xMin, xMax], [yMin, yMax], [swarm.paramRanges[2][1], swarm.paramRanges[2][2]]], controls=False) ipv.volshow(data=data.T, opacity=.15, level=[0.25, 0., 0.25], extent=[[swarm.paramRanges[0][1], swarm.paramRanges[0][2]], [yMin, yMax], [zMin, zMax]], controls=False) comboBox = append_label_buttons(swarm, ipvFig) if tabbedPlot: return comboBox display(comboBox) return None
def plot_in_space( position_interpolator, time, show_detector_pointing=False, show_earth=True, show_sun=False, show_moon=False, background_color="#01000F", detector_scaling_factor=20000.0, show_stars=False, show_orbit=True, realistic=True, earth_time="night", sky_points=None, min_distance=8000, ): """ Plot Fermi in Space! :param position_interpolator: :param time: :param show_detector_pointing: :param show_earth: :param show_sun: :param show_moon: :param background_color: :param detector_scaling_factor: :returns: :rtype: """ fig = ipv.figure(width=800, height=600) ipv.pylab.style.box_off() ipv.pylab.style.axes_off() ipv.pylab.style.set_style_dark() ipv.pylab.style.background_color(background_color) distances = [min_distance] if sky_points is not None: sky_points = np.atleast_1d(sky_points) if show_orbit: tmin, tmax = position_interpolator.minmax_time() tt = np.linspace(tmin, tmax, 500) sc_pos = position_interpolator.sc_pos(tt) ipv.plot(sc_pos[:, 0], sc_pos[:, 1], sc_pos[:, 2], lw=0.5) if show_earth: earth = Earth( earth_time=earth_time, realistic=realistic, astro_time=position_interpolator.astro_time(time), ) earth.plot() if show_sun: sun_pos = position_interpolator.sun_position(time) x, y, z = sun_pos.cartesian.xyz.to("km").value sol = Sol(x, y, z) distances.append(compute_distance(x, y, z, sol.radius)) sol.plot() if show_moon: moon_pos = position_interpolator.moon_position(time) x, y, z = moon_pos.cartesian.xyz.to("km").value moon = Moon(x, y, z, realistic=True) distances.append(compute_distance(x, y, z, moon.radius)) moon.plot() # now get fermi position sx, sy, sz = position_interpolator.sc_pos(time) fermi_real = Fermi( position_interpolator.quaternion(time), sc_pos=position_interpolator.sc_pos(time), transform_to_space=True, ) fermi_real.plot_fermi_ipy() if show_detector_pointing: distances.append(detector_scaling_factor) gbm = GBM( position_interpolator.quaternion(time), position_interpolator.sc_pos(time), ) for k, v in gbm.detectors.items(): x, y, z = v.center_icrs.cartesian.xyz.value * max(distances) # x_line = np.array([sx, sx + x]) # y_line = np.array([sy, sy + y]) # z_line = np.array([sz, sz + z]) color = _det_colors[k] cone = Cone(sx, sy, sz, sx + x, sy + y, sz + z, _open_angle) cone.plot(color=color) # ipv.pylab.plot(x_line, y_line, z_line, color=color) if sky_points is not None: for sp in sky_points: sp.plot(sx, sy, sz, max(distances)) # distances.append(sp.distance) if show_stars: sf = StarField(n_stars=100, distance=max(distances) - 2) sf.plot() # move the camera here fig.camera.position = tuple( position_interpolator.sc_pos(time) / np.linalg.norm(position_interpolator.sc_pos(time)) ) ipv.xyzlim(max(distances)) ipv.show() return fig
def plot_brain(brain, surface='dots', nodes=True, node_colors=False, node_groups=None, surface_color=None, node_color='red', network=None, dot_size=0.1, dot_color='gray', min_fibers=10, max_fibers=500, lowest_cmap_color=0.2, highest_cmap_color=0.7, cmap='rocket', background='light'): import ipyvolume as ipv if surface_color is None: if surface == 'dots': surface_color = 'gray' elif surface == 'full': surface_color = 'orange' if isinstance(node_colors, bool) and node_colors: node_colors = ['red', 'green', 'blue', 'violet', 'yellow'] if node_colors and node_groups is None: node_groups = brain['nodes']['label'] fig = ipv.figure() # plot surface x, y, z = [brain['surface'][key] for key in list('xyz')] if surface == 'dots': ipv.scatter(x, y, z, marker='box', color=dot_color, size=dot_size) elif surface == 'full': ipv.plot_trisurf(x, y, z, triangles=brain['surface']['tri'], color=surface_color) # plot nodes if nodes: xyz = brain['nodes']['xyz'] if node_colors: for label_idx, color in zip(np.unique(node_groups), node_colors): mask = node_groups == label_idx ipv.scatter(xyz[mask, 0], xyz[mask, 1], xyz[mask, 2], marker='sphere', color=color, size=1.5) else: ipv.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], marker='sphere', color=node_color, size=1.5) # plot connections if network is not None: x, y, z = brain['nodes']['xyz'].T scaling = highest_cmap_color - lowest_cmap_color min_fibers_log = np.log(min_fibers) max_fibers_log = np.log(max_fibers) if hasattr(plt.cm, cmap): cmp = getattr(plt.cm, cmap) else: import seaborn as sns cmp = getattr(sns.cm, cmap) with fig.hold_sync(): for ii in range(89): for jj in range(ii, 90): if network[ii, jj] > min_fibers: float_color = (min( np.log((network[ii, jj] - min_fibers)) / (max_fibers_log - min_fibers_log), 1.) * scaling + lowest_cmap_color) line_color = cmp(float_color) ipv.plot(x[[ii, jj]], y[[ii, jj]], z[[ii, jj]], color=line_color[:3]) ipv.squarelim() ipv.style.use([background, 'minimal']) ipv.show() return fig
def plot_all_annuli( self, projection="astro degrees mollweide", radius=None, center=None, cmap="Set1", threeD=True, use_all=False, **kwargs, ): if not threeD: assert projection in [ "astro degrees aitoff", "astro degrees mollweide", "astro hours aitoff", "astro hours mollweide", "astro globe", "astro zoom", ] skw_dict = dict(projection=projection) if projection in ["astro globe", "astro zoom"]: assert center is not None, "you must specify a center" skw_dict = dict(projection=projection, center=center) if projection == "astro zoom": assert radius is not None, "you must specify a radius" skw_dict = dict(projection=projection, center=center, radius=radius) fig, ax = plt.subplots(subplot_kw=skw_dict) else: fig = ipv.figure() ipv.pylab.style.box_off() ipv.pylab.style.axes_off() ax = None # get the colors to use if use_all: n_verts = self._n_detectors * (self._n_detectors - 1) / 2 colors = mpl_color.colors_from_cmap(int(n_verts), cmap=cmap) for i, (d1, d2) in enumerate(combinations(self._detectors.keys(), 2)): _ = self.plot_annulus( d1, d2, projection=projection, center=center, radius=radius, ax=ax, edgecolor=colors[i], threeD=threeD, color=colors[i], **kwargs, ) if threeD: loc1 = self._detectors[d1].location.get_cartesian_coord( ).xyz.value loc2 = self._detectors[d2].location.get_cartesian_coord( ).xyz.value ipv.plot( np.array([loc1[0], loc2[0]]), np.array([loc1[1], loc2[1]]), np.array([loc1[2], loc2[2]]), color=colors[i], ) else: colors = mpl_color.colors_from_cmap(len(self._detectors) - 1, cmap=cmap) det_list = list(self._detectors.keys()) d1 = det_list[0] for i, d2 in enumerate(det_list[1:]): _ = self.plot_annulus( d1, d2, projection=projection, center=center, radius=radius, ax=ax, edgecolor=colors[i], threeD=threeD, color=colors[i], **kwargs, ) if threeD: loc1 = self._detectors[d1].location.get_cartesian_coord( ).xyz.value loc2 = self._detectors[d2].location.get_cartesian_coord( ).xyz.value ipv.plot( np.array([loc1[0], loc2[0]]), np.array([loc1[1], loc2[1]]), np.array([loc1[2], loc2[2]]), color=colors[i], ) if threeD: ipv.scatter( *(self._grb_radius * self._grb.location.get_cartesian_coord("gcrs").xyz.value / np.linalg.norm( self._grb.location.get_cartesian_coord("gcrs").xyz.value) )[np.newaxis].T, marker="sphere", color="green", ) ipv.show() return fig