コード例 #1
0
def phase_by_region(filename,
                    params=None,
                    out_dir='',
                    region='midplane',
                    overwrite=False):
    '''
        phase_by_region(filename,out_dir='',region='midplane)
        
        calculate 2D joint PDFs from TIGRESS vtk dump.

        Inputs
        ------
        filename: string
            file name of vtk dump
        
        Parameters
        ----------
        params: class (phase_parameters)
        
        out_dir: string
            directory name for the output hdf5 file
            
        region: string
            setting the region for joint PDFs to be calculated
            'midplane' -- cubic region near the midplane
            'upper' or 'lower' -- region upper or lower than 512 pc
            'full' -- entire domain
    '''
    if params is None: params = phase_parameters()
    tigress_unit_system = params.unit_system

    ds = yt.load(filename,
                 units_override=ya.unit_base,
                 unit_system=tigress_unit_system)
    ya.add_yt_fields(ds, cooling=True, mhd=True, rotation=False)

    le = ds.domain_left_edge
    re = ds.domain_right_edge

    if region == 'midplane':
        le[2] = le[1]
        re[2] = re[1]
    elif region == 'upper':
        le[2] = yt.YTQuantity(512, 'pc')
    elif region == 'lower':
        re[2] = yt.YTQuantity(-512, 'pc')
    elif region == 'full':
        pass
    else:
        print('{} is unsupported region type.')
        print('region = [midplane, upper, lower, full]'.format(region))
        raise ValueError

    print('Joint PDFs to be calculated for quantities in')
    print('x = {} ~ {}'.format(le[0], re[0]))
    print('y = {} ~ {}'.format(le[1], re[1]))
    print('z = {} ~ {}'.format(le[2], re[2]))
    region = ds.box(le, re)

    phase_part(ds, region, out_dir, params=params, overwrite=overwrite)
コード例 #2
0
def FG_model(ds, center, size, height, mP):
    try:
        box = cell_patch(ds, center, size, height)
#    gal_center = ds.arr([0.5, 0.5, 0.6], 'code_length')
#    mP = massProfile(gal_center, ds)
        size = yt.YTQuantity(size, 'pc')
        Q = Qpatch(box, size, mP)

        phi = 1./Q
        F = 1.
        retMomentum = yt.YTQuantity(3000., 'km/s')
        SigmaG = GasDensity(ds,center, size, height, temp = 'all')

        SigmaSF = (2.*np.sqrt(2.)*np.pi*G*Q*phi/F)*((retMomentum)**-1)*(SigmaG**2)


 #    SigmaSF = yt.YTQuantity(13., 'Msun/yr/kpc**2')*(Q*phi/F)*((retMomentum/yt.YTQuantity(3000., 'km/s'))**-1)*(SigmaG/yt.YTQuantity(10**3, 'Msun/pc**2'))**2


        print('SigmaG: ', SigmaG)
        print('SigmaSFR: ', SigmaSF)
        return SigmaSF.in_units('Msun/yr/kpc**2')

    except:
        pass
コード例 #3
0
def SFDensity_age_cut(ds, center, size, height, age_range):

    #define center, establish YT Quantities
    x, y, z = center
    size = yt.YTQuantity(size,'pc')
    height = yt.YTQuantity(height, 'pc')
    min_age, max_age = age_range
    min_age = yt.YTQuantity(min_age, 'Myr')
    max_age = yt.YTQuantity(max_age, 'Myr')

    #Create spatial patch
    box = cell_patch(ds, center, size, height)

    #Select new star particles in patch
    formed_star_birth = box['formed_star', 'creation_time'].in_units('Myr')
    formed_star_ages = (ds.current_time.in_units('Myr') - formed_star_birth).in_units('Myr')
    formed_star_mass = box['formed_star', 'particle_mass']

    #Select stars between min and max age
    low_filter = formed_star_ages > min_age
    high_filter = formed_star_ages < max_age
    filtered_mass = formed_star_mass[low_filter & high_filter]
    
    #Find total mass of stars, then SD
    total_star_mass = np.sum(filtered_mass)
    sfrDen = (total_star_mass/((size**2)*max_age)).in_units('Msun/yr/kpc**2')

    return sfrDen
コード例 #4
0
    def nonlinear_fH2(fH2, G0):

        Sigma_H2 = (fH2*SigmaG).in_units('Msun/pc**2').in_cgs()
        Sigma_HI = ((1-fH2)*SigmaG).in_units('Msun/pc**2').in_cgs()
        RH2 = Sigma_H2/Sigma_HI


        #Plug values into system of equations                                                                                                                                                                                                                                              
        nCNM_min = 31*G0*(1+3.1*(Z)**0.365)**-1

        nCNM_2p = yt.YTQuantity(23*G0*((1+3.1*Z**0.365)/4.1)**-1, 'cm**-3')

        Pth = ((np.pi*G*Sigma_HI**2)/(4.*alpha))*(1+2*RH2+np.sqrt(((1+2*RH2)**2)+(32*zd*alpha*fw*rhoSD*cw**2)/(np.pi*G*Sigma_HI**2)))

        nCNM_hydro = Pth/(1.1*kB*tCNM)

        nCNM = max([nCNM_hydro.in_units('cm**-3'), nCNM_2p.in_units('cm**-3')])

        n1 = nCNM/yt.YTQuantity(10., 'cm**-3')

        Chi = (7.2*G0/n1).in_units('')

        Tc = (0.066*fc*Z*SigmaG_0).in_units('')

        S = np.log(1 + 0.6*Chi + 0.01*Chi**2)/(0.6*Tc)

        if S < 2.:
            fH2_inferred = 1 - (3/4)*S/(1+0.25*S)
        else:
            fH2_inferred = 0

        return fH2 - fH2_inferred
コード例 #5
0
def _MicroTurb(field, data):
    turb = data[inputs.velocityX_field]
    turb[turb>=0] = yt.YTQuantity(inputs.microturbulence_speed, "cm/s")
    turb[turb<=0] = yt.YTQuantity(inputs.microturbulence_speed, "cm/s")
    #print(turb.min())
    #print(turb.max())
    return turb
コード例 #6
0
    def _entr(field, data):
        """
	fixed the entropy units in flash
        """
        entr = data["entr"]
        kb_by = yt.YTQuantity(1, 'erg') / yt.YTQuantity(
            1, 'K') / yt.YTQuantity(1, 'g') * (1.3806488e-16 / 1.674e-24)
        return entr * kb_by
コード例 #7
0
def _NumberDensityXYZ(field, data):
    aw = yt.YTQuantity(inputs.gas_mmw*Csts.mp, 'g')
    H2numDen = (inputs.x_H2/aw)*data[inputs.density_field]
    XYZnumDen= (inputs.x_XYZ/aw)*data[inputs.density_field]
    #print(H2numDen.min())
    #print(H2numDen.max())
    if(inputs.allow_freezeout):
        XYZnumDen[H2numDen < inputs.freeze_minN] = yt.YTQuantity(0.0, "cm**-3")
        XYZnumDen[H2numDen > inputs.freeze_maxN] = yt.YTQuantity(0.0, "cm**-3")
    return XYZnumDen
コード例 #8
0
def generate_sim_column_densities(sim, ion_list, res=800):
    #cdens_file = h5.File('../../data/simulated_ion_column_densities_%s.h5'%(sim), 'w')
    cdens_file = h5.File('test.h5', 'w')

    ds, center, bv = spg.load_simulation_properties(sim)
    print(center)
    center = ds.arr(center, 'kpc')

    trident.add_ion_fields(ds, ion_list)

    field_list = ipd.generate_ion_field_list(ion_list,
                                             'number_density',
                                             model='P0')

    width = yt.YTQuantity(110, 'kpc')
    px, py = np.mgrid[-width / 2:width / 2:res * 1j,
                      -width / 2:width / 2:res * 1j]
    radius = (px**2.0 + py**2.0)**0.5

    if "radius" not in cdens_file.keys():
        cdens_file.create_dataset("radius", data=radius.ravel())

    # note: something weird going on in x-axis with P0
    for axis in ['x', 'y', 'z']:
        frb = ipd.make_projection(ds, axis, field_list, center, width)

        for i, ion in enumerate(ion_list):
            dset = "%s_%s" % (ion.replace(" ", ""), axis)
            if dset not in cdens_file.keys():
                cdens_file.create_dataset(dset,
                                          data=frb[field_list[i]].ravel())
                cdens_file.flush()
コード例 #9
0
ファイル: test_profiles.py プロジェクト: jameslehoux/yt
    def test_unequal_bin_field_profile(self):
        density = np.random.random(128)
        temperature = np.random.random(127)
        mass = np.random.random((128, 128))

        my_data = {
            ("gas", "density"): density,
            ("gas", "temperature"): temperature,
            ("gas", "mass"): mass,
        }
        fake_ds_med = {"current_time": yt.YTQuantity(10, "Myr")}
        field_types = {field: "gas" for field in my_data.keys()}
        yt.save_as_dataset(fake_ds_med,
                           "mydata.h5",
                           my_data,
                           field_types=field_types)

        ds = yt.load("mydata.h5")

        with assert_raises(YTProfileDataShape):
            yt.PhasePlot(
                ds.data,
                ("gas", "temperature"),
                ("gas", "density"),
                ("gas", "mass"),
            )
コード例 #10
0
 def massInterior(self, r):
     if not self.cached:
         self.cache()
     # the interpolation function os for logr-logM
     print('r: ', r.in_units('kpc'))
     return yt.YTQuantity(
         np.power(10.0, self.f(np.log10(r.in_units('kpc')))), 'msun')
def generate_sim_column_densities(sim, ion_list, res = 800):
    cdens_file = h5.File('../../data/simulated_ion_column_densities_%s.h5'%(sim), 'a')

    if sim == 'ad' or sim == 'stream':
        ds = yt.load('/Users/irynabutsky/Work/galaxy/g160_torB_%s/DD2600'%(sim))
    elif sim == 'P0':
        ds = yt.load('/Users/irynabutsky/Work/galaxy/P0/P0.003195')
        
    trident.add_ion_fields(ds, ion_list)
    if sim == 'P0':
#        center = YTArray([-1.693207e4, -1.201068e4, 5.303337e3], 'kpc')
        center = [-0.42323229, -0.30021773,  0.13256167]
    else:
        v, center = ds.h.find_max(("gas", "density")) 
    print(center)
    
    field_list = ipd.generate_ion_field_list(ion_list, 'number_density', model = 'P0')

    width = yt.YTQuantity(1000, 'kpc')
    px, py = np.mgrid[-width/2:width/2:res*1j, -width/2:width/2:res*1j]
    radius = (px**2.0 + py**2.0)**0.5
    
    if "radius" not in cdens_file.keys():
        cdens_file.create_dataset("radius", data = radius.ravel())

    # note: something weird going on in x-axis with P0
    for axis in ['y', 'z']:
        frb = ipd.make_projection(ds, axis, field_list, center, width)
        
        for i, ion in enumerate(ion_list):
            dset = "%s_%s" % (ion.replace(" ", ""), axis)
            if dset not in cdens_file.keys():
                cdens_file.create_dataset(dset, data=frb[field_list[i]].ravel())
                cdens_file.flush()
コード例 #12
0
def Ostriker_model(ds, center, size, height):
    box = cell_patch(ds, center, size, height)

    SigmaG = GasDensity(ds, center, size, height, temp='all')
    print('SigmaG: ', SigmaG)
    size = yt.YTQuantity(size, 'pc').in_cgs()
    height = yt.YTQuantity(height, 'pc').in_cgs()
    SigmaG_0 = (SigmaG / yt.YTQuantity(1., 'Msun/pc**2')).in_units('')
    Z = 0.1
    rhoSD = (np.sum(box['particle_mass'].in_units('g')) /
             ((size**2) * (2 * height))).in_cgs()
    print('rhoSD: ', rhoSD)

    Sigma_h = (2 * alpha * Pth_0) / (np.pi * G * SigmaSF_0 * t_SF)

    S = (8. * zd * alpha * fw * rhoSD * cw**2) / (np.pi * G * SigmaG**2)

    omega = SigmaG / Sigma_h
    print('Sigma_h: ', Sigma_h)
    print('s: ', S)
    print('omega: ', omega)

    def Gdiff_frac(x):
        return omega * (1. + (1. + (1. / (omega * (1. - x))) +
                              (S / (1. - x)**2.))**(1. / 2.)) - (1 / x)

    x = opt.brentq(Gdiff_frac, 10**-5, 1)
    print('x: ', x)
    Sigma_diff = x * SigmaG
    Sigma_GBC = (1 - x) * SigmaG
    print('Sigma_diff', Sigma_diff)
    print('Sigma_GBC', Sigma_GBC)

    #diffuse-gas thermal equilibrium

    #    phi_d = (1./4.)*(1+3*(Z*SigmaG/SigmaG_0)**0.4)

    #   Pth = (1-phi_d)*(Pth_0/SigmaSF_0)*(Sigma_GBC/t_SF)

    #  Pth = ((np.pi*G*Sigma_diff**2)/(4*alpha))*(1+2*(Sigma_GBC/Sigma_dff)+((1+2*(Sigma_GBC/Sigma_diff))**2+((32*zd*alpha*fw*cw**2)/(np.pi*G))*(rhoSD/(Sigma_diff**2)))**(1/2))

    SigmaSF = (Sigma_GBC / t_SF)

    print('tSF: ', t_SF)
    print('SigmaSFR: ', SigmaSF)

    return SigmaSF.in_units('Msun/yr/kpc**2')
コード例 #13
0
    def _entrdens(field, data):
        """
        create a new derived field to show both entropy and density

        if density > PNS_DENSITY:
            entropy = PNS_ENTR
        else:
            entropy = entropy

        """
        dens = data["dens"]
        entr = data["entr"]
        entrdens = entr * (
            np.exp(-(dens.in_cgs() / PNS_DENSITY)**5)) + PNS_ENTR
        kb_by = yt.YTQuantity(1, 'erg') / yt.YTQuantity(
            1, 'K') / yt.YTQuantity(1, 'g') * (1.3806488e-16 / 1.674e-24)
        return entrdens * kb_by
コード例 #14
0
def SFDensity(ds, center, size, height, cutoff):

    #define center, establish YT Quantities
    x, y, z = center
    size = yt.YTQuantity(size,'pc')
    height = yt.YTQuantity(height, 'pc')
    #max_age = yt.YTQuantity(max_age, 'Myr')
    cutoff = yt.YTQuantity(cutoff, 'Myr')
    max_age = (ds.current_time.in_units('Myr') - cutoff).in_units('Myr')

    #Create spatial patch
    box = cell_patch(ds, center, size, height)

    #Create array of masses & ages of all particles
    star_mass = box['particle_mass'].in_units('Msun')
    creation_time = box['creation_time']

    #Select new star particles in patch
    new_stars = creation_time > 0
    new_star_time = creation_time[new_stars].in_units('Myr')
    new_star_ages = (ds.current_time.in_units('Myr') - new_star_time).in_units('Myr')
    birth_years = creation_time[new_stars].in_units('Myr')

    #Create cutoff after SFR is stabilized (~200MYR)
#    cutoff = yt.YTQuantity(200, 'Myr')
#    cut_mask = new_star_ages < cutoff
#    cut_ages = new_star_ages[cut_mask]

    #young = new_star_ages < max_age
    #stars = new_star_ages[young]
    #stars = new_star_ages[young]
    young = birth_years > cutoff
    stars = birth_years[young]
    


    #Get masses of new stars
    new_star_mass = star_mass[new_stars]
#    new_star_mass = new_star_mass[cut_mask]
    young_star_mass = new_star_mass[young]

    #Find total mass of new stars, then surface density
    total_star_mass = np.sum(young_star_mass)
    sfrDen = (total_star_mass/((size**2)*max_age)).in_units('Msun/yr/kpc**2')

    return sfrDen
コード例 #15
0
    def nonlinear_G0(G0):
        fH2_found = opt.brentq(nonlinear_fH2, 0, 1, args = (G0))

        tff = yt.YTQuantity(31*SigmaG_0**(-1/4), 'Myr')

        SigmaSF = fH2_found*Eff*SigmaG/tff

        return SigmaSF/SigmaSF_0 - G0
コード例 #16
0
def set_units(input_units):
    """
    sets units used for all calculations
    """
    global length_unit
    global velocity_unit
    global mass_unit
    global time_unit
    for key in input_units.keys():
        if key in units.keys():
            units[key] = input_units[key]
    length_unit = yt.YTQuantity(units["length_unit"][0],
                                units["length_unit"][1])
    velocity_unit = yt.YTQuantity(units["velocity_unit"][0],
                                  units["velocity_unit"][1])
    mass_unit = yt.YTQuantity(units["mass_unit"][0], units["mass_unit"][1])
    time_unit = yt.YTQuantity(units["time_unit"][0], units["time_unit"][1])
    density_unit = yt.YTQuantity(units["density_unit"][0],
                                 units["density_unit"][1])
コード例 #17
0
def luminosity(global_data, sink_inds, global_ind):
    """
    Calculates the luminosity of the given indexes
    """
    global f_acc
    radius = yt.YTQuantity(2.0, 'rsun')
    M_dot = accretion(sink_inds, global_ind)
    M = yt.YTArray(global_data['m'][global_ind,sink_inds]*units['mass_unit'].in_units('msun'), 'Msun')
    L_acc = f_acc * (yt.units.G * M.in_units('g') * M_dot.in_units('g/s'))/radius.in_units('cm')
    L_tot = L_acc.in_units('Lsun')
    return L_tot
コード例 #18
0
def generate_column_data(output, ion_list, res=800, axis='y'):
    sim = 'romulusC'
    field_list = ion_help.generate_ion_field_list(ion_list, 'number_density')
    ds = yt.load('/nobackupp2/ibutsky/simulations/%s/%s.%06d' %
                 (sim, sim, output))

    trident.add_ion_fields(ds, ions=ion_list)

    cdens_file = h5.File(
        '/nobackupp2/ibutsky/data/%s/%s.%06d_column_data.h5' %
        (sim, sim, output), 'a')
    rom_center = rom_help.get_romulus_center(sim, output)

    id_list, center_x_list, center_z_list, width_list = \
                np.loadtxt('data/temp_coordinate_list.dat'%(sim, output, axis), skiprows=3, unpack = True)

    for region_id, center_x, center_z, width in zip(id_list, center_x_list,
                                                    center_z_list, width_list):
        cdens_file = h5.File(
            '/nobackupp2/ibutsky/data/%s/%s.%06d_column_data_region_%i.h5' %
            (sim, sim, output, region_id), 'a')
        width = yt.YTQuantity(width, 'kpc')
        px, py = np.mgrid[-width / 2:width / 2:res * 1j,
                          -width / 2:width / 2:res * 1j]
        radius = (px**2.0 + py**2.0)**0.5

        if "px" not in cdens_file.keys():
            cdens_file.create_dataset("px", data=px.ravel())

        if "py" not in cdens_file.keys():
            cdens_file.create_dataset("py", data=py.ravel())

        if "radius" not in cdens_file.keys():
            cdens_file.create_dataset("radius", data=radius.ravel())

        center = [
            rom_center[0] + center_x, rom_center[1], rom_center[2] + center_z
        ]
        center = (center / ds.length_unit).d

        frb = ion_help.make_projection(ds,
                                       axis,
                                       field_list,
                                       center,
                                       width,
                                       res=res)

        for i, ion in enumerate(ion_list):
            dset = "%s_%s" % (ion.replace(" ", ""), axis)
            if dset not in cdens_file.keys():
                cdens_file.create_dataset(dset,
                                          data=frb[field_list[i]].ravel())
                cdens_file.flush()
コード例 #19
0
def expectedSFR_calculator(ds, center, size, height):

    #Create patch of cells
    box = cell_patch(ds, center, size, height)
    #Make inputs into YT Quantites
    size = yt.YTQuantity(size, 'pc')
    height = yt.YTQuantity(height, 'pc')
    #Find cells in patch
    cell_sfr = box['expectedSFR'].in_units('Msun/yr/kpc**3')

    v_cells = box['cell_volume']

        #Create Temperature Cut
#    cell_temp = ad['temperature'].in_units('K')
#    cell_temp_patch = cell_temp[box]
#    cold_gas = cell_temp_patch < 10**4
    #Add up mass of cells in patch under temp cut
#    cold_gas_mass = patch_cells[cold_gas]
    cell_sfr = cell_sfr*v_cells
    total_sfr = np.sum(cell_sfr)
    density = (total_sfr/size**2).in_units('Msun/yr/kpc**2')
    return density
コード例 #20
0
def GasDensity(ds, center, size, height, temp):

    x,y,z = center

    #Create patch of cells
    box = cell_patch(ds, center, size, height)

    #Make inputs into YT Quantites
    size = yt.YTQuantity(size, 'pc')
    height = yt.YTQuantity(height, 'pc')

    #Find cells in patch
    mass = box['cell_mass'].in_units('Msun')
#    patch_cells = cell_mass[box]

    #Create Temperature Cut
    cell_temp = box['temperature'].in_units('K')
#    cell_temp_patch = cell_temp[box]
    if temp == 'cold':
        cold_gas = cell_temp < 10**4

        #Add up mass of cells in patch under temp cut
        cold_gas_mass = mass[cold_gas]
        total_mass = np.sum(cold_gas_mass)

    elif temp == 'warm':
        warm_gas = cell_temp > 10**4
        warm_gas_mass = mass[warm_gas]
        total_mass = np.sum(warm_gas_mass)
    elif temp == 'all':
        total_mass = np.sum(mass)



    
    print(total_mass, size**2)
    #Calculate density (Divide by area)
    density = total_mass/(size**2)
    return density
コード例 #21
0
def test_patch(data):
    ''' Define a patch in the middle of the galaxy, and add up all the star formation inside, estimated based on the gas-only quantities. Just testing if the patch function and the expectedSFR field are working as expected.'''
    a = define_patch(data, (yt.YTQuantity(0.1, 'kpc'), yt.YTQuantity(
        0.1, 'kpc'), yt.YTQuantity(0.0, 'kpc')), yt.YTQuantity(3, 'kpc'),
                     yt.YTQuantity(1.0, 'kpc'), yt.YTQuantity(1.0e4, 'K'))
    print(
        np.sum((data['expectedSFR'][a] *
                data['cell_volume'][a]).in_units('msun/yr')))
コード例 #22
0
def calculateKnownExtrema(Param_Dict, Edit_Dict):
    """Our Dataset already has some of the extrema as attributes, so we can add
    those to the Mins and Maxs.
    Parameters:
        Edit_Dict: To set the center edits"""
    ds = Param_Dict["CurrentDataSet"]
    axes = ["X", "Y", "Z"]
    if Param_Dict["Geometry"] == "cartesian":
        edgeList = ["x", "y", "z"]
    elif Param_Dict["Geometry"] == "cylindrical":
        edgeList = ["r", "z", "theta"]
    else:
        raise NotImplementedError("only cartesian and cylindrical geometries "
                                  "have been implemented so far")
    for i, field in enumerate(edgeList):
        minArray = ds.domain_left_edge
        maxArray = ds.domain_right_edge
        unit = Param_Dict["FieldUnits"][field]
        if field == "theta":
            minVal = minArray[i].value
            maxVal = maxArray[i].value
            minTextVal, maxTextVal = 0, 0
        else:
            minVal = yt.YTQuantity(ds.quan(minArray[i],
                                           'code_length')).to_value(unit)
            maxVal = yt.YTQuantity(ds.quan(maxArray[i],
                                           'code_length')).to_value(unit)
            minTextVal = yt.YTQuantity(minVal,
                                       unit).to_value(Param_Dict["GridUnit"])
            maxTextVal = yt.YTQuantity(maxVal,
                                       unit).to_value(Param_Dict["GridUnit"])
        Param_Dict["FieldMins"][field] = minVal
        Param_Dict["FieldMaxs"][field] = maxVal
        center = 0.5 * (maxTextVal + minTextVal)
        cenEdit = Edit_Dict[axes[i] + "Center"]
        cenEdit.setText(f"{center:.3g}")
        cenEdit.textChanged.emit(cenEdit.text())
コード例 #23
0
def SlicePlot(Param_Dict, worker):
    """Takes a DataSet object loaded with yt and performs a slicePlot on it.
    Parameters:
        Param_Dict: Dict with Parameters
    """
    ds = Param_Dict["CurrentDataSet"]
    gridUnit = Param_Dict["GridUnit"]
    c0 = yt.YTQuantity(Param_Dict["XCenter"], gridUnit)
    c1 = yt.YTQuantity(Param_Dict["YCenter"], gridUnit)
    if Param_Dict["Geometry"] == "cartesian":
        c2 = yt.YTQuantity(Param_Dict["ZCenter"], gridUnit)
    else:
        c2 = Param_Dict["ZCenter"]
    field = Param_Dict["ZAxis"]
    width = (Param_Dict["HorWidth"], gridUnit)
    height = (Param_Dict["VerWidth"], gridUnit)
    if Param_Dict["NormVecMode"] == "Axis-Aligned":
        plot = yt.AxisAlignedSlicePlot(ds, Param_Dict["NAxis"], field,
                                       axes_unit=Param_Dict["GridUnit"],
                                       fontsize=14, center=[c0, c1, c2],
                                       width=(width, height))
    else:
        normVec = [Param_Dict[axis + "NormDir"] for axis in ["X", "Y", "Z"]]
        northVec = [Param_Dict[axis + "NormNorth"] for axis in ["X", "Y", "Z"]]
        plot = yt.OffAxisSlicePlot(ds, normVec, field, north_vector=northVec,
                                   axes_unit=Param_Dict["GridUnit"],
                                   fontsize=14, center=[c0, c1, c2],
                                   width=(width, height))
    emitStatus(worker, "Setting slice plot modifications")
    # Set min, max, unit log and color scheme:
    setAxisSettings(plot, Param_Dict, "Z")
#    # yt will automatically make it quadratic, so we'll set the individual
#    plot.set_width((max(width, height), gridUnit))  # width and height later
    plot.zoom(Param_Dict["Zoom"])
    emitStatus(worker, "Annotating the slice plot")
    annotatePlot(Param_Dict, plot)
    finallyDrawPlot(plot, Param_Dict, worker)
コード例 #24
0
def getDerFieldInfo(Param_Dict, ComboBox_Dict, Misc_Dict, dialog):
    """If the user has filled everything in correctly and presses apply, this
    function is called to store the function"""
    # get all of the information from the dialog:
    fieldName = dialog.fieldName
    displayName = dialog.displayName
    fieldFunction = dialog.fieldFunction
    unit = dialog.unit
    dim = dialog.dim
    override = dialog.override
    if dim == 1:
        dim = "dimensionless"
    text = dialog.functionText
    # Add the field to the known fields in Param_Dict and comboboxes:
    for axis in ["X", "Y", "Z"]:
        Param_Dict[axis + "Fields"].insert(3, fieldName)
        ComboBox_Dict[axis + "Axis"].insertItem(3, fieldName)
        if axis != "X":
            ComboBox_Dict[axis + "Weight"].insertItem(3, fieldName)
    Param_Dict["WeightFields"].insert(3, fieldName)
    yt.add_field(("gas", fieldName),
                 function=fieldFunction,
                 units=unit,
                 dimensions=dim,
                 force_override=override,
                 display_name=displayName,
                 take_log=False)
    reloadFiles(Param_Dict, Misc_Dict)
    # Save the parameters in Param_Dict for the ScriptWriting function
    Param_Dict["NewDerFieldDict"][fieldName] = {}
    Param_Dict["NewDerFieldDict"][fieldName]["Override"] = override
    Param_Dict["NewDerFieldDict"][fieldName]["DisplayName"] = displayName
    Param_Dict["NewDerFieldDict"][fieldName]["FunctionText"] = text
    if unit == "auto":
        Param_Dict["NewDerFieldDict"][fieldName]["Unit"] = dialog.baseUnit
    else:
        Param_Dict["NewDerFieldDict"][fieldName]["Unit"] = unit
    Param_Dict["NewDerFieldDict"][fieldName]["Dimensions"] = dim
    if unit == "auto":
        unit = fieldFunction(
            "Hello, I'm a fancy placeholder, why did you \
                             call me?", dialog.sp).units
    ds = Param_Dict["CurrentDataSet"]
    Param_Dict["FieldUnits"][fieldName] = yt.YTQuantity(ds.arr(1, unit)).units
    GUILogger.log(
        29, f"The new field <b>{fieldName}</b> with {dim}-dimension \
                  has been added successfully.")
    GUILogger.info("You can find it in the comboBoxes for the field selection,"
                   " and it will be added to every new dataset.")
コード例 #25
0
def generate_column_data(sim, ion_list, width=400, res=800):

    field_list = ion_help.generate_ion_field_list(ion_list, 'number_density')
    ds, center = rom.load_charlotte_sim(sim)
    trident.add_ion_fields(ds, ions=ion_list)

    fn = '/nobackupp2/ibutsky/data/charlotte/%s_column_data.h5' % (sim)
    cdens_file = h5.File(fn)
    axis_list = ['x', 'y', 'z']

    width = yt.YTQuantity(width, 'kpc')
    px, py = np.mgrid[-width / 2:width / 2:res * 1j,
                      -width / 2:width / 2:res * 1j]
    radius = (px**2.0 + py**2.0)**0.5

    if "px" not in cdens_file.keys():
        cdens_file.create_dataset("px", data=px.ravel())

    if "py" not in cdens_file.keys():
        cdens_file.create_dataset("py", data=py.ravel())

    if "radius" not in cdens_file.keys():
        cdens_file.create_dataset("radius", data=radius.ravel())

    for axis in axis_list:
        #frb = ion_help.make_projection(ds, axis, field_list, center, width, res = res)

        for i, ion in enumerate(ion_list):
            dset = "%s_%s" % (ion.replace(" ", ""), axis)
            if dset not in cdens_file.keys():
                print(dset)
                sys.stdout.flush()
                #frb = ion_help.make_projection(ds, axis, field_list[i], center, width, res = res)
                p = yt.ProjectionPlot(ds,
                                      axis,
                                      field_list[i],
                                      width=width,
                                      weight_field=None,
                                      center=center)
                p.set_zlim(field_list[i], 1e13, 1e15)
                p.save()
                frb = p.data_source.to_frb(width, res)
                print(frb)
                print(frb.keys())
                print(frb[field_list[i]])
                cdens_file.create_dataset(dset,
                                          data=frb[field_list[i]].d.ravel())
                cdens_file.flush()
コード例 #26
0
    def test_unequal_bin_field_profile(self):
        density = np.random.random(128)
        temperature = np.random.random(127)
        cell_mass = np.random.random((128, 128))

        my_data = {
            "density": density,
            "temperature": temperature,
            "cell_mass": cell_mass}
        fake_ds_med = {"current_time": yt.YTQuantity(10, "Myr")}
        yt.save_as_dataset(fake_ds_med, "mydata.h5", my_data)

        ds = yt.load('mydata.h5')

        assert_raises(
            YTProfileDataShape,
            yt.PhasePlot, ds.data, 'temperature', 'density', 'cell_mass')
コード例 #27
0
ファイル: my_ramses_module.py プロジェクト: rajikalk/Scripts
def generate_frame_times(files,
                         dt,
                         start_time=0,
                         presink_frames=25,
                         end_time=None,
                         form_time=None):
    if form_time != None:
        sink_form_time = form_time
    else:
        sink_form_time = find_sink_formation_time(files)

    if end_time != None or len(files) == 1:
        max_time = end_time
    else:
        csv.register_dialect('dat', delimiter=' ', skipinitialspace=True)
        with open(files[-1].split("info")[0] + 'stars_output.snktxt',
                  'r') as f:
            reader = csv.reader(f, dialect='dat')
            for row in reader:
                time = yt.YTQuantity(
                    float(row[1]) * time_unit.in_units('yr').value, 'yr')
                break
        if form_time != None:
            max_time = time.in_units('yr') - form_time
        else:
            max_time = time.in_units('yr')

    if len(files) == 1:
        m_times = [time]
    else:
        if presink_frames != 0:
            m_times = np.logspace(0.0, np.log10(sink_form_time),
                                  presink_frames) - sink_form_time
        else:
            m_times = np.array([])
        m_times = m_times.tolist()

        postsink = 0.0
        while postsink <= max_time:
            if start_time is not None:
                if postsink >= start_time:
                    m_times.append(postsink)
            else:
                m_times.append(postsink)
            postsink = postsink + dt
    return m_times
コード例 #28
0
 def validateUnit(self):
     """Checks whether the unit given matches the dimensionality of the out-
     put of the function."""
     if self.fieldFunctionEdit.isValid:
         if self.unitEdit.text() == "auto":
             self.unitEdit.turnTextBlack()
             setValidity(self.unitEdit, True)
             return
         try:
             unit = yt.YTQuantity(self.sp.ds.arr(
                 1, self.unitEdit.text())).units
             if unit.dimensions == self.dim:
                 self.unitEdit.turnTextBlack()
                 setValidity(self.unitEdit, True)
             else:
                 self.unitEdit.turnTextRed()
                 setValidity(self.unitEdit, False)
         except (UnitParseError, AttributeError):
             self.unitEdit.turnTextRed()
             setValidity(self.unitEdit, False)
     else:
         self.unitEdit.turnTextRed()
         setValidity(self.unitEdit, False)
コード例 #29
0
def setProfileAxisSettings(Param_Dict, axis, axes):
    """Sets the axis settings for profile plots. This includes log scaling,
    limits and setting the labels to the correct latex representation.
    Parameters:
        Param_Dict: Parameter dictionary for dataset, axis and unit
        axis: "X" or "Y" for the axis
        axes: the axes instance to put the label on
    """
    if Param_Dict[axis + "Log"]:
        eval(f"axes.set_{axis.lower()}scale('log')")
    field = Param_Dict[axis + "Axis"]
    ds = Param_Dict["CurrentDataSet"]  # is necessary for eval commands
    unit = yt.YTQuantity(1, Param_Dict[axis + "Unit"]).units.latex_repr  # get latex repr for unit
    if unit != "":  # do not add empty brackets
        unit = r"$\:\left[" + unit + r"\right]$"
    if field == "dens" or field == "temp":
        name = eval(f"ds.fields.flash.{field}.get_latex_display_name()")
    elif field == "time":
        name = r"$\rm{Time}$"
    else:
        name = eval(f"ds.fields.gas.{field}.get_latex_display_name()")
    eval(f"axes.set_{axis.lower()}label(name + unit)")
    eval(f"axes.set_{axis.lower()}lim(Param_Dict[axis + 'Min'], Param_Dict[axis + 'Max'])")
コード例 #30
0
def doit(field):
    ds = yt.load(args.infile)

    if not args.width:
        width = max(ds.domain_width)
    else:
        width = yt.YTQuantity(args.width, 'cm')

    maxv = ds.all_data().max(field)
    minv = ds.all_data().min(field)
    pos_maxv = np.ceil(np.log10(maxv))
    neg_maxv = np.ceil(np.log10(minv))
    logmaxv = max(pos_maxv, neg_maxv)
    linminv = min(abs(maxv), abs(minv))

    if args.octant:
        dcenter = width.in_units('cm').v / 2.0
        cpos = ds.arr([dcenter, dcenter, dcenter], 'cm')
        s = yt.SlicePlot(ds,
                         'x',
                         field,
                         center=cpos,
                         width=width,
                         origin="native")
    else:
        s = yt.SlicePlot(ds, 'x', field, center='c', width=width)

    s.annotate_scale()

    if args.drawcells:
        s.annotate_cell_edges()

    if args.drawgrids:
        s.annotate_grids()

    s.set_buff_size(2048)

    if minv < 0.0 and maxv > 0.0:
        s.set_cmap(field, 'PiYG')
        linthresh = 0.1
        if ((args.logscale or args.symlog) and not args.sign
                and not field == 'conv_type'):
            if args.linthresh:
                linthresh = args.linthresh
            s.set_log(field, args.logscale, linthresh=linthresh)
        else:
            s.set_log(field, args.logscale)
        if args.sign or field == 'conv_type':
            s.set_zlim(field, -1.0, 1.0)
            plot = s.plots[field]
            colorbar = plot.cb
            s._setup_plots()
            if field != 'conv_type':
                colorbar.set_ticks([-1, 0, 1])
                colorbar.set_ticklabels(['$-1$', '$0$', '$+1$'])
            else:
                colorbar.set_ticks([-0.8, 0, 0.65])
                colorbar.ax.tick_params(axis=u'both', which=u'both', length=0)
                colorbar.ax.set_yticklabels(
                    ['stable', 'semiconvective', 'convective'], rotation=90)
        elif args.field_min and args.field_max:
            s.set_zlim(field, args.field_min, args.field_max)
        elif args.field_min and args.field_min < 0.0:
            s.set_zlim(field, args.field_min, -args.field_min)
        elif args.field_max and args.field_max > 0.0:
            s.set_zlim(field, -args.field_max, args.field_max)
        else:
            s.set_zlim(field, -linthresh, linthresh)
    else:
        s.set_cmap(field, 'Greens')

    s.save('{}.slice.{}.png'.format(args.infile, field))