def plot_projection(surfname,starfname,stars=True,writefile=True,runaway=True,aux={},norm_factor=2.,active=False): plt.rc('font',size=11) plt.rc('xtick',labelsize=11) plt.rc('ytick',labelsize=11) fig=plt.figure(0,figsize=(5.5,5)) gs = gridspec.GridSpec(2,2,width_ratios=[1,0.03],wspace=0.0) if stars: sp=read_starvtk(starfname) frb=pickle.load(open(surfname,'rb'))#,encoding='latin1') if 'time' in frb: tMyr=frb['time'] else: time,sp=read_starvtk(starfname,time_out=True) tMyr=time*Myr if 'z' in frb: frb=frb['z'] extent=np.array(frb['bounds'])/1.e3 x0=extent[0] y0=extent[2] Lx=extent[1]-extent[0] Lz=extent[3]-extent[2] ax=plt.subplot(gs[:,0]) im=ax.imshow(frb['data'],origin='lower') im.set_extent(extent) if 'norm' in aux: im.set_norm(aux['norm']) if 'cmap' in aux: im.set_cmap(aux['cmap']) if 'clim' in aux: im.set_clim(aux['clim']) # if aux['log']: im.set_norm(LogNorm(*aux['clim'])) ax.text(extent[0]*0.9,extent[3]*0.9, 't=%3d Myr' % tMyr,ha='left',va='top',**(texteffect()))
def plot_projection(surfname, f): global aux plt.rc('font', size=11) plt.rc('xtick', labelsize=11) plt.rc('ytick', labelsize=11) fig = plt.figure(0, figsize=(5.5, 5)) gs = gridspec.GridSpec(2, 2, width_ratios=[1, 0.03], wspace=0.0) sp = read_starvtk(f[:-3] + 'starpar.vtk') frb = pickle.load(open(surfname, 'rb')) extent = np.array(frb['bounds']) / 1.e3 if frb.has_key('time'): tMyr = frb['time'] else: time, sp = read_starvtk(f[:-3] + 'starpar.vtk', time_out=True) tMyr = time * Myr ax = plt.subplot(gs[:, 0]) im = ax.imshow(frb['data'], norm=LogNorm(), origin='lower') im.set_extent(extent) im.set_cmap(aux['surface_density']['cmap']) im.set_clim(aux['surface_density']['clim']) ax.text(extent[0] * 0.9, extent[3] * 0.9, 't=%3d Myr' % tMyr, ha='left', va='top', **(texteffect())) scatter_sp(sp, ax, axis='z', runaway=True, type='surf') sp_legend(ax, top=True) cax = plt.subplot(gs[0, 1]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') cbar.set_label(aux['surface_density']['label']) cax = plt.subplot(gs[1, 1]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') ax.set_xlabel('x [kpc]') ax.set_ylabel('y [kpc]') pngfname = surfname[:-1] + 'png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure( plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close()
def recal_rates(h, sn, base, problem_dir, problem_id): import glob from pyathena.set_plt import units from pyathena.parse_par import parse_par import pandas as pd par, blocks, fields, = parse_par('{}{}/{}.par'.format( base, problem_dir, problem_id)) dt = float(par['output1']['dt'][0]) Lx = float(par['domain1']['x1max'][0]) - float(par['domain1']['x1min'][0]) Ly = float(par['domain1']['x2max'][0]) - float(par['domain1']['x2min'][0]) area = Lx * Ly nhst = len(h.index) starvtk = glob.glob('{}{}/starpar/{}.*.starpar.vtk'.format( base, problem_dir, problem_id)) starvtk.sort() sp = pa.read_starvtk(starvtk[-1]) cl = sp[sp.mass != 0] cl_birth_time = (cl.time - cl.age) #*units['Myr'] cl_mass = cl.mass * units['Msun'] time = np.arange(nhst + 1) * dt + h.index[0] * units['Myr'] Msp, t = np.histogram(cl_birth_time, bins=time, weights=cl_mass) sfr_inst = pd.Series(Msp / area / dt) rates = pd.DataFrame() rates['sfr'] = sfr_inst typeIa = sn[(sn.runaway == 2) | (sn.runaway == -1)] runaway = sn[sn.runaway == 1] cluster = sn[sn.runaway == 0] for lab, sndata in zip(['', '_run', '_cl', '_Ia'], [sn, runaway, cluster, typeIa]): sn_time = sndata.time * units['Myr'] NSN, t = np.histogram(sn_time, bins=time) rates['snr{}'.format(lab)] = NSN / dt / area for rinst_key in ['sfr', 'snr', 'snr_run', 'snr_cl', 'snr_Ia']: rinst = rates[rinst_key] for tbin in [1., 10., 40., 100.]: window = int(tbin / dt) rates['{}{}'.format(rinst_key, int(tbin))] = rinst.rolling( window, min_periods=1).mean() rates.index = time[:-1] return rates
def plot(**kwargs): plt.rc('font', size=11) plt.rc('xtick', labelsize=11) plt.rc('ytick', labelsize=11) dir = kwargs['base_directory'] + kwargs['directory'] fname = glob.glob(dir + 'id0/' + kwargs['id'] + '.????.vtk') fname.sort() fig = plt.figure(0, figsize=(5.5, 5)) gs = gridspec.GridSpec(2, 2, width_ratios=[1, 0.03], wspace=0.0) for f in fname: surfname = dir + 'surf/' + kwargs['id'] + f[-9:-4] + '.surf.p' sp = read_starvtk(f[:-3] + 'starpar.vtk') frb = pickle.load(open(surfname, 'rb')) ax = plt.subplot(gs[:, 0]) im = ax.imshow(frb['data'], norm=LogNorm(), origin='lower') im.set_extent(np.array(frb['bounds']) / 1.e3) im.set_cmap(plt.cm.pink_r) im.set_clim(1.e-1, 1.e2) scatter_sp(sp, ax, axis='z', runaway=True, type='surf') sp_legend(ax, top=True) cax = plt.subplot(gs[0, 1]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') cbar.set_label(r'$\Sigma [M_\odot {\rm pc}^{-2}]$') cax = plt.subplot(gs[1, 1]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') ax.set_xlabel('x [kpc]') ax.set_ylabel('y [kpc]') pngfname = dir + 'surf/' + kwargs['id'] + f[-9:-4] + '.surf.png' canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) canvas.print_figure(pngfname, bbox_inches='tight', num=0, dpi=150) fig.clf()
def slice(slcfname,starfname,fields_to_draw,zoom=1.,aux={},\ writefile=True,tstamp=True,stars=True,field_label=True,norm_factor=2): plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(left=0.10, right=0.90, wspace=0, hspace=0) sp = read_starvtk(starfname) if 'time' in slc_data: tMyr = slc_data['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): data = slc_data[axis][f] ax = plt.subplot(gs[i, j]) im = ax.imshow(data, origin='lower') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) if stars: if j == 0: scatter_sp(sp, ax, axis=axis, runaway=False, norm_factor=norm_factor) elif j == 1: scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) gs2 = gridspec.GridSpec(nf + 2 + stars, 1) gs2.update(left=0.91, right=0.93, hspace=0.05) for j, (im, f) in enumerate(zip(images, fields_to_draw)): cax = plt.subplot(gs2[j + stars]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) if stars: cax = plt.subplot(gs2[0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') axes = fig.axes[:2 * nf] if field_label: for ax, f in zip(axes[:nf], fields_to_draw): if f in aux: if 'label' in aux[f]: lab = aux[f]['label'] label = lab[:lab.rfind(r'\;')] + '$' ax.text(0.5, 0.95, label, size=20, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) if stars: s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: plt.setp(axes[0], 'title', 't=%3d Myr' % tMyr) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname[:-1] + 'png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close(1) else: return fig
def slice2(slcfname,starfname,fields_to_draw,zoom=1.,aux={},\ writefile=True,tstamp=True,stars=True,field_label=True,norm_factor=2): plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 1.2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(top=0.95, left=0.10, right=0.95, wspace=0.05, hspace=0) if stars: sp = read_starvtk(starfname) if 'time' in slc_data: tMyr = slc_data['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[i, j]) if f is 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor, type='surf') if axis is 'y': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) if axis is 'z': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(x0, x0 + Lx) ax.set_aspect(1.0) else: data = slc_data[axis][f] im = ax.imshow(data, origin='lower', interpolation='bilinear') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) for j, (im, f) in enumerate(zip(images, fields_to_draw[1:])): ax = plt.subplot(gs[0, j + 1]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = fig.colorbar(im, cax=cax, orientation='horizontal') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') ax = plt.subplot(gs[0, 0]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: ax = axes[0] ax.text(0.5, 0.95, 't=%3d Myr' % tMyr, size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname + 'ng' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close(1) else: return fig
def plot_slice(slcfname,vtkfname,fields_to_draw,zoom=1.,\ writefile=True,tstamp=True,stars=True,field_label=True): global aux plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data['yextent'][0] y0 = slc_data['yextent'][3] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Nx, Nz = slc_data['y']['nH'].shape Lz = Lz / zoom ix = 2 iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf + ix, iz + ix * 2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, ix]) gs.update(left=0.10, right=0.90, wspace=0, hspace=0) sp = read_starvtk(vtkfname[:-3] + 'starpar.vtk') if slc_data.has_key('time'): tMyr = slc_data['time'] else: time, sp = read_starvtk(vtkfname[:-3] + 'starpar.vtk', time_out=True) tMyr = time * Myr images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): data = slc_data[axis][f] ax = plt.subplot(gs[i, j]) im = ax.imshow(data, origin='lower') if aux[f]['log']: im.set_norm(LogNorm()) extent = slc_data[axis + 'extent'] im.set_extent(extent) im.set_cmap(aux[f]['cmap']) im.set_clim(aux[f]['clim']) images.append(im) if stars: if j == 0: scatter_sp(sp, ax, axis=axis, runaway=False, norm_factor=4.) elif j == 1: scatter_sp(sp, ax, axis=axis, norm_factor=4.) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) gs2 = gridspec.GridSpec(nf + 2 + stars, 1) gs2.update(left=0.91, right=0.93, hspace=0.05) for j, (im, f) in enumerate(zip(images, fields_to_draw)): cax = plt.subplot(gs2[j + stars]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') cbar.set_label(aux[f]['label']) #cax.xaxis.tick_top() #cax.xaxis.set_label_position('top') if aux[f].has_key('cticks'): cbar.set_ticks(aux[f]['cticks']) if stars: cax = plt.subplot(gs2[0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') axes = fig.axes[:2 * nf] if field_label: for ax, f in zip(axes[:nf], fields_to_draw): lab = aux[f]['label'] label = lab[:lab.rfind(r'\;')] + '$' ax.text(0.5, 0.95, label, size=20, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) if stars: legend = sp_legend(axes[-1], top=False, norm_factor=4.) plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: # axes[0].text(x0*0.9,y0*0.9, # 't=%3d Myr' % tMyr,ha='left',va='top',**(texteffect(16))) plt.setp(axes[0], 'title', 't=%3d Myr' % tMyr) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname[:-1] + 'png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=1, dpi=150) plt.close()
def slice3(slcfname,fields_to_draw,axis='y',extent=None,\ writefile=True,tstamp=True,field_label=True): global aux plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb')) x0 = slc_data[axis + 'extent'][0] y0 = slc_data[axis + 'extent'][2] print x0, y0 Lx = slc_data[axis + 'extent'][1] - slc_data[axis + 'extent'][0] Ly = slc_data[axis + 'extent'][3] - slc_data[axis + 'extent'][2] if extent is None: extent = [x0, x0 + Lx, y0, y0 + Ly] x0 = extent[0] y0 = extent[2] lx = extent[1] - extent[0] ly = extent[3] - extent[2] print extent, lx, ly ix = 2 iz = ix * ly / lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + ix * 1.2)) gs = gridspec.GridSpec(1, nf) gs.update(top=0.95, left=0.10, right=0.95, wspace=0.05, hspace=0) norm_factor = 2. starname = slcfname.replace('slice/', 'id0/').replace('slice.p', 'starpar.vtk') sp = read_starvtk(starname) if slc_data.has_key('time'): tMyr = slc_data['time'] else: time, sp = read_starvtk(starname, time_out=True) tMyr = time * Myr images = [] star_axis = -1 for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[0, j]) if f is 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor, type='surf') ax.set_xlim(x0, x0 + lx) ax.set_ylim(y0, y0 + ly) ax.set_aspect(1.0) star_axis = j else: data = slc_data[axis][f] im = ax.imshow(data, origin='lower', interpolation='bilinear' ) #interpolation='nearest',resample=True) if aux[f]['log']: im.set_norm(LogNorm()) im.set_extent(slc_data[axis + 'extent']) im.set_cmap(aux[f]['cmap']) im.set_clim(aux[f]['clim']) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) ax.set_aspect(1.0) for j, (im, f) in enumerate(zip(images, fields_to_draw)): if f != 'star_particles': ax = plt.subplot(gs[0, j]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") ## cax=plt.subplot(gs[0,j]) cbar = fig.colorbar(im, cax=cax, orientation='horizontal') cbar.set_label(aux[f]['label']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') if aux[f].has_key('cticks'): cbar.set_ticks(aux[f]['cticks']) if star_axis != -1: ax = plt.subplot(gs[0, star_axis]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") ## cax=plt.subplot(gs[0,0]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Ly * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + lx) ax.set_ylim(y0, y0 + ly) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:nf]], visible=False) plt.setp(axes[:nf], 'xlim', (x0, x0 + lx)) plt.setp(axes[:nf], 'ylim', (y0, y0 + ly)) plt.setp(axes[0], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: ax = axes[0] ax.text(0.5, 0.95, 't=%3d Myr' % tMyr, size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) # axes[0].text(x0*0.9,y0*0.9, # 't=%3d Myr' % tMyr,ha='left',va='top',**(texteffect(16))) # plt.setp(axes[0],'title','t=%3d Myr' % tMyr) plt.setp([ax.get_xticklabels() for ax in axes[:nf:nf]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[:nf:nf]], rotation=45) pngfname = slcfname + '.png' #canvas = mpl.backends.backend_agg.FigureCanvasAgg(fig) #canvas.print_figure(pngfname,num=1,dpi=150,bbox_inches='tight') if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
# ds.domain # information of grid #0 # ds.grids[0] # yet, we didn't read data. # let's read each data field in a full domain # this can be original data fields # d = ds.read_all_data('density')*unit['density'].value if j == 6 or j == 5: if tidx < 474: starfname = vtkfname.replace('id0', 'starpar').replace( 'vtk', 'starpar.vtk') sp = pa.read_starvtk(starfname) # print(sp.shape) # print (sp) star_clu = sp[ sp['mass'] != 0] # choose cluster, if choose 'mass' = 0, it means runaway star star_clu2 = star_clu[star_clu['age'] * Myr < agebin] M_star_c += sum(star_clu2['mass'] ) * Msun # mass sum in time scale / cumulative M_star = sum(star_clu2['mass']) * Msun # SFR time variation else: M_star = 0 else: starfname = vtkfname.replace('id0', 'starpar').replace(
def plot_projection_all(surfnames, axis='y', pngfname=None, runaway=True, icm_max=1.0, iscal=-1, norm_factor=2.): plt.rc('font', size=30) plt.rc('xtick', labelsize=30) plt.rc('ytick', labelsize=30) nsurf = len(surfnames) setup = True for i, surfname in enumerate(surfnames): scalfnames = glob.glob(surfname.replace('surf.p', 'scal?.p')) scalfnames.sort() starfnames = glob.glob( surfname.replace('surf/', 'starpar/').replace( 'surf.p', 'starpar.vtk')) + glob.glob( surfname.replace('surf/', 'id0/').replace( 'surf.p', 'starpar.vtk')) nstar = len(starfnames) nscal = len(scalfnames) if nstar > 0: starfname = starfnames[0] sp = read_starvtk(starfname) frb = pickle.load(open(surfname, 'rb'), encoding='latin1') if nscal > 0: icm = pickle.load(open(scalfnames[iscal], 'rb'), encoding='latin1') if icm[axis]['data'].max() > (icm_max * 1.1): print(scalfnames[iscal], icm[axis]['data'].min(), icm[axis]['data'].max()) if 'time' in frb: tMyr = frb['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr if setup: extent = np.array(frb[axis]['bounds']) / 1.e3 x0 = extent[0] y0 = extent[2] Lx = extent[1] - extent[0] Lz = extent[3] - extent[2] if axis == 'z': ix = 6 else: ix = 3 iz = ix * Lz / Lx cism = plt.cm.bone_r cicm = plt.cm.Reds cicm._init() x = np.arange(cicm.N) alphas = 0.4 * (np.tanh((x - 100) / 50.) + 1) #alphas = np.linspace(0.5, 0.5, cicm.N) cicm._lut[:-3, -1] = alphas cicm._lut[-3, -1] = alphas.min() cicm._lut[-2, -1] = alphas.max() if 'clim' in aux: clim = aux['clim'] else: clim = (1.e-3, 10) clim_icm = (0.0, 0.5) norm_icm = Normalize() fig = plt.figure(0, figsize=(ix * nsurf + 0.5, iz)) width_list = [1] * nsurf + [0.05] gs = gridspec.GridSpec(3, nsurf + 1, width_ratios=width_list, wspace=0.0) setup = False ax1 = plt.subplot(gs[:, i]) im1 = ax1.imshow(frb[axis]['data'], norm=LogNorm(), origin='lower') im1.set_extent(extent) im1.set_cmap(cism) im1.set_clim(clim) if nscal > 0: icm[axis]['data'] /= icm_max im11 = ax1.imshow(icm[axis]['data'], norm=norm_icm, origin='lower') im11.set_extent(extent) im11.set_cmap(cicm) im11.set_clim(clim_icm) if nstar > 0: scatter_sp(sp, ax1, axis=axis, runaway=runaway, type='surf', norm_factor=norm_factor) if i == 0: ax1.set_title('t=%3dMyr' % tMyr, **(texteffect(30))) else: ax1.set_title('%3dMyr' % tMyr, **(texteffect(30))) axes = fig.axes[:nsurf] ax1 = axes[-1] cax = plt.subplot(gs[0, nsurf]) cbar = fig.colorbar(im1, cax=cax, orientation='vertical') if 'label' in aux: cbar.set_label(aux['label']) cax = plt.subplot(gs[1, nsurf]) cbar = fig.colorbar(im11, cax=cax, orientation='vertical') cbar.set_label(r'$C_{\rm ICM}$') if nstar > 0: cax = plt.subplot(gs[2, nsurf]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') starlabels = (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$') if axis == 'z': legend = ax1.legend((s1, s2, s3), starlabels, loc='upper left', ncol=3, bbox_to_anchor=(0.0, 1.15), fontsize='medium', frameon=True) else: legend = ax1.legend((s1, s2, s3), starlabels, loc='lower right', fontsize='medium', frameon=True) plt.setp(axes, 'xlim', (x0, x0 + Lx)) plt.setp(axes, 'ylim', (y0, y0 + Lz)) ax1 = axes[0] if axis == 'z': #plt.setp(axes,'xlabel','x [kpc]') ax1.set_xlabel('x [kpc]') ax1.set_ylabel('y [kpc]') elif axis == 'y': #plt.setp(axes,'xlabel','x [kpc]') ax1.set_xlabel('x [kpc]') ax1.set_ylabel('z [kpc]') elif axis == 'x': #plt.setp(axes,'xlabel','y [kpc]') ax1.set_ylabel('y [kpc]') ax1.set_ylabel('z [kpc]') plt.setp([ax.get_yticklabels() for ax in axes[1:]], visible=False) plt.setp([ax.get_xticklabels() for ax in axes[1:]], visible=False) if pngfname is not None: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
def plot_projection_icm(surfname, scalfname, starfname, stars=True, writefile=True, runaway=True, norm_factor=2., aux={}): plt.rc('font', size=20) plt.rc('xtick', labelsize=20) plt.rc('ytick', labelsize=20) if stars: sp = read_starvtk(starfname) frb = pickle.load(open(surfname, 'rb'), encoding='latin1') icm = pickle.load(open(scalfname, 'rb'), encoding='latin1') if 'time' in frb: tMyr = frb['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr extent = np.array(frb['y']['bounds']) / 1.e3 x0 = extent[0] y0 = extent[2] Lx = extent[1] - extent[0] Lz = extent[3] - extent[2] ix = 3 iz = ix * Lz / Lx cism = plt.cm.bone_r cicm = plt.cm.Reds cicm._init() x = np.arange(cicm.N) alphas = 0.4 * (np.tanh((x - 80) / 30.) + 1) #alphas = np.linspace(0.5, 0.5, cicm.N) cicm._lut[:-3, -1] = alphas cicm._lut[-3, -1] = alphas.min() cicm._lut[-2, -1] = alphas.max() if 'clim' in aux: clim = aux['clim'] clim_icm = (0.0, 0.5) norm_icm = Normalize() fig = plt.figure(0, figsize=(ix * 2 + 0.5, iz)) gs = gridspec.GridSpec(3, 3, width_ratios=[1, 1, 0.05], wspace=0.0) ax1 = plt.subplot(gs[:, 0]) im1 = ax1.imshow(frb['y']['data'], norm=LogNorm(), origin='lower') im1.set_extent(extent) im1.set_cmap(cism) im1.set_clim(clim) im11 = ax1.imshow(icm['y']['data'], norm=norm_icm, origin='lower') im11.set_extent(extent) im11.set_cmap(cicm) im11.set_clim(clim_icm) ax1.text(0., extent[3] * 0.9, 't=%3d Myr' % tMyr, ha='center', va='top', **(texteffect(20))) if stars: scatter_sp(sp, ax1, axis='y', runaway=runaway, type='surf', norm_factor=norm_factor) ax2 = plt.subplot(gs[:, 1]) im2 = ax2.imshow(frb['x']['data'], norm=LogNorm(), origin='lower') im2.set_extent(extent) im2.set_cmap(cism) im2.set_clim(clim) im21 = ax2.imshow(icm['x']['data'], norm=norm_icm, origin='lower') im21.set_extent(extent) im21.set_cmap(cicm) im21.set_clim(clim_icm) if stars: scatter_sp(sp, ax2, axis='x', runaway=runaway, type='surf', norm_factor=norm_factor) cax = plt.subplot(gs[0, 2]) cbar = fig.colorbar(im1, cax=cax, orientation='vertical') if 'label' in aux: cbar.set_label(aux['label']) cax = plt.subplot(gs[1, 2]) cbar = fig.colorbar(im11, cax=cax, orientation='vertical') cbar.set_label(r'$C_{\rm ICM}$') if stars: cax = plt.subplot(gs[2, 2]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax1.set_xlim(x0, x0 + Lx) ax2.set_xlim(x0, x0 + Lx) ax1.set_ylim(y0, y0 + Lz) ax2.set_ylim(y0, y0 + Lz) legend = ax1.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), loc='lower left', fontsize='medium', frameon=True) ax1.set_xlabel('x [kpc]') ax1.set_ylabel('z [kpc]') ax2.set_xlabel('y [kpc]') plt.setp(ax2.get_yticklabels(), visible=False) pngfname = scalfname + 'ng' if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
def plot_projection(surfname, starfname, stars=True, writefile=True, runaway=True, aux={}, norm_factor=2., active=False, scale_func=np.sqrt, vy0=0., timestamp=True, nstarkeys=4): plt.rc('font', size=11) plt.rc('xtick', labelsize=11) plt.rc('ytick', labelsize=11) if stars: sp = read_starvtk(starfname) frb = pickle.load(open(surfname, 'rb'), encoding='latin1') if 'time' in frb: tMyr = frb['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr if 'z' in frb: frb = frb['z'] extent = np.array(frb['bounds']) / 1.e3 x0 = extent[0] y0 = extent[2] Lx = extent[1] - extent[0] Ly = extent[3] - extent[2] ix = 5 iz = ix * Ly / Lx fig = plt.figure(0, figsize=(ix + 0.5, iz)) gs = gridspec.GridSpec(2, 2, width_ratios=[1, 0.03], wspace=0.0) ax = plt.subplot(gs[:, 0]) data = frb['data'] if (vy0 != 0.): import scipy.ndimage as sciim yshift = np.mod(vy0 * tMyr / Myr, Ly * 1.e3) Ny, Nx = data.shape jshift = yshift / (Ly * 1.e3) * Ny data = sciim.interpolation.shift(data, (-jshift, 0), mode='wrap') sp['x2'] -= yshift sp['x2'][sp['x2'] < 0] += Ly * 1.e3 #print tMyr,yshift,Ly,Ny,jshift im = ax.imshow(data, origin='lower') im.set_extent(extent) if 'norm' in aux: im.set_norm(aux['norm']) if 'cmap' in aux: im.set_cmap(aux['cmap']) if 'clim' in aux: im.set_clim(aux['clim']) if timestamp: ax.text(extent[0] * 0.9, extent[3] * 0.9, 't=%3d Myr' % tMyr, ha='left', va='top', **(texteffect())) if stars: scatter_sp(sp, ax, axis='z', runaway=runaway, type='surf', norm_factor=norm_factor, active=active, scale_func=scale_func) cax = plt.subplot(gs[0, 1]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') if 'label' in aux: cbar.set_label(aux['label']) if stars: cax = plt.subplot(gs[1, 1]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$') syms = [] for i in range(nstarkeys): s0 = mlines.Line2D([], [], color='k', marker='o', ls='', markersize=np.sqrt( scale_func(10.**(i + 3)) / norm_factor), alpha=.8, label=r'$10^{} M_\odot$'.format(i + 3)) syms.append(s0) ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Ly) legend = ax.legend(handles=syms, loc=2, ncol=4, bbox_to_anchor=(-0.1, 1.0 + 0.15 * Lx / Ly), fontsize='medium', frameon=True) ax.set_xlabel('x [kpc]') ax.set_ylabel('y [kpc]') pngfname = surfname + 'ng' if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
def plot_projection(surfname, starfname, stars=True, writefile=True, runaway=True, aux=None, norm_factor=2.): if aux == None: aux = ya.set_aux(os.path.basename(surfname)) aux = aux['surface_density'] plt.rc('font', size=11) plt.rc('xtick', labelsize=11) plt.rc('ytick', labelsize=11) fig = plt.figure(0, figsize=(5.5, 5)) gs = gridspec.GridSpec(2, 2, width_ratios=[1, 0.03], wspace=0.0) if stars: sp = read_starvtk(starfname) frb = pickle.load(open(surfname, 'rb')) #,encoding='latin1') if 'time' in frb: tMyr = frb['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr if 'z' in frb: frb = frb['z'] extent = np.array(frb['bounds']) / 1.e3 x0 = extent[0] y0 = extent[2] Lx = extent[1] - extent[0] Lz = extent[3] - extent[2] ax = plt.subplot(gs[:, 0]) im = ax.imshow(frb['data'], origin='lower') im.set_extent(extent) if aux['log']: im.set_norm(LogNorm()) im.set_cmap(aux['cmap']) im.set_clim(aux['clim']) ax.text(extent[0] * 0.9, extent[3] * 0.9, 't=%3d Myr' % tMyr, ha='left', va='top', **(texteffect())) if stars: scatter_sp(sp, ax, axis='z', runaway=runaway, type='surf', norm_factor=norm_factor) cax = plt.subplot(gs[0, 1]) cbar = fig.colorbar(im, cax=cax, orientation='vertical') cbar.set_label(aux['label']) if stars: cax = plt.subplot(gs[1, 1]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap='PuOr_r', norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$', fontsize=45) s1 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), loc=2, ncol=3, bbox_to_anchor=(0.0, 1.15), fontsize='medium', frameon=True) ax.set_xlabel('x [kpc]') ax.set_ylabel('y [kpc]') pngfname = surfname + 'ng' if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.close() else: return fig
def plot_projection_Z(surfname, starfname, axis='y', stars=True, writefile=True, runaway=True, norm_factor=2.): aux = ya.set_aux(os.path.basename(surfname)) plt.rc('font', size=16) plt.rc('xtick', labelsize=16) plt.rc('ytick', labelsize=16) if stars: sp = read_starvtk(starfname) frb = pickle.load(open(surfname, 'rb')) #,encoding='latin1') if 'time' in frb: tMyr = frb['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr extent = np.array(frb[axis]['bounds']) / 1.e3 x0 = extent[0] y0 = extent[2] Lx = extent[1] - extent[0] Lz = extent[3] - extent[2] ix = 3 iz = ix * Lz / Lx fig = plt.figure(0, figsize=(ix * 2 + 0.5, iz)) gs = gridspec.GridSpec(2, 3, width_ratios=[1, 1, 0.03], wspace=0.0) ax1 = plt.subplot(gs[:, 0]) im1 = ax1.imshow(frb['y']['data'], norm=LogNorm(), origin='lower') im1.set_extent(extent) im1.set_cmap(aux['surface_density']['cmap']) clim = aux['surface_density']['clim'] cmin = clim[0] cmax = clim[1] clim = (cmin * 0.1, cmax) im1.set_clim(clim) ax1.text(extent[0] * 0.9, extent[3] * 0.9, 't=%3d Myr' % tMyr, ha='left', va='top', **(texteffect())) if stars: scatter_sp(sp, ax1, axis='y', runaway=runaway, type='surf', norm_factor=norm_factor) ax2 = plt.subplot(gs[:, 1]) im2 = ax2.imshow(frb['x']['data'], norm=LogNorm(), origin='lower') im2.set_extent(extent) im2.set_cmap(aux['surface_density']['cmap']) im2.set_clim(clim) if stars: scatter_sp(sp, ax2, axis='x', runaway=runaway, type='surf') cax = plt.subplot(gs[0, 2]) cbar = fig.colorbar(im1, cax=cax, orientation='vertical') cbar.set_label(aux['surface_density']['label'], fontsize=45) if stars: cax = plt.subplot(gs[1, 2]) cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.PuOr, norm=Normalize(vmin=0, vmax=40), orientation='vertical') cbar.set_label(r'${\rm age [Myr]}$', fontsize=45) s1 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax1.scatter(Lx * 2, Lz * 2, s=np.sqrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') ax1.set_xlim(x0, x0 + Lx) ax1.set_ylim(y0, y0 + Lz) ax2.set_xlim(x0, x0 + Lx) ax2.set_ylim(y0, y0 + Lz) legend = ax1.legend( (s1, s2, s3), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$'), loc='lower left', fontsize='medium', frameon=True) ax1.set_xlabel('x [kpc]') ax1.set_ylabel('z [kpc]') ax2.set_xlabel('y [kpc]') plt.setp(ax2.get_yticklabels(), visible=False) pngfname = surfname + 'ng' if writefile: plt.savefig(pngfname, bbox_inches='tight', num=0, dpi=150) plt.show() plt.close() else: return fig
def main(**kwargs): dir = kwargs['base_directory'] + kwargs['directory'] fname = dir + 'id0/%s.%4.4d.vtk' % (kwargs['id'], kwargs['itime']) starfname = dir + 'id0/%s.%4.4d.starpar.vtk' % (kwargs['id'], kwargs['itime']) ds = yt.load(fname, units_override=unit_base) ds.coordinates.x_axis[1] = 0 ds.coordinates.x_axis['y'] = 0 ds.coordinates.y_axis[1] = 2 ds.coordinates.y_axis['y'] = 2 sp = read_starvtk(starfname) ratio = ds.domain_width[2] / ds.domain_width[0] ix = 2 iz = ix * ratio fig = plt.figure(figsize=(ix * nf, iz + ix + 0.1 * ix)) gs = gridspec.GridSpec(3, nf, height_ratios=[0.1 * ix, iz, ix], hspace=0.01, wspace=0.02) c = ds.domain_center images = [] for i, axis in enumerate(['y', 'z']): slc = yt.SlicePlot(ds, axis, fields) slc_frb = slc.data_source.to_frb(slc.width[0], slc.width, c, slc.width[1]) extent = np.array(slc_frb.bounds) / 1.e3 for j, f in enumerate(fields): if aux[f].has_key('unit'): data = slc_frb[f].in_units(aux[f]['unit']).d else: data = slc_frb[f].d if aux[f].has_key('factor'): data *= aux[f]['factor'] ax = plt.subplot(gs[i + 1, j]) im = ax.imshow(data, origin='lower', norm=aux[f]['norm']) im.set_clim((aux[f]['cmin'], aux[f]['cmax'])) im.set_cmap(aux[f]['cmap']) im.set_extent(extent) images.append(im) if j == 0: scatter_sp(sp, ax, axis=axis, runaway=False) elif j == 1: scatter_sp(sp, ax, axis=axis) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) for j, (im, f) in enumerate(zip(images[:nf], fields)): cax = plt.subplot(gs[0, j]) cbar = fig.colorbar(im, cax=cax, orientation='horizontal') cbar.set_label(aux[f]['title']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') if f is 'nH': cbar.set_ticks([1.e-4, 1.e-2, 1, 1.e2]) if f.startswith('velocity'): cbar.set_ticks([-100, 0, 100]) axes = fig.axes sp_legend(axes[nf - 1]) plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) for ax in fig.axes: ax.tick_params(axis='both', which='major', labelsize=12) if kwargs['label']: plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = "%s/4slices/%s.%4.4d.4slices.png" % ( kwargs['base_directory'], kwargs['id'], kwargs['itime']) fig.savefig(pngfname, dpi=300, bbox_inches='tight')
def slice_proj(slcfname,projfname,starfname,fields_to_draw,zoom=1.,aux={},vy0=0.,\ writefile=True,tstamp=True,stars=True,field_label=True,norm_factor=2): plt.rc('font', size=14) plt.rc('xtick', labelsize=14) plt.rc('ytick', labelsize=14) slc_data = pickle.load(open(slcfname, 'rb'), encoding='latin1') proj_data = pickle.load(open(projfname, 'rb'), encoding='latin1') x0 = slc_data['yextent'][0] y0 = slc_data['zextent'][2] z0 = slc_data['yextent'][2] Lx = slc_data['yextent'][1] - slc_data['yextent'][0] Ly = slc_data['zextent'][3] - slc_data['zextent'][2] Lz = slc_data['yextent'][3] - slc_data['yextent'][2] Lz = Lz / zoom ix = 2 iy = ix * Ly / Lx iz = ix * Lz / Lx nf = len(fields_to_draw) fig = plt.figure(1, figsize=(ix * nf, iz + iy * 1.2)) gs = gridspec.GridSpec(2, nf, height_ratios=[iz, iy]) gs.update(top=0.95, left=0.08, bottom=0.05, right=0.98, wspace=0.05, hspace=0) if stars: sp = read_starvtk(starfname) if 'time' in slc_data: tMyr = slc_data['time'] else: time, sp = read_starvtk(starfname, time_out=True) tMyr = time * Myr if (vy0 != 0): import scipy.ndimage as sciim yshift = np.mod(vy0 * tMyr / Myr, Ly * 1.e3) Ny, Nx = slc_data['z']['nH'].shape jshift = yshift / (Ly * 1.e3) * Ny sp['x2'] -= yshift sp['x2'][sp['x2'] < 0] += Ly * 1.e3 images = [] for i, axis in enumerate(['y', 'z']): for j, f in enumerate(fields_to_draw): ax = plt.subplot(gs[i, j]) if f is 'star_particles': scatter_sp(sp, ax, axis=axis, norm_factor=norm_factor, type='surf', active=False, scale_func=np.cbrt) if axis is 'y': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(z0, z0 + Lz) if axis is 'z': ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Ly) ax.set_aspect(1.0) elif f is 'surface_density': data = proj_data[axis]['data'] if (vy0 != 0) and (axis == 'z'): data = sciim.interpolation.shift(data, (-jshift, 0), mode='wrap') im = ax.imshow(data, origin='lower', interpolation='bilinear') if axis is 'z': im.set_norm(aux['surface_density']['norm']) im.set_cmap(aux['surface_density']['cmap']) im.set_clim(aux['surface_density']['clim']) else: im.set_norm(aux['nH']['norm']) im.set_cmap(aux['nH']['cmap']) im.set_clim(aux['nH']['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) elif f is 'specific_scalar3_proj': proj_data2 = pickle.load(open( projfname.replace('surf.p', 'scal3.p'), 'rb'), encoding='latin1') data = proj_data2[axis]['data'] if (vy0 != 0) and (axis == 'z'): data = sciim.interpolation.shift(data, (-jshift, 0), mode='wrap') im = ax.imshow(data, origin='lower', interpolation='bilinear') im.set_norm(aux['specific_scalar3']['norm']) im.set_cmap(aux['specific_scalar3']['cmap']) im.set_clim(aux['specific_scalar3']['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) else: data = slc_data[axis][f] if (vy0 != 0) and (axis == 'z'): data = sciim.interpolation.shift(data, (-jshift, 0), mode='wrap') im = ax.imshow(data, origin='lower', interpolation='bilinear') if f in aux: if 'norm' in aux[f]: im.set_norm(aux[f]['norm']) if 'cmap' in aux[f]: im.set_cmap(aux[f]['cmap']) if 'clim' in aux[f]: im.set_clim(aux[f]['clim']) extent = slc_data[axis + 'extent'] im.set_extent(extent) images.append(im) ax.set_xlim(extent[0], extent[1]) ax.set_ylim(extent[2], extent[3]) for j, (im, f) in enumerate(zip(images[nf - 1:], fields_to_draw[stars:])): ax = plt.subplot(gs[0, j + stars]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = fig.colorbar(im, cax=cax, orientation='horizontal') if f in aux: if 'label' in aux[f]: cbar.set_label(aux[f]['label']) if 'cticks' in aux[f]: cbar.set_ticks(aux[f]['cticks']) cax.xaxis.tick_top() cax.xaxis.set_label_position('top') if stars: ax = plt.subplot(gs[0, 0]) divider = make_axes_locatable(ax) cax = divider.append_axes("top", "3%", pad="1%") cbar = colorbar.ColorbarBase(cax, ticks=[0, 20, 40], cmap=plt.cm.cool_r, norm=Normalize(vmin=0, vmax=40), orientation='horizontal') cax.xaxis.tick_top() cax.xaxis.set_label_position('top') cbar.set_label(r'${\rm age [Myr]}$') s1 = ax.scatter(Lx * 2, Lz * 2, s=np.cbrt(1.e3) / norm_factor, color='k', alpha=.8, label=r'$10^3 M_\odot$') s2 = ax.scatter(Lx * 2, Lz * 2, s=np.cbrt(1.e4) / norm_factor, color='k', alpha=.8, label=r'$10^4 M_\odot$') s3 = ax.scatter(Lx * 2, Lz * 2, s=np.cbrt(1.e5) / norm_factor, color='k', alpha=.8, label=r'$10^5 M_\odot$') s4 = ax.scatter(Lx * 2, Lz * 2, s=np.cbrt(1.e6) / norm_factor, color='k', alpha=.8, label=r'$10^6 M_\odot$') ax.set_xlim(x0, x0 + Lx) ax.set_ylim(y0, y0 + Lz) legend = ax.legend((s1, s2, s3, s4), (r'$10^3 M_\odot$', r'$10^4 M_\odot$', r'$10^5 M_\odot$', r'$10^6 M_\odot$'), scatterpoints=1, loc='lower left', fontsize='medium', frameon=True) axes = fig.axes plt.setp([ax.get_xticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf]], visible=False) plt.setp(axes[:nf], 'ylim', (slc_data['yextent'][2] / zoom, slc_data['yextent'][3] / zoom)) plt.setp(axes[nf:2 * nf], 'xlabel', 'x [kpc]') plt.setp(axes[0], 'ylabel', 'z [kpc]') if tstamp: ax = axes[0] ax.text(0.5, 0.95, 't=%3d Myr' % tMyr, size=16, horizontalalignment='center', transform=ax.transAxes, **(texteffect())) plt.setp(axes[nf], 'ylabel', 'y [kpc]') plt.setp([ax.get_xticklabels() for ax in axes[nf:]], visible=True) plt.setp([ax.get_yticklabels() for ax in axes[:2 * nf:nf]], visible=True) plt.setp([ax.xaxis.get_majorticklabels() for ax in axes[nf:2 * nf]], rotation=45) pngfname = slcfname.replace('.p', '_proj.png') if writefile: plt.savefig(pngfname, num=1, dpi=150) plt.close(1) else: return fig