def __getitem__(self, item, flatten=True, cpu=None): ''' Return an object containing this field. flatten - Return a numpy array containing all points. cpu - Return only the domain belonging to this CPU. If flatten == False and cpu=None, return an iterable ''' source = self._snapshot.source ndim = '3D' fields = [ v.name for v in output.RamsesOutput.amr_field_descrs_by_file[ndim] ['hydro'] ] if item in fields: #Load and return (will work with multiple fields too!) #amr_source = self.amr_source(item) cells = CellsToPoints(source) if flatten: return cells.flatten() elif cpu is None: return cells.iter_dsets() else: return cells.get_domain_dset(cpu) else: #Particle field #part_source = self.particle_source(item) if flatten: return source.flatten() elif cpu is None: return source.iter_dsets() else: return source.get_domain_dset(cpu)
def load(self, *fields): """Loads a list of quantitys in the self.qtyDataFrame""" print "-> Loading fields ...", ro = self.ramsesOutput df = self.qtyDataFrame # Recherche les champs de *fields qui # ne sont pas encore charges dans le dataframe fields_to_load = [] for field in fields: if field.name not in df.keys(): fields_to_load.append(field) # if fields_to_load: amr_fields_to_read = Q.get_amrfields_to_read(*fields_to_load) amrSource = ro.amr_source(amr_fields_to_read, grav_compat=True, verbose=self._verbose) amrSource = RegionFilter(self.sphere, amrSource) dset = CellsToPoints(amrSource).flatten() for field in fields_to_load: df[field.name] = pd.Series(field.process(ro, dset)) print " Fields loaded :", for field in fields_to_load: print field.name, print "" return fields_to_load else: print " No field to load" return []
def process(cls, ro, dset=None, unit=None, verbose=False): if dset == None: source = ro.amr_source(cls.amrFields, grav_compat=GRAV_COMPAT, verbose=verbose) dset = CellsToPoints(source).flatten() return cls.get_calc(ro, unit)(dset)
def filt_cube(self, cube, dset_type, fields): ''' Return flattened dset of points contained by this cube ''' if dset_type == Type.AMR: source = self.amr_source(fields) elif dset_type == Type.PART: source = self.particle_source(fields) else: raise Exception("No such type: ", dset_type) from pymses.filters import CellsToPoints from pymses.filters import RegionFilter filt_source = RegionFilter(cube, source) return CellsToPoints(filt_source).flatten()
def amr2cell(ro=None, list_var=None, log_sfera=False, camera_in={}, verbose=False): """ log_sfera: Boolean True for sphere """ assert ro != None assert list_var != None from pymses.utils import regions from pymses.filters import RegionFilter, CellsToPoints amr = ro.amr_source(list_var) center = camera_in['center'] radius = camera_in['region_size'][0] if (log_sfera): regione_sp = regions.Sphere(center, radius) else: sinistra = np.copy(center) - radius destra = np.copy(center) + radius regione_sp = regions.Box((sinistra, destra)) if (verbose): print 'Extracting cells' if (log_sfera): print ' getting a sphere' print ' center:', center print ' radius:', radius else: print ' getting a box' print ' center:', center print ' size :', radius print ' left :', sinistra print ' right :', destra # cut the region amr = RegionFilter(regione_sp, amr) amr = CellsToPoints(amr) celle = amr.flatten() amr = None return celle
def __getitem__(self, fields): """ Data access via pymses for family specific tracked/derived fields """ from serensource import SerenSource if not hasattr(fields, "__iter__"): fields = [fields] source, required_fields = self.get_source(fields, return_required_fields=True) if self.family in ['amr', 'rt']: from pymses.filters import CellsToPoints source = CellsToPoints(source) cpu_list = None if hasattr(self.base, "region"): from pymses.filters import RegionFilter source = RegionFilter(self.base.region, source) return SerenSource(self, source)
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)
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
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
def mstar_halomass_tree(self, tree, ds): snapshot = self._snapshot ro = snapshot.raw_snapshot() parts = ro.particle_source(["mass", "epoch"]) amr = ro.amr_source(['rho']) #Figure out the smallest possible cell size in code units boxlen = ro.info['boxlen'] lmax = ro.info['levelmax'] min_dx = boxlen/float(2**(lmax)) offset = tree.get_offset() snap_num = self._snapshot.output_number() - offset halos = tree.sub_catalogue('snap_num', snap_num) #idx = np.where(tree._tree[:]['snap_num'] == self._snapshot.output_number()-30)[0] #halos = tree[idx] # Is this right? print 'Loaded halos have snap_num:', halos[1]['snap_num'] mstar = [] mhalo = [] i = 1 for halo in halos: #Check if distinct halo if not halo['pid'].value == -1: print 'Halo %d skipped: PID = %d'%(halo['id'].value, halo['pid'].value) continue #Unit conversion cen = halo['pos'] cen = ds.arr(cen.value, cen.unit) r = halo['Rvir'] r = ds.arr(r.value, r.unit) #Create the sphere cen = cen.in_units('code_length').value r = r.in_units('code_length').value r_amr = float(r) #If the halo radius is smaller than the min cell size, #we need to try and approximate the masses enclosed. #Not sure how correct this is... factor = 1 if r < min_dx: r_amr += min_dx vol_halo = (4./3.)*np.pi*r**3 vol_cell = (4./3.)*np.pi*r_amr**3 factor = vol_halo/vol_cell #Define the regions region_part = Sphere(cen, r) region_amr = Sphere(cen, r_amr) #Filter the particles filt_parts = RegionFilter(region_part, parts) part_source = filt_parts.flatten() dm = np.where(part_source['epoch'] == 0)[0] stars = np.where(part_source['epoch'] != 0)[0] part_mass = part_source['mass']*ro.info['unit_mass'].express(C.Msun) if len(part_mass[dm]) < 50: print 'Discarding halo with less than 200 particles. Mvir=%e'%halo['Mvir'].value continue #Filter the AMR data filt_amr = RegionFilter(region_amr, amr) cell_source = CellsToPoints(filt_amr) cells = cell_source.flatten() rho = cells['rho']*ro.info['unit_density'].express(C.Msun/C.kpc**3) vol = (cells.get_sizes()*ro.info['unit_length'].express(C.kpc))**3 cell_mass = rho*vol #Compute the total mass enclosed gas_mass = np.sum(cell_mass)*factor # Multiply by factor incase we had to inflate the sphere stellar_mass = np.sum(part_mass[stars]) particle_mass = np.sum(part_mass) total_mass = gas_mass + particle_mass mstar.append(stellar_mass) mhalo.append(total_mass) i+=1 print i #print i if(config.verbose and (i%100)==0): print 'Processed %d halos...'%i return np.array(mstar), np.array(mhalo)
import numpy as np import sys # Parse Arguments if len(sys.argv) == 1: iout = 1 elif len(sys.argv) == 2: iout = int(sys.argv[1]) # Prepare Output output = RamsesOutput(".", iout) source = output.amr_source(["rho"]) # Convert Leaf-Cells to Points cell_source = CellsToPoints(source) cells = cell_source.flatten() # Get Density & Cell Size rho = cells["rho"] dx = output.info["boxlen"] * cells.get_sizes() dV = dx**output.info["ndim"] # Print Stuff # print cells["rho"] # contains densities # print rho # contains densities # print cells.points # contains coordinates # print dx print "" # Compute Total Mass
def image(simu, owner, num_output, dir_save): save = True radius_zoom = 1 v_proj = True title_time = True title_time_cor = False seuil_rho = 1e-10 fleche_vel = False nbre_fleche = 20 #En fait plus c'est faible plus y'a de fleches... selon_x = True selon_y = True selon_z = True vmin_vel = None #-4.5 vmax_vel = None #-vmin_vel vmin_dens = None #22.7 vmax_dens = None #28.9 color_sink_colmap = 'firebrick' transparence_sink_colmap = 0.4 color_sink_velmap = 'limegreen' transparence_sink_velmap = 0.7 reposition_fig = False #Pour repositionner les figures ouvertes par matplotlib #Pour fermer toutes les figures avec matplotlib : plt.close('all') #-------------------------------------------------------------- #Chemin de la simulation et du dossier de sauvegarde des images #-------------------------------------------------------------- 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 + '/' #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 #------------------------------------------------------------ lbox = ro.info['boxlen'] lbox_m = ro.info['unit_length'].express(cst.m) 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_vel_km_s = ro.info['unit_velocity'].express(cst.km / cst.s) simulation_time = ro.info['time'] * factor_time_yr #--------------------------------------------------------------------------------- #Calcul des t_0 de chaque simulation ou lecture des fichiers si calculs deja faits #--------------------------------------------------------------------------------- if title_time_cor == True: if os.path.isfile(path_analyse + '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_analyse + 't0_seuil_rho_' + str(seuil_rho) + '.txt', ref) else: ref = np.loadtxt(path_analyse + 't0_seuil_rho_' + str(seuil_rho) + '.txt') #Erreur si on cherche a etudier un fichier inferieur au t0 de la simulation de reference if num_output < ref[0]: print print print("=================================================") print("=================================================") print("/!\ output_ref < output_ref_t0 /!\ ") print("=================================================") print("=================================================") title_time_cor = 0 #--------------------------------------------------------- #Definition du centre des images et de leur niveau de zoom #--------------------------------------------------------- #Position du "centre" de la simulation = endroit le plus dense if radius_zoom == 5: center = [0.5, 0.5, 0.5] else: arg_centre = np.argmax(rho) center = [ pos[:, 0][arg_centre], pos[:, 1][arg_centre], pos[:, 2][arg_centre] ] zoom_v = [0.045, 0.015, 0.005, 0.005 / 3., 0.5] if 'bigbox' or 'jet' in simu: zoom_v = [ 0.045 / 2, 0.015 / 2, 0.005 / 2, 0.005 / 3. / 2, 0.5, 0.5 / 2, 0.005 / 20. ] if radius_zoom == 6: center = [0.5, 0.5, 0.5] if 'hugebox' in simu: zoom_v = [ 0.045 / 4, 0.015 / 4, 0.005 / 4, 0.005 / 3. / 4, 0.5, 0.5 / 4 ] if radius_zoom == 6: center = [0.5, 0.5, 0.5] radius = zoom_v[radius_zoom - 1] #radius=float(zoom_v[np.where(zoom_v==radius_zoom)]) #0.015#0.005 #Niveau de zoom correspondant au niveau '3' des images de "pipeline_image_unique.py" #------------------------------------------------------------------------ #Get the properties of the particules with just the particules' positions #Copie depuis module_extract.py #------------------------------------------------------------------------ def read_sink_csv(num, directory, no_cvs=None): name = directory + 'output_' + str(num).zfill(5) + '/sink_' + str( num).zfill(5) + '.csv' print 'read sinks from ', name if (no_cvs is None): sinks = np.loadtxt(name, delimiter=',', ndmin=2, usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8)) #,9,10,11,12)) else: sinks = np.loadtxt(name, ndmin=2, usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) return sinks #------------------------------ #Pour visualiser les sinks #Adapted from module_extract.py #------------------------------ def visualise_sink_AU(path, num_output): sinks = read_sink_csv(num_output, path) if len(sinks) != 0: mass_sinks = sinks[:, 1] #masse des sinks en masses solaires x_sinks = sinks[:, 3] * lbox_au / lbox #coordonnees x des sinks en AU y_sinks = sinks[:, 4] * lbox_au / lbox #coordonnees y des sinks en AU z_sinks = sinks[:, 5] * lbox_au / lbox #coordonnees z des sinks en AU return mass_sinks, x_sinks, y_sinks, z_sinks #--------------------------------------- #Lecture du fichier sink.csv s'il existe #--------------------------------------- sink_plot = False if os.path.isfile(path + 'output_' + str(num_output).zfill(5) + '/sink_' + str(num_output).zfill(5) + '.csv') == True: #sink_plot=True sinks = read_sink_csv(num_output, path) if len(sinks) != 0: sink_plot = True if sink_plot == True: m_sinks, x_sinks, y_sinks, z_sinks = visualise_sink_AU( path, num_output) #size_sinks=20*np.tanh(25*m_sinks) size_sinks = 20 * np.sqrt(m_sinks) if radius_zoom != 5: #centrage sur la plus grosse sink au lieu de rho max arg_biggest_sink = np.argmax(m_sinks) x_biggest_sink = x_sinks[arg_biggest_sink] / lbox_au y_biggest_sink = y_sinks[arg_biggest_sink] / lbox_au z_biggest_sink = z_sinks[arg_biggest_sink] / lbox_au center = [x_biggest_sink, y_biggest_sink, z_biggest_sink] #--------------------------------------------------------------------------------------------------------------- #Definition prise sur https://stackoverflow.com/questions/20144529/shifted-colorbar-matplotlib/20146989#20146989 #pour avoir le centre de la colorbar a 0 #--------------------------------------------------------------------------------------------------------------- class MidpointNormalize(Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) #----------------- #----------------- #Calcul des cartes #----------------- #----------------- if selon_x == True: #-------------------------------------------- #Calcul de la carte ou l'on regarde suivant x #-------------------------------------------- cam_x = Camera(center=center, line_of_sight_axis='x', region_size=[2. * radius, 2. * radius], distance=radius, far_cut_depth=radius, up_vector='z', map_max_size=512) rho_op = ScalarOperator(lambda dset: dset["rho"], ro.info["unit_density"]) rt = raytracing.RayTracer(amr, ro.info, rho_op) datamap = rt.process(cam_x, surf_qty=True) map_col = np.log10(datamap.map.T * lbox_cm) if v_proj == True: Vx_op = ScalarOperator( lambda dset: dset["vel"][..., 0] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vx_op) datamap_vx = rt.process(cam_x, surf_qty=True) map_Vx = datamap_vx.map.T / datamap.map.T * factor_vel_km_s if fleche_vel == True: Vy_depuis_x_op = ScalarOperator( lambda dset: dset["vel"][..., 1] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vy_depuis_x_op) datamap_vy_depuis_x = rt.process(cam_x, surf_qty=True) map_vy_depuis_x = datamap_vy_depuis_x.map.T / datamap.map.T * factor_vel_km_s map_vy_depuis_x_red = map_vy_depuis_x[::nbre_fleche, ::nbre_fleche] Vz_depuis_x_op = ScalarOperator( lambda dset: dset["vel"][..., 2] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vz_depuis_x_op) datamap_vz_depuis_x = rt.process(cam_x, surf_qty=True) map_vz_depuis_x = datamap_vz_depuis_x.map.T / datamap.map.T * factor_vel_km_s map_vz_depuis_x_red = map_vz_depuis_x[::nbre_fleche, ::nbre_fleche] plt.figure() im = plt.imshow(map_col, extent=[(-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au, (-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au], origin='lower') plt.xlabel('$y$ (AU)') plt.ylabel('$z$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_x_' + str(radius_zoom) + '_' + str(num_output) + '.pdf', bbox_inches='tight') nx = map_vy_depuis_x_red.shape[0] ny = map_vy_depuis_x_red.shape[1] vec_x = (np.arange(nx) * 2. / nx * radius - radius + center[0] + radius / nx) * lbox_au vec_y = (np.arange(ny) * 2. / ny * radius - radius + center[1] + radius / nx) * lbox_au xx, yy = np.meshgrid(vec_x, vec_y) plt.quiver(xx, yy, map_vy_depuis_x_red, map_vz_depuis_x_red) else: plt.figure() plt.imshow(map_col, extent=[(-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au, (-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au], origin='lower', vmin=vmin_dens, vmax=vmax_dens) if sink_plot == True: for i in range(len(m_sinks)): if (y_sinks[i] > (-radius + center[1]) * lbox_au) & ( y_sinks[i] < (radius + center[1]) * lbox_au) & ( z_sinks[i] > (-radius + center[2]) * lbox_au) & ( z_sinks[i] < (radius + center[2]) * lbox_au): plt.plot(y_sinks[i], z_sinks[i], '.', color=color_sink_colmap, markersize=size_sinks[i], alpha=transparence_sink_colmap) plt.xlabel('$y$ (AU)') plt.ylabel('$z$ (AU)') cbar = plt.colorbar() if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_x_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if v_proj == True: plt.figure() norm = MidpointNormalize( midpoint=0) #Pour avoir le centre de la colormap a 0 plt.imshow(map_Vx, extent=[(-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au, (-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au], origin='lower', cmap='RdBu_r', norm=norm, vmin=vmin_vel, vmax=vmax_vel) if sink_plot == True: for i in range(len(m_sinks)): if (y_sinks[i] > (-radius + center[1]) * lbox_au) & ( y_sinks[i] < (radius + center[1]) * lbox_au) & ( z_sinks[i] > (-radius + center[2]) * lbox_au) & ( z_sinks[i] < (radius + center[2]) * lbox_au): plt.plot(y_sinks[i], z_sinks[i], '.', color=color_sink_velmap, markersize=size_sinks[i], alpha=transparence_sink_velmap) plt.xlabel('$y$ (AU)') plt.ylabel('$z$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$v_x \, (km.s^{-1})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'vel_x_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if selon_y == True: #-------------------------------------------- #Calcul de la carte ou l'on regarde suivant y #-------------------------------------------- cam_y = Camera(center=center, line_of_sight_axis='y', region_size=[2. * radius, 2. * radius], distance=radius, far_cut_depth=radius, up_vector='x', map_max_size=512) rho_op = ScalarOperator(lambda dset: dset["rho"], ro.info["unit_density"]) rt = raytracing.RayTracer(amr, ro.info, rho_op) datamap = rt.process(cam_y, surf_qty=True) map_col = np.log10(datamap.map.T * lbox_cm) if v_proj == True: Vy_op = ScalarOperator( lambda dset: dset["vel"][..., 1] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vy_op) datamap_vy = rt.process(cam_y, surf_qty=True) map_Vy = datamap_vy.map.T / datamap.map.T * factor_vel_km_s if fleche_vel == True: Vx_depuis_y_op = ScalarOperator( lambda dset: dset["vel"][..., 0] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vx_depuis_y_op) datamap_vx_depuis_y = rt.process(cam_y, surf_qty=True) map_vx_depuis_y = datamap_vx_depuis_y.map.T / datamap.map.T * factor_vel_km_s map_vx_depuis_y_red = map_vx_depuis_y[::nbre_fleche, ::nbre_fleche] Vz_depuis_y_op = ScalarOperator( lambda dset: dset["vel"][..., 2] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vz_depuis_y_op) datamap_vz_depuis_y = rt.process(cam_y, surf_qty=True) map_vz_depuis_y = datamap_vz_depuis_y.map.T / datamap.map.T * factor_vel_km_s map_vz_depuis_y_red = map_vz_depuis_y[::nbre_fleche, ::nbre_fleche] plt.figure() im = plt.imshow(map_col, extent=[(-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au, (-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au], origin='lower') plt.xlabel('$z$ (AU)') plt.ylabel('$x$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_y_' + str(radius_zoom) + '_' + str(num_output) + '.pdf', bbox_inches='tight') nx = map_vx_depuis_y_red.shape[0] ny = map_vx_depuis_y_red.shape[1] vec_x = (np.arange(nx) * 2. / nx * radius - radius + center[0] + radius / nx) * lbox_au vec_y = (np.arange(ny) * 2. / ny * radius - radius + center[1] + radius / nx) * lbox_au xx, yy = np.meshgrid(vec_x, vec_y) plt.quiver(xx, yy, map_vz_depuis_y_red, map_vx_depuis_y_red) else: plt.figure() im = plt.imshow(map_col, extent=[(-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au, (-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au], origin='lower', vmin=vmin_dens, vmax=vmax_dens) if sink_plot == True: for i in range(len(m_sinks)): if (z_sinks[i] > (-radius + center[2]) * lbox_au) & ( z_sinks[i] < (radius + center[2]) * lbox_au) & ( x_sinks[i] > (-radius + center[0]) * lbox_au) & ( x_sinks[i] < (radius + center[0]) * lbox_au): plt.plot(z_sinks[i], x_sinks[i], '.', color=color_sink_colmap, markersize=size_sinks[i], alpha=transparence_sink_colmap) plt.xlabel('$z$ (AU)') plt.ylabel('$x$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_y_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if v_proj == True: plt.figure() norm = MidpointNormalize( midpoint=0) #Pour avoir le centre de la colormap a 0 plt.imshow(map_Vy, extent=[(-radius + center[2]) * lbox_au, (radius + center[2]) * lbox_au, (-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au], origin='lower', cmap='RdBu_r', norm=norm, vmin=vmin_vel, vmax=vmax_vel) if sink_plot == True: for i in range(len(m_sinks)): if (z_sinks[i] > (-radius + center[2]) * lbox_au) & ( z_sinks[i] < (radius + center[2]) * lbox_au) & ( x_sinks[i] > (-radius + center[0]) * lbox_au) & ( x_sinks[i] < (radius + center[0]) * lbox_au): plt.plot(z_sinks[i], x_sinks[i], '.', color=color_sink_velmap, markersize=size_sinks[i], alpha=transparence_sink_velmap) plt.xlabel('$z$ (AU)') plt.ylabel('$x$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$v_y \, (km.s^{-1})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'vel_y_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if selon_z == True: #-------------------------------------------- #Calcul de la carte ou l'on regarde suivant z #-------------------------------------------- cam_z = Camera(center=center, line_of_sight_axis='z', region_size=[2. * radius, 2. * radius], distance=radius, far_cut_depth=radius, up_vector='y', map_max_size=512) rho_op = ScalarOperator(lambda dset: dset["rho"], ro.info["unit_density"]) rt = raytracing.RayTracer(amr, ro.info, rho_op) datamap = rt.process(cam_z, surf_qty=True) map_col = np.log10(datamap.map.T * lbox_cm) if v_proj == True: Vz_op = ScalarOperator( lambda dset: dset["vel"][..., 2] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vz_op) datamap_vz = rt.process(cam_z, surf_qty=True) map_Vz = datamap_vz.map.T / datamap.map.T * factor_vel_km_s if fleche_vel == True: Vx_depuis_z_op = ScalarOperator( lambda dset: dset["vel"][..., 0] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vx_depuis_z_op) datamap_vx_depuis_z = rt.process(cam_z, surf_qty=True) map_vx_depuis_z = datamap_vx_depuis_z.map.T / datamap.map.T * factor_vel_km_s map_vx_depuis_z_red = map_vx_depuis_z[::nbre_fleche, ::nbre_fleche] Vy_depuis_z_op = ScalarOperator( lambda dset: dset["vel"][..., 1] * dset["rho"], ro.info["unit_velocity"]) rt = raytracing.RayTracer(amr, ro.info, Vy_depuis_z_op) datamap_vy_depuis_z = rt.process(cam_z, surf_qty=True) map_vy_depuis_z = datamap_vy_depuis_z.map.T / datamap.map.T * factor_vel_km_s map_vy_depuis_z_red = map_vy_depuis_z[::nbre_fleche, ::nbre_fleche] plt.figure() im = plt.imshow(map_col, extent=[(-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au, (-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au], origin='lower') plt.xlabel('$x$ (AU)') plt.ylabel('$y$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_z_' + str(radius_zoom) + '_' + str(num_output) + '.pdf', bbox_inches='tight') nx = map_vx_depuis_z_red.shape[0] ny = map_vx_depuis_z_red.shape[1] vec_x = (np.arange(nx) * 2. / nx * radius - radius + center[0] + radius / nx) * lbox_au vec_y = (np.arange(ny) * 2. / ny * radius - radius + center[1] + radius / nx) * lbox_au xx, yy = np.meshgrid(vec_x, vec_y) plt.quiver(xx, yy, map_vx_depuis_z_red, map_vy_depuis_z_red) else: plt.figure() im = plt.imshow(map_col, extent=[(-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au, (-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au], origin='lower', vmin=vmin_dens, vmax=vmax_dens) if sink_plot == True: for i in range(len(m_sinks)): if (x_sinks[i] > (-radius + center[0]) * lbox_au) & ( x_sinks[i] < (radius + center[0]) * lbox_au) & ( y_sinks[i] > (-radius + center[1]) * lbox_au) & ( y_sinks[i] < (radius + center[1]) * lbox_au): plt.plot(x_sinks[i], y_sinks[i], '.', color=color_sink_colmap, markersize=size_sinks[i], alpha=transparence_sink_colmap) plt.xlabel('$x$ (AU)') plt.ylabel('$y$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$log(N) \, \, (cm^{-2})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'dens_z_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if v_proj == True: plt.figure() norm = MidpointNormalize( midpoint=0) #Pour avoir le centre de la colormap a 0 plt.imshow(map_Vz, extent=[(-radius + center[0]) * lbox_au, (radius + center[0]) * lbox_au, (-radius + center[1]) * lbox_au, (radius + center[1]) * lbox_au], origin='lower', cmap='RdBu_r', norm=norm, vmin=vmin_vel, vmax=vmax_vel) if sink_plot == True: for i in range(len(m_sinks)): if (x_sinks[i] > (-radius + center[0]) * lbox_au) & ( x_sinks[i] < (radius + center[0]) * lbox_au) & ( y_sinks[i] > (-radius + center[1]) * lbox_au) & ( y_sinks[i] < (radius + center[1]) * lbox_au): plt.plot(x_sinks[i], y_sinks[i], '.', color=color_sink_velmap, markersize=size_sinks[i], alpha=transparence_sink_velmap) plt.xlabel('$x$ (AU)') plt.ylabel('$y$ (AU)') cbar = plt.colorbar() cbar.set_label(r'$v_z \, (km.s^{-1})$') if title_time == True: plt.title('Time = ' + str(int(simulation_time)) + ' years') if title_time_cor == True: plt.title('Time = ' + str(int(simulation_time)) + ' years \n Corrected time = ' + str(int(simulation_time - ref[1] * 1e6)) + ' years') if radius_zoom == 5: plt.xlim([0, lbox_au]) plt.ylim([0, lbox_au]) if save == True: plt.savefig(path_save + 'vel_z_' + str(radius_zoom) + '_%05d' % num_output + '.png', bbox_inches='tight') plt.close() if v_proj == True and reposition_fig == True: for i in range(3): i *= 2 for j in range(2): plt.figure(i + j + 1) mngr = plt.get_current_fig_manager() geom = mngr.window.geometry() x, y, dx, dy = geom.getRect() mngr.window.setGeometry(1920 / 3 * (i / 2), 1080 / 2 * j, dx, dy) plt.figure(1) #Oblige sinon figure 1 mal placee... mngr = plt.get_current_fig_manager() geom = mngr.window.geometry() x, y, dx, dy = geom.getRect() #mngr.window.setGeometry(65,52,dx,dy) mngr.window.setGeometry(1, 1, dx, dy) return
def SFR_calculation(simu,owner,output_min,output_max,colorsink,colorgas,colortot,legend): #-------------------------------------------------------------- #Chemin de la simulation et du dossier de sauvegarde des images #-------------------------------------------------------------- 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_analyse='/home/averliat/these/analyses/'+simu+'/' path_t0=path #------------------------------------------------------------------------ #Get the properties of the particules with just the particules' positions #Copie depuis module_extract.py #------------------------------------------------------------------------ def read_sink_csv(num,directory,no_cvs=None): name = directory+'output_'+str(num).zfill(5)+'/sink_'+str(num).zfill(5)+'.csv' print 'read sinks from ', name if(no_cvs is None): sinks = np.loadtxt(name,delimiter=',',ndmin=2,usecols=(0,1,2,3,4,5,6,7,8)) #,9,10,11,12)) else: sinks = np.loadtxt(name,ndmin=2,usecols=(0,1,2,3,4,5,6,7,8,9,10,11,12)) return sinks #--------------------------------------- #Lecture du fichier sink.csv s'il existe #--------------------------------------- mass_sinks_tab=np.zeros(output_max+1-output_min,dtype=object) mass_gas_tab=np.zeros(output_max+1-output_min) numero_output=np.zeros(output_max+1-output_min) simulation_time=np.zeros(output_max+1-output_min) ind_output=0 for num_output in range(output_min,output_max+1): m_sinks=None if os.path.isfile(path+'output_'+str(num_output).zfill(5)+'/sink_'+str(num_output).zfill(5)+'.csv') == True: sinks=read_sink_csv(num_output,path) if len(sinks) != 0: m_sinks=sinks[:,1] #masse des sinks en masses solaires else: m_sinks=0. mass_sinks_tab[ind_output]=np.array(m_sinks) numero_output[ind_output]=num_output #------------------- #lecture de l'output #------------------- ro=pymses.RamsesOutput(path,num_output) amr = ro.amr_source(["rho"]) cell_source = CellsToPoints(amr) cells = cell_source.flatten(verbose=False) dx = cells.get_sizes() rho = cells["rho"] #------------------------------ #conversion en unites physiques #------------------------------ lbox_au = ro.info['unit_length'].express(cst.au) factor_dist= ro.info['unit_length'].express(cst.m) factor_vel = ro.info['unit_velocity'].express(cst.m/cst.s) factor_rho = ro.info['unit_density'].express(cst.kg/(cst.m)**3) factor_time_Myr = ro.info['unit_time'].express(cst.Myr) simulation_time[ind_output] = ro.info['time']*factor_time_Myr dx *= factor_dist rho *= factor_rho mass_tot = np.sum( rho * dx**3 ) / 1.9889e+30 #En Msun mass_gas_tab[ind_output]=mass_tot ind_output+=1 mass_sinks_sum_tab=np.zeros(output_max+1-output_min) for i in range(len(mass_sinks_tab)): mass_sinks_sum_tab[i]=np.sum(mass_sinks_tab[i]) #--------------------------------------------------- #Trace de la masse des sinks en fonction de l'output #--------------------------------------------------- plt.figure(20) plt.plot(numero_output,mass_sinks_sum_tab,linestyle='solid',marker='.',color=colorsink) plt.xlabel(r"Numero de l'output") plt.ylabel(r"Masse des sinks ($M_\odot$)") plt.figure(21) plt.plot(simulation_time,mass_sinks_sum_tab,linestyle='solid',marker='.',color=colorsink) plt.xlabel(r"Temps (Myr)") plt.ylabel(r"Masse des sinks ($M_\odot$)") plt.figure(22) plt.plot(numero_output,mass_sinks_sum_tab+mass_gas_tab,linestyle='solid',marker='.',color=colortot) plt.xlabel(r"Numero de l'output") plt.ylabel(r"Masse totale ($M_\odot$)") plt.figure(23) plt.semilogy(simulation_time,mass_gas_tab,linestyle='solid',marker='.',color=colorgas,label='Gas'+legend) plt.semilogy(simulation_time,mass_sinks_sum_tab,linestyle='solid',marker='.',color=colorsink,label='Sinks'+legend) plt.semilogy(simulation_time,mass_sinks_sum_tab+mass_gas_tab,linestyle='solid',marker='.',color=colortot,label='Gas + sinks'+legend) plt.xlabel(r"Temps (Myr)") plt.ylabel(r"Masse ($M_\odot$)") plt.legend(loc='best')
def temps_0_simu(path_simu, seuil_rho=1e-10, num_min=2, num_max=150, sortie_output=2): #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) max_rho = 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() rho = cells["rho"] factor_rho = ro.info['unit_density'].express(cst.kg / (cst.m)**3) rho *= factor_rho max_rho[l] = np.max(rho) print print print("===========================================================") print('max(rho) = ' + str(np.max(rho)) + ' kg.m^-3') print("===========================================================") print print print if max_rho[l] >= seuil_rho: 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 densité non atteint /!\ ") print("===========================================================") print("===========================================================") ''' plt.semilogy(simulation_time, max_rho, linestyle=None, marker='.') plt.show() ''' return (output_seuil, time_seuil)
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)
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 #------------------------------ lbox_au = ro.info['unit_length'].express(cst.au) lbox_pc = ro.info['unit_length'].express(cst.pc) factor_dist = ro.info['unit_length'].express(cst.m) factor_vel = ro.info['unit_velocity'].express(cst.m / cst.s) factor_rho = ro.info['unit_density'].express(cst.kg / (cst.m)**3)
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
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 #------------------------------------------------------------ lbox=ro.info['boxlen'] lbox_m = ro.info['unit_length'].express(cst.m) 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)
def fgas_halomass(self, halos=None): snapshot = self._snapshot ro = snapshot.raw_snapshot() amr = ro.amr_source(['rho']) parts = ro.particle_source(["mass"]) #Figure out the smallest possible cell size in code units boxlen = ro.info['boxlen'] lmax = ro.info['levelmax'] min_dx = boxlen/float(2**(lmax)) if config.verbose: print 'min_dx=', min_dx if (halos == None): halos = snapshot.halos() if config.verbose: print 'Processing %d halos'%len(halos) fgas = [] mhalo = [] #z = self._snapshot.current_redshift() #a = 1./(1.+z) i = 0 for halo in halos: if halo['num_p'] < 150: break #if tree: #Find this halo and count number of progenitors. #If too high, skip (frequent mergers -> tidal stripping) #idx_tree_halo = (tree._tree[:]['orig_halo_id'] == halo['id'].value) &\ # (tree._tree[:]['snap_num'] == snapshot.rockstar_output_number()) #print idx_tree_halo #tree_halo = tree._tree[idx_tree_halo] #assert(len(tree_halo)==1) #all_halos = [] #tree.find_progs(np.array([tree_halo]), all_halos) #num_progs = len(all_halos) #print 'Halo %d has %d progenitors'%(halo['id'], num_progs) #if num_progs > 150: continue #Create the sphere cen = halo['pos'].in_units('code_length').value r = halo['Rvir'].in_units('code_length').value r_amr = float(r) #If the halo radius is smaller than the min cell size, #we need to try and approximate the masses enclosed. #Not sure how correct this is... factor = 1 if r < min_dx: r_amr += min_dx vol_halo = (4./3.)*np.pi*r**3 vol_cell = (4./3.)*np.pi*r_amr**3 factor = vol_halo/vol_cell #Define the regions region_part = Sphere(cen, r) region_amr = Sphere(cen, r_amr) #Filter the particles filt_parts = RegionFilter(region_part, parts) part_source = filt_parts.flatten() part_mass = part_source['mass']*ro.info['unit_mass'].express(C.Msun) #Filter the AMR data filt_amr = RegionFilter(region_amr, amr) cell_source = CellsToPoints(filt_amr) cells = cell_source.flatten() rho = cells['rho']*ro.info['unit_density'].express(C.Msun/C.kpc**3) vol = (cells.get_sizes()*ro.info['unit_length'].express(C.kpc))**3 cell_mass = rho*vol #Compute the total mass enclosed gas_mass = np.sum(cell_mass)*factor # Multiply by factor incase we had to inflate the sphere particle_mass = np.sum(part_mass) total_mass = gas_mass + particle_mass fgas.append(gas_mass/total_mass) mhalo.append(total_mass) i+=1 #print i if(config.verbose and (i%100)==0): print 'Processes %d halos...'%i return np.array(fgas), np.array(mhalo)