def load_scorpio_uniform(self,flnm): """ scorpio uniform data loader Input: flnm: the name of the file to be opened """ with h5py.File(flnm,'r') as file: leftBdry = file['leftBdry'][()] rightBdry = file['rightBdry'][()] ashape = tuple(file['nMesh'][()].astype('int')) bbox = np.array([file['leftBdry'][()],file['rightBdry'][()]]).T nbuf = int(file['nbuf'][()]) domain = tuple([slice(nbuf,-nbuf)]*3) time = file['t'][()] data = {} data['density']=file['den'][domain].T data['magnetic_x']=0.5*(file['bxl'][domain].T+file['bxr'][domain].T) data['magnetic_y']=0.5*(file['byl'][domain].T+file['byr'][domain].T) data['magnetic_z']=0.5*(file['bzl'][domain].T+file['bzr'][domain].T) self.ds = yt.load_uniform_grid(data, ashape, bbox=bbox, sim_time = time, nprocs=64, unit_system="code" ) return self.ds
def yt_conversion(self): if yt_present: self.ytdict = dict( density=(np.exp(self.lnrho) * self.minfo.contents['AC_unit_density'], "g/cm**3"), uux=(self.uu[0] * self.minfo.contents['AC_unit_velocity'], "cm/s"), uuy=(self.uu[1] * self.minfo.contents['AC_unit_velocity'], "cm/s"), uuz=(self.uu[2] * self.minfo.contents['AC_unit_velocity'], "cm/s"), bbx=(self.bb[0] * self.minfo.contents['AC_unit_magnetic'], "gauss"), bby=(self.bb[1] * self.minfo.contents['AC_unit_magnetic'], "gauss"), bbz=(self.bb[2] * self.minfo.contents['AC_unit_magnetic'], "gauss"), ) bbox = self.minfo.contents['AC_unit_length'] \ *np.array([[self.xx.min(), self.xx.max()], [self.yy.min(), self.yy.max()], [self.zz.min(), self.zz.max()]]) self.ytdata = yt.load_uniform_grid(self.ytdict, self.lnrho.shape, length_unit="cm", bbox=bbox) else: print("ERROR. No YT support found!")
def ytrender(filename, vmin = None, vmax = None, useLog = False, nLayer = 10, cmap = 'gist_rainbow', colorwidth = 0.005, phi = 0.5, theta = 1.570796, outfile = None, usedomain = (0.25, 0.6, 0.6), Xrays = 768, Yrays = 512): cube = fits.getdata(filename) if not vmin: vmin = np.percentile(cube,50) if not vmax: vmax = np.percentile(cube,99.5) if len(cube.shape)>3: cube = cube.squeeze() if not outfile: outfile = filename.replace('fits','png') cube[np.isnan(cube)] = np.nanmin(cube) data = dict(density = cube) pf = yt.load_uniform_grid(data, cube.shape, 9e16) tf = yt.ColorTransferFunction((vmin, vmax)) c = (pf.domain_right_edge + pf.domain_left_edge)/2.0 tf.add_layers(nLayer, w=colorwidth,colormap=cmap, alpha = np.logspace(-1.0,0,nLayer)) c = [0.51, 0.51, 0.51] # centre of the image L = [np.cos(theta), np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi)] # normal vector W = usedomain cam = pf.camera(c,L,W,(Xrays,Yrays),tf,no_ghost=False, north_vector=[1.0,0,0], fields=['density'],log_fields=[useLog]) image = cam.snapshot(outfile, 8.0)
def magnetic_field_to_yt_dataset(Bx: u.gauss, By: u.gauss, Bz: u.gauss, range_x: u.cm, range_y: u.cm, range_z: u.cm): """ Reshape vector magnetic field data into a yt dataset Parameters ---------- Bx,By,Bz : `~astropy.units.Quantity` 3D arrays holding the x,y,z components of the extrapolated field range_x, range_y, range_z : `~astropy.units.Quantity` Spatial range in the x,y,z dimensions of the grid """ Bx = Bx.to(u.gauss) By = By.to(u.gauss) Bz = Bz.to(u.gauss) data = dict(Bx=(np.swapaxes(Bx.value, 0, 1), Bx.unit.to_string()), By=(np.swapaxes(By.value, 0, 1), By.unit.to_string()), Bz=(np.swapaxes(Bz.value, 0, 1), Bz.unit.to_string())) # Uniform, rectangular grid bbox = np.array([ range_x.to(u.cm).value, range_y.to(u.cm).value, range_z.to(u.cm).value ]) return yt.load_uniform_grid(data, data['Bx'][0].shape, bbox=bbox, length_unit=yt.units.cm, geometry=('cartesian', ('x', 'y', 'z')))
def load_mockstreams_func(filename): temp_ds = yt.load(filename) fields = ['density','temperature','metallicity',\ 'velocity_x','velocity_y','velocity_z','phase_types'] units = ['g/cm**3', 'K', 'Zsun', 'cm/s', 'cm/s', 'cm/s', ''] data = {} for i, f in enumerate(fields): def func(field, data): return (data['data', f]) temp_ds.add_field(("gas", f), function=func, sampling_type="local", units=units[i]) data['gas', f] = (temp_ds.data['gas', f]) bbox = np.array([[ np.amin(temp_ds.data['data', 'x']), np.amax(temp_ds.data['data', 'x']) ], [ np.amin(temp_ds.data['data', 'y']), np.amax(temp_ds.data['data', 'y']) ], [ np.amin(temp_ds.data['data', 'z']), np.amax(temp_ds.data['data', 'z']) ]]) ds = yt.load_uniform_grid(data,\ temp_ds.data['gas','density'].shape, \ length_unit="kpc", bbox=bbox) return ds
def open_unigrid(iout=1, run='.', data='../data', verbose=0, copy=True): s = dispatch.snapshot(iout, run, data) # parameters = dispatch.yt.parameters(s) #data=dispatch.select.unigrid_volume(s) data = dispatch.yt.patches(s, copy=copy) ds = yt.load_uniform_grid(data, **parameters) return ds
def run_slice(): with h5py.File("den_init.h5", "r") as f: d = f["/density_dataset"][:] ds = yt.load_uniform_grid({'density': d}, d.shape, bbox = np.array([ [ 0.0, 1.0], [0.0, 1.0], [0.0, 1.0]])) yt.SlicePlot(ds, "x", "density").save()
def createFrames2D(dataSet, frameName="default", rotation=0): ''' Called by animateDataSet() Generates animation frames for a 2D animation based on the data set inputted. dataSet needs to be passed in as a (total frames, box side length, box side length, box side length) shape array. Will plot slice at z = 0 ----- Arguments ----- dataSet: numpy array of shape (frames, box side, box side, box side). frameName: Filename of the frames generated, without directories. rotation: gradual rotation occurs around the data set across all frames up until this point. NOT IMPLEMENTED!! ----- Returns ----- Returns total frames rendered. Frames generated are stored in local Frames/2D directory. ''' resolution = int(len(dataSet[0, 0, 0])) totalFrames = int(len(dataSet[:])) # The bounding box of the volume rendered. This is arbitrary but used to position the camera around. bboxSize = 5.3 boundingBox = np.array([[-bboxSize, bboxSize], [-bboxSize, bboxSize], [-bboxSize, bboxSize]]) # What data values we care about rendering. Values outside (min, max) won't appear in rendering. # Does not like 0! Don't do 0. bounds = (0.01, 1) # Main rendering loop, each iteration will get us one frame. for index in range(totalFrames): # ds is yt convention for dataset, sc is scene frameData = dict(mesh_id=(dataSet[index])) ds = yt.load_uniform_grid(frameData, dataSet[index].shape, bbox=boundingBox, nprocs=resolution) slc = yt.SlicePlot(ds, 'z', 'mesh_id') slc.set_cmap('all', 'Eos B') # Hold the colorbar in place and rename label slc.set_zlim('all', 1e-16, 1) slc.set_colorbar_label('mesh_id', 'Probability') slc.annotate_text( (0.05, 0.03), 'System Probability: {}'.format(np.sum(dataSet[index, :, :, 0])), coord_system='figure', text_args={'color': 'black'}) slc.annotate_title('Probability Density in a 2D Box') # Set x and y labels units to be nothing (1, technically). slc.set_axes_unit('unitary') slc.save('Frames/2D/{0}{1}'.format(frameName, index)) return totalFrames
def yt_setup_tau(Ui, plot_geometry, limits): """ Plot the interpolated data using yt-python. """ import yt import numpy as np import matplotlib as plt import matplotlib.cm as cm from yt.utilities.physical_constants import mp, kb from yt.units import dimensions result = dict(density=(Ui[0], "g/cm**3"), pressure=(Ui[1], "dyne/cm**2"), tau_ff=(Ui[2], "")) ''' velocity_x = (Ui[2], "cm/s"), velocity_y = (Ui[3], "cm/s"), velocity_z = (Ui[4], "cm/s"), magnetic_field_x = (Ui[5], "G"), magnetic_field_y = (Ui[6], "G"), magnetic_field_z = (Ui[7], "G"), tau_ff1 = (Ui[8], ""), tau_ff2 = (Ui[9], ""), tau_ff3 = (Ui[10], "") ) ''' ds = yt.load_uniform_grid(result, Ui[0].shape, length_unit="9*Rsun", mass_unit=2.4578492774399997e+23, time_unit=6.26e6, velocity_unit="cm/s", magnetic_unit="G", bbox=limits, geometry=plot_geometry) def _temperature(field, data): mu = 1.01 return (data["gas", "pressure"] * mu * mp) / (data["gas", "density"] * kb) ds.add_field(("gas", "temperature"), function=_temperature, units="auto", dimensions=dimensions.temperature) def _H_number_density(field, data): mu_i = 1.01 return data["gas", "density"] / (mu_i * mp) ds.add_field(("gas", "H_number_density"), function=_H_number_density, units="cm**-3") return ds
def makeYtDS(xc1, xc2, xc3, Bc1, Bc2, Bc3): ''' Makes a dataset that can further be used with the yt module ''' data = dict(B_x=(Bc1, 'G'), B_y=(Bc2, 'G'), B_z=(Bc3, 'G')) bbox = np.array([[xc1[0], xc1[-1]], [xc2[0], xc2[-1]], [xc3[0], xc3[-1]]]) return yt.load_uniform_grid(data, Bc1.shape, length_unit='cm', bbox=bbox)
def cube_ds(self): if not self._cube_ds: self._cube_ds = yt.load_uniform_grid( dict( density=self.cube_data(SimTypes.DENSITY).cube, velocity_x=self.cube_data(SimTypes.X_VELOCITY).cube, velocity_y=self.cube_data(SimTypes.Y_VELOCITY).cube, velocity_z=self.cube_data(SimTypes.Z_VELOCITY).cube, pressure=self.cube_data(SimTypes.PRESSURE).cube, ), self.cube_data(SimTypes.DENSITY).cube.shape, # TODO: Fix scaling. Doesn't find many clumps with this enabled. #length_unit=self.ramses_ds.length_unit/512,#3080*6.02, ) return self._cube_ds
def prepare_star_unigrid(data, regionsize_kpc=7., verbose=False, add_unit=False, debug=False): import yt # prepare unigrid for stars bbox_lim = regionsize_kpc / 2. bbox = np.array([[-bbox_lim, bbox_lim], [-bbox_lim, bbox_lim], [-bbox_lim, bbox_lim]]) shape_data = data['velx'].shape if add_unit: data = dict(mass=(data['mass'], "Msun"), age=(data['epochMyr'], "Myr"), velx=(data['velx'], "km/s"), vely=(data['vely'], "km/s"), velz=(data['velz'], "km/s")) ds = yt.load_uniform_grid(data, shape_data, length_unit='kpc', bbox=bbox) else: ds = yt.load_uniform_grid(data, shape_data) dd = ds.all_data() if verbose: print dd['velx'].max(), dd['velx'].min() print dd['mass'].max(), dd['mass'].min() print dd['epoch'].max(), dd['epoch'].min() return ds, dd
def ytrender(filename, vmin=None, vmax=None, useLog=False, nLayer=10, cmap='gist_rainbow', colorwidth=0.005, phi=0.5, theta=1.570796, outfile=None, usedomain=(0.25, 0.6, 0.6), Xrays=768, Yrays=512): cube = fits.getdata(filename) if not vmin: vmin = np.percentile(cube, 50) if not vmax: vmax = np.percentile(cube, 99.5) if len(cube.shape) > 3: cube = cube.squeeze() if not outfile: outfile = filename.replace('fits', 'png') cube[np.isnan(cube)] = np.nanmin(cube) data = dict(density=cube) pf = yt.load_uniform_grid(data, cube.shape, 9e16) tf = yt.ColorTransferFunction((vmin, vmax)) c = (pf.domain_right_edge + pf.domain_left_edge) / 2.0 tf.add_layers(nLayer, w=colorwidth, colormap=cmap, alpha=np.logspace(-1.0, 0, nLayer)) c = [0.51, 0.51, 0.51] # centre of the image L = [ np.cos(theta), np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi) ] # normal vector W = usedomain cam = pf.camera(c, L, W, (Xrays, Yrays), tf, no_ghost=False, north_vector=[1.0, 0, 0], fields=['density'], log_fields=[useLog]) image = cam.snapshot(outfile, 8.0)
def to_dataset(S, timestep, fields, **kwargs): omega_r = Q( S._reference_angular_frequency_SI, 's**-1') L_r = c / omega_r data = { change_magnetic_field_name(name): S.Field(number, name, **kwargs, units=[unit]).getData(timestep=timestep)[0] * Q(1, unit) for name, number, unit in fields } ddim = data[change_magnetic_field_name(fields[0][0])].shape length_unit = 'um' time_unit = 'fs' bbox = np.array( [[0, L_i] for L_i in S.namelist.Main.grid_length] ) * L_r if 'subset' in kwargs: subset = kwargs['subset'] axes = ['x', 'y', 'z'] for i, ax in enumerate(axes): if ax in subset: bbox[i, :] = subset[ax] * L_r return yt.load_uniform_grid(data, ddim, length_unit=length_unit, bbox=(bbox / Q(1,length_unit)).to('1'), time_unit=time_unit)
def cube_vis(cube): # Loading data into yt structure R_unit="mpc" #r_sim.unit.to_string() R=r_sim.value.max() print('Box Radius and unit:',R,R_unit) data = {} data["density"] = (cube,R_unit) bbox = np.array([[-0.5,0.5],[-0.5,0.5],[0,1]]) # bbox of width 1 on a side with center (0,0,0) ds = yt.load_uniform_grid(data, cube.shape, length_unit=(2*R,R_unit), nprocs=1, bbox=bbox,geometry="spherical") #cam = volume_plot(ds) cam = vol_vis(ds) return ds,cam
def yt_load(ds_name, fields, use_ftype=False, periodic=True): try: with h5py.File(ds_name) as ds: mars_r = ds.attrs['radius'] except: print("Can't load radius from h5 file, assuming Mars Radius") mars_r = 3390.0 data = load_data(ds_name, fields=fields) xlim = (data['x'].min(), data['x'].max()) ylim = (data['y'].min(), data['y'].max()) zlim = (data['z'].min(), data['z'].max()) bbox = np.array([xlim, ylim, zlim]) for test_field in data.keys(): if test_field not in ["attrs", "x", "y", "z"]: break shape = data[test_field].shape #data['H_p1_number_density'].shape attrs = data['attrs'] data = {("gas", k): v for k, v in data.items() if k not in ["attrs", 'x', 'y', 'z']} for f in data.keys(): if "velocity" in f[1]: data[f] = (data[f], "km/s") if "number_density" in f[1]: data[f] = (data[f], "cm**-3") if "magnetic_field" in f[1]: data[f] = (data[f], "nT") if periodic: periodicity = (True, True, True) else: periodicity = (False, False, False) ds = yt.load_uniform_grid(data, shape, mars_r * 1e5, bbox=bbox, periodicity=periodicity) ds.my_attributes = attrs return ds
log=False, color=colors, bottom=[0]) if os.path.exists(out_dir) is False: os.mkdir(out_dir) plt.savefig(os.path.join(out_dir, 'transfer_function.png')) # load the data as a uniform grid, create the 3d scene sc_mult = 1.0 # scale multiplier bbox = model.cart['bbox'] # list-like [[xmin,xmax],[ymin,ymax],[zmin,zmax]] ds = yt.load_uniform_grid(data, data[datafld].shape, sc_mult, bbox=bbox, nprocs=1, periodicity=(True, True, True), unit_system="mks") sc = yt.create_scene(ds, datafld) # Draw the domain boundary and useful grids lat_rnge = [ np.min(model.data.variables['latitude']), np.max(model.data.variables['latitude']) ] lon_rnge = [ np.min(model.data.variables['longitude']), np.max(model.data.variables['longitude']) ]
dis_x.append((val2[0]-val1[0])*cm_to_km) dis_y.append(slice_height) side_x.append(val1[0]) side_x.append(val2[0]) side_y.append(slice_height) side_y.append(slice_height) side_time.append(ti*dt) jet_sides_index1_array.append(jet_sides_index1) jet_sides_index2_array.append(jet_sides_index2) data = dict(density=(arr_rho, "g/cm**3"), b1=(arr_b1, "gauss"), b2=(arr_b2, "gauss"),pressure=(arr_p,"dyne/cm**2"), temperature=(arr_T,"K")) bbox = np.array([[-2.5e4-shift_x_factor, 2.5e4-shift_x_factor], [0, 3e4], [-1, 1]]) ds = yt.load_uniform_grid(data, arr_rho.shape, length_unit="km", bbox=bbox, nprocs=128) # for i in sorted(ds.field_list): # print(i) # trying to use yt for magnetic tension. doesnt work b1_grad_fields = ds.add_gradient_fields(('stream', 'b1')) b2_grad_fields = ds.add_gradient_fields(('stream', 'b2')) # trying to calc magnetic tension def _magnetic_tension_(field, data): dxb1 = data['b1_gradient_x'] dyb1 = data['b1_gradient_y'] dxb2 = data['b2_gradient_x'] dyb2 = data['b2_gradient_y'] b1 = data['b1'] b2 = data['b2']
err = masclet.tools.clean_field(err, cr0amr, solapst, npatch, up_to_level=up_to_level) u = masclet.tools.uniform_grid_zoom_parallel(err, ubox, up_to_level, npatch, patchnx, patchny, patchnz, patchrx, patchry, patchrz, size, nmax, ncores=ncores, copies=2, verbose=True) bbox = np.array([[ubox[0], ubox[1]], [ubox[2], ubox[3]], [ubox[4], ubox[5]]]) data = dict(Error=u) ds = yt.load_uniform_grid(data, u.shape, 3.08e24, bbox=bbox, nprocs=ncores) slc = yt.SlicePlot(ds, 'z', 'Error') slc.save(plotname) if verbose: print('#####################') print('Error field is computed!') print('#####################')
#vel_div = track['velocity_divergence'].reshape(track['velocity_divergence'].shape + (1,)) #div_vel = track['divvel_plus'].reshape(track['divvel_plus'].shape + (1,)) den = rs2(track['density'][:, 1]) cell_v = rs2(track['cell_volume'][:, 1]) data = { 'density': den, 'magnetic_field_strength': mag, #'_vel_mag':vel_bulk, #'velocity_divergence':vel_div, 'my_vol': cell_v, #'divvel_plus':div_vel, 'velocity_magnitude': vel } bbox = np.array([[0., 1.]] * 3) ds = yt.load_uniform_grid(data, den.shape, length_unit="cm", bbox=bbox) ad = ds.all_data() extrema = { 'density': [5e-3, 100], 'magnetic_field_strength': [0.25, 100], 'velocity_magnitude': [5e-3, 100] } def ratio_pair(field, ad_pre=None, ad_cores=None, extrema={}, zlim=[1e-2, 1e4]): pdf_pre = yt.create_profile(ad_pre, [field[0], field[1]],
def show_potential_with_yt(self,output='',angle=np.pi/4.0, N_layer=5, alpha_norm=5.0, cmap='BrBG', Proj=0, Slice=0, gifmaking=0, show3D=0, continoursshade = 50.0, boxoutput='scratch/opac_phi3D_Gauss_phases_mean'): """ Visualize the gravitational potential using yt. We're after something like http://yt-project.org/doc/_images/vr_sample.jpg - described at http://yt-project.org/doc/visualizing/volume_rendering.html """ # Load the potential field into a yt data structure, # offsetting such that minimum value is zero. # First get extrema of phi array: mi = np.min(self.phi) ma = np.max(self.phi) print mi, ma # Symmetrize to put zero at center of range: ma = np.max(np.abs([mi,ma])) mi = -ma # Offset to make minimum value zero: offset = ma ma = 2.0*ma mi = 0.0 # Size of the box containing the phi # Physical -2 to 2 box # bbox = np.array([[-2, 2], [-2, 2], [-2, 2]]) # Physical box from the iFFT bbox = np.array([[np.min(self.x), np.max(self.x)], [np.min(self.y), np.max(self.y)], [np.min(self.z), np.max(self.z)]]) # Apply offset and store phi array in a yt data structure, # I'm putting some random density units here # (seems to be needed to display properly): xnorm=np.sqrt(self.x**2 + self.y**2 + self.z**2); if (Slice is not 1) and (Proj is not 1): indgtr = (~(xnorm < 0.9)).astype(int) indsmlr = (~(xnorm > 1.1)).astype(int) ind = indgtr*indsmlr sphere = np.ones(self.phi.shape) sphere = 5.*ind #sphere = 0.0007*ind negsphere = -self.phi*ind else: sphere = np.zeros(self.phi.shape) negsphere = np.zeros(self.phi.shape) #self.phi[0,0,200]=-40 #self.phi[-1,-1,200]=20 #phiprime=self.phi #phiprime[np.where(self.phi<-18)]=-20 # ds = yt.load_uniform_grid((dict(density=(self.phi+sphere, 'g/cm**3'), Xnorm=(xnorm, 'g/cm**3'))), self.phi.shape, bbox=bbox, nprocs=1) ds = yt.load_uniform_grid((dict(density=(self.phi+offset+sphere, 'g/cm**3'), Xnorm=(xnorm, 'g/cm**3'))), self.phi.shape, bbox=bbox, nprocs=1) field = 'density' #Check that the loaded field is recognized by yt # print ds.field_list # Here's Sam's gist, from https://gist.github.com/samskillman/0e574d1a4f67d3a3b1b1 # im, sc = yt.volume_render(ds, field='phi') # sc.annotate_domain(ds) # sc.annotate_axes() # im = sc.render() # im.write_png(output, background='white') # volume_render is not yet available, though. # Following the example at http://yt-project.org/doc/visualizing/volume_rendering.html # Set minimum and maximum of plotting range (in proper yt units): dd = ds.all_data() mi2, ma2 = dd.quantities.extrema(field) #print "Extrema of ds phi:",mi,ma, mi2, ma2 use_log = False # Instantiate the ColorTransferFunction. # tf = yt.ColorTransferFunction((mi2, ma2)) # tf.grey_opacity=True # Add some isopotential surface layers: # tf.add_layers(N_layer, 0.0000005*(ma2 - mi2) / N_layer, alpha=alpha_norm*np.ones(N_layer,dtype='float64'), colormap = cmap) # Instantiate the ColorTransferFunction using the transfer function helper. from IPython.core.display import Image from yt.visualization.volume_rendering.transfer_function_helper import TransferFunctionHelper tfh = yt.TransferFunctionHelper(ds) tfh.set_field('density') tfh.set_log(False) tfh.set_bounds() tfh.build_transfer_function() tfh.tf.grey_opacity=True #For small units, wide Gaussians: tfh.tf.add_layers(N_layer, w=0.0005*(ma2 - mi2) /N_layer, mi=0.2*ma, ma=ma-0.2*ma, alpha=alpha_norm*np.ones(N_layer,dtype='float64'), col_bounds=[0.2*ma,ma-0.2*ma] , colormap=cmap) #For big units, small Gaussians #tfh.tf.add_layers(N_layer, w=0.00000005*(ma2 - mi2) /N_layer, mi=0.3*ma, ma=ma-0.2*ma, alpha=alpha_norm*np.ones(N_layer,dtype='float64'), col_bounds=[0.3*ma,ma-0.3*ma] , colormap=cmap) if (Slice is not 1) and (Proj is not 1): tfh.tf.map_to_colormap(5., 10.0, colormap='jet', scale=continoursshade) #tfh.tf.map_to_colormap(0.001, 0.0014, colormap='jet', scale=continoursshade) #tfh.tf.add_layers(1, w=0.001*ma2, mi=0.0108, ma=0.012, colormap='Pastel1', col_bounds=[0.01, 0.012]) # Check if the transfer function captures the data properly: densityplot1 = tfh.plot('densityplot1') densityplot2 = tfh.plot('densityplot2', profile_field='cell_mass') # Set up the camera parameters: center, looking direction, width, resolution c = (np.max(self.x)+np.min(self.x))/2.0 Lx = np.sqrt(2.0)*np.cos(angle) Ly = np.sqrt(2.0)*np.sin(angle) Lz = 0.75 L = np.array([Lx, Ly, Lz]) W = ds.quan(1.6, 'unitary') N = 512 # Create a camera object cam = ds.camera(c, L, W, N, tfh.tf, fields=[field], log_fields = [use_log], no_ghost = False) cam.transfer_function = tfh.tf if self.Pdist == 1: im1 = cam.snapshot('scratch/opac_phi3D_Uniform_phases_0-'+str(self.Pmax)+'.png', clip_ratio=5) else: im1 = cam.snapshot('scratch/'+boxoutput+str(self.Pmax)+'_var'+str(self.Pvar)+'.png', clip_ratio=5) im1.write_png('scratch/transparent_bg.png', background=[0.,0.,0.,0.]) im1.write_png('scratch/white1_bg.png', background=[1.,1.,1.,1.]) nim = cam.draw_grids(im1) #im=cam.snapshot #nim = cam.draw_box(im, np.array([0.25,0.25,0.25]), np.array([0.75,0.75,0.75])) if show3D == 1: nim.write_png(boxoutput) cam.show() # Make a color bar with the colormap. # cam.save_annotated("vol_annotated.png", nim, dpi=145, clear_fig=False) self.cam = cam if gifmaking == 1: # Add the domain box to the image: nim = cam.draw_domain(im1) # Save the image to a file: nim.write_png(output) if Proj == 1: s = yt.ProjectionPlot(ds, "z", "density") #this still doesnt work : s.annotate_sphere([0., 0., 0.], radius=(1, 'kpc'), circle_args={'color':'red', "linewidth": 3}) s.show() s.save('phi') if Slice == 1: w = yt.SlicePlot(ds, "z", "density", center="c") w.set_cmap(field="density", cmap='jet') w.annotate_sphere([0., 0., 0.], radius=(1, 'cm'), circle_args={'color':'red',"linewidth": 3}) w.show() w.save('phi') return
dir = '/srv/astro/erosolo/n253/cubes/newrelease/lines/robust/non_pbcor/' tracer = 'hcn' cube= fits.getdata(dir+'ngc253_'+tracer+'_clean_RO.fits') #ALMA data has a polarization axis. Collapse along it. cube = cube.squeeze() #Log transform the data in order to get on a viewable scale # color transfer function no longer correct. #cube = np.log(cube) # Masking out nan elements cube[np.isnan(cube)] = np.nanmin(cube) # Loading data into yt structure data = dict(density = cube) pf = yt.load_uniform_grid(data, cube.shape, 9e16) # Set the min/max to the data set (in units of log10(I)) # These values are specific to the example cube mi,ma = -2.47,-0.764 # Define a colour transfer function. tf = yt.ColorTransferFunction((mi, ma)) c = (pf.domain_right_edge + pf.domain_left_edge)/2.0 nLayer = 10 tf.add_layers(nLayer, w=0.005,colormap='gist_rainbow', alpha = np.logspace(-1.0,0,nLayer)) nStep = 6 # Number of frames in the movie phiarray = np.linspace(0,2*np.pi,nStep) count = 0
if dim == 2: arr3d = np.transpose(arr1d.reshape((1, N, N))) bbox = np.array([[0, N * dh], [0, N * dh], [0, dh]]) elif dim == 3: arr3d = np.transpose(arr1d.reshape((N, N, N))) bbox = np.array([[0, N * dh], [0, N * dh], [0, N * dh]]) else: sys.exit('ERROR : dim must be 2/3 !!') data = {} data[field] = (arr3d, str(data_unit[0]) + "*" + data_unit[1]) ds = yt.load_uniform_grid(data, arr3d.shape, length_unit=length_unit, bbox=bbox, nprocs=1) # plot sz = yt.SlicePlot(ds, "z", field, center='c', origin=('left', 'window')) #sz = yt.ProjectionPlot( ds, "z", field, center='c', origin=('left','window') ) sz.set_unit(field, plot_unit) #sz.set_zlim( field, 1.0e4, 1.0e8 ) #sz.set_colorbar_label( field, "Surface density [$\\mathrm{M_\\odot/kpc^2}$]" ) #sz.annotate_scale( coeff=5.0, unit='kpc', pos=(0.15,0.10) ) #sz.hide_axes() #sz.set_cmap( field, "afmhot" ) #sz.set_figure_size( 16 ) #sz.set_buff_size( 2048 )
def show_potential_with_yt( self, output='', angle=np.pi / 4.0, N_layer=5, alpha_norm=5.0, cmap='BrBG', Proj=0, Slice=0, gifmaking=0, show3D=0, continoursshade=50.0, boxoutput='scratch/opac_phi3D_Gauss_phases_mean', slicerad=1): """ Visualize the gravitational potential using yt. We're after something like http://yt-project.org/doc/_images/vr_sample.jpg - described at http://yt-project.org/doc/visualizing/volume_rendering.html """ # Load the potential field into a yt data structure, # offsetting such that minimum value is zero. # First get extrema of phi array: mi = np.min(self.phi) ma = np.max(self.phi) print mi, ma # Symmetrize to put zero at center of range: ma = np.max(np.abs([mi, ma])) mi = -ma # Offset to make minimum value zero: offset = ma ma = 2.0 * ma mi = 0.0 # Size of the box containing the phi # Physical -2 to 2 box # bbox = np.array([[-2, 2], [-2, 2], [-2, 2]]) # Physical box from the iFFT bbox = np.array([[np.min(self.x), np.max(self.x)], [np.min(self.y), np.max(self.y)], [np.min(self.z), np.max(self.z)]]) # Apply offset and store phi array in a yt data structure, # I'm putting some random density units here # (seems to be needed to display properly): xnorm = np.sqrt(self.x**2 + self.y**2 + self.z**2) if (Slice is not 1) and (Proj is not 1): indgtr = (~(xnorm < 0.9)).astype(int) indsmlr = (~(xnorm > 1.1)).astype(int) ind = indgtr * indsmlr sphere = np.ones(self.phi.shape) sphere = 5. * ind #sphere = 0.0007*ind negsphere = -self.phi * ind else: sphere = np.zeros(self.phi.shape) negsphere = np.zeros(self.phi.shape) #self.phi[0,0,200]=-40 #self.phi[-1,-1,200]=20 #phiprime=self.phi #phiprime[np.where(self.phi<-18)]=-20 # ds = yt.load_uniform_grid((dict(density=(self.phi+sphere, 'g/cm**3'), Xnorm=(xnorm, 'g/cm**3'))), self.phi.shape, bbox=bbox, nprocs=1) ds = yt.load_uniform_grid( (dict(density=(self.phi + offset + sphere, 'g/cm**3'), Xnorm=(xnorm, 'g/cm**3'))), self.phi.shape, bbox=bbox, nprocs=1) field = 'density' #Check that the loaded field is recognized by yt # print ds.field_list # Here's Sam's gist, from https://gist.github.com/samskillman/0e574d1a4f67d3a3b1b1 # im, sc = yt.volume_render(ds, field='phi') # sc.annotate_domain(ds) # sc.annotate_axes() # im = sc.render() # im.write_png(output, background='white') # volume_render is not yet available, though. # Following the example at http://yt-project.org/doc/visualizing/volume_rendering.html # Set minimum and maximum of plotting range (in proper yt units): dd = ds.all_data() mi2, ma2 = dd.quantities.extrema(field) #print "Extrema of ds phi:",mi,ma, mi2, ma2 use_log = False # Instantiate the ColorTransferFunction. # tf = yt.ColorTransferFunction((mi2, ma2)) # tf.grey_opacity=True # Add some isopotential surface layers: # tf.add_layers(N_layer, 0.0000005*(ma2 - mi2) / N_layer, alpha=alpha_norm*np.ones(N_layer,dtype='float64'), colormap = cmap) # Instantiate the ColorTransferFunction using the transfer function helper. from IPython.core.display import Image from yt.visualization.volume_rendering.transfer_function_helper import TransferFunctionHelper tfh = yt.TransferFunctionHelper(ds) tfh.set_field('density') tfh.set_log(False) tfh.set_bounds() tfh.build_transfer_function() tfh.tf.grey_opacity = True #For small units, wide Gaussians: tfh.tf.add_layers(N_layer, w=0.0005 * (ma2 - mi2) / N_layer, mi=0.2 * ma, ma=ma - 0.2 * ma, alpha=alpha_norm * np.ones(N_layer, dtype='float64'), col_bounds=[0.2 * ma, ma - 0.2 * ma], colormap=cmap) #For big units, small Gaussians #tfh.tf.add_layers(N_layer, w=0.00000005*(ma2 - mi2) /N_layer, mi=0.3*ma, ma=ma-0.2*ma, alpha=alpha_norm*np.ones(N_layer,dtype='float64'), col_bounds=[0.3*ma,ma-0.3*ma] , colormap=cmap) if (Slice is not 1) and (Proj is not 1): tfh.tf.map_to_colormap(5., 10.0, colormap='jet', scale=continoursshade) #tfh.tf.map_to_colormap(0.001, 0.0014, colormap='jet', scale=continoursshade) #tfh.tf.add_layers(1, w=0.001*ma2, mi=0.0108, ma=0.012, colormap='Pastel1', col_bounds=[0.01, 0.012]) # Check if the transfer function captures the data properly: densityplot1 = tfh.plot('densityplot1') densityplot2 = tfh.plot('densityplot2', profile_field='cell_mass') # Set up the camera parameters: center, looking direction, width, resolution c = (np.max(self.x) + np.min(self.x)) / 2.0 Lx = np.sqrt(2.0) * np.cos(angle) Ly = np.sqrt(2.0) * np.sin(angle) Lz = 0.75 L = np.array([Lx, Ly, Lz]) W = ds.quan(1.6, 'unitary') N = 512 # Create a camera object cam = ds.camera(c, L, W, N, tfh.tf, fields=[field], log_fields=[use_log], no_ghost=False) cam.transfer_function = tfh.tf if self.Pdist == 1: im1 = cam.snapshot('scratch/opac_phi3D_Uniform_phases_0-' + str(self.Pmax) + '.png', clip_ratio=5) else: im1 = cam.snapshot('scratch/' + boxoutput + str(self.Pmax) + '_var' + str(self.Pvar) + '.png', clip_ratio=5) im1.write_png('scratch/transparent_bg.png', background=[0., 0., 0., 0.]) im1.write_png('scratch/white1_bg.png', background=[1., 1., 1., 1.]) nim = cam.draw_grids(im1) #im=cam.snapshot #nim = cam.draw_box(im, np.array([0.25,0.25,0.25]), np.array([0.75,0.75,0.75])) if show3D == 1: nim.write_png(boxoutput) cam.show() # Make a color bar with the colormap. # cam.save_annotated("vol_annotated.png", nim, dpi=145, clear_fig=False) self.cam = cam if gifmaking == 1: # Add the domain box to the image: nim = cam.draw_domain(im1) # Save the image to a file: nim.write_png(output) if Proj == 1: s = yt.ProjectionPlot(ds, "z", "density") #this still doesnt work : s.annotate_sphere([0., 0., 0.], radius=(1, 'kpc'), circle_args={ 'color': 'red', "linewidth": 3 }) s.show() s.save('phi') if Slice == 1: w = yt.SlicePlot(ds, "z", "density", center=[0, 0, slicerad]) w.set_cmap(field="density", cmap=cmap) circrad = np.sqrt(1 - slicerad * slicerad) w.annotate_sphere([0., 0., 0.], radius=(circrad, 'cm'), circle_args={ 'color': 'red', "linewidth": 3 }) w.show() w.save('phi') return
ax.set_ylim3d(0, WD) ax.set_zlim3d(Range) ax.set_xlabel('X axis(m)') ax.set_ylabel('Y axis(m)') ax.set_zlabel('Z axis(m)') ax.legend(loc='best') #plt.show() print('End of Simulation') mag = Bz0**2 + Bx0**2 + By0**2 #data = { 'Bz' : (Bz0,'gauss'),'By' : (By0,'gauss'), 'Magnitude' : (mag,'gauss')} data = dict(Bz=(Bz0), By=(By0), Bx=(Bx0), Magnitude=(mag)) print data.keys() bbox = np.array([[0, 0.05], [0, 0.5], [0, 0.5]]) ds = yt.load_uniform_grid(data, data['Magnitude'].shape, length_unit="Mpc", bbox=bbox) slc = yt.SlicePlot(ds, "y", ['Magnitude'], center=(0.025, 0.25, 0.25)) slc.set_log('Magnitude', False) slc.save('mode ' + mode + m + n + ' B-field ' + 'x-z cross-section') slc = yt.SlicePlot(ds, "x", ['Magnitude'], center=(0.025, 0.25, 0.25)) slc.set_log('Magnitude', False) slc.save('mode ' + mode + m + n + ' B-field ' + 'y-z cross-section') mag2 = Ez0**2 + Ex0**2 + Ey0**2 #data = { 'Ez' : (Ez0,'gauss'),'Ey' : (Ey0,'gauss'), 'Magnitude' : (mag,'gauss')} data = dict(Ez=(Ez0), Ey=(Ey0), Ex=(Ex0), Magnitude=(mag2)) print data.keys() bbox = np.array([[0, 0.05], [0, 0.5], [0, 0.5]]) ds = yt.load_uniform_grid(data,
def core_model_dust(outname, x_co=1.0e-4, x_h2co=1.0e-9, x_ch3oh=1e-9, zh2=2.8, sz=16, max_rad=10000*u.au, rbreak=1000*u.au, radius_cm=1*u.au.to(u.cm), mass_g=1*u.M_sun.to(u.g), n0=5e8*u.cm**-3, power=-1.5, recompute_dusttemperature=True, luminosity=2e4*u.L_sun,): if not os.path.exists('dustkappa_mrn5.inp'): get_dust_opacity() mu_h2 = yt.YTArray(zh2 * u.Da.to(u.g), 'g') # Problem setup: pure density field zz,yy,xx = np.indices([sz,sz,sz]) rr = ((zz-(sz-1)/2.)**2 + (yy-(sz-1)/2.)**2 + (xx-(sz-1)/2.)**2)**0.5 max_velo = 1*u.km/u.s velo = max_velo - np.array([(sz-1)/2.-zz, (sz-1/2.)-yy, (sz-1/2.)-xx]) / rr.max() * max_velo # now rr has units rr = rr * max_rad / (sz/2.) dens = broken_powerlaw(rr, rbreak=rbreak, n0=n0, power=power) data = {('gas','density'): ((dens*u.Da*zh2).to(u.g/u.cm**3), "g/cm**3"), ('gas','z_velocity'): (velo[0].to(u.km/u.s).value, 'km/s'), ('gas','y_velocity'): (velo[1].to(u.km/u.s).value, 'km/s'), ('gas','x_velocity'): (velo[2].to(u.km/u.s).value, 'km/s'), } bbox = np.array([[-max_rad.value,max_rad.value]]*3) ds = yt.load_uniform_grid(data, dens.shape, length_unit="au", bbox=bbox, nprocs=64) dust_to_gas = 0.01 def _DustDensity(field, data): return dust_to_gas * data['density'] ds.add_field(("gas", "dust_density"), function=_DustDensity, units="g/cm**3") def _NumberDensityH2(field, data): return (1./mu_h2)*data['density'] # data['density']# ds.add_field(("gas", "number_density_H2"), function=_NumberDensityH2, units="cm**-3") def _GasTemperature(field, data): return yt.YTArray(np.ones_like(data['density'])*100., 'K') ds.add_field(("gas", "temperature"), function=_GasTemperature, units='K') def _DustTemperature(field, data): return yt.YTArray(np.ones_like(data['density'])*100., 'K') ds.add_field(("gas", "dust_temperature"), function=_DustTemperature, units='K') writer = RadMC3DWriter(ds) writer.write_amr_grid() dens_fn = "numberdens_h2.inp" # not h2_numberdens.inp? writer.write_line_file(("gas", "number_density_H2"), dens_fn) writer.write_dust_file(("gas", "temperature"), "gas_temperature.inp") writer.write_dust_file(("gas", "dust_density"), "dust_density.inp") #writer.write_dust_file(("gas", "dust_temperature"), "dust_temperature.inp") writer.write_line_file([('gas','x_velocity'), ('gas','y_velocity'), ('gas','z_velocity')], "gas_velocity.inp") # central star position_cm = [0.0, 0.0, 0.0] temperature_K = 1000.0 temperature_K = ((luminosity / (4 * np.pi * (radius_cm*u.cm)**2 * constants.sigma_sb))**0.25 ).to(u.K).value star = RadMC3DSource(radius_cm, mass_g, position_cm, temperature_K) sources_list = [star] wavelengths_micron = np.logspace(-1.0, 4.0, 1000) writer.write_source_files(sources_list, wavelengths_micron) get_dust_opacity() params=dict(istar_sphere=0, itempdecoup=0, lines_mode=3, nphot=1000000, nphot_scat=30000, nphot_spec=100000, rto_style=3, scattering_mode=0, scattering_mode_max=0, tgas_eq_tdust=1,) params_string = """ istar_sphere = {istar_sphere} itempdecoup = {itempdecoup} lines_mode = {lines_mode} nphot = {nphot} nphot_scat = {nphot_scat} nphot_spec = {nphot_spec} rto_style = {rto_style} scattering_mode = {scattering_mode} scattering_mode_max = {scattering_mode_max} tgas_eq_tdust = {tgas_eq_tdust} """ with open('wavelength_micron.inp', 'w') as fh: fh.write("{0}\n".format(len(wavelengths_micron))) for nu in wavelengths_micron: fh.write("{0}\n".format(nu)) # with open('stars.inp', 'w') as fh: # fh.write("2\n") # nstars = 1 # nlam = nfrq # fh.write("{0} {1}\n".format(nstars,nlam)) # rstar = (1*u.au).to(u.cm).value # mstar = 15*u.M_sun.to(u.g) # x,y,z = 0,0,0 # fh.write("{0} {1} {2} {3} {4}\n".format(rstar, mstar, x, y, z)) # for nu in wavelengths_micron: # fh.write("{0}\n".format(nu)) # temperature = 1000 * u.K # for nu in wavelengths_micron: # fh.write("{0}\n".format(-temperature.to(u.K).value)) with open('radmc3d.inp','w') as f: params['lines_mode'] = 1 # 3 = sobolev (LVG) f.write(params_string.format(**params)) if recompute_dusttemperature: # compute the dust temperature assert os.system('radmc3d mctherm') == 0 dust_temperature = read_dust_temperature('dust_temperature.bdat', sz=sz) shutil.copy('dust_temperature.bdat','dust_temperature_{0}.bdat'.format(outname)) else: try: shutil.copy('dust_temperature_{0}.bdat'.format(outname),'dust_temperature.bdat',) except Exception as ex: print(ex) dust_temperature = read_dust_temperature('dust_temperature.bdat', sz=sz) if os.path.exists('lines.inp'): os.remove('lines.inp') assert os.system('radmc3d image npix 50 incl 0 sizeau 10000 noscat pointau 0.0 0.0 0.0 fluxcons lambda 1323 dpc 5400') == 0 im = radmc3dPy.image.readImage('image.out') im.writeFits('dustim1323um_{0}.fits'.format(outname), fitsheadkeys={}, dpc=5400, coord='19h23m43.963s +14d30m34.56s', overwrite=True) return dust_temperature
def plot_LIC(U_grid, V_grid, method='yt', cmap="viridis", normalize=False, density=1, lim=(0, 1), const_alpha=False, kernellen=100, xlab='Dim 1', ylab='Dim 2', file=None): """Visualize vector field with quiver, streamline and line integral convolution (LIC), using velocity estimates on a grid from the associated data. A white noise background will be used for texture as default. Adjust the bounds of lim in the range of [0, 1] which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. When const_alpha=False, alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used. Arguments --------- U_grid: 'np.ndarray' Original data. V_grid: 'np.ndarray' Original data. method: 'float' sigma2 is defined as sum(sum((Y - V)**2)) / (N * D) cmap: 'float' Percentage of inliers in the samples. This is an inital value for EM iteration, and it is not important. normalize: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. density: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. lim: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. const_alpha: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. kernellen: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. Returns ------- P: 'np.ndarray' Posterior probability, related to equation 27. E: `np.ndarray' Energy, related to equation 26. """ if method == 'yt': velocity_x_ori, velocity_y_ori, velocity_z_ori = U_grid, V_grid, np.zeros( U_grid.shape) velocity_x = np.repeat(velocity_x_ori[:, :, np.newaxis], V_grid.shape[1], axis=2) velocity_y = np.repeat(velocity_y_ori[:, :, np.newaxis], V_grid.shape[1], axis=2) velocity_z = np.repeat(velocity_z_ori[np.newaxis, :, :], V_grid.shape[1], axis=0) data = {} data["velocity_x"] = (velocity_x, "km/s") data["velocity_y"] = (velocity_y, "km/s") data["velocity_z"] = (velocity_z, "km/s") data["velocity_sum"] = (np.sqrt(velocity_x**2 + velocity_y**2), "km/s") ds = yt.load_uniform_grid(data, data["velocity_x"][0].shape, length_unit=(1.0, "Mpc")) slc = yt.SlicePlot(ds, "z", ["velocity_sum"]) slc.set_cmap("velocity_sum", cmap) slc.set_log("velocity_sum", False) slc.annotate_velocity(normalize=normalize) slc.annotate_streamlines('velocity_x', 'velocity_y', density=density) slc.annotate_line_integral_convolution('velocity_x', 'velocity_y', lim=lim, const_alpha=const_alpha, kernellen=kernellen) slc.set_xlabel(xlab) slc.set_ylabel(ylab) slc.show() if file is not None: # plt.rc('font', family='serif', serif='Times') # plt.rc('text', usetex=True) # plt.rc('xtick', labelsize=8) # plt.rc('ytick', labelsize=8) # plt.rc('axes', labelsize=8) slc.save(file, mpl_kwargs={figsize: [2, 2]}) elif method == 'lic': velocyto_tex = runlic(V_grid, V_grid, 100) plot_LIC_gray(velocyto_tex)
potdata = np.transpose(np.loadtxt('potential.csv', delimiter=',', usecols=3).reshape((num['x'], num['y'], num['z'])), (1,2,0)) # Load wavefunction data wave_file = [] if parital: wave_file = 'wavefunction_' + number + '_partial.csv' else: wave_file = 'wavefunction_' + number + '.csv' wavedata = np.abs(np.transpose(np.loadtxt(wave_file, delimiter=',', usecols=3).reshape((num['x'], num['y'], num['z'])), (1,2,0))) # Build yt structure data = dict(potential = (potdata, 'eV'), wavefunction = wavedata) bbox = np.array([[-x, x], [-y, y], [-z, z]]) ds = yt.load_uniform_grid(data, potdata.shape, bbox=bbox, length_unit=1, nprocs=numcpus) # Plot slices in y slc = yt.SlicePlot(ds, 'y', ['potential', 'wavefunction']) slc.set_log('wavefunction' , False) slc.set_log('potential' , False) slc.set_axes_unit('m') slc.set_cmap('potential', 'Blues') slc.annotate_grids(cmap=None) slc.save() # Volume renders. These are very finiky, so you need to alter the values case by case. # Documentation can be found here: http://yt-project.org/doc/visualizing/volume_rendering.html #Find the min and max of the field mi, ma = ds.all_data().quantities.extrema('wavefunction') #Reduce the dynamic range
def line_integral_conv( adata, basis="umap", U_grid=None, V_grid=None, xy_grid_nums=[50, 50], method="yt", cmap="viridis", normalize=False, density=1, lim=(0, 1), const_alpha=False, kernellen=100, V_threshold=None, vector='velocity', file=None, save_show_or_return='show', save_kwargs={}, g_kwargs_dict={}, ): """Visualize vector field with quiver, streamline and line integral convolution (LIC), using velocity estimates on a grid from the associated data. A white noise background will be used for texture as default. Adjust the bounds of lim in the range of [0, 1] which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. When const_alpha=False, alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used. Arguments --------- adata: :class:`~anndata.AnnData` AnnData object that contains U_grid and V_grid data basis: `str` (default: trimap) The dimension reduction method to use. U_grid: 'np.ndarray' (default: None) Original velocity on the first dimension of a 2 d grid. V_grid: 'np.ndarray' (default: None) Original velocity on the second dimension of a 2 d grid. xy_grid_nums: `tuple` (default: (50, 50)) the number of grids in either x or y axis. The number of grids has to be the same on both dimensions. method: 'float' sigma2 is defined as sum(sum((Y - V)**2)) / (N * D) cmap: 'float' Percentage of inliers in the samples. This is an inital value for EM iteration, and it is not important. normalize: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. density: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. lim: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. const_alpha: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. kernellen: 'float' Paramerter of the model of outliers. We assume the outliers obey uniform distribution, and the volume of outlier's variation space is a. V_threshold: `float` or `None` (default: None) The threshold of velocity value for visualization vector: `str` (default: `velocity`) Which vector type will be used for plotting, one of {'velocity', 'acceleration'} or either velocity field or acceleration field will be plotted. save_show_or_return: {'show', 'save', 'return'} (default: `show`) Whether to save, show or return the figure. save_kwargs: `dict` (default: `{}`) A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function will use the {"path": None, "prefix": 'line_integral_conv', "dpi": None, "ext": 'pdf', "transparent": True, "close": True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys according to your needs. Returns ------- Nothing, but plot the vector field with quiver, streamline and line integral convolution (LIC). """ import matplotlib.pyplot as plt X = adata.obsm["X_" + basis][:, :2] if "X_" + basis in adata.obsm.keys() else None V = ( adata.obsm[vector + '_' + basis][:, :2] if vector + '_' + basis in adata.obsm.keys() else None ) if X is None: raise Exception( f"The {basis} dimension reduction is not performed over your data yet." ) if V is None: raise Exception( f"The {basis}_velocity velocity (or velocity) result does not existed in your data." ) if U_grid is None or V_grid is None: if "VecFld_" + basis in adata.uns.keys(): # first check whether the sparseVFC reconstructed vector field exists X_grid_, V_grid = ( adata.uns["VecFld_" + basis]["VecFld"]["grid"], adata.uns["VecFld_" + basis]["VecFld"]["grid_V"], ) N = int(np.sqrt(V_grid.shape[0])) U_grid = np.reshape(V_grid[:, 0], (N, N)).T V_grid = np.reshape(V_grid[:, 1], (N, N)).T elif "grid_velocity_" + basis in adata.uns.keys(): # then check whether the Gaussian Kernel vector field exists X_grid_, V_grid_, _ = ( adata.uns["grid_velocity_" + basis]["X_grid"], adata.uns["grid_velocity_" + basis]["V_grid"], adata.uns["grid_velocity_" + basis]["D"], ) U_grid = V_grid_[0, :, :].T V_grid = V_grid_[1, :, :].T else: # if no VF or Gaussian Kernel vector fields, recreate it grid_kwargs_dict = { "density": None, "smooth": None, "n_neighbors": None, "min_mass": None, "autoscale": False, "adjust_for_stream": True, "V_threshold": None, } grid_kwargs_dict.update(g_kwargs_dict) X_grid_, V_grid_, _ = velocity_on_grid( X[:, [0, 1]], V[:, [0, 1]], xy_grid_nums, **grid_kwargs_dict ) U_grid = V_grid_[0, :, :].T V_grid = V_grid_[1, :, :].T if V_threshold is not None: mass = np.sqrt((V_grid ** 2).sum(0)) if V_threshold is not None: V_grid[0][mass.reshape(V_grid[0].shape) < V_threshold] = np.nan if method == "yt": try: import yt except ImportError: print( "Please first install yt package to use the line integral convolution plot method. " "Install instruction is provided here: https://yt-project.org/" ) velocity_x_ori, velocity_y_ori, velocity_z_ori = ( U_grid, V_grid, np.zeros(U_grid.shape), ) velocity_x = np.repeat( velocity_x_ori[:, :, np.newaxis], V_grid.shape[1], axis=2 ) velocity_y = np.repeat( velocity_y_ori[:, :, np.newaxis], V_grid.shape[1], axis=2 ) velocity_z = np.repeat( velocity_z_ori[np.newaxis, :, :], V_grid.shape[1], axis=0 ) data = {} data["velocity_x"] = (velocity_x, "km/s") data["velocity_y"] = (velocity_y, "km/s") data["velocity_z"] = (velocity_z, "km/s") data["velocity_sum"] = (np.sqrt(velocity_x ** 2 + velocity_y ** 2), "km/s") ds = yt.load_uniform_grid( data, data["velocity_x"][0].shape, length_unit=(1.0, "Mpc") ) slc = yt.SlicePlot(ds, "z", ["velocity_sum"]) slc.set_cmap("velocity_sum", cmap) slc.set_log("velocity_sum", False) slc.annotate_velocity(normalize=normalize) slc.annotate_streamlines("velocity_x", "velocity_y", density=density) slc.annotate_line_integral_convolution( "velocity_x", "velocity_y", lim=lim, const_alpha=const_alpha, kernellen=kernellen, ) slc.set_xlabel(basis + "_1") slc.set_ylabel(basis + "_2") slc.show() if file is not None: # plt.rc('font', family='serif', serif='Times') # plt.rc('text', usetex=True) # plt.rc('xtick', labelsize=8) # plt.rc('ytick', labelsize=8) # plt.rc('axes', labelsize=8) slc.save(file, mpl_kwargs={"figsize": [2, 2]}) elif method == "lic": # velocyto_tex = runlic(V_grid, V_grid, 100) # plot_LIC_gray(velocyto_tex) pass if save_show_or_return == "save": s_kwargs = {"path": None, "prefix": 'line_integral_conv', "dpi": None, "ext": 'pdf', "transparent": True, "close": True, "verbose": True} s_kwargs = update_dict(s_kwargs, save_kwargs) save_fig(**s_kwargs) elif save_show_or_return == "show": plt.tight_layout() plt.show() elif save_show_or_return == "return": return slc
Lx = 5.0 Ly = 5.0 Lz = 5.0 xMax, xMin = Lx / 2, -Lx / 2 yMax, yMin = Ly / 2, -Ly / 2 zMax, zMin = Lz / 2, -Lz / 2 dx, dy, dz = Lx / (nWidth - 1), Ly / (nHeight - 1), Lz / (nDepth - 1) Z, Y, X = np.mgrid[zMin:zMax:nDepth * 1j, yMin:yMax:nHeight * 1j, xMin:xMax:nWidth * 1j] arr = np.cos(X) * np.cos(Y) * np.cos(Z) + 20 data = {'density': (arr, "g/cm**3")} bbox = np.array([[-1.5, 1.5], [-1.5, 1.5], [-1.5, 1.5]]) ds = yt.load_uniform_grid(data, arr.shape, length_unit="Mpc", bbox=bbox, nprocs=64) #slc = yt.SlicePlot(ds, "z", ["density"]) #slc.set_cmap("density", "Blues") #slc.annotate_grids(cmap=None) #slc.show() #Find the min and max of the field mi, ma = ds.all_data().quantities.extrema('density') ##Reduce the dynamic range #mi = mi.value + 1.5e7 #ma = ma.value - 0.81e7 tf = yt.ColorTransferFunction((mi, ma), )
from matplotlib import cm if(1): # override for quick testing ris,__,__ = np.shape(H2) ris1,ris2 = ris/4 , 3*ris/4 H2 = np.copy(density[ris1:ris2,ris1:ris2,ris1:ris2]) H2[H2<=0] = np.min(H2[H2>0]) shape_data = H2.shape bounds = (1.e-3, 1.e+3) data = dict(density=H2) # data = dict(density=density*H2) #data = dict(density=density, H2=H2) ds = yt.load_uniform_grid(data, shape_data) #dd = ds.all_data() # from refined_snapshot28_ytclump_fields import _h2density # from yt.units import dimensions # ds.add_field(("stream", "h2density"), function=_h2density, units='code_mass/code_length**3') # units="1/cm**3") sc = yt.create_scene(ds, lens_type='perspective') # Get reference to the VolumeSource associated with this scene # It is the first source associated with the scene, so we can refer to it # using index 0. source = sc[0] source.set_log = True
#grab binary data file, convert to 3d array simulation_data = np.fromfile(filepath, np.float64).reshape( (box_size, box_size, box_size)) ##First Question, can I convert the raw density values into g/cm**3 by multiplying by density_conv variable? data = dict(density=(simulation_data * density_conv, "g/cm**3"), particle_position_x=(simulation_data, 'Mpc'), particle_position_y=(simulation_data, 'Mpc'), particle_position_z=(simulation_data, 'Mpc')) bbox = np.array([[0, sim_dim], [0, sim_dim], [0, sim_dim]]) #load array into yt dataset # ds = yt.load_uniform_grid(data, simulation_data.shape, length_unit=(voxel, "Mpc"), mass_unit=(1.0,"Msun"),bbox=bbox, nprocs=box_size) ds = yt.load_uniform_grid(data, simulation_data.shape, length_unit="Mpc", bbox=bbox, nprocs=box_size) # ad = ds.all_data() def matter_density_field(field, data): matter_a = (matter_0 / (scale_factor**3)) / ((matter_0 / (scale_factor**3)) + lambda_0) # print("----matter_a------") # print(matter_a) # print(np.average(data['matter_density'] )) # print("----------") matter_a = data['density'] * (matter_0 / lambda_0)
def make_onezone_dataset(density=1e-26, temperature=1000, metallicity=0.3, domain_width=10.): """ Create a one-zone hydro dataset for use as test data. The dataset consists of a single cubicle cell of gas with hydro quantities specified in the function kwargs. It makes an excellent test dataset through which to send a sightline and test Trident's capabilities for making absorption spectra. Using the defaults and passing a ray through the full domain should result in a spectrum with a good number of absorption features. **Parameters** :density: float, optional The gas density value of the dataset in g/cm**3 Default: 1e-26 :temperature: float, optional The gas temperature value of the dataset in K Default: 10**3 :metallicity: float, optional The gas metallicity value of the dataset in Zsun Default: 0.3 :domain_width: float, optional The width of the dataset in kpc Default: 10. **Returns** **Example** Create a simple one-zone dataset, pass a ray through it, and generate a COS spectrum for that ray. >>> import trident >>> ds = trident.make_onezone_dataset() >>> ray = trident.make_simple_ray(ds, ... start_position=ds.domain_left_edge, ... end_position=ds.domain_right_edge, ... fields=['density', 'temperature', 'metallicity']) >>> sg = trident.SpectrumGenerator('COS') >>> sg.make_spectrum(ray) >>> sg.plot_spectrum('spec_raw.png') """ one = np.ones([1, 1, 1]) zero = np.zeros([1, 1, 1]) dens = np.array([[[density]]]) * one temp = np.array([[[temperature]]]) * one metal = np.array([[[metallicity]]]) * one domain_width *= 1e3 * pc / cm bbox = np.array([[0., domain_width], [0., domain_width], [0., domain_width]]) data = { 'density': dens, 'temperature': temp, 'metallicity': metal * Zsun, 'velocity_x': zero, 'velocity_y': zero, 'velocity_z': zero } return load_uniform_grid(data, one.shape, length_unit='cm', mass_unit='g', bbox=bbox)
arr = np.zeros((Nx,Ny,Nz), dtype=np.float64) arr[:,:,:] = 1.0 bbox = np.array([ [xmin, xmax], [ymin, ymax], [zmin, zmax] ]) # coordinates -- in the notation data[i, j, k] dcoord = (xmax - xmin)/Nx x = np.linspace(xmin+dcoord, xmax-dcoord, Nx, endpoint=True) y = np.linspace(ymin+dcoord, ymax-dcoord, Ny, endpoint=True) z = np.linspace(zmin+dcoord, zmax-dcoord, Nz, endpoint=True) x3d, y3d, z3d = np.meshgrid(x, y, z, indexing="ij") data = dict(Density = arr) ds = yt.load_uniform_grid(data, arr.shape, bbox=bbox) import yt.visualization.volume_rendering.api as vr # looking from edge in midplane z c = np.array([-5*xmax,-5*ymax,0.5*(zmin+zmax)]) L = np.array([1.0, 1.0, 0.0]) zoom = 4.0 # looking from below c = np.array([-5*xmax,-5*ymax,-1.0*zmax]) L = np.array([1.0, 1.0, 0.5]) zoom = 1.0 W = zoom*ds.domain_width N = 720
velo = max_velo - u.Quantity([mid - zz, mid - yy, mid - xx ]) / rr.max() * max_velo # now rr has units dens = broken_powerlaw(rr, rbreak=rbreak, n0=5e8 * u.cm**-3, power=-1.5) data = { 'density': ((dens * u.Da * zh2).to(u.g / u.cm**3), "g/cm**3"), 'z_velocity': (velo[0].to(u.km / u.s).value, 'km/s'), 'y_velocity': (velo[1].to(u.km / u.s).value, 'km/s'), 'x_velocity': (velo[2].to(u.km / u.s).value, 'km/s'), } bbox = np.array([[-max_rad.value, max_rad.value]] * 3) ds = yt.load_uniform_grid(data, dens.shape, length_unit="au", bbox=bbox, nprocs=64) dust_to_gas = 0.01 def _DustDensity(field, data): return dust_to_gas * data['density'] ds.add_field(("gas", "dust_density"), function=_DustDensity, units="g/cm**3") def _NumberDensityCH3OH(field, data): return (1. / mu_h2) * data['density'] * x_ch3oh # data['density']#
data = {'particle_velocity_x':u, 'particle_velocity_y':v, 'particle_velocity_z':w, 'density':density} ''' #density = np.expand_dims(p,axis=-1) data = {'x-velocity': u, 'y-velocity': v, 'z-velocity': w, 'density': density} #ds = yt.visualization.fits_image.FITSImageData(data,wcs=WCS(stokes_i.header)) #s = yt.FITSSlice(ds,'z','density') #s.show() ds = yt.load_uniform_grid(data, (p.shape[0], p.shape[1], 1)) print(dir(ds.fields.stream)) exit() print(ds.field_list) print(ds.derived_field_list) s = yt.SlicePlot(ds, 'z', 'density') #s.annotate_streamlines('density_gradient_x','density_gradient_y',factor=16) s.annotate_streamlines('x-velocity', 'y-velocity', factor=16) #s.set_origin('lower-left-domain') #print(dir(s)) #print(s) #print(ds.field_list) #print(ds.derived_field_list)
zz,yy,xx = np.indices([sz,sz,sz]) * max_rad / (sz/2.) mid = max_rad * (sz-1.)/sz rr = ((zz-mid)**2 + (yy-mid)**2 + (xx-mid)**2)**0.5 max_velo = 2*u.km/u.s velo = max_velo - u.Quantity([mid-zz, mid-yy, mid-xx]) / rr.max() * max_velo # now rr has units dens = broken_powerlaw(rr, rbreak=rbreak, n0=5e8*u.cm**-3, power=-1.5) data = {'density': ((dens*u.Da*zh2).to(u.g/u.cm**3), "g/cm**3"), 'z_velocity': (velo[0].to(u.km/u.s).value, 'km/s'), 'y_velocity': (velo[1].to(u.km/u.s).value, 'km/s'), 'x_velocity': (velo[2].to(u.km/u.s).value, 'km/s'), } bbox = np.array([[-max_rad.value,max_rad.value]]*3) ds = yt.load_uniform_grid(data, dens.shape, length_unit="au", bbox=bbox, nprocs=64) dust_to_gas = 0.01 def _DustDensity(field, data): return dust_to_gas * data['density'] ds.add_field(("gas", "dust_density"), function=_DustDensity, units="g/cm**3") def _NumberDensityCH3OH(field, data): return (1./mu_h2)*data['density']*x_ch3oh # data['density']# ds.add_field(("gas", "number_density_CH3OH"), function=_NumberDensityCH3OH, units="cm**-3") def _NumberDensityH2(field, data): return (1./mu_h2)*data['density'] # data['density']# ds.add_field(("gas", "number_density_H2"), function=_NumberDensityH2, units="cm**-3") def _GasTemperature(field, data):
def visualize_tables(table_path, geom_file, slices=True, projections=True, plot_3d=True): tables_dir = dirname(table_path) table_fname = basename(table_path) tables_basename = table_fname for name in [ 'survival_prob', 'avg_photon_x', 'avg_photon_y', 'avg_photon_z' ]: tables_basename = tables_basename.replace('_' + name + '.fits', '') if tables_basename[-1] == '_': tables_basename = tables_basename[:-1] det_string_depth_xyz = np.load(geom_file) num_doms_in_detector = np.prod(det_string_depth_xyz.shape[:2]) data = {} fname = '%s_survival_prob.fits' % tables_basename fpath = join(tables_dir, fname) with pyfits.open(fpath) as fits_file: survival_prob = fits_file[0].data ma = survival_prob.max() print('Max survival probability :', ma) mi = survival_prob.min() print('Min survival probability :', mi) mi_nonzero = survival_prob[survival_prob != 0].min() print('Min non-zero survival probability:', mi_nonzero) data['density'] = (survival_prob, 'kg/m**3') xyz_shape = fits_file[1].data lims = fits_file[2].data doms_used = fits_file[3].data # If 3D, dims represent: (string numbers, depth indices, (x, y, z)) if len(doms_used.shape) == 3: doms_used = np.stack( (doms_used[:, :, 0].flatten(), doms_used[:, :, 1].flatten(), doms_used[:, :, 2].flatten())).T nx, ny, nz = xyz_shape xlims = lims[0, :] ylims = lims[1, :] zlims = lims[2, :] print('x lims:', xlims) print('y lims:', ylims) print('z lims:', zlims) print('(nx, ny, nz):', xyz_shape) num_doms_used = doms_used.shape[0] print('num doms used:', num_doms_used) print('doms used:', doms_used.shape) if slices: mask = survival_prob > 0 #(ma / 10000000) avg_photon_info = {} for dim in ['x', 'y', 'z']: fname = '%s_avg_photon_%s.fits' % (tables_basename, dim) fpath = join(tables_dir, fname) with pyfits.open(fpath) as fits_file: d = np.zeros_like(survival_prob) d[mask] = fits_file[0].data[mask] #d = -fits_file[0].data avg_photon_info[dim] = d data['velocity_' + dim] = (d, 'm/s') avg_photon_info = Cart3DCoord(**avg_photon_info) del mask bbox = lims ds = yt.load_uniform_grid(data, domain_dimensions=(nx, ny, nz), bbox=bbox, nprocs=4) savefig_kw = dict(name=join(tables_dir, tables_basename), suffix='png', mpl_kwargs=dict(dpi=300)) plots = [] sphere_kwargs = dict(radius=(5 * DOM_RADIUS_M, 'cm'), coord_system='data', circle_args=dict(color=(0, 0.8, 0), linewidth=1, alpha=0.3)) if projections: for normal in ['x', 'y', 'z']: prj = yt.ProjectionPlot(ds, normal, 'density') prj.set_log('density', False) prj.set_cmap('density', 'inferno') # Display all doms in the detector for depth_xyz in det_string_depth_xyz: for xyz in depth_xyz: prj.annotate_sphere(xyz, **sphere_kwargs) # Display only doms used (if subset of the detector) if num_doms_used != num_doms_in_detector: kw = deepcopy(sphere_kwargs) kw['radius'] = (15 * DOM_RADIUS_M, 'cm') kw['circle_args']['alpha'] = 1 for depth_xyz in doms_used: prj.annotate_sphere(depth_xyz, **kw) prj.save(**savefig_kw) plots.append(prj) if plot_3d: # Choose a vector representing the viewing direction. L = [-0.5, -0.5, -0.5] # Define the center of the camera to be the domain center c = ds.domain_center[0] #c = (1400*100, 1300*100, 1300*100) # Define the width of the image W = 1.0 * ds.domain_width[0] # Define the number of pixels to render Npixels = 2048 sc = yt.create_scene(ds, 'density') source = sc[0] source.log_field = False tf = yt.ColorTransferFunction((0, ma), grey_opacity=True) tf.map_to_colormap(0, ma, scale=1.0, colormap='inferno') source.set_transfer_function(tf) sc.add_source(source) cam = sc.add_camera() cam.width = W cam.center = c cam.normal_vector = L cam.north_vector = [0, 0, 1] cam.position = (1400, 1300, 1300) #sc.show(sigma_clip=4) sc.save(savefig_kw['name']) plots.append(sc) if slices: skw = deepcopy(sphere_kwargs) skw['circle_args']['color'] = (0.8, 0, 0) if num_doms_used != num_doms_in_detector: center = np.mean(doms_used, axis=0) else: center = (0, 0, 0) #center = det_string_depth_xyz[35, 47] #cut_plane_strings = [1 - s for s in [6, 12, 27, 36, 45, 54, 62, 69, 75]] #normal = #north_vector = (0, 0, 1) for normal in ['x', 'y', 'z']: #if normal == 'x': # plt. slc = yt.SlicePlot(ds, normal=normal, fields='density', center=center) slc.set_cmap('density', 'octarine') #slc.set_log('density', False) for depth_xyz in det_string_depth_xyz: for xyz in depth_xyz: slc.annotate_sphere(xyz, **skw) if num_doms_used != num_doms_in_detector: kw = deepcopy(skw) kw['radius'] = (15 * DOM_RADIUS_M, 'cm') kw['circle_args']['alpha'] = 1 for depth_xyz in doms_used: slc.annotate_sphere(depth_xyz, **kw) nskip = 10 kw = dict(factor=nskip, scale=1e3) if normal == 'x': slc.annotate_quiver('velocity_y', 'velocity_z', **kw) elif normal == 'y': slc.annotate_quiver('velocity_z', 'velocity_x', **kw) elif normal == 'z': slc.annotate_quiver('velocity_x', 'velocity_y', **kw) #slc.annotate_grids(cmap=None) slc.save(**savefig_kw) plots.append(slc) return ds, plots
import numpy as np import yt from astropy.io import fits data0 = fits.open("combined_all_b5_c18o_21_noise_weighted.fits")[0].data ##to make the final obj file small enough to be uploaded to sketchfab # data0 = data0[160:210, 6:63, 66:136] data = dict(Density=data0) ds = yt.load_uniform_grid(data, data0.shape) dd = ds.all_data() sf = ds.surface(dd, "Density", 1.5) sf.export_obj("test", transparency=0.6) print len(sf.vertices[sf.vertices == sf.vertices])