gamma package#
Submodules#
gamma.galaxy module#
- class gamma.galaxy.Galaxy(simulation='IllustrisTNG', **kwargs)[source]#
Bases:
objectBase class for all galaxies. This module contains the Galaxy class as the main class of the package. It is used to load a galaxy from a simulation and to render images of the galaxy. One can specify the simulation the galaxy is from and the halo id of the galaxy. The Galaxy class will then load the galaxy data from the simulation based on the Class defined in the simulatoins module and rotate the galaxy to face-on and horizontal orientation. The get_image method can then be used to render images of different fields of the galaxy, and chose if they should be mass weighted or not.
- Parameters:
simulation (str, optional) – The simulation the galaxy is from. Curenntly only “IllustrisTNG” is supported. You can add your own simulation by adding a new class to the simulations.py file.
**kwargs (dict) – Additional arguments for the galaxy class. This is used to initialize the galaxy class of a specific simulation. See the documentation of the galaxy class defined in simulations.py for more information.
- galaxy_object#
The galaxy object of the simulation. This is the class defined in the simulations.py file.
- Type:
object
- plot_factor#
Factor used in the horizontal_rotation method defined in the rotation.py module to scale the image. The default is 10. For more information see the documentation of the horizontal_rotation method.
- Type:
int
- res#
Resolution of the image. The default is 64. For more information see the documentation of the horizontal_rotation method.
- Type:
int
- smoothing_length#
Smoothing length of the galaxy. This is used for the image rendering.
- Type:
numpy.array
- coordinates#
Coordinates of the particles. This is used for the image rendering.
- Type:
numpy.array
- rotated_flag#
Flag to check if the galaxy is already rotated. This is used for the image rendering.
- Type:
bool
Examples
>>> galaxy = Galaxy("IllustrisTNG", halo_id=0, particle_type="stars") # Load a galaxy from the IllustrisTNG simulation. Note that the Class IllustrisTNG needs to be defined in the simulations.py file >>> galaxy.get_image("GFM_StellarFormationTime", mass_weighted=True) # Render an image of the age of the stars in the galaxy >>> galaxy.get_rotation_matrix() # Get the rotation matrix used to rotate the galaxy to face-on and horizontal orientation
- get_coordinates()[source]#
Get the coordinates of the particles of the galaxy.
The coordinates are rotated by the total rotation matrix of the galaxy.
- Returns:
The correctly rotated coordinates of the particles of the galaxy.
- Return type:
numpy.array
- get_image(field, mass_weighted=True, normed=False, res=None, plotfactor=None, dim=2, **kwargs)[source]#
Get the image of a given field.
This function renders the image of a given field, which can be any field that is available in the snapshot and can be accessed by the get_field function of the galaxy object. The images can be mass weighted and normalized.
It uses the _render_image_2D function to render the image. You can change the image rendering by implementing your own image rendering function there.
- Parameters:
field (str) – The field to be rendered. Can be any field that is available in the snapshot. Used to call the get_field function of the galaxy object.
mass_weighted (bool, optional) – If True, the image is mass weighted. The default is True.
normed (bool, optional) – If True, the image is normalized. The default is False.
res (int, optional) – The resolution of the image. The default is None. If None, the resolution is set to the default value of the Galaxy class, which is 64.
plotfactor (int, optional) – The plotfactor used to scale the image. The default is None. If None, the plotfactor is set to the default value of the Galaxy class, which is 10.
dim (int, optional) – The dimension of the image. The default is 2. If 2, the image is rendered as a 2D image. If 3, the image is rendered as a 3D image.
**kwargs (dict) – Additional arguments for the normalization function. This is only used if normed is True. For more information see the documentation of the norm function defined in the image_modules.py file.
- Returns:
The image of the given field.
- Return type:
numpy.array
Examples
>>> galaxy = Galaxy(halo_id=0, particle_type="stars", base_path="data", snapshot=99) >>> image = galaxy.get_image("Masses", mass_weighted=False, normed=True) >>> plt.imshow(image)
- get_rotated_velocities()[source]#
Get the correctly rotated velocities of the particles of the galaxy.
The velocities are rotated by the total rotation matrix of the galaxy.
- Returns:
The correctly rotated velocities of the particles of the galaxy.
- Return type:
numpy.array
- get_rotation_matrix()[source]#
Get the total rotation matrix of the galaxy.
The total rotation matrix is the rotation matrix that combines the rotation face on rotation and horizontal rotation.
- Returns:
The total rotation matrix of the galaxy.
- Return type:
numpy.array
- render_image(field, dim, coordinates=None)[source]#
Render the image of a given field.
This function is called by the get_image function. It renders the image using the _render_image_2D or _render_image_3D function based on the dimension of the image. You can change the image rendering by implementing your own image rendering function in the _render_image_2D or _render_image_3D function.
- Parameters:
field (str) – The field to be rendered. Can be any field that is available in the snapshot. Used to call the get_field function of the galaxy object.
dim (int) – The dimension of the image. Can be either 2 or 3.
coordinates (numpy.array, optional) – The coordinates of the particles. If not given, the coordinates of the galaxy object are used. The default is None.
- Raises:
ValueError – If the dimension is not 2 or 3.
- Returns:
The rendered image.
- Return type:
numpy.array
gamma.generate module#
gamma.image_utils module#
Coordinate Rotation and Image Render Modules for the Galaxy Class
This module contains the coordinate rotation functions and the image render functions for the Galaxy class defined in the galaxy.py file. The image render functions are called by the get_image function of the Galaxy class defined in the galaxy.py file.
- gamma.image_utils.calc_rotation_matrix(angle)[source]#
Calculate the rotation matrix around the z-axis for a given angle.
Calculate the rotation matrix around the z-axis for a given angle. The rotation matrix is used to rotate the galaxy around the z-axis.
- Parameters:
angle (float) – The angle to rotate the galaxy around the z-axis. Needs to be in radians.
- Returns:
The rotation matrix.
- Return type:
numpy.array
- gamma.image_utils.clip_image(data, lower=0.1, upper=1.0)[source]#
Clip image to [lower,upper] quantile.
This function is called by the get_image function of the Galaxy class defined in the galaxy.py file. It clips the image to the [lower,upper] quantile.
- Parameters:
data (numpy.array) – The image to be clipped.
lower (float, optional) – The lower quantile. The default is 0.1.
upper (float, optional) – The upper quantile. The default is 1.
- Returns:
The clipped image.
- Return type:
numpy.array
- gamma.image_utils.face_on_rotation(rHalf, subhalo_pos, coordinates, particle_masses, return_rotation_matrix=False)[source]#
Rotate the galaxy to face-on orientation.
The galaxy is rotated to face-on orientation using the rotation matrix calculated from the moment of inertia tensor.
- Parameters:
rHalf (float) – The half mass radius of the galaxy.
subhalo_pos (numpy.array) – The position of the subhalo.
coordinates (numpy.array) – The coordinates of the particles.
particle_masses (numpy.array) – The masses of the particles.
- Returns:
The rotated coordinates of the particles.
- Return type:
numpy.array
- gamma.image_utils.get_horizontal_angle(img)[source]#
Calculate the angle of the galaxy bar in the image.
Uses the PCA to calculate the angle of the galaxy in the image. The PCA is calculated on the pixels with a value above the 75% quantile in order to only take the brightest pixels into account. The angle is calculated from the first principal component, which represents the direction of maximum variance in the data i.e. the direction of the galaxy bar.
- Parameters:
img (numpy.array) – The image of the galaxy.
- Returns:
The angle of the galaxy in the image in radians.
- Return type:
float
- gamma.image_utils.horizontal_rotation(img, coordinates, halfmassrad, plotfactor=10, return_rotation_matrix=False)[source]#
Rotate the galaxy to be horizontal.
The galaxy is rotated to be horizontal using the angle of the galaxy bar in the image calculated with the PCA.
- Parameters:
img (numpy.array) – The image of the galaxy.
coordinates (numpy.array) – The coordinates of the particles.
halfmassrad (float) – The half mass radius of the galaxy.
plotfactor (float, optional) – The factor to multiply the half mass radius with to get the size of the image. The default is 10.
- Returns:
The rotated coordinates of the particles.
- Return type:
numpy.array
- gamma.image_utils.image2D(coordinates, R_half, weights, smoothing_length, plot_factor=10, res=64)[source]#
Image Render Module for 2D images.
This function renders a 2D image of the given field. The image is rendered using the scatter2D function from the swiftsimio.visualisation.projection module. The image is rendered in the xy-plane. The image is calculated in plot_factor*R_half. The image is res x res pixels.
- Parameters:
coordinates (numpy.array) – The coordinates of the particles. The Galaxy should be centered at the origin and already rotated to the xy-plane
R_half (float) – The half mass radius of the galaxy used to set the plot range.
weights (numpy.array) – The weights of the particles. This is the field that is rendered.
smoothing_length (numpy.array) – The smoothing length of the particles used for the SPH kernel.
plot_factor (float) – The factor by which the image is zoomed in. The image is calculated for -plot_factor*R_half < x < plot_factor*R_half
res (int) – The resolution of the image. The image is res x res pixels. The default is 64.
- Returns:
The rendered image.
- Return type:
numpy.array
- gamma.image_utils.image3D(coordinates, R_half, weights, smoothing_length, plot_factor=10, res=64)[source]#
Image Render Module for 3D images.
This function renders a 3D image of the given field. The image is rendered using the scatter function from the swiftsimio.visualisation.volume_render module. The image is calculated in plot_factor*R_half. The image is res x res x res pixels.
- Parameters:
coordinates (numpy.array) – The coordinates of the particles. The Galaxy should be centered at the origin and already rotated to the xy-plane
R_half (float) – The half mass radius of the galaxy used to set the plot range.
weights (numpy.array) – The weights of the particles. This is the field that is rendered.
smoothing_length (numpy.array) – The smoothing length of the particles used for the SPH kernel.
plot_factor (float) – The factor by which the image is zoomed in. The image is calculated for -plot_factor*R_half < x,y,z < plot_factor*R_half
res (int) – The resolution of the image. The image is res x res pixels. The default is 64.
- Returns:
The rendered image.
- Return type:
numpy.array
- gamma.image_utils.moment_of_intertia_tensor(coordinates, particle_masses, rHalf, subhalo_pos)[source]#
Calculate the moment of inertia tensor of a galaxy.
The moment of inertia tensor is calculated to determine the orientation of the galaxy. The tensor is calculated in the center of mass frame of the galaxy using
I_ij = sum(m_i*(x_i-x_cm)*(x_j-x_cm)).
for the particles within 2*rHalf of the center of the galaxy.
- Parameters:
coordinates (numpy.array) – The coordinates of the particles.
particle_masses (numpy.array) – The masses of the particles.
rHalf (float) – The half mass radius of the galaxy.
subhalo_pos (numpy.array) – The center of the galaxy.
- Returns:
The moment of inertia tensor of the galaxy.
- Return type:
numpy.array
- gamma.image_utils.norm(x, takelog=True, plusone=True, clip=True, lower=0.1, upper=1.0)[source]#
Normalize image.
This function is called by the get_image function of the Galaxy class defined in the galaxy.py file. It normalizes the image by taking the log10 of the image and clipping it to the [lower,upper] quantile. For that we use a mask to ignore the zero values. The image is normalized to the range [0,1].
- Parameters:
x (numpy.array) – The image to be normalized.
takelog (bool, optional) – If True the log10 of the image is taken. The default is True.
plusone (bool, optional) – If True 1 is added to the image. The default is True.
clip (bool, optional) – If True the image is clipped to the [lower,upper] quantile. The default is True.
lower (float, optional) – The lower quantile. The default is 0.1. Only used if clip = True.
upper (float, optional) – The upper quantile. The default is 1.. Only used if clip = True.
- Returns:
The normalized image.
- Return type:
numpy.array
- gamma.image_utils.radial_distance(coords, center)[source]#
Calculate the radial distance of a set of coordinates to a center. Used to calculate the moment of inertia tensor.
- Parameters:
coords (numpy.array) – The coordinates of the particles.
center (numpy.array) – The center of the galaxy.
- Returns:
The radial distance of the particles to the center.
- Return type:
numpy.array
- gamma.image_utils.rotation_matrix(inertiaTensor, return_value='face-on')[source]#
Calculate the rotation matrix to orient the galaxy.
The rotation matrix is calculated from the moment of inertia tensor using the eigenvalues and eigenvectors of the tensor. The rotation matrix is used to rotate the galaxy to the x,y,z axes.
- Parameters:
inertiaTensor (numpy.array) – The moment of inertia tensor of the galaxy. This can be calculated using the moment_of_intertia_tensor function.
return_value (str, optional) – The orientation of the galaxy. The default is “face-on”. Can be “face-on” or “edge-on”.
- Returns:
The rotation matrix to orient the galaxy.
- Return type:
numpy.array
- gamma.image_utils.volume(hist, opacity=0.1, isomin=None, isomax=None, surface_count=30, add_small_number=True, norm_hist=True, **kwargs)[source]#
Visualise a 3D histogram as a volume.
Uses plotly to visualise a 3D histogram as a volume. The volume can be normalised and a small number can be added to the histogram to avoid visualising empty space.
- Parameters:
hist (numpy.array) – The 3D histogram to visualise.
opacity (float, optional) – The opacity of the volume. The default is .1.
isomin (float, optional) – The minimum value of the volume. The default is 0.
isomax (float, optional) – The maximum value of the volume. The default is None.
surface_count (int, optional) – The number of surfaces to use for the volume. The default is 30.
add_small_number (bool, optional) – Whether to add a small number to the histogram to avoid visualizing empty space. The default is True.
norm_hist (bool, optional) – Whether to normalise the histogram. The default is True.
**kwargs – Additional arguments to pass to the normalisation function.
gamma.load module#
- class gamma.load.Gamma(path, show_structure=True, m_min=None, m_max=None)[source]#
Bases:
objectClass to load the GAMMA data generated by the generate_data.py script.
Parameters:#
- pathstr
The path to the hdf5 file generated by the generate_data.py script.
- show_structurebool, optional
If True, print the structure of the hdf5 file.
- m_minfloat, optional
The minimum mass of the galaxies to load. If None, no filter is applied.
- m_maxfloat, optional
The maximum mass of the galaxies to load. If None, no filter is applied.
Attributes:#
- pathstr
The path to the hdf5 file generated by the generate_data.py script.
- masknp.ndarray
The mask to filter the data. If None, no mask is applied.
- _galaxy_attributes_keyslist
The keys of the galaxy attributes.
- _particles_keyslist
The keys of the particles.
- _image_fieldsdict
The fields of the images.
- get_attribute(attribute, index=None, ignore_mask=False)[source]#
Get a galaxy attribute.
If index is None, first check if a mask is set, and then return the specific attribute of all galaxies. Otherwise, return the attribute of the specified index in the dataset.
Parameters:#
- attributestr
The attribute to return. Must be a valid attribute, otherwise a ValueError is raised.
- indexint, optional
The galaxy index in the dataset to return. If None, return all galaxies.
- ignore_maskbool, optional
Whether to ignore the mask set for the dataset. Default is False.
Returns:#
- attributenp.ndarray
The attribute of the specified galaxy index in the dataset.
Examples:#
>>> data = Gamma("data.hdf5") >>> data.get_attribute("mass") # Get the mass of all galaxies in the dataset >>> data.get_attribute("mass", 10) # Get the mass of the 10th galaxy in the dataset Load Data with a mask >>> data = Gamma("data.hdf5", m_min=10, m_max=11) >>> data.get_attribute("mass") # Get the mass of all galaxies in the dataset with mass between 10^10 and 10^11
- get_image(particle_type, field, index=None, ignore_mask=False, dim=2)[source]#
Get the image of the specified particle type and field.
If index is None, return all images. Otherwise, return the galaxy image of the specified index and field in the dataset.
Parameters:#
- particle_typestr
The particle type of the image.
- fieldstr
The field of the image.
- indexint, optional
The galaxy index ind the dataset to return. If None, return all images.
- dimint, optional
The dimension of the image. If 2, return a 2D image. If 3, return a 3D image.
Returns:#
- imagenp.ndarray
The image of the specified particle type and field.
Examples:#
>>> data = Gamma("data.hdf5") >>> image = data.get_image("stars", "Masses", 10) # Get the stars masses image of the 10th galaxy in the dataset >>> all_images = data.get_image("stars", "Masses") # Get all stars masses images in the dataset
- show_structure()[source]#
Print the structure of the HDF5 file.
This method is useful to check the structure of the HDF5 file and the available attributes and images.
Examples:#
>>> data = Gamma("data.hdf5") >>> data.show_structure() File: data.hdf5 Group: Galaxies Group: Attributes Dataset: halo_id (int64) Dataset: mass (float64) Group: Particles Group: stars Group: Images Dataset: Masses (np.ndarray) Dataset: GFM_Metallicity (np.ndarray) Group: gas Group: Images Dataset: Masses (np.ndarray)
gamma.select_galaxies module#
gamma.simulations module#
This module contains the class for specific simulations. Currently only IllustrisTNG is implemented. You can add your own simulation by creating a new class based on the following template: class YourSimulation():
- def __init__(self, halo_id, particle_type, data_path):
self.data_path = data_path #Path to the data. self.halo_id= halo_id #Halo ID of a subhalo self.particle_type = particle_type #Particle type of the subhalo
# Add any other attributes you need. # These can later be accessed by the galaxy object using the getattr function, and can be saved in the HDF5 file.
self._load_data()
- def _load_data(self):
#Load the data from the snapshot and subhalo catalog. #The data needs to be stored in the following attributes:
self.particle_coordinates #Coordinates of the particles,used for face-on rotation and image rendering. self.particle_masses #Masses of the particles, used for face-on rotation and image rendering. self.center #Center of the subhalo. Used for centering the galaxy self.halfmassrad #Half mass radius of the subhalo. Used for the image rendering self.hsml #Smoothing length of the subhalo. Used for the image rendering.
- def get_field(self, field):
#Get the field from the snapshot. #The field should be returned as a numpy array and converted to physical units. #This field is then later used to create the weighted image.
return field
Note that the class name should be the same as the simulation name, since this is used to create the galaxy object.
- class gamma.simulations.IllustrisTNG(halo_id, particle_type, base_path, snapshot)[source]#
Bases:
objectClass for the IllustrisTNG simulation.
- get_field(field, particle_type=None)[source]#
Load a field from the particle data. Used for the image generation. The field is returned as a numpy array and converted to physical units.
- Parameters:
field (str) – Name of the field to load. The field should be stored in the snapshot.
particle_type (str, optional) – If the field is stored for multiple particle types, this specifies which particle type to return. If None, the field is returned for all particle types. The default is None.
- Returns:
The field converted to physical units.
- Return type:
numpy.array
Examples
>>> galaxy = Galaxy("IllustrisTNG", halo_id=0, particle_type="stars") >>> galaxy.get_field("GFM_StellarFormationTime")
- class gamma.simulations.illustrisAPI(api_key, particle_type='stars', simulation='TNG100-1', snapshot=99)[source]#
Bases:
object- DATAPATH = './tempdata'#
- URL = 'http://www.tng-project.org/api/'#
- get(path, params=None, name=None)[source]#
Get data from the Illustris API.
- Parameters:
path (str) – Path to load from.
params (dict) – Parameters to pass to the API.
name (str) – Name to save the file as. If None, the name will be taken from the content-disposition header.
- Returns:
r – The requests object.
- Return type:
requests object
- get_particle_data(id, fields)[source]#
Get particle data from the Illustris API.
Returns the particle data for the given subhalo ID.
- Parameters:
id (int) – Subhalo ID to load.
fields (str or list) – Fields to load. If a string, the fields should be comma-separated.
- Returns:
data – Dictionary containing the particle data in the given fields.
- Return type:
dict
- gamma.simulations.select_illustris_galaxies(basepath, snapshot, M_min, M_max, particle_type='stars')[source]#
Galaxy selection for IllustrisTNG.
Selects all galaxies with stellar mass between M_min and M_max and with SubhaloFlag == 1 (i.e proper galaxies).
Parameters:#
- basepath: str
Path to the IllustrisTNG data.
- snapshot: int
Snapshot number.
- M_min: float
Minimum stellar mass in Msun/h.
- M_max: float
Maximum stellar mass in Msun/h.
- particle_type: str
Particle type of the galaxy. Default: “stars”
Returns:#
- halo_ids: numpy array
Array of halo IDs of the selected galaxies.