Exemple #1
0
def test_mesh_slices():
    # This test is temporarily disabled because it is seg faulty,
    # see #1394
    return

    # Perform I/O in safe place instead of yt main dir
    tmpdir = tempfile.mkdtemp()
    curdir = os.getcwd()
    os.chdir(tmpdir)

    np.random.seed(0x4d3d3d3)

    # tetrahedral ds
    ds = fake_tetrahedral_ds()

    for field in ds.field_list:
        for idir in [0, 1, 2]:
            sl = yt.SlicePlot(ds, idir, field)
            sl.annotate_mesh_lines()
            sl.save()

    # hexahedral ds
    ds = fake_hexahedral_ds()

    for field in ds.field_list:
        for idir in [0, 1, 2]:
            sl = yt.SlicePlot(ds, idir, field)
            sl.annotate_mesh_lines()
            sl.save()

    os.chdir(curdir)
    # clean up
    shutil.rmtree(tmpdir)
Exemple #2
0
def yt_derived_field_demo():
    ds = yt.frontends.libyt.libytDataset()
    slc1 = yt.SlicePlot(ds, "z", ("gamer", "level_derived_func"))
    slc2 = yt.SlicePlot(ds, "z", ("gamer", "level_derived_func_with_name"))

    if yt.is_root():
        slc1.save()
        slc2.save()
Exemple #3
0
def anlzD(ds, anlsD, outdir):
    """ Use yt to make plots (z-axis slice) of density and electron temperature for this timestep """
    pltnum = str(ds)[-4:] # Plot number string, e.g. strips "0020" off of "lasslab_hdf5_plt_cnt_0020"

    slc = yt.SlicePlot(ds, 'z', 'dens')
    slc.save('dens_' + pltnum + ".png") # E.g. "dens_0020.png"

    slc = yt.SlicePlot(ds, 'z', 'tele')
    slc.save('pres_' + pltnum + ".png") # E.g. "pres_0020.png"
Exemple #4
0
def slices(ds, slcfname, slc_fields, aux={}):
    ds.coordinates.x_axis[1] = 0
    ds.coordinates.x_axis['y'] = 0
    ds.coordinates.y_axis[1] = 2
    ds.coordinates.y_axis['y'] = 2

    time = ds.current_time.in_units('Myr').v
    c = ds.domain_center
    dx = ds.domain_width / ds.domain_dimensions

    slc_data = {}
    slc_data['time'] = time

    for i, axis in enumerate(['x', 'y', 'z']):
        slc = yt.SlicePlot(ds, axis, slc_fields)
        ix = ds.coordinates.x_axis[axis]
        iy = ds.coordinates.y_axis[axis]
        #        res=(int(slc.width[1]/dx[ix]),int(slc.width[0]/dx[iy]))
        res = (ds.domain_dimensions[ix], ds.domain_dimensions[iy])
        slc_frb = slc.data_source.to_frb(slc.width[0], res, c, slc.width[1])
        extent = np.array(slc_frb.bounds) / 1.e3
        slc_data[axis] = {}
        slc_data[axis + 'extent'] = extent
        for f in slc_fields:
            slc_data[axis][f] = np.array(slc_frb[f])
            if f in aux:
                if 'unit' in aux[f]:
                    slc_data[axis][f] = np.array(slc_frb[f].in_units(
                        aux[f]['unit']))
                    #print(f,aux[f]['unit'])
                if 'factor' in aux[f]: slc_data[axis][f] *= aux[f]['factor']

    if yt.is_root():
        pickle.dump(slc_data, open(slcfname, 'wb'), pickle.HIGHEST_PROTOCOL)
Exemple #5
0
def plot_slice_frames(dsi, fpath = '.'):

    fields = ['N_Fraction','O_Fraction','Fe_Fraction','Ba_Fraction', 'velocity_spherical_radius'] #
    ds = yt.load(fpath + '/DD%0004i/DD%0004i'%(dsi,dsi))
    fg.generate_derived_fields(ds)
    ds = yt.load(fpath + '/DD%0004i/DD%0004i'%(dsi,dsi))
    data = ds.all_data()

    proj = yt.SlicePlot(ds, 'z', center =[0.5,0.5,0.5], fields = fields, width = 2.0*yt.units.kpc)
    proj.set_buff_size(2048)

#    proj.set_cmap('N_N', 'viridis')
#    proj.set_cmap('O_Number_Density', 'magma')
#    proj.set_cmap('Fe_Number_Density', 'plasma')
#    proj.set_cmap('Ba_Number_Density', 'RdYlBu_r')

    for f in fields:
        if f == 'velocity_spherical_radius':
            proj.set_cmap(f, 'cubehelix')
            proj.set_log(f, False)
            proj.set_unit(f, 'km/s')
            proj.set_zlim(f, -400.0, 400.0)
        else:
            proj.set_cmap(f, 'magma')
#        fmin = np.min(proj.data_source[('gas',f)])
#        fmax = np.max(proj.data_source[('gas',f)])
            fmax = np.max( data[f][ data['spherical_radius'] < 1.0*yt.units.kpc])
            plot_min = 1.0E-4 * fmax
            plot_max = fmax
            proj.set_zlim(f, plot_min, plot_max)  #1.0E9,1.0E16)

#    proj.annotate_quiver('velocity_y','velocity_z', 64)
    proj.annotate_streamlines('velocity_y','velocity_z', density = 4)

    proj.save('./elements3/')
def slic_whole(ds,dim,gas_density_extrema,simtype,curr_src):
    """
    ds - dataset
    dim  - 'x','y','z', or array [1,0.5,0.2] for off axis slice
    gas_density_extrema - array [min,max]
    simtype - string 'LCDM' /'Sym D' / etc
    curr_src - current output folder as string, e.g '00009'
    Function assumes that the gas_density_extrema are in cgs units (g/cm**3)
    """
    print datetime.now().strftime('%H:%M:%S'),'Making Slice plots of whole sim along %s axis'%dim

    #Apply units to the extremas and convert to solar masses per kilparsec cubed
    gas_density_extrema = gas_density_extrema*yt.units.g/yt.units.cm**3
    gas_density_extrema = gas_density_extrema.in_units('Msun/kpc**3')

    field = 'density'

    output = yt.SlicePlot(ds, dim, field)
    #save plot object to file
    #output.frb.save_as_dataset('yt_%s_%s_%s_slice_%s'%(simtype,curr_src,field,dim))

    output.annotate_timestamp(corner='upper_left', time=False,redshift=True, draw_inset_box=False)
    output.annotate_scale(corner='upper_right')
    output.set_axes_unit('Mpccm/h')
    output.set_zlim(('gas','density'), gas_density_extrema[0],gas_density_extrema[1])
    output.set_unit(field, 'Msun/kpc**3')
    output.save('%s_%s_%s_slice_%s.png'%(simtype,curr_src,field,dim))
    return output
def halo_over_grid_plot(ds,dim,cen,wid,simtype,curr_src,curr_halo):
    print datetime.now().strftime('%H:%M:%S'),'Making overdensity slice plot of halo #%d along %s axis with grid annotated'%(curr_halo,dim)
    field = 'baryon_overdensity'
    s = yt.SlicePlot(ds, dim, field, center=cen, width=wid)
    s.annotate_grids()
    #s.set_zlim('baryon_overdensity',-2,210)
    s.save('%s_%s_%d_slice_%s_%s_grid.png'%(simtype,curr_src,curr_halo,field,dim))
def halo_over_plot(ds,dim,cen,wid,simtype,curr_src,curr_halo):
    print datetime.now().strftime('%H:%M:%S'),'Making overdensity slice plot of halo #%d along %s axis'%(curr_halo,dim)
    field = 'baryon_overdensity'
    s = yt.SlicePlot(ds, dim, field, center=cen, width=wid)
    s.set_axes_unit('Mpccm/h')
    #s.set_zlim('baryon_overdensity',-2,210)    
    s.save('%s_%s_%d_slice_%s_%s.png'%(simtype,curr_src,curr_halo,field,dim))
Exemple #9
0
def slice_plot(ds,field,width=(5000,"km"),zoffset=False,plotprops=None,debug=False):
    slc = yt.SlicePlot(ds,"x",field,width=width)
    if debug: # faster plotting; lower resolution as one measure for speed-up
        slc.set_buff_size((100,100)) #double resolution.
    else:
        slc.set_buff_size((1600,1600)) #double resolution.
    if zoffset:
        slc.set_center((0,width[0]/2),"km")
    
    # get plot properties for field if existent
    if plotprops is not None:
        fpp = dict(plotprops)
    else:
        fpp = fpps.get(field,{})
    
    # colormap 
    cmap = plt.matplotlib.cm.get_cmap(fpp.get("cmap","viridis"))
    so = fpp.get("cmap_set_over",None)
    if so:
        cmap.set_over(so)
    su = fpp.get("cmap_set_under",None)
    if su:
        cmap.set_under(su)
    slc.set_cmap(field,cmap)
    zlim = fpp.get("zlim",None)
    if zlim:
        slc.set_zlim(field,*zlim)
    zlinthresh = fpp.get("zlinthresh",None)
    slc.set_log(field, fpp.get("log",True),zlinthresh)
    return slc
Exemple #10
0
    def generate_plot(self):
        r"""Generates an on axis slice plot from the given parameters in the
        widget. """
        source = self.parent.active_data_object.data
        axis = self.plot_axis.get_axis()
        fields = self.plot_fields.get_fields()
        c = self.center_w.text()
        w = self.width.get_width()

        if c not in ['m', 'c', '', 'max', 'min']:
            self.center_w.setText("CHANGE IT.")
            c = None

        fs = self.font_size.value()

        field_params = self.field_parameters.get_field_parameters()

        dsource = self.data_source.get_data_source()

        if field_params == "None":
            plot = yt.SlicePlot(source,
                                axis,
                                fields,
                                width=w,
                                fontsize=fs,
                                data_source=dsource)
            view = PlotWindowView(plot)
            self.plot_ref.addSubWindow(view)
            view.show()
def add_plot(ax, ds, field, field_type = 'slice', view = 'x', cmap = 'viridis', \
                 norm_factor = 1.0, cbar = True, vmin = None, vmax = None, weight_field = 'ones'):
        
    if not field_type.__contains__('phase'):
        if field_type.__contains('slice'):
            s = yt.SlicePlot(ds, view, field)
        elif field_type.__contains('proj'):
            s = yt.ProjectionPlot(ds, view, field, weight_field = weight_field)
        frb = s.frb
        xbins = frb['y'].in_units('kpc')
        ybins = frb['z'].in_units('kpc')
        field_frb = frb[field]
        
        if field_type.__contains__('fluct'):
            data = []
            for field_slice in field_frb:
                ave_field = np.mean(field_slice)
                data.append((field_slice - ave_field) / field_slice)
        else:
            data  = field_frb / norm_factor
                
        if vmin == None:
            vmin = min(data)
        if vmax == None: 
            vmax = max(data)

        pcm = ax.pcolormesh(xbins, ybins, data, norm = LogNorm(), cmap = cmap, vmin = vmin, vmax = vmax)
        if cbar:
            cbar = fig.colorbar(pcm, ax = ax, pad=0)
            cbar.set_label('Normalized Density (Slice)')
        elif i == 1:
            cbar.set_label('Normalized Density (Projection)')
        ax[i][0].set_xlabel('y (kpc)')
        ax[i][0].set_ylabel('z (kpc)')
def slice_plot(
    path,
    field,
    axis,
    idx_start=1,
    idx_end=100,
    didx=1,
):
    ts = yt.load([
        path + '/Data_%06d' % idx
        for idx in range(idx_start, idx_end + 1, didx)
    ])
    ds = yt.load(path + '/Data_000001')

    cg = ds.covering_grid(0, left_edge=[0.0, 0.0, 0.0], dims=[256, 256, 256])
    cg.get_data(field)
    field_data = cg[field]

    field_min = field_data.min()
    field_max = field_data.max()

    for ds in ts.piter():

        sz = yt.SlicePlot(ds, axis, field)
        try:
            sz.set_log(field, True)
        except ValueError:
            pass
        sz.set_cmap(field, 'arbre')
        sz.annotate_timestamp(time_unit='code_time',
                              corner='upper_right',
                              time_format='t = {time:.4f} {units}')
        sz.set_zlim(field, field_min, field_max)
        sz.save(name=path + '/images/' + str(ds))
Exemple #13
0
    def plot_all_density(self, projection_plane, savename):
        """
        Inputs:
        ------
        projection_plane: int or str
            0,1,2 or 'x', 'y', 'z' to set which cross section of the 3D data is plotts
            
        savename: str
            String to save file name. Leave off the file extension

        Output:
        ------
        A 2D plot showing the volumetric density of the cut box 
        """

        center = self.com
        ds = yt.load(self.path, bounding_box=self.bbox)
        ad = ds.all_data()

        slc = yt.SlicePlot(ds,
                           projection_plane, ('deposit', 'Disk_density'),
                           center=center)
        slc.set_width((self.box_size, 'kpc'))
        slc.annotate_text((0.7, 0.85),
                          '%s Gyr' % round(self.header_time(), 2),
                          coord_system='figure',
                          text_args={'color': 'white'})
        slc.save('%s' % savename)
        return
Exemple #14
0
def makeslice(ni, no, width=60):
    for i in range(ni, no + 1):
        print i
        filename = 'disk.out1.' + '{:05d}'.format(i) + '.athdf'
        data = yt.load(filename)
        xcenter = data.domain_center[0].d
        left = data.domain_left_edge[0].d
        shift = xcenter - width * 0.5
        slc = yt.SlicePlot(data, 'phi', 'Er')
        slc.pan([-shift, 0])
        slc.set_width(width, 100)
        slc.set_figure_size(4)
        slc.set_cmap(field="Er", cmap='RdGy_r')

        slc.set_colorbar_label("Er", "$E_r/a_rT_0^4$")
        slc.set_zlim(field='Er', zmin=rhomin, zmax=rhomax)
        slc.set_xlabel('$r/r_s$')
        slc.set_ylabel('$z/r_s$')
        slc.annotate_text(
            (0.35, 0.96),
            'time=' + "%4.2f" % (data.current_time * crat) + ' $r_s/c$',
            coord_system='figure',
            text_args={'color': 'black'})
        slc.set_font({
            'family': 'sans-serif',
            'style': 'italic',
            'weight': 'bold',
            'size': 24,
            'color': 'black'
        })
        #slc.annotate_streamlines('velocity_logspherical_logr','velocity_logspherical_theta')
        #slc.annotate_quiver('velocity_logspherical_logr', 'velocity_logspherical_theta',40)
        slc.set_font_size(25)
        outputname = 'disk.' + '{:05d}'.format(i)
        slc.save(outputname)
Exemple #15
0
def draw_3d(ds,options):

    rmax = float(options.rmax)
    var  = options.var
    log  = options.log
    clim = "auto"
    fout = "slice.png"

    ds.periodicity = (True, True, True)
    slice = yt.SlicePlot(ds,'z',[var],
            center=[0,0,0],
            width=(rmax,'cm'))

    if log!="None":
        slice.set_log(var,True)
    else:
        slice.set_log(var,False)
    if clim != "auto":
        slice.set_zlim(var,cmin,cmax)
    slice.set_cmap('entr',cmap="Spectral_r")
    slice.set_width((2.*rmax,2.*rmax))
    slice.save(fout)
    
    # open the image
    image = plt.imread(fout)
    fig, ax = plt.subplots()
    ax.imshow(image)
    ax.axis('off')
    plt.show()

    return
Exemple #16
0
def plot_slice(input_dir, ax, field_data, max_field_value, min_field_value,
               zoom_val, file_name):
    print 'Processor ' + str(os.getpid()) + '\n is plotting slice file ' + str(
        file_name[-4:])
    ds = yt.load(file_name)
    slice_ = yt.SlicePlot(ds, ax, field_data)
    if zoom_val != -1:
        print 'Setting Zoom value.'
        slice_.zoom(zoom_val)
    else:
        print 'No zoom value given. Skipping.'
        None
    if max_field_value != -1:
        print 'Setting max/min field value'
        slice_.set_zlim(field_data, min_field_value, max_field_value)
    else:
        print 'No max/min field value given. Skipping.'
        None
    slice_.set_font_size(24)
    slice_.annotate_timestamp()
    slice_.annotate_title('$10^5$ M$_{\odot}$ Projection ' + field_data)
    slice_.annotate_scale()
    slice_.save('/data/draco/slewis' + input_dir + '/figures/' +
                file_name[-4:])
    print 'Plot ' + str(file_name[-4:]) + ' saved.'
Exemple #17
0
def test_filter_wiring():

    ds = fake_amr_ds(fields=[("gas", "density")], units=["g/cm**3"])
    p = yt.SlicePlot(ds, "x", "density")

    # Note: frb is a FixedResolutionBuffer object
    frb1 = p.frb
    data_orig = frb1["density"].value

    sigma = 2
    nbeam = 30
    p.frb.apply_gauss_beam(nbeam=nbeam, sigma=sigma)
    frb2 = p.frb
    data_gauss = frb2["density"].value

    p.frb.apply_white_noise()
    frb3 = p.frb
    data_white = frb3["density"].value

    # We check the frb objects are different
    assert frb1 is not frb2
    assert frb1 is not frb3
    assert frb2 is not frb3

    # We check the resulting image are different each time
    assert not np.allclose(data_orig, data_gauss)
    assert not np.allclose(data_orig, data_white)
    assert not np.allclose(data_gauss, data_white)
Exemple #18
0
def makeslice(file_num, variable, label, lim1, lim2, width=60):
    filename = 'disk.out1.' + '{:05d}'.format(file_num) + '.athdf'
    data = yt.load(filename)
    xcenter = data.domain_center[0].d
    left = data.domain_left_edge[0].d
    shift = xcenter - width * 0.5
    slc = yt.SlicePlot(data, 'phi', variable)
    slc.pan([-shift, 0])
    slc.set_width(width, 180)
    slc.set_figure_size(4.5)
    slc.set_cmap(field=variable, cmap='RdGy_r')

    slc.set_colorbar_label(variable, label)
    slc.set_zlim(field=variable, zmin=lim1, zmax=lim2)
    slc.set_xlabel('$r/r_s$')
    slc.set_ylabel('$z/r_s$')
    slc.annotate_text(
        (0.35, 0.96),
        'time=' + "%4.2f" % (data.current_time * crat) + ' $r_s/c$',
        coord_system='figure',
        text_args={'color': 'black'})
    slc.set_font({
        'family': 'sans-serif',
        'style': 'italic',
        'weight': 'bold',
        'size': 24,
        'color': 'black'
    })
    #slc.annotate_streamlines('velocity_logspherical_logr','velocity_logspherical_theta')
    #slc.annotate_quiver('velocity_logspherical_logr', 'velocity_logspherical_theta',40)
    slc.set_font_size(25)
    outputname = 'disk.' + '{:05d}'.format(file_num)
    slc.save(outputname)
Exemple #19
0
def SlicePlot_cacherun(ds, *args, **kwargs):
    # ds = RamsesSnapshot(jobdir, out)

    def slice_ds(ds, *args, **kwargs):
        return yt.SlicePlot(ds, *args, **kwargs).data_source

    class T:
        def __init__(self, _ds):
            self._ds = _ds
            self._folder = os.path.dirname(_ds.directory)
            self._outnum = int(os.path.basename(_ds.directory)[-5:])

        def CachePath(self):
            pathname = self._folder
            # Put the cache files in the simulation folder itself
            path = f"{pathname}/cache/cache/yt{yt.__version__}/output" \
                   f"_{self._outnum:05d}/"
            if not os.path.exists(path):
                try:
                    os.makedirs(path)
                except:
                    pass  # Probably fine. Probably.
            return path

    fakesnap = T(ds)
    # new_ds = slice_ds(ds, *args, **kwargs)
    new_ds = CacheRun(slice_ds)(fakesnap, *args, **kwargs)
    return yt.SlicePlot(ds, *args, **kwargs, data_source=new_ds)
Exemple #20
0
def make_images(input_prefix,output_prefix,z_slice,min_dens,max_dens):
    
    ds_pattern = f"{input_prefix}_????/{input_prefix}_????.block_list"
    center = [0.0,0.0,z_slice]
    for ds in yt.DatasetSeries(ds_pattern):

        slc = yt.SlicePlot(ds,"z",("gas","density"),
                           center = center,
                           width = ds.domain_width[0])
        
        box = ds.box(left_edge = -ds.domain_width/2.0,
                     right_edge = ds.domain_width/2.0)
        sink_positions = [s for s in zip(box["sink","x"],
                                         box["sink","y"],
                                         box["sink","z"])]
        for s in sink_positions:
            slc.annotate_marker(s,
                                coord_system = "data",
                                plot_args = {'color':"k"})

        slc.annotate_grids(linewidth = 0.5,alpha = 1.0)
        slc.set_zlim(("gas","density"),min_dens,max_dens)

        current_cycle = ds.parameters["current_cycle"]
        filename = f"{output_prefix}_{current_cycle:03}.png"
        slc.save(filename)
Exemple #21
0
def slices(ds, slcfname, slc_fields):
    global aux
    ds.coordinates.x_axis[1] = 0
    ds.coordinates.x_axis['y'] = 0
    ds.coordinates.y_axis[1] = 2
    ds.coordinates.y_axis['y'] = 2

    time = ds.current_time.in_units('Myr').v
    c = ds.domain_center
    dx = ds.domain_width / ds.domain_dimensions

    slc_data = {}
    slc_data['time'] = time
    ya.check_aux(slc_fields)

    for i, axis in enumerate(['x', 'y', 'z']):
        slc = yt.SlicePlot(ds, axis, slc_fields)
        ix = ds.coordinates.x_axis[axis]
        iy = ds.coordinates.y_axis[axis]
        res = (slc.width[1] / dx[ix], slc.width[0] / dx[iy])

        slc_frb = slc.data_source.to_frb(slc.width[0], res, c, slc.width[1])
        extent = np.array(slc_frb.bounds) / 1.e3
        slc_data[axis] = {}
        slc_data[axis + 'extent'] = extent
        for f in slc_fields:
            if aux[f].has_key('unit'):
                slc_data[axis][f] = np.array(slc_frb[f].in_units(
                    aux[f]['unit']))
            else:
                slc_data[axis][f] = np.array(slc_frb[f])
            if aux[f].has_key('factor'): slc_data[axis][f] *= aux[f]['factor']

    if yt.is_root():
        pickle.dump(slc_data, open(slcfname, 'wb'), pickle.HIGHEST_PROTOCOL)
Exemple #22
0
 def slice_image(filename_prefix):
     sl = yt.SlicePlot(ds, idir, field)
     if annotate:
         sl.annotate_mesh_lines()
     sl.set_log('all', False)
     image_file = sl.save(filename_prefix)
     return image_file
Exemple #23
0
def double_plot(settings, ds):

    fig = plt.figure()
    grid = AxesGrid(fig, (0.09,0.09,0.8,0.8),
                    nrows_ncols = (1, 2),
                    axes_pad = 0.05,
                    label_mode = "L",
                    share_all = True,
                    cbar_location="right",
                    cbar_mode="single",
                    cbar_size="5%",
                    cbar_pad="1.2%")

    for i, fn in enumerate(fns):

        if settings["option"] == "top_down":
            slc = yt.SlicePlot(ds, 
                               'z' , 
                               settings["field"], 
                               center=settings["center"], 
                               width=settings["width"],
                               fontsize=settings["font"])
            if settings["streamlines"]:
                slc.annotate_streamlines('velocity_x', 
                                         'velocity_y', 
                                         density=1.5,
                                         factor=16, 
                                         plot_args={
                                             'color': 'black', 
                                             'linewidth': 0.25})

        if settings["option"] == "side_on":
            slc = yt.OffAxisSlicePlot(ds, 
                                      settings["L"],
                                      settings["field"], 
                                      center=settings["center"], 
                                      north_vector=settings["north_vector"], 
                                      width=settings["width"],
                                      fontsize=settings["font"])
            slc.set_xlabel('x $\ (\mathrm{R}_{\odot})$')
            slc.set_ylabel('z $\ (\mathrm{R}_{\odot})$')
            if settings["streamlines"]:
                slc.annotate_streamlines('magnetic_field_x', 
                                         'magnetic_field_z', 
                                         density=1.5, 
                                         factor=16, 
                                         plot_args={
                                             'color': 'white', 
                                             'linewidth': 0.75})
            
        slc.set_cmap(field=settings["field"], cmap='jet')
        slc.set_zlim(settings["field"], settings["lim"][0], settings["lim"][1])

        plot = slc.plots[settings["field"]]
        plot.figure = fig
        plot.axes = grid[i].axes
        plot.cax = grid.cbar_axes[i]
        slc._setup_plots()

    slc.save("plots/"+settings["save_name"]+".pdf")
Exemple #24
0
def time_series(ds):

    for ds in ts:
        slc = yt.SlicePlot(ds, 'z' , field, center=center, width=width)

        #slc = yt.ProjectionPlot(ds, 'z', field)
        #slc = yt.OffAxisSlicePlot(ds, L, field, center=center, north_vector=north_vector, width=width)

        slc.set_cmap(field=field, cmap='jet')
        """
        slc.annotate_streamlines('magnetic_field_x', 
                                 'magnetic_field_z', 
                                 density=2, 
                                 plot_args={'color': 'white', 'linewidth': 1.0})
        """
        """
        slc.annotate_streamlines('velocity_x', 
                                 'velocity_y', 
                                 density=2, 
                                 plot_args={'color': 'white', 'linewidth': 1.0})
        """                          
        #slc.annotate_line_integral_convolution('velocity_x', 'velocity_z', lim=(0.5,0.65))
        #slc.annotate_cell_edges()
        #slc.annotate_velocity()
        #slc.annotate_line((10.1, 0.0), (-15, 7.2), coord_system='plot')

        slc.save('plots/Free_AMR_higB_highUV/close_up_z.png')
Exemple #25
0
def produce_slice_plot(data, variable, axis=axis):
    slc = yt.SlicePlot(data,
                       axis,
                       variable,
                       width=(width, "cm"),
                       center=center)
    # Set the color scale of variables to log
    slc.set_log(variable, False)
    # Plot Boxes (uncomment next line to activate)
    #slc.annotate_grids()
    # Plot Grid points (uncomment next line to activate)
    #slc.annotate_cell_edges()
    # Plot contours (uncomment next line to activate)
    #slc.annotate_contour(variable)
    # Resolution of the fixed resolution mesh used for plotting
    slc.set_buff_size(1024)
    # Color map used for plooting
    slc.set_cmap(field=variable, cmap="dusk")
    slc.set_xlabel(r"x $\left[\frac{1}{m}\right]$")
    slc.set_ylabel(r"y $\left[\frac{1}{m}\right]$")
    slc.set_colorbar_label(variable, variable)
    slc.annotate_text(
        (0.13, 0.92),
        ("time = " + str(float(data.current_time)) + " 1/m"),
        coord_system="figure",
        text_args={"color": "white"},
    )
    # Set size of plotted window
    slc.set_window_size(10)
    slc.save(variable + "/")
Exemple #26
0
def YT_multislice(cluster):
    r200 = cluster.group_r200()
    fname = cluster.partdata_filePaths()[0]  # dataset to load
    CoP = cluster.group_centre_of_potential()
    print(fname)

    unit_base = {
        'UnitLength_in_cm': 3.08568e+21,
        'UnitMass_in_g': 1.989e+43,
        'UnitVelocity_in_cm_per_s': 100000
    }

    bbox_lim = 1e5  # kpc

    bbox = [[-bbox_lim, bbox_lim], [-bbox_lim, bbox_lim],
            [-bbox_lim, bbox_lim]]

    ds = yt.load(fname, unit_base=unit_base, bounding_box=bbox)
    ad = ds.all_data()
    density = ad[("PartType0", "density")]
    wdens = np.where(density == np.max(density))
    coordinates = ad[("PartType0", "Coordinates")]
    center = coordinates[wdens][0]

    # Create density slices of several fields along the x axis
    yt.SlicePlot(ds,
                 'z', [('gas', 'density'), ('gas', 'temperature')],
                 width=(15 * r200, 'Mpc'),
                 center=center).save()
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()
Exemple #28
0
def make_slice_plot(ds, prefix, field, zmin, zmax, cmap, **kwargs):
    axis = kwargs.get("axis", ['x', 'y', 'z'])  # if axis not set, do all
    box = kwargs.get("box", "")
    center = kwargs.get("center", "")
    appendix = kwargs.get("appendix", "")
    width = kwargs.get("width", default_width)
    resolution = kwargs.get("resolution",
                            (1048, 1048))  # correct for the nref11f box
    ision = kwargs.get("ision", False)
    if ision:
        basename = prefix + 'ions/' + ds.basename + appendix
        if not (os.path.exists(prefix + 'ions/')):
            os.system("mkdir " + prefix + 'ions/')
    else:
        basename = prefix + 'physical/' + ds.basename + appendix
        if not (os.path.exists(prefix + 'physical/')):
            os.system("mkdir " + prefix + 'physical')
    for ax in axis:
        if ision:
            print("field = ", species_dict[field])
            s = yt.SlicePlot(ds,
                             ax,
                             species_dict[field],
                             center=center,
                             data_source=box,
                             width=(width, 'kpc'))
            s.set_zlim(species_dict[field], zmin, zmax)
            s.set_cmap(field=species_dict[field], cmap=cmap)
        else:
            s = yt.SlicePlot(ds,
                             ax,
                             field,
                             center=center,
                             data_source=box,
                             width=(width, 'kpc'))
            s.set_zlim(field, zmin, zmax)
            s.set_cmap(field=field, cmap=cmap)
        s.annotate_timestamp(corner='upper_left',
                             redshift=True,
                             draw_inset_box=True)
        if field == "density" or field == "metal_density":
            s.set_unit(('gas', 'density'), 'Msun/pc**3')
        s.annotate_scale(size_bar_args={'color': 'white'})
        s.hide_axes()
        s.save(basename + '_Slice_' + ax + '_' + field + '.png')
        s.save(basename + '_Slice_' + ax + '_' + field + '.pdf')
    def test_projection_setup(self):
        axis = "x"
        self.slc = yt.SlicePlot(self.ds, axis, "Density")

        assert self.ds.coordinates.data_projection[axis] is None
        assert self.ds.coordinates.data_transform[axis] is None
        assert self.slc._projection is None
        assert self.slc._transform is None
Exemple #30
0
def slice_plot(field, output_filename, pltfile, idir=3):
    """Create an axis-aligned slice plot over a given field with yt."""

    import yt
    import matplotlib.pyplot as plt

    ds = yt.load(pltfile)

    dim = ds.dimensionality

    fields = [field]

    if dim == 1:

        print("This slice plot routine is not implemented in one dimension.")
        exit

    elif dim == 2:

        if idir == 1:
            axis = 'r'
        elif idir == 2:
            axis = 'z'
        elif idir == 3:
            axis = 'theta'
        else:
            print("Unknown direction for slicing in slice_plot.")
            exit

    elif dim == 3:

        if idir == 1:
            axis = 'x'
        elif idir == 2:
            axis = 'y'
        elif idir == 3:
            axis = 'z'
        else:
            print("Unknown direction for slicing in slice_plot.")

    sp = yt.SlicePlot(ds, axis, fields=fields)

    sp.set_cmap(field, 'hot')

    plot = sp.plots[field]

    cb = plot.cb
    cb.solids.set_rasterized(True)

    sp._setup_plots()

    plt.savefig(output_filename)

    insert_commits_into_eps(output_filename, pltfile, 'plot')

    plt.savefig(output_filename[:-4] + '.png')

    plt.close()