예제 #1
0
    def __init__(self, path, ioutput, **kwargs):
        Snapshot.Snapshot.__init__(self, path, ioutput, "pymses", **kwargs)
        '''
		Load the snapshot using pymses.RamsesOutput
		TODO Verify snapshot exists
		'''
        self._snapshot = pymses.RamsesOutput(path, ioutput)
예제 #2
0
def connect(dir="backreaction_b5_3d3yr",
            out=9,
            var=["d", "ux", "uy", "uz", "P", "f", "tS", "tI", "tB", "g", "w"]):
    global output, grid
    output = pymses.RamsesOutput(basedir + dir, out)
    print output.info
    grid = output.amr_source(var)
예제 #3
0
def connect(dir="L68_off",
            out=11,
            var=["d", "ux", "uy", "uz", "P", "f", "tS", "tI", "tB", "g"]):
    global output, grid
    output = pymses.RamsesOutput(basedir + dir, out)
    print output.info
    grid = output.amr_source(var)
예제 #4
0
def get_dx(ssnum):
    # hard-code to get dx for now...
    # saved in fetch_gal_fields.py
    ro = pymses.RamsesOutput("output", ssnum)
    ds = np.load('snapshot' + str(ssnum) + '_center_fields0123456-15.npz')
    dx_vector = ds['dx_vector']

    originalLevels = np.log2(1. / np.unique(dx_vector))
    highestRes = 2.**(originalLevels.max() * -1)
    # after finely sample unigrid
    dx_pc = highestRes * get_units(ro=ro)['dx'][0]
    return dx_pc
예제 #5
0
    def __init__(self, path, ioutput, ro=None, verbose=False, **kwargs):
        super(PymsesSnapshot, self).__init__(path, ioutput, **kwargs)

        from pymses import rcConfig as pymsesrc
        self.verbose = verbose
        if ro is None:
            self._ro = pymses.RamsesOutput(path,
                                           ioutput,
                                           metals=self.metals,
                                           verbose=self.verbose,
                                           **kwargs)
        else:
            self._ro = ro
        self._nproc_multiprocessing = pymsesrc.multiprocessing_max_nproc
		print("=================================================")
		print("/!\   output_ref  <  output_ref_t0   /!\ ")
		print("=================================================")
		print("=================================================")
		System.exit (0)

else:
	ref=(1,0)
	a_comparer=(1,0)



#-----------------------------------------
#Lecture du temps de l'output de reference
#-----------------------------------------
ro=pymses.RamsesOutput(path_simu_ref, num_output_ref)

factor_time_Myr_ref = ro.info['unit_time'].express(cst.Myr)
simulation_time_ref = ro.info['time']*factor_time_Myr_ref - ref[1]



#----------------------------------------------------------------
#Recherche des output correspondant dans la simulation a comparer
#----------------------------------------------------------------
output_manquant=0
for l in range(num_output_max):
	current_output = (l+1) + int(a_comparer[0])
	try:
		ro=pymses.RamsesOutput(path_simu_a_comparer, current_output)
	except:
예제 #7
0
#Chargement moments cinetiques de la simulation HR sans rotation
#---------------------------------------------------------------
path_1_norot = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr/Moment_cinetique_tot_output_1_44_barycentre.fits'
path_2_norot = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr/Integrale_valeurs_absolues_moments_cinetiques_output_1_44_barycentre.fits'

path_simu_norot='/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr/'
num_min_norot=1
num_max_norot=44

nmbr_output_norot = num_max_norot-num_min_norot+1


if lecture_time == True:
	simulation_time_norot = np.zeros(nmbr_output_norot)
	for l in range(nmbr_output_norot):
		ro=pymses.RamsesOutput(path_simu_norot,l+1)
		factor_time_norot_Myr = ro.info['unit_time'].express(cst.Myr)
		simulation_time_norot[l] = ro.info['time']*factor_time_norot_Myr



#----------------------------------------------------------------
#Chargement moments cinetiques de la simulation HR2 sans rotation
#----------------------------------------------------------------
path_1_norot2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Moment_cinetique_tot_output_1_102_barycentre.fits'
path_2_norot2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Integrale_valeurs_absolues_moments_cinetiques_output_1_102_barycentre.fits'

path_simu_norot2='/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr2/'
num_min_norot2=1
num_max_norot2=102
numero_output = np.zeros(nmbr_output)
time_tab = np.zeros(nmbr_output)
time_cor_tab = np.zeros(nmbr_output)
max_rho_tab = np.zeros((nmbr_output,3))


#------------------------------------------------------------------------------------
#Boucle sur les differents output pour extraire le rayon des disques de chaque output	
#------------------------------------------------------------------------------------
output_manquant=0
nbre_output_effectif=0
verif=0
for i in range(nmbr_output):
    num = i+output_min
    try:
        ro=pymses.RamsesOutput(path,num)
    except:
        output_manquant += 1
        if output_manquant==100:
            print
            print
            print("=========================================================================================")
            print("=========================================================================================")
            print("Pas assez d'output pour la simulation : "+path )
            print("=========================================================================================")
            print("=========================================================================================")
            break
        continue

    verif=1
    output_manquant=0
예제 #9
0
def trace_angle_gradient_vitesse(simu,tag,output,R_min,R_max,dr,legend,marker,ang_absolu,ang_relat,omega,moment_spec,save_fig):
#------------------
#Differents chemins
#------------------
    path='/drf/projets/alfven-data/averliat/'+simu+'/'
    path_analyses='/home/averliat/these/analyses/'+simu+'/'
    file_save_ang = 'Angle_omega_J_gradient_vitesse_log_output'+str(output)+'_Rmin'+str(R_min)+'_Rmax'+str(R_max)+'_dr'+str(dr)+'.hdf5'
    #file_save_ang = 'Angle_gradient_vitesse_output'+str(output)+'comparaison_mathilde.hdf5'



#------------------------------------
#Chargement des differentes quantites
#------------------------------------
    h5f = h5py.File(path_analyses+file_save_ang, 'r')

    shells_au=h5f['shells_au'][:]
    ang_x_tab=h5f['ang_x_tab'][:]
    ang_y_tab=h5f['ang_y_tab'][:]
    ang_z_tab=h5f['ang_z_tab'][:]
    if omega==True:
        omega_x_tab=h5f['omega_x_tab'][:]
        omega_y_tab=h5f['omega_y_tab'][:]
        omega_z_tab=h5f['omega_z_tab'][:]
    if moment_spec==True:
        moment_spec_x_tab=h5f['moment_spec_x_tab'][:]
        moment_spec_y_tab=h5f['moment_spec_y_tab'][:]
        moment_spec_z_tab=h5f['moment_spec_z_tab'][:]

    h5f.close()



#---------------------------------------------------
#Recalage des angles par rapport à l'angle initial
#---------------------------------------------------
    ang_x_tab[np.where(ang_x_tab<0)] = ang_x_tab[np.where(ang_x_tab<0)]+360
    ang_y_tab[np.where(ang_y_tab<0)] = ang_y_tab[np.where(ang_y_tab<0)]+360
    ang_z_tab[np.where(ang_z_tab<0)] = ang_z_tab[np.where(ang_z_tab<0)]+360

    
    seuil_ang=200

    ang_0=ang_x_tab[0]
    for i in range(len(ang_x_tab)):
        if np.abs(ang_0-ang_x_tab[i])>seuil_ang:
            ang_x_tab[i]=ang_x_tab[i]+360
            if np.abs(ang_0-ang_x_tab[i])>seuil_ang:
                ang_x_tab[i]=ang_x_tab[i]-720
        ang_0=ang_x_tab[i]

    ang_0=ang_y_tab[0]
    for i in range(len(ang_y_tab)):
        if np.abs(ang_0-ang_y_tab[i])>seuil_ang:
            ang_y_tab[i]=ang_y_tab[i]+360
            if np.abs(ang_0-ang_y_tab[i])>seuil_ang:
                ang_y_tab[i]=ang_y_tab[i]-720
        ang_0=ang_y_tab[i]

    ang_0=ang_z_tab[0]
    for i in range(len(ang_z_tab)):
        if np.abs(ang_0-ang_z_tab[i])>seuil_ang:
            ang_z_tab[i]=ang_z_tab[i]+360
            if np.abs(ang_0-ang_z_tab[i])>seuil_ang:
                ang_z_tab[i]=ang_z_tab[i]-720
        ang_0=ang_z_tab[i]
    

    ang_x_tab_recal = ang_x_tab - ang_x_tab[0]
    ang_y_tab_recal = ang_y_tab - ang_y_tab[0]
    ang_z_tab_recal = ang_z_tab - ang_z_tab[0]
    


#---------------------------------------------------------------------------------
#Calcul des t_0 de chaque simulation ou lecture des fichiers si calculs deja faits
#---------------------------------------------------------------------------------
    ro=pymses.RamsesOutput(path,output)
    factor_time_yr = ro.info['unit_time'].express(cst.year)
    simulation_time = ro.info['time']*factor_time_yr
    seuil_rho = 1e-10
    if os.path.isfile(path_analyses+'t0_seuil_rho_'+str(seuil_rho)+'.txt') == False:
        ref = np.array(t_0.temps_0_simu(path_t0, seuil_rho, sortie_output=1))
        np.savetxt(path_analyses+'t0_seuil_rho_'+str(seuil_rho)+'.txt', ref)
    else:
        ref=np.loadtxt(path_analyses+'t0_seuil_rho_'+str(seuil_rho)+'.txt')



#------------------
#Debut de la figure
#------------------
    cmappts = plt.get_cmap('magma')
    colorspts = [cmappts(i) for i in np.linspace(0.1,0.9,7)]

    if ang_absolu==True:
        plt.figure()
        plt.semilogx(shells_au, ang_x_tab, marker='.',color=colorspts[2], label=r'$x$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')

        #plt.figure()
        plt.semilogx(shells_au, ang_y_tab, marker='.',color=colorspts[4], label=r'$y$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')
        plt.title('Time = '+str(int(simulation_time - ref[1]*1e6))+' years  ~~~~~~~~~ $ \\varepsilon= 50 \%$')

        #plt.figure()
        plt.semilogx(shells_au, ang_z_tab, marker='.',color=colorspts[6], label=r'$z$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')

        if save_fig==True:
            plt.tight_layout(pad=0.1) #pad en inch si besoin
            plt.savefig(path_analyses+'Article_1/Angle_gradient_vitesse_'+simu+'_output'+str(output)+'_Rmin'+str(R_min)+'_Rmax'+str(R_max)+'_dr'+str(dr)+'.pdf')#, bbox_inches='tight')


    if ang_relat==True:
        plt.figure()
        plt.semilogx(shells_au, ang_x_tab_recal, marker='.',color=colorspts[2], label=r'$x$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')
        plt.title('Time = '+str(int(simulation_time - ref[1]*1e6))+' years ~~~~~~~~~ $\\varepsilon= 50 \%$')

        #plt.figure()
        plt.semilogx(shells_au, ang_y_tab_recal, marker='.',color=colorspts[4], label=r'$y$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')

        #plt.figure()
        plt.semilogx(shells_au, ang_z_tab_recal, marker='.',color=colorspts[6], label=r'$z$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"Angle (°)")
        plt.legend(loc='best')

        if save_fig==True:
            plt.tight_layout(pad=0.1) #pad en inch si besoin
            plt.savefig(path_analyses+'Article_1/Angle_relatif_gradient_vitesse_'+simu+'_output'+str(output)+'_Rmin'+str(R_min)+'_Rmax'+str(R_max)+'_dr'+str(dr)+'.pdf')#, bbox_inches='tight')



    if omega==True:
        plt.figure()
        plt.loglog(shells_au, omega_x_tab, marker='.',color=colorspts[2], label=r'$x$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$\Omega$  $\left( km.s^{-1}.pc^{-1} \right)")
        plt.legend(loc='best')

        #plt.figure()
        plt.loglog(shells_au, omega_y_tab, marker='.',color=colorspts[4], label=r'$y$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$\Omega$  $\left( km.s^{-1}.pc^{-1} \right)$")
        plt.legend(loc='best')
        plt.title('Time = '+str(int(simulation_time - ref[1]*1e6))+' years ~~~~~~~~~ $\\varepsilon = 50 \%$')

        #plt.figure()
        plt.loglog(shells_au, omega_z_tab, marker='.',color=colorspts[6], label=r'$z$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$\Omega$  $\left( km.s^{-1}.pc^{-1} \right)$")
        plt.legend(loc='best')

        if save_fig==True:
            plt.tight_layout(pad=0.1) #pad en inch si besoin
            plt.savefig(path_analyses+'Article_1/Amplitude_gradient_vitesse_'+simu+'_output'+str(output)+'_Rmin'+str(R_min)+'_Rmax'+str(R_max)+'_dr'+str(dr)+'.pdf')#, bbox_inches='tight')



    if moment_spec==True:
        plt.figure()
        plt.loglog(shells_au, moment_spec_x_tab, marker='.',color=colorspts[2], label=r'$x$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$j$  $\left( km.s^{-1}.pc \right)$")
        plt.legend(loc='best')

        #plt.figure()
        plt.loglog(shells_au, moment_spec_y_tab, marker='.',color=colorspts[4], label=r'$y$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$j$  $\left( km.s^{-1}.pc \right)$")
        plt.legend(loc='best')
        plt.title('Time = '+str(int(simulation_time - ref[1]*1e6))+' years ~~~~~~~~~ $\\varepsilon= 50 \%$')

        #plt.figure()
        plt.loglog(shells_au, moment_spec_z_tab, marker='.',color=colorspts[6], label=r'$z$ projection')
        plt.xlabel(ur'Radius (AU)')
        plt.ylabel(ur"$j$  $\left( km.s^{-1}.pc \right)$")
        plt.legend(loc='best')

        if save_fig==True:
            plt.tight_layout(pad=0.1) #pad en inch si besoin
            plt.savefig(path_analyses+'Article_1/Moment_specifique_gradient_vitesse_'+simu+'_output'+str(output)+'_Rmin'+str(R_min)+'_Rmax'+str(R_max)+'_dr'+str(dr)+'.pdf')#, bbox_inches='tight')
예제 #10
0
### ipython --pylab

import pymses
import pylab
import numpy

ro = pymses.RamsesOutput("Data/Sedov3d/output", 5)
amr = ro.amr_source(["rho"])

#sph_center = [0.5, 0.5, 0.5]
#sph_radius = 0.5
#from pymses.utils.regions import Sphere
#sph = Sphere(sph_center, sph_radius)

#from pymses.analysis import sample_points
#points = sph.random_points(1.0e6) # 1M sampling points

end = [1, 1, 1]
N = 2 * 2**ro.info["levelmax"]
points = 1. * numpy.array([end] * N)
for i in range(N):
    points[i] *= (i + 1.) / N
point_dset = sample_points(amr, points)
pylab.plot(point_dset.points, point_dset['rho'])

#rho_weight_func = lambda dset: dset["rho"]
#r_bins = numpy.linspace(0.0, sph_radius, 200)
#from pymses.analysis import bin_spherical
#rho_profile = bin_spherical(point_dset, sph_center, rho_weight_func, r_bins, divide_by_counts=True)

#pylab.plot(r_bins[0:len(r_bins)-1],rho_profile)
def temps_0_simu(path_simu,
                 seuil_rho=1e11,
                 critere_mass_seuil=10,
                 num_min=1,
                 num_max=150,
                 sortie_output=1):
    #sortie_output=1 nouveau parametre pour prendre en compte si les output sont sortie tous les pas ou tous les n pas de temps (dans ce cas mettre sortie_output=n avec n=2, 3, ...)

    #--------------------------------------------
    #Caracteristiques de la simulation consideree
    #--------------------------------------------
    #simu='/gpfs/data1/averliat/B335_noturb_rot3_hydro/'
    #num_min=1
    #num_max=150  #Pas obligatoirement l'output max, peut depasser

    #seuil_rho = 1e-10  #kg.m^-3

    nmbr_output = num_max - num_min + 1

    #-------------------------------------------------
    #Lecture du temps et des densites de chaque output
    #-------------------------------------------------
    simulation_time = np.zeros(nmbr_output)
    accreted_mass = np.zeros(nmbr_output)

    output_seuil = 0
    time_seuil = 0

    for l in range(nmbr_output):
        if os.path.isdir(path_simu + 'output_' +
                         str(sortie_output * (l + 1)).zfill(5)) == False:
            print(
                "===========================================================")
            print(
                "===========================================================")
            print("      /!\  Output manquante ou seuil trop haut  /!\ ")
            print(
                "===========================================================")
            print(
                "===========================================================")
            break

        ro = pymses.RamsesOutput(path_simu, sortie_output * (l + 1))

        factor_time_Myr = ro.info['unit_time'].express(cst.Myr)
        simulation_time[l] = ro.info['time'] * factor_time_Myr

        amr = ro.amr_source(["rho"])
        cell_source = CellsToPoints(amr)
        cells = cell_source.flatten(verbose=False)

        dx = cells.get_sizes()
        pos = cells.points
        rho = cells["rho"]

        #------------------------------------------------------------
        #Facteur de conversion des unites de code en unites physiques
        #------------------------------------------------------------
        lbox = ro.info['boxlen']
        lbox_m = ro.info['unit_length'].express(cst.m)
        factor_dist_m = ro.info['unit_length'].express(cst.m)
        factor_dist_cm = ro.info['unit_length'].express(cst.cm)
        lbox_au = ro.info['unit_length'].express(cst.au)
        lbox_cm = ro.info['unit_length'].express(cst.cm)
        factor_time_yr = ro.info['unit_time'].express(cst.year)

        factor_rho_Hcc = ro.info['unit_density'].express(cst.H_cc)
        factor_rho = ro.info['unit_density'].express(cst.kg / (cst.m)**3)

        #------------------------------
        #Conversion en unites physiques
        #------------------------------
        simulation_time_yr = ro.info['time'] * factor_time_yr
        dx *= factor_dist_m
        rho_Hcc = rho * factor_rho_Hcc
        rho *= factor_rho

        #---------------------------------------------------------
        #Definition du centre des images et de leur niveau de zoom
        #---------------------------------------------------------
        mask = rho_Hcc > seuil_rho

        rho_masked = rho[mask]
        dx_masked = dx[mask]

        mass_core = np.sum(rho_masked * dx_masked**3) / 1.9889e+30  #En Msun
        mass_tot = np.sum(rho * dx**3) / 1.9889e+30  #En Msun

        pourcent_mass_core = mass_core / mass_tot * 100

        print
        print
        print(
            "=========================================================================="
        )
        print("    M_central_core = " + str(mass_core) + " Msun")
        print("    M_tot = " + str(mass_tot) + " Msun")
        print("    Pourcent_M_central_core = " + str(pourcent_mass_core) +
              " %")
        print(
            "=========================================================================="
        )
        print
        print

        accreted_mass[l] = pourcent_mass_core

        if accreted_mass[l] >= critere_mass_seuil:
            output_seuil = sortie_output * (l + 1)
            time_seuil = simulation_time[l]
            print(
                "===========================================================")
            print(
                "===========================================================")
            print("         output_seuil = " + str(output_seuil))
            print("         time_seuil = " + str(time_seuil) + " Myr")
            print(
                "===========================================================")
            print(
                "===========================================================")
            break

    if output_seuil == 0:
        print("===========================================================")
        print("===========================================================")
        print("          /!\  Seuil de masse accretee non atteint  /!\ ")
        print("===========================================================")
        print("===========================================================")
    '''
	plt.semilogy(simulation_time, max_rho, linestyle=None, marker='.')
	plt.show()
	'''

    return (output_seuil, time_seuil)
#------------------------------------------------------------
#Chargement moments cinetiques de la simulation sans rotation
#------------------------------------------------------------
path_1_norot = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr/Moment_cinetique_tot_output_1_44_barycentre.fits'
path_2_norot = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr/Integrale_valeurs_absolues_moments_cinetiques_output_1_44_barycentre.fits'

path_simu_norot = '/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr/'
num_min_norot = 1
num_max_norot = 44

nmbr_output_norot = num_max_norot - num_min_norot + 1

if lecture_time == True:
    simulation_time_norot = np.zeros(nmbr_output_norot)
    for l in range(nmbr_output_norot):
        ro = pymses.RamsesOutput(path_simu_norot, l + 1)
        factor_time_norot_Myr = ro.info['unit_time'].express(cst.Myr)
        simulation_time_norot[l] = ro.info['time'] * factor_time_norot_Myr

#-------------------------------------------------------------------
#Chargement moments cinetiques de la simulation incluant 1% rotation
#-------------------------------------------------------------------
path_1_rot = '/home/users/mnt/averliat/analyses/B335_noturb_rot_hydro/Moment_cinetique_tot_output_1_98_barycentre.fits'
path_2_rot = '/home/users/mnt/averliat/analyses/B335_noturb_rot_hydro/Integrale_valeurs_absolues_moments_cinetiques_output_1_98_barycentre.fits'

path_simu_rot = '/gpfs/data1/averliat/B335_noturb_rot_hydro/'
num_min_rot = 1
num_max_rot = 98

nmbr_output_rot = num_max_rot - num_min_rot + 1
예제 #13
0
    outname = "snapshot" + str(ssnum) + "_center_stars_resampled.h5"

    if os.path.exists(outname):
        os.system('rm ' + outname)

    camera = {'center': center, 'region_size': originalSize}

    loc_vec = ds['loc_vector']
    level_vec = ds['level']
    epoch_vec = ds['epoch']
    id_vec = ds['id']
    mass_vec = ds['mass']
    vel_vec = ds['vel']

    import pymses
    ro = pymses.RamsesOutput("output", ssnum)

    # resample star particle mass and compute mass-weighted avg epoch correspondingly
    resample_star_mass_age(loc_vec,
                           level_vec,
                           epoch_vec,
                           mass_vec,
                           vel_vec,
                           outname,
                           camera,
                           old_dt_myr=100.,
                           young_dt_myr=10.,
                           ro_in=ro,
                           Nrefined=N,
                           debug=False)
예제 #14
0
    #See Teyssier, R et al. 2010. n is number density in units H/cc
    T_eq = 10**4 * (n / 0.3)**(-0.5)
    return T_eq


if __name__ == "__main__":

    if (len(sys.argv) == 1):
        print 'Case 1 Usage: python %s <simdir> <ioutput> <nstar>' % sys.argv[0]
        print 'Case 2 Usage: python %s <omega_m0> <h> <L_box (Mpc/h)> <ell_min> <ell_max> <nstar>' % sys.argv[
            0]
        sys.exit(1)

    elif os.path.isdir(sys.argv[1]):

        ro = pymses.RamsesOutput(sys.argv[1], int(sys.argv[2]))
        omega_m0 = ro.info['omega_m']
        omega_b = ro.info['omega_b']
        h = ro.info['H0'] / 100
        aexp = ro.info['aexp']
        boxsize = ro.info[
            'unit_length'].val / 3.08e22 / aexp * h  # Mpc/h at z=0
        lgridmin = ro.info['levelmin']
        lgridmax = ro.info['levelmax']
        n_star = float(sys.argv[3])  # H/cc
    else:
        omega_m0 = float(sys.argv[1])
        omega_b = 0.045
        h = float(sys.argv[2])
        boxsize = float(sys.argv[3])  # Mpc/h
        lgridmin = int(sys.argv[4])
예제 #15
0
# careful sometimes i used "density" (e.g., resample.py), see
# resample_fields.py to make sure
density     = f["rho"].value
H2          = f["H2"].value
Pressure    = f["P"].value
P_nt        = f["P_nt"].value
metallicity = f["Z"].value
velx        = f["vel_x"].value
vely        = f["vel_y"].value
velz        = f["vel_z"].value


import pymses
from pymses.utils import constants as C

ro = pymses.RamsesOutput("output", snapshot_num)

from io_modules.manipulate_fetch_gal_fields import get_units
factor_density = get_units(ro=ro)['rho'][0]      # 1/cm^3 (not H/cm^3)
density *= factor_density
print density.max()

factor_vel = get_units(ro=ro)['vel'][0]
velx *= factor_vel
vely *= factor_vel
velz *= factor_vel
print velx.max(), vely.max(), velz.max()

factor_P = get_units(ro=ro)['P'][0]
Pressure *= factor_P
P_nt *= factor_P
예제 #16
0
path_2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Integrale_valeurs_absolues_moments_cinetiques_output_1_102_par_densite_normalise.fits'

path_simu = '/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr2/'
num_min = 1
num_max = 102

class_rho = np.array([1e-21, 1e-18, 1e-15, 1e-12, 1e-9, 1e-6])

#---------------------------
#Calcul de l'abscisse en Myr
#---------------------------
nmbr_output = num_max - num_min + 1
simulation_time = np.zeros(nmbr_output)

for l in range(nmbr_output):
    ro = pymses.RamsesOutput(path_simu, l + 1)
    factor_time_Myr = ro.info['unit_time'].express(cst.Myr)
    simulation_time[l] = ro.info['time'] * factor_time_Myr

#--------------------------
#Ouverture de la sauvegarde
#--------------------------
J_tot_tab = fits.open(path_1)[0].data
J_abs_tot_tab = fits.open(path_2)[0].data

#------------------
#Debut de la figure
#------------------
plt.clf()
#output_tab = np.linspace(num_min,num_max, num_max-num_min+1
예제 #17
0
        data = pickle.load(f)

    center = data[str(ssnum)]['center_init']
    region_size = [data[str(ssnum)]['size']
                   ]  # subregion inside which we extracted, in code unit

    camera = {'center': center, 'region_size': region_size}

    loc_vec = ds['loc_vector']
    level_vec = ds['level']
    epoch_vec = ds['epoch']
    id_vec = ds['id']
    mass_vec = ds['mass']
    vel_vec = ds['vel']

    # hard-coded for testing
    amrfile = '../snapshot' + str(
        ssnum) + '_center_fields0123456-15_resampled.h5'
    import h5py
    f = h5py.File(amrfile, "r")
    N = f['rho'].shape[0]

    import pymses
    ro = pymses.RamsesOutput("../output", ssnum)

    # resample star particle mass and compute mass-weighted avg epoch correspondingly
    resample_star_mass_age(loc_vec, level_vec, epoch_vec, mass_vec, vel_vec, outname, camera, old_dt_myr=100., \
                           young_dt_myr=10., ro_in=ro, Nrefined=N, debug=True)

# ------
예제 #18
0
def oneOutput(output):
    global prevpos
    outputn = int(output.split('_')[-1])

    # Load ramses output
    r = pymses.RamsesOutput(ramsesdir, outputn, verbose=False)

    nbin = 2**7  # int(np.sqrt(map.map.shape[0]))
    percell = 50./4
    vmin = 0
    vmax = 4

    def saveAndNotify(fname):
        plt.savefig(fname)  # , dpi=120)
        # print(fname)

    plt.clf()
    ##########################################
    # Gas
    ##########################################
    # Get AMR field
    vx_op = ScalarOperator(lambda dset: dset["vel"][:, 0],
                           r.info["unit_density"])
    vy_op = ScalarOperator(lambda dset: dset["vel"][:, 1],
                           r.info["unit_density"])
    rho_op = ScalarOperator(lambda dset: dset["rho"], r.info["unit_density"])
    amr = r.amr_source(['rho', 'vel'])
    rhomap = SliceMap(amr, cam, rho_op, use_multiprocessing=False)
    vxmap = SliceMap(amr, cam, vx_op, use_multiprocessing=False)
    vymap = SliceMap(amr, cam, vy_op, use_multiprocessing=False)
    lvlmap = SliceMap(amr, cam, MaxLevelOperator(), use_multiprocessing=False)

    # Plot
    plt.subplot(122)
    plt.title('Gas map')

    plt.imshow(rhomap.map.T[::-1],
               extent=(0, 1, 0, 1),
               aspect='auto',
               vmin=vmin, vmax=vmax,
               cmap='viridis')
    cb = plt.colorbar()
    cb.set_label(u'Density [g.cm³]')

    # Velocity map
    xx = np.linspace(0, 1, vxmap.map.shape[0])
    yy = np.linspace(0, 1, vxmap.map.shape[1])
    xs = ys = 8
    plt.quiver(xx[::xs], yy[::ys],
               vxmap.map.T[::xs, ::ys], vymap.map.T[::xs, ::ys],
               angles='xy',
               scale=70, scale_units='xy')
    if args.zoom:
        plt.xlim(0.4, 0.6)
    else:
        plt.xlim(0, 1)

    plt.ylim(0, 1)

    ##########################################
    # Particles
    ##########################################
    # Get them
    _, pos, vel, mass, lvl, cpus = read_output(output)
    if prevpos is None:
        prevpos = pos.copy()

    # Select 1024 random particles
    strain = max(pos.shape[1] // (1024), 1)

    # Estimate displacement
    x, y = pos[0:2, ::strain]
    vx, vy = (pos[0:2, ::strain] - prevpos[0:2, ::strain])
    prevpos = pos.copy()

    # Projecting on grid
    strain2 = 1
    hist_pt, epx, epy = np.histogram2d(pos[0, ::strain2], pos[1, ::strain2],
                                       range=[[0, 1], [0, 1]],
                                       bins=nbin)
    # Plot everything

    plt.subplot(121)
    plt.title('Particles')
    plt.pcolormesh(epx, epy, hist_pt.T/percell,
                   cmap='viridis', vmin=vmin, vmax=vmax)
    cb = plt.colorbar()
    cb.set_label('density')

    plt.quiver(x, y, vx, vy,
               scale_units='xy', scale=5, angles='xy', color='white')

    # Plot lvl contours (if need be)
    ncontours = np.ptp(lvlmap.map)
    if ncontours > 0:
        plt.contour(lvlmap.map.T,
                    extent=(epx[0], epx[-1], epy[0], epy[-1]),
                    levels=np.linspace(lvlmap.map.min()+0.5,
                                       lvlmap.map.max()-0.5,
                                       ncontours),
                    alpha=1)

    if args.zoom:
        plt.xlim(0.4, 0.6)
    else:
        plt.xlim(0, 1)

    plt.ylim(0, 1)

    plt.suptitle('$t=%.3f$' % r.info['time'])

    ##########################################
    # Store images
    ##########################################
    outputn = int(output.split('_')[-1])
    fname = pjoin(prefix, 'density_{:0>5}_{}.{}'.format(
        outputn, now.strftime('%Hh%M_%d-%m-%y'), ext))

    saveAndNotify(fname)

    return pos
if owner == 'averliat':
    path = '/mnt/magmist/magmist/simu_B335_averliat/' + simu + '/'
if owner == 'phennebe':
    path = '/drf/projets/capucine/' + owner + '/' + simu + '/'
if owner == 'sapanais':
    path = '/dsm/anais/storageA/magmist/' + simu + '/'
if owner == 'averliat_alfven':
    path = '/drf/projets/alfven-data/averliat/' + simu + '/'

#path_save='/home/averliat/these/analyses/'+simu+'/'+dir_save+'/'
path_analyse = '/home/averliat/these/analyses/' + simu + '/'

#-------------------
#Lecture de l'output
#-------------------
ro = pymses.RamsesOutput(path, output)
lbox_pc = ro.info['unit_length'].express(cst.pc)

amr = ro.amr_source(["rho", "vel", "P", "phi", "g"])

cell_source = CellsToPoints(amr)
cells = cell_source.flatten(verbose=False)
dx = cells.get_sizes()

pos = cells.points
vel = cells["vel"]
rho = cells["rho"]

#------------------------------
#Conversion en unites physiques
#------------------------------
예제 #20
0
def pdf_to_singledisc_rad(path,
                          num,
                          path_out=None,
                          force=False,
                          ps=False,
                          xmin=0,
                          xmax=1.,
                          ymin=0,
                          ymax=1.,
                          zmin=0.,
                          zmax=1.,
                          tag='',
                          order='<',
                          do_plot=False):

    print(num)

    #get the mass weighted density prob density function
    hist_logrho, hist_rho_edges = get_rhopdf(path,
                                             num,
                                             path_out=path_out,
                                             force=force,
                                             ps=ps,
                                             xmin=xmin,
                                             xmax=xmax,
                                             ymin=ymin,
                                             ymax=ymax,
                                             zmin=zmin,
                                             zmax=zmax,
                                             tag=tag,
                                             order=order,
                                             do_plot=do_plot)

    nbin = len(hist_logrho)

    mask_min = hist_rho_edges[0:nbin] > 8.
    mask_max = hist_rho_edges[0:nbin] < 11.

    mask = mask_min * mask_max

    amin = np.argmin(hist_logrho[mask])

    #density at the disk edge
    log_rho_disk = hist_rho_edges[0:nbin][mask][amin]

    print 'log_rho_disk', log_rho_disk

    #    pdb.set_trace() # debug mode

    ro = pymses.RamsesOutput(path, num)
    lbox = ro.info['boxlen']  #boxlen in codeunits (=>pc)

    AU, pc, Ms, Myr, scale_n, scale_d, scale_t, scale_l, scale_v, scale_T2, scale_ener, scale_mag, microG, km_s, Cwnm, scale_mass, unit_col, lbox_pc = me.normalisation_averliat(
        ro)

    time = ro.info['time'] * scale_t / Myr

    amr = ro.amr_source(["rho", "vel", "Br"])

    cell_source = CellsToPoints(amr)
    cells = cell_source.flatten()
    dx = cells.get_sizes()

    pos = cells.points

    #cells belonging to the disk
    mask_rho_disk = np.log10(cells['rho']) > log_rho_disk

    print 'disk cell number', np.sum(mask_rho_disk)

    #mean magnetic field in the whole selected region
    mrd = mask_rho_disk

    #volume of the selected region
    vol = np.sum(dx[mrd]**3)

    mag_mean_broad = np.sum(
        np.sqrt((cells['Br'][:, 0][mrd]**2 + cells['Br'][:, 1][mrd]**2 +
                 cells['Br'][:, 2][mrd]**2)) * dx[mrd]**3) / vol

    #normalise it in cgs
    mag_mean_broad = mag_mean_broad * scale_mag

    #maximum density cell
    mask_rho_max = cells['rho'] == np.max(cells['rho'])

    #mass disk
    mass_disk = np.sum(dx[mask_rho_disk]**3 * cells['rho'][mask_rho_disk])
    mass_disk = mass_disk * scale_mass / Ms

    #position of maximum density cell
    pos_max_x = pos[:, 0][mask_rho_max][0]
    pos_max_y = pos[:, 1][mask_rho_max][0]
    pos_max_z = pos[:, 2][mask_rho_max][0]

    #position of disk cell
    pos_disk_x = pos[:, 0][mask_rho_disk] - pos_max_x
    pos_disk_y = pos[:, 1][mask_rho_disk] - pos_max_y
    pos_disk_z = pos[:, 2][mask_rho_disk] - pos_max_z

    #position of maximum density cell
    vel_max_x = cells['vel'][:, 0][mask_rho_max][0]
    vel_max_y = cells['vel'][:, 1][mask_rho_max][0]
    vel_max_z = cells['vel'][:, 2][mask_rho_max][0]

    #position of disk cell
    vel_disk_x = cells['vel'][:, 0][mask_rho_disk] - vel_max_x
    vel_disk_y = cells['vel'][:, 1][mask_rho_disk] - vel_max_y
    vel_disk_z = cells['vel'][:, 2][mask_rho_disk] - vel_max_z

    #radial component of V
    norm_pos = np.sqrt(pos_disk_x**2 + pos_disk_y**2 + pos_disk_z**2)
    mask = norm_pos == 0.
    norm_pos[mask] = 1.e-10
    Vrad = (vel_disk_x * pos_disk_x + vel_disk_y * pos_disk_y +
            vel_disk_z * pos_disk_z) / norm_pos

    #non radial component of V
    Vpar_x = (vel_disk_z * pos_disk_y - vel_disk_y * pos_disk_z) / norm_pos
    Vpar_y = (vel_disk_x * pos_disk_z - vel_disk_z * pos_disk_x) / norm_pos
    Vpar_z = (vel_disk_y * pos_disk_x - vel_disk_x * pos_disk_y) / norm_pos
    Vpar = np.sqrt(Vpar_x**2 + Vpar_y**2 + Vpar_z**2)
    Vpar[mask] = 1.e-10

    #now select the point that have a parallel velocity larger than the radial one
    mask = (-Vrad) / Vpar < 0.5

    if (np.sum(mask) <= 1):
        return time, 0., 0., 0., 0., log_rho_disk, mag_mean_broad, 0., 0.  #, max_rad_disk, mean_rad_disk, mean_out_rad_disk

    pos_disk_x = pos_disk_x[mask]
    pos_disk_y = pos_disk_y[mask]
    pos_disk_z = pos_disk_z[mask]

    vel_disk_x = vel_disk_x[mask]
    vel_disk_y = vel_disk_y[mask]
    vel_disk_z = vel_disk_z[mask]

    #    print 'sum mask',np.sum(mask),len(pos_disk_x)

    #determine the direction of the mean angular momentum
    Jx = np.mean(pos_disk_y * vel_disk_z - pos_disk_z * vel_disk_y)
    Jy = np.mean(pos_disk_z * vel_disk_x - pos_disk_x * vel_disk_z)
    Jz = np.mean(pos_disk_x * vel_disk_y - pos_disk_y * vel_disk_x)

    Jnorm = np.sqrt(Jx**2 + Jy**2 + Jz**2)
    Jx = Jx / Jnorm
    Jy = Jy / Jnorm
    Jz = Jz / Jnorm

    #project the radial vector in the disk plane
    Jpos = Jx * pos_disk_x + Jy * pos_disk_y + Jz * pos_disk_z
    pos_dpl_x = pos_disk_x - Jpos * Jx
    pos_dpl_y = pos_disk_y - Jpos * Jy
    pos_dpl_z = pos_disk_z - Jpos * Jz

    if (pos_dpl_x[0]**2 + pos_dpl_x[1]**2 + pos_dpl_x[2]**2 != 0.):
        pos_x = pos_dpl_x[0]
        pos_y = pos_dpl_y[0]
        pos_z = pos_dpl_z[0]
    else:
        pos_x = pos_dpl_x[1]
        pos_y = pos_dpl_y[1]
        pos_z = pos_dpl_z[1]

    #calculate the cosinus
    cos_pos = (pos_dpl_x * pos_x + pos_dpl_y * pos_y + pos_dpl_z * pos_z)

    mask = pos_dpl_x * pos_dpl_x + pos_dpl_y * pos_dpl_y + pos_dpl_z * pos_dpl_z > 0.

    cos_pos = cos_pos / np.sqrt(pos_x * pos_x + pos_y * pos_y + pos_z * pos_z)
    cos_pos[mask] = cos_pos[mask] / np.sqrt(pos_dpl_x * pos_dpl_x +
                                            pos_dpl_y * pos_dpl_y +
                                            pos_dpl_z * pos_dpl_z)[mask]

    #radius of disk cells
    #    rad_disk = np.sqrt( (pos_disk[:,0]-pos_max_x)**2 + (pos_disk[:,1]-pos_max_y)**2 + (pos_disk[:,2]-pos_max_z)**2 )
    rad_disk = np.sqrt((pos_disk_x)**2 + (pos_disk_y)**2 + (pos_disk_z)**2)

    #mean disk radius
    mean_rad_disk = np.mean(rad_disk)
    median_rad_disk = np.median(rad_disk)

    arg_d = np.argsort(rad_disk)

    ndisk = len(arg_d)

    print 'ndisk', ndisk

    mask_out_disk = arg_d[np.int(ndisk * 0.9):ndisk - 1]

    #mean radius of the 90% point having higher radius
    mean_out_rad_disk = np.mean(rad_disk[mask_out_disk])

    #now look at the maximum in a series of direction
    ndir = 500
    rad_loc_v = np.zeros(ndir)
    cos_min = -1.
    cos_max = cos_min + 2. / (ndir + 1)
    for ld in range(ndir):

        mask1 = cos_pos >= cos_min
        mask2 = cos_pos < cos_max
        mask = mask1 * mask2

        print 'len mask, sum mask', len(mask), np.sum(mask)

        if (np.sum(mask) != 0):
            #            pdb.set_trace()
            rad_loc_v[ld] = np.max(rad_disk[mask])
        else:
            rad_loc_v[ld] = 0.

        cos_min = cos_min + 2. / (ndir + 1)
        cos_max = cos_max + 2. / (ndir + 1)

    max_rad_loc = np.max(
        rad_loc_v[rad_loc_v < 500 / lbox / pc * AU]) * lbox * pc / AU

    min_rad_loc = np.min(
        rad_loc_v[rad_loc_v < 500 / lbox / pc * AU]) * lbox * pc / AU

    mean_rad_loc = np.mean(
        rad_loc_v[rad_loc_v < 500 / lbox / pc * AU]) * lbox * pc / AU

    median_rad_loc = np.median(
        rad_loc_v[rad_loc_v < 500 / lbox / pc * AU]) * lbox * pc / AU

    #--------------------------
    #Ajout par AV pour essayer de mieux estimer la taille des disques
    rad_loc_v = rad_loc_v * lbox * pc / AU  #listes des rayons en AU

    taille_bin = 4  #AU
    largeur_modale = 2

    min_serie = np.floor(np.min(rad_loc_v))
    min_serie -= min_serie % taille_bin
    max_serie = np.floor(np.max(rad_loc_v)) + 1
    max_serie += (taille_bin - max_serie % taille_bin)

    nbr_bin = (max_serie - min_serie) / taille_bin
    bins = np.arange(nbr_bin) * taille_bin + min_serie + taille_bin / 2.

    count = np.zeros(len(bins))

    for i in range(len(rad_loc_v)):
        ind = np.int(np.floor((rad_loc_v[i] - min_serie) / taille_bin))
        count[ind] += 1

    bin_central = bins[np.argmax(count)]
    lim_inf = bin_central - taille_bin / 2. - largeur_modale * taille_bin
    lim_sup = bin_central + taille_bin / 2. + largeur_modale * taille_bin

    rad_new = rad_loc_v[rad_loc_v > lim_inf]
    rad_new = rad_new[rad_new < lim_sup]

    rad_estim = np.median(rad_new)
    #--------------------------

    mean_rad_disk = mean_rad_disk * lbox * pc / AU

    mean_out_rad_disk = mean_out_rad_disk * lbox * pc / AU

    #    pdb.set_trace() # debug mode

    return time, mass_disk, max_rad_loc, min_rad_loc, mean_rad_loc, log_rho_disk, mag_mean_broad, median_rad_loc, rad_estim  #, max_rad_disk, mean_rad_disk, mean_out_rad_disk
예제 #21
0
파일: test_DoG.py 프로젝트: astro313/mc_eor
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import h5py

f = h5py.File("snapshot28_center_densityfield_resampled.h5", "r")
density = f["density"].value

# convert from code unit density to g/cc (depending on how fetch_gal.py is implemented.)
convert_unit = True

if convert_unit:
    import pymses
    from pymses.utils import constants as C

    ro = pymses.RamsesOutput("output", 28)
    factor = ro.info["unit_density"].express(C.H_cc)
    density *= factor
    print density.max()


from skimage.feature import blob_dog
# blobs are assumed to be light on dark background

# min_sigma = 1     # keep it low for smaller blobs
# max_sigma =       # keep it high to detect large blobs
# sigma_ratio =     # ratio btw the stddev of Gaussian Kernels used.
# overlap = 0.8     # between 0 and 1; if the area of two blobs overlaps by a fraction > this, smaller blob is eliminated.

# For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob.
_max = density.max()
예제 #22
0
def get_rhopdf(path_in,
               num,
               path_out=None,
               force=False,
               ps=False,
               xmin=0,
               xmax=1.,
               ymin=0,
               ymax=1.,
               zmin=0.,
               zmax=1.,
               tag='',
               order='<',
               do_plot=False):

    if (path_out is not None):
        directory_out = path_out
    else:
        directory_out = path_in

    if (tag != ''):
        tag = tag + '_'

    name_save_pdf = directory_out + 'pdf_' + tag + str(num).zfill(5) + '.save'

    #a list of dictionnary to describe the plots
    list_plot = []

    ro = pymses.RamsesOutput(path_in, num, order=order)

    lbox = ro.info['boxlen']  #boxlen in codeunits (=>pc)

    amr = ro.amr_source(["rho"])

    cell_source = CellsToPoints(amr)
    cells = cell_source.flatten()
    dx = cells.get_sizes()

    mask1 = cells.points[:, 0] > xmin
    mask2 = cells.points[:, 0] < xmax
    mask3 = cells.points[:, 1] > ymin
    mask4 = cells.points[:, 1] < ymax
    mask5 = cells.points[:, 2] > zmin
    mask6 = cells.points[:, 2] < zmax
    mask = mask1 * mask2 * mask3 * mask4 * mask5 * mask6

    AU, pc, Ms, Myr, scale_n, scale_d, scale_t, scale_l, scale_v, scale_T2, scale_ener, scale_mag, microG, km_s, Cwnm, scale_mass, unit_col, lbox_pc = me.normalisation_averliat(
        ro)

    vol = dx**3
    mass = cells["rho"] * vol * scale_mass / Ms

    log_rho = np.log10(cells['rho'])
    log_min = min(log_rho)
    log_max = max(log_rho)
    nbin = 50
    width = (log_max - log_min) / nbin

    hist_logrho, hist_rho_edges = P.histogram(log_rho[mask],
                                              bins=nbin,
                                              range=(log_min, log_max),
                                              weights=mass[mask])
    #    pdf_logrho , histrhomv_edges = P.histogram(log_rho[mask],bins=nbin,range=(log_min,log_max),weights=vol[mask])

    if (do_plot):
        #mass weighted histogram of density
        P.clf()
        P.bar(hist_rho_edges[:-1],
              np.log10(hist_logrho) + 3.,
              width,
              -3.,
              color='none',
              edgecolor='k')

        xlabel = '$log(n)$ (cm$^{-3}$)'
        ylabel = '$log(M)$ (M$_\odot$)'

        P.xlabel(r'$log(n)$ (cm$^{-3}$)')
        P.ylabel(r'$log(M)$ (M$_\odot$)')

        name_im = directory_out + 'pdfmw_logrho_bd_' + tag + str(num).zfill(5)

        P.savefig(name_im + '.ps')
        P.savefig(name_im + '.png')

    return hist_logrho, hist_rho_edges
예제 #23
0
def myplot(path='.',output=-1,sink=False,center=[0.5,0.5,0.5],los='x',size=[0.5,0.5], \
           minimum=None,maximum=None,typlot='rho',record=False,igrp=-1,plot_velocity=False,slice=False):

    filerep = path
    if (record):
        savedir = os.path.join(filerep, "results")
        if not os.path.exists(savedir):
            os.makedirs(savedir)
        #mu,alpha,lmax = parseDirSink(directory)
        #savedir       = checkDir(savedir, "mu" + mu)
        #savedir       = checkDir(savedir, "lmax" + lmax)

    # if output=-1, take last output
    if output == -1:
        outputname = np.sort(glob.glob(os.path.join(filerep,
                                                    "output_?????")))[-1]
        output = int(outputname.split('_')[-1])

    # Define the file
    ro = pm.RamsesOutput(filerep, output)

    if igrp != -1 and (igrp > ro.info["ngrp"] or igrp < 0):
        print(bold + 'PROBLEM:' + reset + ' igrp=' + str(igrp) +
              '  but simulation with ngrp=' + str(ro.info["ngrp"]))
        sys.exit(1)

    # Define the output data structure (to use with pymses5)
    ro.define_amr_scalar_field("hydro", "rho", 0)
    ro.define_amr_vector_field("hydro", "vel", [1, 2, 3])
    ro.define_amr_vector_field("hydro", "Bl", [4, 5, 6])
    ro.define_amr_vector_field("hydro", "Br", [7, 8, 9])
    ro.define_amr_scalar_field("hydro", "P", 10)
    ro.define_amr_multivalued_field("hydro", "Er", 11, ro.info["ngrp"])
    ro.define_amr_vector_field(
        "hydro", "J",
        [11 + ro.info["ngrp"], 12 + ro.info["ngrp"], 13 + ro.info["ngrp"]])
    ro.define_amr_scalar_field("hydro", "eint", 14 + ro.info["ngrp"])
    if ro.info["eos"]:
        ro.define_amr_scalar_field("hydro", "T", 15 + ro.info["ngrp"])
    ro.define_amr_vector_field("grav", "g", [0, 1, 2])

    time = ro.info["time"] * ro.info["unit_time"].express(ct.kyr)
    if (sink):
        # Read sink particles
        sink_filename = os.path.join(
            filerep, 'output_%05d' % output + '/sink_%05d' % output + '.csv')
        print("Reading sinks     : " + reset + sink_filename)
        sinkp = np.loadtxt(sink_filename,
                           dtype={
                               'names':
                               ('Id', 'mass', 'x', 'y', 'z', 'vx', 'vy', 'vz',
                                'rot_period', 'lx', 'ly', 'lz', 'acc_rate',
                                'acc_lum', 'age', 'int_lum', 'Teff'),
                               'formats':
                               ('i', 'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f',
                                'f', 'f', 'f', 'f', 'f', 'f', 'f', 'f')
                           },
                           delimiter=',')
        sinkp = np.atleast_1d(sinkp)  # to work even if only 1 sink
        nsink = sinkp.size

        # Define the accretion radius
        if ("ncell_racc" in ro.info):
            ncell_racc = ro.info['ncell_racc']
        else:
            ncell_racc = 4

        dxmin = 0.5**ro.info['levelmax'] * ro.info["unit_length"].express(
            ct.au)
        r_acc = dxmin * ncell_racc
        #area  = np.pi*r_acc**2

        xc, yc, zc = sinkp['x'] / ro.info['boxlen'], sinkp['y'] / ro.info[
            'boxlen'], sinkp['z'] / ro.info['boxlen']
    else:
        nsink = 0

    if nsink == 0:
        nsink = 1
        # Center
        xc, yc, zc = np.atleast_1d(center[0]), np.atleast_1d(
            center[1]), np.atleast_1d(center[2])

    cmap = pl.cm.get_cmap('seismic', 100)
    if typlot == 'rho':
        cmap = pl.cm.get_cmap('jet', 100)
    elif typlot == 'Tr':
        cmap = pl.cm.get_cmap('hot', 100)
    elif typlot == 'B':
        cmap = pl.cm.get_cmap('PuOr', 100)
    elif typlot == 'beta_plasma':
        cmap = pl.cm.get_cmap('seismic', 100)
    else:
        cmap = pl.cm.get_cmap('jet', 100)

    # Width of the region to plot
    xr, yr = size[0], size[1]
    xbl = (-xr / 2. * ro.info["unit_length"]).express(ct.au)
    xbr = (+xr / 2. * ro.info["unit_length"]).express(ct.au)
    ybl = (-yr / 2. * ro.info["unit_length"]).express(ct.au)
    ybr = (+yr / 2. * ro.info["unit_length"]).express(ct.au)
    extent = [xbl, xbr, ybl, ybr]

    # Define camera
    if los == 'x':
        upvec = "z"
        vx = 1
        vy = 2
        labelx = 'Y (AU)'
        labely = 'Z (AU)'
        plane = 'yz'
    elif los == 'y':
        upvec = "x"
        vx = 2
        vy = 0
        labelx = 'Z (AU)'
        labely = 'X (AU)'
        plane = 'zx'
    elif los == 'z':
        upvec = "y"
        vx = 0
        vy = 1
        labelx = 'X (AU)'
        labely = 'Y (AU)'
        plane = 'xy'

    def plot_func(dset):
        if typlot == 'rho':
            return dset['rho'] * ro.info["unit_density"].express(
                ct.g / ct.cm**3)
        if typlot == 'eint':
            return dset['eint'] * (ro.info["unit_density"] *
                                   ro.info["unit_velocity"]**2).express(
                                       ct.erg / ct.cm**3)
        if typlot == 'T':
            if ro.info["eos"]:
                return dset['T']
            else:
                return dset['P'] / dset['rho'] * ro.info[
                    "unit_temperature"].express(ct.K) * ro.info["mu_gas"]
        if typlot == 'B':
            B = 1./4*( (dset['Bl'][:,0]+dset['Br'][:,0])**2  \
                      +(dset['Bl'][:,1]+dset['Br'][:,1])**2  \
                      +(dset['Bl'][:,2]+dset['Br'][:,2])**2)
            return B
        # To use with pymses5
        if typlot == 'Er' or typlot == 'Tr':
            if igrp == -1:
                Er = np.sum(dset['Er'], axis=-1) * (
                    ro.info["unit_density"] *
                    ro.info["unit_velocity"]**2).express(ct.erg / ct.cm**3)
            else:
                Er = dset['Er'][:, igrp - 1] * (
                    ro.info["unit_density"] *
                    ro.info["unit_velocity"]**2).express(ct.erg / ct.cm**3)

            if typlot == 'Er':
                return Er
            else:
                return (Er / ct.a_R.express(ct.erg / ct.cm**3 / ct.K**4))**0.25

        if typlot == 'entropy':
            return dset['P'] / dset['rho']**ro.hydro_info["gamma"]

        if typlot == 'Pth_Pdyn':
            return dset['P'] / (0.5 * dset['rho'] *
                                np.sum(dset['vel']**2, axis=-1))

        if typlot == 'beta_plasma':
            B = 1./4.*( (dset['Bl'][:,0]+dset['Br'][:,0])**2  \
                      +(dset['Bl'][:,1]+dset['Br'][:,1])**2  \
                      +(dset['Bl'][:,2]+dset['Br'][:,2])**2)
            if igrp == -1:
                Er = np.sum(
                    dset['Er'], axis=-1
                )  #*(ro.info["unit_density"]*ro.info["unit_velocity"]**2).express(ct.erg/ct.cm**3)
            else:
                Er = dset[
                    'Er'][:, igrp -
                          1]  #*(ro.info["unit_density"]*ro.info["unit_velocity"]**2).express(ct.erg/ct.cm**3)

            return dset['P'] / (B)  #/dset['rho'])

        else:
            print(bold + 'Problem in typlot')
            sys.exit()

    # Fields to be read
    fields_to_read = []
    if (not ro.info["eos"] and typlot == 'T') or typlot == 'entropy':
        fields_to_read = ["rho", "P"]
    elif typlot == 'Tr':
        fields_to_read = ["Er"]
    elif typlot == 'Pth_Pdyn':
        fields_to_read = ["P", "rho", "vel"]
    elif typlot == 'B':
        fields_to_read = ["Bl", "Br"]
    elif typlot == 'beta_plasma':
        fields_to_read = ["Bl", "Br", "rho", "P", "Er"]
    else:
        fields_to_read = [typlot]
    if (plot_velocity):
        fields_to_read.append("vel")
    if not slice:
        fields_to_read.append("rho")

    fields_to_read = list(set(fields_to_read))  #to remove duplicates

    if slice:
        source = ro.amr_source(fields_to_read)
        varplot_op = ScalarOperator(plot_func)
    else:
        rt = raytracing.RayTracer(ro, fields_to_read)

        if typlot == 'rho':
            func = lambda dset: plot_func(dset) * ro.info["unit_length"
                                                          ].express(ct.cm)
            varplot_op = ScalarOperator(func)
        else:
            up_func = lambda dset: (dset["rho"] * ro.info["unit_density"].
                                    express(ct.g / ct.cm**3) * plot_func(dset))
            down_func = lambda dset: (dset["rho"] * ro.info["unit_density"].
                                      express(ct.g / ct.cm**3))
            varplot_op = FractionOperator(up_func, down_func)

    for i in range(nsink):
        fig = pl.figure()
        ax = pl.subplot(111)

        pl.xlabel(labelx)
        pl.ylabel(labely)

        cam = Camera(center=[xc[i], yc[i], zc[i]],line_of_sight_axis=los,region_size=[xr, yr] \
                         , up_vector=upvec,map_max_size=512, log_sensitive=True)

        if slice:
            mapx = SliceMap(source, cam, varplot_op, z=0.)
        else:
            # WARNING! surf_qty=True to get an integral over dz and not dSdz
            # so that if typlot=='rho', get surface density map
            # and if not, get a density-weighted map (and not a mass-weighted map)
            mapx = rt.process(varplot_op, cam, surf_qty=True)

        if typlot == 'Pth_Pdyn':
            imx    = pl.imshow(mapx.transpose(), extent = extent, origin='lower' \
                                   , vmin = minimum, vmax = maximum,cmap=cmap)
            #imx    = pl.contourf(mapx.transpose(), extent = extent, origin='lower' \
            #                       , vmin = minimum, vmax = maximum)
            cbar = pl.colorbar()
            cbar.set_label(typlot)
        else:
            imx    = pl.imshow(np.log10(mapx.transpose()), extent = extent, origin='lower' \
                                   , vmin = minimum, vmax = maximum,cmap=cmap)
            #imx    = pl.contourf(np.log10(mapx.transpose()), extent = extent, origin='lower' \
            #                       , vmin = minimum, vmax = maximum)
            cbar = pl.colorbar()

            #            cmap = pl.cm.get_cmap('jet',100)

            if typlot == 'rho':
                cbar.set_label(r'$\mathrm{log(}\rho)$', fontsize=15)
            elif typlot == 'Tr':
                cbar.set_label(r'$\mathrm{log(T_r)}$', fontsize=15)
            elif typlot == 'Pth_Pdyn':
                cbar.set_label('Pth/Pdyn')
            elif typlot == 'B':
                cbar.set_label('log(|B|)')
            elif typlot == 'beta_plasma':
                cbar.set_label(r'$\mathrm{log(}\beta)$', fontsize=15)
            else:
                cbar.set_label('Log(' + typlot + ')')

        if (sink):
            for isink in range(nsink):
                # Plot sinks position
                mass = sinkp[isink]["mass"]
                col = cmap(int(mass * 100))
                xp = (sinkp[isink]['x'] / ro.info['boxlen'] -
                      xc[i]) * ro.info["unit_length"].express(ct.au)
                yp = (sinkp[isink]['y'] / ro.info['boxlen'] -
                      yc[i]) * ro.info["unit_length"].express(ct.au)
                zp = (sinkp[isink]['z'] / ro.info['boxlen'] -
                      zc[i]) * ro.info["unit_length"].express(ct.au)

                if los == 'x':
                    ax.add_patch(
                        pl.Circle((yp, zp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((yp, zp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(yp,zp,'k+',mew=2,ms=10)
                elif los == 'y':
                    ax.add_patch(
                        pl.Circle((zp, xp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((zp, xp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(zp,xp,'k+',mew=2,ms=10)
                elif los == 'z':
                    ax.add_patch(
                        pl.Circle((xp, yp),
                                  radius=r_acc,
                                  fc='white',
                                  alpha=0.65))
                    ax.add_patch(
                        pl.Circle((xp, yp),
                                  radius=(r_acc / ncell_racc),
                                  fc=col,
                                  ec=col))
                #pl.plot(xp,yp,'k+',mew=2,ms=10)

        # Plot velocity field
        if (slice and plot_velocity):
            p = cam.get_slice_points(0.0)
            nx, ny = cam.get_map_size()
            dset = pm.analysis.sample_points(source, p)
            vel = dset["vel"] * ro.info["unit_velocity"].express(ct.km / ct.s)
            rs = 32
            x = np.linspace(xbl, xbr, nx)
            y = np.linspace(ybl, ybr, ny)
            u, v = np.zeros((nx, ny)), np.zeros((nx, ny))
            mask = np.zeros((nx, ny))
            for ii in range(nx):
                for jj in range(ny):
                    if (ii % rs == 0 and jj % rs == 0):
                        u[ii, jj] = vel[:, vx].reshape(nx, ny)[ii, jj]
                        v[ii, jj] = vel[:, vy].reshape(nx, ny)[ii, jj]
                    else:
                        u[ii, jj] = 'Inf'
                        v[ii, jj] = 'Inf'
                        mask[ii, jj] = 1

            u2 = u[::rs, ::rs]
            v2 = v[::rs, ::rs]
            x2 = x[::rs]
            y2 = y[::rs]

            vel_mean = np.mean(np.sqrt(u2**2 + v2**2))
            vel_max = np.max(np.sqrt(u2**2 + v2**2))

            #pl.quiver(x,y,u.transpose(),v.transpose(),scale=20*nx)
            #Q=pl.quiver(x,y,u.transpose(),v.transpose(),scale=100,pivot='mid')
            #u_masked=np.ma.masked_array(u,mask=mask)
            #v_masked=np.ma.masked_array(v,mask=mask)
            #vel_mean=np.mean(np.sqrt(u_masked**2+v_masked**2))

            Q = pl.quiver(x2,
                          y2,
                          u2.transpose(),
                          v2.transpose(),
                          scale=100,
                          pivot='mid')
            #pl.quiverkey(Q,0.7,0.92,vel_mean,r'%.2f km/s'%vel_mean,coordinates='figure')
            pl.quiverkey(Q,
                         0.7,
                         0.92,
                         vel_max,
                         r'%.2f km/s' % vel_max,
                         coordinates='figure')
            pl.axis(extent)
            del (u, v, x, y, u2, v2, x2, y2)

            if (sink):
                # Print the mass of the sinks
                mass = 0
                for j in range(nsink):
                    mass = mass + sinkp["mass"][j]

                pl.figtext(0.01,
                           00.01,
                           "$\mathrm{M}_*=$" + "%4.1f " % mass + "$M_\odot$",
                           fontsize=15)

        pl.suptitle("%.3f kyr" % time)

        if (record):
            for format in ("png", "eps", "pdf"):
                if slice:
                    namefig = os.path.join(
                        savedir, "slice_" + typlot + "_" + plane + "_eps" +
                        "_%.3f" % size[0] + "_out" + "_%05d" % output +
                        "_isink_%05d." % sinkp['Id'][i] + format)
                else:
                    namefig = os.path.join(
                        savedir, "proj_" + typlot + "_" + plane + "_eps" +
                        "_%.3f" % size[0] + "_out" + "_%05d" % output +
                        "_isink_%05d." % sinkp['Id'][i] + format)
                print(bold + "Save figure: " + reset + namefig)
                pl.savefig(namefig)
            pl.close()
        else:
            pl.ion()
            pl.show()

    if (sink):
        # Print the mass of the sinks
        for i in range(nsink):
            mass = sinkp["mass"][i]
            print(bold + "Mass(" + str(i) + "): " + reset + "%.2e Msun" % mass)
예제 #24
0
def pdf_to_singledisc_for_plot(path,
                               num,
                               path_out=None,
                               force=False,
                               ps=False,
                               xmin=0,
                               xmax=1.,
                               ymin=0,
                               ymax=1.,
                               zmin=0.,
                               zmax=1.,
                               tag='',
                               order='<',
                               do_plot=False):

    print(num)

    #get the mass weighted density prob density function
    hist_logrho, hist_rho_edges = get_rhopdf(path,
                                             num,
                                             path_out=path_out,
                                             force=force,
                                             ps=ps,
                                             xmin=xmin,
                                             xmax=xmax,
                                             ymin=ymin,
                                             ymax=ymax,
                                             zmin=zmin,
                                             zmax=zmax,
                                             tag=tag,
                                             order=order,
                                             do_plot=do_plot)

    nbin = len(hist_logrho)

    mask_min = hist_rho_edges[0:nbin] > 8.
    mask_max = hist_rho_edges[0:nbin] < 11.

    mask = mask_min * mask_max

    amin = np.argmin(hist_logrho[mask])

    #density at the disk edge
    log_rho_disk = hist_rho_edges[0:nbin][mask][amin]

    print 'log_rho_disk', log_rho_disk

    rho_min_disk = 10**log_rho_disk

    #    pdb.set_trace() # debug mode

    ro = pymses.RamsesOutput(path, num)
    lbox = ro.info['boxlen']  #boxlen in codeunits (=>pc)

    AU, pc, Ms, Myr, scale_n, scale_d, scale_t, scale_l, scale_v, scale_T2, scale_ener, scale_mag, microG, km_s, Cwnm, scale_mass, unit_col, lbox_pc = me.normalisation_averliat(
        ro)

    #time = ro.info['time'] * scale_t / Myr

    amr = ro.amr_source(["rho", "vel"])  #,"Br"])

    cell_source = CellsToPoints(amr)
    cells = cell_source.flatten()
    dx = cells.get_sizes()

    pos = cells.points

    #cells belonging to the disk
    mask_rho_disk = np.log10(cells['rho']) > log_rho_disk

    print 'disk cell number', np.sum(mask_rho_disk)

    #mean magnetic field in the whole selected region
    #mrd=mask_rho_disk

    #volume of the selected region
    #vol = np.sum(dx[mrd]**3)

    #mag_mean_broad=np.sum(np.sqrt((cells['Br'][:,0][mrd]**2+cells['Br'][:,1][mrd]**2+cells['Br'][:,2][mrd]**2))*dx[mrd]**3)/vol

    #normalise it in cgs
    #mag_mean_broad = mag_mean_broad*scale_mag

    #maximum density cell
    mask_rho_max = cells['rho'] == np.max(cells['rho'])

    #mass disk
    #mass_disk = np.sum(dx[mask_rho_disk]**3 * cells['rho'][mask_rho_disk])
    #mass_disk = mass_disk * scale_mass / Ms

    #position of maximum density cell
    pos_max_x = pos[:, 0][mask_rho_max][0]
    pos_max_y = pos[:, 1][mask_rho_max][0]
    pos_max_z = pos[:, 2][mask_rho_max][0]

    #velocity of maximum density cell
    vel_max_x = cells['vel'][:, 0][mask_rho_max][0]
    vel_max_y = cells['vel'][:, 1][mask_rho_max][0]
    vel_max_z = cells['vel'][:, 2][mask_rho_max][0]

    #if(np.sum(mask) <= 1):
    #    return time, 0., 0., 0., 0. , log_rho_disk, mag_mean_broad #, max_rad_disk, mean_rad_disk, mean_out_rad_disk

    #pos_disk_x = pos_disk_x[mask]
    #pos_disk_y = pos_disk_y[mask]
    #pos_disk_z = pos_disk_z[mask]

    #vel_disk_x = vel_disk_x[mask]
    #vel_disk_y = vel_disk_y[mask]
    #vel_disk_z = vel_disk_z[mask]

    #radius of disk cells
    #    rad_disk = np.sqrt( (pos_disk[:,0]-pos_max_x)**2 + (pos_disk[:,1]-pos_max_y)**2 + (pos_disk[:,2]-pos_max_z)**2 )
    #rad_disk = np.sqrt( (pos_disk_x)**2 + (pos_disk_y)**2 + (pos_disk_z)**2 )

    #mean disk radius
    #mean_rad_disk = np.mean(rad_disk)

    return rho_min_disk, pos_max_x, pos_max_y, pos_max_z, vel_max_x, vel_max_y, vel_max_z
path_2_hr2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Integrale_valeurs_absolues_moments_cinetiques_output_1_36.fits'

path_3_hr2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Moment_cinetique_tot_output_1_55_barycentre.fits'
path_4_hr2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Integrale_valeurs_absolues_moments_cinetiques_output_1_55_barycentre.fits'

path_simu_hr2='/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr2/'
num_min_hr2=1
num_max_hr2=36


nmbr_output_hr2 = num_max_hr2-num_min_hr2+1

simulation_time_hr2 = np.zeros(nmbr_output_hr2)

for l in range(nmbr_output_hr2):
	ro=pymses.RamsesOutput(path_simu_hr2,l+1)
	factor_time_hr2_Myr = ro.info['unit_time'].express(cst.Myr)
	simulation_time_hr2[l] = ro.info['time']*factor_time_hr2_Myr



#--------------------------
#Ouverture de la sauvegarde
#--------------------------
J_tot_tab_hr2 = fits.open(path_1_hr2)[0].data[0:nmbr_output_hr2]
J_abs_tot_tab_hr2 = fits.open(path_2_hr2)[0].data[0:nmbr_output_hr2]

J_tot_tab_hr2_barycentre = fits.open(path_3_hr2)[0].data[0:nmbr_output_hr2]
J_abs_tot_tab_hr2_barycentre = fits.open(path_4_hr2)[0].data[0:nmbr_output_hr2]

			path='/gpfs/data1/'+owner+'/'+simu+'/'
		if owner=='phennebe':
			path='/drf/projets/capucine/'+owner+'/'+simu+'/'
		path_save='/gpfs/data1/averliat/analyses/'+simu+'/'


		nbre_output=output_max-output_min+1

		pourcent_mass_core = np.zeros(nbre_output)
		simulation_time = np.zeros(nbre_output)

		output_manquant=0
		for l in range(nbre_output):
			current_output = (l+1)
			try:
				ro=pymses.RamsesOutput(path, current_output)
			except:
				output_manquant += 1
				continue

			#-------------------
			#Lecture de l'output
			#-------------------
			lbox_pc = ro.info['unit_length'].express(cst.pc)

			amr = ro.amr_source(["rho","vel","P","phi","g"])

			cell_source = CellsToPoints(amr)
			cells = cell_source.flatten(verbose=False)
			dx = cells.get_sizes()
예제 #27
0
from optparse import OptionParser

parser = OptionParser()
parser.usage = "%prog ramses_directory ramses_output_number map_max_resolution=512"
(opts, args) = parser.parse_args()
try:
    fileDir = args[0]
    outNumber = int(args[1])
except:
    fileDir = None
    outNumber = None
try:
    mms = int(args[2])
except:
    mms = 512
ro = pymses.RamsesOutput(fileDir, outNumber)
outNumber = ro.iout
source = ro.amr_source(["rho"])
cam = Camera(center=[0.5, 0.5, 0.5],
             line_of_sight_axis='z',
             region_size=[1., 1.],
             up_vector='y',
             distance=0.0,
             far_cut_depth=0.0,
             map_max_size=mms)
op = ScalarOperator(lambda dset: dset["rho"])
from time import time

t0 = time()
# Optional CameraOctreeDatasource creation (may be faster...)
#from pymses.sources.ramses.octree import CameraOctreeDatasource
def masse_dans_coeur_output_unique(simu, owner, num_output, rho_seuil):
	#--------------------------------------------------------------
	#Chemin de la simulation et du dossier de sauvegarde des images
	#--------------------------------------------------------------
	if owner=='averliat':
		path='/gpfs/data1/'+owner+'/'+simu+'/'
	if owner=='phennebe':
		path='/drf/projets/capucine/'+owner+'/'+simu+'/'
	path_save='/gpfs/data1/averliat/analyses/'+simu+'/'



	#-------------------
	#Lecture de l'output
	#-------------------
	ro=pymses.RamsesOutput(path,num_output)
	lbox_pc = ro.info['unit_length'].express(cst.pc)

	amr = ro.amr_source(["rho","vel","P","phi","g"])

	cell_source = CellsToPoints(amr)
	cells = cell_source.flatten(verbose=False)
	dx = cells.get_sizes()

	pos = cells.points
	rho = cells["rho"]



	#------------------------------------------------------------
	#Facteur de conversion des unites de code en unites physiques
	#------------------------------------------------------------
	lbox=ro.info['boxlen']
	lbox_m = ro.info['unit_length'].express(cst.m)
	factor_dist_m = ro.info['unit_length'].express(cst.m)
	factor_dist_cm = ro.info['unit_length'].express(cst.cm)
	lbox_au = ro.info['unit_length'].express(cst.au)
	lbox_cm = ro.info['unit_length'].express(cst.cm)
	factor_time_yr = ro.info['unit_time'].express(cst.year)

	factor_rho_Hcc = ro.info['unit_density'].express(cst.H_cc)
	factor_rho = ro.info['unit_density'].express(cst.kg/(cst.m)**3)



	#------------------------------
	#Conversion en unites physiques
	#------------------------------
	simulation_time = ro.info['time']*factor_time_yr
	dx *= factor_dist_m
	rho_Hcc = rho * factor_rho_Hcc
	rho *= factor_rho



	#---------------------------------------------------------
	#Definition du centre des images et de leur niveau de zoom
	#---------------------------------------------------------
	mask = rho_Hcc > rho_seuil

	rho_masked = rho[mask]
	dx_masked = dx[mask]

	mass_core = np.sum( rho_masked * dx_masked**3 ) / 1.9889e+30  #En Msun
	mass_tot = np.sum( rho * dx**3 ) / 1.9889e+30  #En Msun

	pourcent_mass_core = mass_core / mass_tot *100

	print
	print("==========================================================================")
	print("    M_central_core = "+str(mass_core)+ " Msun")
	print("    M_tot = "+str(mass_tot)+ " Msun")
	print("    Pourcent_M_central_core = "+str(pourcent_mass_core)+ " %")
	print("==========================================================================")
	print
	
	return (mass_core, mass_tot, pourcent_mass_core)
예제 #29
0
#if simu == 'B335_noturb_norot_hydro_pert_asym_aleatoire50_vhr':
#   path_t0='/mnt/magmist/magmist/simu_B335_averliat/'+simu+'/'
#else:
#   path_t0=path
path_t0=path

if save==True:
    if os.path.isdir(path_save) == False:
        os.mkdir(path_save)



#-------------------
#Lecture de l'output
#-------------------
ro=pymses.RamsesOutput(path,num_output)
lbox_pc = ro.info['unit_length'].express(cst.pc)

amr = ro.amr_source(["rho","vel","P","phi","g"])

cell_source = CellsToPoints(amr)
cells = cell_source.flatten()

pos = cells.points
rho = cells["rho"]



#------------------------------------------------------------
#Facteur de conversion des unites de code en unites physiques
#------------------------------------------------------------
#------------------------------------------------------------------
#Chargement moments cinetiques de la simulation perturbee a la main
#------------------------------------------------------------------
path_1_pert_llf = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_pert_llf/Moment_cinetique_tot_output_1_48_par_densite.fits'
path_2_pert_llf = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_pert_llf/Integrale_valeurs_absolues_moments_cinetiques_output_1_48_par_densite.fits'

path_simu_pert_llf='/gpfs/data1/phennebe/B335_noturb_norot_hydro_pert_llf/'
num_min_pert_llf=1
num_max_pert_llf=48

nmbr_output_pert_llf = num_max_pert_llf-num_min_pert_llf+1

simulation_time_pert_llf = np.zeros(nmbr_output_pert_llf)

for l in range(nmbr_output_pert_llf):
	ro=pymses.RamsesOutput(path_simu_pert_llf,l+1)
	factor_time_pert_llf_Myr = ro.info['unit_time'].express(cst.Myr)
	simulation_time_pert_llf[l] = ro.info['time']*factor_time_pert_llf_Myr



#--------------------------------------------------
#Chargement moments cinetiques de la simulation HR2
#--------------------------------------------------
path_1_hr2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Moment_cinetique_tot_output_1_78_par_densite.fits'
path_2_hr2 = '/home/users/mnt/averliat/analyses/B335_noturb_norot_hydro_hr2/Integrale_valeurs_absolues_moments_cinetiques_output_1_78_par_densite.fits'

path_simu_hr2='/gpfs/data1/phennebe/B335_noturb_norot_hydro_hr2/'
num_min_hr2=1
num_max_hr2=78