示例#1
0
def test_particle_profile_negative_field():
    # see Issue #1340
    n_particles = int(1e4)

    ppx, ppy, ppz = np.random.normal(size=[3, n_particles])
    pvx, pvy, pvz = -np.ones((3, n_particles))

    data = {
        'particle_position_x': ppx,
        'particle_position_y': ppy,
        'particle_position_z': ppz,
        'particle_velocity_x': pvx,
        'particle_velocity_y': pvy,
        'particle_velocity_z': pvz
    }

    bbox = 1.1 * np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)],
                           [min(ppz), max(ppz)]])
    ds = yt.load_particles(data, bbox=bbox)
    ad = ds.all_data()

    profile = yt.create_profile(ad,
                                ["particle_position_x", "particle_position_y"],
                                "particle_velocity_x",
                                weight_field=None)
    assert profile['particle_velocity_x'].min() < 0
示例#2
0
    def to_yt_dataset(self, box_size, ptypes=None):
        """
        Create an in-memory yt dataset for the particles.

        Parameters
        ----------
        box_size : float
            The width of the domain on a side, in kpc.
        ptypes : string or list of strings, optional
            The particle types to export to the dataset. If
            not set, all will be exported.
        """
        from yt import load_particles
        data = self.fields.copy()
        if ptypes is None:
            ptypes = self.particle_types
        ptypes = ensure_list(ptypes)
        for ptype in ptypes:
            pos = data.pop((ptype, "particle_position"))
            vel = data.pop((ptype, "particle_velocity"))
            for i, ax in enumerate("xyz"):
                data[ptype, "particle_position_%s" % ax] = pos[:,i]
                data[ptype, "particle_velocity_%s" % ax] = vel[:,i]
        return load_particles(data, length_unit="kpc", bbox=[[0.0, box_size]]*3,
                              mass_unit="Msun", time_unit="Myr")
示例#3
0
文件: render_data.py 项目: SKIRT/PTS
def plot(data, bbox):

    """
    This function ...
    :param data:
    :param bbox:
    :return:
    """

    #yt.load_amr_grids()

    ds = yt.load_particles(data, length_unit=parsec, mass_unit=1e8*Msun, n_ref=256, bbox=bbox)

    #xwidth = (data.x_span,"pc",)
    #ywidth = (data.y_span,"pc",)
    xwidth = (bbox[0][1]-bbox[0][0], "pc",)
    ywidth = (bbox[1][1]-bbox[1][0], "pc",)

    #print(ds.derived_field_list)

    what = ('deposit', 'io_density')
    slc = yt.SlicePlot(ds, "z", what)
    slc.set_width((xwidth,ywidth,))

    #slc.show() # only for ipython notebook? :(
    slc.save("test.pdf")
示例#4
0
def create_sph_fields(data_source: YTSelectionContainer,
                      ptype: str = "all",
                      *args,
                      **kwargs) -> Dataset:
    """
    Return a dataset with sph interpolation

    Parameters:
    -----------
    data_source : YTSelectionContainer
        The data source from which particles will be extracted
    ptype : str
        The type of particle to extract
    args, kwargs : extra arguments will be passed to `add_sph_fields`

    Returns
    -------
    ds : Dataset
        A dataset with sph interpolation.
    """
    ds = data_source.ds

    if hasattr(ds, "add_sph_fields"):
        ds.add_sph_fields(*args, **kwargs)
        return ds

    logger.debug("Loading data from data source")
    data = {(ptype, fname): data_source[ftype, fname]
            for (ftype, fname) in ds.field_list
            if (ftype == ptype) and (data_source[ftype, fname].ndim == 1)}

    # Make sure position and masses are copied
    for k in "xyz":
        data[ptype,
             f"particle_position_{k}"] = data_source[ptype,
                                                     f"particle_position_{k}"]
    data[ptype, "particle_mass"] = data_source[ptype, "particle_mass"]
    data[ptype, "particle_identity"] = data_source[ptype, "particle_identity"]
    data[ptype, "particle_family"] = data_source[ptype, "particle_family"]

    periodicity = (True, True, True)
    # No support for aperiodicity for now
    # L, R = data_source.get_bbox()
    # periodicity = (
    #     np.asarray(ds.periodicity)
    #     & (ds.domain_left_edge == L)
    #     & (ds.domain_right_edge == R)
    # )

    logger.debug("Create particle dataset")
    sph_ds = yt.load_particles(data,
                               data_source=data_source,
                               periodicity=periodicity)
    sph_ds.current_redshift = ds.current_redshift  # Copy current redshift
    sph_ds.add_sph_fields(*args, **kwargs, sph_ptype=ptype)

    return sph_ds
示例#5
0
    def plot_particle_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 particle plot showing the mass density of the cut box 
        """

        bbox = 1.1 * 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)]])
        ds = yt.load_particles(self.data,
                               length_unit=kpc,
                               mass_unit=1e10,
                               bbox=bbox,
                               n_ref=4)
        center = self.com
        p = yt.ParticleProjectionPlot(
            ds, projection_plane,
            ['particle_mass'
             ])  #, center=center)#, width=self.box_size, depth=self.box_size)
        p.set_colorbar_label('particle_mass', 'Msun')
        #p.zoom(2)
        p.annotate_text((0.7, 0.85),
                        '%s Gyr' % round(self.header_time(), 2),
                        coord_system='figure',
                        text_args={'color': 'black'})
        p.save('%s' % savename)
        return
示例#6
0
    def yt4x_projection(self, cut_positions, cut_weights, width, 
        axis=0, method='mip', pixels=2048, img_rotate=0, 
        length_unit='kpc', mass_unit='Msun', **kwargs):
        """
        use the yt-4 method of creating a ProjectionPlot out of 
        particle data defined cut_positions and cut_weights, 

        Args:
            * cut_positions (N x 3 array):  array of particle positions

            * cut_weights (len N array):  array of particle weights

            * width (float):  size of box to visualize, in length_unit

            * axis (int or str):  axis to project along

            * method (str):  method to pass to ProjectionPlot.  most 
                             likely either 'integrate' for LOS densities
                             or 'mip' for max-in-pixel volume densities

            * pixels (int):  number of pixels in the image 
                             (scales the dpi; uses a fixed image size)

            * img_rotate (int):  either 0, 90, 180, or 270 to rotate the image 
                                 (in the plane) through that many degrees. 

            * length_unit (str):  unit of the cut_positions

            * mass_unit (str):  unit of the cut_weights

            * ptype (str):  particle type being visualized.  only matters for the colorbar.

            ** kwargs:  passed to yt.ProjectionPlot


        Returns:
            a yt.ProjectionPlot instance
        """
        self.method = method

        ## prepare a dictionary with our data
        ## here the data does HAVE to be in 'io', as that's where 
        ## the sph field adder looks
        data = self.prepare_data_dictionary(cut_positions, cut_weights, 'io', axis, img_rotate)
        
        ## get the bounding box for our particles
        bbox = self.get_bbox(width)

        ## load the particles into yt.  no n_ref this time because we're not 
        ## putting the particles onto a grid (so no refining)
        ds = yt.load_particles(data, length_unit=length_unit, mass_unit=mass_unit, bbox=bbox,
            periodicity=(False, False, False))

        ## since we're not putting on a grid, we have to calculate 
        ## densities in an sph-like way.  this method adds the 
        ## smoothing length and density fields
        ds.add_sph_fields()

        self.field = ('io', 'density')
        self.field_name = self.field[1]

        ## now make the projection.  
        self.proj = yt.ProjectionPlot(ds, axis, self.field, center=np.zeros(3), 
            width=(width, length_unit), buff_size=(pixels, pixels), method=self.method)

        ## again, fix up the background color etc.
        self.set_bgcolor_and_units()

        ## and set our figure size again.  no need to set our 
        ## buff size afterwards because we can set it in the 
        ## constructor now
        self.proj.set_figure_size(self.figure_size)
        
        self.dpi = pixels / self.figure_size

        return self.proj
示例#7
0
    def yt3x_projection(self, cut_positions, cut_weights, width, 
        n_ref=8, axis=0, method='mip', pixels=2048, img_rotate=0, 
        length_unit='kpc', mass_unit='Msun', interpolation='bicubic', 
        **kwargs):
        """
        use the yt-3 method of creating a ProjectionPlot out of 
        particle data defined cut_positions and cut_weights, 

        Args:
            * cut_positions (N x 3 array):  array of particle positions

            * cut_weights (len N array):  array of particle weights

            * width (float):  size of box to visualize, in length_unit

            * n_ref (int):  number of particles to allow in a cell before
                            refining (i.e. refines cells with > n_ref particles).
                            smaller values give a higher resolution image

            * axis (int or str):  axis to project along

            * method (str):  method to pass to ProjectionPlot.  most 
                             likely either 'integrate' for LOS densities
                             or 'mip' for max-in-pixel volume densities

            * pixels (int):  number of pixels in the image 
                             (scales the dpi; uses a fixed image size)

            * img_rotate (int):  either 0, 90, 180, or 270 to rotate the image 
                                 (in the plane) through that many degrees. 

            * length_unit (str):  unit of the cut_positions

            * mass_unit (str):  unit of the cut_weights

            * interpolation (str):  type of interpolation to apply to the image

            ** kwargs:  passed to yt.ProjectionPlot


        Returns:
            a yt.ProjectionPlot instance
        """

        ## set the method as a class variable for future function to use
        self.method = method

        ## put the data in the structure we want
        ## note that we'll use 'io' here as the species name, but 
        ## it's really irrelevant in yt3 -- we can use whatever we want
        ## as long as we're consistent below
        data = self.prepare_data_dictionary(cut_positions, cut_weights, 'io', axis, img_rotate)

        ## build the bounding box
        bbox = self.get_bbox(width)

        ## load the particles into yt.  no periodicity because we've artificially trimmed the particles
        ds = yt.load_particles(data, length_unit=length_unit, mass_unit=mass_unit, bbox=bbox, 
            n_ref=n_ref, periodicity=(False, False, False))


        self.field = ('deposit', 'io_density')
        self.field_name = self.field[1]

        ## make the actual projection
        self.proj = yt.ProjectionPlot(ds, axis, self.field, method=self.method, 
            center=np.zeros(3), width=(width, length_unit), **kwargs)

        ## set the interpolation between pixels in the image
        plot = self.proj.plots[list(self.proj.plots)[0]]
        ax = plot.axes
        img = ax.images[0]
        img.set_interpolation(interpolation)

        ## set the buffer size -- have to do this in post in yt3 main branch
        self.proj.set_buff_size((pixels, pixels))

        ## set the figure size too
        self.proj.set_figure_size(self.figure_size)

        ## store the appropriate DPI for later saving
        self.dpi = pixels / self.figure_size 

        ## fig the color of the background and set units of the colorbar
        self.set_bgcolor_and_units()

        return self.proj
示例#8
0
pos -= CM

ppx, ppy, ppz = pos.T
# Creates data to work with in YT
data = {
    'particle_position_x': pos[:, 0],
    'particle_position_y': pos[:, 1],
    'particle_position_z': pos[:, 2],
    'particle_mass': sn.MassTable[1] * np.ones(len(pos))
}

bbox = 1.1 * np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)],
                       [min(ppz), max(ppz)]])
ds = yt.load_particles(data,
                       length_unit=1000 * parsec,
                       mass_unit=1e10 * Msun,
                       n_ref=64,
                       bbox=bbox)
ad = ds.all_data()

# This is generated with "cloud-in-cell" interpolation.
cic_density = "deposit", "all_cic"
# Neares Neighbor
nn_density = "deposit", "all_density"
nn_deposited_mass = "deposit", "all_mass"
particle_count_per_cell = "deposit", "all_count"

# Choose a center for the render.
c = [0, 0, 0]
'''
# Create the off axis projection.
示例#9
0
def plotHalo(filename, pos, lvl, halo, redshift):

    # Font size
    MEDIUM_SIZE = 20
    SMALL_SIZE = 20
    SSSMALL_SIZE = 11
    plt.rc('font', size=SSSMALL_SIZE)  # controls default text sizes
    plt.rc('axes', titlesize=MEDIUM_SIZE)  # fontsize of the axes title
    plt.rc('axes', labelsize=MEDIUM_SIZE)  # fontsize of the x and y labels
    plt.rc('xtick', labelsize=SMALL_SIZE)  # fontsize of the tick labels
    plt.rc('ytick', labelsize=SMALL_SIZE)  # fontsize of the tick labels

    #rad = (a*b*c)**(1./3.)
    # Filter box
    #ind = np.where((abs(pos[:,0])< 1.5*a) & (abs(pos[:,1])< 1.5*a)& (abs(pos[:,2])< 2*a))[0]
    npos = pos[:, :]
    ppx, ppy, ppz = npos.T

    # Creates data to work with in YT
    data = {
        'particle_position_x': ppx,
        'particle_position_y': ppy,
        'particle_position_z': ppz,
        'particle_mass': DMass * np.ones(len(npos))
    }

    bbox = 1.1 * np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)],
                           [min(ppz), max(ppz)]])
    ds = yt.load_particles(data,
                           length_unit=1000 * parsec,
                           mass_unit=1e10 * Msun,
                           n_ref=64,
                           bbox=bbox)
    ad = ds.all_data()

    # This is generated with "cloud-in-cell" interpolation.
    #cic_density = "deposit", "all_cic"
    # Neares Neighbor
    nn_density = "deposit", "all_density"
    #nn_deposited_mass = "deposit", "all_mass"
    #particle_count_per_cell = "deposit", "all_count"

    # Choose a center for the render.
    c = [0, 0, 0]

    p = yt.ProjectionPlot(ds,
                          'z',
                          nn_density,
                          center=c,
                          weight_field=nn_density,
                          width=(0.2 * (npos.max() - npos.min()), 'kpc'))
    #p = yt.ParticlePlot(ds, 'particle_position_x','particle_position_y', weight_field=nn_density, width=(2*rad,2*rad))

    # Title
    p.annotate_title(filename.split('.')[0])
    # Changes CMap
    p.set_cmap(nn_density, 'inferno')
    # Draws density contour
    p.annotate_contour(nn_density, ncont=10, take_log=True)
    # Plots center of the halo (potential)
    p.annotate_marker(
        (0, 0),
        coord_system='plot',
        plot_args={
            'color': 'blue',
            's': 500,
            'label': "z=" + '{:.2e}'.format(float(redshift))
        })
    p.set_figure_size(6)

    #p.save("tmp.png")
    #p.display()

    ##############################################################################################

    # Gets matplotlib figure,axes
    mpl = p.plots[nn_density]

    #mpl.axes.plot([0],[0], marker = 'o', label = "z="+'{:.2e}'.format(float(redshift)))
    # Draws ellipse
    from matplotlib.patches import Ellipse
    elli = Ellipse(xy=[0, 0],
                   width=2 * 0,
                   height=2 * 0,
                   fill=False,
                   linewidth=0)
    # Filter box
    mpl.axes.add_artist(elli)
    leg = mpl.axes.legend(facecolor='w', loc=0)
    #text = leg.get_texts()
    #plt.setp(text, color = 'w')
    #mpl.figure.savefig("Otro.png")

    #############################################################################################

    mpl.figure.savefig("../Plots/" + lvl + "/" + halo + "/" + filename)

    plt.close()
                  [pz1.min(), pz1.max()]])

px2 = np.random.normal(size=128**3, loc=10.0)
py2 = np.random.normal(size=128**3, loc=10.0)
pz2 = np.random.normal(size=128**3, loc=10.0)

bbox2 = np.array([[px2.min(), px2.max()], [py2.min(), py2.max()],
                  [pz2.min(), pz2.max()]])

print(bbox1, bbox2)

ds1 = yt.load_particles(
    {
        'particle_position_x': px1,
        'particle_position_y': py1,
        'particle_position_z': pz1,
        'particle_mass': np.ones(128**3)
    },
    1.0,
    bbox=bbox1)

ds2 = yt.load_particles(
    {
        'particle_position_x': px2,
        'particle_position_y': py2,
        'particle_position_z': pz2,
        'particle_mass': np.ones(128**3)
    },
    1.0,
    bbox=bbox2)
示例#11
0
def load_brick(filename, bbox=None, center=None, return_ds=True):
    """Load a brick file as outputed by HaloFinder.

    You can pass a bbox (in Mpc) to force the box size."""
    with open(filename, "rb") as f:
        # Load headers
        hvals = {}
        attrs = (('nbodies', 1, 'i'),
                 ('particle_mass', 1, 'f'),
                 ('aexp', 1, 'f'),
                 ('omega_t', 1, 'f'),
                 ('age_univ', 1, 'f'),
                 (('nhalos', 'nsubhalos'), 2, 'i'))

        hvals.update(fpu.read_attrs(f, attrs))

        # Load halo data
        halos = {}
        for _ in range(hvals['nhalos']):
            tmp = _read_halo(f)

            halo_id = tmp.get('particle_identifier')
            halos[halo_id] = tmp

        for _ in range(hvals['nsubhalos']):
            tmp = _read_halo(f)

            halo_id = tmp.get('particle_identifier')
            halos[halo_id] = tmp

    if not return_ds:
        return halos

    # Now converts everything into yt-aware quantities
    def g(key):
        return [halos[i][key] for i in halos]

    am_unit = (1, 'Msun*Mpc*km/s')
    unit_dict = {
        'particle_identifier': (1, '1'), 'particle_mass': (1e11, 'Msun'),
        'particle_position_x': (1, 'Mpc'), 'particle_position_y': (1, 'Mpc'),
        'particle_position_z': (1, 'Mpc'), 'particle_velocity_x': (1, 'km/s'),
        'particle_velocity_y': (1, 'km/s'), 'particle_velocity_z': (1, 'km/s'),
        'subhalo_level': (1, '1'), 'subhalo_hosthalo': (1, '1'),
        'subhalo_host': (1, '1'),
        'subhalo_number': (1, '1'), 'subhalo_next': (1, '1'),
        'particle_angular_momentum_x': am_unit,
        'particle_angular_momentum_y': am_unit,
        'particle_angular_momentum_z': am_unit,
        'virial_radius': (1, 'Mpc'), 'virial_mass': (1e11, 'Msun'),
        'virial_temp': (1, 'K'),
        'virial_vel': (1, 'km/s'),
        'particle_spin': (1, '1'), 'particle_radius': (1, 'Mpc'),
        'particle_axis_a': (1, 'Mpc'), 'particle_axis_b': (1, 'Mpc'),
        'particle_axis_c': (1, 'Mpc')}

    data = {}
    for key in unit_dict:
        intensity = unit_dict[key][0]
        unit = unit_dict[key][1]
        arr = np.array([halos[i][key] for i in halos]) * intensity
        data[key] = (arr, unit)

    n_ref = 1

    ppx, ppy, ppz = [data['particle_position_%s' % d][0]
                     for d in ('x', 'y', 'z')]

    if bbox is not None:
        try:
            bbox = np.array(bbox.to('Mpc'))
        except:
            bbox = np.array(bbox)
        width = bbox[1] - bbox[0]
        left = -width / 2
        right = +width / 2
    else:
        left = np.array([min(ppx), min(ppy), min(ppz)])
        right = np.array([max(ppx), max(ppy), max(ppz)])

    data['particle_position_x'] = (ppx - left[0]), 'Mpc'
    data['particle_position_y'] = (ppy - left[1]), 'Mpc'
    data['particle_position_z'] = (ppz - left[2]), 'Mpc'

    right -= left
    left -= left

    bbox = np.array([left, right]).T

    ds = yt.load_particles(data, length_unit=U.Mpc, mass_unit=1e11*U.Msun,
                           bbox=bbox, n_ref=n_ref)

    @yt.particle_filter('halos', requires=["particle_mass"],
                        filtered_type='all')
    def is_halo(pfilter, data):
        return data[(pfilter.filtered_type, "particle_mass")] > 0

    ds.add_particle_filter('halos')
    return ds
#load the particles into memory
ppx = f[basePath+particlesPath+"/electrons/position/x"][:]
ppy = f[basePath+particlesPath+"/electrons/position/y"][:]
ppz = f[basePath+particlesPath+"/electrons/position/z"][:]
pmx = f[basePath+particlesPath+"/electrons/momentum/x"][:]
pmy = f[basePath+particlesPath+"/electrons/momentum/y"][:]
pmz = f[basePath+particlesPath+"/electrons/momentum/z"][:]
ppm = np.ones_like(ppx) # Generate the same mass for all particles

#create a dictionary for yt
#! you can only use fieldtypes already known by yt
data = {'particle_position_x': ppx, # assumes input is cm
        'particle_position_y': ppy,
        'particle_position_z': ppz,
        'particle_momentum_x': pmx, # assumes input is cm/s
        'particle_momentum_y': pmy,
        'particle_momentum_z': pmz,
        'particle_mass': ppm}

#create the size of the simulation box
bbox = np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)], [min(ppz), max(ppz)]])
print bbox

#load the particles into yt
ds = yt.load_particles(data, n_ref=64, bbox=bbox)

#plot the particles
p = yt.ProjectionPlot(ds, "y", ["all_density"])
p.show()
示例#13
0
ppy = f[basePath + particlesPath + "/electrons/position/y"][:]
ppz = f[basePath + particlesPath + "/electrons/position/z"][:]
pmx = f[basePath + particlesPath + "/electrons/momentum/x"][:]
pmy = f[basePath + particlesPath + "/electrons/momentum/y"][:]
pmz = f[basePath + particlesPath + "/electrons/momentum/z"][:]
ppm = np.ones_like(ppx)  # Generate the same mass for all particles

#create a dictionary for yt
#! you can only use fieldtypes already known by yt
data = {
    'particle_position_x': ppx,  # assumes input is cm
    'particle_position_y': ppy,
    'particle_position_z': ppz,
    'particle_momentum_x': pmx,  # assumes input is cm/s
    'particle_momentum_y': pmy,
    'particle_momentum_z': pmz,
    'particle_mass': ppm
}

#create the size of the simulation box
bbox = np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)],
                 [min(ppz), max(ppz)]])
print bbox

#load the particles into yt
ds = yt.load_particles(data, n_ref=64, bbox=bbox)

#plot the particles
p = yt.ProjectionPlot(ds, "y", ["all_density"])
p.show()
示例#14
0
def dummy_datasets(dataset, field):

    normal = dataset.get_field_parameter("normal")

    min_pos_x = abs(
        dataset[field,
                'particle_position_relative_x'].in_units("cm").value.min())
    min_pos_y = abs(
        dataset[field,
                'particle_position_relative_y'].in_units("cm").value.min())
    min_pos_z = abs(
        dataset[field,
                'particle_position_relative_z'].in_units("cm").value.min())

    sim_data_verb = {
        "particle_mass":
        dataset.ds.arr(dataset[field, "particle_mass"].in_units("g").value,
                       "g"),
        "particle_age_flip":
        dataset.ds.arr(dataset[field, 'particle_age_flip'].in_units("s").value,
                       "s"),
        "particle_position_x":
        dataset.ds.arr(
            dataset[field, 'particle_position_relative_x'].in_units("cm").value
            + min_pos_x, "cm"),
        "particle_position_y":
        dataset.ds.arr(
            dataset[field, 'particle_position_relative_y'].in_units("cm").value
            + min_pos_y, "cm"),
        "particle_position_z":
        dataset.ds.arr(
            dataset[field, 'particle_position_relative_z'].in_units("cm").value
            + min_pos_z, "cm"),
        "particle_velocity_x":
        dataset.ds.arr(
            dataset[field,
                    'particle_velocity_relative_x'].in_units("cm/s").value,
            "cm/s"),
        "particle_velocity_y":
        dataset.ds.arr(
            dataset[field,
                    'particle_velocity_relative_x'].in_units("cm/s").value,
            "cm/s"),
        "particle_velocity_z":
        dataset.ds.arr(
            dataset[field,
                    'particle_velocity_relative_x'].in_units("cm/s").value,
            "cm/s"),
    }

    box_min = np.hstack((sim_data_verb["particle_position_x"].v,
                         sim_data_verb["particle_position_y"].v,
                         sim_data_verb["particle_position_z"].v)).min()
    box_max = np.hstack((sim_data_verb["particle_position_x"].v,
                         sim_data_verb["particle_position_y"].v,
                         sim_data_verb["particle_position_z"].v)).max()

    bbox = 1.0 * np.array([[box_min, box_max], [box_min, box_max],
                           [box_min, box_max]])

    ds = yt.load_particles(sim_data_verb,
                           length_unit="cm",
                           mass_unit="g",
                           time_unit="s",
                           bbox=bbox,
                           n_ref=1)

    ad = ds.all_data()

    new_center = ad.ds.arr([min_pos_x, min_pos_y, min_pos_z], "cm")

    return ds, new_center

bbox = np.array([[min(data['particle_position_x']), max(data['particle_position_x'])],
                 [min(data['particle_position_y']), max(data['particle_position_y'])],
                 [min(data['particle_position_z']), max(data['particle_position_z'])]])

loading_params = {'length_unit':kiloparsec.in_cgs(),
                  'mass_unit':gram.in_cgs(),
                  'time_unit':second.in_cgs(),
                  'velocity_unit':(centimeter/second).in_cgs(),
                 }

for ii in (1,10,100):
    d = {x: data[x][::ii] for x in data}
    ds = yt.load_particles(d,
                           periodicity=(False,False,False),
                           bbox=bbox,
                           **loading_params)


    direction = 'z'
    proj = yt.ProjectionPlot(ds, direction, ('deposit','all_density'),)
    proj.set_zlim('all', 1e-10, 1e-1)
    proj.set_cmap('all','cubehelix')
    proj.save("z_projection_every{0}th.png".format(ii))

for ii in range(4):
    d = {x: data[x][ii*(len(data[x])/4):(ii+1)*(len(data[x])/4)] for x in data}
    ds = yt.load_particles(d,
                           periodicity=(False,False,False),
                           bbox=bbox,
                           **loading_params)
示例#16
0
def test_particle_profile_negative_field():
    # see Issue #1340
    n_particles = int(1e4)

    ppx, ppy, ppz = np.random.normal(size=[3, n_particles])
    pvx, pvy, pvz = -np.ones((3, n_particles))

    data = {
        'particle_position_x': ppx,
        'particle_position_y': ppy,
        'particle_position_z': ppz,
        'particle_velocity_x': pvx,
        'particle_velocity_y': pvy,
        'particle_velocity_z': pvz
    }

    bbox = 1.1 * np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)],
                           [min(ppz), max(ppz)]])
    ds = yt.load_particles(data, bbox=bbox)
    ad = ds.all_data()

    profile = yt.create_profile(ad,
                                ["particle_position_x", "particle_position_y"],
                                "particle_velocity_x",
                                logs={
                                    'particle_position_x': True,
                                    'particle_position_y': True,
                                    'particle_position_z': True
                                },
                                weight_field=None)
    assert profile['particle_velocity_x'].min() < 0
    assert profile.x_bins.min() > 0
    assert profile.y_bins.min() > 0

    profile = yt.create_profile(ad,
                                ["particle_position_x", "particle_position_y"],
                                "particle_velocity_x",
                                weight_field=None)
    assert profile['particle_velocity_x'].min() < 0
    assert profile.x_bins.min() < 0
    assert profile.y_bins.min() < 0

    # can't use CIC deposition with log-scaled bin fields
    with assert_raises(RuntimeError):
        yt.create_profile(ad, ["particle_position_x", "particle_position_y"],
                          "particle_velocity_x",
                          logs={
                              'particle_position_x': True,
                              'particle_position_y': False,
                              'particle_position_z': False
                          },
                          weight_field=None,
                          deposition='cic')

    # can't use CIC deposition with accumulation or fractional
    with assert_raises(RuntimeError):
        yt.create_profile(ad, ["particle_position_x", "particle_position_y"],
                          "particle_velocity_x",
                          logs={
                              'particle_position_x': False,
                              'particle_position_y': False,
                              'particle_position_z': False
                          },
                          weight_field=None,
                          deposition='cic',
                          accumulation=True,
                          fractional=True)
   m = data[0]
   x = data[1]
   y = data[2]
   z = data[3]

   data_dic = { 'particle_mass'      : m,
                'particle_position_x': x,
                'particle_position_y': y,
                'particle_position_z': z }

   bbox_width = [ max(x)-min(x), max(y)-min(y), max(z)-min(z) ]
   bbox       = np.array(  [  [ min(x)-bext*bbox_width[0], max(x)+bext*bbox_width[0] ],
                              [ min(y)-bext*bbox_width[1], max(y)+bext*bbox_width[1] ],
                              [ min(z)-bext*bbox_width[2], max(z)+bext*bbox_width[2] ]  ]  )

   ds = yt.load_particles( data_dic, length_unit=unit_l, mass_unit=unit_m, time_unit=unit_t,
                           n_ref=nref, bbox=bbox, sim_time=time, periodicity=(False,False,False) )


#  plot
   p = yt.ParticleProjectionPlot( ds, proj_axis, fields=field, center=plot_center,
                                  width=(plot_width[0],plot_width[1]), depth=plot_width[2] )
#  p = yt.ParticlePlot( ds, 'particle_position_x', 'particle_position_y', 'particle_mass' )

   p.set_unit( field, 'Msun' )
   p.set_unit( 'particle_position_x', 'Mpc' )
   p.set_unit( 'particle_position_y', 'Mpc' )
   p.set_zlim( field, 1.0e0, 6.0e0 )
   p.set_cmap( field, colormap )
   p.annotate_timestamp( time_unit='Myr', corner='upper_right', text_args={'color':'k'} )

   p.save( prefix_out+'_%06d'%idx+'.png', mpl_kwargs={'dpi':dpi} )