Analysis
- opencosmo.analysis.reduce(dataset, function, operation='sum', all=False, **evaluate_kwargs)
Combine results from several MPI processes into a single result. By defualt, the result is returned to the root process (rank 0), while all other processes are returned
None. You can return the result to all processes by settingall = True.Under the hood, this function uses
evaluateto perform the computation. Besides the specific arguments mentioned below, you should pass in the arguments that you would if you were callingevaluatedirectly (includingvectorize, which you will probably want to set toTrue)For example, to compute a halo mass function across a large simulation:
import matplotlib.pyplot as plt import numpy as np import opencosmo as oc from opencosmo.analysis import reduce ds = oc.open("haloproperties.hdf5") def halo_mass_function(fof_halo_mass, log_bins, box_size): log_mass = np.log10(fof_halo_mass) hist, _ = np.histogram(log_mass, log_bins) return hist / np.diff(log_mass) / box_size ** 3 bins = np.linspace(10, 15) box_size = ds.header.simulation["box_size"].value results = reduce(ds, halo_mass_function, log_bins = bins, box_size = box_size, vectorize = True) if histogram is not None: plt.plot(bins, histogram["halo_mass_function"]) plt.savefig("hmf.png")
If you call this function but you are not working with MPI it will succeed but print a warning.
This function checks that the values returned from the different processes can actually be combined, and throws an error if not. The most common failure cases is when the arrays returned by various processes are not the same size.
Althoug the example above only returns a single array, you may return multiple arrays as a dictionary. Each array in the dictionary will be processed seperately.
- Parameters:
dataset (Dataset | Collection) – Any OpenCosmo dataset or collection which supports
evaluatefunction (Callable) – A function to compute on the dataset. See the documentation for
evaluatefor your given data type for details on the expected signature.operation (string, "sum" | "prod" | "avg", default = "sum") – The operation to use when performing the reduction. If “avg”, the averages will be weighted by the relative sizes of the datasets on each rank.
all (bool, default = False) – Whether to return the result to all processes or just the root process. If
False, all processes besides the root process will recieveNone**evaluate_kwargs (Any) – Additional keyword arguments that will be passed directly into
dataset.evalute.
- Returns:
results – The result of the reduction. If
all = False(the default) only the root process will recieve the results with the remaining processes receivingNone. Ifall = True, all processes will recieve the results- Return type:
dict[str, np.ndarray] | None
- opencosmo.analysis.create_yt_dataset(data, compute_xray_fields=False, return_source_model=False, source_model_kwargs={})
Converts particle data to a yt dataset. Note that yt is generally developed with AMR codes in mind, but support for SPH codes is continually being added. yt’s documentation can be found here.
If compute_xray_fields is enabled, X-ray emissivity and luminosity fields will be added using pyxsim, which generates photon samples from gas properties.
- Parameters:
data (dict of astropy.table.Table) – A dictionary of particle datasets. Must include at least positions and masses.
compute_xray_fields (bool, optional) – Whether or not to compute X-ray luminosities with pyxsim. Uses CIESourceModel, which considers thermal emission from gas assuming collisional ionization equilibrium.
return_source_model (bool, optional) – Whether or not to return the pyxsim source model for further interaction, such as computing additional luminosities in different frequency bands or generating synthetic observations.
source_model_kwargs (dict, optional) – Keyword arguments passed to the CIESourceModel constructor in pyxsim. These can include parameters like emin, emax, nbins, abund_table, etc., to control the spectral resolution and emission model behavior. If None, default values will be used for all source model parameters.
- Returns:
ds (yt.data_objects.static_output.Dataset) – A yt dataset built from the input particle data, with additional fields (e.g., X-ray luminosities) if requested.
source_model (pyxsim.source_models.CIESourceModel, optional) – Returned only if return_source_model=True.
- Return type:
Union[YT_Dataset, Tuple[YT_Dataset, CIESourceModel]]
- opencosmo.analysis.visualize_halo(halo_id, data, projection_axis='z', length_scale='top left', text_color='lightgray', width=None)
Creates a figure showing particle projections of dark matter, stars, gas, and/or gas temperature for given halo. If any of the listed particle types are not present in the dataset, this will create a horizontal arrangement with only the particles/fields that are present. Otherwise, creates a 2x2-panel figure. Each panel is an 800x800 pixel array.
To customize the arrangement of panels, fields, colormaps, etc., see
halo_projection_array().- Parameters:
halo_id (int) – Identifier of the halo to be visualized.
data (opencosmo.StructureCollection) – OpenCosmo StructureCollection object containing both halo properties and particle data (e.g. output of
opencosmo.open([haloproperties, sodbighaloparticles])).projection_axis (str, optional) – Data is projected along this axis (
"x","y", or"z"). Overridden ifparams["projection_axes"]is providedlength_scale (str or None, optional) –
Optionally add a horizontal bar denoting length scale in Mpc.
- Options:
"top left": add to top left panel"top right": add to top right panel"bottom left": add to bottom left panel"bottom right": add to bottom right panel"all top": add to all panels on top row"all bottom": add to all panels on bottom row"all left": add to all panels on leftmost column"all right": add to all panels on rightmost column"all": add to all panelsNone: no length scale on any panel
text_color (str, optional) – Set the color of all text annotations. Default is “gray”
width (float, optional) – Width of each projection panel in units of R200 for the halo. If None, plots full subvolume around halo.
- Returns:
A matplotlib Figure object.
- Return type:
matplotlib.figure.Figure
- opencosmo.analysis.halo_projection_array(halo_ids, data, field=('dm', 'particle_mass'), weight_field=None, projection_axis='z', cmap='gray', cmap_norm=None, zlim=None, params=None, length_scale=None, text_color='lightgray', width=None)
Creates a multipanel figure of projections for different fields and/or halos.
By default, creates an arrangement of dark matter particle projections with the same shape as halo_ids. Each panel is an 800x800 pixel array.
Customizable — can change which fields are plotted for which halos, their order, weighting, etc., using params.
NOTE: Dark matter particle masses often aren’t stored for gravity-only simulations because the particles all have the same mass by construction. The particles are also labelled as “gravity” particles in this case instead of “dm” particles in the data. To project dark matter particles in gravity only, one can use the
("gravity", "particle_ones")field in place of("dm", "particle_mass"). This will produce the same final image.- Parameters:
halo_ids (int or 2D array of int) – Unique ID of the halo(s) to be visualized. The shape of halo_ids sets the layout of the figure (e.g., if halo_ids is a 2x3 array, the outputted figure will be a 2x3 array of projections). To leave a panel in the outputted figure blank, set the corresponding entry into the halo_ids array to None. If int, a single panel is output while preserving formatting.
data (opencosmo.StructureCollection) – OpenCosmo StructureCollection dataset containing both halo properties and particle data (e.g., output of
opencosmo.open([haloproperties, sodbighaloparticles])).field (tuple of str, optional) – Field to plot for all panels. Follows yt naming conventions (e.g.,
("dm", "particle_mass"),("gas", "temperature")). Overridden ifparams["fields"]is provided.weight_field (tuple of str, optional) – Field to weight by during projection. Follows yt naming conventions. Overridden if
params["weight_fields"]is provided.projection_axis (str, optional) – Data is projected along this axis (
"x","y", or"z"). Overridden ifparams["projection_axes"]is providedcmap (str) – Matplotlib colormap to use for all panels. Overridden if
params["cmaps"]is provided. See https://matplotlib.org/stable/gallery/color/colormap_reference.html for named colormaps.cmap_norm (Normalize) – Normalization for matplotlib colormap (e.g. for setting
norm=matplotlib.colors.SymLogNorm()). IfNone, defaults tomatplotlib.colors.LogNorm(vmin=zlim[0], vmax=zlim[1])zlim (tuple of float, optional) – Colorbar limits for field. Overridden if
params["zlims"]is provided.length_scale (str or None, optional) –
Optionally add a horizontal bar denoting length scale in Mpc.
- Options:
"top left": add to top left panel"top right": add to top right panel"bottom left": add to bottom left panel"bottom right": add to bottom right panel"all top": add to all panels on top row"all bottom": add to all panels on bottom row"all left": add to all panels on leftmost column"all right": add to all panels on rightmost column"all": add to all panelsNone: no length scale shown
params (dict, optional) –
Dictionary of customization parameters for the projection panels. Overrides defaults. All values must be 2D arrays with the same shape as halo_ids.
- Keys may include:
"fields": 2D array of fields to plot (yt naming conventions)"weight_fields": 2D array of projection weights (or None)"projection_axes": 2D array of projection axes (“x”, “y”, or “z”)"zlims": 2D array of colorbar limits (log-scaled)"labels": 2D array of panel labels (or None)"cmaps": 2D array of Matplotlib colormaps for each panel"cmap_norms": 2D array of colormap normalization method (e.g. matplotlib.colors.LogNorm())"widths": 2D array of widths in units of R200
text_color (str, optional) – Set the color of all text annotations. Default is “gray”
width (float, optional) – Width of each projection panel in units of R200 for the halo. Overridden if
params["widths"]is provided. If None, plots full subvolume.
- Returns:
A Matplotlib Figure object.
- Return type:
matplotlib.figure.Figure
- opencosmo.analysis.ParticleProjectionPlot(*args, **kwargs)
Wrapper for yt.ParticleProjectionPlot.
Creates a 2D projection plot of particle-based data along a specified axis.
- Parameters:
*args – Positional arguments passed directly to yt.ParticleProjectionPlot.
**kwargs – Keyword arguments passed directly to yt.ParticleProjectionPlot.
- Returns:
A ParticleProjectionPlot object containing the particle projection plot.
- Return type:
yt.visualization.plot_window.ParticleProjectionPlot
- opencosmo.analysis.ProjectionPlot(*args, **kwargs)
Wrapper for yt.ProjectionPlot.
Creates a 2D projection plot of particle-based data along a specified axis. Smoothing is applied to SPH particle data over the smoothing length
- Parameters:
*args – Positional arguments passed directly to yt.ProjectionPlot.
**kwargs – Keyword arguments passed directly to yt.ProjectionPlot.
- Returns:
A ProjectionPlot object containing the smoothed particle projection plot.
- Return type:
yt.visualization.plot_window.ProjectionPlot
- opencosmo.analysis.SlicePlot(*args, **kwargs)
Wrapper for yt.SlicePlot.
Creates a 2D slice plot of particle-based data along a specified axis. Smoothing is applied to SPH particle data over the smoothing length
- Parameters:
*args – Positional arguments passed directly to yt.SlicePlot.
**kwargs – Keyword arguments passed directly to yt.SlicePlot.
- Returns:
A PlotWindow object containing the particle slice plot.
- Return type:
yt.visualization.plot_window.PlotWindow
- opencosmo.analysis.ProfilePlot(*args, **kwargs)
Wrapper for yt.ProfilePlot.
Creates a bin-averaged profile of a dependent variable as a function of one or more independent variables.
- Parameters:
*args – Positional arguments passed directly to yt.ProfilePlot.
**kwargs – Keyword arguments passed directly to yt.ProfilePlot.
- Returns:
A PlotWindow object containing the profile plot.
- Return type:
yt.visualization.plot_window.PlotWindow
- opencosmo.analysis.PhasePlot(*args, **kwargs)
Wrapper for yt.PhasePlot.
Creates a 2D histogram (phase plot) showing how one quantity varies as a function of two others, useful for visualizing thermodynamic or structural relationships (e.g., temperature vs. density colored by mass).
- Parameters:
*args – Positional arguments passed directly to yt.PhasePlot.
**kwargs – Keyword arguments passed directly to yt.PhasePlot.
- Returns:
A PlotWindow object containing the phase plot.
- Return type:
yt.visualization.plot_window.PlotWindow