def getimage(data, poss, temp, mass, hsml, num, norm, cmap): print('There are', poss.shape[0], 'gas particles in the region') # Set up particle objects P1 = sph.Particles(poss, mass=temp * mass, hsml=hsml) P2 = sph.Particles(poss, mass=mass, hsml=hsml) # Initialise the scene S1 = sph.Scene(P1) S2 = sph.Scene(P2) i = data[num] i['xsize'] = 3840 i['ysize'] = 2160 i['roll'] = 0 S1.update_camera(**i) S2.update_camera(**i) R1 = sph.Render(S1) R2 = sph.Render(S2) R1.set_logscale() R2.set_logscale() img1 = R1.get_image() img2 = R2.get_image() img = img1 - img2 vmax = 7.5 vmin = 3.5 print("gas temperature", np.min(img), np.max(img)) # Convert images to rgb arrays rgb = cmap(norm(img)) return rgb, R1.get_extent()
def myplot(x, y, nb=32, xsize=500, ysize=500): """This function reads in a set of data and smooths it using nearest neighbors summing. It then outputs the smoothed data with a measure of its extent. This output is then inputed to Axes.imshow. :param: x,y two columns of data such as particle positions :param: nb smoothing size. """ xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) x0 = (xmin + xmax) / 2. y0 = (ymin + ymax) / 2. pos = np.zeros([3, len(x)]) pos[0, :] = x pos[1, :] = y w = np.ones(len(x)) P = sph.Particles(pos, w, nb=nb) S = sph.Scene(P) S.update_camera(r='infinity', x=x0, y=y0, z=0, xsize=xsize, ysize=ysize) R = sph.Render(S) R.set_logscale() img = R.get_image() extent = R.get_extent() for i, j in zip(xrange(4), [x0, x0, y0, y0]): extent[i] += j print extent, x0, y0 return img, extent
def getimage_stars(data, poss, mass, hsml, num, max_pixel, cmap, Type="gas"): print('There are', poss.shape[0], 'gas particles in the region') # Set up particle objects P = sph.Particles(poss, mass=mass, hsml=hsml) print(np.min(mass)) # Initialise the scene S = sph.Scene(P) i = data[num] i['xsize'] = 3840 i['ysize'] = 2160 i['roll'] = 0 S.update_camera(**i) R = sph.Render(S) R.set_logscale() img = R.get_image() img = ndimage.gaussian_filter(img, sigma=(3, 3), order=0) if Type == "gas": vmax = 11 vmin = 6 print("gas", np.max(img)) else: vmax = 13 vmin = 7.5 print("star", np.max(img)) # Convert images to rgb arrays rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax)) return rgb, R.get_extent()
def myplot(x, y, nb=32, xsize=500, ysize=500): xmin = np.min(x) xmax = np.max(x) ymin = np.min(y) ymax = np.max(y) print xmin, xmax, ymin, ymax x0 = (xmin+xmax)/2. y0 = (ymin+ymax)/2. pos = np.zeros([3, len(x)]) pos[0,:] = x pos[1,:] = y w = np.ones(len(x)) P = sph.Particles(pos, w, nb=nb) S = sph.Scene(P) S.update_camera(r='infinity', x=x0, y=y0, z=0, xsize=xsize, ysize=ysize) R = sph.Render(S) R.set_logscale() img = R.get_image() extent = R.get_extent() for i, j in zip(xrange(4), [x0,x0,y0,y0]): extent[i] += j #print extent return img, extent
def plot_sph(x: pd.Series, y: pd.Series, w: pd.Series, nb=32, xsize=1000, ysize=1000): x_min = np.min(x) x_max = np.max(x) y_min = np.min(y) y_max = np.max(y) x0 = np.average((x_min, x_max)) y0 = np.average((y_min, y_max)) pos = np.zeros([len(df), 3]) pos[:, 0] = x pos[:, 1] = y w = w.to_numpy() * 100 particles = sph.Particles(pos, mass=w, nb=nb) scene = sph.Scene(particles) scene.update_camera(r="infinity", x=x0, y=y0, z=0, xsize=xsize, ysize=ysize) render = sph.Render(scene) render.set_logscale() img = render.get_image() extent = render.get_extent() for i, j in zip(range(4), [x0, x0, y0, y0]): extent[i] += j return img, extent
def getimage(data, poss, hsml, num, boxsize): print('There are', poss.shape[0], 'dark matter particles in the region') # Set up particle objects P = sph.Particles(poss, mass=np.ones(poss.shape[0]), hsml=hsml) # Initialise the scene S = sph.Scene(P) i = data[num] i['xsize'] = int(boxsize / hsml.max()) i['ysize'] = int(boxsize / hsml.max()) i['roll'] = 0 S.update_camera(**i) R = sph.Render(S) R.set_logscale() img = R.get_image() vmax = 7 vmin = 1 # Get colormaps cmap = cmaps.twilight() print(img.max()) # Convert images to rgb arrays rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax)) return rgb, R.get_extent()
def plot_dist(fig, ax,P,coods,cmap, vmin=1e-4,vmax=None,extent=300, p=0,t=0,roll=0): C = sph.Camera(x=coods[0], y=coods[1], z=coods[2], r='infinity', zoom=1, t=t, p=p, roll=roll, extent=[-extent,extent,-extent,extent], xsize=512, ysize=512) S = sph.Scene(P, Camera=C) R = sph.Render(S) #R.set_logscale() img = R.get_image() # img = img / img.mean() if vmax is None: vmax = img.max() if vmin > vmax: print("vmin larger than vmax! Setting lower") vmin = img.max() / 10 print("vmin,vmax:",vmin,vmax) cNorm = colors.LogNorm(vmin=vmin,vmax=vmax) sm = cm.ScalarMappable(norm=cNorm, cmap=cmap) ax.imshow(img, extent=[-extent,extent,-extent,extent], cmap=cmap, norm=cNorm) return sm,img
def getimage(data, poss, mass, hsml, num, max_pixel, cmap, Type="gas"): print('There are', poss.shape[0], 'gas particles in the region') # Set up particle objects P = sph.Particles(poss, mass=mass, hsml=hsml) print(np.min(mass)) # Initialise the scene S = sph.Scene(P) i = data[num] i['xsize'] = 5000 i['ysize'] = 5000 i['roll'] = 0 S.update_camera(**i) R = sph.Render(S) R.set_logscale() img = R.get_image() if Type == "gas": vmax =11 vmin = 6 print("gas", np.max(img)) # Convert images to rgb arrays rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax)) else: vmax = 21.6 vmin = 15.0 print("star", np.min(img[img != 0]), np.max(img)) rgb = img return rgb, R.get_extent()
def plot_ledlow_contours(t, world2pixel, ngb=12, xsize=500, ysize=500): """ Smooth galaxy positions of Ledlow+ (2005) to get contour lines @param t : astropy.table.Table holding Ledlow data @param world2pixel : aplpy.FITSFigure world2pixel function to map RA,dec coordinates to Chandra mosaic pixels @param ngb : number of neighbours to smooth over @param xsize, ysize: size of the image (resolution?) @return : img, extent """ ra = 15 * astropy.coordinates.Angle(t['RAJ2000'].filled(numpy.nan), unit=u.degree) dec = astropy.coordinates.Angle(t['DEJ2000'].filled(numpy.nan), unit=u.degree) ra, dec = world2pixel(ra, dec) # convert ra, dec to xray mosaic pixel values # Perform kernel density estimate # https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.stats.gaussian_kde.html # X, Y = numpy.mgrid[xmax:xmin:300j, ymin:ymax:3000j] # positions = numpy.vstack([X.ravel(), Y.ravel()]) # values = numpy.vstack([ra, dec]) # kernel = kde.gaussian_kde(values) # Z = numpy.reshape(kernel(positions).T, X.shape) # Z /= ((41.1-40.6)*60*(20.025-19.50)*60) # pyplot.imshow(numpy.rot90(Z), cmap=pyplot.cm.gist_earth_r, # extent=[xmax, xmin, ymin, ymax]) # cset = pyplot.contour(X, Y, Z, colors="w", # levels=numpy.array([1,2,3,5,8,10])*Z.max()/10) # pyplot.clabel(cset, inline=1, fontsize=10) # https://stackoverflow.com/questions/2369492 xmin, xmax = ra.min(), ra.max() ymin, ymax = dec.min(), dec.max() x0 = (xmin + xmax) / 2. y0 = (ymin + ymax) / 2. pos = numpy.zeros([3, len(ra)]) pos[0, :] = ra pos[1, :] = dec w = numpy.ones(len(ra)) P = sphviewer.Particles(pos, w, nb=ngb) S = sphviewer.Scene(P) S.update_camera(r="infinity", x=x0, y=y0, z=0, xsize=xsize, ysize=ysize) R = sphviewer.Render(S) img = R.get_image() extent = R.get_extent() for i, j in zip(xrange(4), [x0, x0, y0, y0]): extent[i] += j img = 10 * img / numpy.max(img) return img, extent
def image(self, x=0., y=0., z=0., theta=45., phi=0., extent=400., resolution=1024, camera_distance='infinity', save=True, show=True, path='/home/arijdav1/Dropbox/phd/figures/sph_pics/'): px_size = extent / float(resolution) # in kpc px_size_pc = px_size * 1e3 self.Scene.update_camera(x=x, y=y, z=z, r=camera_distance, t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) Render = sphviewer.Render(self.Scene) Render.set_logscale() extent = Render.get_extent() img = Render.get_image() if self.property == 'xrays': img += 30. img -= np.log10(px_size_pc ** 2) vmin = np.amin(img[np.isfinite(img)]) vmax = np.amax(img[np.isfinite(img)]) if self.property == 'stars': vmin = 0. if self.property == 'gas': vmin = -0.3 if self.property == 'hotgas': vmin = 0. # if self.property == 'xrays': # vmin = 0. fig = plt.figure(1, figsize=(20, 20)) ax1 = fig.add_subplot(111) im1 = plt.imshow(img, extent=extent, origin='lower', cmap=self.cmap, vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.15) col = plt.colorbar(im1, cax=cax) col.set_label(self.axlab, fontsize=16) if save: plt.savefig(path + 'group' + str(self.groupnumber) + '_' + self.property + '_t%03d' % (theta) + '_p%03d' % ( phi) + '.png') if show: plt.show() plt.close()
def getimage(data, poss, hsml, num, z, cmap): print('There are', poss.shape[0], 'dark matter particles in the region') # Set up particle objects P = sph.Particles(poss, mass=np.ones(poss.shape[0]), hsml=hsml) # Initialise the scene S = sph.Scene(P) i = data[num] i['xsize'] = 3840 i['ysize'] = 2160 i['roll'] = 0 S.update_camera(**i) print("Scene") R = sph.Render(S) print("Render") R.set_logscale() print("Logscale") img = R.get_image() print("Image") print(img.max(), np.percentile(img, 99.99), np.percentile(img, 95), np.percentile(img, 90), np.percentile(img, 67.5), np.percentile(img, 50)) vmax = 6.9 vmin = 0.1 # # Get colormaps # cmap2 = cmr.torch_r(np.linspace(0, 1, 128)) # cmap3 = cmr.swamp(np.linspace(0, 1, 128)) # # # combine them and build a new colormap # colors = np.vstack((cmap2, cmap3)) # cmap = mcolors.LinearSegmentedColormap.from_list('colormap', colors) hex_list = ["#000000", "#590925", "#6c1c55", "#7e2e84", "#ba4051", "#f6511d", "#ffb400", "#f7ec59", "#fbf6ac", "#ffffff"] #cmap = get_continuous_cmap(hex_list, float_list=None) img = ndimage.gaussian_filter(img, sigma=(3, 3), order=0) # Convert images to rgb arrays rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax)) return rgb, R.get_extent()
def __init__(self, pos, mass=None, hsml=None, nb=None, logscale=True, plot=True, min_hsml=None, max_hsml=None, **kwargs): if (mass is None): mass = np.ones(len(pos[0, :])) if (nb == None): self._P = sph.Particles(pos, mass, hsml) else: self._P = sph.Particles(pos, mass, hsml, nb) if ((min_hsml is not None) or (max_hsml is not None)): hsml = self.get_hsml() if (min_hsml is not None): min_hsml = min_hsml else: min_hsml = np.min(hsml) if (max_hsml is not None): max_hsml = max_hsml else: max_hsml = np.max(hsml) hsml = np.clip(hsml, min_hsml, max_hsml) print 'Limiting smoothing lenght to the range [%.3f,%.3f]' % ( min_hsml, max_hsml) self._P.set_hsml(hsml) self._S = sph.Scene(self._P) self._S.update_camera(**kwargs) self._R = sph.Render(self._S) if (logscale): self._R.set_logscale() self._img = self._R.get_image() self._extent = self._R.get_extent() if (plot): self.imshow(aspect='auto') return else: return
def getimage(snap, num, data, part_type, overwrite=False, P=None, S=None): if overwrite: i = data[num] i['xsize'] = 5000 i['ysize'] = 5000 i['roll'] = 0 S.update_camera(**i) R = sph.Render(S) R.set_logscale() img = R.get_image() extent = R.get_extent() np.save('animationdata/ptype%s_animationdata_reg%s_snap%s_angle%05d.npy'%(part_type,reg,snap,num), img) else: img = np.load('animationdata/ptype%s_animationdata_reg%s_snap%s_angle%05d.npy'%(part_type,reg,snap,num)) extent = [-45,45,45,-45] return img, extent
for i in range(0, N_StePS): if StePS_coordinates[i, 2] > -alpha and StePS_coordinates[ i, 2] < alpha and plot_R_limit > np.sqrt(StePS_coordinates[i, 0]**2 + StePS_coordinates[i, 1]**2 + StePS_coordinates[i, 2]**2): StePS_slice[j, 0] = StePS_coordinates[i, 0] StePS_slice[j, 1] = StePS_coordinates[i, 1] StePS_slice[j, 2] = StePS_coordinates[i, 2] StePS_slice[j, 3] = StePS_coordinates[i, 3] j += 1 end = time.time() print("..done in %fs. \n\n" % (end - start)) cmap = 'inferno' extent = [-R_plot, R_plot, -R_plot, R_plot] Particles = sph.Particles(StePS_slice[:, 0:3].T, StePS_slice[:, 3].T) Scene = sph.Scene(Particles) Scene.update_camera(r='infinity', extent=extent) Render = sph.Render(Scene) Render.set_logscale() img = Render.get_image() fig = plt.figure(1, figsize=(6, 6)) ax1 = fig.add_subplot(111) ax1.imshow(img, extent=extent, origin='lower', cmap=cmap) ax1.set_xlabel('x[Mpc]', size=10) ax1.set_ylabel('y[Mpc]', size=10) plt.title(title) plt.show()
Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length) Scene = sphviewer.Scene(Particles) phi_list = np.arange(0., 359., 1) for p, phi in tqdm(enumerate(phi_list)): Scene.update_camera(x=0., y=0., z=0., r='infinity', t=45., p=phi, extent=[-ext, ext, -ext, ext], xsize=res, ysize=res) Render = sphviewer.Render(Scene) Render.set_logscale() img = Render.get_image() img -= np.log10(px_size_pc**2) if p == 0: vmin = np.amin(img) vmax = np.amax(img) if prop == 'stars': vmin = -0.5 extent = Render.get_extent() fig = plt.figure(1, figsize=(8, 8)) ax1 = fig.add_subplot(111)
def image( self, gn, centre, # coordinates must be in kpc! theta=0., phi=0., extent=1024., vmax=None, vmin=None, resolution=1024, camera_distance='infinity', cmap=None, cbar_loc='right', cbarpad=-80., showaxes=False, save=True, show=True, set_contrast=True, path='/home/arijdav1/Dropbox/phd/figures/sph_pics/columndensity/', fname=None, imageonly=False, circleradius=None, scalebar_size=None, scalebar_colour=None, redshift_label=False, framenumber=0, returnarray=False): if os.path.exists(path) == False: os.makedirs(path) if camera_distance == 'infinity': px_size = 2 * extent / float(resolution) # in kpc px_size *= 1e3 mass_units = '$M_{\odot}$ $\mathrm{pc}^{-2}$' ion_units = r'${\rm g \, cm}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{pc}^{-2}$' else: px_size = (90. / float(resolution)) * 60. # in arcmin mass_units = '$M_{\odot}$ $\mathrm{arcmin}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{arcmin}^{-2}$' if self.property == 'gas': if cmap == None: cmap = 'afmhot' axlab = r'$\log\Sigma_g$ [%s]' % (mass_units) elif self.property == 'entropy': if cmap == None: cmap = 'nipy_spectral' axlab = r'entropy' elif self.property == 'xrays': if cmap == None: cmap = 'inferno' axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [%s]' % (lum_units) elif self.property == 'stars': if cmap == None: cmap = 'bone' axlab = r'$\log\Sigma_*$ [%s]' % (mass_units) else: raise IOError('Plot options are "gas", "stars" or "xrays"') if self.Scene is not None: if camera_distance == 'infinity': if self.property in [ 'entropy', ]: self.weightScene.update_camera( x=centre[0], y=centre[1], z=centre[2], r='infinity', t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) self.propScene.update_camera( x=centre[0], y=centre[1], z=centre[2], r='infinity', t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) else: self.Scene.update_camera( x=centre[0], y=centre[1], z=centre[2], r='infinity', t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) else: self.Scene.update_camera(x=x, y=y, z=z, r=camera_distance, t=theta, p=phi, xsize=resolution, ysize=resolution) if not self.quiet: print 'Rendering image...' if self.property in [ 'entropy', ]: Render = sphviewer.Render(self.propScene) propRender = Render.get_image() Render = sphviewer.Render(self.weightScene) weightRender = Render.get_image() rendered_img = propRender / weightRender # weighted mean of property in each pixel # fig,ax = plt.subplots(1,figsize=(1,1)) # plt.tick_params(axis='x',which='both',bottom='off',top='off') # plt.tick_params(axis='y',which='both',left='off',right='off') # im1 = ax.imshow(np.log10(rendered_img), cmap=cmap, origin='lower') # divider = make_axes_locatable(ax) # cax = divider.append_axes("right", size="5%", pad=0.15) # col = plt.colorbar(im1, cax=cax) # plt.show() # return else: Render = sphviewer.Render(self.Scene) rendered_img = Render.get_image() extent = Render.get_extent() if returnarray == True: # Return the raw array in crazy altered by 1e20 or 1e30 units, not sure if other codes depend on this return rendered_img img = deepcopy(rendered_img) img[img == 0.] = 1e-10 img = np.log10(img) if self.property == 'xrays': img += 30. if self.property == 'gas': img += 20. if self.property not in [ 'entropy', ]: img -= np.log10(px_size**2) if camera_distance == 'infinity': # If you don't know the dynamic range, set the defaults and make them callable if set_contrast: if self.property == 'stars': self.vmin = -1.5 elif self.property == 'gas': self.vmin = -1.5 elif self.property == 'xrays': self.vmin = 22.5 self.vmax = np.amax(img[np.isfinite(img)]) if self.property == 'entropy': self.vmin = np.amin(img[np.isfinite(img)]) self.vmax = np.amax(img[np.isfinite(img)]) elif not set_contrast and vmax == None or vmin == None: print 'Please use set_contrast or specify a vmax and vmin' exit() else: if set_contrast: minim = np.amin(img[np.isfinite(img)]) maxim = np.amax(img[np.isfinite(img)]) self.vmax = maxim if self.property == 'stars': self.vmin = np.percentile( np.linspace(minim, maxim, 100), 72) elif self.property == 'gas': self.vmin = np.percentile( np.linspace(minim, maxim, 100), 25) elif self.property == 'xrays': self.vmin = 22.5 elif not set_contrast and vmax == None or vmin == None: print 'Please use set_contrast or specify a vmax and vmin' exit() if vmax == None: vmax = self.vmax if vmin == None: vmin = self.vmin else: img = np.full((resolution, resolution), 0.) vmax = 1. vmin = 0. if imageonly: # save the img array as a picture with no colourbars etc, at right resolution if fname == None: savepath = path + self.sim + '_snap%03d'%(self.snapnum) + '_group' + str(gn) + '_' +\ self.property + '_ext%0d' % (extent[1]) +\ '_t%03d' % (theta) + '_p%03d' % (phi) + '_noborder.png' else: savepath = path + fname fig = plt.figure(figsize=(1, 1)) ax = fig.add_axes([0, 0, 1, 1]) plt.tick_params(axis='x', which='both', bottom='off', top='off') plt.tick_params(axis='y', which='both', left='off', right='off') im1 = ax.imshow(img, vmin=vmin, vmax=vmax, cmap=cmap, origin='lower') if redshift_label: ax.text(0.95, 0.9, r'$z=%.1f$' % (self.z), verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, color='white', fontsize=3) if circleradius != None: ax.add_artist( plt.Circle((0, 0), circleradius, fc='none', edgecolor='w', lw=2, ls='--')) if scalebar_size != None: ob = AnchoredHScaleBar(size=scalebar_size, label="", ax=ax, loc=4, frameon=False, pad=0.6, sep=4, color=scalebar_colour) ax.add_artist(ob) if not showaxes: ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) plt.savefig(savepath, dpi=resolution) if show: plt.show() plt.close(fig) return fig = plt.figure() ax1 = fig.add_subplot(111) im1 = plt.imshow(img, extent=extent, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax1) if cbar_loc == 'top': cax = divider.append_axes("top", size="5%", pad=0.) col = plt.colorbar(im1, cax=cax, orientation='horizontal') col.ax.xaxis.set_ticks_position('top') caxticks = col.ax.xaxis.get_major_ticks() caxticks[0].label2.set_visible(False) caxticks[-1].label2.set_visible(False) col.set_label(axlab, labelpad=cbarpad, fontsize=24) cax.tick_params(axis='both', which='major', labelsize=16) else: cax = divider.append_axes("right", size="5%", pad=0.15) col = plt.colorbar(im1, cax=cax) col.set_label(axlab, fontsize=16) if not showaxes: ax1.axes.get_xaxis().set_visible(False) ax1.axes.get_yaxis().set_visible(False) if circleradius != None: ax1.add_artist( plt.Circle((0, 0), circleradius, fc='none', edgecolor='w', lw=2, ls='--')) if scalebar_size != None: ob = AnchoredHScaleBar(size=scalebar_size, label="", ax=ax1, loc=4, frameon=False, pad=0.6, sep=4, color=scalebar_colour) ax1.add_artist(ob) if scalebar_size >= 1000.: sb_label = '%.0f Mpc' % (scalebar_size / 1000.) else: sb_label = '%.0f kpc' % (scalebar_size) #ax1.text(0.63*extent[1],-0.82*extent[1],sb_label,color=scalebar_colour,fontsize=16) if save: DPI = fig.get_dpi() #DPI = 1024. fig.set_size_inches(1024.0 / float(DPI), 1080.0 / float(DPI)) # for colorbar if fname == None: savepath = path + self.sim + '_snap%03d'%(self.snapnum) + '_group' + str(gn) + '_' +\ self.property + '_ext%0d' % (extent[1]) +\ '_t%03d' % (theta) + '_p%03d' % (phi) + '_noborder.png' else: savepath = path + fname plt.savefig(savepath, pad_inches=0.0, dpi='figure') if show: plt.show() plt.close() return img
def image(self, gn, x, y, z, # coordinates must be in kpc! theta=0., phi=0., extent=400., vmax = None, vmin = None, resolution=1024, camera_distance='infinity', cmap = None, save=True, show=True, set_contrast = True, path='/home/arijdav1/Dropbox/phd/figures/sph_pics/', movieflag=False, framenumber=0): if os.path.exists(path) == False: os.makedirs(path) if camera_distance == 'infinity': px_size = 2*extent / float(resolution) # in kpc px_size *= 1e3 mass_units = '$M_{\odot}$ $\mathrm{pc}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{pc}^{-2}$' else: px_size = (90./float(resolution))*60. # in arcmin mass_units = '$M_{\odot}$ $\mathrm{arcmin}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{arcmin}^{-2}$' if self.property == 'gas': if cmap==None: cmap = 'afmhot' axlab = r'$\log\Sigma_g$ [%s]'%(mass_units) elif self.property == 'xrays': if cmap==None: cmap = 'inferno' axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [%s]'%(lum_units) elif self.property == 'stars': if cmap==None: cmap = 'bone' axlab = r'$\log\Sigma_*$ [%s]'%(mass_units) else: raise IOError('Plot options are "gas", "stars" or "xrays"') if camera_distance == 'infinity': self.Scene.update_camera(x=x, y=y, z=z, r='infinity', t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) else: self.Scene.update_camera(x=x, y=y, z=z, r=camera_distance, t=theta, p=phi, xsize=resolution, ysize=resolution) Render = sphviewer.Render(self.Scene) #Render.set_logscale() extent = Render.get_extent() rendered_img = Render.get_image() img = deepcopy(rendered_img) img[img==0.] = 1e-10 img = np.log10(img) if self.property == 'xrays': img += 30. if self.property == 'gas': img += 20. img -= np.log10(px_size ** 2) if camera_distance == 'infinity': # If you don't know the dynamic range, set the defaults and make them callable if set_contrast: if self.property == 'stars': self.vmin = -1.5 elif self.property == 'gas': self.vmin = -1.5 elif self.property == 'xrays': self.vmin = 22.5 self.vmax = np.amax(img[np.isfinite(img)]) elif not set_contrast and vmax==None or vmin==None: print 'Please use set_contrast or specify a vmax and vmin' exit() else: if set_contrast: minim = np.amin(img[np.isfinite(img)]) maxim = np.amax(img[np.isfinite(img)]) self.vmax = maxim if self.property == 'stars': self.vmin = np.percentile(np.linspace(minim,maxim,100),72) elif self.property == 'gas': self.vmin = np.percentile(np.linspace(minim,maxim,100),25) elif self.property == 'xrays': self.vmin = 22.5 elif not set_contrast and vmax==None or vmin==None: print 'Please use set_contrast or specify a vmax and vmin' exit() if vmax == None: vmax = self.vmax if vmin == None: vmin = self.vmin inches = np.floor((resolution+500.)/100.) fig = plt.figure(1, figsize=(inches,inches)) ax1 = fig.add_subplot(111) im1 = plt.imshow(img, extent=extent, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.15) col = plt.colorbar(im1, cax=cax) col.set_label(axlab, fontsize=16) if save: if movieflag: plt.savefig(path+'frame%s'%(str(framenumber))+'.png',bbox_inches='tight') else: plt.savefig(path + 'group' + str(gn) + '_' +\ self.property + '_ext%0d' % (extent[1]) +\ '_t%03d' % (theta) + '_p%03d' % (phi) + '.png',bbox_inches='tight') if show: plt.show() plt.close()
def image(self, gn, centre, # coordinates must be in kpc! theta=0., phi=0., align = None, extent=400., vmax = None, vmin = None, resolution=1024, camera_distance='infinity', cmap = None, save=True, show=True, set_contrast = True, path='/home/arijdav1/Dropbox/phd/figures/sph_pics/', movieflag=False, circleradius = None, scalebar_size = None, scalebar_colour = None, framenumber=0, returnarray=False): if align != None: # make sure the alignment isn't ruined by too many inputs theta = 0. phi = 0. if os.path.exists(path) == False: os.makedirs(path) if camera_distance == 'infinity': px_size = 2*extent / float(resolution) # in kpc px_size *= 1e3 mass_units = '$M_{\odot}$ $\mathrm{pc}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{pc}^{-2}$' else: px_size = (90./float(resolution))*60. # in arcmin mass_units = '$M_{\odot}$ $\mathrm{arcmin}^{-2}$' lum_units = '$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{arcmin}^{-2}$' if self.property == 'gas': if cmap==None: cmap = 'afmhot' axlab = r'$\log\Sigma_g$ [%s]'%(mass_units) elif self.property == 'xrays': if cmap==None: cmap = 'inferno' axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [%s]'%(lum_units) elif self.property == 'stars': if cmap==None: cmap = 'bone' axlab = r'$\log\Sigma_*$ [%s]'%(mass_units) else: raise IOError('Plot options are "gas", "stars" or "xrays"') if camera_distance == 'infinity': self.Scene.update_camera(x=centre[0], y=centre[1], z=centre[2], r='infinity', t=theta, p=phi, extent=[-extent, extent, -extent, extent], xsize=resolution, ysize=resolution) else: self.Scene.update_camera(x=x, y=y, z=z, r=camera_distance, t=theta, p=phi, xsize=resolution, ysize=resolution) if align == 'face' or align == 'edge': angles = self.get_alignment(gn) rot_x = angles[0][0] rot_y = angles[0][1] rot_z = angles[0][2] print rot_x print rot_y print rot_z #self.Scene.update_camera(p=-1.*(90.+phi_J)) self.Scene.update_camera(t=rot_x,p=rot_y,roll=rot_z) print 'Rendering image...' Render = sphviewer.Render(self.Scene) #Render.set_logscale() extent = Render.get_extent() rendered_img = Render.get_image() if returnarray == True: return rendered_img img = deepcopy(rendered_img) img[img==0.] = 1e-10 img = np.log10(img) if self.property == 'xrays': img += 30. if self.property == 'gas': img += 20. img -= np.log10(px_size ** 2) if camera_distance == 'infinity': # If you don't know the dynamic range, set the defaults and make them callable if set_contrast: if self.property == 'stars': self.vmin = -1.5 elif self.property == 'gas': self.vmin = -1.5 elif self.property == 'xrays': self.vmin = 22.5 self.vmax = np.amax(img[np.isfinite(img)]) elif not set_contrast and vmax==None or vmin==None: print 'Please use set_contrast or specify a vmax and vmin' exit() else: if set_contrast: minim = np.amin(img[np.isfinite(img)]) maxim = np.amax(img[np.isfinite(img)]) self.vmax = maxim if self.property == 'stars': self.vmin = np.percentile(np.linspace(minim,maxim,100),72) elif self.property == 'gas': self.vmin = np.percentile(np.linspace(minim,maxim,100),25) elif self.property == 'xrays': self.vmin = 22.5 elif not set_contrast and vmax==None or vmin==None: print 'Please use set_contrast or specify a vmax and vmin' exit() if vmax == None: vmax = self.vmax if vmin == None: vmin = self.vmin inches = np.floor((resolution+500.)/100.) fig = plt.figure(1, figsize=(inches,inches)) ax1 = fig.add_subplot(111) im1 = plt.imshow(img, extent=extent, origin='lower', cmap=cmap, vmin=vmin, vmax=vmax) divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.15) col = plt.colorbar(im1, cax=cax) col.set_label(axlab, fontsize=16) if circleradius != None: ax1.add_artist(plt.Circle((0,0),circleradius,fc='none',edgecolor='green',lw=2,ls='--')) if scalebar_size != None: ob = AnchoredHScaleBar(size=scalebar_size, label="", ax=ax1, loc=4, frameon=False, pad=0.6,sep=4,color=scalebar_colour) ax1.add_artist(ob) if scalebar_size>=1000.: sb_label = '%.0f Mpc'%(scalebar_size/1000.) else: sb_label = '%.0f kpc'%(scalebar_size) #ax1.text(0.63*extent[1],-0.82*extent[1],sb_label,color=scalebar_colour,fontsize=16) if save: if movieflag: plt.savefig(path+'frame%s'%(str(framenumber))+'.png',bbox_inches='tight') else: plt.savefig(path + self.sim + '_snap' + str(self.snapnum) + '_group' + str(gn) + '_' +\ self.property + '_ext%0d' % (extent[1]) +\ '_t%03d' % (theta) + '_p%03d' % (phi) + '.png',bbox_inches='tight',dpi=400) if show: plt.show() plt.close()
cmap = 'hot' axlab = r'$\log\Sigma_g$ [$M_{\odot}$ $\mathrm{kpc}^{-2}]$' elif prop == 'xrays': cmap = 'gnuplot' axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{kpc}^{-2}]$' elif prop == 'stars': cmap = 'bone' axlab = r'$\log\Sigma_*$ [$M_{\odot}$ $\mathrm{kpc}^{-2}]$' else: raise IOError('Plot options are "gasmass", "stars", "temperature" or "xrays"') Particles = sphviewer.Particles(pos,quantity,hsml=smoothing_length) Scene = sphviewer.Scene(Particles) Scene.update_camera(x=0.,y=0.,z=0.,r='infinity',t=90.,extent=[-ext,ext,-ext,ext],xsize=res,ysize=res) Render = sphviewer.Render(Scene) #Render.set_logscale() img = Render.get_image() sdensity_img = img/px_size**2 ''' # For quickly viewing the individual images extent = Render.get_extent() plt.figure() plt.imshow(sdensity_img,cmap='hot',extent=extent, origin='lower') plt.show() ''' ''' fig = plt.figure(1,figsize=(5,5))
def __init__(self, pos, mass=None, hsml=None, nb=None, logscale=True, plot=True, min_hsml=None, max_hsml=None, **kwargs): """ Quickview is a simple wrapper of the sphviewer API. This utility stores the particles, defines the Scene and the Camera, and produces the rendering of the Scene in one step, thus making the process of producing images of SPH particles easy and quick. The arguments of the functions are: - pos = SPH particle positions. Array of shape [N,3], where N in the number of particles and pos[:,0] = x; pos[:,1] = y; pos[:,2] = z. - mass (optional): is the mass of the SPH particles. If present, it must be an array of size N. If absent, a constant value, mass = 1, will be assumed for all particles. - hsml (optional): this is an array containing the smoothing lenghts of the SPH particles. The absence of the array will trigger the calculation of the smoothing lenghts. - nb (optional): number of neighbours to be used for the calculation of the SPH smoothing lengths. If absent, the default value nb=32 will be used. This arguement is ignored if the array hsml is provided. - logscale (optional): If True, the output image becomes out_log = log10(1.0+output) - plot (optional): If true, QuickView will plot the resulting image in the current active figure. - min_hsml / max_hsml: Physical values of the minimum / maximum smoothing lengths. Only used when defined. **kwargs These include the parameters of the Camera: """ if (mass is None): mass = np.ones(len(pos)) if (nb == None): self._P = sph.Particles(pos, mass, hsml) else: self._P = sph.Particles(pos, mass, hsml, nb) if ((min_hsml is not None) or (max_hsml is not None)): hsml = self.get_hsml() if (min_hsml is not None): min_hsml = min_hsml else: min_hsml = np.min(hsml) if (max_hsml is not None): max_hsml = max_hsml else: max_hsml = np.max(hsml) hsml = np.clip(hsml, min_hsml, max_hsml) print('Limiting smoothing length to the range ' '[%.3f,%.3f]' % (min_hsml, max_hsml)) self._P.set_hsml(hsml) self._S = sph.Scene(self._P) self._S.update_camera(**kwargs) self._R = sph.Render(self._S) if (logscale): self._R.set_logscale() self._img = self._R.get_image() self._extent = self._R.get_extent() if (plot): self.imshow(aspect='auto') return else: return
# ----escala de colores que te guste (http://matplotlib.org/examples/color/colormaps_reference.html)--- cmap='jet' <<<<<<< HEAD nb1 = 10 #nb1 = 100 ======= #nb1 = 5 nb1 = 100 >>>>>>> b29321f0c229ffcfec5b2b43354097e24d056487 particles=sph.Particles(pos[:3,corte],mstr[corte]*1e10,nb=nb1) escena=sph.Scene(particles) escena.update_camera(r='infinity',x=0,y=0,z=0,extent=[-rl,rl,-rl,rl]) rend=sph.Render(escena) extent=escena.get_extent() rend.set_logscale() ax[0,0].imshow(rend.get_image(),extent=extent,origin='lower',cmap=cmap, vmin=vmin, vmax= vmax) ax[0,0].set_xlim(-5,5) ax[0,0].set_ylim(-5,5) ax[0,0].set_xticks([]) ax[0,0].set_yticks([]) ax[0,0].set_yticklabels([]) ax[0,0].set_xticklabels([]) # ax[0,0].set_ylabel('$y\:[kpc]$', fontsize=40) # ax[0,0].minorticks_on() # ax[0,0].tick_params( labelsize=40) # ax[0,0].tick_params('both', length=5, width=1.8,which='minor', direction='in', right='on',top='on') # ax[0,0].tick_params('both', length=8, width=1.8,which='major', direction='in', right='on',top='on')
def plot_parent(i, P, n, res, centre, z_centre): print("i:", i) sys.stdout.flush() cmap = cmaps.twilight() f = modified_sigmoid(i / n, 3) L, l = 3300 / 2, 50 dl = L * (1 - f) + l * f R = 16. / 9 offset = 100 dx = dl * R dy = dl ext_x = 3200 / 2 ext_y = 3200 / 2 if ext_x > dx: ext_x = dx if ext_y > dy: ext_y = dy C = sph.Camera(r='infinity', t=0, p=0, roll=0, xsize=res, ysize=res, x=centre, y=centre, z=z_centre, extent=[-ext_x, ext_x, -ext_y, ext_y]) S = sph.Scene(P, C) R = sph.Render(S) extent = R.get_extent() img = np.log10(R.get_image()) print(img.max(), img.min()) fig = plt.figure(figsize=(16, 9)) ax = fig.add_axes([0, 0, 1, 1]) # ax.imshow(img, cmap=cmap, vmin=-0.05, vmax=1.2, extent=extent,aspect='equal') ax.imshow(img, cmap=cmap, vmin=--1, vmax=2.4, extent=extent, aspect='equal') del (img) del (C) ax.set_facecolor(cmap(0.0)) ax.set_xlim(-dx, dx) ax.set_ylim(-dy, dy) ax.hlines(0.9, 0.092, 0.192, transform=ax.transAxes, color='red', lw=2) ax.text(0.1, 0.94, '$%i \; \mathrm{cMpc}$' % (dx * 0.2), transform=ax.transAxes, size=12, color='black') rect = patches.Rectangle((0.09, 0.92), 0.105, 0.065, linewidth=1, edgecolor='none', facecolor='white', alpha=0.5, transform=ax.transAxes) ax.add_patch(rect) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # plt.show() fname = 'plots/parent_zoom/parent_zoom_%03d.png' % i # plt.gca().set_axis_off() # plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, # hspace = 0, wspace = 0) # plt.margins(0,0) print(fname) fig.savefig(fname, dpi=150) #, bbox_inches='tight', pad_inches = 0) plt.close(fig)
anchors['extent'] = [10, 'pass', 'pass', 'pass', 'pass', 'pass', 30] data = get_camera_trajectory(targets, anchors) n1 = 10000 cube1 = np.random.rand(3, n1) cube1[1, :] -= 6 cube2 = np.random.rand(3, n1) cube2[1, :] += 1 cubes = np.concatenate((cube1, cube2), axis=1) mass = np.ones(n1+n1) P = sph.Particles(cubes, mass) S = sph.Scene(P) h = 0 for i in data: i['xsize'] = 200 i['ysize'] = 200 i['roll'] = 0 S = sph.Scene(P) S.update_camera(**i) print(S.Camera.get_params()) R = sph.Render(S) img = R.get_image() R.set_logscale() plt.imsave('test/image_'+str('%d.png' % h), img, vmin=0, vmax=6, cmap='cubehelix') h += 1
def getimage(path, snap, soft, num, centre, data, part_type): # Get plot data if part_type == 0: poss_gas, masses_gas, smls_gas = get_sphere_data(path, snap, part_type=0, soft=None) elif part_type == 1: poss_gas, masses_gas, smls_gas = get_sphere_data(path, snap, part_type=1, soft=soft) else: return -1 # Centre particles poss_gas -= centre # Remove boundary particles rgas = np.linalg.norm(poss_gas, axis=1) okinds_gas = rgas < 14 / 0.677 poss_gas = poss_gas[okinds_gas, :] masses_gas = masses_gas[okinds_gas] smls_gas = smls_gas[okinds_gas] if part_type == 0: print('There are', len(masses_gas), 'gas particles in the region') elif part_type == 1: print('There are', len(masses_gas), 'dark matter particles in the region') # Set up particle objects P_gas = sph.Particles(poss_gas, mass=masses_gas, hsml=smls_gas) # Initialise the scene S_gas = sph.Scene(P_gas) i = data[num] i['xsize'] = 5000 i['ysize'] = 5000 i['roll'] = 0 S_gas.update_camera(**i) R_gas = sph.Render(S_gas) R_gas.set_logscale() img_gas = R_gas.get_image() if part_type == 0: np.save( 'animationdata/gas_animationdata_reg' + reg + '_snap' + snap + '_angle%05d.npy' % num, img_gas) if part_type == 1: np.save( 'animationdata/dm_animationdata_reg' + reg + '_snap' + snap + '_angle%05d.npy' % num, img_gas) # fig = plt.figure() # ax = fig.add_subplot(111) # # ax.hist(get_normalised_image(img_gas).ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k') # # if part_type == 0: # fig.savefig('plots/spheres/All/histDM_animation_reg' + reg + '_snap' + snap + '_angle%05d.png'%num, # bbox_inches='tight') # if part_type == 1: # fig.savefig('plots/spheres/All/histgas_animation_reg' + reg + '_snap' + snap + '_angle%05d.png'%num, # bbox_inches='tight') # plt.close(fig) vmax_gas = img_gas.max() vmin_gas = vmax_gas * 0.5 # Get colormaps if part_type == 0: cmap_gas = cmaps.twilight() elif part_type == 1: cmap_gas = ml.cm.Greys_r # Convert images to rgb arrays rgb_gas = cmap_gas(get_normalised_image(img_gas, vmin=vmin_gas)) return rgb_gas, R_gas.get_extent()