Dataset

class opencosmo.Dataset(header, state, tree=None)
Parameters:
property header: OpenCosmoHeader

The header associated with this dataset.

OpenCosmo headers generally contain information about the original data this dataset was produced from, as well as any analysis that was done along the way.

Returns:

header

Return type:

opencosmo.header.OpenCosmoHeader

property columns: list[str]

The names of the columns in this dataset.

Returns:

columns

Return type:

list[str]

property meta_columns: list[str]
property descriptions: dict[str, str | None]

Return the descriptions (if any) of the columns in this dataset as a dictonary. Columns without a description will be included in the dictionary with a value of None

Returns:

descriptions – The column descriptions

Return type:

dict[str, str | None]

property cosmology: Cosmology

The cosmology of the simulation this dataset is drawn from as an astropy.cosmology.Cosmology object.

Returns:

cosmology

Return type:

astropy.cosmology.Cosmology

property dtype: str

The data type of this dataset.

Returns:

dtype

Return type:

str

property redshift: float | tuple[float, float] | None

The redshift slice or range this dataset was drawn from

Returns:

redshift

Return type:

float

property region: Region

The region this dataset is contained in. If no spatial queries have been performed, this will be the entire simulation box for snapshots or the full sky for lightcones

Returns:

region

Return type:

opencosmo.spatial.Region

property simulation: HaccSimulationParameters

The parameters of the simulation this dataset is drawn from.

Returns:

parameters

Return type:

opencosmo.parameters.hacc.HaccSimulationParameters

property data: QTable | Quantity

Return the data in the dataset in astropy format. The value of this attribute is equivalent to the return value of Dataset.get_data("astropy").

Returns:

  • data (astropy.table.Table or astropy.table.Column) – The data in the dataset.

  • .. deprecated:: 1.1.0 – Accessing data through the .data attribute is deprecated and will be removed in a future version. Use get_data()

get_metadata(columns=[])
Parameters:

columns (str | list[str])

get_data(output='astropy', unpack=True, metadata_columns=[])

Get the data in this dataset as an astropy table/column or as numpy array(s). Note that a dataset does not load data from disk into memory until this function is called. As a result, you should not call this function until you have performed any transformations you plan to on the data.

The method supports output into several different formats, including “astropy”, “numpy”, “pandas”, “polars”, and “pyarrow”. Although astropy and numpy are core dependencies of OpenCosmo, the remaining formats require you to have the relevant libraries installed in your python environment. This method will check that it can import the necessary libraries before attempting to read data. Note that outputting as “polars” or “arrow” requires copying the data out of its original numpy arrays, which will impact performance.

If the dataset only contains a single column, it will not be put in a table or dictionary. “astropy”, “numpy” and “arrow” will return a single array in this case, while “polars” and “pandas” will return a Series object.

Parameters:

output (str, default="astropy") – The format to output the data in. Currently supported are “astropy”, “numpy”, “pandas”, “polars”, “arrow”

Returns:

data – The data in this dataset.

Return type:

Any

bound(region, select_by=None)

Restrict the dataset to some subregion. The subregion will always be evaluated in the same units as the current dataset. For example, if the dataset is in the default “comoving” unit convention, positions are always in units of comoving Mpc. However Region objects themselves do not carry units. See Regions for details of how to construct regions.

Parameters:
  • region (opencosmo.spatial.Region) – The region to query.

  • select_by (Optional[str])

Returns:

dataset – The portion of the dataset inside the selected region

Return type:

opencosmo.Dataset

Raises:
  • ValueError – If the query region does not overlap with the region this dataset resides in

  • AttributeError: – If the dataset does not contain a spatial index

evaluate(func, vectorize=False, insert=True, format='astropy', batch_size=-1, **evaluate_kwargs)

Iterate over the rows in this dataset, apply func to each, and collect the result as new columns in the dataset.

This function is the equivalent of with_new_columns for cases where the new column is not a simple algebraic combination of existing columns. Unlike with_new_columns, this method will evaluate the results immediately and the resulting columns will not change under unit transformations. You may also choose to simply return the result instead of adding it as a column.

The function should take in arguments with the same name as the columns in this dataset that are needed for the computation, and should return a dictionary of output values. The dataset will automatically selected the needed columns to avoid reading unnecessarily reading data from disk

The new columns will have the same names as the keys of the output dictionary See Evaluating on Datasets for more details.

If vectorize is set to True, the full columns will be pased to the dataset. Otherwise, rows will be passed to the function one at a time.

If the function returns None, this method will also return None as output. For example, the function could simply produce plots and save the to files.

Parameters:
  • func (Callable) – The function to evaluate on the rows in the dataset.

  • vectorize (bool, default = False) – Whether to provide the values as full columns (True) or one row at a time (False). Ignored if batch_size is set.

  • insert (bool, default = True) – If true, the data will be inserted as a column in this dataset. The new column will have the same name as the function. Otherwise the data will be returned directly.

  • format (str, default = astropy) – Whether to provide data to your function as “astropy” quantities or “numpy” arrays/scalars. Default “astropy”. Note that this method does not support all the formats available in get_data

  • batch_size (int, default = -1) – If set, feed data to the function in batches of the specified size. Default is -1, which disables batching. If set to another value, the vectorize flag is ignored.

  • **evaluate_kwargs (any,) – Any additional arguments that are required for your function to run. These will be passed directly to the function as keyword arguments. If a kwarg is an array of values with the same length as the dataset, it will be treated as an additional column.

Returns:

result – The new dataset with the evaluated column(s) or the results as numpy arrays or astropy quantities

Return type:

Dataset | dict[str, np.ndarray | astropy.units.Quantity]

filter(*masks)

Filter the dataset based on some criteria. See Querying Based on Column Values for more information.

Parameters:

*masks (Mask) – The masks to apply to dataset, constructed with opencosmo.col()

Returns:

dataset – The new dataset with the masks applied.

Return type:

Dataset

Raises:

ValueError – If the given refers to columns that are not in the dataset, or the would return zero rows.

rows(include_units=True, metadata_columns=[])

Iterate over the rows in the dataset. Rows are returned as a dictionary For performance, it is recommended to first select the columns you need to work with.

Parameters:
  • output (str, default = "astropy") – Whether to return values as “astropy” quantities or “numpy” scalars

  • include_units (bool)

Yields:

row (dict) – A dictionary of values for each row in the dataset with units.

Return type:

Generator[Mapping[str, float | units.Quantity | np.ndarray]]

select(columns)

Create a new dataset from a subset of columns in this dataset

Parameters:

columns (str or list[str]) – The column or columns to select.

Returns:

dataset – The new dataset with only the selected columns.

Return type:

Dataset

Raises:

ValueError – If any of the given columns are not in the dataset.

drop(columns)

Create a new dataset without the provided columns.

Parameters:

columns (str or list[str]) – The columns to drop

Returns:

dataset – The new dataset without the droppedcolumns

Return type:

Dataset

Raises:

ValueError – If any of the provided columns are not in the dataset.

sort_by(column, invert=False)

Sort this dataset by the values in a given column. By default sorting is in ascending order (least to greatest). Pass invert = True to sort in descending order (greatest to least).

This can be used to, for example, select largest halos in a given dataset:

dataset = oc.open("haloproperties.hdf5")
dataset = dataset
            .sort_by("fof_halo_mass", invert=True)
            .take(100, at="start")
Parameters:
  • column (str) – The column in the halo_properties or galaxy_properties dataset to order the collection by.

  • invert (bool, default = False) – If False (the default), ordering will be from least to greatest. Otherwise greatest to least.

Returns:

result – A new Dataset ordered by the given column.

Return type:

Dataset

take(n, at='random')

Create a new dataset from some number of rows from this dataset.

Can take the first n rows, the last n rows, or n random rows depending on the value of ‘at’.

Parameters:
  • n (int) – The number of rows to take.

  • at (str) – Where to take the rows from. One of “start”, “end”, or “random”. The default is “random”.

Returns:

dataset – The new dataset with only the selected rows.

Return type:

Dataset

Raises:

ValueError – If n is negative or greater than the number of rows in the dataset, or if ‘at’ is invalid.

take_range(start, end)

Create a new dataset from a row range in this dataset. We use standard indexing conventions, so the rows included will be start -> end - 1.

Parameters:
  • start (int) – The beginning of the range

  • end (int) – The end of the range

Returns:

table – The table with only the rows from start to end.

Return type:

astropy.table.Table

Raises:

ValueError – If start or end are negative or greater than the length of the dataset or if end is greater than start.

take_rows(rows)

Take the rows of a dataset specified by the rows argument. rows should be an array of integers.

Parameters:

rows: np.ndarray[int]

returns:
  • dataset (The dataset with only the specified rows included)

  • Raises

  • ——-

  • ValueError – If any of the indices is less than 0 or greater than the length of the dataset.

Parameters:

rows (np.ndarray | DataIndex)

with_new_columns(descriptions={}, **new_columns)

Create a new dataset with additional columns. These new columns can be derived from columns already in the dataset, a numpy array, or an astropy quantity array. When a column is derived from other columns, it will behave appropriately under unit transformations. Columns provided directly as astropy quantities will not change under unit transformations. See Adding Custom Columns for examples.

Parameters:
  • descriptions (str | dict[str, str], optional) – A description for the new columns. These descriptions will be accessible through Dataset.descriptions. If a dictionary, should have keys matching the column names.

  • new_columns (**)

Returns:

dataset – This dataset with the columns added

Return type:

opencosmo.Dataset

with_units(convention=None, conversions={}, **columns)

Create a new dataset from this one with a different unit convention, and/or convert one unit to another across the entire dataset, or convert individual columns.

Unit conversions are always performed after a change of convention, and changing conventions clears any existing unit conversions. Individual column conversions always take precedence over blanket unit conversions.

Calling this function without arguments will clear any existing unit conversions.

For more, see Working with Units.

import astropy.units as u

# this works
dataset = dataset.with_units(fof_halo_mass=u.kg)

# this clears the previous conversion
dataset = dataset.with_units("scalefree")

# This now fails, because the units of masses
# are Msun / h, which cannot be converted to kg
dataset = dataset.with_units(fof_halo_mass=u.kg)

# this will work, the units of halo mass in the "physical"
# convention are Msun (no h).
dataset = dataset.with_units("physical", fof_halo_mass=u.kg, fof_halo_center_x=u.lyr)

# Suppose you want all distances in lightyears, but the x coordinate of your
# halo center in kilometers, for some reason ¯\_(ツ)_/¯
blanket_conversions = {u.Mpc: u.lyr}
dataset = dataset.with_units(conversions = blanket_conversions, fof_halo_center_x = u.km)
Parameters:
  • convention (str, optional) – The unit convention to use. One of “physical”, “comoving”, “scalefree”, or “unitless”.

  • conversions (dict[astropy.units.Unit, astropy.Units.Unit]) – Conversions that apply to all columns in the dataset with the unit given by the key.

  • **column_conversions (astropy.units.Unit) – Custom unit conversions for one or more or of the columns in this dataset.

  • columns (Unit)

Returns:

dataset – The new dataset with the requested unit convention and/or conversions.

Return type:

Dataset