def plot_mass_fraction_time_evolution(): """ Make a panel plot of the time evolution of all elemental abundance ratios with respect to both H and Fe (as separate plots) """ filename = workdir + '/abundances/abundances/abundances.h5' hdf5_data = h5py.File(filename, 'r') dfiles = hdf5_data.keys() dfile = dfiles[-1] # do this with most recent data file data = dd.io.load(filename, '/' + str(dfile)) elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)]) # elements = elements + ['alpha'] for time_type in ['cumulative','10Myr']: fig, ax = plt.subplots(4,4, sharex = True, sharey = True) fig.set_size_inches(4*4,4*4) fig.subplots_adjust(hspace=0.0, wspace = 0.0) i,j = 0,0 for e in elements: print("plotting " + e + "mass fraction time evolution") index = (i,j) t = data['mass_fraction_statistics'][time_type]['bins'] y = data['mass_fraction_statistics'][time_type][e]['median'] Q1 = data['mass_fraction_statistics'][time_type][e]['Q1'] Q3 = data['mass_fraction_statistics'][time_type][e]['Q3'] select = (y*0 == 0) # remove nan values t = t[select] t = t - t[0] ax[index].plot( t, y[select], lw = line_width, ls = '-', color = 'black', label = r' ' + e +' ') ax[index].fill_between(t, Q1[select], Q3[select], color = 'black', alpha = 0.5, lw = 0.5 * line_width) ax[index].set_xlim(0.0, np.max(t)) ax[index].plot( [0.0,1000.0], [0.0,0.0], ls = ':', color = 'black', lw = line_width) ax[index].legend(loc = 'upper right') j = j + 1 if j >= 4: j = 0 i = i + 1 for i in np.arange(4): ax[(3,i)].set_xlabel(r'Time (Myr)') ax[(i,0)].set_ylabel(r'log(X Mass Fraction)') ax[(i,0)].set_ylim(1.0E-10, 1.0E-4) ax[(i,0)].semilogy() # for j in np.arange(3): # ax[(j,i)].set_xticklabels([]) # ax[(i,j+1)].set_yticklabels([]) # ax[(3,i)].set_xticklabels(np.arange(0,np.max(t)+20,20)) # if base == 'Fe': # ax[(i,0)].set_yticklabels([-3,-2,-1,0,1,2,3,]) # else: # ax[(i,0)].set_yticklabels([-12, -10, -8, -6, -4, -2, 0]) plt.minorticks_on() fig.savefig('stellar_mass_fraction_' + time_type +'_evolution.png') plt.close() return
def plot_ratios_with_histograms(X='alpha',A='Fe',B='Fe',C='H'): filename = workdir + '/abundances/abundances/abundances.h5' hdf5_data = h5py.File(filename, 'r') dfiles = hdf5_data.keys() dfile = dfiles[-1] # do this with most recent data file data = dd.io.load(filename, '/' + str(dfile)) elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)]) elements = elements + ['alpha'] + ['H'] age = data['Time'] - data['creation_time'] # age of all particles in this data set # -------------------- check_elements = [x for x in [X,A,B,C] if (not (x in elements))] if len(check_elements) > 0: print(check_elements, " not in elements list") print("available: ", elements) raise ValueError sep = 0.02 left, width = 0.125, 0.65 bottom, height = 0.1, 0.65 left_h = left + width + sep bottom_h = bottom + height + sep rect_scatter = [left,bottom,width,height] # rect_colorbar = # rect_histx = [left, bottom_h, width, 0.95 - bottom_h - (left-bottom)] # rect_histy = [left_h, bottom, 0.95 - left_h, height] # fig,ax = plt.subplots() fig = plt.figure(1, figsize=(8,8)) # fig.set_size_inches(8,8) ax_scatter = plt.axes(rect_scatter) # ax_hist_x = plt.axes(rect_histx) # ax_hist_y = plt.axes(rect_histy) # ax_color = plt.axes(rect_colorbar) x_values = data['abundances'][B][C] y_values = data['abundances'][X][A] age = age - np.min(age) # normalize # scatter plot p = ax_scatter.scatter(x_values, y_values, s = point_size, lw = 2, c = age, cmap = 'plasma_r', alpha = 0.75) p.set_clim([0.0, np.max(age)]) cb = fig.colorbar(p, ax = ax_scatter, orientation = 'horizontal', pad = 0.125, fraction = 0.046, aspect = 40) cb.set_label(r'Stellar Age (Myr)') # # # ax_scatter.set_xlim(-9,-1) ax_scatter.set_ylim(-1.75,1.75) ax_scatter.tick_params(axis='x',which='minor',bottom='on') ax_scatter.tick_params(axis='y',which='minor',bottom='on') ax_scatter.set_xlabel(r'log([' + B + '/' + C + '])') ax_scatter.set_ylabel(r'log([' + X + '/' + A + '])') plt.minorticks_on() # # find main plot and construct histograms # divider = make_axes_locatable(ax_scatter) left, bottom, width, height = divider.get_position() # width, height = divider.get_horizontal(), divider.get_vertical() sep = 0.01 thickness = np.min( np.array([0.95 - left - width - sep, 0.95 - bottom - height - sep])) rect_histx = [left, bottom + height + sep, width, thickness] rect_histy = [left + width + sep, bottom, thickness, height] ax_hist_x = plt.axes(rect_histx) ax_hist_y = plt.axes(rect_histy) # construct the histogram for the horizontal axis (goes up top) nbins = 100 hist,bins = np.histogram(x_values, bins = nbins) weights = np.ones(np.size(x_values)) * (1.0 / (1.0*np.max(hist))) ax_hist_x.hist(x_values, color = 'C0', bins = nbins, weights = weights) # plot_histogram(ax_hist_x, bins, hist / (1.0*np.max(hist)), color = 'black') plt.minorticks_on() # hist,bins = np.histogram(alpha, bins = 24) # plot_histogram(ax_hist_y, bins, hist / (1.0*np.max(hist)), color = 'black', orientation = 'horizontal') # now do the same for the vertical axis histogram nbins = 50 hist,bins = np.histogram(y_values, bins = nbins) weights = np.ones(np.size(y_values)) * (1.0 / (1.0*np.max(hist))) ax_hist_y.hist(y_values, orientation='horizontal', color = 'C0', bins = nbins, weights = weights) ax_hist_x.xaxis.set_major_formatter(NullFormatter()) ax_hist_y.yaxis.set_major_formatter(NullFormatter()) ax_hist_x.set_xlim(ax_scatter.get_xlim()) ax_hist_y.set_ylim(ax_scatter.get_ylim()) ticks = [0.0,0.25,0.5,0.75,1.0] ax_hist_x.set_yticks(ticks) ax_hist_y.set_xticks(ticks) ax_hist_y.set_xticklabels(ticks, rotation = 270) plt.minorticks_on() # plt.tight_layout() fig.savefig(X + '_over_' + A + '_vs_' + B + '_over_' + C + '_hist.png') plt.close() return
def plot_spatial_profiles(field = 'metallicity', abundance = False, bins = None, spatial_type = 'cylindrical_radius'): filename = workdir + '/abundances/abundances/abundances.h5' hdf5_data = h5py.File(filename, 'r') dfiles = hdf5_data.keys() dfile = dfiles[-1] # do this with most recent data file data = dd.io.load(filename, '/' + str(dfile)) elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)]) elements = elements + ['alpha'] if spatial_type == 'cylindrical_radius': bin_field = np.sqrt(data['kinematics']['x']**2 + data['kinematics']['y']**2) xlabel = r'Radius (pc)' elif spatial_type == 'z': bin_field = np.abs( data['kinematics']['z'] ) xlabel = r'Z (pc)' if bins is None: bins = np.linspace(np.floor(np.min(bin_field)), np.ceil(np.max(bin_field)), 100) centers = 0.5 * (bins[1:] + bins[:-1]) nbins = np.size(bins) hist_index = np.digitize(bin_field, bins = bins) median, q1, q3 = np.zeros(nbins-1), np.zeros(nbins-1), np.zeros(nbins-1) if field == 'metallicity': # make a single plot # bin the data for i in np.arange(nbins-1): x = data['metallicity'][hist_index == i + 1] median[i] = np.median(x) if np.size(x) > 1: q1[i] = np.percentile(x, 25.0) q3[i] = np.percentile(x, 75.0) elif np.size(x) == 1: q1[i] = median[i] q3[i] = median[i] # now plot fig, ax = plt.subplots() fig.set_size_inches(8,8) plot_histogram(ax, bins, median, lw = line_width, color = 'black', ls = '-') ax.fill_between(centers, q1, q3, lw = 1.5, color = 'grey') ax.set_ylabel(r'Metallicity Fraction') ax.set_xlabel(xlabel) ax.set_xlim( np.min(bins), np.max(bins)) plt.tight_layout() plt.minorticks_on() fig.savefig('metallicity_' + spatial_type + '_profile.png') plt.close() elif abundance: fig, ax = plt.subplots(4,4, sharex = True, sharey = True) fig.set_size_inches(16,16) fig.subplots_adjust(hspace = 0.0, wspace = 0.0) axi, axj = 0,0 for e in elements: if field == e: continue index = (axi,axj) for i in np.arange(nbins-1): x = np.array(data['abundances'][e][field]) x = x[ hist_index == (i + 1)] if np.size(x) > 0: median[i] = np.median(x) q1[i] = np.percentile(x, 25) q3[i] = np.percentile(x, 75) else: median[i] = None; q1[i] = None; q3[i] = None ax[index].annotate(e, xy=(0.8,0.8),xytext=(0.8,0.8), xycoords='axes fraction',textcoords = 'axes fraction') plot_histogram(ax[index], bins, median, lw = line_width, color = 'black', ls = '-') ax[index].fill_between(centers,q1,q3,lw=1.5,color='grey') axj = axj+1 if axj>=4: axj = 0 axi = axi + 1 for i in np.arange(4): ax[(3,i)].set_xlabel(xlabel) ax[(i,0)].set_ylabel(r'log[X/' + field +'])') if field == 'H': ax[(0,i)].set_ylim(-10.25,0.125) else: ax[(0,i)].set_ylim(-3.25,3.25) for j in np.arange(4): ax[(j,i)].plot([bins[0],bins[-1]], [0.0,0.0], lw = 0.5 * line_width, ls = '--',color ='black') ax[(i,0)].set_xlim(np.min(bins), np.max(bins)) plt.minorticks_on() fig.savefig(field + '_' + spatial_type + '_profile_panel.png') plt.close() return
def plot_MDF(plot_base = ['H','Fe']): """ Make a panel plot of the time evolution of all elemental abundance ratios with respect to both H and Fe (as separate plots) """ if (not (type(plot_base) is list)): plot_base = [plot_base] filename = workdir + '/abundances/abundances/abundances.h5' hdf5_data = h5py.File(filename, 'r') dfiles = hdf5_data.keys() dfile = dfiles[-1] # do this with most recent data file data = dd.io.load(filename, '/' + str(dfile)) elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)]) elements = elements + ['alpha'] for base in plot_base: fig, ax = plt.subplots(4,4, sharex = True, sharey = True) fig.set_size_inches(4*4,4*4) fig.subplots_adjust(hspace=0.0, wspace = 0.0) if base == 'Fe': bins = np.arange(-3,3.1,0.1) else: bins = np.arange(-9,0,0.1) i,j = 0,0 for e in elements: if (base == e): continue index = (i,j) points = np.array(data['abundances'][e][base]) single_MDF(points, bins = bins, norm = 'peak', ax = ax[index], label = False, lw = line_width) x = np.max(bins) - (0.25/6.0 * (bins[-1] - bins[0])) y = 0.9 ax[index].annotate(e, xy = (x,y), xytext =(x,y)) ax[index].plot([0,0], [0.0,1.0], ls = ':', lw = 0.5 * line_width, color = 'black') j = j + 1 if j >= 4: j = 0 i = i + 1 for i in np.arange(4): ax[(3,i)].set_xlabel(r'log([X/' + base + '])') ax[(i,0)].set_ylabel(r'N/N$_{\rm peak}$') if base == 'H': ax[(i,0)].set_xlim(-10.25, 0.125) elif base == 'Fe': ax[(i,0)].set_xlim(-3.25, 3.25) plt.minorticks_on() fig.savefig(base + '_MDF.png') plt.close() return
def plot_basic_outflow_and_loading(work_dir='./', t_min=0.0, t_max=1000.0, phase=None, outdir='./'): data_list, times = utilities.select_data_by_time(dir=work_dir, tmin=t_min, tmax=t_max) xpos = dd.io.load(data_list[0], '/gas_profiles/outflow/sphere') xpos = xpos['centers_rvir'] temp = dd.io.load(data_list[0], '/gas_meta_data/masses/CNM') elements = utilities.sort_by_anum([ x for x in temp.keys() if len(x) <= 2 and (not (x in ['H', 'He', 'H2', 'HI', 'HII', 'HeI'])) ]) # # Mass Outflow Plot # fig, ax = plt.subplots() fig.set_size_inches(8, 8) all_data = obtain_outflow_rates(data_list, 'cell_mass', elements, phase=phase) metal_data = obtain_outflow_rates(data_list, 'Total Tracked Metals', elements, phase=phase) metal_mass = obtain_metal_mass(data_list) stellar_mass = obtain_stellar_mass( data_list) # total mass in stars produced at a time, NOT M_* of galaxy sfr = obtain_sfr(data_list, times) binned_y = 1.0 * all_data # np.array( [all_data[k] for k in all_data.keys()] ) binned_metal_mass = 1.0 * metal_data for i, loc in enumerate([0.1, 0.25, 0.5, 1.0]): loc_bin = np.argmin(np.abs(xpos - loc)) # get the right position bin y = binned_y[:, loc_bin] print(i, loc, loc_bin) bin_edges = utilities.bin_edges(np.round(times)) # rebin with 10 Myr bins, rather than previous 1 Myr bins newx, rebiny = utilities.simple_rebin( 1.0 * bin_edges, 1.0 * y, np.arange(np.min(bin_edges), np.max(bin_edges) + 2, 10), 'average') plot_histogram(ax, newx - newx[0], rebiny, lw=line_width, color=plasma(i / 4.0), label=r"%0.1f R$_{\rm vir}$" % (loc)) ax.set_xlabel(r'Time (Myr)') ax.set_ylabel(r'Outflow Rate (M$_{\odot}$ yr$^{-1}$)') ax.semilogy() ax.set_xlim(0.0, np.min([TMAX, np.max(newx - newx[0])])) ax.set_ylim(1.0E-5, 0.03) plt.tight_layout() ax.legend(loc='best') plt.minorticks_on() outname = outdir + 'total_mass_outflow' if not (phase is None): outname += '_' + phase fig.savefig(outname + '.png') plt.close() # # Mass Loading plot # fig, ax = plt.subplots() fig.set_size_inches(8, 8) # binned_y = np.array( [all_data[k] for k in all_data.keys()] ) for i, loc in enumerate([0.1, 0.25, 0.5, 1.0]): loc_bin = np.argmin(np.abs(xpos - loc)) # get the right position bin y = binned_y[:, loc_bin] / sfr bin_edges = utilities.bin_edges(np.round(times)) # rebin with 10 Myr bins, rather than previous 1 Myr bins newx, rebiny = utilities.simple_rebin( 1.0 * bin_edges, 1.0 * y, np.arange(np.min(bin_edges), np.max(bin_edges) + 2, 10), 'average') plot_histogram(ax, newx - newx[0], rebiny, lw=line_width, color=plasma(i / 4.0), label=r"%0.1f R$_{\rm vir}$" % (loc)) ax.set_xlabel(r'Time (Myr)') ax.set_ylabel(r'Mass Loading Factor') ax.semilogy() ax.set_xlim(0.0, np.min([TMAX, np.max(newx - newx[0])])) ax.set_ylim(0.1, 300) plt.tight_layout() #ax.legend(loc='best') plt.minorticks_on() outname = outdir + 'total_mass_loading' if not (phase is None): outname += '_' + phase fig.savefig(outname + '.png') plt.close() # # Metal Mass Loading # fig, ax = plt.subplots() fig.set_size_inches(8, 8) for i, loc in enumerate([0.1, 0.25, 0.5, 1.0]): loc_bin = np.argmin(np.abs(xpos - loc)) # get the right position bin print(np.shape(binned_y), np.shape(binned_metal_mass), np.size(sfr), np.size(metal_mass), np.size(stellar_mass)) y = binned_metal_mass[:, loc_bin] / (sfr * (metal_mass / stellar_mass) ) # metal mass loading factor print(loc, np.min(y), np.max(y), np.average(y)) print(np.min(metal_mass), np.max(metal_mass), np.min(stellar_mass), np.max(stellar_mass)) bin_edges = utilities.bin_edges(np.round(times)) # rebin with 10 Myr bins, rather than previous 1 Myr bins newx, rebiny = utilities.simple_rebin( 1.0 * bin_edges, 1.0 * y, np.arange(np.min(bin_edges), np.max(bin_edges) + 2, 10), 'average') plot_histogram(ax, newx - newx[0], rebiny, lw=line_width, color=plasma(i / 4.0), label=r"%0.1f R$_{\rm vir}$" % (loc)) ax.set_xlabel(r'Time (Myr)') ax.set_ylabel(r'Metal Mass Loading Factor') ax.semilogy() ax.set_xlim(0.0, np.min([TMAX, np.max(newx - newx[0])])) ax.set_ylim(0.04, 20) plt.tight_layout() ax.legend(loc='upper right') plt.minorticks_on() outname = outdir + 'metal_mass_loading' if not (phase is None): outname += '_' + phase fig.savefig(outname + '.png') plt.close() # # Metal Mass Loading # fig, ax = plt.subplots() fig.set_size_inches(8, 8) for i, loc in enumerate([0.1, 0.25, 0.5, 1.0]): loc_bin = np.argmin(np.abs(xpos - loc)) # get the right position bin print(np.shape(binned_y), np.shape(binned_metal_mass), np.size(sfr), np.size(metal_mass), np.size(stellar_mass)) y = binned_metal_mass[:, loc_bin] / (sfr) # metal mass loading factor print(loc, np.min(y), np.max(y), np.average(y)) print(np.min(metal_mass), np.max(metal_mass), np.min(stellar_mass), np.max(stellar_mass)) bin_edges = utilities.bin_edges(np.round(times)) # rebin with 10 Myr bins, rather than previous 1 Myr bins newx, rebiny = utilities.simple_rebin( 1.0 * bin_edges, 1.0 * y, np.arange(np.min(bin_edges), np.max(bin_edges) + 2, 10), 'average') print(np.sum(rebiny) / (1.0 * np.size(rebiny)), '-------------') plot_histogram(ax, newx - newx[0], rebiny, lw=line_width, color=plasma(i / 4.0), label=r"%0.1f R$_{\rm vir}$" % (loc)) ax.set_xlabel(r'Time (Myr)') ax.set_ylabel(r'Metal Mass Loading Factor') ax.semilogy() ax.set_xlim(0.0, np.min([TMAX, np.max(newx - newx[0])])) ax.set_ylim(1.0E-6, 1.0) plt.tight_layout() ax.legend(loc='best') plt.minorticks_on() outname = outdir + 'metal_mass_loading_sfr' if not (phase is None): outname += '_' + phase fig.savefig(outname + '.png') plt.close() return
def plot_panel(A = 'Fe', B = 'Fe', C = 'H', color = True): """ Make panel plots of X/A vs. B/C where "X" is a loop through all elements available, and A, B, C are fixed for all plots, chosen by user. Defualt will plot [X/Fe] vs. [Fe/H]. Default behavior is to color points by age. """ filename = workdir + '/abundances/abundances/abundances.h5' hdf5_data = h5py.File(filename, 'r') dfiles = hdf5_data.keys() dfile = dfiles[-1] # do this with most recent data file data = dd.io.load(filename, '/' + str(dfile)) elements = utilities.sort_by_anum([x for x in data['abundances'].keys() if (not 'alpha' in x)]) elements = elements + ['alpha'] age = data['Time'] - data['creation_time'] # age of all particles in this data set for base in ['H','Fe']: fig, ax = plt.subplots(4,4, sharex = True, sharey = True) fig.set_size_inches(4*4,4*4) fig.subplots_adjust(hspace=0.0, wspace = 0.0) if base == 'Fe': bins = np.arange(-3,3.1,0.1) else: bins = np.arange(-9,0,0.1) i,j = 0,0 for e in elements: if (A == e): # skip continue index = (i,j) y = np.array(data['abundances'][e][A]) x = np.array(data['abundances'][B][C]) p = ax[index].scatter(x, y, s = point_size*0.5, lw = 2, c = age, cmap = 'plasma_r', alpha = 0.75) p.set_clim([0.0, np.max(age)]) xy = (0.8,0.8) ax[index].annotate(e, xy=xy, xytext=xy, xycoords = 'axes fraction', textcoords = 'axes fraction') # cb = fig.colorbar(p) # cb.set_label(r'Stellar Age (Myr)') j = j + 1 if j >= 4: j = 0 i = i + 1 for i in np.arange(4): ax[(3,i)].set_xlabel(r'log([' + B + '/' + C + '])') ax[(i,0)].set_ylabel(r'log([X/' + A + '])') if C == 'H': ax[(i,0)].set_xlim(-10.25, 0.125) else: ax[(i,0)].set_xlim(-3.25, 3.25) if A == 'H': ax[(0,i)].set_ylim(-10.25, 0.125) else: ax[(0,i)].set_ylim(-3.25, 3.25) for j in np.arange(4): ax[(j,i)].plot([-10,10], [0.0,0.0], lw = 0.5 * line_width, ls = ':', color = 'black') plt.minorticks_on() fig.savefig('X_over_' + A +'_vs_' + B + '_over_' + C + '_panel.png') plt.close() return
def plot_species_outflow_panel(work_dir='./', t_min=0.0, t_max=1000.0, phase=None, method='fraction', outdir='./'): """ Default to plotting the following: For each species, x, plots (dM_x/dt / M_x_prod) / SFR or the fractional mass outflow rate per unit SFR. """ data_list, times = utilities.select_data_by_time(dir=work_dir, tmin=0.0, tmax=1000) xpos = dd.io.load(data_list[0], '/gas_profiles/outflow/sphere') xpos = xpos['centers_rvir'] temp = dd.io.load(data_list[0], '/gas_meta_data/masses/CNM') elements = utilities.sort_by_anum([ x for x in temp.keys() if len(x) <= 2 and (not (x in ['H', 'He', 'H2', 'HI', 'HII', 'HeI'])) ]) fig, ax = plt.subplots(4, 4, sharex=True, sharey=True) fig.set_size_inches(16, 16) fig.subplots_adjust(hspace=0.0, wspace=0.0) SFR = obtain_sfr(data_list, times) axi, axj = 0, 0 for e in elements: index = (axi, axj) field_name = e + '_Mass' all_data = obtain_outflow_rates(data_list, field_name, elements, phase=phase) M_prod = obtain_mprod(data_list, e) binned_y = 1.0 * all_data # np.array( [all_data[k] for k in all_data.keys()] ) for i, loc in enumerate([0.1, 0.25, 0.5, 1.0]): loc_bin = np.argmin(np.abs(xpos - loc)) # get the right position bin y = binned_y[:, loc_bin] bin_edges = utilities.bin_edges(np.round(times)) # rebin with 10 Myr bins, rather than previous 1 Myr bins # convert y from outflow rate to outflow rate / mass produced / sfr if method == 'fraction': y = (y / M_prod) * 1.0E6 # convert to 1/Myr else: y = (y / M_prod) / SFR newx, rebiny = utilities.simple_rebin( 1.0 * bin_edges, 1.0 * y, np.arange(np.min(bin_edges), np.max(bin_edges) + 2, 5.0), 'average') plot_histogram(ax[index], newx - newx[0], rebiny, lw=line_width, color=plasma(i / 4.0), label=r"%0.1f R$_{\rm vir}$" % (loc)) if i == 0: xy = (np.max(newx - newx[0]) * 0.8, np.max(rebiny) * 10.0) ax[index].annotate(e, xy=xy, xytext=xy) axj = axj + 1 if axj >= 4: axj = 0 axi = axi + 1 for i in np.arange(4): ax[(3, i)].set_xlabel(r'Time (Myr)') # ax[(i,0)].set_ylabel(r'log(X Fractional Outflow per SFR [M$_\odot$ yr$^{-1}$]$^{-1}$)') ax[(i, 0)].set_xlim(newx[0] - newx[0], np.min([TMAX, newx[-1] - newx[0]])) if method == 'fraction': ax[(0, i)].set_ylim(1.0E-5, 1.0E-1) else: ax[(0, i)].set_ylim(1.0E-7, 1.0E-3) ax[(0, i)].semilogy() if method == 'fraction': ax[(2, 0)].set_ylabel(r'log(X Fractional Outflow Rate [Myr$^{-1}$])') else: ax[(2, 0)].set_ylabel( r'log(X Fractional Outflow per SFR [M$_\odot$ yr$^{-1}$]$^{-1}$)') plt.minorticks_on() if method == 'fraction': fig.savefig(outdir + 'X_Fractional_Outflow_panel.png') else: fig.savefig(outdir + 'X_Fractional_Outflow_loading_panel.png') plt.close() return
def plot_time_evolution(dir='./abundances/', fname='gas_abundances.h5', abundance=False, show_std=False, show_quartile=False, fraction_type='mass', plot_type='Fe'): # for each dataset, plot the distributions of gas fractions in each phase all_data = dd.io.load(dir + fname) all_fields = all_data['abundance_fields'] share_axis = False if abundance: if plot_type == 'standard': all_fields = all_data['abundance_fields'] # plot all over Fe and Fe over H plot_fields = utilities.sort_by_anum( [x for x in all_fields if '_over_Fe' in x]) plot_fields = plot_fields + ['Fe_over_H'] elif len(plot_type) <= 2: # assume it is a species name plot_fields = utilities.sort_by_anum( [x for x in all_fields if ('_over_' + plot_type) in x]) # No longer doing this - plot separately with everything else to allow for share axis # if (plot_type + '_over_H') in all_fields: # plot_fields = plot_fields + [plot_type + '_over_H'] share_axis = True else: plot_fields = utilities.sort_by_anum(all_data['metal_species']) plot_fields = [x + '_Fraction' for x in plot_fields] nplots = len(plot_fields) nrow, ncol = utilities.rowcoldict[nplots] # all_ds represents list of dataset names and kwargs to pull from all_ds = np.sort([x for x in all_data.keys() if 'DD' in x]) # gather times for all data sets times = utilities.extract_nested_dict_asarray(all_data, ['general', 'Time'], loop_keys=all_ds) # normalize time evolution times = times - times[0] # set up plot - define the phase names we want to loop over if share_axis: fig, ax = plt.subplots(nrow, ncol, sharex=True, sharey=True) else: fig, ax = plt.subplots(nrow, ncol) fig.set_size_inches(4 * nrow, 4 * ncol) fig.subplots_adjust(hspace=0.0, wspace=0.0) all_phases = ['CNM', 'WNM', 'HIM', 'star_forming', 'halo'] # these are all that are available axi, axj = 0, 0 xmin, xmax = 1.0E99, -1.0E99 for field in plot_fields: axind = (axi, axj) # plot all phases for a fixed plot - add std or quartile if desired ymax = -1.0E99 for j, phase in enumerate(all_phases): key_list = [phase, fraction_type + '_fraction', field] avg = utilities.extract_nested_dict_asarray(all_data, key_list + ['mean'], loop_keys=all_ds) ax[axind].plot(times, avg, color=_mask_color[phase], ls=_mask_ls[phase], label=phase, lw=line_width) ymax = np.max([ymax, np.max(avg)]) if show_std: std = utilities.extract_nested_dict_asarray(all_data, key_list + ['std'], loop_keys=all_ds) ax[axind].fill_between(times, avg - std, avg + std, color=_mask_color[phase], alpha=0.5, lw=2.0) if show_quartile: Q1 = utilities.extract_nested_dict_asarray(all_data, key_list + ['Q1'], loop_keys=all_ds) Q3 = utilities.extract_nested_dict_asarray(all_data, key_list + ['Q3'], loop_keys=all_ds) # filter out "None" that can appear select = (Q1 > -np.inf) * (Q3 > -np.inf) * (times > -np.inf) # print times[select] # print Q1[select] # print Q3[select] # print _mask_color[phase], phase xmin = np.min([xmin, np.min(times[select])]) xmax = np.max([xmax, np.max(times[select])]) ax[axind].fill_between(times[select], np.array(Q1[select]).astype(float), np.array(Q3[select]).astype(float), color=_mask_color[phase], alpha=0.5, lw=2.0) # set axis limits and labels based on whether or not we are plotting # abundance ratios or number fractions if abundance: label = field.split('_over_') if share_axis: xy = (0.125, 0.8) ax[axind].annotate(label[0], xy=xy, xytext=xy, xycoords='axes fraction', textcoords='axes fraction') label = r'log([X/' + label[1] + '])' else: label = r'log([' + label[0] + '/' + label[1] + '])' # set axis limits and labels according to shared restrictions if (share_axis and axj == 0) or (not share_axis): ax[axind].set_xlim(xmin, xmax) ax[axind].set_ylabel(label) if (share_axis and axi == nrow) or (not share_axis): ax[axind].set_xlabel(r'Time (Myr)') if (share_axis and axi == 0) or (not share_axis): dx = 0.0 # some slop to get axis labels to not clash if share_axis: dx = 0.15 if '_over_H' in field: ax[axind].set_ylim(-8 - dx, 0 + dx) else: ax[axind].set_ylim(-3 - dx, 3 + dx) else: if share_axis: xy = (0.125, 0.8) ax[axind].annotate(field.split('_Frac')[0], xy=xy, xytext=xy, xycoords='axes fraction', textcoords='axes fraction') label = r'log([X Fraction])' else: label = r'log([' + field + '])' if (share_axis and axj == 0) or (not share_axis): ax[axind].set_xlim(xmin, xmax) ax[axind].set_ylabel(label) if (share_axis and axi == nrow) or (not share_axis): ax[axind].set_xlabel(r'Time (Myr)') if (share_axis and axi == 0) or (not share_axis): ax[axind].set_ylim(1.0E-12, 3.0E-2) ax[axind].semilog_y() ax[axind].minorticks_on() axj = axj + 1 if axj >= ncol: axj = 0 axi = axi + 1 ax[(0, 0)].legend(loc='best', ncol=2) if not share_axis: plt.tight_layout() plt.minorticks_on() if abundance: outname = 'time_evolution_' + fraction_type + '_abundances_over_' + plot_type + '.png' else: outname = 'time_evolution_' + fraction_type + '_fractions.png' if show_quartile: outname = 'quartile_' + outname fig.savefig(outname) plt.close() return
def plot_sequestering(directory='./', fields=None, elements=None, fraction=None): """ Given a directory, goes through all data outputs in that directory and plots the time evolution of the mass contained in specified gas phases for a given species. The default behavior is to plot all fields for each element on a different plot for each element. fields : list, default is to use all of: Disk, CNM, WNM, HIM, FullBox, stars, Molecular, OutsideBox, GravBound elements : list, default is to loop through all elements: H, He, C, N, O, Mg, Ca, Si, Mn, S, Fe, Y, Eu, and Metals fraction : optional, string. Plot the mass fraction. Normalize all lines by one of the fields listed above. """ output_dir = directory + '/sequestering/' if not os.path.exists(output_dir): os.makedirs(output_dir) if not fraction is None: output_dir += fraction + '/' if not os.path.exists(output_dir): os.makedirs(output_dir) sfields = fields if sfields is None: sfields = [ 'Disk', 'CNM', 'WNM', 'HIM', 'FullBox', 'stars', 'Molecular', 'OutsideBox', 'GravBound' ] # # get all data # all_output = np.sort(glob.glob(directory + '/DD*.h5')) all_elements = elements if all_elements is None: # this is a hacky way of getting the metal fields - should just save this to file metal_fields = dd.io.load(all_output[0], '/gas_meta_data/masses/FullBox') exclude = [ 'H', 'HI', 'HII', 'H2', 'Metals', 'Total', 'He', 'HeI', 'HeII', 'HeIII' ] metal_fields = utilities.sort_by_anum( [x for x in metal_fields if (not any([y in x for y in exclude]))]) individual_metals = metal_fields all_elements = ['H', 'He', 'Metals'] + individual_metals for element in all_elements: fig, ax = plt.subplots() # construct dictionary and time array plot_data = {} t = np.zeros(len(all_output)) for s in sfields: plot_data[s] = np.zeros(len(all_output)) # loop through all output, gathering time and mass values for i in np.arange(len(all_output)): t[i] = dd.io.load(all_output[i], '/meta_data/Time') x = dd.io.load(all_output[i], '/gas_meta_data/masses') # now loop through all fields for s in sfields: if element == 'Metals' and s == 'stars': plot_data[s][i] = x[s]['metals'] else: plot_data[s][i] = x[s][element] # normalize if necessary norm = np.ones(np.size(plot_data[sfields[0]])) if not fraction is None: norm = 1.0 / plot_data[fraction] ymax = np.max(plot_data['FullBox'] * norm) if fraction is None: ymax = 5.0 * ymax ymin = 1.0E-8 * ymax # try and set something reasonable for minimum if it exists ymin = np.max([ymin, np.min(plot_data['stars'] * norm) * 10.0]) for s in sfields: # ignore fields that are too tiny to show up on plot if np.max(plot_data[s] * norm) < ymin: continue ax.plot(t, plot_data[s] * norm, lw=ps.lw, label=s, ls=ls[s], color=colors[s]) ax.set_xlabel(r'Time (Myr') if not fraction is None: ax.set_ylabel('Mass Fraction of ' + element + ' relative to ' + fraction) else: ax.set_ylabel(element + r' Mass (M$_{\odot}$)') ax.set_ylim(ymin, ymax) ax.semilogy() plt.minorticks_on() fig.set_size_inches(8, 8) plt.tight_layout() ax.legend(loc='best', ncol=2) outname = output_dir + '/' + element + '_sequestering.png' if not fraction is None: outname = output_dir + '/' + element + '_' + fraction + '_fraction_sequestering.png' fig.savefig(outname) plt.close(fig) del (plot_data) return
def sort_labels(l): elements = [x for x in l if len(x) <=2] other = [x for x in l if len(x) > 2] return other + utilities.sort_by_anum(elements)
import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid from galaxy_analysis.yt_fields import field_generators as fg from galaxy_analysis.utilities import utilities import galaxy_analysis as ga yt.funcs.mylog.setLevel(50) from joblib import Parallel, delayed import multiprocessing import deepdish as dd temp = dd.io.load('DD0100_galaxy_data.h5', '/gas_meta_data/masses/CNM') elements = utilities.sort_by_anum([x for x in temp.keys() if len(x) <= 2 and (not (x in ['H','He','H2','HI','HII','HeI']))]) print(np.size(elements), '-----------') def plot_single_frames(dsi, fpath = '.'): fields = ['N_Number_Density','O_Number_Density','Fe_Number_Density','Ba_Number_Density'] # fields = ['O_over_Fe', 'Fe_over_H', 'N_over_H', 'O_over_H', 'N_over_O', 'Ba_over_H'] ds = yt.load(fpath + '/DD%0004i/DD%0004i'%(dsi,dsi)) fg.generate_derived_fields(ds) ds = yt.load(fpath + '/DD%0004i/DD%0004i'%(dsi,dsi)) data = ds.all_data() data = ds.disk([0.5,0.5,0.5],[0,0,1],(2.0,'kpc'), (500,'pc'))