firestudio.studios.gas_studio.GasStudio

class firestudio.studios.gas_studio.GasStudio(datadir: str, snapnum: int, sim_name: str, cache_file_name: Optional[str] = None, gas_snapdict: Optional[dict] = None, star_snapdict: Optional[dict] = None, galaxy_kwargs: Optional[dict] = None, master_loud: bool = True, setup_id_append: str = '', **kwargs)[source]

Bases: firestudio.studios.studio.Studio

Studio class for making gas projection images. Can be used for stars (or other collisionless particles), but you will either have to pass smoothing lengths or allow FIRE Studio to calculate them itself, which can take a long time.

__init__(datadir: str, snapnum: int, sim_name: str, cache_file_name: Optional[str] = None, gas_snapdict: Optional[dict] = None, star_snapdict: Optional[dict] = None, galaxy_kwargs: Optional[dict] = None, master_loud: bool = True, setup_id_append: str = '', **kwargs)

Base class that handles camera manipulation and data caching.

Parameters
  • datadir (str) – directory to put intermediate and output files, 'firestudio' is appended if the directory contains sim_name

  • snapnum (int) – snapshot number (feel free to lie if you aren’t using FIRE_studio to open a snapshot, it is needed for cache file name though)

  • sim_name (str) – name of the simulation, i.e. 'm12i_res7100'. prepends the cache_file_name if the sim_name isn’t already in the path to disambiguate caches.

  • cache_file_name (str, optional) – the name of the file to save maps to, if None 'proj_maps_%03d.hdf5'%snapnum, defaults to None

  • gas_snapdict (dict, optional) – a dictionary containing SPH data, defaults to None

  • star_snapdict (dict, optional) – a dictionary containing collisionless particle data, defaults to None

  • galaxy_kwargs (dict, optional) – dictionary that contains kwargs that should be passed to the opened abg_python.galaxy.Galaxy instance that is used to load snapshot data from disk, defaults to None

  • master_loud (bool, optional) – flag for enabling/disabling all print statements, defaults to True

  • setup_id_append (str, optional) – suffix to append to the setup_id in the cache file, defaults to ‘’

Methods

__init__(datadir, snapnum, sim_name[, ...])

Base class that handles camera manipulation and data caching.

addScaleBar(image)

_summary_

addText(ax)

_summary_

computeFrameBoundaries()

Uses the camera to calculate the minimum and maximum x, y, and z limits as well as the physical resolution of the image.

cullFrameIndices(Coordinates)

boolean mask of those particles within the volume defined by Xmin-Xmax, Ymin-Ymax, and Zmin-Zmax

drawCoordinateAxes(ax[, spacing, length, colors])

_summary_

get_HSML(snapdict_name[, use_metadata, ...])

Compute smoothing lengths for particles that don't have them, typically collisionless particles (like stars).

gradientBlendImages(image_1[, image_2, ...])

_summary_

load_SnapshotData([gas_mask, star_mask])

Binds simulation output to self.gas_snapdict and self.star_snapdict.

plotImage(ax, final_image)

Implementation of overlaying artists on top of projected image.

prepareCoordinates(snapdict_name, weights, ...)

_summary_

print_ImageParams()

Prints the current image parameters.

produceImage([weight_name, quantity_name, ...])

Generates a projected image using the stored image parameters.

projectAlongLOS(weights, weight_name, ...[, ...])

Projects a weighted quantity along the LOS into pixels.

quick_projectAlongLOS(weights, weight_name, ...)

Approximates the projection of a weighted quantity along the LOS into pixels.

render([ax])

Generates an image with the produceImage method and then plots it with the plotImage method.

renormalizeTransposeImage(image, min_val, ...)

_summary_

saveFigure(fig[, image_name])

_summary_

set_CacheFile()

Creates the cache hdf5 file.

set_ImageParams([use_defaults, loud])

Changes the parameters of the image.

Attributes

required_snapdict_keys

these are minimum required keys for render() function to run.

addScaleBar(image: numpy.ndarray)

_summary_

Parameters

image (np.ndarray) – array of RGB image pixel values

Returns

image

Return type

np.ndarray

addText(ax: matplotlib.axes._axes.Axes)

_summary_

Parameters

ax (plt.Axes) – _description_

computeFrameBoundaries()

Uses the camera to calculate the minimum and maximum x, y, and z limits as well as the physical resolution of the image.

Sets following attributes

self.Xmin, self.Xmaxself.Ymin, self.Ymaxself.Zmin, self.Zmaxself.npix_x, self.npix_yself.Acell

cullFrameIndices(Coordinates: numpy.ndarray)

boolean mask of those particles within the volume defined by Xmin-Xmax, Ymin-Ymax, and Zmin-Zmax

Parameters

Coordinates (np.ndarray) – array of particle coordinates

Returns

a boolean mask which is True for particles in the extraction volume and False outside.

Return type

bool np.ndarray

drawCoordinateAxes(ax: matplotlib.axes._axes.Axes, spacing: float = 1, length: float = 10, colors: Optional[list] = None)

_summary_

Parameters
  • ax (plt.Axes) – _description_

  • spacing (float, optional) – _description_, defaults to 1

  • length (float, optional) – _description_, defaults to 10

  • colors (list, optional) – _description_, defaults to None

Returns

_description_

Return type

_type_

get_HSML(snapdict_name: str, use_metadata: bool = True, save_meta: bool = True, assert_cached: bool = False, loud: bool = True, **kwargs)

Compute smoothing lengths for particles that don’t have them, typically collisionless particles (like stars).

Parameters
  • snapdict_name (str) – string identifying which snapdict should be used to compute smoothing lengths, either 'gas' or 'star'

  • use_metadata (bool, optional) – flag for whether a cached result should be used (if it exists), defaults to True

  • save_meta (bool, optional) – flag to save the result in the cache, defaults to True

  • assert_cached (bool, optional) – flag to require a cache hit and raise an exception otherwise, defaults to False

  • loud (bool, optional) – flag for whether cache hits/misses should be announced to the console, defaults to True

Returns

estimated smoothing lengths

Return type

np.float32 np.ndarray

gradientBlendImages(image_1: numpy.ndarray, image_2: Optional[numpy.ndarray] = None, gradient_width_percent: float = 0.1, angle: Optional[float] = None, **kwargs)

_summary_

Parameters
  • image_1 (np.ndarray) – _description_

  • image_2 (np.ndarray, optional) – _description_, defaults to None

  • gradient_width_percent (float, optional) – _description_, defaults to 0.1

  • angle (float, optional) – _description_, defaults to None

Returns

_description_

Return type

_type_

load_SnapshotData(gas_mask: Optional[numpy.ndarray] = None, star_mask: Optional[numpy.ndarray] = None, **kwargs)

Binds simulation output to self.gas_snapdict and self.star_snapdict.

Parameters
  • gas_mask (np.ndarray, optional) – boolean mask that should be applied to the galaxy.sub_snap, defaults to None

  • star_mask (np.ndarray, optional) – boolean mask that should be applied to the galaxy.sub_star_snap, defaults to None

Kwargs
  • fuse_saved_subsnapshots (bool, optional) – save/load subsnapshots, uncompressed copies of the snapshot oriented on the main disk with particles within the virial radius. This can take up lots of disk space, defaults to False

  • del_galaxy (bool, optional) – flag for whether the abg_python.galaxy.gal_utils.Galaxy object should be deleted after being used to get the snapshot dictionaries, defaults to True

Returns

abg_python.galaxy.Galaxy if del_galaxy == False, otherwise returns None

Return type

None/abg_python.galaxy.Galaxy object

plotImage(ax: matplotlib.axes._axes.Axes, final_image: numpy.ndarray)[source]

Implementation of overlaying artists on top of projected image. Also calls the base method plotImage(). If self.use_colorbar we add a colorbar to the image, see set_ImageParams() for details.

Parameters
  • ax (plt.Axes) – matplotlib axis to plot image to

  • final_image (np.ndarray) – array of RGB image pixel values

prepareCoordinates(snapdict_name: str, weights: numpy.ndarray, weight_name: str, quantities: numpy.ndarray, quantity_name: str)[source]

_summary_

Parameters
  • snapdict_name (str) – one of gas or star to identify which of self.gas_snapdict or self.star_snapdict to read data from.

  • weights (np.ndarray) – array of weights to use alongside the smoothing kernel (typically self.snapdict['Masses']).

  • weight_name – Name of the key in the snapdict that should be used as the weights if weights are not passed. special weight_names are Volumes and Ones, which do not have to be present in the snapdict. :type weight_name: str

  • quantities (np.ndarray) – array of quantities to project along the line of sight.

  • quantity_name (str) – Name of the field that is being projected, should be in the snapdict if quantities is not passed.

Raises
  • KeyError – if snapdict_name is not 'gas' or 'star'

  • KeyError – if weight_name is not in snapdict.keys()

  • KeyError – if quantity_name is not in snapdict.keys()

Returns

self.Xmin - minimum x value of coordinates, already applied just returned for convenience
self.Xmax - maximum x value of coordinates, already applied just returned for convenience
self.Ymin - minimum y value of coordinates, already applied just returned for convenience
self.Ymax - maximum y value of coordinates, already applied just returned for convenience
self.npix_x - number of pixels along the x axis
self.npix_y - number of pixels along the y axis
pos - coordinate data for particles in kpc
weights - filtered array of weights to use alongside the smoothing kernel (typically self.snapdict['Masses']).
quantities - filtered array of quantities to project along the line of sight.
hsml - filtered array of smoothing lengths/radii for each particle

Return type

float, float, float, float, float, float, np.ndarray, np.ndarray, np.ndarray, np.ndarry

print_ImageParams()[source]

Prints the current image parameters.

produceImage(weight_name: str = 'Masses', quantity_name: str = 'Temperature', weights: Optional[numpy.ndarray] = None, quantities: Optional[numpy.ndarray] = None, min_weight: Optional[float] = None, max_weight: Optional[float] = None, min_quantity: Optional[float] = None, max_quantity: Optional[float] = None, weight_adjustment_function=None, quantity_adjustment_function=None, cmap: str = 'viridis', quick: bool = False, **kwargs)[source]

Generates a projected image using the stored image parameters. Specify whether the image should be “one-color” (i.e. a simple projection map) or “two-color” (a projection map where the hue is set by the LOS projected weighted quantity and the saturation is set by the LOS projected weight) by passing values for min_weight, max_weight, min_quantity, and max_quantity.

Parameters
  • weight_name (str, optional) – Name of the key in the snapdict that should be used as the weights if weights are not passed. Special weight_names are Volumes and Ones, which do not have to be present in the snapdict, defaults to 'Masses'

  • quantity_name (str, optional) – Name of the field that is being projected, should be in the snapdict if quantities is not passed, defaults to 'Temperature'

  • weights (np.ndarray, optional) – array of weights to use alongside the smoothing kernel (typically self.snapdict['Masses']). If None searches self.snapdict for weight_name, defaults to None

  • quantities (np.ndarray, optional) – array of quantities to project along the line of sight. If None searches self.snapdict for weight_name, defaults to None

  • min_weight (float, optional) – minimum value to use for the colorbar of weight projection maps and saturation for two-color images, defaults to None

  • max_weight (float, optional) – maximum value to use for the colorbar of weight projection maps and saturation for two-color images, defaults to None

  • min_quantity (float, optional) – minimum value to use for the colorbar of weighted quantity projection maps and hue for two-color images, defaults to None

  • max_quantity (float, optional) – maximum value to use for the colorbar of weighted quantity projection maps and hue for two-color images, defaults to None

  • weight_adjustment_function (_type_, optional) – function to apply to the weightMap after it is returned by projectAlongLOS() for the purposes of specifying min_weight and max_weight, defaults to None

  • quantity_adjustment_function (_type_, optional) – function to apply to the weightWeightedQuantityMap after it is returned by projectAlongLOS() for the purposes of specifying min_quantity and max_quantity, defaults to None

  • cmap (str, optional) – name of colormap to apply to image, defaults to 'viridis'

Raises

ValueError – if an invalid combination of min/max weight/quantity parameters are passed.

Returns

array of RGB image pixel values

Return type

np.ndarray(npix_x,npix_y,3)

Example usage
## makes a gas surface density map
gasStudio.render(
    weight_name='Masses',
    min_weight=-0.1,
    max_weight=1.5,
    weight_adjustment_function=lambda x:
        np.log10(x/gasStudio.Acell)+10-6) ## log10(msun/pc^2)

## makes a mass weighted temperature map
gasStudio.render(
    weight_name='Masses',
    quantity_name='Temperature',
    min_quantity=2,
    max_quantity=7,
    quantity_adjustment_function= np.log10
    )

## makes a saturation-hue gas surface density + Temperature map
gasStudio.render(
    weight_name='Masses',
    min_weight=-0.1,
    max_weight=1.5,
    weight_adjustment_function=lambda x:
        np.log10(x/gasStudio.Acell)+10-6 ## log10(msun/pc^2)
    quantity_name='Temperature',
    min_quantity=2,
    max_quantity=7,
    quantity_adjustment_function= np.log10)
projectAlongLOS(weights: numpy.ndarray, weight_name: str, quantities: numpy.ndarray, quantity_name: str, use_metadata: bool = True, save_meta: bool = True, assert_cached: bool = False, loud: bool = True, **kwargs)[source]

Projects a weighted quantity along the LOS into pixels. Projection is done with a cubic spline kernel that is renormalized to conserve mass.

I.e. renorm_i = sum_j ( k(r_ij,h_i)) where j is a sum over the pixels particle i contributes to. The maps computed in the flattened pixel array at index j are then:

W[j] = sum_i( k(r_ij,h_i)/renorm_i * weight)
Q[j] = sum_i( k(r_ij,h_i)/renorm_i * weight * quantity) / W[j]
Parameters
  • weights (np.ndarray) – array of weights to use alongside the smoothing kernel (typically self.snapdict['Masses']).

  • weight_name – Name of the key in the snapdict that should be used as the weights if weights are not passed. special weight_names are Volumes and Ones, which do not have to be present in the snapdict. :type weight_name: str

  • quantities (np.ndarray) – array of quantities to project along the line of sight.

  • quantity_name (str) – Name of the field that is being projected, should be in the snapdict if quantities is not passed.

  • use_metadata (bool, optional) – flag for whether a cached result should be used (if it exists), defaults to True

  • save_meta (bool, optional) – flag to save the result in the cache, defaults to True

  • assert_cached (bool, optional) – flag to require a cache hit and raise an exception otherwise, defaults to False

  • loud (bool, optional) – flag for whether cache hits/misses should be announced to the console, defaults to True

Kwargs
  • snapdict_name (str, optional) – one of gas or star to identify which of self.gas_snapdict or self.star_snapdict to read data from.

Returns

weightMap - image of sum(weights) along the line of sight in each pixel
weightWeightedQuantityMap - image of sum(weights*quantity) along the line of sight in each pixel

Return type

np.ndarray, np.ndarray

quick_projectAlongLOS(weights: numpy.ndarray, weight_name: str, quantities: numpy.ndarray, quantity_name: str, snapdict_name='gas', **kwargs)[source]

Approximates the projection of a weighted quantity along the LOS into pixels. using a 2d histogram and assuming particles have 0 extent. much faster than the real thing and useful for quick and dirty testing.

Parameters
  • weights (np.ndarray) – array of weights to use alongside the smoothing kernel (typically self.snapdict['Masses']).

  • weight_name – Name of the key in the snapdict that should be used as the weights if weights are not passed. special weight_names are Volumes and Ones, which do not have to be present in the snapdict. :type weight_name: str

  • quantities (np.ndarray) – array of quantities to project along the line of sight.

  • quantity_name (str) – Name of the field that is being projected, should be in the snapdict if quantities is not passed.

  • snapdict_name (str, optional) – one of gas or star to identify which of self.gas_snapdict or self.star_snapdict to read data from.

Returns

weightMap - image of sum(weights) along the line of sight in each pixel
weightWeightedQuantityMap - image of sum(weights*quantity) along the line of sight in each pixel

Return type

np.ndarray, np.ndarray

render(ax: Optional[matplotlib.axes._axes.Axes] = None, **kwargs)

Generates an image with the produceImage method and then plots it with the plotImage method.

Parameters

ax (plt.Axes, optional) – axis to plot image to, if None will create a new figure, defaults to None

Returns

ax – the axis the image was plotted to final_image – Npixels x Npixels x 3 RGB pixel array

Return type

plt.Axes, np.ndarray

renormalizeTransposeImage(image: numpy.ndarray, min_val: float, max_val: float, quantity_name: str)

_summary_

Parameters
  • image (np.ndarray) – _description_

  • min_val (float) – _description_

  • max_val (float) – _description_

  • quantity_name (str) – _description_

Returns

_description_

Return type

_type_

required_snapdict_keys = ['Coordinates', 'Masses', 'SmoothingLength', 'Temperature', 'Velocities']

these are minimum required keys for render() function to run.

saveFigure(fig, image_name: Optional[str] = None, **savefig_args)

_summary_

Parameters
  • fig (_type_) – _description_

  • image_name (str, optional) – _description_, defaults to None

set_CacheFile()

Creates the cache hdf5 file. Requires self.snapnum and sim_name be set.

Raises

IOError – if self.snapnum and self.sim_name are not set to disambiguate the cache file

Returns

cache file for storing image maps

Return type

abg_python.galaxy.metadata_utils.Metadata

set_ImageParams(use_defaults: bool = False, loud: bool = True, **kwargs)[source]

Changes the parameters of the image. Also calls Studio’s set_ImageParams(), passing along any unmatched kwargs.

Parameters
  • use_defaults (bool, optional) – If True then default values of the parameters will be set (potentially overwriting any previously specified parameters). If False adjust only the keywords passed, defaults to False

  • loud (bool, optional) – flag to print which parameters are being set/updated, defaults to True

Kwargs
  • use_colorbar (bool, optional) – flag to add a colorbar to the image. not currently implemented for two-color images, defaults to False

  • cbar_label (str, optional) – label for the colorbar, defaults to ‘’

  • cbar_logspace (bool, optional) – flag for whether ticks on the colorbar should be log-spaced, defaults to False

Example usage
gasStudio.set_ImageParams(
    use_colorbar=True,
    cbar_label='Temperature',
    cbar_logspace=True,
    figure_label='t = 13.8 Gyr')