Example #1
0
def make_frbs(filename,center,fields,ions,fdbk=False):
    ds = yt.load(filename)
    args = filename.split('/')

    trident.add_ion_fields(ds,ions=ions)

    if fdbk== True:
        print 'in fdbk'
        halo_center, halo_velocity = get_halo_center(ds,center)

        refine_box = fdbk_refine_box(ds,halo_center)

        width = [(160,'kpc'),(80.,'kpc')]
        resolution = (320,160)
        for field in fields:
            fileout = args[-3]+'_'+args[-2]+'_x_'+field+'.cpkl'
            obj = ds.proj(field,'x',data_source=refine_box)
            frb = obj.to_frb(width,resolution,center=box_center)
            cPickle.dump(frb[field],open(fileout,'wb'),protocol=-1)

    else:
        print 'in else'
        halo_center, halo_velocity = get_halo_center(ds,center)
        refine_box = sym_refine_box(ds,halo_center)
        width = [(40,'kpc'),(100.,'kpc')]
        resolution = (80,200)

        for field in fields:
            fileout = args[-3]+'_'+args[-2]+'_x_'+field+'.cpkl'
            obj = ds.proj(field,'x',data_source=refine_box)
            frb = obj.to_frb(width,resolution,center=halo_center)
            cPickle.dump(frb[field],open(fileout,'wb'),protocol=-1)
    return
Example #2
0
def plot_phase_diagrams(filenames,fileout):
    for i in range(len(filenames)):
        print 'i: ',i
        ds = yt.load(filenames[i])
        center_guess = initial_center_guess(ds,track_name)
        halo_center = get_halo_center(ds,center_guess)
        rb = sym_refine_box(ds,halo_center)

        args = filenames[i].split('/')
        sim_label = args[-3]

        dens = np.log10(rb['H_nuclei_density'])
        temp = np.log10(rb['Temperature'])

        df = pd.DataFrame({'temp':temp, 'dens':dens})
        phase_scatter = hv.Scatter(df,kdims=['dens'],vdims=['temp'],label=sim_label)

        #phase_data = np.zeros((len(rb['H_nuclei_density']),2))
        #phase_data[:,0] = np.log10(rb['H_nuclei_density'])
        #phase_data[:,1] = np.log10(rb['Temperature'])

        #points = hv.Points(phase_data,kdims=['nH','temp'],label=sim_label)
        hv.opts({'Histogram': {'style': {'alpha':0.3, 'fill_color':'k'}}})
        xhist = (histogram(phase_scatter, bin_range=(-7.5, 1), dimension='dens',normed=True)) #,alpha=0.3, fill_color='k'))
        yhist = (histogram(phase_scatter, bin_range=(3, 8.5), dimension='temp',normed=True)) #,alpha=0.3, fill_color='k'))

        if i == 0:
            phase_plot = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125))
        else:
            plot2 = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125))
            phase_plot = phase_plot + plot2

        renderer = hv.renderer('bokeh').instance(fig='html')
        renderer.save(phase_plot, fileout)
    return
Example #3
0
def gas_mass_phase_evolution(basename,RDnums,prefix):
    gas_mass = np.zeros((5,len(RDnums)))
    for i in range(len(RDnums)):
        if RDnums[i] < 100:
            zero = '00'
        else:
            zero = '0'
        ds = yt.load(basename+('/'+prefix+zero+str(RDnums[i]))*2)

        center_guess = initial_center_guess(ds,track_name)
        halo_center, halo_velocity = get_halo_center(ds,center_guess)
        rb = sym_refine_box(ds,halo_center)

        temp = np.log10(rb['Temperature'])
        cold = np.where(temp < 4.)[0]
        cool = np.where((temp >= 4.) & (temp < 5.))[0]
        warm = np.where((temp >= 5.) & (temp < 6.))[0]
        hot = np.where(temp >= 6.)[0]

        gas_mass[0,i] = ds.current_redshift
        gas_mass[1,i] = np.log10(np.sum(rb['cell_mass'][cold].in_units('Msun')))
        gas_mass[2,i] = np.log10(np.sum(rb['cell_mass'][cool].in_units('Msun')))
        gas_mass[3,i] = np.log10(np.sum(rb['cell_mass'][warm].in_units('Msun')))
        gas_mass[4,i] = np.log10(np.sum(rb['cell_mass'][hot].in_units('Msun')))
    return gas_mass
Example #4
0
def plot_cell_mass_histogram(filenames,fileout):
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])

        center_guess = initial_center_guess(ds,track_name)
        halo_center, halo_velocity = get_halo_center(ds,center_guess)
        sim_label = filenames[i].split('/')[-3]
        kwargs = plot_kwargs[sim_label]

        rb = sym_refine_box(ds,halo_center)
        cell_mass = rb['cell_mass'].in_units('Msun')
        cell_mass = np.log10(cell_mass)
        plt.hist(cell_mass,normed=True,bins=100,alpha=0.6,range=(-2,6.5),
                 color=kwargs['color'],label=sim_label)
    #hubble_time = 13e9/1.e6
    #plt.axvline(hubble_time,ls='--',color='k')
    plt.axvline(np.log10(2.2e5),ls='--',color='k') ## EAGLE https://arxiv.org/abs/1709.07577
    plt.text(np.log10(2.2e5),1.0,'EAGLE')
    plt.axvline(np.log10(7.1e3),ls='--',color='k') ## FIRE https://arxiv.org/abs/1606.09252
    plt.text(np.log10(7.1e3),1.0,'FIRE')
    plt.axvline(np.log10(1e6),ls='--',color='k') ## IllustrisTNG https://arxiv.org/abs/1703.02970
    plt.text(np.log10(1e6)-0.5,0.9,'IllustrisTNG')
    plt.legend()
    plt.xlabel('Cell Mass [log(Msun)]')
    plt.savefig(fileout)
    return
Example #5
0
def compute_disk_masses(filenames):
    rds = np.arange(28,43)
    rds = rds[::-1]
    timesteps = np.zeros(len(rds))
    gas_masses = np.zeros((len(rds),len(filenames)))
    stellar_masses = np.zeros((len(rds),len(filenames)))

    add_particle_filter("formed_star", function=formed_star, filtered_type='all',
                        requires=["creation_time"])

    for j in range(len(filenames)):
        center_guess = [0.48988587,0.47121728,0.50938220]
        for i in range(len(rds)):
            filein = filenames[j]+'/RD00'+str(rds[i])+'/RD00'+str(rds[i])
            ds = yt.load(filein)
            ds.add_particle_filter('formed_star')
            halo_center, halo_velocity = get_halo_center(ds,center_guess)
            center_guess = halo_center
            (Lx,x) = diskVectors(ds,halo_center)
            disk = ds.disk(halo_center,Lx,(40.,'kpc'),(20.,'kpc'))
            ## let's look for cold/dense gas
            ## ISM conditions from review paper:
            ## n > 0.1, T < 4
            idx = np.where((disk['H_p0_number_density'] < 0.1) &
                           (disk['Temperature'] < 1e4))[0]
            gas_masses[i,j] = np.sum(disk['cell_mass'][idx].in_units('Msun'))
            stellar_masses[i,j] = np.sum(disk['formed_star', 'particle_mass'].in_units('Msun'))
            timesteps[i] = ds.current_redshift
    data = {'gas_masses':gas_masses,'stellar_masses':stellar_masses,'timesteps':timesteps}
    cPickle.dump(data,open('disk_mass_evol.cpkl','wb'),protocol=-1)
    return gas_masses,stellar_masses,timesteps
Example #6
0
def plot_cooling_length_histogram(filenames,fileout):
    fig,ax = plt.subplots(1,2,sharey=True)
    fig.set_size_inches(10,5)
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])

        center_guess = initial_center_guess(ds,track_name)
        halo_center, halo_velocity = get_halo_center(ds,center_guess)
        sim_label = filenames[i].split('/')[-3]
        kwargs = plot_kwargs[sim_label]

        rb = sym_refine_box(ds,halo_center)
        cooling_length = rb['cooling_time']*rb['sound_speed']
        cooling_length = np.log10(cooling_length.in_units('kpc'))
        cell_mass = rb['cell_mass'].in_units('Msun')
        ax[0].hist(cooling_length,normed=True,bins=100,alpha=0.3,range=(-6,4),
                 color=kwargs['color'],label=sim_label,weights=cell_mass)

        idx = np.where(rb['H_nuclei_density'] < 0.1)[0]
        ax[1].hist(cooling_length[idx],normed=True,bins=100,alpha=0.3,range=(-6,4),
                 color=kwargs['color'],label=sim_label,weights=cell_mass[idx])
    #line for nref11
    #plt.axvline(np.log10(0.176622518811),ls='--',color='k')
    #line for nref10
    ax[0].axvline(np.log10(0.353245037622),ls='--',color='k')
    ax[1].axvline(np.log10(0.353245037622),ls='--',color='k')

    ax[1].legend()
    fig.text(0.5, 0.04, 'Cooling Length [log(kpc)]', ha='center')
    plt.savefig(fileout)
    return
Example #7
0
def plot_cooling_time_histogram(filenames, fileout):
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])

        center_guess = initial_center_guess(ds, track_name)
        halo_center, halo_velocity = get_halo_center(ds, center_guess)
        sim_label = filenames[i].split('/')[-3]
        kwargs = plot_kwargs[sim_label]

        rb = sym_refine_box(ds, halo_center)
        cooling_time = rb['cooling_time'].in_units('Myr')
        cooling_time = np.log10(cooling_time)
        cell_mass = rb['cell_mass'].in_units('Msun')
        plt.hist(cooling_time,
                 normed=True,
                 bins=100,
                 alpha=0.3,
                 range=(0, 6),
                 color=kwargs['color'],
                 label=sim_label,
                 weights=cell_mass)
    hubble_time = np.log10(13e9 / 1.e6)
    plt.axvline(hubble_time, ls='--', color='k')
    plt.legend()
    plt.xlabel('Cooling Time [log(Myr)]')
    plt.savefig(fileout)
    return
Example #8
0
def plot_mass_in_phase_evolution(basename,RDnums,prefix,fileout):
    gas_mass = gas_mass_phase_evolution(basename,RDnums,prefix)
    colors = ['salmon','purple','green','yellow']
    labels = ['cold','cool','warm','hot']
    fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=False,
                                   gridspec_kw={'height_ratios': [3, 1]},
                                   figsize=(7, 5))
    for i in range(4):
        print i
        ax[0].plot(gas_mass[0,:],gas_mass[i+1,:],color=colors[i],label=labels[i])
    zero = '00'
    if RDnums[-1] > 100 : zero='0'
    ds = yt.load(basename+('/'+prefix+zero+str(RDnums[-1]))*2)
    center_guess = initial_center_guess(ds,track_name)
    halo_center, halo_velocity = get_halo_center(ds,center_guess)
    sp = ds.sphere(halo_center,(50.,'kpc'))
    sfr = StarFormationRate(ds, data_source=sp)
    ax[1].plot(sfr.redshift,sfr.Msol_yr,'k')

    ax[0].set_xlim(gas_mass[0,:].max(),gas_mass[0,:].min())
    ax[1].set_xlabel('Redshift')
    ax[0].set_ylabel('log(Gas Mass) [Msun]')
    ax[1].set_ylabel('SFR [Msun/yr]')
    ax[0].legend()
    ax[0].set_ylim(6,11)
    ax[1].set_ylim(0,8)

    plt.tight_layout()
    plt.savefig(fileout)
    plt.close()
    return
Example #9
0
def plot_point_radialprofiles(filenames, center, field, fileout, plt_log=True):
    fig, ax = plt.subplots(2, 5, sharex=True, sharey=True)
    ax = ax.flatten()
    fig.set_size_inches(14, 8)
    fig.subplots_adjust(hspace=0.1, wspace=0.1)
    for i in range(len(filenames)):
        kwargs = plot_kwargs[filenames[i].split('/')[-3]]
        ds = yt.load(filenames[i])
        halo_center, halo_velocity = get_halo_center(ds, center)
        refine_box = fdbk_refine_box(ds, halo_center)
        halo_center = ds.arr(halo_center, 'code_length')
        dists = compute_cell_distance(halo_center, refine_box['x'],
                                      refine_box['y'], refine_box['z'])
        dists = dists.in_units('kpc')
        if plt_log:
            ax[i].plot(dists,
                       np.log10(refine_box[field]),
                       alpha=0.1,
                       color=kwargs['color'])
        else:
            ax[i].plot(dists,
                       refine_box[field],
                       '.',
                       alpha=0.1,
                       color=kwargs['color'])

        ax[0].set_ylabel(field)
        ax[7].set_xlabel('Distance [kpc]')
        plt.savefig(fileout)
    return
Example #10
0
def plot_entropy_profile_evolution(basename,RDnums,fileout):
    n = len(RDnums)
    colors = pl.cm.viridis(np.linspace(0,1,n))
    #fig,ax = plt.subplots(2,1)
    for i in range(len(RDnums)):
        ds = yt.load(basename+('/RD00'+str(RDnums[i]))*2)
        center_guess = initial_center_guess(ds,track_name)
        halo_center, halo_velocity = get_halo_center(ds,center_guess)
        rb = sym_refine_box(ds,halo_center)
        rp = yt.create_profile(rb,'radius',['entropy','total_energy'],
                                units = {'radius':'kpc'},logs = {'radius':False})
        zhere = "%.2f" % ds.current_redshift

        plt.figure(1)
        plt.plot(rp.x.value,rp['entropy'].value,color=colors[i],lw=2.0,label=zhere)
        plt.xlim(0,200)
        plt.figure(2)
        plt.plot(rp.x.value,np.log10(rp['total_energy'].value),color=colors[i],lw=2.0,label=zhere)

    plt.figure(1)
    plt.legend()
    plt.xlabel('Radius [kpc]')
    plt.ylabel('Entropy')
    plt.savefig(fileout+'_entropy.pdf')

    plt.figure(2)
    plt.legend()
    plt.xlabel('Radius [kpc]')
    plt.ylabel('Energy')
    plt.savefig(fileout+'_energy.pdf')

    plt.close()

    return
Example #11
0
def confirm_halo_centers(filenames,center):
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])
        args = filenames[i].split('/')[-3]
        halo_center, halo_velocity = get_halo_center(ds,center)
        sl = yt.SlicePlot(ds,'x','Density',center=halo_center,width=(200,'kpc'))
        sl.annotate_text(center,'c')
        sl.save(args)
    return
Example #12
0
def confirm_disks(filenames,center):
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])
        args = filenames[i].split('/')[-3]
        halo_center, halo_velocity = get_halo_center(ds,center)
        (Lx,x) = diskVectors(ds, halo_center)
        disk = ds.disk(halo_center,Lx,(100.,'kpc'),(20.,'kpc'))
        sl = yt.ProjectionPlot(ds,'y','Density',center=halo_center,width=(200,'kpc'),
                          data_source=disk)
        sl.annotate_text(center,'c')
        sl.save(args+'_disk')
    return
Example #13
0
def check_cooling_criteria(filenames):
        for i in range(len(filenames)):
            ds = yt.load(filenames[i])
            args = filenames[i].split('/')[-3]

            center_guess = initial_center_guess(ds,track_name)
            halo_center, halo_velocity = get_halo_center(ds,center_guess)
            rb = sym_refine_box(ds,halo_center)
            proj = yt.ProjectionPlot(ds,'x',('gas','cooling_criteria'),
                                    center=halo_center,width=(100,'kpc'),
                                    method='mip',data_source=rb)
            proj.set_zlim(('gas','cooling_criteria'),0.001,1.)
            #proj.annotate_text(center,'c')
            proj.save(args+'_refinebox')
        return
Example #14
0
def plot_mass_in_phase(filenames, fileout):
    total_masses,cold_masses,cool_masses,warm_masses,hot_masses = [],[],[],[],[]
    tick_labels = []
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])

        center_guess = initial_center_guess(ds, track_name)
        halo_center, halo_velocity = get_halo_center(ds, center_guess)
        sim_label = filenames[i].split('/')[-3]
        kwargs = plot_kwargs[sim_label]
        tick_labels = np.append(tick_labels, sim_label)

        rb = sym_refine_box(ds, halo_center)
        temp = np.log10(rb['Temperature'])
        cold = np.where(temp < 4.)[0]
        cool = np.where((temp >= 4.) & (temp < 5.))[0]
        warm = np.where((temp >= 5.) & (temp < 6.))[0]
        hot = np.where(temp >= 6.)[0]

        total_masses = np.append(
            total_masses, np.log10(np.sum(rb['cell_mass'].in_units('Msun'))))
        cold_masses = np.append(
            cold_masses,
            np.log10(np.sum(rb['cell_mass'][cold].in_units('Msun'))))
        cool_masses = np.append(
            cool_masses,
            np.log10(np.sum(rb['cell_mass'][cool].in_units('Msun'))))
        warm_masses = np.append(
            warm_masses,
            np.log10(np.sum(rb['cell_mass'][warm].in_units('Msun'))))
        hot_masses = np.append(
            hot_masses,
            np.log10(np.sum(rb['cell_mass'][hot].in_units('Msun'))))

    width = 0.35
    ind = np.arange(len(filenames))
    p1 = plt.bar(ind, cold_masses, width, color='salmon')
    p2 = plt.bar(ind, cool_masses, width, color='purple')
    p3 = plt.bar(ind, warm_masses, width, color='green')
    p4 = plt.bar(ind, hot_masses, width, color='yellow')

    plt.xlabel('Simulation')
    plt.ylabel('Gas Mass in Each Phase [log(Msun)]')
    plt.legend((p1[0], p2[0], p3[0], p4[0]), ('Cold', 'Cool', 'Warm', 'Hot'))

    plt.xticks(ind, tick_labels)
    plt.savefig(fileout)
    return
Example #15
0
def get_evolultion_Lx(filenames,center_guess):
    rds = np.arange(27,43)
    rds = rds[::-1]
    timesteps = np.zeros(len(rds))
    lvectors = np.zeros((len(rds),len(filenames)))

    for j in range(len(filenames)):
        for i in range(len(rds)):
            filein = filenames[i]+'/RD00'+str(rds[i])+'/RD00'+str(rds[i])
            ds = yt.load(filein)
            halo_center, halo_velocity = get_halo_center(ds,center_guess)
            (Lx,x) = diskVectors(ds,halo_center)
            lvectors[j,i] = Lx

            if (j==0) & (i == 0):
                timesteps[i] = ds.current_redshift

    return
Example #16
0
def plot_compare_basic_radial_profiles(filenames, fileout):
    fig, ax = plt.subplots(1, 3)
    fig.set_size_inches(12, 4)
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])

        center_guess = initial_center_guess(ds, track_name)
        halo_center, halo_velocity = get_halo_center(ds, center_guess)
        rb = sym_refine_box(ds, halo_center)

        dens = np.log10(rb['H_nuclei_density'])
        temp = np.log10(rb['Temperature'])
        Zgas = np.log10(rb['metallicity'])
        y_dists = [dens, temp, Zgas]
        x = rb['x']
        y = rb['y']
        z = rb['z']

        halo_center = ds.arr(halo_center, 'code_length')
        dist = np.sqrt((halo_center[0] - rb['x'])**2. +
                       (halo_center[1] - rb['y'])**2. +
                       (halo_center[2] - rb['z'])**2.).in_units('kpc')

        sim_label = filenames[i].split('/')[-3]
        kwargs = plot_kwargs[sim_label]
        for j in range(len(y_dists)):
            rp = spherical_radial_profile(dist, y_dists[j], 0.5)
            ax[j].plot(rp.r, rp.median, label=sim_label, **kwargs)
            ax[j].plot(rp.r, rp.q25, **kwargs)
            ax[j].plot(rp.r, rp.q75, **kwargs)
            ax[j].fill_between(rp.r,
                               rp.q25,
                               rp.q75,
                               alpha=0.3,
                               color=kwargs['color'])
            ax[j].set_xlabel('Radius [kpc]')
            #if j == (len(y_dists)-1)

        ax[0].set_title('Hydrogen Number Density')
        ax[1].set_title('Temperature')
        ax[2].set_title('Metallicity')
        ax[2].legend()
        plt.savefig(fileout)
    return
Example #17
0
def plot_phase_diagrams(filenames,fileout):
    fig,ax = plt.subplots(1,2,sharex=True,sharey=True)
    ax = ax.flatten()
    fig.set_size_inches(14,8)
    fig.subplots_adjust(hspace=0.1,wspace=0.1)
    fig.subplots_adjust(right=0.8)
    for i in range(len(filenames)):
        ds = yt.load(filenames[i])
        center_guess = initial_center_guess(ds,track_name)
        halo_center, halo_velocity = get_halo_center(ds,center_guess)
        refine_box = sym_refine_box(ds,halo_center)
        cellmass = refine_box['cell_mass'].in_units('Msun')
        H, xedges, yedges = np.histogram2d(np.log10(refine_box[('gas','H_nuclei_density')]),
                                           np.log10(refine_box['Temperature']),
                                           bins=200.,range=[[-6,0],[3, 8]],weights=cellmass) #,normed=True)

        im = ax[i].imshow(np.log10(H.T),extent=[-6,0,3,8],interpolation='nearest',
                     origin='lower',cmap='plasma',vmin=4,vmax=8)

        ax[i].set_title(filenames[i].split('/')[-3])
        ax[i].grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.87')
        ax[i].grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.87',alpha=0.2)
        ax[i].grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.87')
        ax[i].grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.87',alpha=0.2)
        ax[i].tick_params(axis='x',which='both',bottom='off',top='off',labelbottom='on')
        ax[i].tick_params(axis='y',which='both',bottom='off',top='off',labelbottom='off')
        ax[i].set_xlim([-6,0])
        ax[i].set_ylim([3,8])


    ax[0].set_ylabel('Temperature [log(K)]')
    fig.text(0.5, 0.04, 'nH [log(cm^-3)]', ha='center')
    #ax[0].set_xlabel('nH [log(cm^-3)]')
    #ax[0].set_xbound(lower=-6,upper=0)
    #ax[0].set_ybound(lower=3,upper=8)

    cbar_ax = fig.add_axes([0.85, 0.15, 0.02, 0.7])
    fig.colorbar(im, cax=cbar_ax)

    plt.savefig(fileout)
    return
Example #18
0
def plot_radial_profiles(filenames,fileout):
    for i in range(len(filenames)):
        print 'i: ',i
        ds = yt.load(filenames[i])
        center_guess = initial_center_guess(ds,track_name)
        halo_center = get_halo_center(ds,center_guess)
        rb = sym_refine_box(ds,halo_center)

        args = filenames[i].split('/')
        sim_label = args[-3]

        dens = np.log10(rb['H_nuclei_density'])
        temp = np.log10(rb['Temperature'])
        Zgas = np.log10(rb['metallicity'])
        x = rb['x']
        y = rb['y']
        z = rb['z']

        halo_center = ds.arr(halo_center,'code_length')
        dist = np.sqrt((halo_center[0]-rb['x'])**2.+(halo_center[1]-rb['y'])**2.+(halo_center[2]-rb['z'])**2.).in_units('kpc')

        df = pd.DataFrame({'temp':temp, 'dens':dens, 'Zgas':Zgas,
                            'x':x,'y':y,'z':z,'dist':dist})

        temp_dist = hv.Scatter(df,kdims=['dist'],vdims=['temp'],label="Temperature "+sim_label)
        dens_dist = hv.Scatter(df,kdims=['dist'],vdims=['dens'],label='Hydrogen Number Density')
        metal_dist = hv.Scatter(df,kdims=['dist'],vdims=['Zgas'],label='Metallicity')

        if i == 0:
            dist_plots = (datashade(temp_dist,cmap=cm.Reds, dynamic=False,x_range=(0,60),y_range=(2,8.4))
		          + datashade(dens_dist,cmap=cm.Blues, dynamic=False,x_range=(0,60),y_range=(-8,2))
		          + datashade(metal_dist,cmap=cm.BuGn, dynamic=False,x_range=(0,60),y_range=(-5,1.4)))
        else:
            dist_plots2 = (datashade(temp_dist,cmap=cm.Reds, dynamic=False,x_range=(0,60),y_range=(2,8.4))
		          + datashade(dens_dist,cmap=cm.Blues, dynamic=False,x_range=(0,60),y_range=(-8,2))
		          + datashade(metal_dist,cmap=cm.BuGn, dynamic=False,x_range=(0,60),y_range=(-5,1.4)))
            dist_plots = dist_plots + dist_plots2

    renderer = hv.renderer('bokeh').instance(fig='html')
    renderer.save(dist_plots.cols(3), fileout)
    return
Example #19
0
    if args.run == "natural":
        ds_loc = ds_base + "halo_008508/nref11n/natural/" + args.output + "/" + args.output
        track_name = ds_base + "halo_008508/nref11n/nref11n_nref10f_refine200kpc/halo_track"
        output_dir = output_path + "plots_halo_008508/nref11n/natural/spectra/"
        haloname = "halo008508_nref11n"
    elif args.run == "nref10f":
        ds_loc =  ds_base + "halo_008508/nref11n/nref11n_nref10f_refine200kpc/" + args.output + "/" + args.output
        track_name = ds_base + "halo_008508/nref11n/nref11n_nref10f_refine200kpc/halo_track"
        output_dir = output_path + "plots_halo_008508/nref11n/nref11n_nref10f_refine200kpc/spectra/"
        haloname = "halo008508_nref11n_nref10f"
    elif args.run == "nref11f":
        ds_loc =  ds_base + "halo_008508/nref11n/nref11f_refine200kpc/" + args.output + "/" + args.output
        track_name = ds_base + "halo_008508/nref11n/nref11f_refine200kpc/halo_track"
        output_dir = output_path + "plots_halo_008508/nref11n/nref11f_refine200kpc/spectra/"
        haloname = "halo008508_nref11f"

    ds = yt.load(ds_loc)

    print("opening track: " + track_name)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')
    zsnap = ds.get_parameter('CosmologyCurrentRedshift')
    refine_box, refine_box_center, x_width = get_refine_box(ds, zsnap, track)
    halo_center = get_halo_center(ds, refine_box_center)[0]

    generate_random_rays(ds, halo_center, haloname=haloname, track=track, \
                         output_dir=output_dir, Nrays=args.Nrays)

    # generate_random_rays(ds, halo_center, line_list=["H I 1216"], haloname="halo008508", Nrays=100)
    sys.exit("~~~*~*~*~*~*~all done!!!! spectra are fun!")
Example #20
0
def make_movie():
    # load the simulation
    ds = yt.load(
        "/Users/molly/foggie/halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/RD0020/RD0020"
    )
    output_dir = "/Users/molly/Dropbox/foggie-collab/plots_halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/spectra/"
    # ds = yt.load("/Users/molly/foggie/halo_008508/natural/nref11/RD0020/RD0020")
    track_name = "/Users/molly/foggie/halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/halo_track"
    # output_dir = "/Users/molly/Dropbox/foggie-collab/plots_halo_008508/nref11n/natural/spectra/"
    os.chdir(output_dir)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')
    zsnap = ds.get_parameter('CosmologyCurrentRedshift')
    proper_box_size = get_proper_box_size(ds)
    refine_box, refine_box_center, x_width = get_refine_box(ds, zsnap, track)
    halo_center = get_halo_center(ds, refine_box_center)
    x_left = np.float(refine_box.left_edge[0].value)
    x_right = np.float(refine_box.right_edge[0].value)
    y_left = np.float(refine_box.left_edge[1].value)
    y_right = np.float(refine_box.right_edge[1].value)

    # slice will be repeated, so let's make it first
    z_center = [refine_box_center[0], refine_box_center[1], halo_center[2]]
    slc = yt.SlicePlot(ds,
                       'z', ('gas', 'H_p0_number_density'),
                       center=z_center,
                       width=1.5 * x_width)
    ## slc = ds.r[xmin:xmax, ymin:ymax, halo_center[2]]
    res = [1000, 1000]
    # frb = slc.frb(x_width, res)
    frb = slc.frb['gas', 'H_p0_number_density']
    # image = np.array(frb['gas', 'density'])
    image = np.array(frb)
    print "min, max H I density = ", np.min(np.log10(image)), np.max(
        np.log10(image))
    # extent = [float(x.in_units('code_length')) for x in (pro.xlim + pro.ylim)]
    extent = [x_left, x_right, y_left, y_right]

    # spectral features
    #g = Gaussian1DKernel((7/0.0267)/2.355)  # HIRES v_fwhm = 7 km/s
    #snr = 30.

    # get a spectrum!
    # impact = 25.
    # impacts = np.arange(25.,50.5,0.5)
    #impacts = np.arange(-50., -24.5, 0.5)
    impacts = [-50.]
    for impact in impacts:
        out_fits_name = "hlsp_misty_foggie_halo008508_"+ds.basename.lower()+"_i"+"{:05.1f}".format(impact) + \
                    "_dx"+"{:4.2f}".format(0.)+"_v2_los.fits"
        out_plot_name = "HI_slice_with_lots_spectra_halo008508_"+ds.basename.lower()+"_i"+"{:05.1f}".format(impact) + \
                    "_dx"+"{:4.2f}".format(0.)+".png"
        hdulist, ray_start, ray_end = extract_spectra(
            ds,
            impact,
            read_fits_file=False,
            out_fits_name=out_fits_name,
            xmin=x_left,
            xmax=x_right,
            halo_center=halo_center,
            refine_box_center=refine_box_center)
        print "(impact/proper_box_size)/x_width = ", (
            impact / proper_box_size) / x_width

        print "ray start:", ray_start
        print "ray end:", ray_end
        print "refine box center:", refine_box_center
        print "halo center:", halo_center
        print "z_center:", z_center

        # start by setting up plots
        fig = plt.figure(figsize=(16, 6), dpi=100)

        # creates grid on which the figure will be plotted
        gs = gridspec.GridSpec(6, 3, width_ratios=[0.05, 1, 1])

        ## this will be the slice
        ax_slice = fig.add_subplot(gs[:, 1])
        slc = ax_slice.imshow(np.log10(image), extent=extent, cmap=h1_color_map, \
                                        vmin=np.log10(h1_slc_min), vmax=np.log10(h1_slc_max))
        ax_slice.plot([ray_start[0], ray_end[0]], [ray_start[1], ray_end[1]],
                      color="white",
                      lw=2.)
        ax_slice.set_aspect('equal')
        ax_slice.xaxis.set_major_locator(ticker.NullLocator())
        ax_slice.yaxis.set_major_locator(ticker.NullLocator())
        # cbar = fig.colorbar(cax, ax=ax_cbar, orientation='vertical', pad=0.01, shrink=0.8)
        ax_cbar = fig.add_subplot(gs[:, 0])
        cbar = fig.colorbar(slc, cax=ax_cbar, extend='both')
        ax_cbar.yaxis.set_ticks_position('left')
        ax_cbar.yaxis.set_label_position('left')
        cbar.set_label(r'log HI density', fontsize=16.)

        ## these will be the spectra
        zmin, zmax = 1.998, 2.004
        vmin, vmax = -1000, 1000

        ax_spec1 = fig.add_subplot(gs[0, 2])
        velocity = ((hdulist["H I 1216"].data['wavelength'] /
                     hdulist['H I 1216'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["H I 1216"].data['flux']
        # v_conv = convolve(velocity, g)
        # ax_spec1.step(v_conv, flux, color="#4575b4",lw=2)
        ax_spec1.plot(velocity, flux, color='darkorange', lw=1)
        ax_spec1.text(vmin + 100, 0, "H I 1216", fontsize=12.)
        ax_spec1.xaxis.set_major_locator(ticker.NullLocator())
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        ax_spec2 = fig.add_subplot(gs[1, 2])
        velocity = ((hdulist["H I 973"].data['wavelength'] /
                     hdulist['H I 973'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["H I 973"].data['flux']
        # v_conv = convolve(velocity, g)
        # ax_spec2.step(v_conv, flux, color="#4575b4",lw=2)
        ax_spec2.plot(velocity, flux, color='darkorange', lw=1)
        ax_spec2.text(vmin + 100, 0, "Ly c", fontsize=12.)
        ax_spec2.xaxis.set_major_locator(ticker.NullLocator())
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        ax_spec3 = fig.add_subplot(gs[2, 2])
        velocity = ((hdulist["H I 919"].data['wavelength'] /
                     hdulist['H I 919'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["H I 973"].data['flux']
        # v_conv = convolve(velocity, g)
        # ax_spec3.step(v_conv, flux, color="#4575b4",lw=2)
        ax_spec3.plot(velocity,
                      hdulist["H I 919"].data['flux'],
                      color='darkorange',
                      lw=1)
        ax_spec3.text(vmin + 100, 0, "Ly 10", fontsize=12.)
        ax_spec3.xaxis.set_major_locator(ticker.NullLocator())
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        ax_spec4 = fig.add_subplot(gs[3, 2])
        velocity = ((hdulist["Si III 1207"].data['wavelength'] /
                     hdulist['Si III 1207'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["Si III 1207"].data['flux']
        ax_spec4.plot(velocity, flux, color='darkorange', lw=1)
        ax_spec4.text(vmin + 100, 0, "Si III 1207", fontsize=12.)
        ax_spec4.xaxis.set_major_locator(ticker.NullLocator())
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        ax_spec5 = fig.add_subplot(gs[4, 2])
        velocity = ((hdulist["C IV 1548"].data['wavelength'] /
                     hdulist['C IV 1548'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["C IV 1548"].data['flux']
        ax_spec5.plot(velocity, flux, color='darkorange', lw=1)
        ax_spec5.text(vmin + 100, 0, "C IV 1548", fontsize=12.)
        ax_spec5.xaxis.set_major_locator(ticker.NullLocator())
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        ax_spec6 = fig.add_subplot(gs[5, 2])
        velocity = ((hdulist["O VI 1032"].data['wavelength'] /
                     hdulist['O VI 1032'].header['restwave']) - 1 -
                    ds.current_redshift) * 299792.458 - 250
        flux = hdulist["O VI 1032"].data['flux']
        ax_spec6.plot(velocity, flux, color='darkorange', lw=1)
        ax_spec6.text(vmin + 100, 0, "O VI 1032", fontsize=12.)
        plt.xlim(vmin, vmax)
        plt.ylim(-0.05, 1.05)

        fig.tight_layout()
        plt.savefig(out_plot_name)
        plt.close()
Example #21
0
def calc_ang_mom_and_fluxes(halo, foggie_dir, output_dir, run, **kwargs):
    outs = kwargs.get("outs", "all")
    trackname = kwargs.get("trackname", "halo_track")

    ### set up the table of all the stuff we want
    data = Table(names=('redshift', 'radius', 'nref_mode', \
                        'net_mass_flux', 'net_metal_flux', \
                        'mass_flux_in', 'mass_flux_out', \
                        'metal_flux_in', 'metal_flux_out', \
                        'net_kinetic_energy_flux','net_thermal_energy_flux','net_entropy_flux',\
                        'kinetic_energy_flux_in','kinetic_energy_flux_out',\
                        'thermal_energy_flux_in','thermal_energy_flux_out',\
                        'entropy_flux_in','entropy_flux_out',\
                        'net_cold_mass_flux', 'cold_mass_flux_in', 'cold_mass_flux_out', \
                        'net_cool_mass_flux', 'cool_mass_flux_in', 'cool_mass_flux_out', \
                        'net_warm_mass_flux', 'warm_mass_flux_in', 'warm_mass_flux_out', \
                        'net_hot_mass_flux', 'hot_mass_flux_in', 'hot_mass_flux_out', \
                        'annular_ang_mom_gas_x', 'annular_ang_mom_gas_y','annular_ang_mom_gas_z', \
                        'annular_spec_ang_mom_gas_x', 'annular_spec_ang_mom_gas_y','annular_spec_ang_mom_gas_z',\
                        'annular_ang_mom_dm_x', 'annular_ang_mom_dm_y','annular_ang_mom_dm_z', \
                        'annular_spec_ang_mom_dm_x', 'annular_spec_ang_mom_dm_y', 'annular_spec_ang_mom_dm_z', \
                        'outside_ang_mom_gas_x', 'outside_ang_mom_gas_y', 'outside_ang_mom_gas_z',  \
                        'outside_spec_ang_mom_gas_x', 'outside_spec_ang_mom_gas_y', 'outside_spec_ang_mom_gas_z', \
                        'outside_ang_mom_dm_x', 'outside_ang_mom_dm_y','outside_ang_mom_dm_z',\
                        'outside_spec_ang_mom_dm_x', 'outside_spec_ang_mom_dm_y', 'outside_spec_ang_mom_dm_z', \
                        'inside_ang_mom_stars_x', 'inside_ang_mom_stars_y', 'inside_ang_mom_stars_z', \
                        'inside_spec_ang_mom_stars_x', 'inside_spec_ang_mom_stars_y', 'inside_spec_ang_mom_stars_z'),
                  dtype=('f8', 'f8', 'i8','f8', 'f8', 'f8',
                         'f8', 'f8', 'f8','f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8'
                        ))
    data2 = Table(names=('redshift', 'radius',
                        'net_mass_flux', 'net_metal_flux', \
                        'mass_flux_in', 'mass_flux_out', \
                        'metal_flux_in', 'metal_flux_out', \
                        'net_cold_mass_flux', 'cold_mass_flux_in', 'cold_mass_flux_out', \
                        'net_cool_mass_flux', 'cool_mass_flux_in', 'cool_mass_flux_out', \
                        'net_warm_mass_flux', 'warm_mass_flux_in', 'warm_mass_flux_out', \
                        'net_hot_mass_flux', 'hot_mass_flux_in', 'hot_mass_flux_out', \
                        'annular_ang_mom_gas_x', 'annular_ang_mom_gas_y','annular_ang_mom_gas_z', \
                        'annular_spec_ang_mom_gas_x', 'annular_spec_ang_mom_gas_y','annular_spec_ang_mom_gas_z',\
                        'outside_ang_mom_gas_x', 'outside_ang_mom_gas_y', 'outside_ang_mom_gas_z',  \
                        'outside_spec_ang_mom_gas_x', 'outside_spec_ang_mom_gas_y', 'outside_spec_ang_mom_gas_z'), \
                    dtype=('f8', 'f8', 'f8','f8', 'f8', 'f8',
                         'f8', 'f8', 'f8','f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8', 'f8', 'f8', 'f8', 'f8',
                         'f8', 'f8'))

    print(foggie_dir)
    track_name = foggie_dir + 'halo_00' + str(halo) + '/' + run + trackname
    if args.system == "pleiades":
        track_name = foggie_dir + "halo_008508/nref11f_refine200kpc_z4to2/halo_track"

    print("opening track: " + track_name)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')

    ## default is do allll the snaps in the directory
    ## want to add flag for if just one
    run_dir = foggie_dir + 'halo_00' + str(halo) + '/' + run
    if halo == "8508":
        prefix = output_dir + 'plots_halo_008508/' + run + '/'
    else:
        prefix = output_dir + 'other_halo_plots/' + str(halo) + '/' + run + '/'
    if not (os.path.exists(prefix)):
        os.system("mkdir " + prefix)

    if outs == "all":
        print("looking for outputs in ", run_dir)
        outs = glob.glob(os.path.join(run_dir, '?D????/?D????'))
    else:
        print("outs = ", outs)
        new_outs = [glob.glob(os.path.join(run_dir, snap)) for snap in outs]
        print("new_outs = ", new_outs)
        new_new_outs = [snap[0] for snap in new_outs]
        outs = new_new_outs

    #print("outs:")
    #print (outs)
    #dataset_series = yt.load(outs)
    storage = {}
    #for sto,ds in dataset_series.piter(storage=storage):
    for sto, snap in yt.parallel_objects(outs, 2, storage=storage):
        # load the snapshot
        #print('opening snapshot '+ snap)
        ds = yt.load(snap)

        # add the particle filters
        ds.add_particle_filter('stars')
        ds.add_particle_filter('dm')

        # create all the regions
        zsnap = ds.get_parameter('CosmologyCurrentRedshift')
        #proper_box_size = get_proper_box_size(ds)
        # another option than the function:
        proper_box_size = ds.quan(1., 'code_length').to('kpc')

        refine_box, refine_box_center, refine_width_code = get_refine_box(
            ds, zsnap, track)
        refine_width = refine_width_code * proper_box_size

        # center is trying to be the center of the halo
        halo_center, halo_velocity = get_halo_center(ds, refine_box_center)

        ### OK, now want to set up some spheres of some sizes and get the stuff
        radii = refine_width * 0.5 * np.arange(0.9, 0.1,
                                               -0.01)  # 0.5 because radius
        small_sphere = ds.sphere(halo_center,
                                 0.05 * refine_width_code)  # R=10ckpc/h
        big_sphere = ds.sphere(halo_center, 0.45 * refine_width_code)

        # we want to subtract the bulk velocity from the radial velocities
        bulk_velocity = big_sphere.quantities["BulkVelocity"]()

        # find number of cells for the FRB
        # by default, it uses nref10 as the cell size for the frb
        # then create the 3D FRB for calculating the fluxes
        cell_size = np.unique(big_sphere['dx'].in_units('kpc'))[1]
        box_width = ds.quan(0.9 * refine_width, 'kpc')
        nbins = int(np.ceil(box_width / cell_size).value)

        halo_center = ds.arr(halo_center, 'code_length')
        xL, xR = halo_center[0] - box_width / 2., halo_center[
            0] + box_width / 2.
        yL, yR = halo_center[1] - box_width / 2., halo_center[
            1] + box_width / 2.
        zL, zR = halo_center[2] - box_width / 2., halo_center[
            2] + box_width / 2.
        jnbins = complex(0, nbins)
        box = ds.r[xL:xR:jnbins, yL:yR:jnbins, zL:zR:jnbins]
        box.set_field_parameter("center", halo_center)
        box.set_field_parameter("bulk_velocity", bulk_velocity)

        ### OK, now want to call the fields that we'll need for the fluxes
        ### otherwise, the code crashes when trying to select subsets of the data
        ## GAS FIELDS
        temperature = box['Temperature'].flatten()
        cell_mass = box['cell_mass'].to("Msun").flatten()
        metal_mass = box[('gas', 'metal_mass')].to("Msun").flatten()
        radius = box['radius'].to("kpc").flatten()
        radial_velocity = box['radial_velocity'].to('kpc/yr').flatten()
        cell_volume = box['cell_volume'].flatten()
        #grid_levels = box['index', 'grid_level']
        gas_ang_mom_x = box[('gas', 'angular_momentum_x')].flatten()
        gas_ang_mom_y = box[('gas', 'angular_momentum_y')].flatten()
        gas_ang_mom_z = box[('gas', 'angular_momentum_z')].flatten()
        gas_spec_ang_mom_x = box[('gas',
                                  'specific_angular_momentum_x')].flatten()
        gas_spec_ang_mom_y = box[('gas',
                                  'specific_angular_momentum_y')].flatten()
        gas_spec_ang_mom_z = box[('gas',
                                  'specific_angular_momentum_z')].flatten()
        kinetic_energy = box['gas', 'kinetic_energy'].flatten()
        kinetic_energy = (kinetic_energy * cell_volume / cell_mass).to('erg/g')
        thermal_energy = box['gas', 'thermal_energy'].flatten()
        entropy = box['entropy'].flatten()
        hden = box['H_nuclei_density'].flatten()

        ## STAR PARTICLE FIELDS
        star_ang_mom_x = big_sphere['stars',
                                    'particle_angular_momentum_x'].flatten()
        star_ang_mom_y = big_sphere['stars',
                                    'particle_angular_momentum_y'].flatten()
        star_ang_mom_z = big_sphere['stars',
                                    'particle_angular_momentum_z'].flatten()
        star_spec_ang_mom_x = big_sphere[
            'stars', 'particle_specific_angular_momentum_x'].flatten()
        star_spec_ang_mom_y = big_sphere[
            'stars', 'particle_specific_angular_momentum_y'].flatten()
        star_spec_ang_mom_z = big_sphere[
            'stars', 'particle_specific_angular_momentum_z'].flatten()
        star_distance = np.sqrt(
            (big_sphere['stars', 'particle_position_x'] - halo_center[0])**2. +
            (big_sphere['stars', 'particle_position_y'] - halo_center[1])**2. +
            (big_sphere['stars', 'particle_position_z'] -
             halo_center[2])**2.).to("kpc")

        ## DM PARTICLE FIELDS
        dm_ang_mom_x = big_sphere['dm',
                                  'particle_angular_momentum_x'].flatten()
        dm_ang_mom_y = big_sphere['dm',
                                  'particle_angular_momentum_y'].flatten()
        dm_ang_mom_z = big_sphere['dm',
                                  'particle_angular_momentum_z'].flatten()
        dm_spec_ang_mom_x = big_sphere[
            'dm', 'particle_specific_angular_momentum_x'].flatten()
        dm_spec_ang_mom_y = big_sphere[
            'dm', 'particle_specific_angular_momentum_y'].flatten()
        dm_spec_ang_mom_z = big_sphere[
            'dm', 'particle_specific_angular_momentum_z'].flatten()
        dm_distance = np.sqrt(
            (big_sphere['dm', 'particle_position_x'] - halo_center[0])**2. +
            (big_sphere['dm', 'particle_position_y'] - halo_center[1])**2. +
            (big_sphere['dm', 'particle_position_z'] -
             halo_center[2])**2.).to("kpc")

        table1 = np.zeros((len(radii), len(data.keys())))
        table2 = np.zeros((len(radii), len(data2.keys())))
        for rad in parallel_objects(radii):
            print(rad)
            if rad != np.max(radii):
                idI = np.where(radii == rad)[0]
                if rad == radii[-1]:
                    minrad, maxrad = ds.quan(0., 'kpc'), rad
                else:
                    maxrad, minrad = rad, radii[idI[0] + 1]

                # some radius / geometry things
                dr = maxrad - minrad
                rad_here = (minrad + maxrad) / 2.

                # find the indices that I'm going to need
                idR = np.where((radius >= minrad) & (radius < maxrad))[0]
                idCd = np.where((radius >= minrad) & (radius < maxrad)
                                & (temperature <= 1e4))[0]
                idCl = np.where((radius >= minrad) & (radius < maxrad)
                                & (temperature > 1e4)
                                & (temperature <= 1e5))[0]
                idW = np.where((radius >= minrad) & (radius < maxrad)
                               & (temperature > 1e5) & (temperature <= 1e6))[0]
                idH = np.where((radius >= minrad) & (radius < maxrad)
                               & (temperature >= 1e6))
                idRdm = np.where((dm_distance >= minrad)
                                 & (dm_distance < maxrad))[0]
                big_annulusGAS = np.where(radius >= rad_here)[0]
                big_annulusDM = np.where(dm_distance >= rad_here)[0]
                inside = np.where(star_distance < rad_here)[0]

                # most common refinement level
                #nref_mode = stats.mode(grid_levels[idR])
                nref_mode = 10.  ## FIX FOR NOW!
                # mass fluxes
                gas_flux = (np.sum(cell_mass[idR] * radial_velocity[idR]) /
                            dr).to("Msun/yr")
                metal_flux = (np.sum(metal_mass[idR] * radial_velocity[idR]) /
                              dr).to("Msun/yr")
                kinetic_energy_flux = (
                    np.sum(kinetic_energy[idR] * radial_velocity[idR]) /
                    dr).to("erg/(g*yr)")
                thermal_energy_flux = (
                    np.sum(thermal_energy[idR] * radial_velocity[idR]) /
                    dr).to("erg/(g*yr)")
                entropy_flux = (np.sum(entropy[idR] * radial_velocity[idR]) /
                                dr)

                ## also filter based off radial velocity
                idVin = np.where(radial_velocity[idR] <= 0.)[0]
                idVout = np.where(radial_velocity[idR] > 0.)[0]
                gas_flux_in = (np.sum(
                    cell_mass[idR][idVin] * radial_velocity[idR][idVin]) /
                               dr).to("Msun/yr")
                gas_flux_out = (np.sum(
                    cell_mass[idR][idVout] * radial_velocity[idR][idVout]) /
                                dr).to("Msun/yr")
                metal_flux_in = (np.sum(
                    metal_mass[idR][idVin] * radial_velocity[idR][idVin]) /
                                 dr).to("Msun/yr")
                metal_flux_out = (np.sum(
                    metal_mass[idR][idVout] * radial_velocity[idR][idVout]) /
                                  dr).to("Msun/yr")
                kinetic_energy_flux_in = (np.sum(
                    kinetic_energy[idR][idVin] * radial_velocity[idR][idVin]) /
                                          dr).to("erg/(g*yr)")
                kinetic_energy_flux_out = (
                    np.sum(kinetic_energy[idR][idVout] *
                           radial_velocity[idR][idVout]) / dr).to("erg/(g*yr)")
                thermal_energy_flux_in = (np.sum(
                    thermal_energy[idR][idVin] * radial_velocity[idR][idVin]) /
                                          dr).to("erg/(g*yr)")
                thermal_energy_flux_out = (
                    np.sum(thermal_energy[idR][idVout] *
                           radial_velocity[idR][idVout]) / dr).to("erg/(g*yr)")
                entropy_flux_in = (
                    np.sum(entropy[idR][idVin] * radial_velocity[idR][idVin]) /
                    dr)
                entropy_flux_out = (np.sum(
                    entropy[idR][idVout] * radial_velocity[idR][idVout]) / dr)

                ## and filter on temperature! and velocity! woo!
                idVin = np.where(radial_velocity[idH] <= 0.)[0]
                idVout = np.where(radial_velocity[idH] > 0.)[0]
                hot_gas_flux = (np.sum(cell_mass[idH] * radial_velocity[idH]) /
                                dr).to("Msun/yr")
                hot_gas_flux_in = (np.sum(
                    cell_mass[idH][idVin] * radial_velocity[idH][idVin]) /
                                   dr).to("Msun/yr")
                hot_gas_flux_out = (np.sum(
                    cell_mass[idH][idVout] * radial_velocity[idH][idVout]) /
                                    dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idW] <= 0.)[0]
                idVout = np.where(radial_velocity[idW] > 0.)[0]
                warm_gas_flux = (
                    np.sum(cell_mass[idW] * radial_velocity[idW]) /
                    dr).to("Msun/yr")
                warm_gas_flux_in = (np.sum(
                    cell_mass[idW][idVin] * radial_velocity[idW][idVin]) /
                                    dr).to("Msun/yr")
                warm_gas_flux_out = (np.sum(
                    cell_mass[idW][idVout] * radial_velocity[idW][idVout]) /
                                     dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idCl] <= 0.)[0]
                idVout = np.where(radial_velocity[idCl] > 0.)[0]
                cool_gas_flux = (
                    np.sum(cell_mass[idCl] * radial_velocity[idCl]) /
                    dr).to("Msun/yr")
                cool_gas_flux_in = (np.sum(
                    cell_mass[idCl][idVin] * radial_velocity[idCl][idVin]) /
                                    dr).to("Msun/yr")
                cool_gas_flux_out = (np.sum(
                    cell_mass[idCl][idVout] * radial_velocity[idCl][idVout]) /
                                     dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idCd] <= 0.)[0]
                idVout = np.where(radial_velocity[idCd] > 0.)[0]
                cold_gas_flux = (
                    np.sum(cell_mass[idCd] * radial_velocity[idCd]) /
                    dr).to("Msun/yr")
                cold_gas_flux_in = (np.sum(
                    cell_mass[idCd][idVin] * radial_velocity[idCd][idVin]) /
                                    dr).to("Msun/yr")
                cold_gas_flux_out = (np.sum(
                    cell_mass[idCd][idVout] * radial_velocity[idCd][idVout]) /
                                     dr).to("Msun/yr")

                ## GAS angular momentum!
                annular_ang_mom_gas_x = np.sum(gas_ang_mom_x[idR])
                annular_ang_mom_gas_y = np.sum(gas_ang_mom_y[idR])
                annular_ang_mom_gas_z = np.sum(gas_ang_mom_z[idR])
                annular_spec_ang_mom_gas_x = np.mean(gas_spec_ang_mom_x[idR])
                annular_spec_ang_mom_gas_y = np.mean(gas_spec_ang_mom_y[idR])
                annular_spec_ang_mom_gas_z = np.mean(gas_spec_ang_mom_z[idR])

                outside_ang_mom_gas_x = np.sum(gas_ang_mom_x[big_annulusGAS])
                outside_ang_mom_gas_y = np.sum(gas_ang_mom_y[big_annulusGAS])
                outside_ang_mom_gas_z = np.sum(gas_ang_mom_z[big_annulusGAS])
                outside_spec_ang_mom_gas_x = np.mean(
                    gas_spec_ang_mom_x[big_annulusGAS])
                outside_spec_ang_mom_gas_y = np.mean(
                    gas_spec_ang_mom_y[big_annulusGAS])
                outside_spec_ang_mom_gas_z = np.mean(
                    gas_spec_ang_mom_z[big_annulusGAS])

                ## PARTICLE angular momentum calculations
                inside_ang_mom_stars_x = np.sum(star_ang_mom_x[inside])
                inside_ang_mom_stars_y = np.sum(star_ang_mom_y[inside])
                inside_ang_mom_stars_z = np.sum(star_ang_mom_z[inside])
                inside_spec_ang_mom_stars_x = np.sum(
                    star_spec_ang_mom_x[inside])
                inside_spec_ang_mom_stars_y = np.sum(
                    star_spec_ang_mom_y[inside])
                inside_spec_ang_mom_stars_z = np.sum(
                    star_spec_ang_mom_z[inside])

                annular_ang_mom_dm_x = np.sum(dm_ang_mom_x[idRdm])
                annular_ang_mom_dm_y = np.sum(dm_ang_mom_y[idRdm])
                annular_ang_mom_dm_z = np.sum(dm_ang_mom_z[idRdm])
                annular_spec_ang_mom_dm_x = np.mean(dm_spec_ang_mom_x[idRdm])
                annular_spec_ang_mom_dm_y = np.mean(dm_spec_ang_mom_y[idRdm])
                annular_spec_ang_mom_dm_z = np.mean(dm_spec_ang_mom_z[idRdm])

                outside_ang_mom_dm_x = np.sum(dm_ang_mom_x[big_annulusDM])
                outside_ang_mom_dm_y = np.sum(dm_ang_mom_y[big_annulusDM])
                outside_ang_mom_dm_z = np.sum(dm_ang_mom_z[big_annulusDM])
                outside_spec_ang_mom_dm_x = np.mean(
                    dm_spec_ang_mom_x[big_annulusDM])
                outside_spec_ang_mom_dm_y = np.mean(
                    dm_spec_ang_mom_y[big_annulusDM])
                outside_spec_ang_mom_dm_z = np.mean(
                    dm_spec_ang_mom_z[big_annulusDM])

                table1[idI,:] = [ds.current_redshift, rad, nref_mode, gas_flux, metal_flux, \
                                gas_flux_in, gas_flux_out, metal_flux_in, metal_flux_out, \
                                kinetic_energy_flux, thermal_energy_flux, entropy_flux,\
                                kinetic_energy_flux_in,kinetic_energy_flux_out,\
                                thermal_energy_flux_in,thermal_energy_flux_out,\
                                entropy_flux_in,entropy_flux_out,\
                                cold_gas_flux, cold_gas_flux_in, cold_gas_flux_out, \
                                cool_gas_flux, cool_gas_flux_in, cool_gas_flux_out, \
                                warm_gas_flux, warm_gas_flux_in, warm_gas_flux_out, \
                                hot_gas_flux, hot_gas_flux_in, hot_gas_flux_out,
                                annular_ang_mom_gas_x, annular_ang_mom_gas_y,annular_ang_mom_gas_z, \
                                annular_spec_ang_mom_gas_x, annular_spec_ang_mom_gas_y,annular_spec_ang_mom_gas_z,\
                                annular_ang_mom_dm_x, annular_ang_mom_dm_y,annular_ang_mom_dm_z, \
                                annular_spec_ang_mom_dm_x, annular_spec_ang_mom_dm_y, annular_spec_ang_mom_dm_z, \
                                outside_ang_mom_gas_x, outside_ang_mom_gas_y, outside_ang_mom_gas_z,  \
                                outside_spec_ang_mom_gas_x, outside_spec_ang_mom_gas_y, outside_spec_ang_mom_gas_z, \
                                outside_ang_mom_dm_x, outside_ang_mom_dm_y,outside_ang_mom_dm_z,\
                                outside_spec_ang_mom_dm_x, outside_spec_ang_mom_dm_y, outside_spec_ang_mom_dm_z, \
                                inside_ang_mom_stars_x, inside_ang_mom_stars_y, inside_ang_mom_stars_z, \
                                inside_spec_ang_mom_stars_x, inside_spec_ang_mom_stars_y, inside_spec_ang_mom_stars_z]

                ####### REPEATING THE CALCUATION WITHOUT THE DENSEST ISM-LIKE GAS #########
                idR = np.where((radius >= minrad) & (radius < maxrad)
                               & (hden < 0.1))[0]
                idCd = np.where((radius >= minrad) & (radius < maxrad)
                                & (temperature <= 1e4) & (hden < 0.1))[0]
                idCl = np.where((radius >= minrad) & (radius < maxrad)
                                & (temperature > 1e4) & (temperature <= 1e5)
                                & (hden < 0.1))[0]
                idW = np.where((radius >= minrad) & (radius < maxrad)
                               & (temperature > 1e5) & (temperature <= 1e6)
                               & (hden < 0.1))[0]
                idH = np.where((radius >= minrad) & (radius < maxrad)
                               & (temperature >= 1e6) & (hden < 0.1))
                big_annulusGAS = np.where((radius >= rad_here)
                                          & (hden < 0.1))[0]

                # mass fluxes
                gas_flux = (np.sum(cell_mass[idR] * radial_velocity[idR]) /
                            dr).to("Msun/yr")
                metal_flux = (np.sum(metal_mass[idR] * radial_velocity[idR]) /
                              dr).to("Msun/yr")

                ## also filter based off radial velocity
                idVin = np.where(radial_velocity[idR] <= 0.)[0]
                idVout = np.where(radial_velocity[idR] > 0.)[0]
                gas_flux_in = (np.sum(
                    cell_mass[idR][idVin] * radial_velocity[idR][idVin]) /
                               dr).to("Msun/yr")
                gas_flux_out = (np.sum(
                    cell_mass[idR][idVout] * radial_velocity[idR][idVout]) /
                                dr).to("Msun/yr")
                metal_flux_in = (np.sum(
                    metal_mass[idR][idVin] * radial_velocity[idR][idVin]) /
                                 dr).to("Msun/yr")
                metal_flux_out = (np.sum(
                    metal_mass[idR][idVout] * radial_velocity[idR][idVout]) /
                                  dr).to("Msun/yr")

                ## and filter on temperature! and velocity! woo!
                idVin = np.where(radial_velocity[idH] <= 0.)[0]
                idVout = np.where(radial_velocity[idH] > 0.)[0]
                hot_gas_flux = (np.sum(cell_mass[idH] * radial_velocity[idH]) /
                                dr).to("Msun/yr")
                hot_gas_flux_in = (np.sum(
                    cell_mass[idH][idVin] * radial_velocity[idH][idVin]) /
                                   dr).to("Msun/yr")
                hot_gas_flux_out = (np.sum(
                    cell_mass[idH][idVout] * radial_velocity[idH][idVout]) /
                                    dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idW] <= 0.)[0]
                idVout = np.where(radial_velocity[idW] > 0.)[0]
                warm_gas_flux = (
                    np.sum(cell_mass[idW] * radial_velocity[idW]) /
                    dr).to("Msun/yr")
                warm_gas_flux_in = (np.sum(
                    cell_mass[idW][idVin] * radial_velocity[idW][idVin]) /
                                    dr).to("Msun/yr")
                warm_gas_flux_out = (np.sum(
                    cell_mass[idW][idVout] * radial_velocity[idW][idVout]) /
                                     dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idCl] <= 0.)[0]
                idVout = np.where(radial_velocity[idCl] > 0.)[0]
                cool_gas_flux = (
                    np.sum(cell_mass[idCl] * radial_velocity[idCl]) /
                    dr).to("Msun/yr")
                cool_gas_flux_in = (np.sum(
                    cell_mass[idCl][idVin] * radial_velocity[idCl][idVin]) /
                                    dr).to("Msun/yr")
                cool_gas_flux_out = (np.sum(
                    cell_mass[idCl][idVout] * radial_velocity[idCl][idVout]) /
                                     dr).to("Msun/yr")

                idVin = np.where(radial_velocity[idCd] <= 0.)[0]
                idVout = np.where(radial_velocity[idCd] > 0.)[0]
                cold_gas_flux = (
                    np.sum(cell_mass[idCd] * radial_velocity[idCd]) /
                    dr).to("Msun/yr")
                cold_gas_flux_in = (np.sum(
                    cell_mass[idCd][idVin] * radial_velocity[idCd][idVin]) /
                                    dr).to("Msun/yr")
                cold_gas_flux_out = (np.sum(
                    cell_mass[idCd][idVout] * radial_velocity[idCd][idVout]) /
                                     dr).to("Msun/yr")

                ## GAS angular momentum!
                annular_ang_mom_gas_x = np.sum(gas_ang_mom_x[idR])
                annular_ang_mom_gas_y = np.sum(gas_ang_mom_y[idR])
                annular_ang_mom_gas_z = np.sum(gas_ang_mom_z[idR])
                annular_spec_ang_mom_gas_x = np.mean(gas_spec_ang_mom_x[idR])
                annular_spec_ang_mom_gas_y = np.mean(gas_spec_ang_mom_y[idR])
                annular_spec_ang_mom_gas_z = np.mean(gas_spec_ang_mom_z[idR])

                outside_ang_mom_gas_x = np.sum(gas_ang_mom_x[big_annulusGAS])
                outside_ang_mom_gas_y = np.sum(gas_ang_mom_y[big_annulusGAS])
                outside_ang_mom_gas_z = np.sum(gas_ang_mom_z[big_annulusGAS])
                outside_spec_ang_mom_gas_x = np.mean(
                    gas_spec_ang_mom_x[big_annulusGAS])
                outside_spec_ang_mom_gas_y = np.mean(
                    gas_spec_ang_mom_y[big_annulusGAS])
                outside_spec_ang_mom_gas_z = np.mean(
                    gas_spec_ang_mom_z[big_annulusGAS])

                table2[idI,:] = [zsnap, rad,gas_flux, metal_flux, \
                                gas_flux_in, gas_flux_out, metal_flux_in, metal_flux_out, \
                                cold_gas_flux, cold_gas_flux_in, cold_gas_flux_out, \
                                cool_gas_flux, cool_gas_flux_in, cool_gas_flux_out, \
                                warm_gas_flux, warm_gas_flux_in, warm_gas_flux_out, \
                                hot_gas_flux, hot_gas_flux_in, hot_gas_flux_out,
                                annular_ang_mom_gas_x, annular_ang_mom_gas_y,annular_ang_mom_gas_z, \
                                annular_spec_ang_mom_gas_x, annular_spec_ang_mom_gas_y,annular_spec_ang_mom_gas_z,\
                                outside_ang_mom_gas_x, outside_ang_mom_gas_y, outside_ang_mom_gas_z,  \
                                outside_spec_ang_mom_gas_x, outside_spec_ang_mom_gas_y, outside_spec_ang_mom_gas_z]

        print("#################")
        print("combining threads")
        print("#################")
        comm = communication_system.communicators[-1]
        for i in range(table1.shape[0]):
            table1[i, :] = comm.mpi_allreduce(table1[i, :], op="sum")

        for i in range(table2.shape[0]):
            table2[i, :] = comm.mpi_allreduce(table2[i, :], op="sum")

        sto.result = (table1, table2)
        sto.result_id = str(ds)

    if yt.is_root():
        print("####################")
        print("In final table build")
        print("####################")
        for key in storage.keys():
            table1, table2 = storage[key]
            for i in range(table1.shape[0] - 1):
                data.add_row(table1[i + 1, :])
                data2.add_row(table2[i + 1, :])

        data = set_table_units(data)
        data2 = set_table_units(data2)
        tablename = run_dir + '/' + args.run + '_angular_momenta_and_fluxes.hdf5'
        data.write(tablename,
                   path='all_data',
                   serialize_meta=True,
                   overwrite=True)
        data2.write(tablename,
                    path='noISM_data',
                    serialize_meta=True,
                    overwrite=False,
                    append=True)

    return "whooooo angular momentum wheeeeeeee"
Example #22
0
def plot_script(halo, run, axis, **kwargs):
    outs = kwargs.get("outs", "all")
    trackname = kwargs.get("trackname", "halo_track")
    if axis == "all":
        axis = ['x','y','z']

    track_name = foggie_dir + 'halo_00' + str(halo) + '/' + run + '/' + trackname
    print("opening track: " + track_name)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')

    ## default is do allll the snaps in the directory
    ## want to add flag for if just one
    run_dir = foggie_dir + 'halo_00' + str(halo) + '/' + run
    if halo == "8508":
        prefix = output_dir + 'plots_halo_008508/' + run + '/'
    else:
        prefix = output_dir + 'other_halo_plots/' + str(halo) + '/' + run + '/'
    if not (os.path.exists(prefix)):
        os.system("mkdir " + prefix)

    if outs == "all":
        print("looking for outputs in ", run_dir)
        outs = glob.glob(os.path.join(run_dir, '?D0???/?D0???'))
    else:
        print("outs = ", outs)
        new_outs = [glob.glob(os.path.join(run_dir, snap)) for snap in outs]
        print("new_outs = ", new_outs)
        new_new_outs = [snap[0] for snap in new_outs]
        outs = new_new_outs

    print("making plots for ", axis, " axis in ", outs)

    for snap in outs:
        # load the snapshot
        print('opening snapshot '+ snap)
        ds = yt.load(snap)
        if args.all or args.ions:
            trident.add_ion_fields(ds, ions=['C IV', 'O VI', 'H I', 'Si II', 'C II', 'Si III', 'Si IV'])
        #if args.silicon:
        trident.add_ion_fields(ds, ions=['Si II', 'Si III', 'Si IV'])

        # box = ds.r[ center[0]-wide/143886:center[0]+wide/143886, center[1]-wide/143886.:center[1]+wide/143886., center[2]-wide/143886.:center[2]+wide/143886.]

        #### this was for the off-center box
        # center = [centerx, centery+20. / 143886., centerz]
        # box = ds.r[ center[0]-wide/143886:center[0]+wide/143886, center[1]-wide/143886.:center[1]+wide/143886., center[2]-wide/143886.:center[2]+wide/143886.]

        zsnap = ds.get_parameter('CosmologyCurrentRedshift')
        proper_box_size = get_proper_box_size(ds)

        refine_box, refine_box_center, refine_width = get_refine_box(ds, zsnap, track)
        refine_width = refine_width * proper_box_size

        # center is trying to be the center of the halo
        center = get_halo_center(ds, refine_box_center)
        width = refine_width + 10. ## add a little on the edges
        width_code = width / proper_box_size ## needs to be in code units
        box = ds.r[center[0] - 0.5*width_code : center[0] + 0.5*width_code, \
                  center[1] - 0.5*width_code : center[1] + 0.5*width_code, \
                  center[2] - 0.5*width_code : center[2] + 0.5*width_code]

        args_dict = {'ds' : ds,
                     'prefix' : prefix,
                     'field' : 'SiII',
                     'zmin' : si2_min,
                     'zmax' : si2_max,
                     'cmap' : si2_color_map,
                     'ision' : True,
                     'axis' : ['x','y','z'],
                     'center' : center,
                     'axis' : axis,
                     'box' : refine_box,
                     'width' : refine_width-10.,
                     'appendix' : '_refine'}
#        make_projection_plot_dict(args_dict)

        make_projection_plot(ds, prefix, "SiII",  \
                            si2_min, si2_max, si2_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=(refine_width-10.), appendix="_refine")

        ### trying yt parallel

        # if not args.noslices:
        #     if args.all or args.physical or args.density or args.slices:
        #         make_density_slice_plot(ds, prefix, axis=axis, center=center, box=refine_box, \
        #                            width=(refine_width-10.), appendix="_refine")
        #
        #     if args.all or args.physical or args.metals or args.slices:
        #         make_metal_slice_plot(ds, prefix, axis=axis, center=center, box=refine_box, \
        #                               width=(refine_width-10.), appendix="_refine")
        #
        #     if args.all or args.physical or args.slices:
        #         make_temperature_slice_plot(ds, prefix, axis=axis, center=center, box=refine_box, \
        #                               width=(refine_width-10.), appendix="_refine")
        #         make_entropy_slice_plot(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #         make_entropy_slice_plot(ds, prefix, axis=axis, center=refine_box_center, \
        #                               box=refine_box, width=refine_width, appendix="_refine")
        #
        #
        # if args.all or args.physical or args.density:
        #     print(width, refine_width, default_width)
        #     make_density_projection_plot(ds, prefix, axis=axis, center=center, box=box, \
        #                        width=width, appendix="_box")
        #     make_density_projection_plot(ds, prefix, axis=axis, center=refine_box_center, box=refine_box, \
        #                        width=refine_width, appendix="_refine")
        #
        # if args.all or args.physical:
        #     make_temperature_projection_plot(ds, prefix, axis=axis, center=refine_box_center,\
        #                      box=refine_box, width=refine_width, appendix="_refine")
        #     make_temperature_projection_plot(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #
        # if args.all or args.physical or args.metals:
        #     make_metal_projection_plot(ds, prefix, axis=axis, center=refine_box_center,\
        #                      box=refine_box, width=refine_width, appendix="_refine")
        #     make_metal_projection_plot(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #
        # if args.all or args.ions or args.hi:
        #     make_hi_plots(ds, prefix,  center=refine_box_center, \
        #                   box=refine_box, width=refine_width, appendix="_refine")
        #     make_hi_plots(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #
        # if args.all or args.ions or args.ovi:
        #     make_o6_plots(ds, prefix, axis=axis, center=refine_box_center, \
        #                   box=refine_box, width=refine_width, appendix="_refine")
        #     make_o6_plots(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #
        # if args.all or args.ions or args.civ:
        #     make_c4_plots(ds, prefix, axis=axis, center=refine_box_center, \
        #                   box=refine_box, width=refine_width, appendix="_refine")
        #     make_c4_plots(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #
        # if args.all or args.ions or args.silicon:
        #     make_si2_plots(ds, prefix, axis=axis, center=refine_box_center, box=refine_box, width=refine_width, appendix="_refine")
        #     make_si2_plots(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")
        #     make_si3_plots(ds, prefix, axis=axis, center=refine_box_center, box=refine_box, width=refine_width, appendix="_refine")
        #     make_si3_plots(ds, prefix, axis=axis, center=center, box=box, width=width, appendix="_box")

    return "yay plots! all done!"
Example #23
0
    '/astro/simulations/FOGGIE/halo_008508/nref11n_selfshield_z15/nref11n_nref10f_selfshield_z6/RD0018/RD0018'
)
dsc = yt.load(
    '/astro/simulations/FOGGIE/halo_008508/nref11n_selfshield_z15/nref11c_nref9f_selfshield_z6/RD0018/RD0018'
)

track_name = "/astro/simulations/FOGGIE/halo_008508/nref11n_selfshield_z15/nref11n_nref10f_selfshield_z6/halo_track"
#track_name = "/astro/simulations/FOGGIE/halo_008508/nref11n/nref11n_nref10f_refine200kpc/halo_track"
track = Table.read(track_name, format='ascii')
track.sort('col1')
width = 15.  #kpc

proper_box_size = get_proper_box_size(dsr)
refine_box, refine_box_center, refine_width = get_refine_box(
    dsr, dsr.current_redshift, track)
centerr, velocity = get_halo_center(dsr, refine_box_center)
refine_width = refine_width * proper_box_size
width_code = width / proper_box_size  ## needs to be in code units
boxr = dsr.r[centerr[0] - 0.5*width_code : centerr[0] + 0.5*width_code, \
           centerr[1] - 0.5*width_code : centerr[1] + 0.5*width_code, \
           centerr[2] - 0.5*width_code : centerr[2] + 0.5*width_code]

proper_box_size = get_proper_box_size(dsn)
refine_box_natural, refine_box_center, refine_width = get_refine_box(
    dsn, dsn.current_redshift, track)
centern, velocity = get_halo_center(dsn, refine_box_center)
width_code = width / proper_box_size  ## needs to be in code units
boxn = dsn.r[centern[0] - 0.5*width_code : centern[0] + 0.5*width_code, \
           centern[1] - 0.5*width_code : centern[1] + 0.5*width_code, \
           centern[2] - 0.5*width_code : centern[2] + 0.5*width_code]
Example #24
0
    foggie_dir, output_path, run_loc, trackname, haloname, spectra_dir = get_run_loc_etc(
        args)
    ds_loc = foggie_dir + run_loc + args.output + "/" + args.output

    if args.linelist == 'long':
        line_list = ['H I 1216', 'H I 1026', 'H I 973',
                       'H I 950', 'H I 919', 'Al II 1671', 'Al III 1855', \
                       'Si II 1260', 'Si III 1206', 'Si IV 1394', \
                       'C II 1335', 'C III 977', 'C IV 1548', \
                       'O VI 1032', 'Ne VIII 770']
    elif args.linelist == 'kodiaq':
        line_list = ['H I 1216', 'H I 919', \
                        'Si II 1260', 'Si IV 1394', 'C IV 1548', 'O VI 1032']
    else:  ## short --- these are what show_velphase has
        line_list = ['H I 1216', 'Si II 1260', 'O VI 1032']

    ds = yt.load(ds_loc)

    print("opening track: " + trackname)
    track = Table.read(trackname, format='ascii')
    track.sort('col1')
    zsnap = ds.get_parameter('CosmologyCurrentRedshift')
    refine_box, refine_box_center, x_width = get_refine_box(ds, zsnap, track)
    halo_center, halo_velocity = get_halo_center(ds, refine_box_center)
    halo_center = get_halo_center(ds, refine_box_center)[0]

    generate_random_rays(ds, halo_center, haloname=haloname, track=track, line_list=line_list, \
                         output_dir=spectra_dir, Nrays=args.Nrays, seed=args.seed, axis=args.axis)

    sys.exit("~~~*~*~*~*~*~all done!!!! spectra are fun!")
Example #25
0
def plot_script(halo, foggie_dir, output_dir, run, axis, **kwargs):
    outs = kwargs.get("outs", "all")
    trackname = kwargs.get("trackname", "halo_track")
    if axis == "all":
        axis = ['x', 'y', 'z']

    print(foggie_dir)
    track_name = foggie_dir + 'halo_00' + str(
        halo) + '/' + run + '/' + trackname
    print("opening track: " + track_name)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')

    ## default is do allll the snaps in the directory
    ## want to add flag for if just one
    run_dir = foggie_dir + 'halo_00' + str(halo) + '/' + run
    if halo == "8508":
        prefix = output_dir + 'plots_halo_008508/' + run + '/'
    else:
        prefix = output_dir + 'other_halo_plots/' + str(halo) + '/' + run + '/'
    if not (os.path.exists(prefix)):
        os.system("mkdir " + prefix)

    if outs == "all":
        print("looking for outputs in ", run_dir)
        outs = glob.glob(os.path.join(run_dir, '?D0???/?D0???'))
    else:
        print("outs = ", outs)
        new_outs = [glob.glob(os.path.join(run_dir, snap)) for snap in outs]
        print("new_outs = ", new_outs)
        new_new_outs = [snap[0] for snap in new_outs]
        outs = new_new_outs

    print("making plots for ", axis, " axis in ", outs)

    for snap in outs:
        # load the snapshot
        print('opening snapshot ' + snap)
        ds = yt.load(snap)
        if args.all or args.ions:
            trident.add_ion_fields(ds,
                                   ions=[
                                       'C IV', 'O VI', 'Mg II', 'Si II',
                                       'C II', 'Si III', 'Si IV', 'Ne VIII'
                                   ])
        if args.mgii or args.ions:
            trident.add_ion_fields(ds, ions=['Mg II'])
        if args.neviii or args.ions:
            trident.add_ion_fields(ds, ions=['Ne VIII'])
        if args.silicon:
            trident.add_ion_fields(ds, ions=['Si II', 'Si III', 'Si IV'])

        ## add metal density
        ds.add_field(("gas", "metal_density"),
                     function=_metal_density,
                     units="g/cm**2")

        # box = ds.r[ center[0]-wide/143886:center[0]+wide/143886, center[1]-wide/143886.:center[1]+wide/143886., center[2]-wide/143886.:center[2]+wide/143886.]

        #### this was for the off-center box
        # center = [centerx, centery+20. / 143886., centerz]
        # box = ds.r[ center[0]-wide/143886:center[0]+wide/143886, center[1]-wide/143886.:center[1]+wide/143886., center[2]-wide/143886.:center[2]+wide/143886.]

        zsnap = ds.get_parameter('CosmologyCurrentRedshift')
        proper_box_size = get_proper_box_size(ds)

        refine_box, refine_box_center, refine_width = get_refine_box(
            ds, zsnap, track)
        refine_width = refine_width * proper_box_size

        # center is trying to be the center of the halo
        center, velocity = get_halo_center(ds, refine_box_center)

        ## if want to add to the edges, need to loop over axes so unrefined
        ## region not in foreground / background
        width = default_width
        width_code = width / proper_box_size  ## needs to be in code units
        box = ds.r[center[0] - 0.5*width_code : center[0] + 0.5*width_code, \
                  center[1] - 0.5*width_code : center[1] + 0.5*width_code, \
                  center[2] - 0.5*width_code : center[2] + 0.5*width_code]

        if not args.noslices:
            if args.all or args.physical or args.density or args.slices:
                make_slice_plot(ds, prefix, "density", \
                                density_slc_min, density_slc_max, density_color_map, \
                                ision=False, axis=axis, center=center, box=refine_box, \
                                width=refine_width, appendix="_refine")

            if args.all or args.physical or args.metals or args.slices:
                make_slice_plot(ds, prefix, "metallicity", \
                                metal_min, metal_max, metal_color_map, \
                                ision=False, axis=axis, center=center, box=refine_box, \
                                width=refine_width, appendix="_refine")

            if args.all or args.physical or args.slices:
                make_slice_plot(ds, prefix, "temperature", \
                                temperature_min, temperature_max, temperature_color_map, \
                                ision=False, axis=axis, center=center, box=refine_box, \
                                width=refine_width, appendix="_refine")
                make_slice_plot(ds, prefix, "entropy", \
                                entropy_min, entropy_max, entropy_color_map, \
                                ision=False, axis=axis, center=center, box=refine_box, \
                                width=refine_width, appendix="_refine")

        if args.all or args.physical or args.density:
            print(width, refine_width, default_width)
            make_projection_plot(ds, prefix, "density",  \
                            density_proj_min, density_proj_max, density_color_map, \
                            ision=False, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "density",  \
                            density_proj_min, density_proj_max, density_color_map, \
                            ision=False, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.physical:
            make_projection_plot(ds, prefix, "temperature",  \
                            temperature_min, temperature_max, temperature_color_map, \
                            ision=False, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "temperature",  \
                            temperature_min, temperature_max, temperature_color_map, \
                            ision=False, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.physical or args.metals:
            make_projection_plot(ds, prefix, "metal_density",  \
                            metal_density_min, metal_density_max, metal_color_map, \
                            ision=False, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "metal_density",  \
                            metal_density_min, metal_density_max, metal_color_map, \
                            ision=False, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

            make_projection_plot(ds, prefix, "metallicity",  \
                            metal_min, metal_max, metal_color_map, \
                            ision=False, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "metallicity",  \
                            metal_min, metal_max, metal_color_map, \
                            ision=False, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")
        if args.hi:
            make_slice_plot(ds, prefix, "HI", \
                                h1_slc_min, h1_slc_max, h1_color_map,\
                                ision=True, axis=axis, center=center, box=refine_box, \
                                width=refine_width, appendix="_refine")

        if args.all or args.ions or args.hi:
            make_projection_plot(ds, prefix, "HI",  \
                            h1_proj_min, h1_proj_max, h1_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "HI",  \
                            h1_proj_min, h1_proj_max, h1_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.ions or args.ovi:
            make_projection_plot(ds, prefix, "OVI",  \
                            o6_min, o6_max, o6_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "OVI",  \
                            o6_min, o6_max, o6_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.ions or args.mgii:
            make_projection_plot(ds, prefix, "MgII",  \
                            mg2_min, mg2_max, mg2_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "MgII",  \
                            mg2_min, mg2_max, mg2_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.ions or args.civ:
            make_projection_plot(ds, prefix, "CIV",  \
                            c4_min, c4_max, c4_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "CIV",  \
                            c4_min, c4_max, c4_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.ions or args.silicon:
            make_projection_plot(ds, prefix, "SiIV",  \
                            si4_min, si4_max, si4_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "SiIV",  \
                            si4_min, si4_max, si4_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")
            make_projection_plot(ds, prefix, "SiIII",  \
                            si3_min, si3_max, si3_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "SiIII",  \
                            si3_min, si3_max, si3_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")
            make_projection_plot(ds, prefix, "SiII",  \
                            si2_min, si2_max, si2_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "SiII",  \
                            si2_min, si2_max, si2_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

        if args.all or args.ions or args.neviii:
            make_projection_plot(ds, prefix, "NeVIII",  \
                            ne8_min, ne8_max, ne8_color_map, \
                            ision=True, center=center, axis=axis, box=refine_box, \
                            width=refine_width, appendix="_refine")
            make_projection_plot(ds, prefix, "NeVIII",  \
                            ne8_min, ne8_max, ne8_color_map, \
                            ision=True, center=center, axis=axis, box=box, \
                            width=width, appendix="_box")

    return "yay plots! all done!"
Example #26
0
def make_movie():
    # load the simulation
    # ds = yt.load("/Users/molly/foggie/halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/RD0020/RD0020")
    #  track_name = "/Users/molly/foggie/halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/halo_track"
    # output_dir = "/Users/molly/Dropbox/foggie-collab/plots_halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/spectra/"
    ds = yt.load(
        "/Users/molly/foggie/halo_008508/nref11n/natural/RD0020/RD0020")
    track_name = "/Users/molly/foggie/halo_008508/nref11n/nref11n_nref10f_refine200kpc_z4to2/halo_track"
    output_dir = "/Users/molly/Dropbox/foggie-collab/plots_halo_008508/nref11n/natural/spectra"
    os.chdir(output_dir)
    track = Table.read(track_name, format='ascii')
    track.sort('col1')
    zsnap = ds.get_parameter('CosmologyCurrentRedshift')
    proper_box_size = get_proper_box_size(ds)
    refine_box, refine_box_center, x_width = get_refine_box(ds, zsnap, track)
    halo_center = get_halo_center(ds, refine_box_center)

    # interpolate the center from the track
    x_left = np.float(refine_box.left_edge[0].value)
    x_right = np.float(refine_box.right_edge[0].value)
    y_left = np.float(refine_box.left_edge[1].value)
    y_right = np.float(refine_box.right_edge[1].value)

    # slice will be repeated, so let's make it first
    slc = yt.SlicePlot(ds,
                       'z', ('gas', 'density'),
                       center=halo_center,
                       width=x_width)
    ## slc = ds.r[xmin:xmax, ymin:ymax, halo_center[2]]
    res = [1000, 1000]
    # frb = slc.frb(x_width, res)
    frb = slc.frb['gas', 'density']
    # image = np.array(frb['gas', 'density'])
    image = np.array(frb)
    print "min, max density = ", np.min(np.log10(image)), np.max(
        np.log10(image))
    # extent = [float(x.in_units('code_length')) for x in (pro.xlim + pro.ylim)]
    extent = [x_left, x_right, y_left, y_right]

    # get a spectrum!
    # impact = 25.
    # impacts = np.arange(25.,45.,0.5)
    impacts = [25.]
    for impact in impacts:
        out_fits_name = "hlsp_misty_foggie_halo008508_"+ds.basename.lower()+"_i"+"{:05.1f}".format(impact) + \
                    "_dx"+"{:4.2f}".format(0.)+"_v2_los.fits"
        out_plot_name = "slice_with_spectra_halo008508_"+ds.basename.lower()+"_i"+"{:05.1f}".format(impact) + \
                    "_dx"+"{:4.2f}".format(0.)+".png"
        hdulist, ray_start, ray_end = extract_spectra(
            ds,
            impact,
            read_fits_file=False,
            out_fits_name=out_fits_name,
            xmin=x_left,
            xmax=x_right,
            halo_center=halo_center)
        print "(impact/proper_box_size)/x_width = ", (
            impact / proper_box_size) / x_width

        # start by setting up plots
        fig = plt.figure(figsize=(12, 6), dpi=100)

        # creates grid on which the figure will be plotted
        gs = gridspec.GridSpec(3, 2)

        ## this will be the slice
        ax_slice = fig.add_subplot(gs[:, 0])
        cax = ax_slice.imshow(np.log10(image), extent=extent, cmap=density_color_map, \
                                        vmin = -29.6, vmax=-23.5)
        ax_slice.plot([ray_start[0], ray_end[0]], [ray_start[1], ray_end[1]],
                      color="white",
                      lw=2.)
        ax_slice.set_aspect('equal')
        ax_slice.xaxis.set_major_locator(ticker.NullLocator())
        ax_slice.yaxis.set_major_locator(ticker.NullLocator())
        cbar = fig.colorbar(cax, orientation='vertical', pad=0.01, shrink=0.8)
        cbar.set_label(r'log density [cm$^{-3}$]')
        ## print ray_start, ray_end, extent

        zmin, zmax = 1.998, 2.004
        ## these will be the spectra
        ax_spec1 = fig.add_subplot(gs[0, 1])
        ax_spec1.plot(hdulist["H I 1216"].data['redshift'],
                      hdulist["H I 1216"].data['flux'],
                      color="#4575b4",
                      lw=2)
        ax_spec1.text(zmin + 0.0003, 0, "H I 1216", fontsize=12.)
        plt.xlim(zmin, zmax)
        plt.ylim(-0.05, 1.05)

        ## these will be the spectra
        ax_spec2 = fig.add_subplot(gs[1, 1])
        ax_spec2.plot(hdulist["C IV 1548"].data['redshift'],
                      hdulist["C IV 1548"].data['flux'],
                      color="#4575b4",
                      lw=2)
        ax_spec2.text(zmin + 0.0003, 0, "C IV 1548", fontsize=12.)
        plt.xlim(zmin, zmax)
        plt.ylim(-0.05, 1.05)

        ## these will be the spectra
        ax_spec3 = fig.add_subplot(gs[2, 1])
        ax_spec3.plot(hdulist["O VI 1032"].data['redshift'],
                      hdulist["O VI 1032"].data['flux'],
                      color="#4575b4",
                      lw=2)
        ax_spec3.text(zmin + 0.0003, 0, "O VI 1032", fontsize=12.)
        plt.xlim(zmin, zmax)
        plt.ylim(-0.05, 1.05)

        fig.tight_layout()
        plt.savefig(out_plot_name)
        plt.close()