b = ad[YT_magnetic_field_strength].v d = ad[YT_density].v dv = ad[YT_cell_volume].v #dbins = np.geomspace( d[d>0].min(), d.max(),64) #bbins = np.geomspace( b[b>0].min(), b.max(),65) dbins = np.geomspace(d_ext.minmax[0], d_ext.minmax[1], 64) bbins = np.geomspace(b_ext.minmax[0], b_ext.minmax[1], 65) hist, xb, yb = np.histogram2d(d, b, bins=[dbins, bbins], weights=dv) #pch.helper(hist,xb,yb,ax=ax) d = this_looper.tr.track_dict['density'][:, nf] b = this_looper.tr.track_dict['magnetic_field_strength'][:, nf] dv = this_looper.tr.track_dict['cell_volume'][:, nf] hist, xb, yb = np.histogram2d(d, b, bins=[dbins, bbins], weights=dv) pch.helper(hist, xb, yb, ax=ax1) axbonk(ax, xscale='log', yscale='log', xlabel='density', ylabel='magnetic', xlim=d_ext.minmax, ylim=b_ext.minmax) axbonk(ax1, xscale='log', yscale='log', xlabel='density', ylabel='magnetic', xlim=d_ext.minmax, ylim=b_ext.minmax) #ax1.set_xlim( ax.get_xlim())
def run(self, core_list=None, plot=False): 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 thtr.sort_time() tsorted = thtr.times self.core_list = core_list self.times = tsorted self.b_array = np.zeros([len(core_list), len(tsorted)]) self.d_array = np.zeros([len(core_list), len(tsorted)]) self.a_array = np.zeros([len(core_list), len(tsorted)]) if plot: ds = this_looper.load(frame) ad = ds.all_data() b = ad[YT_magnetic_field_strength].v d = ad[YT_density].v dv = ad[YT_cell_volume].v dbins = np.geomspace(d[d > 0].min(), d.max(), 64) bbins = np.geomspace(b[b > 0].min(), b.max(), 64) hist, xb, yb = np.histogram2d(d, b, bins=[dbins, bbins], weights=dv) for nc, core_id in enumerate(core_list): print('do %s %d' % (self.this_looper.sim_name, core_id)) #continue #ms = trackage.mini_scrubber(thtr,core_id) #ms.particle_pos(core_id) #self.ms = ms #if ms.nparticles < 10: # continue self.cores_used.append(core_id) B = thtr.c([core_id], 'magnetic_field_strength') density = thtr.c([core_id], 'density') cell_volume = thtr.c([core_id], 'cell_volume') Vtotal = cell_volume.sum(axis=0) self.mean_b[core_id] = (B * cell_volume).sum(axis=0) / Vtotal self.b_array[nc, :] = self.mean_b[core_id] self.mean_rho[core_id] = (density * cell_volume).sum(axis=0) / Vtotal self.d_array[nc, :] = self.mean_rho[core_id] rm = rainbow_map(tsorted.size) if plot: fig, ax = plt.subplots(1, 1) pch.helper(hist, xb, yb, ax=ax) for nframe in [0]: #range(B.shape[1]-1): BBB = np.log10(B[:, nframe]) DDD = np.log10(density[:, nframe]) popt, pcov = curve_fit(b_from_rho, DDD, BBB, p0=[1, 1]) self.alpha_FTA[core_id].append(popt[0]) if plot: ax.scatter(10**DDD, 10**BBB, c=[rm(nframe)] * density.shape[0]) #ax.scatter(DDD , BBB, c=[rm(nframe)]*density.shape[0]) #ax.plot(DDD, DDD*pfit[1]+pfit[0]) ax.plot(10**DDD, 10**b_from_rho(DDD, *popt), c='k') if np.isnan(self.alpha_FTA[core_id]).any(): pdb.set_trace() self.a_array[nc, :-1] = self.alpha_FTA[core_id] if plot: axbonk(ax, xscale='log', yscale='log', xlabel='density', ylabel='magnetic_field_strength') fig.savefig('plots_to_sort/b_rho_%s_c%04d.png' % (self.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)
ps2 = phi2.sum(axis=0) p3min, p3max = min([ps1.min(), ps2.min()]), max([ps1.max(), ps2.max()]) norm = mpl.colors.Normalize(p3min, p3max) ax2.imshow(ps1, norm=norm) ax3.imshow(ps2, norm=norm) print('more plots') if 1: rbins = np.geomspace(1 / 2048, rcube.max(), 64) phibins = np.linspace(phi_min, phi_max, 65) print(' hist1') hist1, xb1, yb1 = np.histogram2d(rcube.flatten(), phi1.flatten(), bins=[rbins, phibins], weights=dv_cube.flatten()) pch.helper(hist1, xb1, yb1, ax=ax4) print(' hist2') hist2, xb2, yb2 = np.histogram2d(rcube.flatten(), phi2.flatten(), bins=[rbins, phibins], weights=dv_cube.flatten()) pch.helper(hist2, xb2, yb2, ax=ax5) ax4.set_xscale('log') ax5.set_xscale('log') ax4.set_ylim(phi_min, phi_max) ax5.set_ylim(phi_min, phi_max) if 0: ax4.scatter(rcube.flatten(), phi1.flatten(), c='k', s=0.1) ax5.scatter(rcube.flatten(), phi2.flatten(), c='r', s=0.1) #ax4.set_ylim(phi_min,phi_max)
def run(self, output_prefix='NAME', core_list=None, frames=None, verbose=False, los_list=[-1], external_ax=None): print('w3', core_list) dx = 1. / 2048 nx = 1. / dx thtr = self.other_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') if frames is None: frames = thtr.frames thtr.sort_time() tsorted = thtr.times / colors.tff self.core_list = core_list mini_scrubbers = {} other_looper = self.other_looper for core_id in core_list: print('Otherones core %d' % core_id) ms = trackage.mini_scrubber(other_looper.tr, core_id, do_velocity=False) #ms.make_floats(core_id) Ncol = len(frames) frame_index = [ np.where(other_looper.tr.frames == frame)[0][0] for frame in frames ] frame_str = "_%04d" * Ncol % tuple(frames) nrows = len(frame_index) counter = -1 if external_ax is not None: axes = external_ax else: fig, axes = plt.subplots(nrows, 3, figsize=(12, 8)) for nt, frame in zip(frame_index, frames): counter += 1 ax0 = axes[counter][0] #ax0.set_aspect('equal') ax1 = axes[counter][1] #ax = axes[counter][1] #ax.set_aspect('equal') delta = 0.1 mask = slice(None) this_x, this_y, this_z = ms.this_x[mask, nt], ms.this_y[ mask, nt], ms.this_z[mask, nt] this_p = [this_x, this_y, this_z] x = 1 y = 2 ax0.set_xlabel('xyz'[x] + ' [code units]') ax0.set_ylabel('xyz'[y] + ' [code units]') #ax.set_xlabel('xyz'[x]+' [code units]') #ax.set_ylabel('xyz'[y]+' [code units]') x_min, x_max, y_min, y_max = [1, 0, 1, 0] x_min = min([x_min, this_p[x].min(), -delta]) x_max = max([x_max, this_p[x].max(), 1 + delta]) y_min = min([y_min, this_p[y].min(), -delta]) y_max = max([y_max, this_p[y].max(), 1 + delta]) if 1: #projection by 2d histogram. x_ext = extents() #this_p[x]) y_ext = extents() #this_p[y]) x_ext(this_p[x]) y_ext(this_p[y]) #they're quantized at t=0 dx = 1. / 128 dx = [1. / 128, 1. / 256][counter] x_quantized = np.floor( nar(x_ext.minmax) / dx) * dx + 0.5 * dx y_quantized = np.floor( nar(y_ext.minmax) / dx) * dx + 0.5 * dx xbins = np.mgrid[ x_quantized[0]:x_quantized[1]:dx] + 0.5 * dx ybins = np.mgrid[ y_quantized[0]:y_quantized[1]:dx] + 0.5 * dx #r_bins = np.geomspace( *r_ext.minmax) hist, xb, yb = np.histogram2d(this_p[x], this_p[y], bins=[xbins, ybins]) #pch.helper(hist,xb,yb,ax=ax, cmap_name='Blues') pch.helper(hist, xb, yb, ax=ax0, cmap_name='Blues') ms2 = trackage.mini_scrubber(self.first_looper.tr, core_id, do_velocity=False) first_p = np.stack([ ms2.this_x[:, nt], ms2.this_y[:, nt], ms2.this_z[:, nt] ]) #ax.scatter( first_p[x], first_p[y], s=1, marker='+',c='r') ax0.scatter(first_p[x], first_p[y], c='r', marker='.', s=1) box_x, box_y = [0, 1, 1, 0, 0], [0, 0, 1, 1, 0] ax0.plot(box_x, box_y, c=[0.5] * 3) if 0: #projection by mapping the positions onto a cube and projecting. #May be inefficient, definitely cumbersome. ii = np.floor((nar(this_p) * 128)).astype('int') imin = ii.min(axis=1) ii[0] -= imin[0] ii[1] -= imin[1] ii[2] -= imin[2] image = np.zeros([ii.max() + 1] * 3) image[ii[0], ii[1], ii[2]] = 1 #ax.scatter( this_p[x], this_p[y]) #ax.scatter( ii[x], ii[y]) #ax.scatter(ii[x].flatten(), ii[y].flatten()) if 1: TheZ = image.sum(axis=1) norm = mpl.colors.LogNorm(vmin=1, vmax=TheZ.max()) cmap = copy.copy(mpl.cm.get_cmap("Blues")) cmap.set_under('w') #ax.pcolormesh(xx,yy,TheZ, norm=norm,cmap=cmap) #ax.imshow(TheZ, cmap=cmap, norm=norm, origin='lower',interpolation='nearest') box_x, box_y = [0, 1, 1, 0, 0], [0, 0, 1, 1, 0] box_x, box_y = nar(box_x) * 128 - imin[x], nar( box_y) * 128 - imin[y] ax.plot(box_x, box_y, c=[0.5] * 3) ms2 = trackage.mini_scrubber(self.first_looper.tr, core_id, do_velocity=False) first_p = np.stack([ ms2.this_x[:, nt], ms2.this_y[:, nt], ms2.this_z[:, nt] ]) ax.scatter(first_p[x] * 128 - imin[x], first_p[y] * 128 - imin[y], s=1, marker='+', c='r') #ax.scatter( first_p[x]*128-imin[x], first_p[y]*128-imin[y], s=100, facecolors='none',edgecolors='k') #ax.scatter( first_p[x], first_p[y], s=100) xticks = np.mgrid[-imin[x]:128 - imin[x]:11j] labs = ["%0.1f" % val for val in (xticks + imin[x]) / 128] ax.set_xticks(xticks) ax.set_xticklabels(labs) yticks = np.mgrid[-imin[y]:128 - imin[y]:11j] labs = ["%0.1f" % val for val in (yticks + imin[y]) / 128] ax.set_yticks(yticks) ax.set_yticklabels(labs) ax.set_xlabel(r'$%s$' % ('xyz'[x])) ax.set_ylabel(r'$%s$' % ('xyz'[y])) other_density = other_looper.tr.c([core_id], 'density')[:, nt] first_density = self.first_looper.tr.c([core_id], 'density')[:, nt] other_x = ms.this_x[:, nt] - ms2.mean_x[nt] other_y = ms.this_y[:, nt] - ms2.mean_y[nt] other_z = ms.this_z[:, nt] - ms2.mean_z[nt] other_r = np.sqrt(other_x**2 + other_y**2 + other_z**2) rmin = 1 / 2048 rmax = other_r.max() other_r[other_r < rmin] = rmin rrr = ms2.r[:, nt] + 0 rrr[rrr < rmin] = rmin r_ext = extents() d_ext = extents() r_ext(other_r) d_ext(other_density) r_ext(rrr) d_ext(first_density) reload(pch) rho_bins = np.geomspace(other_density.min(), other_density.max(), 64) r_bins = np.geomspace(*r_ext.minmax) hist, xb, yb = np.histogram2d(other_r, other_density, bins=[r_bins, rho_bins]) pch.helper(hist, xb, yb, ax=ax1, cmap_name='Greens') #ax1.scatter( rrr, first_density, s=100, facecolors='none',edgecolors='k') ax1.scatter(rrr, first_density, s=1, marker='+', c='r') axbonk(ax1, xscale='log', yscale='log', xlim=r_ext.minmax, ylim=d_ext.minmax, xlabel=r'$r [code\ units]$', ylabel=r'$density\ [code\ units]$') #axbonk(ax,xlabel='xyz'[x]+' [code units]',ylabel='xyz'[x]+' [code units]') if external_ax is None: outname = 'plots_to_sort/otherones_%s_c%04d_%s.png' % ( output_prefix, core_id, frame_str) fig.savefig(outname) plt.close(fig) 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 = 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 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)