Пример #1
0
    def __call__(self, plot):
        data = plot.data
        if iterable(self.width):
            validate_width_tuple(self.width)
            self.width = plot.data.ds.quan(self.width[0], self.width[1])
        elif isinstance(self.width, YTQuantity):
            self.width = plot.data.ds.quan(self.width.value, self.width.units)
        else:
            self.width = plot.data.ds.quan(self.width, "code_length")
        # we construct a rectangular prism
        x0 = plot.xlim[0].to("code_length")
        x1 = plot.xlim[1].to("code_length")
        y0 = plot.ylim[0].to("code_length")
        y1 = plot.ylim[1].to("code_length")
        xx0, xx1 = plot._axes.get_xlim()
        yy0, yy1 = plot._axes.get_ylim()
        if type(self.data_source)==YTCutRegion:
            mylog.warn("Parameter 'width' is ignored in annotate_particles if the "
                       "data_source is a cut_region. "
                       "See https://github.com/yt-project/yt/issues/1933 for further details.")
            self.region=self.data_source
        else:
            self.region=self._get_region((x0,x1), (y0,y1), plot.data.axis, data)
        ax = data.axis
        xax = plot.data.ds.coordinates.x_axis[ax]
        yax = plot.data.ds.coordinates.y_axis[ax]
        axis_names = plot.data.ds.coordinates.axis_name
        field_x = "particle_position_%s" % axis_names[xax]
        field_y = "particle_position_%s" % axis_names[yax]
        pt = self.ptype
        self.periodic_x = plot.data.ds.periodicity[xax]
        self.periodic_y = plot.data.ds.periodicity[yax]
        self.LE = plot.data.ds.domain_left_edge[xax], \
                  plot.data.ds.domain_left_edge[yax]
        self.RE = plot.data.ds.domain_right_edge[xax], \
                  plot.data.ds.domain_right_edge[yax]
        period_x = plot.data.ds.domain_width[xax]
        period_y = plot.data.ds.domain_width[yax]
        particle_x, particle_y = self._enforce_periodic(self.region[pt, field_x],
                                                        self.region[pt, field_y],
                                                        x0, x1, period_x,
                                                        y0, y1, period_y)
        gg = ( ( particle_x >= x0 ) & ( particle_x <= x1 )
           &   ( particle_y >= y0 ) & ( particle_y <= y1 ) )
        if self.indices is not None:
            mask_to_get = na.zeros(self.indices.shape, dtype='int32')
            found_any, mask = particle_ops.mask_particles(
                self.indices.astype('int64'), self.region['particle_index'].astype('int64'), mask_to_get)
            gg = ( gg & (mask == 1) )

        print( "nparticles in particle callback.", mask_to_get.sum())
        if self.minimum_mass is not None:
            gg &= (self.region[pt, "particle_mass"] >= self.minimum_mass)
            if gg.sum() == 0: return
        px, py = [particle_x[gg][::self.stride], particle_y[gg][::self.stride]]
        px, py = self._convert_to_plot(plot, [px, py])
        plot._axes.scatter(px, py, edgecolors='None', marker=self.marker,
                           s=self.p_size, c=self.color,alpha=self.alpha)
        plot._axes.set_xlim(xx0,xx1)
        plot._axes.set_ylim(yy0,yy1)
Пример #2
0
 def deposit_target_particles(field, data):
     #pdb.set_trace()
     target_indices = data.get_field_parameter('target_indices')
     blank = np.zeros(data.ActiveDimensions, dtype='float64')
     if not hasattr(target_indices, 'sum'):
         return blank
     if data.NumberOfParticles == 0: return blank
     if dbg > 0:
         if hasattr(target_indices, 'sum'):
             print("indices inside", target_indices.sum())
         else:
             print("indices inside", target_indices)
             return blank
     #int 32 because it's just a flag.
     #mask_to_get = np.zeros(target_indices.shape, dtype='int32')
     mask_to_get = data.get_field_parameter('mask_to_get')
     my_indices = data['particle_index'].astype('int64')
     found_any, mask = particle_ops.mask_particles(target_indices,
                                                   my_indices, mask_to_get)
     data.set_field_parameter('mask_to_get',
                              mask_to_get)  #keeping the mask is faster
     pos_to_get = data['particle_position'][mask == 1]
     d = data.deposit(pos_to_get, method="count")
     d = data.ds.arr(d, input_units="cm**-3")
     #print("ahoy.", d.sum())
     return data.apply_units(d, field.units)
Пример #3
0
    def __call__(self, plot):
        data = plot.data
        if iterable(self.width):
            self.width = np.float64(
                plot.data.ds.quan(self.width[0], self.width[1]))
        # we construct a recantangular prism
        x0, x1 = plot.xlim
        y0, y1 = plot.ylim
        xx0, xx1 = plot._axes.get_xlim()
        yy0, yy1 = plot._axes.get_ylim()
        if self.bool is None:
            reg = self._get_region((x0, x1), (y0, y1), plot.data.axis, data)
        else:
            reg = self.bool
        ax = data.axis

        xax = plot.data.ds.coordinates.x_axis[ax]
        yax = plot.data.ds.coordinates.y_axis[ax]
        axis_names = plot.data.ds.coordinates.axis_name
        field_x = "particle_position_%s" % axis_names[xax]
        field_y = "particle_position_%s" % axis_names[yax]
        pt = self.ptype
        gg = ((reg[pt, field_x] >= x0) & (reg[pt, field_x] <= x1)
              & (reg[pt, field_y] >= y0) & (reg[pt, field_y] <= y1))
        if self.indices != None:
            print "particle callback warning: this might get expensive"
            mask_to_get = na.zeros(self.indices.shape, dtype='int32')
            found_any, mask = particle_ops.mask_particles(
                self.indices.astype('int64'),
                reg['particle_index'].astype('int64'), mask_to_get)
            gg = (gg & (mask == 1))

        print "nparticles do it.", mask_to_get.sum()
        if False:
            if self.ptype is not None:
                gg &= (reg["particle_type"] == self.ptype)
                if gg.sum() == 0: return
            if self.stars_only:
                gg &= (reg["creation_time"] > 0.0)
                if gg.sum() == 0: return
            if self.dm_only:
                gg &= (reg["creation_time"] <= 0.0)
                if gg.sum() == 0: return
            if self.minimum_mass is not None:
                gg &= (reg["ParticleMassMsun"] >= self.minimum_mass)
                if gg.sum() == 0: return
        plot._axes.hold(True)
        px, py = self.convert_to_plot(plot, [
            np.array(reg[pt, field_x][gg][::self.stride]),
            np.array(reg[pt, field_y][gg][::self.stride])
        ])
        plot._axes.scatter(px,
                           py,
                           edgecolors='None',
                           marker=self.marker,
                           s=self.p_size,
                           c=self.color)
        plot._axes.set_xlim(xx0, xx1)
        plot._axes.set_ylim(yy0, yy1)
        plot._axes.hold(False)
Пример #4
0
def deposit_target_particles_1(field, data):
    #pdb.set_trace()
    indices_late = data.get_field_parameter('indices_late')
    blank = np.zeros(data.ActiveDimensions, dtype='float64')
    if not hasattr(indices_late,'sum'):
        return blank
    if data.NumberOfParticles == 0: return blank
    if dbg > 0:
        if hasattr(indices_late,'sum'):
            print( "indices inside", indices_late.sum())
        else:
            print( "indices inside", indices_late)
            return blank
    #int 32 because it's just a flag.
    #mask_to_get = np.zeros(indices_late.shape, dtype='int32')
    mask_to_get = data.get_field_parameter('mask_to_get')
    t0 = data.get_field_parameter('timer')
    my_indices = data['particle_index'].astype('int64')
    #print "  min thing"
    #mask_to_get[ indices_late < my_indices.min()] = 1
    #mask_to_get[ indices_late > my_indices.max()] = 1
    #print "  left", mask_to_get.size - mask_to_get.sum()
    #print "  search"
    found_any, mask = particle_ops.mask_particles(
        indices_late, my_indices, mask_to_get)
    data.set_field_parameter('mask_to_get',mask_to_get)
    pos_to_get = data['particle_position'][mask == 1]
    d = data.deposit(pos_to_get, method = "count")
    d = data.ds.arr(d, input_units = "cm**-3")
    t1 = time.time() 
    #print "  DT", t1-t0[-1]
    data.set_field_parameter('timer',t0+[t1])
    return data.apply_units(d, field.units)
Пример #5
0
def centroid_line(dirname, target_frame, source_indices, prefix=None, extra_cuts=None, alpha = 0.0):
    """line at angle Alpha wrt y axis through center"""
    """hard coded size.  Fix that"""
    field = 'density'
    ds = yt.load('%s/DD%04d/data%04d'%(dirname,target_frame,target_frame))
    reg = ds.all_data()
    #source_indices = source_region['particle_index']
    mask_to_get = na.zeros(source_indices.shape, dtype='int32')
    found_any, mask = particle_ops.mask_particles(
        source_indices.astype('int64'), reg['particle_index'].astype('int64'), mask_to_get)
    part_x = reg['particle_position_x'][mask==1]
    part_y = reg['particle_position_y'][mask==1]
    part_z = reg['particle_position_z'][mask==1]
    index  = reg['particle_index'][mask==1]
    if extra_cuts is not None:
        if extra_cuts == 80:
            """ how to pass in this complex logic?"""
            keep_low_x = part_x < 0.5
            print "shape", part_x.shape, keep_low_x.sum()
            part_x = part_x[ keep_low_x]
            part_y = part_y[ keep_low_x]
            part_z = part_z[ keep_low_x]
            index = index[keep_low_x]
    cen_x = part_x.sum()/part_x.shape
    cen_y = part_y.sum()/part_y.shape
    cen_z = part_z.sum()/part_z.shape
    delta_x = 1./128
    Left  = nar([ bd(pos.min(), delta_x) for pos in [part_x,part_y,part_z]])
    Right = nar([ bu(pos.max(), delta_x) for pos in [part_x,part_y,part_z]])
    Cen = 0.5*(Left+Right)
    proj = ds.proj('density',0)
    resolution = 128
    frb = proj.to_frb(1.0,resolution)
    y_coord = int(cen_y*resolution)
    z_coord = int(cen_z*resolution)
    
    half_line_width = int(0.25/4.6*resolution) #half line width
    yi = y_coord-half_line_width
    yf = y_coord+half_line_width
    density_stripe = frb['density'][z_coord,yi:yf]
    y_stripe = (frb['y'][z_coord,yi:yf].v- cen_y.v) *4.6
    plt.clf()
    plt.plot(y_stripe,density_stripe)
    plt.ylabel(r'$\Sigma[code]$')
    plt.xlabel(r'$y [pc]$')
    outname = prefix+".png"
    plt.savefig(outname)
    plt.clf()
    den =copy.copy(frb['density'].v)
    den[z_coord,yi:yf] = den.max()
    plt.imshow(np.log10(den),origin='lower', cmap='gray')
    plt.savefig("%s_stripe_loc.png"%prefix)
    print 'test.png'


    print outname
Пример #6
0
def prepositions(dirname, target_frame, source_indices, prefix=None, extra_cuts=None,
                streamlines=False):
    """from clump_particles, dave callback."""
    field = 'density'
    ds = yt.load('%s/DD%04d/data%04d'%(dirname,target_frame,target_frame))
    reg = ds.all_data()
    #source_indices = source_region['particle_index']
    mask_to_get = na.zeros(source_indices.shape, dtype='int32')
    found_any, mask = particle_ops.mask_particles(
        source_indices.astype('int64'), reg['particle_index'].astype('int64'), mask_to_get)
    part_x = reg['particle_position_x'][mask==1]
    part_y = reg['particle_position_y'][mask==1]
    part_z = reg['particle_position_z'][mask==1]
    index  = reg['particle_index'][mask==1]
    if extra_cuts is not None:
        if extra_cuts == 80:
            """ how to pass in this complex logic?"""
            keep_low_x = part_x < 0.5
            print "shape", part_x.shape, keep_low_x.sum()
            part_x = part_x[ keep_low_x]
            part_y = part_y[ keep_low_x]
            part_z = part_z[ keep_low_x]
            index = index[keep_low_x]
    cen_x = part_x.sum()/part_x.shape
    cen_y = part_y.sum()/part_y.shape
    cen_z = part_z.sum()/part_z.shape
    delta_x = 1./128
    Left  = nar([ bd(pos.min(), delta_x) for pos in [part_x,part_y,part_z]])
    Right = nar([ bu(pos.max(), delta_x) for pos in [part_x,part_y,part_z]])
    Cen = 0.5*(Left+Right)
    new_reg = ds.region(Cen,Left,Right)
    for ax in [0,1,2]:
        proj = ds.proj(field,ax,data_source=new_reg,center=[0.5]*3)
        #proj = ds.proj(field,ax,center=[0.5]*3)
        xi= proj.ds.coordinates.x_axis[ax]
        yi= proj.ds.coordinates.y_axis[ax]
        axis_names = ds.coordinates.axis_name
        xv = "velocity_%s" % (axis_names[xi])
        yv = "velocity_%s" % (axis_names[yi])
        pw = proj.to_pw(center=[0.5]*3)
        pw.set_cmap('density','gray')
        pw.annotate_sphere([cen_x,cen_y,cen_z], 0.01, circle_args={'color':'r'})
        #pw.annotate_dave_particles(1.0, indices = index, col='y')
        if streamlines:
            pw.annotate_streamlines(xv,yv,factor=1, density = 4)
            annotate_box(pw,[Left[xi],Left[yi]],[Right[xi],Right[yi]], plot_args={'color':'r'})

        print pw.save(prefix)
Пример #7
0
def target_particle_volume(field, data):
    #pdb.set_trace()
    target_indices = data.get_field_parameter('target_indices')
    blank = np.zeros(data.ActiveDimensions, dtype='float64')
    if type(target_indices) == float:
        return blank
    if data.NumberOfParticles == 0: return blank
    mask_to_get = data.get_field_parameter('mask_to_get')
    my_indices = data['particle_index'].astype('int64')
    print("target_particle_volume nparticles %d" % my_indices.size)
    found_any, mask = particle_ops.mask_particles(target_indices, my_indices,
                                                  mask_to_get)
    data.set_field_parameter('mask_to_get',
                             mask_to_get)  #keeping the mask is faster
    pos_to_get = data['particle_position'][mask == 1]
    d = data.deposit(pos_to_get, method="count")
    d = data.ds.arr(d, input_units="cm**-3")
    mask = d > 0
    d[mask] = data['cell_volume'][mask]
    return d
Пример #8
0
                       right_edge=loc + 1.5 * min_dx)
    indices_late, xpos_late, ypos_late, zpos_late = clump_particles.particles_from_clump(
        region)
    print indices_late.size

if 0:
    """ make a movie with the particles.  Stride 64 over particles to make it go."""
    #indices_0360 = fPickle.load('p19_u02d_0360_indices_late.pickle')
    for frame in [200]:  #range(0,370,10):
        setname = template % (frame, frame)
        ds = yt.load(sggetname)

        if 1:
            mask_to_get = na.zeros(self.indices.shape, dtype='int32')
            found_any, mask = particle_ops.mask_particles(
                self.indices.astype('int64'),
                reg['particle_index'].astype('int64'), mask_to_get)

            region = ds.region

        if 0:
            proj_full = ds.proj('density', 2,
                                center='c')  #width = (1.0,'code_length'))
            pw_full = proj_full.to_pw(center='c', width=(1.0, 'code_length'))
            pw_full.annotate_dave_particles(1.0, col='r', indices=indices_late)
            pw_full.set_cmap('density', 'gray')
            pw_full.save('u02d_early_peak_%04d' % frame)

        if 0:
            ad = ds.all_data()
            mask_to_get = np.zeros(
bad_index = np.where(my_indices==bad_id)
if 'gtots' not in dir():
    gtots = this_looper.snaps[60][31].ds.index.grids[66]
    snap = this_looper.snaps[60][31]


if 'getmask_pos' not in dir():
    getmask_pos = data_region['particle_position'][bad_index]
    getmask_vel = data_region['particle_velocity'][bad_index]
    grid_index=75
    print( 'got the right one: ',gtots['particle_index'][grid_index]==bad_id)
    grid_pos = gtots['particle_position'][grid_index]
    print( getmask_pos-grid_pos)

if 'found_any' not in dir():
    found_any, mask = particle_ops.mask_particles(these_pids,my_indices,mask_to_get)
    data_region['particle_index'][mask.astype('bool')] == bad_id
if 1:
    index_3= np.where( snap.ind == bad_id)
    print("pos: mask",getmask_pos)
    print("pos: snap",snap.pos[index_3])
    print("den: fv", snap.field_values['density'][index_3])

if 1:
    thtr = this_looper.tr
    track_id = np.where(thtr.particle_ids==1499257)
    tr_density = thtr.c(31,'density')
    this_density = tr_density[track_id,-1]
    #print("The density for that particle",this_density)
    print("The density for that particle",thtr.p([bad_id],'density'))
    def __call__(self, plot):
        data = plot.data
        if iterable(self.width):
            self.width = np.float64(plot.data.ds.quan(self.width[0], self.width[1]))
        # we construct a recantangular prism
        x0, x1 = plot.xlim
        y0, y1 = plot.ylim
        xx0, xx1 = plot._axes.get_xlim()
        yy0, yy1 = plot._axes.get_ylim()
        if self.bool is None:
            reg = self._get_region((x0,x1), (y0,y1), plot.data.axis, data)
        else:
            reg = self.bool
        ax = data.axis


        xax = plot.data.ds.coordinates.x_axis[ax]
        yax = plot.data.ds.coordinates.y_axis[ax]
        axis_names = plot.data.ds.coordinates.axis_name
        field_x = "particle_position_%s" % axis_names[xax]
        field_y = "particle_position_%s" % axis_names[yax]
        pt = self.ptype
        shifted_field_x = reg[pt, field_x]
        shifted_field_y = reg[pt, field_y]
        shifted_field = [shifted_field_x, shifted_field_y]
        lower_lim = data.ds.arr([xx0,yy0],'code_length')
        upper_lim = data.ds.arr([xx1,yy1],'code_length')
        dx_min = data.ds.index.get_smallest_dx()*0.1
        for ndim,dim in enumerate([xax,yax]):
            print("SHIFT", ndim, dim)
            if data.ds.periodicity[dim]:
                #If the plot is to the right of the domain
                delta = upper_lim[ndim] - data.ds.domain_right_edge[dim]
                if delta > dx_min:
                    delta = delta + data.ds.domain_left_edge[dim]
                    particles_to_shift = np.where(shifted_field[ndim] < delta)
                    shifted_field[ndim][particles_to_shift] += data.ds.domain_width[dim]
                #If the plot is to the left
                delta = data.ds.domain_left_edge[dim] - lower_lim[ndim]
                if delta > dx_min:
                    delta = data.ds.domain_right_edge[dim] - delta
                    particles_to_shift = np.where(shifted_field[ndim] > delta)
                    shifted_field[ndim][particles_to_shift] -= data.ds.domain_width[dim]



        gg = ( ( shifted_field_x >= x0 ) & ( shifted_field_x <= x1 )
           &   ( shifted_field_y >= y0 ) & ( shifted_field_y <= y1 ) )
        print("CHECK", x0, x1, y0, y1, "npart", reg['particle_index'].size,"n(gg)", gg.sum())
        #import pdb
        #pdb.set_trace()

        if self.indices != None:
            print "particle callback warning: this might get expensive"
            mask_to_get = na.zeros(self.indices.shape, dtype='int32')
            found_any, mask = particle_ops.mask_particles(
                self.indices.astype('int64'), reg['particle_index'].astype('int64'), mask_to_get)
            gg = ( gg & (mask == 1) )

        print "nparticles do it.", mask_to_get.sum()
        if False:
            if self.ptype is not None:
                gg &= (reg["particle_type"] == self.ptype)
                if gg.sum() == 0: return
            if self.stars_only:
                gg &= (reg["creation_time"] > 0.0)
                if gg.sum() == 0: return
            if self.dm_only:
                gg &= (reg["creation_time"] <= 0.0)
                if gg.sum() == 0: return
            if self.minimum_mass is not None:
                gg &= (reg["ParticleMassMsun"] >= self.minimum_mass)
                if gg.sum() == 0: return
        #plot._axes.hold(True)
        px, py = self.convert_to_plot(plot,
                    [np.array(shifted_field_x[gg][::self.stride]),
                     np.array(shifted_field_y[gg][::self.stride])])
        plot._axes.scatter(px, py, edgecolors='None', marker=self.marker,
                           s=self.p_size, c=self.color)
        plot._axes.set_xlim(xx0,xx1)
        plot._axes.set_ylim(yy0,yy1)