def __init__(self, size): self.size = size self.paths = [] self.reset_maze() self.flood = self.Flood(self, 10) self.colormap1 = cubehelix.cmap(startHue=-100, endHue=300, minLight=0.35, maxLight=0.8) self.colormap2 = cubehelix.cmap(startHue=540, endHue=140, minLight=0.35, maxLight=0.8, reverse=True)
def div_cmap(ncolors=1024): """Create a diverging colormap using cubehelix.""" # Get a high-resolution unit interval. Evaluate two cubehelixes on # it, one for the positive values and one for the negatives. u = np.linspace(0., 1., 1024) bot = cubehelix.cmap(start=0.5, rot=-0.5)(u) top = cubehelix.cmap(start=0.5, rot=0.5, reverse=True)(u) # Slap the two together into a linear segmented colormap. ch = lsc.from_list('ch_sym', np.vstack((bot, top))) # From there, get a colormap with the desired number of intervals. return ListedColormap(ch(np.linspace(0.05, 0.95, ncolors)))
def div_cmap(ncolors=1024): """Create a diverging colormap using cubehelix.""" # Get a high-resolution unit interval. Evaluate two cubehelixes on # it, one for the positive values and one for the negatives. u = np.linspace(0., 1., 1024) bot = cubehelix.cmap(start=0.5, rot=-0.5)(u) top = cubehelix.cmap(start=0.5, rot=0.5, reverse=True)(u) # Slap the two together into a linear segmented colormap. ch = lsc.from_list( 'ch_sym', np.vstack( (bot, top) ) ) # From there, get a colormap with the desired number of intervals. return ListedColormap( ch( np.linspace(0.05, 0.95, ncolors) ) )
def plot_isoc_grid_ages(self, ax, band1, band2, show_cb=False, cb_ax=None): isoc_set = get_demo_age_grid( **dict(isoc_kind='parsec_CAF09_v1.2S', photsys_version='yang')) cmap = cubehelix.cmap(startHue=240, endHue=-300, minSat=1, maxSat=2.5, minLight=.3, maxLight=.8, gamma=.9) norm = mpl.colors.Normalize(vmin=7., vmax=10.1) scalar_map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) scalar_map.set_array(np.array([isoc.age for isoc in isoc_set])) d = Distance(785 * u.kpc) for isoc in isoc_set: ax.plot(isoc[band1] - isoc[band2], isoc[band2] + d.distmod.value, c=scalar_map.to_rgba(np.log10(isoc.age)), lw=0.8) if show_cb: cb = plt.colorbar(mappable=scalar_map, cax=cb_ax, ax=ax, ticks=np.arange(6., 10.2)) cb.set_label(r"log(age)")
def plot_triptyk(self, fig, ax_obs, ax_model, ax_chi, fit_key, plane_key, xtick=1., xfmt="%.0f"): cmapper = lambda: cubehelix.cmap(startHue=240, endHue=-300, minSat=1, maxSat=2.5, minLight=.3, maxLight=.8, gamma=.9) fit = self.fits[fit_key] plane = self.planes[plane_key] ctp = ChiTriptykPlot(fit, plane) ctp.setup_axes(fig, ax_obs=ax_obs, ax_mod=ax_model, ax_chi=ax_chi, major_x=xtick, major_x_fmt=xfmt) ctp.plot_obs_in_ax(ax_obs, cmap=cmapper()) ctp.plot_mod_in_ax(ax_model, cmap=cmapper()) ctp.plot_chi_in_ax(ax_chi, cmap=cubehelix.cmap()) ax_obs.text(0.0, 1.01, "Observed", transform=ax_obs.transAxes, size=8, ha='left') ax_model.text(0.0, 1.01, "Model", transform=ax_model.transAxes, size=8, ha='left') ax_chi.text(0.0, 1.01, r"$\log \chi^2$", transform=ax_chi.transAxes, size=8, ha='left')
def continuum(self, dx=1e30, dy=-1, noBeam=False, rms=-1, immax=-1, solid=True, title=True, wedge=True, lightBackground=True): if(dy == -1): dy = dx if(self.xunit == 'seconds'): dy = dy/3600. dx = dx/3600. if(self.vaxis.any()): sys.exit(self.fileName + " is not a continuum image") if(rms<0): rms = self.getRMS() xc,yc,vc = self._getIndices(self,dx,dy) ax,cmap,fig = plots.createFigure(self.xaxis, self.yaxis, xc, yc, self.header, title) if(immax == -1): immax = np.nanmax(self.image) cx = cubehelix.cmap(start=0, rot=-0.5, reverse=lightBackground) if(solid): im=ax.imshow(self.image, cmap=cx, alpha=1.0, interpolation='nearest', origin='lower', extent=[np.max(self.xaxis), np.min(self.xaxis), np.min(self.yaxis), np.max(self.yaxis)], vmin=np.nanmin(3*rms), vmax=immax, aspect='auto') if(wedge): cbar = plt.colorbar(im) cbar.set_label('Intensity ('+self.header['BUNIT']+')') else: im=ax.imshow(self.image, cmap=cx, alpha=0.0, interpolation='nearest', origin='lower', extent=[np.max(self.xaxis), np.min(self.xaxis), np.min(self.yaxis), np.max(self.yaxis)], vmin=np.nanmin(3*rms), vmax=immax, aspect='auto') im=ax.contour(self.xaxis, self.yaxis, self.image, colors='black', aspect='auto', interpolation='nearest', linewidths=1.5, levels=np.arange(150)*3*rms+3*rms) if(not noBeam): self._plotBeam(self, ax, xc, yc, lightBackground) return ax, fig
def plot_isoc_grid_ages(self, ax, band1, band2, show_cb=False, cb_ax=None): isoc_set = get_demo_age_grid(**dict(isoc_kind='parsec_CAF09_v1.2S', photsys_version='yang')) cmap = cubehelix.cmap(startHue=240, endHue=-300, minSat=1, maxSat=2.5, minLight=.3, maxLight=.8, gamma=.9) norm = mpl.colors.Normalize(vmin=7., vmax=10.1) scalar_map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) scalar_map.set_array(np.array([isoc.age for isoc in isoc_set])) d = Distance(785 * u.kpc) for isoc in isoc_set: ax.plot(isoc[band1] - isoc[band2], isoc[band2] + d.distmod.value, c=scalar_map.to_rgba(np.log10(isoc.age)), lw=0.8) if show_cb: cb = plt.colorbar(mappable=scalar_map, cax=cb_ax, ax=ax, ticks=np.arange(6., 10.2)) cb.set_label(r"log(age)")
""" # External packages from matplotlib.colors import LogNorm from matplotlib.cm import get_cmap import numpy as np import pynbody as pb SimArray = pb.array.SimArray import os # Internal modules import cubehelix import ffmpeg_writer import pbmov_utils # setup colormaps ch=cubehelix.cmap() cx4 = cubehelix.cmap(reverse=False, start=0., rot=0.5) #mostly reds cx3 = cubehelix.cmap(reverse=False, start=0.3, rot=-0.5)# mostly blues cx_default = ch def render_movie(sim, cameras, targets, nt, vmin=None, vmax=None, camera_rot=0.0,\ res=500, cmap=cx_default, fps=25, savename='movie.mp4', preview=None, nskip=0, **kwargs): """ Renders a movie. **STATIC ARGUMENTS** sim : snapshot A pynbody snapshot nt : int Numer of frames res : int
def plotspec(specData, bandNames, limits, objID, classType, grav=None, plotInstructions=None, figNum=1): # Plots set of spectral data and saves plots in a PDF file. # specData and limits must be dictionaries. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import types import cubehelix import pdb # 1) Check data consistency =============================================== # Stop if specData or limits are not dictionaries try: specData.keys() limits.keys() except AttributeError: print('PLOTSPEC: Data not received as dictionaries.') return # 2) Initialize variables & color sets (hex codes) ======================== cx = cubehelix.cmap(start=0.5, rot=-1.5, sat=1, gamma=1.5) BLACK = '#000000' GRAY = '#666666' WHITE = '#FFFFFF' X_LABEL = 'Wavelength ($\mu$m)' Y_LABEL = 'Normalized Flux (F$_{\lambda}$)' # 3) Initialize Figure ==================================================== plt.close() plt.rc('font', size=8) fig = plt.figure(figNum, figsize=(6.61417, 3.54)) # 168mm x 90mm (9,6)) plt.clf() plt.subplots_adjust(wspace=0.1, top=0.98, bottom=0.1, right=0.98, left=0.03) # 4) Generate Subplots ==================================================== for bandIdx, band in enumerate(bandNames): # 4a) If band data is only one set, convert into array of sets -------- if specData[band][0] is not None: if len(specData[band][0]) > 3: specData[band] = [ specData[band], ] # 4b) Initialize variables -------------------------------------------- spLines = [] minPlot = 1 maxPlot = 1 # Count the number of plots in order to select color set if plotInstructions is not None: tmpFld = np.where(np.array(plotInstructions) == 'field') tmpYng = np.where(np.array(plotInstructions) == 'young') tmpStd = np.where(np.array(plotInstructions) == 'standard') numFld = len(tmpFld[0]) numYng = len(tmpYng[0]) numStd = len(tmpStd[0]) specNum = numFld + numYng + numStd else: specNum = len(filter(None, specData[band])) plotcolors = cx(np.linspace(0, 1, specNum)) cxmap = mpl.cm.coolwarm(np.linspace(0, 1, specNum)) plt.rc('axes', color_cycle=list(cxmap)) # Legend is added when loop is for the J band if band == 'J': textColors = [] # For legend purposes only # 4c) Initialize Subplot ---------------------------------------------- #subPlot = plt.figure(figNum).add_subplot(1,4,4 - bandIdx, \ # position=[0.16 + (3 - bandIdx) * 0.21,0.1,0.19,0.83]) # [left,bottom,width,height] subPlot = plt.figure(figNum).add_subplot(1, 3, 3 - bandIdx) subPlot.set_autoscale_on(False) # Set figure and axes labels if grav == 'Y': plotType = ' young' elif grav == 'B': plotType = r'$\beta$' elif grav == 'G': plotType = r'$\gamma$' elif grav == 'F': plotType = ' field' else: plotType = '' title = classType if plotType != '': title = title + plotType if bandIdx == 1: subPlot.set_xlabel(X_LABEL) #, position=(1.1,0.08)) if bandIdx == 2: subPlot.set_ylabel(Y_LABEL, labelpad=0) #subPlot.set_title(title, fontsize=17, fontweight='bold', \ # position=(-0.01,0.88), ha='left') if band == 'J': tmpband = 'zJ' else: tmpband = band subPlot.set_title(tmpband, fontsize=16, fontstyle='italic', color=GRAY, \ position=(0.84, 0.07), transform=subPlot.transAxes, \ weight='heavy') # 4d) Determine order of spectra plotting ----------------------------- zOrders = [None] * len(plotInstructions) countColor = specNum for plotIdx, plot in enumerate(plotInstructions): if plot == 'young' or plot == 'field' or plot == 'standard': zOrders[plotIdx] = specNum - countColor countColor = countColor - 1 elif plot == 'template': zOrders[ plotIdx] = specNum # Template plotted on top of all others # 4e) Plot spectral data in Subplot ----------------------------------- countColors = specNum - 1 icolor = 0 for specIdx, spec in enumerate(specData[band]): if spec is None: continue elif plotInstructions[specIdx] == 'exclude': continue # Set lines styles lnStyle = '-' if plotInstructions[specIdx] == 'template': lnWidth = 0.9 else: lnWidth = 0.5 # Identify particular objects in legends if plotInstructions[specIdx] == 'template': objLabel = title + ' ' + objID[specIdx] #objLabel = objID[specIdx] + '$\diamondsuit$' else: objLabel = objID[specIdx] # Consolidate color plot and legend designation clr = plotcolors[icolor] if plotInstructions[specIdx] == 'template': plotColor = BLACK legColor = BLACK elif plotInstructions[specIdx] == 'young' or \ plotInstructions[specIdx] == 'field' or \ plotInstructions[specIdx] == 'standard': #plotColor = plotColors[countColors] # Color for plot line #legColor = plotColor # Color for legend text countColors = countColors - 1 #if band == 'J': # textColors.append(legColor) # Colors for legend labels # Plot the damned thing subPlot.plot(spec[0], spec[1], linestyle=lnStyle, drawstyle='steps-mid', \ dash_joinstyle='round', linewidth=lnWidth, label=objLabel, \ zorder=zOrders[specIdx]) #,color=plotColor) # Track the highest & lowest y-axis values to fix y-axis limits later if plotInstructions[specIdx] != 'exclude': tmpMin = np.nanmin(spec[1]) if tmpMin < minPlot: minPlot = tmpMin tmpMax = np.nanmax(spec[1]) if tmpMax > maxPlot: maxPlot = tmpMax # 4f) Fix axes limits ------------------------------------------------- minPlot = minPlot - minPlot * 0.1 if band == 'J': maxOff = 0.12 elif band == 'K' and classType == 'L0' and grav == 'G': maxOff = 0.01 else: maxOff = 0.07 maxPlot = maxPlot + maxPlot * maxOff plt.ylim(ymin=minPlot, ymax=maxPlot) subPlot.set_xlim(xmin=limits[band]['lim'][0], \ xmax=limits[band]['lim'][1] * 1.001) # 4g) Customize y axis ------------------------------------------------ subPlot.spines['left'].set_color('none') subPlot.spines['right'].set_color('none') subPlot.yaxis.set_ticks([]) # 4h) Create and format legend (when loop is for J band) -------------- # if band == 'J': # objLegends = subPlot.legend(handlelength=0, handletextpad=0.1, \ # loc='upper left', \ # bbox_to_anchor=(-1.88,0.97), \ # labelspacing=0.3, numpoints=1) # objLegends.draw_frame(True) # # for legendIdx, legendText in enumerate(objLegends.get_texts()): # plt.setp(legendText, color=textColors[legendIdx], \ # fontsize=7, fontname='Andale Mono') # # # Add Titles for the legends # legendTitles1 = 'Optical' # legendTitles2 = 'Coords. SpType J-K' # xCoord1 = -1.57 # xCoord2 = -1.79 # yCoord1 = 0.99 # yCoord2 = 0.964 # subPlot.text(xCoord1, yCoord1, legendTitles1, fontsize=7, \ # transform=subPlot.transAxes) # subPlot.text(xCoord2, yCoord2, legendTitles2, fontsize=7, \ # transform=subPlot.transAxes) # 4i) Add absorption annotations to Subplots -------------------------- # Sent to addannot only spectra plotted specsAnnot = [] for idxSpec, spec in enumerate(specData[band]): if plotInstructions[idxSpec] != 'exclude': specsAnnot.append(spec) #addannot(filter(None, specsAnnot), subPlot, band, classType) addannot(specsAnnot, subPlot, band, classType) return fig
def plot_imagegrid(modnames, moddisplaynames, wave, tau, angle, comp_index=-2, max_plot_diff=100.0, save_str='', save_eps=False, save_png=False, save_pdf=False): # setup the plots fontsize = 14 font = {'size' : fontsize} mpl.rc('font', **font) mpl.rc('lines', linewidth=2) mpl.rc('axes', linewidth=2) mpl.rc('xtick.major', width=2) mpl.rc('ytick.major', width=2) # generate the filename ifilenames = [modname + '_t' + tau + '_i' + angle + 'a000_w' + wave + '.fits' for modname in modnames] n_orig_files = len(ifilenames) # check all the files exisit, adjust if not filenames = [] displaynames = [] fileindxs = [] for i, cfile in enumerate(ifilenames): if os.path.isfile(cfile): filenames.append(cfile) displaynames.append(moddisplaynames[i]) fileindxs.append(i) n_files = len(filenames) if n_files == 0: print('no files present') print(ifilenames) exit(0) # table for saving offset and standard deviation tab = Table(names=('model','mindex', 'cut1_offset','cut1_stddev','cut1_maxabsdev', 'cut2_offset','cut2_stddev','cut2_maxabsdev'), dtype=('S15', int, float, float, float, float, float, float)) # plot information fig_label = r'Slab, $\tau (1 \mu m)$ = '+tau+r', $\theta$ = ' + angle + \ ', $\lambda$ = ' + wave if save_str != '': fig_label += ' (' + save_str + ' case)' else: fig_label += ' (eff case)' symtype = ['b-','g-','r-','c-','m-','y-','k-','b--','g--','r--','c--', 'm--','y--','k--'] # cut info cut1 = np.array([95,115]) cut2 = np.array([70,90]) # value to split the legend onto the next plot legsplitval = 7 # decide the number of columns for the images nrows = 4 n_image_col = 2 dm = divmod(n_orig_files,nrows) if dm[0] >= n_image_col & dm[0] > 0: n_image_col = dm[0] if dm[1] > 0: n_image_col += 1 # setup figure xsize = 12 ysize = 12 if n_image_col > 2: xsize += 3.0*(n_image_col-2) fig, ax = pyplot.subplots(figsize=(xsize,ysize)) # use gridspec to allow for one plot to be larger than the others gs = gridspec.GridSpec(nrows, n_image_col+3, width_ratios=2*[1.5] + n_image_col*[1.0] + [0.15]) ax = [] for i in range(n_files): gs_indxs = np.array(divmod(fileindxs[i],n_image_col)) gs_indxs[1] += 2 ax.append(pyplot.subplot(gs[gs_indxs[0],gs_indxs[1]])) # cut plots ax.append(pyplot.subplot(gs[0,0:2])) ax.append(pyplot.subplot(gs[1,0:2])) ax.append(pyplot.subplot(gs[2,0:2])) ax.append(pyplot.subplot(gs[3,0:2])) # read in the results from each model for i, cfile in enumerate(filenames): # read in the image timage = np.squeeze(fits.getdata(cfile)) if displaynames[i] in ['CRT','SOC']: timage = np.rot90(timage,3) if timage.shape[0] == 300: timage = timage[9:260,45:255] elif timage.shape[0] == 600: timage = timage[19:520,90:510] # save the image in a cube if i == 0: nx = timage.shape[0] ny = timage.shape[1] all_images = np.empty((timage.shape[0],timage.shape[1],n_files)) minmax_vals = np.empty((n_files,2)) if timage.shape[0] > 300: cut1 *= 2 cut2 *= 2 all_images[:,:,i] = timage # get the image for comparison (if desired) ave_image_comp = np.median(all_images,axis=2) if comp_index > -2: if comp_index >= 0: ave_image_comp = np.array(all_images[:,:,comp_index]) #for i in range(n_files): # all_images[:,:,i] = all_images[:,:,i] - ave_image_comp # timage = all_images[:,:,i] # gindxs = np.where(ave_image_comp[:] > 0.) # timage[gindxs] /= ave_image_comp[gindxs] # get the min/max to plot for i in range(n_files): timage = all_images[:,:,i] #if comp_index > -2: # gindxs = np.where(np.isfinite(timage[:])) #else: gindxs = np.where((timage[:] > 0.) & (timage[:] < np.max(timage[:]))) if len(gindxs[0]) > 0: minmax_vals[i,0] = np.min(timage[gindxs]) minmax_vals[i,1] = np.max(timage[gindxs]) else: print(i,cfile,' has no positive values') #if comp_index > -2: # plot_minmax = [-0.1,0.1] #else: gindxs, = np.where(minmax_vals[:,0] > 0) plot_minmax = [np.median(minmax_vals[gindxs,0]), np.median(minmax_vals[gindxs,1])] # cut plot variables cut1_minmax_x_vals = np.array([1e6,-1e6]) cut1_minmax_y_vals = np.array([1e6,-1e6]) cut1_plot_x = np.arange(nx) cut2_minmax_x_vals = np.array([1e6,-1e6]) cut2_minmax_y_vals = np.array([1e6,-1e6]) cut2_plot_x = np.arange(ny) cut1_plot_y_all = np.median(ave_image_comp[:,cut1[0]:cut1[1]],axis=1) cut2_plot_y_all = np.median(ave_image_comp[cut2[0]:cut2[1],:],axis=0) # now display the cuts for i in range(n_files): # first cut (y) cut1_plot_y = np.median(all_images[:,cut1[0]:cut1[1],i],axis=1) gindxs, = np.where(cut1_plot_y > 0.) if gindxs.shape[0] > 0: gindxs2 = gindxs[1:-1] cut1_minmax_x_vals[0] = np.min([cut1_minmax_x_vals[0], np.min(cut1_plot_x[gindxs2])]) cut1_minmax_x_vals[1] = np.max([cut1_minmax_x_vals[1], np.max(cut1_plot_x[gindxs2])]) cut1_minmax_y_vals[0] = np.min([cut1_minmax_y_vals[0], np.min(cut1_plot_y[gindxs2])]) cut1_minmax_y_vals[1] = np.max([cut1_minmax_y_vals[1], np.max(cut1_plot_y[gindxs2])]) if i < legsplitval: tname = displaynames[i] else: tname = None ax[n_files].plot(cut1_plot_x[gindxs],cut1_plot_y[gindxs], symtype[fileindxs[i]],label=tname) # percent difference plot for first cut gindxs, = np.where((cut1_plot_y > 0) & (cut1_plot_y_all > 0)) if i >= legsplitval: tname = displaynames[i] else: tname = None y = 100.*((cut1_plot_y[gindxs] - cut1_plot_y_all[gindxs])/ cut1_plot_y_all[gindxs]) ax[n_files+1].plot(cut1_plot_x[gindxs],y, symtype[fileindxs[i]],label=tname) # quantitative info to save # remove the point closest to the star for the theta=90 case # some models assume infinite distance, some assume the correct # finite distance # also remove the point furthest from the star # some models seem to get this *very* wrong - edge case so # not really important for the quantitative comparisons comp_y = y[1:len(y)-1] #print(comp_y[0:5]) comp_y_sigclip = sigma_clip(comp_y,sigma=10.) good_only = comp_y_sigclip.data[~comp_y_sigclip.mask] #print(good_only[0:5]) comp_y = good_only cut1_offset = np.average(comp_y) cut1_stddev = np.average(abs(comp_y)) #cut1_stddev = np.median(abs(comp_y)) cut1_maxabsdev = np.amax(abs(comp_y)) # second cut (x) cut2_plot_y = np.median(all_images[cut2[0]:cut2[1],:,i],axis=0) gindxs, = np.where(cut2_plot_y > 0.) if gindxs.shape[0] > 0: gindxs2 = gindxs[1:-1] cut2_minmax_x_vals[0] = np.min([cut2_minmax_x_vals[0], np.min(cut2_plot_x[gindxs2])]) cut2_minmax_x_vals[1] = np.max([cut2_minmax_x_vals[1], np.max(cut2_plot_x[gindxs2])]) cut2_minmax_y_vals[0] = np.min([cut2_minmax_y_vals[0], np.min(cut2_plot_y[gindxs2])]) cut2_minmax_y_vals[1] = np.max([cut2_minmax_y_vals[1], np.max(cut2_plot_y[gindxs2])]) if i < legsplitval: tname = displaynames[i] else: tname = None ax[n_files+2].plot(cut2_plot_x[gindxs],cut2_plot_y[gindxs], symtype[fileindxs[i]],label=tname) # percent difference plot for first cut gindxs, = np.where((cut2_plot_y > 0) & (cut2_plot_y_all > 0)) if i >= legsplitval: tname = displaynames[i] else: tname = None y = 100.*((cut2_plot_y[gindxs] - cut2_plot_y_all[gindxs])/ cut2_plot_y_all[gindxs]) ax[n_files+3].plot(cut2_plot_x[gindxs],y, symtype[fileindxs[i]],label=tname) # quantitative info to save cut2_offset = np.average(y) cut2_stddev = np.average(abs(y)) #cut2_stddev = np.median(abs(y)) cut2_maxabsdev = np.amax(abs(y)) tab.add_row([displaynames[i], i, cut1_offset, cut1_stddev, cut1_maxabsdev, cut2_offset, cut2_stddev, cut2_maxabsdev]) # min y value to plot for percentage plots # keeps the % difference plot from going to *very* small numbers min_yval = 1e-2 # setup for the first cut plot ax[n_files].set_yscale('log') cut1_minmax_x_vals[0] -= 0.1*(cut1_minmax_x_vals[1] - cut1_minmax_x_vals[0]) cut1_minmax_x_vals[1] += 0.5*(cut1_minmax_x_vals[1] - cut1_minmax_x_vals[0]) ax[n_files].set_xlim(cut1_minmax_x_vals) cut1_minmax_y_vals[0] = 10**(np.log10(cut1_minmax_y_vals[0]) - (0.1*(np.log10(cut1_minmax_y_vals[1]) - np.log10(cut1_minmax_y_vals[0])))) cut1_minmax_y_vals[1] = 10**(np.log10(cut1_minmax_y_vals[1]) + (0.1*(np.log10(cut1_minmax_y_vals[1]) - np.log10(cut1_minmax_y_vals[0])))) ax[n_files].set_ylim(cut1_minmax_y_vals) ax[n_files].set_ylabel('SB [MJy/sr]') ax[n_files].set_title('Y slice ($'+str(cut1[0])+' \leq x \leq '+ str(cut1[1])+ '$)') # ax[n_files].set_xlim(95.,120.) # ax[n_files].set_ylim(0.3,0.5) leg = ax[n_files].legend(loc=1,fontsize=fontsize) leg.get_frame().set_linewidth(2) ax[n_files+1].set_ylabel('% difference') ax[n_files+1].set_xlim(cut1_minmax_x_vals) cur_ylim = ax[n_files+1].get_ylim() new_ylim = [max([cur_ylim[0],-1.0*max_plot_diff]), min([cur_ylim[1],max_plot_diff])] new_ylim = [min([new_ylim[0], -min_yval]), max([new_ylim[1], min_yval])] ax[n_files+1].set_ylim(new_ylim) if n_files > legsplitval: leg = ax[n_files+1].legend(loc=1,fontsize=fontsize) leg.get_frame().set_linewidth(2) # setup for the second cut plot ax[n_files+2].set_yscale('log') cut2_minmax_x_vals[0] -= 0.1*(cut2_minmax_x_vals[1] - cut2_minmax_x_vals[0]) cut2_minmax_x_vals[1] += 0.5*(cut2_minmax_x_vals[1] - cut2_minmax_x_vals[0]) ax[n_files+2].set_xlim(cut2_minmax_x_vals) cut2_minmax_y_vals[0] = 10**(np.log10(cut2_minmax_y_vals[0]) - (0.1*(np.log10(cut2_minmax_y_vals[1]) - np.log10(cut2_minmax_y_vals[0])))) cut2_minmax_y_vals[1] = 10**(np.log10(cut2_minmax_y_vals[1]) + (0.1*(np.log10(cut2_minmax_y_vals[1]) - np.log10(cut2_minmax_y_vals[0])))) ax[n_files+2].set_ylim(cut2_minmax_y_vals) ax[n_files+2].set_ylabel('SB [MJy/sr]') ax[n_files+2].set_title('X slice ($'+str(cut2[0])+' \leq y \leq '+ str(cut2[1])+ '$)') leg = ax[n_files+2].legend(loc=1,fontsize=fontsize) leg.get_frame().set_linewidth(2) ax[n_files+3].set_ylabel('% difference') ax[n_files+3].set_xlim(cut2_minmax_x_vals) cur_ylim = ax[n_files+3].get_ylim() new_ylim = [max([cur_ylim[0],-1.0*max_plot_diff]), min([cur_ylim[1],max_plot_diff])] new_ylim = [min([new_ylim[0], -min_yval]), max([new_ylim[1], min_yval])] ax[n_files+3].set_ylim(new_ylim) if n_files > legsplitval: leg = ax[n_files+3].legend(loc=1,fontsize=fontsize) leg.get_frame().set_linewidth(2) #mpl.cm.register_cmap(name='cubehelix3', # data=mpl._cm.cubehelix(gamma=1.0, start=0.0, rot=1.0, hue=320.)) # Heddy's nice cubehelix using the "cubehelix" pacakge (not built into matplotlib custcmap = cubehelix.cmap(reverse = False, rot=1, start=0, startHue=320, sat = 2) # now display the images cutpwidth = 4 for i in range(n_files): # add in the image cut boxes if i == 0: all_images[:,cut1[0]-cutpwidth:cut1[0],i] = np.amax(all_images[:,:,i]) all_images[:,cut1[1]:cut1[1]+cutpwidth,i] = np.amax(all_images[:,:,i]) if i == 1: all_images[cut2[0]-cutpwidth:cut2[0],:,i] = np.amax(all_images[:,:,i]) all_images[cut2[1]:cut2[1]+cutpwidth,:,i] = np.amax(all_images[:,:,i]) # display images cur_cax = ax[i].imshow(all_images[:,:,i], norm=LogNorm(vmin=cut1_minmax_y_vals[0], vmax=cut1_minmax_y_vals[1]), origin='lower', cmap=custcmap) # cmap=pyplot.get_cmap('cubehelix3')) ax[i].set_title(displaynames[i],fontsize=fontsize) ax[i].get_xaxis().set_visible(False) ax[i].get_yaxis().set_visible(False) # add the overall label fig.text (0.5, 0.99, fig_label, horizontalalignment='center', verticalalignment='top',fontsize=1.5*fontsize) # colorbar - force to have 4 ticks log_yvals = np.log10(cut1_minmax_y_vals) tick_vals = np.logspace(log_yvals[0],log_yvals[1],num=4) formatter = ticker.LogFormatter(10, labelOnlyBase=False) cb = fig.colorbar(cur_cax, cax=(pyplot.subplot(gs[0:nrows,n_image_col+2])), ticks=tick_vals, format=formatter) # optimize the figure layout gs.tight_layout(fig, rect=[0, 0.03, 1, 0.96], h_pad=0.25) # display the plot save_name = 'slab_t' + tau + '_i' + angle + '_w' + wave + '_image_comp' if save_str != '': save_name += '_' + save_str # save the table of the offsets and standard deviations tab.write('dat/'+save_name+'.dat', format='ascii.commented_header') if save_png: fig.savefig(save_name+'.png') fig.savefig(save_name+'_small.png',dpi=11) elif save_eps: fig.savefig(save_name+'.eps') elif save_pdf: fig.savefig(save_name+'.pdf') else: pyplot.show() pyplot.close(fig)
matplotlib.rc('xtick.major', width=2) matplotlib.rc('ytick.major', width=2) matplotlib.rc('xtick.minor', width=2) matplotlib.rc('ytick.minor', width=2) # setup figure fig, ax = pyplot.subplots(nrows=3,ncols=5,figsize=(10,6), gridspec_kw = {'height_ratios':[0.435,0.13,0.435]}) # 3 wavelengths, 5 angles modname = 'dirty_newforcebiasxi' xis = ['0.0','0.1','0.5','0.9','1.0'] angles = ['000','090','180'] custcmap = cubehelix.cmap(reverse = False, rot=1, start=0, startHue=320, sat = 2) wave = args.wave if wave == '035.11': minmax_y_vals = np.array([[0.1,1.0], [1e-2,1e0], [0.1,1.0]]) elif wave == '151.99': minmax_y_vals = np.array([[100.,250.], [1e0,1e4], [100.,250.]]) else: wave = '000.15' minmax_y_vals = np.array([[5e-4,1.5e-3], [1e-40,1.0], [1e-34,1e-31]])
def plotspec(specData, bandNames, limits, objID, classType, grav=None, plotInstructions=None, figNum=1): # Plots set of spectral data and saves plots in a PDF file. # specData and limits must be dictionaries. import matplotlib.pyplot as plt import types import numpy as np import cubehelix import matplotlib as mpl # 2) Initialize variables & color sets ==================================== cx = cubehelix.cmap(start=0.5, rot=-1.5, sat=1, gamma=1.5) BLACK = '#000000' GRAY = '#999999' WHITE = '#FFFFFF' X_LABEL = 'Wavelength ($\mu$m)' Y_LABEL = 'Normalized Flux (F$_{\lambda}$)' # 3) Initialize Figure ==================================================== plt.close() plt.rc('font', size=8) fig = plt.figure(figNum, figsize=(6.61417, 3.54)) # 168mm x 90mm (9,6)) plt.clf() # 4) Generate Subplots ==================================================== for bandIdx, band in enumerate(bandNames): # 4a) If band data is only one set, convert into array of sets -------- if specData[band][0] is not None: if len(specData[band][0]) > 3: specData[band] = [specData[band],] # 4b) Initialize variables -------------------------------------------- spLines = [] minPlot = 1 maxPlot = 1 # Count the number of plots in order to select color set if plotInstructions is not None: tmpFld = np.where(np.array(plotInstructions) == 'field') tmpYng = np.where(np.array(plotInstructions) == 'young') numFld = len(tmpFld[0]) numYng = len(tmpYng[0]) specNum = numFld + numYng else: specNum = len(filter(None, specData[band])) plotcolors = cx(np.linspace(0,1,specNum)) cxmap = mpl.cm.coolwarm(np.linspace(0,1,specNum)) #plt.rc('axes', color_cycle=list(cxmap)) # 4c) Initialize Subplot ---------------------------------------------- # Determine position of Subplot multH = 0 multV = 1 gapHoriz = 0.03 gapVertic = 0.04 plotHeight = 0.9 # proportion of total height (11 inches) plotWidth = 0.95 # proportion of total width (8.5 inches) edgeLeft = 0.03 #+ (plotWidth + gapVertic) * multH edgeBottom = 0.08 #+ (plotHeight + gapHoriz) * multV plotLoc = [edgeLeft, edgeBottom, plotWidth, plotHeight] subPlot = plt.figure(figNum).add_axes(plotLoc) subPlot.set_autoscale_on(False) # Set figure and axes labels if grav == 'Y': plotType = ' young' elif grav == 'B': plotType = r'$\beta$' elif grav == 'G': plotType = r'$\gamma$' elif grav == 'F': plotType = ' field' else: plotType = '' title = classType if plotType != '': title = title + plotType subPlot.set_xlabel(X_LABEL, labelpad=0) subPlot.set_ylabel(Y_LABEL, labelpad=0) subPlot.set_title(title, fontsize=15, fontweight='bold', \ position=(0.01,0.75), ha='left') # 4d) Determine order of spectra plotting ----------------------------- zOrders = [None] * len(plotInstructions) countColor = specNum for plotIdx,plot in enumerate(plotInstructions): zOrders[plotIdx] = specNum - countColor countColor = countColor - 1 # 4e) Plot spectral data in Subplot ----------------------------------- icolor = 0 for specIdx, spec in enumerate(filter(None,specData[band])): if spec is None: continue if plotInstructions[specIdx] == 'exclude': continue # Determine line parameters lnWidth = 0.5 objLabel = objID[specIdx] clr = plotcolors[icolor] icolor = icolor + 1 subPlot.plot(spec[0], spec[1], dash_joinstyle='round', \ linewidth=lnWidth, label=objLabel, \ drawstyle='steps-mid', zorder=zOrders[specIdx]) # Track the highest & lowest y-axis values to fix y-axis limits later if plotInstructions[specIdx] != 'exclude': tmpMin = np.nanmin(spec[1]) if tmpMin < minPlot: minPlot = tmpMin tmpMax = np.nanmax(spec[1]) if tmpMax > maxPlot: maxPlot = tmpMax # 4f) Fix axes limits ------------------------------------------------- minPlot = minPlot - minPlot * 0.1 maxOff = 0.1 maxPlot = maxPlot + maxPlot * maxOff plt.ylim(ymin=minPlot, ymax=maxPlot) plt.xlim(xmin=limits[band]['lim'][0], \ xmax=limits[band]['lim'][1] * 1.001) # 4g) Customize y axis ------------------------------------------------ subPlot.spines['left'].set_color('none') subPlot.spines['right'].set_color('none') subPlot.yaxis.set_ticks([]) # Add colorbar manually ax1 = fig.add_axes([0.73, 0.7, 0.23, 0.04]) cb1 = mpl.colorbar.ColorbarBase(ax1, orientation='horizontal', \ cmap=mpl.cm.coolwarm) cb1.dividers=False cb1.outline.set_edgecolor(WHITE) cb1.set_ticks((0.01,0.5,0.99)) cb1.set_ticklabels(('1.1','1.45','1.8')) subPlot.text(0.861, 0.742, r'$J-K$', transform=subPlot.transAxes, ha='center') # objLegends = subPlot.legend(handlelength=0, handletextpad=0.1, \ # loc='upper right', ncol=2, \ # labelspacing=0.3, numpoints=1) # objLegends.draw_frame(True) # # for legendIdx, legendText in enumerate(objLegends.get_texts()): # plt.setp(legendText, \ # fontsize=7, fontname='Andale Mono') # 4h) Add absorption annotations to Subplots addannot(specData[band], subPlot, classType) return fig
from astropy.io import fits from astropy import units as u from astropy.stats import sigma_clip # AstroML from astroML.plotting import hist # SEP import sep # Cubehelix color scheme import cubehelix # Cubehelix color scheme from https://github.com/jradavenport/cubehelix # For high-contrast image cmap1 = cubehelix.cmap(start=0.5, rot=-0.8, gamma=1.0, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0) cmap1.set_bad('k', 1.) # For Mask cmap2 = cubehelix.cmap(start=2.0, rot=-1.0, gamma=2.5, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0, reverse=True) # For Sigma cmap3 = cubehelix.cmap(start=0.5,
if args.plot_orbits: plt.clf() plt.plot(w[...,0], w[...,2], marker=None) plt.title(title) plt.xlim(-40,40) plt.ylim(-40,40) plt.savefig(os.path.join(lm.output_path, "orbit_{}.png".format(fn))) fig = plt.figure(figsize=(8,8)) ax = fig.add_subplot(111) ax.set_axis_bgcolor("#eeeeee") #cax = ax.scatter(X[chaotic], Y[chaotic], c='k', s=75, cax = ax.scatter(X[chaotic], Y[chaotic], c=dm, s=75, edgecolor='#666666', marker='o', cmap=cubehelix.cmap()) # ax.plot(X[~chaotic], Y[~chaotic], color='k', markeredgewidth=1., # markeredgecolor='k', marker='x', linestyle='none', markersize=10) fig.colorbar(cax) ax.set_xlabel(xname) ax.set_ylabel(yname) fig.savefig(os.path.join(lm.output_path, "grid.png")) """ # YETI mpiexec -n 4 /vega/astro/users/amp2217/anaconda/bin/python /vega/astro/users/amp2217/p\ rojects/nonlinear-dynamics/scripts/pal5.py -v --xparam q1 5 0.7 1.8 --yparam qz 5 0.7 \ 1.8 --nsteps=10000 --mpi --prefix=/vega/astro/users/amp2217/projects/nonlinear-dynamics/output/pal5 python /vega/astro/users/amp2217/projects/nonlinear-dynamics/scripts/pal5.py -v --xparam phi 16 0. 1.7 --yparam r_halo 8 --nsteps=10000 --dt=5. --prefix=/vega/astro/users/amp2217/projects/nonlinear-dynamics/output/pal5 --plot-orbits --plot-indicators
#!/usr/bin/env python # encoding: utf-8 """Convert DS9 regions into mask image.""" from __future__ import division import os import copy import numpy as np import argparse from astropy.io import fits import cubehelix # For high-contrast image cmap1 = cubehelix.cmap(start=0.5, rot=-0.8, gamma=1.0, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0) cmap1.set_bad('k', 1.) # import coaddCutoutPrepare as ccp # Matplotlib related import matplotlib as mpl mpl.use('Agg') mpl.rcParams['figure.figsize'] = 12, 10 mpl.rcParams['xtick.major.size'] = 8.0 mpl.rcParams['xtick.major.width'] = 1.5 mpl.rcParams['xtick.minor.size'] = 4.0 mpl.rcParams['xtick.minor.width'] = 1.5 mpl.rcParams['ytick.major.size'] = 8.0 mpl.rcParams['ytick.major.width'] = 1.5 mpl.rcParams['ytick.minor.size'] = 4.0
import numpy as np import matplotlib.pyplot as plt import cubehelix # set up some simple data to plot x = np.random.randn(10000) y = np.random.randn(10000) cx1 = cubehelix.cmap(startHue=240,endHue=-300,minSat=1,maxSat=2.5,minLight=.3,maxLight=.8,gamma=.9) plt.hexbin(x,y,gridsize=50,cmap=cx1) plt.colorbar() #plt.savefig('rainbow.png')
seabed = np.load('data/Penobscot_Seabed.npy') # Finesse the hillshade if you want to. ls = LightSource(azdeg=225, altdeg=140) bumps = ls.hillshade(seabed) # bumps = ls.hillshade(seabed)**0.5 # Sqrt backs it off a bit. # Make the plot. fig = plt.figure(figsize=(18, 8), facecolor='white') ax = fig.add_subplot(111) kmap = make_colormap([(0, 0, 0)]) kmap4 = add_alpha(kmap) cx = cubehelix.cmap(0.75, -0.75, reverse=True, min_light=0.3) params = dict(cmap=cx, aspect=0.5, origin='lower') xlines, inlines = seabed.shape x, y = np.arange(inlines), np.arange(xlines) X, Y = np.meshgrid(x, y) mi, ma = np.floor(np.nanmin(seabed)), np.ceil(np.nanmax(seabed)) levels = np.arange(mi, ma) # Plot everything. ax0 = fig.add_subplot(221) ax0.imshow(seabed, **params) ax0.axis('off') ax1 = fig.add_subplot(222)
def seq_cmap(ncolors=1024): """Create a sequential colormap using cubehelix.""" ch = cubehelix.cmap(start=1.5, rot=-1, reverse=True) # Limit to a discrete number of color intervals. return ListedColormap( ch( np.linspace(0., 1., ncolors) ) )
import os, sys, pygame, fileinput from pygame.locals import * from math import pi, sqrt, sin, cos, asin, atan import numpy as np has_color = True try: import cubehelix as ch except ImportError: print "Could not find cube-helix colormap. No colors." has_color = False if has_color: awesome_1 = ch.cmap() awesome = awesome_1(np.arange(256)) WHITE = 255, 255, 255 GREEN = 0, 255, 0 BLACK = 0, 0, 0 BLUE = 0, 0, 255 RED = 255, 0, 0 vel_scale = 5 pos_scale = 1 pos_offs = 0 poly_scale = 10 poly = [(1, 0), (0, 1 / 3.0), (0, -1 / 3.0), (1, 0)] def rotate((x, y), a): return (x * cos(a) - y * sin(a), x * sin(a) + y * cos(a))
pars = ['period', 'oc', 'os', 'inclination', 'pm', 'T1', 'temprat', 'q1', 'q2', 'pk'] #ELC names parindices = [2, 4, 5, 6, 7, 8, 9, 10, 11, 12] #ELC index nbins = 50 # number of histogram bins (same in both dimensions) # Files that have stuff in them gridloop = filepath + 'gridloop.opt' parfile = filepath + 'generation.all' lcmodel = filepath + 'modelU.mag' lcdata = filepath + 'ELCdataU.fold' rv1model = filepath + 'star1.RV' rv1data = filepath + 'ELCdataRV1.fold' rv2model = filepath + 'star2.RV' rv2data = filepath + 'ELCdataRV2.fold' # Color map for 2D histogram "contours" cx = cubehelix.cmap(reverse=True, maxLight=0.7, start=0., rot=0.5) # Plot colors and LC/RV axis limits red = '#e34a33' # red, star 1 yel = '#fdbb84' # yellow, star 2 phasemin = 0 phasemax = 1 magdim = 9.54 magbright = 9.21 rvmin = -59 rvmax = 59 # Function to fold stuff if it isn't folded already def phasecalc(times, period=100, BJD0=2454833): phases = [] cycles = []
def seq_cmap(ncolors=1024): """Create a sequential colormap using cubehelix.""" ch = cubehelix.cmap(start=1.5, rot=-1, reverse=True) # Limit to a discrete number of color intervals. return ListedColormap(ch(np.linspace(0., 1., ncolors)))
def helix_tables(module, flag, inv=False, values=None): """ Port of P-Smac2/lib/idl/helix_tables.pro of P-Smac colormaps. @param module --> int, corresponds to P-Smac2 module @param flag --> int, corresponds to P-Smac2 flag @param inv --> bool, invert colormap @param values --> iterable of length 4, use given values instead Cubehelix parameters: [ start, rots, hue, gamma] returns a cubehelix colormap ready to use in e.g. pyplot :-) """ if type(module) != int: module = int(module) if type(flag) != "int": flag = int(flag) nModule = 15 nFlag = 15 setup = numpy.zeros((4, nModule, nFlag), dtype=numpy.float) # std values for i in range(0, nModule-1): for j in range(0, nFlag-1): setup[:,i,j] = [ -0, 0, 2.5, 1 ] # density setup[:, 0, 0] = [ 3, 3, 3, 2 ] # velocities setup[:, 1, 0] = [ 1, 1.5, 2, 1 ] # x-rays setup[:, 2, 0] = [ 2, -2, 3, 1 ] # Temperature setup[:, 4, 0] = [ 0.9, 0, 1, 1 ] # Mass Weighted setup[:, 4, 1] = [ 1, 0, 1, 1 ] # Sound Speed setup[:, 4, 2] = [ 1, 0, 1, 1 ] # Emission Weighted setup[:, 4, 3] = [ 1.3, -0.5, 2, 2 ] # Spectroscopic # Pressure setup[:, 5, 0] = [ 0, 3, 1, 1 ] # magnetic field setup[:, 6, 0] = [ 3, 0, 3, 2] # Compton-Y / SZ setup[:, 7, 0] = [ 3, -1, 4, 1 ] setup[:, 7, 1] = [ 2, 1, 4, 1 ] # Dm density setup[:, 10, 0] = [ 3, -1, 4, 1 ] setup[:, 11, 0] = [ 1, 0, 1.4, 1 ] if values: setup[:, module, flag] = values # set start, rots, hue, gamma = setup[:, module, flag] # Cubehelix guy changed "hue" to "sat". cx = cubehelix.cmap(start=start, rot=rots, sat=hue, gamma=gamma, reverse=inv) return cx
def previewCoaddImage(img, msk, var, det, sizeX=10, sizeY=10, prefix='hsc_cutout', outPNG=None, oriX=None, oriY=None, boxW=None, boxH=None): """ Generate a preview figure. Parameters: """ fig, axes = plt.subplots(sharex=True, sharey=True, figsize=(sizeX, sizeY)) # Image cmap = cubehelix.cmap(start=0.5, rot=-0.8, minSat=1.2, maxSat=1.2, minLight=0., maxLight=1., gamma=1.0) cmap.set_bad('k', 1.) imin, imax = hUtil.zscale(img, contrast=0.05, samples=500) ax1 = plt.subplot(2, 2, 1) ax1.imshow(np.arcsinh(img), interpolation="none", vmin=imin, vmax=imax, cmap=cmap, origin='lower') ax1.minorticks_on() ax1.xaxis.set_visible(False) ax1.yaxis.set_visible(False) ax1.text(0.5, 0.9, 'Coadd Image', fontsize=25, fontweight='bold', ha='center', va='center', color='r', transform=ax1.transAxes) ax1.plot([150, 269.1], [150, 150], 'r-', lw=2.5) ax1.text(209, 200, '20"', fontsize=15, ha='center', va='center', color='r', fontweight='bold') ax1.margins(0.00, 0.00, tight=True) # Variance cmap = cubehelix.cmap(start=0.5, rot=-0.8, reverse=True, minSat=1.1, maxSat=1.2, minLight=0., maxLight=1., gamma=0.5) cmap.set_bad('k', 1.) smin, smax = hUtil.zscale(var, contrast=0.1, samples=500) if (smax < smin * 1.001): smax = smin * 1.001 ax2 = plt.subplot(2, 2, 2) ax2.imshow(np.arcsinh(var), interpolation="none", vmin=smin, vmax=smax, cmap=cmap, origin='lower') ax2.minorticks_on() ax2.xaxis.set_visible(False) ax2.yaxis.set_visible(False) ax2.text(0.5, 0.9, 'Variance', fontsize=25, fontweight='bold', ha='center', va='center', color='r', transform=ax2.transAxes) # Mask ax3 = plt.subplot(2, 2, 3) ax3.imshow((msk * 2) + det, cmap=cubehelix.cmap(reverse=True), origin='lower') ax3.minorticks_on() ax3.xaxis.set_visible(False) ax3.yaxis.set_visible(False) ax3.text(0.5, 0.9, 'Mask Plane', fontsize=25, fontweight='bold', ha='center', va='center', color='r', transform=ax3.transAxes) # If necessary, outline the BBox of each overlapped Patch if ((oriX is not None) and (oriY is not None) and ( boxW is not None) and (boxH is not None)): numBox = len(oriX) for ii in range(numBox): box = mpatches.Rectangle((oriX[ii], oriY[ii]), boxW[ii], boxH[ii], fc="none", ec=np.random.rand(3, 1), linewidth=3.5, alpha=0.7, linestyle='dashed') ax3.add_patch(box) # Masked Image imgMsk = copy.deepcopy(img) imgMsk[(msk > 0) | (det > 0)] = np.nan mmin, mmax = hUtil.zscale(img, contrast=0.75, samples=500) cmap = cubehelix.cmap(start=0.5, rot=-0.8, minSat=1.2, maxSat=1.2, minLight=0., maxLight=1., gamma=1.0) cmap.set_bad('k', 1.) ax4 = plt.subplot(2, 2, 4) ax4.imshow(np.arcsinh(imgMsk), interpolation="none", vmin=mmin, vmax=mmax, cmap=cmap, origin='lower') ax4.minorticks_on() ax4.xaxis.set_visible(False) ax4.yaxis.set_visible(False) ax4.text(0.5, 0.9, 'Masked Image', fontsize=25, fontweight='bold', ha='center', va='center', color='r', transform=ax4.transAxes) # Adjust the figure plt.subplots_adjust(hspace=0.0, wspace=0.0, bottom=0.0, top=1.0, right=1.0, left=0.0) # Save a PNG file if outPNG is None: outPNG = prefix + '_pre.png' plt.savefig(outPNG, dpi=80) plt.close(fig)
table_sky = np.column_stack( (xxc.flatten(), yyc.flatten(), img_sky.flatten())) temp_sky = pd.DataFrame(table_sky, columns=['x', 'y', band]) df_sky = pd.concat([df_sky, temp_sky], axis=1) df = df.ix[:, [0, 1, 2, 5, 8, 11, 14]] df_sky = df_sky.ix[:, [0, 1, 2, 5, 8, 11, 14]] ''' Imagem da galaxia, na banda r. ''' plt.figure(1) plt.clf() r_sdss = fits.open('data/frame-r-%s' % (df_fit['name'][i_gal])) img_r = get_image(r_sdss) img_cut_r = img_r[interval[0]:interval[1], interval[2]:interval[3]] cx = cubehelix.cmap(reverse=True, start=0., rot=-0.5) imgplot = plt.imshow(100 * np.log10(img_cut_r / 255), cmap='spectral') titulo = 'Galaxy #%s - banda r' % (df_cat['num'][i_object]) plt.title(titulo) plt.colorbar() figura = 'figures/galaxy_#%s' % df_cat['num'][i_object] plt.savefig(figura) ''' Imagem segmentada da galaxia, na banda r. ''' plt.figure(1) plt.clf() cx = cubehelix.cmap(reverse=True, start=0., rot=-0.5) imgplot = plt.imshow(seg_sex, cmap='spectral') titulo = 'Segmentation Galaxy #%s - banda r' % (df_cat['num'][i_object]) plt.title(titulo)
# Astropy from astropy.io import fits from astropy import units as u from astropy.stats import sigma_clip # AstroML from astroML.plotting import hist # SEP import sep # Cubehelix color scheme import cubehelix # Cubehelix color scheme from https://github.com/jradavenport/cubehelix # For high-contrast image cmap1 = cubehelix.cmap(start=0.5, rot=-0.8, gamma=1.0, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0) cmap1.set_bad('k',1.) # For Mask cmap2 = cubehelix.cmap(start=2.0, rot=-1.0, gamma=2.5, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0, reverse=True) # For Sigma cmap3 = cubehelix.cmap(start=0.5, rot=-0.8, gamma=1.2, minSat=1.2, maxSat=1.2, minLight=0.0, maxLight=1.0) # Matplotlib related import matplotlib as mpl mpl.use('Agg') mpl.rcParams['figure.figsize'] = 12, 10
import os, sys, pygame, fileinput from pygame.locals import * from math import pi,sqrt,sin,cos,asin,atan import cubehelix as ch import numpy as np awesome_1 = ch.cmap() awesome = awesome_1(np.arange(256)) WHITE = 255,255,255 GREEN = 0,255,0 BLACK = 0,0,0 BLUE = 0,0,255 RED = 255,0,0 vel_scale = 5 pos_scale = 1 pos_offs = 0 poly_scale = 10; poly = [ (1,0), (0,1/3.0), (0,-1/3.0), (1,0) ] def rotate((x,y),a): return (x*cos(a)-y*sin(a), x*sin(a)+y*cos(a)) def sign(x): if(x < 0): return -1
def plotClusteringDistribution(lenconstraint,Folder_name,Lenrna): D=scipy.zeros([lenconstraint,lenconstraint]) Dic,B=Load_Probabilities(Folder_name) clusters=defaultdict(a) #print Dic.values(),"ddddddddddddddddddddd" for element in Dic.keys(): print Dic[element] #calculate the Eucledian distance between different entries D=Eucledian_distance(B,Lenrna) data= np.array(D) #rows=[Dic[element][-4:] for element in Dic.keys()] #columns=[Dic[element][4:] for element in Dic.keys()] rows=[Dic[element] for element in Dic.keys()] columns=[Dic[element] for element in Dic.keys()] #print "Clustering with kmeans for n=3"#n=8 # by looking at the reuslt of spectralbilustering, it seeems that a subdivision of 8 is the appropriate one algorithm = cluster.MiniBatchKMeans(n_clusters=8)# 8 #algorithm=cluster.AffinityPropagation(damping=.9, preference=None) algorithm.fit(data) if hasattr(algorithm, 'labels_'): y_pred = algorithm.labels_.astype(np.int) else: y_pred = algorithm.predict(data) for i in range(len(y_pred)): clusters[y_pred[i]].append(Dic[i]) print clusters # score = consensus_score(model.biclusters_,(rows[:, row_idx], columns[:, col_idx])) # order ['NMIAMg', '1M7ILU', 'DMSMg', 'NO', 'NMIA','Nai','1M7ILUMg', '1M7ILU3Mg', 'CMCTMg','NaiMg', 'NMIAMgCE', 'BzCNMg','1M7', '1M7Mg' ,'1M7ILU3'] model = SpectralBiclustering( random_state=0) model.fit(data) fit_data = data[np.argsort(model.row_labels_)] fit_data = fit_data[:, np.argsort(model.column_labels_)] #fit_data = data[np.array([6,0,8,13,11,4,10,2,14,1,12,3,9,7,5])] #fit_data = fit_data[:, np.array([6,0,8,13,11,4,10,2,14,1,12,3,9,7,5])] fig = plt.figure() ax = fig.add_subplot(111) orig=ax.matshow(data, cmap=plt.cm.Blues) fig.colorbar(orig) #plt.title("Base pairs eucledian distance between probing conditions") ax.set_xticklabels(rows) ax.set_xticks(np.arange(len(rows)))# to show all labels ax.set_yticklabels(columns) ax.set_yticks(np.arange(len(columns))) #plt.show() fig = plt.figure() ax = fig.add_subplot(111) cx2 = cubehelix.cmap(reverse=True)#, "#FC8D62" ,"#8DA0CB", "#E78AC3", "#A6D854" #flatui = ["#66C2A5", "#95a5a6","#E78AC3", "#A6D854", "#FC8D62"] flatui=["#66C2A5","#457d6b","#365d50","#263e36","#17221e"] mycmap = ListedColormap(sns.color_palette(flatui).as_hex()) b2=ax.matshow(fit_data, cmap=mycmap) #b2.ax.tick_params(labelsize=18) cbar=fig.colorbar(b2,ticks=[0,50]) cbar.set_label(label='Euclidean distance',size=12) for font_objects in cbar.ax.yaxis.get_ticklabels(): font_objects.set_size(20) #plt.title("Eucledian Distance matrix between conditions after bi-clustering") #rows=[Dic[label][4:] for label in np.argsort(model.row_labels_)] #columns=[Dic[label][4:] for label in np.argsort(model.column_labels_)] rows=[Dic[label][4:] for label in np.argsort(model.row_labels_)] columns=[Dic[label][4:] for label in np.argsort(model.column_labels_)] #print rows ax.set_xticklabels(rows ,rotation=90) ax.set_xticks(np.arange(len(rows))) ax.set_yticklabels(columns, rotation_mode="anchor") ax.set_yticks(np.arange(len(columns))) ax.grid(False) # Turns off grid on the secondary (right) Axis. #ax.right_ax(False) plt.tick_params(axis='both', which='major', labelsize=13) plt.tight_layout() plt.savefig("bi_clustering.pdf",format="pdf", dpi=None, facecolor='w', edgecolor='w',orientation='portrait', papertype=None,transparent=False, bbox_inches=None, pad_inches=0.1,frameon=None, metadata=None) for i in range(len(B)): print i,Dic[i], np.mean([ D[i][j] for j in range(len(B)) if i!=j]), np.min([ D[i][j] for j in range(len(B)) if i!=j]) #%,[ D[i][j] for j in range(len(B))] print '\n' #print "Distance" , D # Clustering process with th plot adist = np.array(D) amax = np.amax(adist) adist /= amax mds = manifold.MDS(n_components=2, dissimilarity="precomputed", random_state=6) results = mds.fit(adist) coords = results.embedding_ # plot results fig = plt.figure() plt.subplots_adjust(bottom = 0.1) plt.scatter(coords[:, 0], coords[:, 1], marker = 'o',s=100,c="#66C2A5")# s for marker size, c for color k=0 ##print Dic.values() listoriented=['NaiMg', 'NMIAMgCE', 'BzCNMg', 'Nai', '1M7ILUMg', '1M7ILU3Mg', '1M7ILU3', '1M7', '1M7Mg', 'CMCTMg', 'NMIAMg', '1M7ILU', 'DMSMg', 'NMIA'] for label, x, y in zip(listoriented, coords[:, 0], coords[:, 1]): k+=1 Pos=(4,6) topbottom='bottom' if k%2==0: state="right" else: state="left" #if(label=="didyNaiMg"): # state="left" #if(label in ["didyNMIAMgCE","didy(-)","didy1M7ILU3Mg","didy1M7ILU","didyBzCNMg"]): Pos=(4,-4) topbottom='top' plt.annotate( label[4:], xy = (x, y), xytext = Pos, textcoords = 'offset points', ha = state, va = topbottom, fontsize=11, bbox = dict(boxstyle = 'round,pad=0.3', fc = "#66C2A5", alpha = 0.3)) #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) plt.xlim(-0.4, 0.4) plt.ylim(-0.7, 0.6) plt.tick_params(axis='both', which='major', labelsize=11) #plt.show() fig.savefig("Euclidean_distance_dot_plot_Matrix.pdf",format="pdf", dpi=None, facecolor='w', edgecolor='w',orientation='portrait', papertype=None,transparent=False, bbox_inches=None, pad_inches=0.1,frameon=None, metadata=None)
mask[:, xmask > 462000 + 38e3] = 1 vel_masked_KG = np.ma.masked_array(vel_KG, mask) del vel_KG, vel_HG, xmask, ymask, mask # Load min velocities for showing region where velocity is above cutoff x_cutoff_KG, y_cutoff_KG, vsurfini_cutoff_KG, ind_cutoff_grid, ind_cutoff = inverselib.get_velocity_cutoff('Kanger',\ velocity_cutoff=velocity_cutoff,model_dir='INV_SSA_ModelT') x_cutoff_HG, y_cutoff_HG, vsurfini_cutoff_HG, ind_cutoff_grid, ind_cutoff = inverselib.get_velocity_cutoff('Helheim',\ velocity_cutoff=velocity_cutoff,model_dir='INV_SSA_ModelT') # Figure fig = plt.figure(figsize=(3.2, 1.8)) gs = matplotlib.gridspec.GridSpec(1, 2) ax = plt.subplot(gs[0]) cx = cubehelix.cmap(start=1.2, rot=-1.1, reverse=True, minLight=0.1, sat=2) p=plt.imshow(vel_masked_KG/1e3,extent=[np.min(xvel_KG),np.max(xvel_KG),np.min(yvel_KG),\ np.max(yvel_KG)],origin='lower',clim=[0,8],cmap=cx) ax = plt.gca() ax.imshow(image_KG[:,:,0],extent=[np.min(ximage_KG),np.max(ximage_KG),np.min(yimage_KG),\ np.max(yimage_KG)],cmap='Greys_r',origin='lower',clim=[0,0.6]) ax.imshow(vel_masked_KG/1e3,extent=[np.min(xvel_KG),np.max(xvel_KG),np.min(yvel_KG),\ np.max(yvel_KG)],origin='lower',alpha=0.7,clim=[0,8],cmap=cx) plt.contour(x_cutoff_KG, y_cutoff_KG, vsurfini_cutoff_KG, [velocity_cutoff], colors='k', linestyles='dashed', linewidths=1) ax.axis('equal') ax.plot(np.r_[extent_KG[:, 0], extent_KG[0, 0]],
cz_masses = model.get('cz_xm')[t0idx:] loggs = model.get('log_g')[t0idx:] Teffs = np.power(10, logTeffs) Rads = np.power(10, logRs) #len1 = len(times) #original length of timestamps #times = np.array([time for time in times if time >= 1e7]) #len2 = len(times) #truncated length of timestamps >= 1e7 #Teffs = np.array([np.power(10,logTeff) for idx, logTeff in enumerate(logTeffs) if idx >= len1-len2]) #Rads = np.array([np.power(10,logR) for idx, logR in enumerate(logRs) if idx >= len1-len2]) #cz_masses = np.array([cz_mass for idx, cz_mass in enumerate(cz_masses) if idx >= len1-len2]) # colorbar settings cx = cubehelix.cmap(startHue=240,endHue=-300,minSat=1,maxSat=2.5,minLight=.3,maxLight=.8,gamma=.9) def integrand(Teff, cz_mass, Rad): ''' see Equation 5 in Verbunt & Phinney 1995 ''' teff_part = np.power((Teff/4500.), (4./3.)) mass_part = np.power(cz_mass, (2./3.)) rad_part = np.power(Rad, 8.) return teff_part * mass_part * rad_part def dlnecalc(f, Mcomp, q, Int, Porb): ''' see Equation 6 in Verbunt & Phinney 1995 ''' return -1.7e-5 * f * np.power(Mcomp, -11./3.) * q * np.power((1.+q), -5./3.) * Int * np.power(Porb, -16./3.)