def _get_dP(self, i):
        key = (i, self.theta % 360)
        if key in self._cache:
            return self._cache[key]

        if self.TS is not None:
            self.F = self.TS[i]

        th = np.pi / 180 * self.theta
        N = [np.sin(th), 0, np.cos(th)]
        print('projecting')
        Bx = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    self.px,
                                    'magnetic_field_x',
                                    north_vector=[0, 1, 0],
                                    num_threads=4)
        By = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    self.px,
                                    'magnetic_field_y',
                                    north_vector=[0, 1, 0],
                                    num_threads=4)
        Bz = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    self.px,
                                    'magnetic_field_z',
                                    north_vector=[0, 1, 0],
                                    num_threads=4)
        print('done')
        # S = [ cos(th), 0, -sin(th)]
        # T = [ 0, 1, 0 ]
        # U = N

        Bs = cm * ((Bx * np.cos(th) - Bz * np.sin(th)) / cm
                   )  # .to_equivalent('gauss', 'CGS')
        Bt = cm * (By / cm)  # .to_equivalent('gauss', 'CGS')

        if self.smoothing > 0:
            Bs = gaussian_filter(Bs /
                                 (gauss * cm), self.smoothing) * gauss * cm
            Bt = gaussian_filter(Bt /
                                 (gauss * cm), self.smoothing) * gauss * cm

        # The momenta here will be converted to PIC units (P / (m_e c))
        dPs = -((q * Bt) / (m * c**2)).to('1').v
        dPt = +((q * Bs) / (m * c**2)).to('1').v

        dPs *= self.strength_scale
        dPt *= self.strength_scale

        self._cache[key] = (dPs, dPt)

        return dPs, dPt
    def proton_dP(self, theta, resolution_um, energy_MeV):
        th = np.pi / 180 * theta
        N = [np.sin(th), 0, np.cos(th)]

        resolution = Q(resolution_um, 'um')
        px_s = int(self.Ws / resolution) + 1
        px_t = int(self.Wt / resolution) + 1
        px = [px_s, px_t]

        Bx = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    px,
                                    'magnetic_field_x',
                                    north_vector=[0, 1, 0])
        By = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    px,
                                    'magnetic_field_y',
                                    north_vector=[0, 1, 0])
        Bz = yt.off_axis_projection(self.F,
                                    self.C,
                                    N,
                                    self.W,
                                    px,
                                    'magnetic_field_z',
                                    north_vector=[0, 1, 0])

        # S = [ cos(th), 0, -sin(th)]
        # T = [ 0, 1, 0 ]
        # U = N

        Bs = cm * ((Bx * np.cos(th) - Bz * np.sin(th)) / cm).to_equivalent(
            'gauss', 'CGS')
        Bt = cm * (By / cm).to_equivalent('gauss', 'CGS')

        s0 = np.linspace(-self.Ws, self.Ws, px_s) / 2
        t0 = np.linspace(-self.Wt, self.Wt, px_t) / 2

        [S0, T0] = np.meshgrid(s0, t0, indexing='ij')

        # The momenta here will be converted to PIC units (P / (m_e c))
        # F ~= N x B = [
        dPs = -(q * Bt) / (m * c**2)
        dPt = +(q * Bs) / (m * c**2)

        E_normalised = Q(energy_MeV, 'MeV') / (m * c**2)
        P0 = np.sqrt((E_normalised + M / m)**2 - (M / m)**2)

        return S0, T0, dPs, dPt, P0
 def project_density(self, data_object=None):
     """ 
     Project density on a plane 
     Input:
         data_object: a yt data object. Optional. Defalt is all_data
     """
     if data_object is None:
         ad = self.ds
     else:
         ad = data_object
     if ((self.derive_field()) and (self.window_created)):
         c = self.window_center
         L = self.los
         W = self.window_width
         N = self.window_resolution
         if isinstance(self.window_north_vector, str):
             if self.window_north_vector == "pos_north":
                 north_vector = self.pos_north
             elif self.window_north_vector == "pos_east":
                 north_vector = self.pos_east
         else:
             north_vector = self.window_north_vector
         self.proj_density = yt.off_axis_projection(ad,c, L, W, N, "density",
                                           north_vector=north_vector,
                                           no_ghost=False,
                                           num_threads = 2)
     else:
         sys.exit("Error: Projection window is not defined")
     return True
 def project_LOS_b(self, data_object=None):
     """
     Integral LOS magnetic field along LOS
     Input:
         data_object: a yt data object. Optional. Defalt is all_data
     """
     if data_object is None:
         ad = self.ds
     else:
         ad = data_object
     if ((self.add_LOS_bfield()) and (self.window_created)):
         c = self.window_center
         L = self.los
         W = self.window_width
         N = self.window_resolution
         if isinstance(self.window_north_vector, str):
             if self.window_north_vector == "pos_north":
                 north_vector = self.pos_north
             elif self.window_north_vector == "pos_east":
                 north_vector = self.pos_east
         else:
             north_vector = self.window_north_vector
         self.integral_LOS_b = yt.off_axis_projection(ad,c, L, W, N,
                                           "magnetic_field_LOS",
                                           #weight="density",
                                           north_vector=north_vector,
                                           no_ghost=False,
                                           num_threads = 2)
     else:
         sys.exit("Error: Projection window is not defined")
     return True
 def project_stokes(self, data_object=None):
     """
     Project stokes parameter on a plane 
     Input:
         data_object: a yt data object. Optional. Defalt is all_data
     """
     if data_object is None:
         ad = self.ds
     else:
         ad = data_object
     if ((self.derive_field()) and (self.window_created)):
         c = self.window_center
         L = self.los
         W = self.window_width
         N = self.window_resolution
         if isinstance(self.window_north_vector, str):
             if self.window_north_vector == "pos_north":
                 north_vector = self.pos_north
             elif self.window_north_vector == "pos_east":
                 north_vector = self.pos_east
         else:
             north_vector = self.window_north_vector
         self.proj_Q = yt.off_axis_projection(ad,c, L, W, N, "stokes_Q",
                                           weight="density",
                                           north_vector=north_vector,
                                           no_ghost=False,
                                           num_threads = 2)
         self.proj_U = yt.off_axis_projection(ad,c, L, W, N, "stokes_U",
                                           weight="density",
                                           north_vector=north_vector,
                                           no_ghost=False,
                                           num_threads = 2)
         self.DOP=np.sqrt(self.proj_Q**2+self.proj_U**2)
         self.offset=.5*np.arctan2(self.proj_U,self.proj_Q)
     else:
         sys.exit("Error: Projection window is not defined")
     return True
Esempio n. 6
0
def thinnest_edge(ds, r, cen, wid, res):
    # r is the current radius around which the edge-on galaxy will be searched for
    rs = np.arange(r - 5, r + 6)
    rad = []
    sig = []
    for current_rad in rs:
        # Defines data sphere at current radius
        sp = ds.sphere(cen, (current_rad, 'kpc'))

        # Calculates angular momentum vector and orthogonal vector at the current radius
        L = sp.quantities.angular_momentum_vector()
        L /= np.linalg.norm(L)

        Lx = np.cross(L, [1., 0., 0.])
        Lx /= np.linalg.norm(Lx)

        image = yt.off_axis_projection(ds,
                                       cen,
                                       Lx,
                                       wid * kpc,
                                       res,
                                       'density',
                                       north_vector=L)

        pix = [range(res)[i] * wid / res - wid / 2 for i in range(res)]

        # Take average density of each row of pixels
        avg_rho = [np.mean(image[:, i]) for i in range(len(pix))]

        # Fits a gaussian to the average density versus column number
        fit, er = opt.curve_fit(gaus, pix, avg_rho)

        # adds the current radius and sigma value to a list for comparison
        sig.append(fit[2])
        rad.append(current_rad)
    return rad[sig.index(min(sig))]
Esempio n. 7
0
    if i > N/2.:
        cn = 1.*(i - N/2.)
        x_w = max(W_kpc_initial - cn, W_kpc_final)
        y_w = max(W_kpc_initial - cn, W_kpc_final)
        z_w = max(W_kpc_initial - cn, W_kpc_final)
    else:
        x_w = W_kpc_initial
        y_w = W_kpc_initial
        z_w = W_kpc_initial

    W = YTArray([x_w, y_w, z_w], 'kpc')

    print W, L

    N = 512
    image1 = yt.off_axis_projection(ds_1, cen_1, L, W, N, ('gas', 'density'), north_vector =  north_vector)
    
    image2 = yt.off_axis_projection(ds_2, cen_2, L, W, N, ('gas', 'density'), north_vector =  north_vector)
    

    fig, axes = subplots(1,2, figsize = (10.8, 5))


    image1 = image1.in_units('Msun * kpc**-2')
    image2 = image2.in_units('Msun * kpc**-2')

    im1 = axes[0].imshow(np.log10(image1), vmin = 4.5, vmax = 9.5)
    im2 = axes[1].imshow(np.log10(image2), vmin = 4.5, vmax = 9.5)
    
    bar_len_kpc = 10.
    bar_len_pix = 1.*N/x_w * bar_len_kpc
def generate_ray_image_data(field_list,
                            weight_list,
                            model='P0',
                            output=3195,
                            ray_data_file='',
                            data_loc='.',
                            ion_list='all',
                            redshift=None):

    # load data set with yt, galaxy center, and the bulk velocity of the halo
    ds, gcenter, bulk_velocity = ds, gcenter, bv = spg.load_simulation_properties(
        model)
    # for annoying reasons... need to convert ray positions to "code units"
    code_unit_conversion = ds.domain_right_edge.d / ds.domain_right_edge.in_units(
        'kpc').d
    print(ray_data_file)
    ray_id_list, impact, bvx, bvy, bvz, xi, yi, zi, xf, yf, zf, cx, cy, cz =\
        np.loadtxt(ray_data_file, skiprows = 1, unpack = True)

    bulk_velocity = YTArray([bvx[0], bvy[0], bvz[0]], 'km/s')
    # set field parameters so that trident knows to subtract off bulk velocity
    ad = ds.all_data()
    ad.set_field_parameter('bulk_velocity', bulk_velocity)
    ad.set_field_parameter('center', gcenter)

    width = ds.arr([300., 20., 10], 'kpc')
    for i in [5]:
        # generate the coordinates of the random sightline
        # write ray id, impact parameter, bulk velocity, and start/end coordinates out to file
        h5file = h5.File(
            '%s/ray_image_data_%s_%i_%i.h5' %
            (data_loc, model, output, ray_id_list[i]), 'w')

        ray_start = ds.arr([xi[i], yi[i], zi[i]], 'kpc')
        ray_end = ds.arr([xf[i], yf[i], zf[i]], 'kpc')
        ray_direction = ray_end - ray_start
        ray_center = ray_start + 0.5 * ray_direction
        normal_vector = ds.arr(gcenter, 'kpc') - ray_center
        normal_vector = np.cross(normal_vector, ray_direction)

        for field, weight in zip(field_list, weight_list):
            print(field)
            sys.stdout.flush()
            if weight is not None:
                weight = ('gas', weight)
            if field not in h5file.keys():
                #left_edge =
                #box = ds.region(ray_center, )
                image = yt.off_axis_projection(ds,
                                               center=ray_center,
                                               normal_vector=normal_vector,
                                               width=width,
                                               resolution=[1200, 80],
                                               item=('gas', field),
                                               weight=weight)

                h5file.create_dataset(field, data=image)
                h5file.flush()

        h5file.close()
        print("saved sightline data %i\n" % (i))
def snapshot_to_tfrec(snapshot_file, save_dir, num_of_projections,
                      number_of_virtual_nodes, number_of_neighbours, plotting):
    """
    load snapshot plt file, rotate for different viewing angles, make projections and corresponding graph nets. Save to
    tfrec files.

    Args:
        snapshot: snaphot
        save_dir: location of tfrecs

    Returns:

    """
    print('loading particle and plt file {}...'.format(snapshot_file))
    t_0 = default_timer()
    # filename = 'turbsph_hdf5_plt_cnt_{:04d}'.format(snapshot)  # only plt file, will automatically find part file
    #
    # file_path = folder_path + filename
    # print(f'file: {file_path}')
    ds = yt.load(
        snapshot_file
    )  # loads in data into data set class. This is what we will use to plot field values
    ad = ds.all_data(
    )  # Can call on the data set's property .all_data() to generate a dictionary
    # containing all data available to be parsed through.
    # e.g. print ad['mass'] will print the list of all cell masses.
    # if particles exist, print ad['particle_position'] gives a list of each particle [x,y,z]
    print('done, time: {}'.format(default_timer() - t_0))

    snapshot = int(snapshot_file[-4:])
    field = 'density'
    width = np.max(ad['x'].to_value()) - np.min(ad['x'].to_value())
    resolution = 256

    print('making property_values...')
    t_0 = default_timer()

    property_values = []
    # property_transforms = [lambda x: x, lambda x: x, lambda x: x, lambda x: x, lambda x: x, lambda x: x, lambda x: x,
    #                        np.log10, np.log10, np.log10, np.log10]

    property_names = [
        'x', 'y', 'z', 'velocity_x', 'velocity_y', 'velocity_z',
        'gravitational_potential', 'density', 'temperature', 'cell_mass',
        'cell_volume'
    ]

    unit_names = [
        'pc', 'pc', 'pc', '10*km/s', '10*km/s', '10*km/s', 'J/mg',
        'Msun/pc**3', 'K', 'Msun', 'pc**3'
    ]

    _values = []
    for name, unit in zip(property_names, unit_names):
        if name == 'gravitational_potential':
            _values.append(-ad[name].in_units(unit).to_value())
        else:
            _values.append(ad[name].in_units(unit).to_value())

    # property_values = np.array(property_values)  # n f
    property_values = np.array(_values).T  # n f
    print('done, time: {}'.format(default_timer() - t_0))

    print('making projections and rotating coordinates')
    t_0 = default_timer()

    positions = []
    properties = []
    proj_images = []
    extra_info = []

    projections = 0
    while projections < num_of_projections:
        print(projections)

        V = np.eye(3)
        R = _random_special_ortho_matrix(3)
        Vprime = np.linalg.inv(R) @ V

        north_vector = Vprime[:, 1]
        viewing_vec = Vprime[:, 2]

        _extra_info = [
            snapshot, projections, viewing_vec[0], viewing_vec[1],
            viewing_vec[2], north_vector[0], north_vector[1], north_vector[2],
            resolution, width
        ]  #, field]
        proj_image = yt.off_axis_projection(ds,
                                            center=[0, 0, 0],
                                            normal_vector=viewing_vec,
                                            north_vector=north_vector,
                                            item=field,
                                            width=width,
                                            resolution=resolution)

        proj_image = np.log10(np.where(proj_image < 1e-5, 1e-5, proj_image))

        xyz = property_values[:, :3]  # n 3
        velocity_xyz = property_values[:, 3:6]  # n 3

        rotated_xyz = (R @ xyz.T).T
        rotated_velocity_xyz = (R @ velocity_xyz.T).T

        _properties = property_values.copy()  # n f
        _properties[:, :3] = rotated_xyz  # n f
        _properties[:, 3:6] = rotated_velocity_xyz  # n f
        _properties[:, 6] = _properties[:, 6]  # n f
        _positions = xyz  # n 3

        positions.append(_positions)
        properties.append(_properties)
        proj_images.append(proj_image)
        extra_info.append(_extra_info)

        projections += 1

    generate_data(positions=positions,
                  properties=properties,
                  proj_images=proj_images,
                  extra_info=extra_info,
                  save_dir=save_dir,
                  number_of_virtual_nodes=number_of_virtual_nodes,
                  plotting=plotting,
                  number_of_neighbours=number_of_neighbours)

    print('done, time: {}'.format(default_timer() - t_0))
Esempio n. 10
0
hc = HaloCatalog(data_ds=ds, halos_ds=halos_ds)
hc.load()
halos = hc.halo_list

fieldname = 'gas'
fieldvalue = fields[fieldname]
index = 0
halo = halos[index]

# PROJECTION PLOT
com = [halo.quantities['particle_position_x'], halo.quantities['particle_position_y'], halo.quantities['particle_position_z']]
sp = ds.sphere(com, (30, 'kpc'))
amv = sp.quantities.angular_momentum_vector()
amv = amv / np.sqrt((amv**2).sum())
center = sp.quantities.center_of_mass()
res = 1024
width = [0.01, 0.01, 0.01]
image = yt.off_axis_projection(ds, center, amv, width, res, fieldvalue)
yt.write_image(np.log10(image), '%s_%d_%s_offaxis_projection.png' % (ds, index, fieldname))

# PROFILE PLOT
com = [halo.quantities['particle_position_x'], halo.quantities['particle_position_y'], halo.quantities['particle_position_z']]
sp = ds.sphere(com, (30, 'kpc'))
profiles = yt.create_profile(sp, 'radius', fields.values())
for fieldname, field in fields.iteritems():
    plt.loglog(profiles.x, profiles[field], label=fieldname)
plt.xlim([profiles.x.min(), profiles.x.max()])
plt.xlabel('Radius $[kpc]$')
plt.ylabel('$\\rho [M_{\odot} kpc^{-3}]$')
plt.legend(loc='best')
plt.savefig('%s_%d_profile.png' % (ds, index))
Esempio n. 11
0
frame = 1
stepAlpha=np.pi/100
stepBeta=np.pi/100
frames=math.ceil(2*np.pi/stepAlpha)

for i in np.arange(0, frames):
    L = yksikkovektori(alpha, beta)
    N = yksikkovektori(alpha+stepAlpha, beta+stepBeta)
    # Now we call the off_axis_projection function, which handles the rest.
    # Note that we set no_ghost equal to False, so that we *do* include ghost
    # zones in our data.  This takes longer to calculate, but the results look
    # much cleaner than when you ignore the ghost zones.
    # Also note that we set the field which we want to project as "density", but
    # really we could use any arbitrary field like "temperature", "metallicity"
    # or whatever.
    image = yt.off_axis_projection(ds, tiheysmaksimi, L, W, Npixels, "density", north_vector=N, no_ghost=False, steady_north=True)

    

    # Image is now an NxN array representing the intensities of the various pixels.
    # And now, we call our direct image saver.  We save the log of the result.
    #yt.write_projection(image, "slice/kaanto/offaxis_projection_colorbar%04i.png" %frame, colorbar_label="Column Density (cm$^{-2}$)")
    yt.write_projection(image, "kuvat/%04i.png" %frame, cmap_name='hot')
    
    frame+=1
    alpha+=stepAlpha
    beta+=stepBeta
    
    
    
Esempio n. 12
0
def generate_ray_image_data(field_list,
                            weight_list,
                            model='P0',
                            output=3195,
                            ray_data_file='../../data/P0_z0.25_ray_data.dat',
                            data_loc='.',
                            ion_list='all',
                            redshift=None):

    # load data set with yt, galaxy center, and the bulk velocity of the halo
    if model == 'P0':
        ds = yt.load('~/Work/galaxy/P0/P0.003195')
        ds.add_field(('gas', 'mass'),
                     function=_mass2,
                     units='g',
                     sampling_type='particle')

    trident.add_ion_fields(ds, ions=ion_list)
    # for annoying reasons... need to convert ray positions to "code units"
    code_unit_conversion = ds.domain_right_edge.d / ds.domain_right_edge.in_units(
        'kpc').d

    ray_id_list, impact, bvx, bvy, bvz, xi, yi, zi, xf, yf, zf, cx, cy, cz =\
        np.loadtxt(ray_data_file, skiprows = 1, unpack = True)

    gcenter_kpc = [cx[0], cy[0], cz[0]
                   ]  # assuming galaxy center is the same for all sightlines
    gcenter = gcenter_kpc * code_unit_conversion
    bulk_velocity = YTArray([bvx[0], bvy[0], bvz[0]], 'km/s')
    # set field parameters so that trident knows to subtract off bulk velocity
    ad = ds.all_data()
    ad.set_field_parameter('bulk_velocity', bulk_velocity)
    ad.set_field_parameter('center', gcenter)

    width = np.array([300., 20., 20.])  # kpc
    width *= code_unit_conversion

    ray_start_list = np.ndarray(shape=(0, 3))
    ray_end_list = np.ndarray(shape=(0, 3))
    for i in range(len(xi)):
        ray_start_list = np.vstack(
            (ray_start_list, [xi[i], yi[i], zi[i]] * code_unit_conversion))
        ray_end_list = np.vstack(
            (ray_end_list, [xf[i], yf[i], zf[i]] * code_unit_conversion))

    for i in [0, 10]:
        # generate the coordinates of the random sightline
        # write ray id, impact parameter, bulk velocity, and start/end coordinates out to file
        h5file = h5.File(
            '%s/ray_image_data_%s_%i_%i.h5' %
            (data_loc, model, output, ray_id_list[i]), 'a')

        ray_center = ray_start_list[i] + 0.5 * (ray_end_list[i] -
                                                ray_start_list[i])
        ray_direction = ray_end_list[i] - ray_start_list[i]
        print(ray_center, ray_direction, width)
        #        ray_center = [-0.42299158, -0.30013312,  0.13297239]
        #        ray_direction =  [0.6779612,  -0.68934122, -0.25529845]
        #        image = yt.off_axis_projection(ds, ray_center, ray_direction, width,
        #                                   [1200, 80], ('gas', 'temperature'), weight = ('gas', 'density'))
        for field, weight in zip(field_list, weight_list):
            print(field)
            sys.stdout.flush()
            if weight is not None:
                weight = ('gas', weight)
            if field not in h5file.keys():
                image = yt.off_axis_projection(ds,
                                               ray_center,
                                               ray_direction,
                                               width, [1200, 80],
                                               ('gas', field),
                                               weight=weight)

                h5file.create_dataset(field, data=image)
                h5file.flush()

        h5file.close()
        print("saved sightline data %i\n" % (i))
Esempio n. 13
0
            ceny = cen_fits['SAT_%.2i' % sat_n].data['box_avg'][1]
            cenz = cen_fits['SAT_%.2i' % sat_n].data['box_avg'][2]
            cen = yt.YTArray([cenx, ceny, cenz], 'kpc')

            #vel_vec = array([anchor_vxs_box_avg, anchor_vys_box_avg, anchor_vzs_box_avg])
            #L = vel_vec/np.linalg.norm(vel_vec)

            #L = [1*math.cos(pi*(DD)/100.),0, 1*math.sin(pi*(DD)/100.)] # vector normal to cutting plane

            fig, axes = plt.subplots(3, 2, figsize=(10.8, 15))

            for i in arange(3):
                L = Ls[i]
                image1 = yt.off_axis_projection(ds,
                                                cen,
                                                L,
                                                W1,
                                                N, ('gas', 'density'),
                                                north_vector=north_vector)
                image2 = yt.off_axis_projection(ds,
                                                cen,
                                                L,
                                                W2,
                                                N, ('gas', 'density'),
                                                north_vector=north_vector)

                image1 = image1.in_units('Msun * kpc**-2')
                image2 = image2.in_units('Msun * kpc**-2')

                im1 = axes[i, 0].imshow(np.log10(image1), vmin=4.5, vmax=9.5)
                im2 = axes[i, 1].imshow(np.log10(image2), vmin=4.5, vmax=9.5)
# dataset, we'll just choose an off-axis value at random.  This gets normalized
# automatically.
L = [0.5, 0.4, 0.7]

# Our "width" is the width of the image plane as well as the depth.
# The first element is the left to right width, the second is the
# top-bottom width, and the last element is the back-to-front width
# (all in code units)
W = [0.04, 0.04, 0.4]

# The number of pixels along one side of the image.
# The final image will have Npixel^2 pixels.
Npixels = 512

# Now we call the off_axis_projection function, which handles the rest.
# Note that we set no_ghost equal to False, so that we *do* include ghost
# zones in our data.  This takes longer to calculate, but the results look
# much cleaner than when you ignore the ghost zones.
# Also note that we set the field which we want to project as "density", but
# really we could use any arbitrary field like "temperature", "metallicity"
# or whatever.
image = yt.off_axis_projection(ds, c, L, W, Npixels, "density", no_ghost=False)

# Image is now an NxN array representing the intensities of the various pixels.
# And now, we call our direct image saver.  We save the log of the result.
yt.write_projection(
    image,
    "offaxis_projection_colorbar.png",
    colorbar_label="Column Density (cm$^{-2}$)",
)
Esempio n. 15
0
frames = math.ceil(2 * np.pi / stepAlpha)

for i in np.arange(0, frames):
    L = yksikkovektori(alpha, beta)
    N = yksikkovektori(alpha + stepAlpha, beta + stepBeta)
    # Now we call the off_axis_projection function, which handles the rest.
    # Note that we set no_ghost equal to False, so that we *do* include ghost
    # zones in our data.  This takes longer to calculate, but the results look
    # much cleaner than when you ignore the ghost zones.
    # Also note that we set the field which we want to project as "density", but
    # really we could use any arbitrary field like "temperature", "metallicity"
    # or whatever.
    image = yt.off_axis_projection(ds,
                                   tiheysmaksimi,
                                   L,
                                   W,
                                   Npixels,
                                   "density",
                                   north_vector=N,
                                   no_ghost=False,
                                   steady_north=True)

    # Image is now an NxN array representing the intensities of the various pixels.
    # And now, we call our direct image saver.  We save the log of the result.
    #yt.write_projection(image, "slice/kaanto/offaxis_projection_colorbar%04i.png" %frame, colorbar_label="Column Density (cm$^{-2}$)")
    yt.write_projection(image, "kuvat/%04i.png" % frame, cmap_name='hot')

    frame += 1
    alpha += stepAlpha
    beta += stepBeta
Esempio n. 16
0
index = 0
halo = halos[index]

# PROJECTION PLOT
com = [
    halo.quantities['particle_position_x'],
    halo.quantities['particle_position_y'],
    halo.quantities['particle_position_z']
]
sp = ds.sphere(com, (30, 'kpc'))
amv = sp.quantities.angular_momentum_vector()
amv = amv / np.sqrt((amv**2).sum())
center = sp.quantities.center_of_mass()
res = 1024
width = [0.01, 0.01, 0.01]
image = yt.off_axis_projection(ds, center, amv, width, res, fieldvalue)
yt.write_image(np.log10(image),
               '%s_%d_%s_offaxis_projection.png' % (ds, index, fieldname))

# PROFILE PLOT
com = [
    halo.quantities['particle_position_x'],
    halo.quantities['particle_position_y'],
    halo.quantities['particle_position_z']
]
sp = ds.sphere(com, (30, 'kpc'))
profiles = yt.create_profile(sp, 'radius', fields.values())
for fieldname, field in fields.iteritems():
    plt.loglog(profiles.x, profiles[field], label=fieldname)
plt.xlim([profiles.x.min(), profiles.x.max()])
plt.xlabel('Radius $[kpc]$')
def graph_img_plotting(plotting, virtual_properties, senders, receivers,
                       xray_image, positions, hot_gas_positions, base_data_dir,
                       center, vprime, dataset, sphere):
    max_pos = np.max(positions.T, axis=1)
    min_pos = np.min(positions.T, axis=1)
    box_size = max_pos - min_pos

    if plotting == 1:
        print('Plotting xray...')
        fig, ax = plt.subplots(1, 3, figsize=(18, 6))
        ax[0].scatter(center[0] + hot_gas_positions[:, 0],
                      center[1] + hot_gas_positions[:, 1],
                      s=10**(2.5 - np.log10(positions.shape[0])))
        ax[0].set_xlim(center[0] - 0.5 * box_size[0],
                       center[0] + 0.5 * box_size[0])
        ax[0].set_ylim(center[1] - 0.5 * box_size[1],
                       center[1] + 0.5 * box_size[1])
        ax[0].set_title('Hot gas particles')
        ax[1].imshow(xray_image)
        # fig.colorbar(xray_plot, ax=ax[1])
        ax[1].set_title('Xray')
        ax[2].scatter(center[0] + positions.T[0],
                      center[1] + positions.T[1],
                      s=10**(2.5 - np.log10(positions.shape[0])))
        ax[2].set_xlim(center[0] - 0.5 * box_size[0],
                       center[0] + 0.5 * box_size[0])
        ax[2].set_ylim(center[1] - 0.5 * box_size[1],
                       center[1] + 0.5 * box_size[1])
        ax[2].set_title('Gas particles')
        plt.savefig(os.path.join(base_data_dir, 'images/xray.png'))
        plt.show()

    if plotting > 1:
        graph = nx.OrderedMultiDiGraph()

        n_nodes = virtual_properties.shape[
            0]  # number of nodes is the number of positions

        virtual_box_size = (np.min(virtual_properties[:, :3]),
                            np.max(virtual_properties[:, :3]))

        pos = dict()  # for plotting node positions.
        edgelist = []

        # Now put the data in the directed graph: first the nodes with their positions and properties
        # pos just takes the x and y coordinates of the position so a 2D plot can be made
        for node, feature, position in zip(np.arange(n_nodes),
                                           virtual_properties,
                                           virtual_properties[:, :3]):
            graph.add_node(node, features=feature)
            pos[node] = (position[:2] - virtual_box_size[0]) / (
                virtual_box_size[1] - virtual_box_size[0])

        # Next add the edges using the receivers and senders arrays we just created
        # Note that an edge is added for both directions
        # The features of the edge are dummy arrays at the moment
        # The edgelist is for the plotting
        # edges = np.stack([senders, receivers], axis=-1) + sibling_node_offset
        for u, v in zip(senders, receivers):
            graph.add_edge(u, v, features=np.array([1., 0.]))
            edgelist.append((u, v))

        print(f'Particle graph nodes : {graph.number_of_nodes()}')
        print(f'Particle graph edges : {graph.number_of_edges()}')

        dens_list = []

        for n in list(graph.nodes.data('features')):
            dens_list.append(n[1][6])

        if plotting == 2:
            # Plotting
            fig, ax = plt.subplots(2, 2, figsize=(12, 12))
            print('Plotting multiplot...')
            draw(graph,
                 ax=ax[0, 0],
                 pos=pos,
                 edge_color='red',
                 node_size=10**(4 - np.log10(len(dens_list))),
                 width=0.1,
                 arrowstyle='-',
                 node_color=dens_list,
                 cmap='viridis')
            # draw(graph, ax=ax[0, 0], pos=pos, node_color='blue', edge_color='red', node_size=10, width=0.1)
            ax[0, 1].scatter(center[0] + hot_gas_positions[:, 0],
                             center[1] + hot_gas_positions[:, 1],
                             s=10**(2.5 - np.log10(positions.shape[0])))
            ax[0, 1].set_xlim(center[0] - 0.5 * box_size[0],
                              center[0] + 0.5 * box_size[0])
            ax[0, 1].set_ylim(center[1] - 0.5 * box_size[1],
                              center[1] + 0.5 * box_size[1])
            ax[0, 1].set_title('Hot gas particles')
            ax[1, 0].imshow(xray_image)
            # fig.colorbar(xray_plot, ax=ax[1])
            # ax[1].set_title('Xray')
            ax[1, 1].scatter(center[0] + positions.T[0],
                             center[1] + positions.T[1],
                             s=10**(2.5 - np.log10(positions.shape[0])))
            ax[1, 1].set_xlim(center[0] - 0.5 * box_size[0],
                              center[0] + 0.5 * box_size[0])
            ax[1, 1].set_ylim(center[1] - 0.5 * box_size[1],
                              center[1] + 0.5 * box_size[1])
            ax[1, 1].set_title('Gas particles')
            print('Multiplot done, showing...')
            plt.savefig(os.path.join(base_data_dir, 'images/multiplot.png'))
            plt.show()

        if plotting == 3:
            interp_virtual_positions = virtual_properties[:, :3] / 1e4
            fig, ax = plt.subplots(figsize=(8, 8))
            _x = np.linspace(np.min(interp_virtual_positions[:, 0]),
                             np.max(interp_virtual_positions[:, 0]), 300)
            _y = np.linspace(np.min(interp_virtual_positions[:, 1]),
                             np.max(interp_virtual_positions[:, 1]), 300)
            _z = np.linspace(np.min(interp_virtual_positions[:, 2]),
                             np.max(interp_virtual_positions[:, 2]), 300)
            x, y, z = np.meshgrid(_x, _y, _z, indexing='ij')

            interp = interpolate.griddata(
                (interp_virtual_positions[:, 0],
                 interp_virtual_positions[:, 1], interp_virtual_positions[:,
                                                                          2]),
                dens_list,
                xi=(x, y, z),
                fill_value=0.0)

            im = np.mean(interp, axis=2).T[::-1, ]
            im = np.log10(
                np.where(im / np.max(im) < 1e-3, 1e-3, im / np.max(im)))
            ax.imshow(im)
            plt.savefig(os.path.join(base_data_dir, 'images/interp.png'))
            plt.show()

        if plotting == 4:
            print('Plotting off-axis projection...')
            east_vector = vprime[:, 0]
            north_vector = vprime[:, 1]
            viewing_vec = vprime[:, 2]
            fig, ax = plt.subplots(figsize=(8, 8))
            off_axis_image = yt.off_axis_projection(data_source=dataset,
                                                    center=sphere.center,
                                                    normal_vector=viewing_vec,
                                                    width=0.01 *
                                                    dataset.domain_width,
                                                    item='Density',
                                                    resolution=[400, 400],
                                                    north_vector=east_vector)
            off_axis_image = np.log10(
                np.where(off_axis_image < 1e17, 1e17, off_axis_image))
            # off_axis_image = off_axis_image.to_ndarray() / np.max(off_axis_image.to_ndarray())
            # off_axis_image = np.log10(np.where(off_axis_image < 1e-5, 1e-5, off_axis_image))
            # print(f'Maximum : {np.max(off_axis_image)}')
            off_axis_image = ax.imshow(off_axis_image)
            fig.colorbar(off_axis_image, ax=ax)
            plt.savefig(os.path.join(base_data_dir,
                                     'images/off_axis_proj.png'))
            plt.show()
            # yt.write_image(np.log10(off_axis_image), os.path.join(base_data_dir, 'images/off_axis_proj.png'))

        if plotting == 5:
            print('Plotting 3D image...')
            mlab.points3d(virtual_properties.T[0],
                          virtual_properties.T[1],
                          virtual_properties.T[2],
                          dens_list,
                          resolution=8,
                          scale_factor=0.15,
                          scale_mode='none',
                          colormap='viridis')
            for u, v in zip(senders, receivers):
                mlab.plot3d(
                    [virtual_properties[u][0], virtual_properties[v][0]],
                    [virtual_properties[u][1], virtual_properties[v][1]],
                    [virtual_properties[u][2], virtual_properties[v][2]],
                    tube_radius=None,
                    tube_sides=3,
                    opacity=0.1)
            mlab.show()
Esempio n. 18
0
"""
Make simple off-axis plot using data
      
"""
from GL import *
from cycler import cycler
import queb3
from queb3 import powerlaw_fit as plfit
import davetools as dt
import h5py
from matplotlib.pyplot import cm
import yt

reload(queb3)

simdir = "half_half"
frame = 30
plotdir = "/Users/Kye/512reruns/512rerunplots/offaxisplots"

ds = yt.load("/Users/Kye/512reruns/frbs/half_half/DD%04d/data%04d" %
             (frame, frame))
L = [1, 1, 0]  # vector normal to cutting plane
north_vector = [-1, 1, 0]
W = [0.02, 0.02, 0.02]
c = [0.5, 0.5, 0.5]
N = 512
image = yt.off_axis_projection(ds, c, L, W, N, "density")
yt.write_image(
    np.log10(image),
    "%s/%s/%04d_offaxis_density_projection.png" % (plotdir, simdir, frame))
Esempio n. 19
0
    width_kpc = radius * 2
    le = center - radius
    re = center + radius
    box = ds.box(le, re)

    # temperature cut mask (same used for mock images 1e5 K)
    min_temperature = 1e5
    box = box.cut_region('obj["temperature"] > %f' % min_temperature)

    for field in fields:
        print field
        # density weighted projection same normal vector as mock images
        proj = yt.off_axis_projection(box,
                                      center=center,
                                      normal_vector=[1, 1, 1],
                                      width=width_kpc,
                                      resolution=nside,
                                      item=field,
                                      weight='number_density')
        proj = proj.v.T  # transpose to get same orientation as mock image
        residual = RadialProfile.residual_field(proj)
        group.create_dataset('residual_%s' % field, data=residual)

        # Make mask for large density fluctuations associated with small cold clumps
        if field == 'number_density':
            max_fluc = 5.
            mask = residual < max_fluc
            mask_group.attrs[
                'large_density_fluctuation_volume_fraction'] = mask[
                    mask == 0].size / float(mask.size)
            mask_group.attrs['max_dens_fluc'] = max_fluc
Esempio n. 20
0
    xs_box, ys_box, zs_box, vxs_box, vys_box, vzs_box, xs, ys, zs, vxs, vys, vzs = \
        np.load('/Users/rsimons/Dropbox/rcs_foggie/outputs/nref11n_orig_%s_sat%i.npy'%(sname, sat_n))[()]

    cen = yt.YTArray([xs_box, ys_box, zs_box], 'kpc')
    L = yt.YTArray([vxs_box, vys_box, vzs_box], 'km/s')
    L_init = L.copy()
    L_init_mag = sqrt(sum(L_init**2))
    L_mag = sqrt(sum(L**2))
    L_n = L / L_mag

    x = 16
    fig, ax = plt.subplots(8, x, figsize=((12 / 8.) * x, 12))
    print 'gas density off-axis projection'
    sat_dens = yt.off_axis_projection(ds,
                                      cen,
                                      -L_n,
                                      W,
                                      N, ('gas', 'density'),
                                      north_vector=north_vector)
    print 'gas stellar density off-axis projection'
    sat_mstar_dens = yt.off_axis_projection(ds,
                                            cen,
                                            -L_n,
                                            W,
                                            N, ('deposit', 'io_density'),
                                            north_vector=north_vector)

    kern = Gaussian2DKernel(0.5 * (N / 15.))
    sat_mstar_dens_c = yt.YTArray(convolve_fft(sat_mstar_dens, kern),
                                  sat_mstar_dens.units)
    for i in arange(x):
        cenS_i = cen + yt.YTArray([-x + 2 * i], 'kpc') * L_n
# Our image plane will be normal to some vector.  For things like collapsing
# objects, you could set it the way you would a cutting plane -- but for this
# dataset, we'll just choose an off-axis value at random.  This gets normalized
# automatically.
L = [0.5, 0.4, 0.7]

# Our "width" is the width of the image plane as well as the depth.
# The first element is the left to right width, the second is the
# top-bottom width, and the last element is the back-to-front width
# (all in code units)
W = [0.04,0.04,0.4]

# The number of pixels along one side of the image.
# The final image will have Npixel^2 pixels.
Npixels = 512

# Now we call the off_axis_projection function, which handles the rest.
# Note that we set no_ghost equal to False, so that we *do* include ghost
# zones in our data.  This takes longer to calculate, but the results look
# much cleaner than when you ignore the ghost zones.
# Also note that we set the field which we want to project as "density", but
# really we could use any arbitrary field like "temperature", "metallicity"
# or whatever.
image = yt.off_axis_projection(ds, c, L, W, Npixels, "density", no_ghost=False)

# Image is now an NxN array representing the intensities of the various pixels.
# And now, we call our direct image saver.  We save the log of the result.
yt.write_projection(image, "offaxis_projection_colorbar.png", 
                    colorbar_label="Column Density (cm$^{-2}$)")
Esempio n. 22
0
ds.add_field(("gas", "Byz"), function=_Byz, units="G", force_override=True)

#fig=plt.figure()

ad=ds.all_data()
#field = ["Byz"]
#p=yt.ProjectionPlot(ds, "x", field, weight_field="density")
#p.zoom(1)
#p.annotate_contour("Byz")
#p.annotate_magnetic_field()
#get(annotate_timestamp)
#p.run_callbacks()
#p.save()

L=np.array([2,1,1])
oap=yt.off_axis_projection(ds, ds.domain_center, L, ds.domain_width, (800, 800), "density")
#yt.write_oap()

oapp=yt.OffAxisProjectionPlot(ds, L, "Byz", weight_field="density")
oapp.annotate_contour(("gas", "density"), ncont=5, factor=4)
#oapp.annotate_magnetic_field()
#oapp.save('contours+vectors_density')
#oapp.save() #to save and include name use oapp.save("%s_oapp.png" % ds)

prj=ds.proj("Byz", "x", weight_field="density")
print prj
#prj.save_object("Byz","Byz_data")

frb=prj.to_frb((4, "AU"), [10000,10000])
#plt.savefig("frb.png")