def plot_mountain_top(this_looper, core_list=None, r_inflection=None, r_mass=None): if core_list is None: core_list=np.unique(this_looper.tr.core_ids) ds = this_looper.load(this_looper.target_frame) xtra_energy.add_energies(ds) reload(mountain_top) #radius=1e-2 radius=4/128 radius = ds.arr(radius,'code_length') for core_id in core_list: peak = this_looper.targets[core_id].peak_location this_target = this_looper.targets[core_id] top1 = mountain_top.top(ds,peak, rhomin = this_target.min_density, peak_id=core_id, radius=radius) proj = ds.proj('density',0,center=top1.location,data_source=top1.region) pw = proj.to_pw() pw.set_cmap('density','Greys') #pw.annotate_clumps([master_clump]+master_clump.leaves) if top1.leaf['particle_index'].size > 10: p_size = 1 else: p_size = 7 pw.annotate_these_particles4(1.0,col='r',positions= top1.leaf['particle_position'], p_size=p_size) pw.zoom(0.5/radius.v) pw.set_axes_unit('code_length') pw.annotate_clumps([top1.leaf], plot_args={'color':'y'}) if r_inflection is not None: RRR = r_inflection[core_id] pw.annotate_sphere( top1.location, RRR, circle_args={'color':'r'}) if r_mass is not None: if core_id in r_mass: RRR = r_mass[core_id] pw.annotate_sphere( top1.location, RRR, circle_args={'color':'b'}) print(pw.save('plots_to_sort/mountain_top_%s_c%04d'%(this_looper.sim_name, core_id)))
def plot_phi(this_looper, core_list=None): if core_list is None: core_list = np.unique(this_looper.tr.core_ids) frame = this_looper.target_frame for core_id in core_list: print('Potential %s %d' % (this_looper.sim_name, core_id)) save_prefix = 'plots_to_sort/%s_n%04d_c%04d' % (this_looper.sim_name, frame, core_id) ds = this_looper.load(frame) xtra_energy.add_energies(ds) ms = trackage.mini_scrubber(this_looper.tr, core_id) c = nar([ms.mean_x[-1], ms.mean_y[-1], ms.mean_z[-1]]) rsph = ds.arr(8.0 / 128, 'code_length') #rsph = ds.arr(2/128,'code_length') sp = ds.sphere(c, rsph) if 0: proj = ds.proj('grav_energy', 0, center=c, data_source=sp) pw = proj.to_pw(center=c) pw.zoom(32) pw.save(save_prefix) GE = np.abs(sp['grav_energy']) dv = np.abs(sp['cell_volume']) RR = sp['radius'] r_sphere = sp['radius'] DD = sp['density'] ok = RR < 0.01 fit = np.polyfit(np.log10(RR[ok]), np.log10(DD[ok]), 1) M = sp['cell_mass'].sum() G = 1620 / (4 * np.pi) coe = -1 / (8 * np.pi * G) power = 2 * fit[0] + 2 phi_del_squ_analy = (coe * G**2 * M**2 * r_sphere** (power)) / max(r_sphere)**(2 * fit[0] + 6) fig, ax = plt.subplots(1, 2) ax0 = ax[0] ax1 = ax[1] if 1: rbins = np.geomspace(r_sphere[r_sphere > 0].min(), r_sphere.max(), 64) gbins = np.geomspace(GE[GE > 0].min(), GE.max(), 64) hist, xb, yb = np.histogram2d(r_sphere, GE, bins=[rbins, gbins], weights=dv) pch.helper(hist, xb, yb, ax=ax0, transpose=False) if 1: rbins = np.geomspace(r_sphere[r_sphere > 0].min(), r_sphere.max(), 64) dbins = np.geomspace(DD[DD > 0].min(), DD.max(), 64) hist, xb, yb = np.histogram2d(r_sphere, DD, bins=[rbins, dbins], weights=dv) pch.helper(hist, xb, yb, ax=ax1, transpose=False) if 0: ax.scatter(sp['radius'], -sp['grav_energy'], c='r', s=0.1) #ax.set_xlim(sp['radius'].min(),sp['radius'].max()) if 1: axt = ax0.twinx() sort = np.argsort(sp['radius']) rsort = sp['radius'][sort] GEdv = (GE * RR)[sort] tots = np.cumsum(GEdv) axt.plot(rsort, tots) ax0.plot(RR, np.abs(phi_del_squ_analy), c='k') ax1.plot(RR[ok], 10**(fit[0] * np.log10(RR[ok]) + fit[1]), c='r') axbonk(ax0, xscale='log', yscale='log', xlabel='r', ylabel='abs(grav_eng)') axbonk(ax1, xscale='log', yscale='log', xlabel='r', ylabel='density') fig.savefig(save_prefix + "grav_eng") continue ax.clear() bins = np.geomspace(GE[GE > 0].min(), GE.max(), 64) ax.hist(np.abs(sp['grav_energy']), bins=bins, histtype='step') axbonk(ax, xlabel='Grad Phi', ylabel='N', xscale='log', yscale='log') fig.savefig(save_prefix + "grad_phi_hist") min_ge = np.argmin(GE) x, y, z = sp['x'][min_ge], sp['y'][min_ge], sp['z'][min_ge] c = ds.arr([x, y, z], 'code_length') SSS = yt.SlicePlot(ds, 'x', 'grav_energy', center=c) SSS.annotate_sphere(center=c, radius=rsph) SSS.save(save_prefix) SSS = yt.SlicePlot(ds, 'x', 'kinetic_energy', center=c) #SSS.annotate_sphere(sp) SSS.save(save_prefix)
def run(self, core_list=None): this_looper = self.this_looper if core_list is None: core_list = np.unique(this_looper.tr.core_ids) frame = this_looper.target_frame ds = this_looper.load(frame) G = ds['GravitationalConstant'] / (4 * np.pi) xtra_energy.add_energies(ds) for core_id in core_list: print('Mass Edge %s %d' % (this_looper.sim_name, core_id)) ms = trackage.mini_scrubber(this_looper.tr, core_id) c = nar([ms.mean_x[-1], ms.mean_y[-1], ms.mean_z[-1]]) R_SPHERE = 4 / 128 rsph = ds.arr(R_SPHERE, 'code_length') sp = ds.sphere(c, rsph) GE = np.abs(sp['grav_energy']) dv = np.abs(sp['cell_volume']) RR = sp['radius'] DD = sp['density'] R_KEEP = R_SPHERE #self.rinflection[core_id] #get the zones in the sphere that are #within R_KEEP ok_fit = np.logical_and(RR < R_KEEP, GE > 0) rok = RR[ok_fit].v ORDER = np.argsort(rok) rho_o = DD[ok_fit][ORDER].v ge_o = GE[ok_fit][ORDER].v dv_o = dv[ok_fit][ORDER].v rr_o_full = RR[ok_fit][ORDER].v mass_r = (rho_o * dv_o).cumsum() enrg_r = (ge_o * dv_o).cumsum() rr_o = np.linspace(max([1 / 2048, rr_o_full.min()]), rr_o_full.max(), 128) all_r, all_m = rr_o_full[1:], mass_r[1:] my_r = np.linspace(max([1 / 2048, all_r.min()]), all_r.max(), 1024) mbins = np.linspace(all_m.min(), all_m.max(), 128) thing, mask = np.unique(all_r, return_index=True) mfunc = interp1d(all_r[mask], all_m[mask]) my_m = gaussian_filter(mfunc(my_r), 2) dm = (my_m[1:] - my_m[:-1]) mm = 0.5 * (my_m[1:] + my_m[:-1]) dr = (my_r[1:] - my_r[:-1]) dm_dr = dm / dr rbins = 0.5 * (my_r[1:] + my_r[:-1]) SWITCH = 2 * rbins * dm_dr / mm findit = np.logical_and(rbins > 0.01, SWITCH < 1) if findit.sum() > 0: ok = np.where(findit)[0][0] self.edge[core_id] = my_r[ok - 1]
def run(self, core_list=None): this_looper = self.this_looper if core_list is None: core_list = np.unique(this_looper.tr.core_ids) frame = this_looper.target_frame ds = this_looper.load(frame) G = ds['GravitationalConstant'] / (4 * np.pi) xtra_energy.add_energies(ds) for core_id in core_list: print('Potential %s %d' % (this_looper.sim_name, core_id)) ms = trackage.mini_scrubber(this_looper.tr, core_id) c = nar([ms.mean_x[-1], ms.mean_y[-1], ms.mean_z[-1]]) R_SPHERE = 8 / 128 rsph = ds.arr(R_SPHERE, 'code_length') sp = ds.sphere(c, rsph) GE = np.abs(sp['grav_energy']) dv = np.abs(sp['cell_volume']) RR = sp['radius'] #2d distribution of GE vs r gbins = np.geomspace(GE[GE > 0].min(), GE.max(), 65) rbins = np.geomspace(RR[RR > 0].min(), RR.max(), 67) r_cen = 0.5 * (rbins[1:] + rbins[:-1]) #we'll need this later. hist, xb, yb = np.histogram2d(RR, GE, bins=[rbins, gbins], weights=dv) #clear out annoying stragglers in the distribution. #any point that doesn't have any neighbors is eliminated. #h2 is the histogram to do math with. if 1: #h2 is the histogram. #we'll remove any stragglers. h2 = hist + 0 shifter = np.zeros(nar(h2.shape) + 2) cuml = np.zeros(h2.shape) c_center = slice(1, -1) #hb is just "is h2 nonzero" #we'll slide this around to look for neighbors hb = (h2 > 0) shifter[c_center, c_center] = hb nx, ny = shifter.shape for i in [0, 1, 2]: for j in [0, 1, 2]: if i == 1 and j == 1: continue s1 = slice(i, nx - 2 + i) s2 = slice(j, ny - 2 + j) cuml += shifter[s1, s2] #kill points that don't have neighbors. h2 *= (cuml > 0) if 1: #Compute the upper bound of the histogram #smooth it #look for the point where the slope goes up. #but to avoid wiggles, it has to first come down a lot. #the upper bound of the distribution #compute upper_envelope y = np.arange(h2.shape[1]) y2d = np.stack([y] * h2.shape[0]) argmax = np.argmax(y2d * (h2 > 0), axis=1) upper_envelope = gbins[argmax] keepers = upper_envelope > 1 #smooth for wiggles. UE = gaussian_filter(upper_envelope[keepers], 1) # # Find the inflection point where the slope comes up again. # #the slope DUE = UE[1:] - UE[:-1] #the max up to this radius cummax = np.maximum.accumulate(UE) #where the slope is positive ok = DUE > 0 #and not too close to the center (for noise) ok = np.logical_and(ok, r_cen[keepers][1:] > 1e-3) #and it has to come down below half its maximum ok = np.logical_and(ok, UE[1:] < 0.5 * cummax[1:]) index = np.argmax(r_cen[keepers]) if ok.any(): #find out the radius where the inflection happens. index = np.where(ok)[0][0] R_KEEP = r_cen[keepers][index] self.rinflection[core_id] = R_KEEP self.rinflection_list.append(R_KEEP)
def run(self, core_list=None, frames=None): dx = 1. / 2048 nx = 1. / dx thtr = self.this_looper.tr all_cores = np.unique(thtr.core_ids) if core_list is None: core_list = all_cores if hasattr(core_list, 'v'): core_list = core_list.v #needs to not have unit. core_list = core_list.astype('int') thtr.sort_time() if frames is None: frames = thtr.frames if frames == 'reg': times = thtr.times #assume the first nonzero time is dt_sim dt = times[times > 0][0] nframe = times / dt outliers = np.round(nframe) - nframe frame_mask = np.abs(outliers) < 1e-3 frames = thtr.frames[frame_mask] times = thtr.times[frame_mask] self.frames = frames self.times = times tsorted = thtr.times self.core_list = core_list for core_id in core_list: ms = trackage.mini_scrubber(thtr, core_id) self.ms = ms if ms.nparticles < 10: continue print('go ', core_id) this_center = ms.mean_center[:, -1] self.cores_used.append(core_id) frame = self.this_looper.target_frame ds = self.this_looper.load(frame) xtra_energy.add_energies(ds) ms.particle_pos(core_id) pos = np.stack([ ms.particle_x.transpose(), ms.particle_y.transpose(), ms.particle_z.transpose() ]) sphere = ds.sphere(center=this_center, radius=0.25) name = self.this_looper.sim_name if 0: proj = ds.proj(YT_grav_energy, 0, data_source=sphere) pw = proj.to_pw(center=this_center, origin='domain') pw.set_cmap(YT_grav_energy, 'Greys') pw.zoom(4) pw.annotate_sphere(this_center, ds.arr(7e-3, 'code_length')) pw.save('plots_to_sort/isohol_%s_n%04d_' % (name, frame)) if 0: proj = ds.proj('density', 0, data_source=sphere) pw = proj.to_pw(center=this_center, origin='domain') pw.zoom(4) pw.set_cmap('density', 'Greys') pw.annotate_sphere(this_center, ds.arr(7e-3, 'code_length')) pw.save('plots_to_sort/isohol_%s_n%04d_' % (name, frame)) if 0: plot = yt.PhasePlot(sphere, YT_density, YT_cell_volume, [YT_cell_mass], weight_field=None) plot.save('plots_to_sort/isorho_%s_n%04d' % (name, frame)) pdb.set_trace() if 0: fig, ax = plt.subplots(1, 1) ax.scatter(sphere[YT_radius], sphere[YT_density]) ax.scatter(ms.r[:, -1], ms.density[:, -1], facecolor='None', edgecolor='r') axbonk(ax, xscale='log', yscale='log') fig.savefig('plots_to_sort/density_radius_%s_c%04d.png' % (name, core_id)) if 0: fig, ax = plt.subplots(1, 1) ax.scatter(sphere[YT_radius], -sphere[YT_grav_energy]) axbonk(ax, xscale='log', yscale='log', xlabel='r', ylabel='|grad phi|') fig.savefig('plots_to_sort/potential_radius_%s_c%04d.png' % (name, core_id)) if 0: fig, ax = plt.subplots(1, 1) ax.scatter(sphere[YT_radius], sphere[YT_kinetic_energy]) axbonk(ax, xscale='log', yscale='log', xlabel='r', ylabel='|grad phi|') fig.savefig('plots_to_sort/KE_radius.png_%s_c%04d.png' % (name, core_id)) if 0: fig, ax = plt.subplots(1, 1) ok = sphere[YT_density] > 300 vx = sphere[YT_velocity_x] vy = sphere[YT_velocity_y] vz = sphere[YT_velocity_z] dv = sphere[YT_cell_volume] rho = sphere[YT_density] m = (rho[ok] * dv[ok]).sum() vx_bar = (vx * dv * rho)[ok].sum() / m vy_bar = (vy * dv * rho)[ok].sum() / m vz_bar = (vz * dv * rho)[ok].sum() / m vbar = 0.5 * ((vx - vx_bar)**2 + (vy - vy_bar)**2 + (vz - vz_bar)**2) ax.scatter(sphere[YT_radius], vbar) axbonk(ax, xscale='log', yscale='log', xlabel='r', ylabel='KE') fig.savefig('plots_to_sort/Velocity_radius_%s_c%04d.png' % (name, core_id)) if 0: fig, ax = plt.subplots(1, 1) rrr = ms.r + 0 rrr[rrr < 1. / 2048] = 1. / 2048 rrr = rrr.transpose() den = ms.density.transpose() fig, ax = plt.subplots(1, 1) xmin = 1 / 2048 xmax = 3.5e-1 ymin = 1e-2 ymax = 1e6 for frame in frames: nframe = np.where(thtr.frames == frame) ax.clear() ax.plot(rrr[:nframe, :], den[:nframe, :], c=[0.5] * 4, linewidth=0.2) #ax.plot( ms.this_x.transpose(), ms.this_y.transpose(), c=[0.5]*4, linewidth=0.2) axbonk(ax, xlabel='r', ylabel='rho', xscale='log', yscale='log', xlim=[xmin, xmax], ylim=[ymin, ymax]) outname = 'plots_to_sort/rho-r-t_%s_c%04d_i%04d' % ( name, core_id, nframe) fig.savefig(outname) print(outname) if 0: import colors fig, ax = plt.subplots(1, 1) t = thtr.times / colors.tff rrr = ms.r + 0 rrr[rrr < 1. / 2048] = 1. / 2048 rrr = rrr.transpose() den = ms.density.transpose() fig, ax = plt.subplots(1, 1) xmin = 1 / 2048 xmax = 3.5e-1 ymin = 1e-2 ymax = 1e6 ax.plot(t, den, c=[0.5] * 4, linewidth=0.2) axbonk(ax, xlabel=r'$t/t_{ff}$', ylabel='rho', yscale='log') fig.savefig('plots_to_sort/rho-t_%s_c%04d' % (name, core_id)) if 1: import colors fig, ax = plt.subplots(2, 2, figsize=(12, 12)) ax0 = ax[0][0] ax1 = ax[0][1] ax2 = ax[1][0] rrr = ms.r + 0 rrr[rrr < 1. / 2048] = 1. / 2048 rrr = rrr.transpose() t = thtr.times / colors.tff den = ms.density.transpose() xmin = 1 / 2048 xmax = 3.5e-1 ymin = 1e-2 ymax = 1e6 for iframe, frame in enumerate(frames): nframe = np.where(thtr.frames == frame)[0][0] ax0.clear() ax1.clear() ax0.plot(rrr[:nframe + 1, :], den[:nframe + 1, :], c=[0.5] * 4, linewidth=0.2) ax0.scatter(rrr[nframe, :], den[nframe, :], c='k', s=0.2) ax1.plot(t[:nframe + 1], den[:nframe + 1, :], c=[0.5] * 4, linewidth=0.2) ax1.scatter([t[nframe]] * ms.nparticles, den[nframe, :], c='k', s=0.2) ax2.plot(pos[0][:nframe + 1, :], pos[1][:nframe + 1, :], c=[0.5] * 4, linewidth=0.2) ax2.scatter(pos[0][nframe + 1, :], pos[1][nframe + 1, :], c='k', s=0.2) #ax.plot( ms.this_x.transpose(), ms.this_y.transpose(), c=[0.5]*4, linewidth=0.2) axbonk(ax0, xlabel='r', ylabel='rho', xscale='log', yscale='log', xlim=[xmin, xmax], ylim=[ymin, ymax]) outname = 'plots_to_sort/so_much_hair_%s_c%04d_i%04d' % ( name, core_id, iframe) fig.savefig(outname) print(outname)
cmap = mpl.cm.jet cmap.set_under('w') color_map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) ploot = ax.pcolormesh(KIN, TTT, CCC, norm=norm) ax.set_xlabel(phase.x_field) ax.set_ylabel(phase.y_field) fig.colorbar(ploot, ax=ax) if 'ds' not in dir() or always: car.frames = [frame] #directory = "/scratch1/dcollins/Paper49_EBQU/ca07_nofield_mach10"; frame=2100 #ds = yt.load("%s/DD%04d/data%04d"%(directory, frame, frame)) ds = car.load(frame) xe.add_energies(ds) ds.add_field('v2', function=v2, units='code_velocity**2') ds.add_field( 'therm_work', function=therm_work, units='code_density*code_velocity/code_length', validators=[yt.ValidateSpatial(1, 'velocity-%s' % s) for s in 'xyz'], sampling_type='cell') ds.add_field('te_ke_ratio', function=te_ke_ratio, units='dimensionless', sampling_type='cell') region = ds.all_data() if 1:
fields = [ 'x', 'y', 'z', 'velocity_magnitude', 'magnetic_field_strength', 'density' ] fields += ['kinetic_energy', 'magnetic_energy', 'grav_energy', 'therm_energy'] fields += ['momentum_flux', 'gravity_work', 'mag_work', 'pressure_work'] #fields = ['grav_energy']#,'therm_energy'] if 0: #h5ptr = h5py.File('u05_0125_peaklist.h5','r') #cen = h5ptr['peaks'][79] cen = np.array([0.40258789, 0.6862793, 0.05249023]) ds = yt.load(dl.enzo_directory + "/DD0125/data0125") #xtra_energy.add_energies(ds) #xtra_energy.add_test_energies(ds) xtra_energy.add_force_terms(ds) xtra_energy.add_energies(ds) radius = 0.1 sphere = ds.sphere(cen, radius) for field in fields: proj = ds.proj(field, 0, center=cen, data_source=sphere) pw = proj.to_pw(center=cen, width=2. * radius) #pw.set_zlim('pressure_work',-1e6,1e6) pw.set_log(field, True, linthresh=0.1) pw.save('/home/dcollins4096/PigPen/test_c0079') #print(gx['momentum_flux']) #print(gx['grav_x']) #for frame in this_looper.ds_list: # xtra_energy.add_test_energies(this_looper.ds_list[frame]) #sys.exit(0)
def run(self, core_list=None, do_plots=True, do_proj=True): if core_list is None: core_list = np.unique(this_looper.tr.core_ids) this_looper = self.this_looper frame = this_looper.target_frame ds = this_looper.load(frame) G = ds['GravitationalConstant'] / (4 * np.pi) xtra_energy.add_energies(ds) for core_id in core_list: print('Potential %s %d' % (this_looper.sim_name, core_id)) ms = trackage.mini_scrubber(this_looper.tr, core_id) c = nar([ms.mean_x[-1], ms.mean_y[-1], ms.mean_z[-1]]) R_SPHERE = 8 / 128 rsph = ds.arr(R_SPHERE, 'code_length') sp = ds.sphere(c, rsph) GE = np.abs(sp['grav_energy']) dv = np.abs(sp['cell_volume']) RR = sp['radius'] DD = sp['density'] R_KEEP = self.rinflection[core_id] #2d distribution of GE vs r gbins = np.geomspace(GE[GE > 0].min(), GE.max(), 65) rbins = np.geomspace(RR[RR > 0].min(), RR.max(), 67) r_cen = 0.5 * (rbins[1:] + rbins[:-1]) #we'll need this later. hist, xb, yb = np.histogram2d(RR, GE, bins=[rbins, gbins], weights=dv) #get the zones in the sphere that are #within R_KEEP ok_fit = np.logical_and(RR < R_KEEP, GE > 0) rok = RR[ok_fit].v # # Binding energy and GMM/R # ge_total = (GE[ok_fit] * dv[ok_fit]).sum() mtotal = (sp['cell_mass'][ok_fit]).sum() gmm = G * mtotal**2 / R_KEEP self.output['ge_total'].append(ge_total) self.output['gmm'].append(gmm) if 1: #store stuff self.output['mass'].append(mtotal) self.output['r0'].append(R_KEEP) if 0: #Just fit GE def plain_powerlaw(x, q, r0): return q * x + r0 popt, pcov = curve_fit(plain_powerlaw, np.log10(rok), np.log10(GE[ok_fit])) GE_fit_line = 10**plain_powerlaw(np.log10(rok), *popt) ouput['alpha_ge'].append(popt[0]) if 1: #Better ge fit def plain_powerlaw(x, q, norm): return (2 * q + 2) * x + norm #np.log10(G*mtotal/R_KEEP) popt, pcov = curve_fit(plain_powerlaw, np.log10(rok / R_KEEP), np.log10(GE[ok_fit])) A = 10**popt[1] alpha = popt[0] rmax = (rok).max() rmin = (rok).min() rfit = np.linspace(rmin, rmax, 128) rr = 0.5 * (rfit[1:] + rfit[:-1]) dr = rfit[1:] - rfit[:-1] GE_fit_line = 10**plain_powerlaw(np.log10(rr / R_KEEP), *popt) #GE_fit_line=10**plain_powerlaw(np.log10(rok/R_KEEP), *popt) self.output['alpha_ge'].append(alpha) self.output['A'].append(A) self.output['AA'].append(G**2 * mtotal**2 / R_KEEP**(2 * alpha + 2)) R0 = R_KEEP self.output['analytic'].append( 4 * np.pi * A / ((R0**(2 * alpha + 2) * (2 * alpha + 5))) * (rmax**(2 * alpha + 5) - rmin**(2 * alpha + 5))) self.output['rmin'].append(rmin) self.output['rmax'].append(rmax) self.output['analytic2'].append( 4 * np.pi * A / ((R0**(2 * alpha + 2) * (2 * alpha + 5))) * (R_KEEP**(2 * alpha + 5))) R0 = R_KEEP M = mtotal E1 = (-G * M * M / R0**(2 * alpha + 6) / (2 * alpha + 5)) * (R0**(2 * alpha + 5) - rmin**(2 * alpha + 5)) self.output['ann_good'].append(E1) if 1: #Fit density #Maybe its not necessary to histogram first, but it makes plotting easier. rbins = np.geomspace(RR[RR > 0].min(), RR.max(), 67) dbins = np.geomspace(DD[DD > 0].min(), DD.max(), 65) dhist, xbdr, ybdr = np.histogram2d(RR, DD, bins=[rbins, dbins], weights=dv) dok = DD[ok_fit] def powerlaw_r0_rkeep(r, q, rho0): return q * np.log10(r / R_KEEP) + np.log10(rho0) poptd, pcovd = curve_fit(powerlaw_r0_rkeep, rok, np.log10(dok)) self.output['alpha_rho'].append(poptd[0]) if do_proj: proj_axis = 0 dx = 1 / 2048 nx = 2 * R_SPHERE / dx pd = ds.proj('density', proj_axis, data_source=sp, center=c) frb = pd.to_frb(2 * R_SPHERE, nx, center=c) fig2, rx = plt.subplots(1, 2, figsize=(12, 8)) rx0 = rx[0] rx1 = rx[1] column_density = frb['density'] norm = mpl.colors.LogNorm(column_density.min(), column_density.max()) rx0.imshow(column_density, norm=norm) column_density = frb[YT_grav_energy] linthresh = 1 norm = mpl.colors.SymLogNorm(linthresh, vmin=column_density.min(), vmax=0) rx1.imshow(column_density, norm=norm) center = nar(column_density.shape) / 2 circle = plt.Circle(center, R_KEEP / dx, fill=False) rx0.add_artist(circle) circle = plt.Circle(center, R_KEEP / dx, fill=False) rx1.add_artist(circle) fig2.savefig('plots_to_sort/cPhiProj_%s_c%04d' % (this_looper.sim_name, core_id)) #Some plotting and fitting. if do_plots: fig, ax = plt.subplots(1, 2) ax0 = ax[0] ax1 = ax[1] if 0: #plot GE ax0.plot(r_cen[keepers], UE) pch.helper(h2, xb, yb, ax=ax0, transpose=False) #ax0.plot( rok, GE_fit_line,c='r') ax0.plot(rr, GE_fit_line, c='r') ax0.scatter(R_KEEP, UE[index], c='r') AlsoA = colors.G * mtotal**2 / (4 * np.pi) * R_KEEP**(-4) ax0.scatter(R_KEEP, A, c='g', marker='*') ax0.scatter(R_KEEP, AlsoA, c='b', marker='*') if 1: #plot density pch.helper(dhist, xbdr, ybdr, ax=ax1, transpose=False) axbonk(ax1, xscale='log', yscale='log', xlabel='r', ylabel='rho') #density_fit_line=10**( poptd[0]*np.log10(rok)+np.log10(poptd[1])) density_fit_line = 10**(powerlaw_r0_rkeep(rok, *poptd)) ax1.plot(rok, density_fit_line, c='g') if 0: rmin = r_cen[keepers].min() ok2 = (RR < R_KEEP) * (RR > rmin) M = sp['cell_mass'][ok2].sum() coe = 1 / (8 * np.pi * G) power = 2 * poptd[0] + 2 #print('DANS POWER',power) #phi_del_squ_analy = (coe*G**2*M**2*rok**(power))/R_KEEP**(2*poptd[0]+6) #horse around DanA = (coe * G**2 * M**2) / R_KEEP**(2 * poptd[0] + 6) phi_del_squ_analy = DanA * rok**(power) self.output['DanA'].append(DanA) alpha = poptd[0] rho0 = poptd[1] #phi_del_squ_analy = (4*np.pi*G*rho0*R_KEEP**(-alpha)*(2*alpha+5)/(alpha+3))**2*rok**power #phi_del_squ_analy = (4*np.pi*G*rho0*R_KEEP**(-alpha)*(alpha+2)/(alpha+3))**2*rok**power ax0.plot(rok, phi_del_squ_analy, c='g') if 0: #works pretty well M = sp['cell_mass'].sum() coe = 1 / (8 * np.pi * G) power = 2 * poptd[0] + 2 phi_del_squ_analy = (coe * G**2 * M**2 * rbins**(power) ) / RR.max()**(2 * poptd[0] + 6) #print(phi_del_squ_analy) ax0.plot(rbins, phi_del_squ_analy, c='k') if 0: #color the upper envelope #to make sure we get it right. print(hist.shape) y = np.arange(hist.shape[1]) y2d = np.stack([y] * hist.shape[0]) argmax = np.argmax(y2d * (hist > 0), axis=1) ind = np.arange(hist.shape[0]) #take = np.ravel_multi_index(nar([argmax,ind]),hist.shape) take = np.ravel_multi_index(nar([ind, argmax]), hist.shape) h1 = hist.flatten() h1[take] = hist.max() h1.shape = hist.shape pch.helper(h1, xb, yb, ax=ax0, transpose=False) outname = 'plots_to_sort/%s_c%04d_potfit' % ( this_looper.sim_name, core_id) axbonk(ax0, xscale='log', yscale='log', xlabel='r', ylabel='grad phi sq') fig.savefig(outname) print(outname)
def plot_mountain_top(this_looper, core_list=None, r_inflection=None, r_mass=None): sim_name = this_looper.sim_name thtr=this_looper.tr if core_list is None: core_list=np.unique(this_looper.tr.core_ids) frame=this_looper.target_frame ds = this_looper.load(frame) if 0: #projections. #I'm not quite right. frame = 0 ds = yt.load('/data/cb1/Projects/P19_CoreSimulations/new_sims/vel_test/DD%04d/data%04d'%(frame,frame)) for axis in [0,1,2]: proj = ds.proj('density',axis) pw=proj.to_pw() pw.annotate_velocity() pw.save('plots_to_sort/arse') xtra_energy.add_energies(ds) xtra_energy.add_gravity(ds) reload(mountain_top) #radius=1e-2 for core_id in core_list: ms = trackage.mini_scrubber(thtr,core_id,do_velocity=True) ms.get_central_at_once(core_id) if r_inflection is not None and False: radius = r_inflection[core_id] radius = ds.arr(radius, 'code_length') else: radius=1/128 radius = ds.arr(radius,'code_length') peak = this_looper.targets[core_id].peak_location this_target = this_looper.targets[core_id] top1=None if 0: top1 = mountain_top.top(ds,peak, rhomin = this_target.min_density, peak_id=core_id, radius=radius) proj_axis=0 if proj_axis == 1: print("ERROR: plotting messed up for axis 1") raise h_axis = ds.coordinates.x_axis[proj_axis] v_axis = ds.coordinates.y_axis[proj_axis] left = peak - radius.v right = peak + radius.v dx = 1/2048 nzones = np.floor((right-left)/dx).astype('int') SphereVbar = None if 1: if r_inflection is not None: RRR = r_inflection[core_id] sph = ds.sphere( peak, RRR) M = (sph[YT_density]*sph[YT_cell_volume]).sum() SphereVbar = [( (sph[('gas','velocity_%s'%s)]*sph[YT_cell_mass]).sum()/M ).v for s in 'xyz'] #SphereVbar = [( (sph[('gas','momentum_%s'%s)]*sph[YT_cell_mass]).sum()/M ).v for s in 'xyz'] cg = ds.covering_grid(4,left,nzones, num_ghost_zones=1) #cg = ds.covering_grid(0,[0.0]*3,[128]*3, num_ghost_zones=1) def from_cg(field): ccc = cg[field]#.swapaxes(0,2) return ccc.v def proj(arr): return arr.sum(axis=proj_axis) fig,ax=plt.subplots(1,1) ax.set_aspect('equal') #field = ('gas','momentum_x') field='density' #field=YT_grav_energy if type(field) is tuple: field_name = field[1] else: field_name=field rho= from_cg(field) dv = from_cg(YT_cell_volume) PPP= proj(rho) if field_name in ['density']: norm = mpl.colors.LogNorm(vmin=PPP.min(), vmax=PPP.max()) else: norm = mpl.colors.Normalize(vmin=PPP.min(), vmax=PPP.max()) x_h = proj( from_cg( ('gas','xyz'[h_axis]) ) ) x_v = proj( from_cg( ('gas','xyz'[v_axis]) ) ) "H for horizontal, V for vertical" if 0: stream_name='momentum' stream_h = 'momentum_%s'%'xyz'[h_axis] stream_v = 'momentum_%s'%'xyz'[v_axis] if 1: stream_name='velocity' stream_h = 'velocity_%s'%'xyz'[h_axis] stream_v = 'velocity_%s'%'xyz'[v_axis] if 0: stream_name='accel' stream_h = 'grav_%s'%'xyz'[h_axis] stream_v = 'grav_%s'%'xyz'[v_axis] Q_H = from_cg(stream_h) Q_V = from_cg(stream_v) M = (rho*dv).sum() if 0: Q_H_mean=0 Q_V_mean=0 if 0: Q_H_mean = Q_H.mean() Q_V_mean = Q_V.mean() if 0: stream_name += "_whole_mean" #works pretty good Q_H_mean = (Q_H*dv*rho).sum()/M Q_V_mean = (Q_V*dv*rho).sum()/M if 0: mean_vx = ms.mean_vx[-1] mean_vy = ms.mean_vy[-1] mean_vz = ms.mean_vz[-1] mean = [mean_vx, mean_vy, mean_vz] Q_H_mean = mean[ h_axis] Q_V_mean = mean[ v_axis] if 1: stream_name += "_vcentral" Q_H_mean = ms.vcentral[h_axis,-1] Q_V_mean = ms.vcentral[v_axis,-1] if 0: LLL = top1.leaf Q_H_mean =((LLL['density']*LLL['cell_volume']*LLL[stream_h]).sum()/(LLL['density']*LLL['cell_volume']).sum()).v Q_V_mean =((LLL['density']*LLL['cell_volume']*LLL[stream_v]).sum()/(LLL['density']*LLL['cell_volume']).sum()).v if 0: LLL = top1.leaf Q_H_mean =((LLL['cell_volume']*LLL[stream_h]).sum()/(LLL['cell_volume']).sum()).v Q_V_mean =((LLL['cell_volume']*LLL[stream_v]).sum()/(LLL['cell_volume']).sum()).v if 0: Q_H_mean = SphereVbar[ h_axis] Q_V_mean = SphereVbar[ v_axis] Q_H -= Q_H_mean Q_V -= Q_V_mean Q_H_p = proj(Q_H) Q_V_p = proj(Q_V) #TheX,TheY,TheU,TheV= x_h, x_v, Q_H, Q_V TheX, TheY = np.meshgrid( np.unique( x_h), np.unique( x_v)) TheU,TheV= Q_H_p, Q_V_p if 0: print(x_h) print('poooo') print(TheX.size) print(TheY.size) print(TheU.size) gg = TheU**2+TheV**2 ok = gg>0 if 0: X_to_plot = TheX#.transpose() Y_to_plot = TheY#.transpose() PPP_to_plot = PPP#.transpose() U_to_plot = TheU#.transpose() V_to_plot = TheV#.transpose() else: X_to_plot = TheY.transpose() Y_to_plot = TheX.transpose() PPP_to_plot = PPP.transpose() U_to_plot = TheU.transpose() V_to_plot = TheV.transpose() #ax.imshow( PPP,norm=norm) ploot=ax.pcolormesh( X_to_plot, Y_to_plot, PPP_to_plot, norm=norm, shading='nearest') fig.colorbar(ploot) #U_to_plot[ PPP_to_plot == 0] = np.nan #V_to_plot[ PPP_to_plot == 0] = np.nan ax.streamplot(X_to_plot, Y_to_plot, U_to_plot, V_to_plot, density=2.5) axbonk(ax, xlabel='xyz'[h_axis], ylabel='xyz'[v_axis]) outname='plots_to_sort/proj_%s_%s_c%04d_n%04d_%s_%s.png'%('xyz'[proj_axis],sim_name, core_id, frame,field_name, stream_name) fig.savefig(outname) print(outname)
def run(self,core_list=None, do_plots=True,do_proj=True): if core_list is None: core_list = np.unique(this_looper.tr.core_ids) this_looper=self.this_looper frame = this_looper.target_frame ds = this_looper.load(frame) G = ds['GravitationalConstant']/(4*np.pi) xtra_energy.add_energies(ds) for core_id in core_list: #print('Potential %s %d'%(this_looper.sim_name,core_id)) ms = trackage.mini_scrubber(this_looper.tr,core_id) c = nar([ms.mean_x[-1], ms.mean_y[-1],ms.mean_z[-1]]) R_SPHERE = 8/128 rsph = ds.arr(R_SPHERE,'code_length') sp = ds.sphere(c,rsph) GE = np.abs(sp['grav_energy']) dv = np.abs(sp['cell_volume']) RR = sp['radius'] DD = sp['density'] R_KEEP = R_SPHERE #self.rinflection[core_id] rinflection=None if self.rinflection is not None: rinflection = self.rinflection[core_id] #get the zones in the sphere that are #within R_KEEP ok_fit = np.logical_and(RR < R_KEEP, GE>0) rok=RR[ok_fit].v ORDER = np.argsort(rok) rho_o = DD[ok_fit][ORDER].v ge_o = GE[ok_fit][ORDER].v dv_o = dv[ok_fit][ORDER].v rr_o_full = RR[ok_fit][ORDER].v mass_r = (rho_o*dv_o).cumsum() enrg_r = (ge_o*dv_o).cumsum() rr_o = np.linspace( max([1/2048, rr_o_full.min()]), rr_o_full.max(), 128) enrg_i = interp1d( rr_o_full, enrg_r) gmm_r = interp1d( rr_o_full, G*mass_r**2/rr_o_full) all_r,all_m=rr_o_full[1:], mass_r[1:] my_r = np.linspace(max([1/2048, all_r.min()]),all_r.max(),1024) mbins = np.linspace( all_m.min(), all_m.max(), 128) thing, mask = np.unique( all_r, return_index=True) mfunc = interp1d( all_r[mask], all_m[mask]) my_m = gaussian_filter(mfunc(my_r),2) fact=enrg_r.max()/my_m.max() fig2,ax2=plt.subplots(1,1) ay0=ax2 ay0.plot( rr_o, enrg_i(rr_o), c='k', label=r'$E_G$') ay0.plot( rr_o, gmm_r(rr_o), c='r', label = r'$GM(<R)^2/R$') az0=ay0.twinx() ay0.plot( all_r, all_m*fact, c=[0.5]*4)#, label=r'$M*f$') ay0.plot( my_r, my_m * fact, c='m', label=r'$M*f$') #ay0.plot( xcen, average_mass, c='r') #az0.plot( my_r, my_m ) #az0.plot( rr_o, rho_o) #az0.set_yscale('log') dm=(my_m[1:]- my_m[:-1]) mm =0.5*(my_m[1:]+my_m[:-1]) dr=(my_r[1:]-my_r[:-1]) dm_dr = dm/dr rbins = 0.5*(my_r[1:]+my_r[:-1]) SWITCH=2*rbins*dm_dr/mm #az0.plot( rbins, SWITCH*my_m.max()/SWITCH.max()) az0.plot( rbins, SWITCH, c='b', label='$2 M^\prime /M$') findit=np.logical_and( rbins>0.01, SWITCH <= 1) PROBLEM=False if findit.sum() > 0: ok = np.where(findit)[0][0] SWITCH=2*rbins*dm_dr/mm az0.scatter( my_r[ok-1], SWITCH[ok-1], c='b') az0.axvline( my_r[ok-1], c='b') az0.axhline(1, c='b') else: PROBLEM=True print("PROBLEM CANNOT FIND RMASS") if rinflection is not None: ay0.axvline( rinflection, c='r', label='$R_I$') if PROBLEM: ay0.set_title('NO MASS EDGE') outname='plots_to_sort/%s_cuml_c%04d.png'%(this_looper.sim_name, core_id) ay0.legend(loc=2) az0.legend(loc=4) axbonk( ay0, xlabel='r',ylabel='E/M', xscale='log', yscale='log') axbonk( az0, ylabel=r'$2 M^\prime/(M/R)$', xscale='log', yscale='log') fig2.savefig(outname) print(outname) if 0: #Fit density #Maybe its not necessary to histogram first, but it makes plotting easier. rbins = np.geomspace( RR [RR >0].min(), RR .max(),67) dbins = np.geomspace( DD[DD>0].min(), DD.max(),65) dhist, xbdr, ybdr = np.histogram2d( RR , DD, bins=[rbins,dbins],weights=dv) dok=DD[ok_fit] def powerlaw_r0_rkeep( r, q, rho0): return q*np.log10(r/R_KEEP)+np.log10(rho0) poptd, pcovd=curve_fit(powerlaw_r0_rkeep, rok, np.log10(dok)) self.output['alpha_rho'].append(poptd[0]) if do_proj: proj_axis=0 dx = 1/2048 nx = 2*R_SPHERE/dx pd = ds.proj('density',proj_axis,data_source=sp, center=c) frb=pd.to_frb(2*R_SPHERE,nx,center=c) fig2,rx=plt.subplots(1,2, figsize=(12,8)) rx0=rx[0]; rx1=rx[1] column_density=frb['density'] norm = mpl.colors.LogNorm( column_density.min(),column_density.max()) rx0.imshow(column_density,norm=norm) column_density=frb[YT_grav_energy] linthresh=1 norm = mpl.colors.SymLogNorm(linthresh, vmin=column_density.min(),vmax=0) xx = ds.coordinates.x_axis[proj_axis] yy = ds.coordinates.y_axis[proj_axis] vh=frb['velocity_%s'%'xyz'[xx]][::8] vv=frb['velocity_%s'%'xyz'[yy]][::8] nx,ny=column_density.shape the_x,the_y = np.mgrid[0:nx:8,0:ny:8] #pdb.set_trace() #the_x=frb['xyz'[xx]] #the_y=frb['xyz'[yy]] rx1.imshow(column_density,norm=norm) rx1.quiver(the_x,the_y,vh,vv) center = nar(column_density.shape)/2 circle = plt.Circle( center, R_KEEP/dx,fill=False) rx0.add_artist(circle) circle = plt.Circle( center, R_KEEP/dx,fill=False) rx1.add_artist(circle) fig2.savefig('plots_to_sort/cPhiProj_%s_c%04d'%(this_looper.sim_name, core_id)) #Some plotting and fitting. if do_plots: fig,ax=plt.subplots(1,2) ax0=ax[0]; ax1=ax[1] if 1: #plot GE #ax0.plot(r_cen[keepers], UE) pch.helper(h2,xb,yb,ax=ax0,transpose=False) #ax0.plot( rok, GE_fit_line,c='r') ax0.plot( rr, GE_fit_line,c='r') #ax0.scatter( R_KEEP,UE[index],c='r') #AlsoA=colors.G*mtotal**2/(4*np.pi)*R_KEEP**(-4) ax0.scatter( R_KEEP, A, c='r',marker='*') #ax0.scatter( R_KEEP, AlsoA, c='b',marker='*') if 1: #plot density pch.helper(dhist,xbdr,ybdr,ax=ax1,transpose=False) axbonk(ax1,xscale='log',yscale='log',xlabel='r',ylabel='rho') #density_fit_line=10**( poptd[0]*np.log10(rok)+np.log10(poptd[1])) density_fit_line=10**( powerlaw_r0_rkeep( rok, *poptd)) ax1.plot( rok, density_fit_line,c='g') if 0: rmin=r_cen[keepers].min() ok2 = (RR < R_KEEP)*(RR > rmin) M = sp['cell_mass'][ok2].sum() coe = 1/(8*np.pi*G) power=2*poptd[0]+2 #print('DANS POWER',power) #phi_del_squ_analy = (coe*G**2*M**2*rok**(power))/R_KEEP**(2*poptd[0]+6) #horse around DanA = (coe*G**2*M**2)/R_KEEP**(2*poptd[0]+6) phi_del_squ_analy = DanA*rok**(power) self.output['DanA'].append( DanA) alpha=poptd[0] rho0=poptd[1] #phi_del_squ_analy = (4*np.pi*G*rho0*R_KEEP**(-alpha)*(2*alpha+5)/(alpha+3))**2*rok**power #phi_del_squ_analy = (4*np.pi*G*rho0*R_KEEP**(-alpha)*(alpha+2)/(alpha+3))**2*rok**power ax0.plot( rok, phi_del_squ_analy ,c='g') if 0: #works pretty well M = sp['cell_mass'].sum() coe = 1/(8*np.pi*G) power=2*poptd[0]+2 phi_del_squ_analy = (coe*G**2*M**2*rbins**(power))/RR.max()**(2*poptd[0]+6) #print(phi_del_squ_analy) ax0.plot( rbins, phi_del_squ_analy ,c='k') outname='plots_to_sort/%s_c%04d_potfit'%(this_looper.sim_name,core_id) axbonk(ax0,xscale='log',yscale='log',xlabel='r',ylabel='grad phi sq') fig.savefig(outname) print(outname)