swiftsimio package
Tools for reading SWIFT simulation data.
The most used functions are load() and mask().
The visualisation sub-module provides visualisation tools.
- class swiftsimio.SWIFTDataset(filename: Path, mask: SWIFTMask | None = None, handle: File | None = None)[source]
Bases:
HandleProviderA collection object for units, metadata and data objects.
It contains:
a
SWIFTUnits,a
SWIFTMetadata,several
SWIFTGroupDataset
This object, in essence, completely represents a SWIFT snapshot. You can access the different particles as follows:
SWIFTDataset.gas.particle_ids
SWIFTDataset.dark_matter.masses
SWIFTDataset.gas.smoothing_lengths
These arrays all have units that are determined by the unit system in the file.
The unit system is available as SWIFTDataset.units and the metadata as SWIFTDataset.metadata.
- Parameters:
- filename: Path
- get_units() None[source]
Load the units from the SWIFT snapshot.
Ordinarily this happens automatically, but you can call this function again if you mess things up.
- swiftsimio.Writer
alias of
SWIFTSnapshotWriter
- class swiftsimio.SWIFTMask(filename: Path, metadata: SWIFTMetadata, *, safe_padding: bool | float = 0.1, handle: File | None = None, spatial_only: bool | None = None)[source]
Bases:
HandleProviderMain masking object. This can have masks for any present particle type in it.
For catalogues (e.g. SOAP) where all arrays are the same size there can be a “shared” mask that is stored once and used for all of them.
Takes the SWIFT metadata and enables individual property-by-property masking when reading from snapshots. When masking like this order-in-file is not preserved, i.e. the 7th particle may not be the 7th particle in the file.
- Parameters:
filename (Path) – File to read cell metadata from.
metadata (SWIFTMetadata) – Metadata loaded from snapshot.
safe_padding (bool or float, optional) – If snapshot does not specify bounding box of cell particles (
MinPositions,MaxPositions), pad the mask to gurantee that all particles in requested spatial region(s) are selected. If the bounding box metadata is present, this argument is ignored. The default (0.1) is to pad by 0.1 times the cell length. Padding can be disabled (False) or set to a different fraction of the cell length (e.g.0.5). Only entire cells are loaded, but if the region boundary is more thansafe_paddingfrom a cell boundary the neighbouring cell is not read. Switching off can reduce I/O load by up to a factor of 30 in some cases (but a few particles in region could be missing). See https://swiftsimio.readthedocs.io/en/latest/masking/index.html for further details.handle (h5py.File, optional) – The file handle to read metadata from.
spatial_only (bool, optional) – Deprecated, any necessary conversions handled automatically.
- filename: Path
- constrained: str | None
- property group_mapping: dict[str, str]
Create mapping between “group names” and their underlying cell metadata names.
Allows for aliases to be used instead of re-creating masks.
- Returns:
The dictionary of corresponding names.
- Return type:
dict[str, str]
- property group_size_mapping: dict[str, str]
Create mapping between “group names” and their underlying cell metadata names.
Allows for aliases to be used instead of re-creating masks.
- Returns:
The dictionary of corresponding names.
- Return type:
dict[str, str]
- property update_list: list[str]
Get list of internal mask variables that need updating when changing spatial mask.
- Returns:
List of the variable names that need updating.
- Return type:
list[str]
- constrain_mask(group_name: str, quantity: str, lower: cosmo_quantity, upper: cosmo_quantity) None[source]
Use
constrain_property()instead.This name is deprecated and will be removed in the future.
- Parameters:
group_name (str) – Particle type (e.g.
"gas").quantity (str) – Quantity being constrained (e.g.
"temperatures").lower (cosmo_quantity) – Constraint lower bound.
upper (cosmo_quantity) – Constraint upper bound.
- convert_masks_to_ranges() None[source]
Convert the masks to range masks.
These are more compact than boolean masks so they can help save space on highly constrained machines.
See also
- class swiftsimio.SWIFTStatisticsFile(filename: str)[source]
Bases:
objectSWIFT statistics files (e.g. SFR.txt, energy.txt) reader.
- Parameters:
filename (str) – File name for the statistics file.
- header_names: list[str]
- header_units: dict[str, unyt_quantity]
- header_snake_case_names: list[str]
- raw_lines: list[str]
- class swiftsimio.SWIFTUnits(filename: Path, handle: File | None = None)[source]
Bases:
HandleProviderGenerate a
unytsystem that can be used with SWIFT data.These give the unit mass, length, time, current, and temperature as unyt unit variables in simulation units. I.e. you can take any value that you get out of the code and multiply it by the appropriate values to get it ‘unyt-ified’ with the correct units.
- Parameters:
filename (Path) – Name of file to read units from.
handle (h5py.File, optional) – The h5py file handle, optional. Will open a new handle with the filename if required.
- mass: unyt_quantity
- length: unyt_quantity
- time: unyt_quantity
- current: unyt_quantity
- temperature: unyt_quantity
- class swiftsimio.SWIFTGroupMetadata(filename: Path, group: str, group_name: str, metadata: SWIFTMetadata, scale_factor: float, handle: File)[source]
Bases:
HandleProviderProvide the metadata for one hdf5 Group.
This, for instance, could be
PartType0, orgas. This will load in the names of all datasets, possible named fields, and present them for use in the actual i/o routines.- Parameters:
filename (Path) – Filename to read metadata from.
group (str) – The name of the group in the hdf5 file.
group_name (str) – The corresponding group name for swiftsimio.
metadata (SWIFTMetadata) – The snapshot metadata.
scale_factor (float) – The snapshot scale factor.
handle (h5py.File) – File handle to read metadata from.
- filename: Path
- class swiftsimio.SWIFTSnapshotMetadata(filename: Path, units: SWIFTUnits | None = None, handle: File | None = None)[source]
Bases:
SWIFTMetadataProvide a metadata interface for SWIFT snapshot files.
For more documentation see
SWIFTMetadata.- Parameters:
filename (Path) – Filename to read metadata from.
units (SWIFTUnits) – Units object to use.
handle (h5py.File, optional) – File handle to read from.
- masking_valid: bool = True
- get_named_column_metadata() None[source]
Load the custom named column metadata from SubgridScheme/NamedColumns.
If name column didn’t exist just set an empty
dictinstead.
- get_mapping_metadata() None[source]
Get the mappings based on the named columns (must have already been read).
From the form:
SubgridScheme/{X}To{Y}Mapping.
Includes a hack of Dust -> Grains that will be deprecated.
- property present_groups: list[str]
Get the groups containing datasets that are present in the file.
- Returns:
List of present groups.
- Return type:
list[str]
- property present_group_names: list[str]
Get the names of the groups that we want to expose.
- Returns:
List of names to expose.
- Return type:
list[str]
- property code_info: str
Get and format a nicely printed set of code information.
Formatting is as:
Name (Git Branch) Git Revision Git Date
- Returns:
The code information.
- Return type:
str
- property compiler_info: str
Get and format information about the compiler.
Formatting is as:
Compiler Name (Compiler Version) MPI library
- Returns:
The compiler information.
- Return type:
str
- property library_info: str
Get and format information about the libraries used.
Formatting is as:
FFTW vFFTW library version GSL vGSL library version HDF5 vHDF5 library version
- Returns:
The library information.
- Return type:
str
- property hydro_info: str
Get and format information about the hydro scheme.
Formatting is as:
Scheme Kernel function in DimensionD $eta$ = Kernel eta (Kernel target N_ngb $N_{ngb}$) $C_{rm CFL}$ = CFL parameter
- Returns:
Hydro scheme information.
- Return type:
str
- property viscosity_info: str
Get and format information about the viscosity scheme.
Formatting is as:
Viscosity Model $alpha_{V, 0}$ = Alpha viscosity, $ell_V$ = Viscosity decay length [internal units], $beta_V$ = Beta viscosity Alpha viscosity (min) < $alpha_V$ < Alpha viscosity (max)
- Returns:
Viscosity scheme information.
- Return type:
str
- property diffusion_info: str
Get and format information about the diffusion scheme.
Formatting is as:
$alpha_{D, 0}$ = Diffusion alpha, $beta_D$ = Diffusion beta Diffusion alpha (min) < $alpha_D$ < Diffusion alpha (max)
- Returns:
Formatted diffusion scheme information.
- Return type:
str
- property partial_snapshot: bool
Check if this is a partial (e.g. a “x.0.hdf5” file).
- Returns:
Trueif the file is a partial file, elseFalse.- Return type:
bool
- class swiftsimio.SWIFTLineOfSightMetadata(filename: Path, units: SWIFTUnits | None = None, handle: File | None = None)[source]
Bases:
SWIFTSnapshotMetadataProvide a metadata interface for SWIFT line-of-sight files.
For more documentation see
SWIFTMetadata.- Parameters:
filename (Path) – Filename to read metadata from.
units (SWIFTUnits) – Units object to use.
handle (h5py.File, optional) – File handle to read from.
- masking_valid: bool = False
- expose_group_attributes: bool = True
- property present_groups: list[str]
Get the groups containing datasets that are present in the file.
- Returns:
List of LOS groups.
- Return type:
list[str]
- property present_group_names: list[str]
Get the names of the groups that we want to expose.
- Returns:
List of names to expose as attributes.
- Return type:
list[str]
- static get_nice_name(group: str) str[source]
Convert the group name to a user-readable name.
- Parameters:
group (str) – The group name as used in the hdf5 file.
- Returns:
The user-readable version of the name.
- Return type:
str
- static get_group_attribute_units(name: str) Callable[[SWIFTUnits], Unit][source]
Get units for line-of-sight group attributes.
- Parameters:
name (str) – Public attribute name as exposed in swiftsimio.
- Returns:
Callable that maps a
SWIFTUnitsobject to the desired unit.- Return type:
Callable[[SWIFTUnits], unyt.Unit]
- static get_group_attribute_comoving(name: str) bool[source]
Get comoving-state metadata for line-of-sight group attributes.
- Parameters:
name (str) – Public attribute name as exposed in swiftsimio.
- Returns:
Trueif the value is stored in comoving units, elseFalse.- Return type:
bool
- get_group_attribute_cosmo_factor(name: str) cosmo_factor[source]
Get cosmological conversion metadata for LOS group attributes.
- Parameters:
name (str) – Public attribute name as exposed in swiftsimio.
scale_factor (float) – Scale factor of the snapshot.
- Returns:
Cosmological conversion factor.
- Return type:
- class swiftsimio.SWIFTFOFMetadata(filename: Path, units: SWIFTUnits | None = None, handle: File | None = None)[source]
Bases:
SWIFTMetadataProvide a metadata interface for FOF catalogue files.
For more documentation see
SWIFTMetadata.- Parameters:
filename (Path) – Filename to read metadata from.
units (SWIFTUnits) – Units object to use.
handle (h5py.File, optional) – File handle to read from.
- homogeneous_arrays: bool = True
- property present_groups: list[str]
The groups containing datasets that are present in the file.
- Returns:
List of available subhalo types.
- Return type:
list[str]
- property present_group_names: list[str]
Provide the names of the groups that we want to expose.
- Returns:
List of the available groups.
- Return type:
list[str]
- class swiftsimio.SWIFTSOAPMetadata(filename: Path, units: SWIFTUnits | None = None, handle: File | None = None)[source]
Bases:
SWIFTMetadataProvide a metadata interface for SOAP catalogue files.
For more documentation see
SWIFTMetadata.- Parameters:
filename (Path) – Filename to read metadata from.
units (SWIFTUnits) – Units object to use.
handle (h5py.File, optional) – File handle to read from.
- masking_valid: bool = True
- homogeneous_arrays: bool = True
- property present_groups: list[str]
The groups containing datasets that are present in the file.
- Returns:
List of available subhalo types.
- Return type:
list[str]
- property present_group_names: list[str]
Provide the names of the groups that we want to expose.
- Returns:
List of the available groups.
- Return type:
list[str]
- class swiftsimio.cosmo_array(input_array: Iterable, units: str | Unit | Unit | None = None, *, registry: UnitRegistry = None, dtype: dtype | str | None = None, bypass_validation: bool = False, name: str = None, cosmo_factor: cosmo_factor = None, scale_factor: float | None = None, scale_exponent: float | None = None, comoving: bool = None, valid_transform: bool = True, compression: str | None = None)[source]
Bases:
unyt_arrayCosmology array class.
This inherits from the
unyt_array, and adds four attributes:compression,cosmo_factor,comoving, andvalid_transform.Note
cosmo_arrayand the relatedcosmo_quantityare now intended to support allnumpyfunctions, propagating units (thanks tounyt) and cosmology information. There are a large number of functions, and a very large number of possible parameter combinations, so some corner cases may have been missed in testing. Please report any issues on github, they are usually easy to fix for future use! Currentlyscipyfunctions are not supported (although some might “just work”). Requests to fully support specific functions can also be submitted as github issues.- comoving
If
Truethen the array is in comoving coordinates, if``False`` then it is in physical units.- Type:
bool
- cosmo_factor
Object to store conversion data between comoving and physical coordinates.
- compression
String describing any compression that was applied to this array in the hdf5 file.
- Type:
str
- valid_transform
If
Truethen the array can be converted from physical to comoving units.- Type:
bool
See also
Notes
This class will generally try to make sense of input and initialize an array-like object consistent with the input, and warn or raise if this cannot be done consistently. However, the way that
unyt_arrayhandles input imposes some limits to this. In particular, nested non-numpy containers given in input are not traversed recursively, but only one level deep. This means that while with this input the attributes are detected by the new array correctly:>>> from swiftsimio.objects import cosmo_array, cosmo_factor >>> x = cosmo_array( ... np.arange(3), ... u.kpc, ... comoving=True, ... scale_factor=1.0, ... scale_exponent=1, ... ) >>> cosmo_array([x, x]) cosmo_array([[0, 1, 2], [0, 1, 2]], 'kpc', comoving='True', cosmo_factor='a at a=1.0', valid_transform='True')
with this input they are lost:
>>> cosmo_array([[x, x],[x, x]]) cosmo_array([[[0, 1, 2],[0, 1, 2]],[[0, 1, 2],[0, 1, 2]]], '(dimensionless)', comoving='None', cosmo_factor='None at a=None', valid_transform='True')
- astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
Copy of the array, cast to a specified type.
- Parameters:
dtype (str or dtype) – Typecode or data-type to which the array is cast.
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to the order the array elements appear in memory as possible. Default is ‘K’.
casting ({'no', 'equiv', 'safe', 'same_kind', 'same_value', 'unsafe'}, optional) –
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ means any data conversions may be done.
’same_value’ means any data conversions may be done, but the values must not change, including rounding of floats or overflow of ints
Added in version 2.4: Support for
'same_value'was added.subok (bool, optional) – If True, then sub-classes will be passed-through (default), otherwise the returned array will be forced to be a base-class array.
copy (bool, optional) – By default, astype always returns a newly allocated array. If this is set to false, and the dtype, order, and subok requirements are satisfied, the input array is returned instead of a copy.
- Returns:
arr_t – Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input parameter), arr_t is a new array of the same shape as the input array, with dtype, order given by dtype, order.
- Return type:
ndarray
- Raises:
ComplexWarning – When casting from complex to float or int. To avoid this, one should use
a.real.astype(t).ValueError – When casting using
'same_value'and the values change or would overflow
Examples
>>> import numpy as np >>> x = np.array([1, 2, 2.5]) >>> x array([1. , 2. , 2.5])
>>> x.astype(int) array([1, 2, 2])
>>> x.astype(int, casting="same_value") Traceback (most recent call last): ... ValueError: could not cast 'same_value' double to long
>>> x[:2].astype(int, casting="same_value") array([1, 2])
- in_units(*args: tuple[Any], **kwargs: dict[str, Any]) object
Creates a copy of this array with the data converted to the supplied units, and returns it.
Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
- Parameters:
units (Unit object or string) – The units you want to get a new quantity in.
equivalence (string, optional) – The equivalence you wish to use. To see which equivalencies are supported for this object, try the
list_equivalenciesmethod. Default: Nonekwargs (optional) – Any additional keyword arguments are supplied to the equivalence
- Raises:
If the provided unit does not have the same dimensions as the array –
this will raise a UnitConversionError –
Examples
>>> from unyt import c, gram >>> m = 10*gram >>> E = m*c**2 >>> print(E.in_units('erg')) 8.987551787368176e+21 erg >>> print(E.in_units('J')) 898755178736817.6 J
- byteswap(inplace=False)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.
- Parameters:
inplace (bool, optional) – If
True, swap bytes in-place, default isFalse.- Returns:
out – The byteswapped array. If inplace is
True, this is a view to self.- Return type:
ndarray
Examples
>>> import numpy as np >>> A = np.array([1, 256, 8755], dtype=np.int16) >>> list(map(hex, A)) ['0x1', '0x100', '0x2233'] >>> A.byteswap(inplace=True) array([ 256, 1, 13090], dtype=int16) >>> list(map(hex, A)) ['0x100', '0x1', '0x3322']
Arrays of byte-strings are not swapped
>>> A = np.array([b'ceg', b'fac']) >>> A.byteswap() array([b'ceg', b'fac'], dtype='|S3')
A.view(A.dtype.newbyteorder()).byteswap()produces an array with the same values but different representation in memory>>> A = np.array([1, 2, 3],dtype=np.int64) >>> A.view(np.uint8) array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0], dtype=uint8) >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True) array([1, 2, 3], dtype='>i8') >>> A.view(np.uint8) array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3], dtype=uint8)
- compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See also
numpy.compressequivalent function
- diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals. In NumPy 1.9 the returned array is a read-only view instead of a copy as in previous NumPy versions. In a future version the read-only restriction will be removed.
Refer to
numpy.diagonal()for full documentation.See also
numpy.diagonalequivalent function
- flatten(order='C')
Return a copy of the array collapsed into one dimension.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.
- Returns:
y – A copy of the input array, flattened to one dimension.
- Return type:
ndarray
See also
ravelReturn a flattened array.
flatA 1-D flat iterator over the array.
Examples
>>> import numpy as np >>> a = np.array([[1,2], [3,4]]) >>> a.flatten() array([1, 2, 3, 4]) >>> a.flatten('F') array([1, 3, 2, 4])
- ravel(order='C')
Return a flattened array.
Refer to numpy.ravel for full documentation.
See also
numpy.ravelequivalent function
ndarray.flata flat iterator on the array.
- repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See also
numpy.repeatequivalent function
- swapaxes(axis1, axis2, /)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See also
numpy.swapaxesequivalent function
- transpose(*axes)
Returns a view of the array with axes transposed.
Refer to numpy.transpose for full documentation.
- Parameters:
axes (None, tuple of ints, or n ints) –
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means that the array’s i-th axis becomes the transposed array’s j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form).
- Returns:
p – View of the array with its axes suitably permuted.
- Return type:
ndarray
See also
transposeEquivalent function.
ndarray.TArray property returning the array transposed.
ndarray.reshapeGive a new shape to an array without changing its data.
Examples
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.transpose() array([[1, 3], [2, 4]]) >>> a.transpose((1, 0)) array([[1, 3], [2, 4]]) >>> a.transpose(1, 0) array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.transpose() array([1, 2, 3, 4])
- view([dtype][, type])
New view of array with the same data.
Note
Passing None for
dtypeis different from omitting the parameter, since the former invokesdtype(None)which is an alias fordtype('float64').- Parameters:
dtype (data-type or ndarray sub-class, optional) – Data-type descriptor of the returned view, e.g., float32 or int16. Omitting it results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the
typeparameter).type (Python type, optional) – Type of the returned view, e.g., ndarray or matrix. Again, omission of the parameter results in type preservation.
Notes
a.view()is used two different ways:a.view(some_dtype)ora.view(dtype=some_dtype)constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.a.view(ndarray_subclass)ora.view(type=ndarray_subclass)just returns an instance of ndarray_subclass that looks at the same array (same shape, dtype, etc.) This does not cause a reinterpretation of the memory.For
a.view(some_dtype), ifsome_dtypehas a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the last axis ofamust be contiguous. This axis will be resized in the result.Changed in version 1.23.0: Only the last axis needs to be contiguous. Previously, the entire array had to be C-contiguous.
Examples
>>> import numpy as np >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
Viewing array data using a different type and dtype:
>>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)]) >>> y = x.view(dtype=nonneg, type=np.recarray) >>> x["a"] array([-1], dtype=int8) >>> y.a array([255], dtype=uint8)
Creating a view on a structured array so it can be used in calculations
>>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)]) >>> xv = x.view(dtype=np.int8).reshape(-1,2) >>> xv array([[1, 2], [3, 4]], dtype=int8) >>> xv.mean(0) array([2., 3.])
Making changes to the view changes the underlying array
>>> xv[0,1] = 20 >>> x array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
Using a view to convert an array to a recarray:
>>> z = x.view(np.recarray) >>> z.a array([1, 3], dtype=int8)
Views share data:
>>> x[0] = (9, 10) >>> z[0] np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16) >>> y = x[:, ::2] >>> y array([[1, 3], [4, 6]], dtype=int16) >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) Traceback (most recent call last): ... ValueError: To change to a dtype of a different size, the last axis must be contiguous >>> z = y.copy() >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) array([[(1, 3)], [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
However, views that change dtype are totally fine for arrays with a contiguous last axis, even if the rest of the axes are not C-contiguous:
>>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4) >>> x.transpose(1, 0, 2).view(np.int16) array([[[ 256, 770], [3340, 3854]], [[1284, 1798], [4368, 4882]], [[2312, 2826], [5396, 5910]]], dtype=int16)
- copy(*args: tuple[Any], **kwargs: dict[str, Any]) object
Return a copy of the array.
- Parameters:
order ({'C', 'F', 'A', 'K'}, optional) – Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and
numpy.copy()are very similar, but have different default values for their order= arguments.)
See also
Examples
>>> from unyt import km >>> x = [[1,2,3],[4,5,6]] * km >>> y = x.copy() >>> x.fill(0) >>> print(x) [[0 0 0] [0 0 0]] km
>>> print(y) [[1 2 3] [4 5 6]] km
- in_cgs(*args: tuple[Any], **kwargs: dict[str, Any]) object
Creates a copy of this array with the data in the equivalent cgs units, and returns it.
- Return type:
unyt_array object with data in this array converted to cgs units.
Example
>>> from unyt import Newton, km >>> print((10*Newton/km).in_cgs()) 10.0 g/s**2
- in_base(*args: tuple[Any], **kwargs: dict[str, Any]) object
Creates a copy of this array with the data in the specified unit system, and returns it in that system’s base units.
- Parameters:
unit_system (string, optional) – The unit system to be used in the conversion. If not specified, the configured default base units of are used (defaults to MKS).
Examples
>>> from unyt import erg, s >>> E = 2.5*erg/s >>> print(E.in_base("mks")) 2.5e-07 W
- take(*args: tuple[Any], **kwargs: dict[str, Any]) object
method
Return an array formed from the elements of a at the given indices.
Refer to
numpy.take()for full documentation.See also
numpy.takeequivalent function
- reshape(shape, /, *, order='C', copy=None)
- reshape(*shape, order='C', copy=None)
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See also
numpy.reshapeequivalent function
Notes
Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example,
a.reshape(4, 2)is equivalent toa.reshape((4, 2)).
- dot(**kwargs: dict[str, Any]) Callable
Prepare arguments, handle
cosmo_factorattributes, and attach attributes.- Parameters:
*args (tuple[Any]) – Arbitrary arguments of the wrapped function.
**kwargs (dict[str, Any]) – Arbitrary kwargs of the wrapped function.
- Returns:
The wrapped function.
- Return type:
Callable
- squeeze(axis=None)
Remove axes of length one from a.
Refer to numpy.squeeze for full documentation.
See also
numpy.squeezeequivalent function
- property T: object
View of the transposed array.
Same as
self.transpose().Examples
>>> import numpy as np >>> a = np.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> a.T array([[1, 3], [2, 4]])
>>> a = np.array([1, 2, 3, 4]) >>> a array([1, 2, 3, 4]) >>> a.T array([1, 2, 3, 4])
See also
- property ua: object
Return an array filled with ones with the same units as this array
Example
>>> from unyt import km >>> a = [4, 5, 6]*km >>> a.unit_array unyt_array([1, 1, 1], 'km') >>> print(a + 7*a.unit_array) [11 12 13] km
- property unit_array: object
Return an array filled with ones with the same units as this array
Example
>>> from unyt import km >>> a = [4, 5, 6]*km >>> a.unit_array unyt_array([1, 1, 1], 'km') >>> print(a + 7*a.unit_array) [11 12 13] km
- convert_to_comoving(units: Unit | str | None = None, *, equivalence: str | None = None, **kwargs: dict[str, Any]) None[source]
Convert the internal data in-place to be in comoving units.
Optionaly, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
- Parameters:
units (Unit or str, optional) – The desired units for the converted array. If omitted the units are preserved.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
This array in the requested comoving units, transformed in place.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- convert_to_physical(units: Unit | str | None = None, *, equivalence: str | None = None, **kwargs: dict[str, Any]) None[source]
Convert the internal data in-place to be in physical units.
Optionaly, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
- Parameters:
units (Unit or str, optional) – The desired units for the converted array. If omitted the units are preserved.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
This array in the requested physical units, transformed in place.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- to_physical(units: Unit | str | None = None, *, equivalence: str | None = None, **kwargs: dict[str, Any]) cosmo_array[source]
Create a copy of the data in physical units.
- Parameters:
units (Unit or str, optional) – The desired units for the new array. If omitted the units are preserved.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of this array in the requested physical units.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- to_comoving(units: Unit | str | None = None, *, equivalence: str | None = None, **kwargs: dict[str, Any]) cosmo_array[source]
Create a copy of the data in comoving units.
- Parameters:
units (Unit or str, optional) – The desired units for the new array. If omitted the units are preserved.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of this array in the requested comoving units.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- to(units: Unit | str | None = None, *, equivalence: str | None = None, comoving: bool | None = None, **kwargs: dict[str, Any]) cosmo_array[source]
Create a copy of the data in specified comoving or physical units.
Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
Note
All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them.
- Parameters:
units (Unit or str, optional) – The desired units for the new array.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.comoving (bool, optional) – If
True, the result is comoving, ifFalseit is physical. By default thecomovingstatus of the array is preserved.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of this array in comoving or physical units.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
Examples
>>> import unyt as u >>> d = cosmo_quantity( ... 1, ... u.Mpc, ... comoving=True, ... scale_factor=0.5, ... scale_exponent=1 ... ) >>> d.to(u.kpc, comoving=False) cosmo_quantity(500., 'kpc', comoving='False', cosmo_factor='a at a=0.5', valid_transform='True')
- to_value(units: Unit | str | None = None, *, equivalence: str | None = None, comoving: bool | None = None, **kwargs: dict[str, Any]) ndarray[source]
Create a copy of the data in specified comoving or physical units.
The copy is then returned with the values as a bare
numpyarray.Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
Note
All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them.
- Parameters:
units (Unit or str) – The desired units for the new array.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.comoving (bool, optional) – If
True, the result is comoving, ifFalseit is physical. By default thecomovingstatus of the array is preserved.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of this array in comoving or physical units.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
Examples
>>> import unyt as u >>> d = cosmo_quantity( ... 1, ... u.Mpc, ... comoving=True, ... scale_factor=0.5, ... scale_exponent=1 ... ) >>> d.to_value(u.kpc, comoving=False) 500.0
- to_physical_value(units: Unit | str, equivalence: str | None = None, **kwargs: dict[str, Any]) ndarray[source]
Return a copy of the array values in the specified physical units.
Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
Note
All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them.
- Parameters:
units (Unit or str) – The desired units for the new array.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of the array values in the specified physical units.
- Return type:
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- to_comoving_value(units: Unit | str, equivalence: str | None = None, **kwargs: dict[str, Any]) ndarray[source]
Return a copy of the array values in the specified comoving units.
Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.
Note
All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them.
- Parameters:
units (Unit or str) – The desired units for the new array.
equivalence (str, optional) – The equivalence to use. To see which equivalences are supported for this quantity, try the
list_equivalencies()method.**kwargs (dict) – Any additional keyword arguments are supplied to the equivalence.
- Returns:
Copy of the array values in the specified comoving units.
- Return type:
np.ndarray
- Raises:
UnitConversionError – If the provided
unitsdoes not have the same dimensions as the array and cannot be converted via a providedequivalence.
- compatible_with_comoving() bool[source]
Check whether array is compatible with comoving units.
This is the case if the
cosmo_arrayis comoving, or if the scale factor exponent is 0, or the scale factor is 1 (either case satisfiescosmo_factor.a_factor() == 1).- Returns:
Trueif compatible,Falseotherwise.- Return type:
bool
- compatible_with_physical() bool[source]
Check whether array is compatible with physical units.
This is the case if the
cosmo_arrayis physical, or if the scale factor exponent is 0, or the scale factor is 1 (either case satisfiescosmo_factor.a_factor() == 1).- Returns:
Trueif compatible,Falseotherwise.- Return type:
bool
- classmethod from_astropy(arr: Quantity, unit_registry: UnitRegistry = None, comoving: bool = None, cosmo_factor: cosmo_factor = cosmo_factor(expr=None, scale_factor=None), compression: str = None, valid_transform: bool = True) cosmo_array[source]
Convert
astropyarrays to our cosmology array class.Convert an
astropy.units.quantity.Quantityto acosmo_array.- Parameters:
arr (astropy.units.quantity.Quantity) – The quantity to convert from.
unit_registry (unyt.unit_registry.UnitRegistry, optional) – A unyt registry to use in the conversion. If one is not supplied, the default one will be used.
comoving (bool) – Flag to indicate whether using comoving coordinates.
cosmo_factor (swiftsimio.objects.cosmo_factor) – Object to store conversion data between comoving and physical coordinates.
compression (str) – Description of the compression filters that were applied to that array in the hdf5 file.
valid_transform (bool) – Flag to indicate whether this array can be converted to comoving. If
False, thencomovingmust beFalse(orNone).
- Returns:
A cosmology-aware array.
- Return type:
Examples
>>> from astropy.units import kpc >>> cosmo_array.from_astropy([1, 2, 3] * kpc) cosmo_array([1., 2., 3.], 'kpc')
- classmethod from_pint(arr: pint.registry.Quantity, unit_registry: UnitRegistry = None, comoving: bool = None, cosmo_factor: cosmo_factor = cosmo_factor(expr=None, scale_factor=None), compression: str = None, valid_transform: bool = True) cosmo_array[source]
Convert
pintarrays to our cosmology array class.Convert a
pint.registry.Quantityto acosmo_array.- Parameters:
arr (pint.registry.Quantity) – The quantity to convert from.
unit_registry (unyt.unit_registry.UnitRegistry, optional) – A unyt registry to use in the conversion. If one is not supplied, the default one will be used.
comoving (bool) – Flag to indicate whether using comoving coordinates.
cosmo_factor (swiftsimio.objects.cosmo_factor) – Object to store conversion data between comoving and physical coordinates.
compression (str) – Description of the compression filters that were applied to that array in the hdf5 file.
valid_transform (bool) – Flag to indicate whether this array can be converted to comoving. If
False, thencomovingmust beFalse(orNone).
- Returns:
A cosmology-aware array.
- Return type:
Examples
>>> from pint import UnitRegistry >>> import numpy as np >>> ureg = UnitRegistry() >>> a = np.arange(4) >>> b = ureg.Quantity(a, "erg/cm**3") >>> b <Quantity([0 1 2 3], 'erg / centimeter ** 3')> >>> c = cosmo_array.from_pint(b) >>> c cosmo_array([0, 1, 2, 3], 'erg/cm**3')
- class swiftsimio.cosmo_quantity(input_scalar: Number, units: str | Unit | Unit | None = None, registry: UnitRegistry | None = None, dtype: dtype | str | None = None, bypass_validation: bool = False, name: str | None = None, cosmo_factor: cosmo_factor | None = None, scale_factor: float | None = None, scale_exponent: float | None = None, comoving: bool | None = None, valid_transform: bool = True, compression: str | None = None)[source]
Bases:
cosmo_array,unyt_quantityCosmology scalar class.
This inherits from both the
cosmo_arrayand theunyt_quantity, and has the same four attributes ascosmo_array:compression,cosmo_factor,comoving, andvalid_transform.Like
unyt.array.unyt_quantity, it is intended to hold a scalar value. Values of this type will be returned bynumpyfunctions that return scalar values.Other than containing a scalar, functionality is identical to
cosmo_array. Refer to that class’s documentation.- comoving
if True then the array is in comoving co-ordinates, and if False then it is in physical units.
- Type:
bool
- cosmo_factor
Object to store conversion data between comoving and physical coordinates
- Type:
float
- compression
String describing any compression that was applied to this array in the hdf5 file.
- Type:
str
- valid_transform
if True then the array can be converted from physical to comoving units
- Type:
bool
- swiftsimio.validate_file(filename: str) bool[source]
Check that the provided file is a SWIFT dataset.
- Parameters:
filename (str) – Name of file we want to check is a dataset.
- Returns:
If
filenameis a SWIFT dataset returnTrue, otherwise raise exception.- Return type:
bool
- Raises:
KeyError – If the file is not a SWIFT data file.
- swiftsimio.mask(filename: str | Path, safe_padding: bool | float = True, spatial_only: bool | None = None) SWIFTMask[source]
Set up a mask to apply to a
swiftsimiodataset.Also makes the dataset’s units and metadata available.
- Parameters:
filename (str or Path) – SWIFT data file to read from. Can also be an open h5py.File handle.
safe_padding (bool or float, optional) – If snapshot does not specify bounding box of cell particles (MinPositions & MaxPositions), pad the mask to gurantee that all particles in requested spatial region(s) are selected. If the bounding box metadata is present, this argument is ignored. The default (
True) is to pad by one cell length. Padding can be disabled (False) or set to a different fraction of the cell length (e.g.0.2). Only entire cells are loaded, but if the region boundary is more thansafe_paddingfrom a cell boundary the neighbouring cell is not read. Switching off can reduce I/O load by up to a factor of 10 in some cases (but a few particles in region could be missing). See https://swiftsimio.readthedocs.io/en/latest/masking/index.html for further details.spatial_only (bool, optional) – Deprecated, any necessary conversions now happen automatically.
- Returns:
Empty mask object set up with the correct units and metadata.
- Return type:
- swiftsimio.load(filename: str | Path, mask: SWIFTMask | None = None) SWIFTDataset[source]
Load a SWIFT dataset (snapshot, FOF or SOAP catalogue).
- Parameters:
filename (str or Path) – SWIFT data file to read from.
mask (SWIFTMask, optional) – Mask to apply when reading dataset.
- Returns:
Dataset object providing an interface to the data file.
- Return type:
- swiftsimio.load_statistics(filename: str | Path) SWIFTStatisticsFile[source]
Load a SWIFT statistics file (
SFR.txt,energy.txt).- Parameters:
filename (str or Path) – SWIFT statistics file path.
Subpackages
- swiftsimio.visualisation package
project_gas()project_pixel_grid()slice_gas()render_gas()generate_smoothing_lengths()- Subpackages
- swiftsimio.visualisation.projection_backends package
- Submodules
- swiftsimio.visualisation.projection_backends.fast module
- swiftsimio.visualisation.projection_backends.gpu module
- swiftsimio.visualisation.projection_backends.histogram module
- swiftsimio.visualisation.projection_backends.kernels module
- swiftsimio.visualisation.projection_backends.reference module
- swiftsimio.visualisation.projection_backends.renormalised module
- swiftsimio.visualisation.projection_backends.subsampled module
- swiftsimio.visualisation.projection_backends.subsampled_extreme module
- Submodules
- swiftsimio.visualisation.slice_backends package
- swiftsimio.visualisation.smoothing_length package
- swiftsimio.visualisation.tools package
- swiftsimio.visualisation.volume_render_backends package
- swiftsimio.visualisation.projection_backends package
- Submodules
Submodules
- swiftsimio.accelerated module
- swiftsimio.conversions module
- swiftsimio.masks module
SWIFTMaskSWIFTMask.filenameSWIFTMask.constrainedSWIFTMask.group_mappingSWIFTMask.group_size_mappingSWIFTMask.update_listSWIFTMask.constrain_mask()SWIFTMask.constrain_property()SWIFTMask.constrain_spatial()SWIFTMask.convert_masks_to_ranges()SWIFTMask.convert_masks_to_bool()SWIFTMask.constrain_index()SWIFTMask.constrain_indices()
- swiftsimio.objects module
InvalidConversionErrorInvalidScaleFactorInvalidSnapshotcosmo_factorcosmo_arraycosmo_array.comovingcosmo_array.cosmo_factorcosmo_array.compressioncosmo_array.valid_transformcosmo_array.astype()cosmo_array.in_units()cosmo_array.byteswap()cosmo_array.compress()cosmo_array.diagonal()cosmo_array.flatten()cosmo_array.ravel()cosmo_array.repeat()cosmo_array.swapaxes()cosmo_array.transpose()cosmo_array.view()cosmo_array.copy()cosmo_array.in_cgs()cosmo_array.in_base()cosmo_array.take()cosmo_array.reshape()cosmo_array.dot()cosmo_array.squeeze()cosmo_array.Tcosmo_array.uacosmo_array.unit_arraycosmo_array.convert_to_comoving()cosmo_array.convert_to_physical()cosmo_array.to_physical()cosmo_array.to_comoving()cosmo_array.to()cosmo_array.to_value()cosmo_array.to_physical_value()cosmo_array.to_comoving_value()cosmo_array.compatible_with_comoving()cosmo_array.compatible_with_physical()cosmo_array.from_astropy()cosmo_array.from_pint()
cosmo_quantity
- swiftsimio.optional_packages module
- swiftsimio.reader module
- swiftsimio.snapshot_writer module
- swiftsimio.statistics module
- swiftsimio.subset_writer module
- swiftsimio.swiftsnap module