swiftsimio.objects module
Definitions of our custom cosmology array and quantity classes.
Defines cosmo_array,
cosmo_quantity and
cosmo_factor objects for cosmology-aware
arrays, extending the functionality of the unyt_array.
For developers, see also swiftsimio._array_functions containing
helpers, wrappers and implementations that enable most numpy and
unyt functions to work with our cosmology-aware arrays.
- exception swiftsimio.objects.InvalidConversionError(message: str = 'Could not convert to comoving coordinates.')[source]
Bases:
ExceptionRaise when attempting comoving/physical conversion when not allowed.
- Parameters:
message (str, optional) – Message to print in case of invalid conversion.
- exception swiftsimio.objects.InvalidScaleFactor(message: str = None, *args: tuple[Any])[source]
Bases:
ExceptionRaised when a scale factor is invalid.
For example, when adding two
cosmo_factorobjects with inconsistent scale factors.- Parameters:
message (str, optional) – Message to print in case of invalid scale factor.
*args (tuple[Any]) – Arbitrary arguments.
- exception swiftsimio.objects.InvalidSnapshot(message: str = None, *args: tuple[Any])[source]
Bases:
ExceptionGenerated when a snapshot is invalid.
For example, trying to partially load a sub-snapshot.
- Parameters:
message (str, optional) – Message to print in case of invalid snapshot.
*args (tuple[Any]) – Arbitrary arguments.
- class swiftsimio.objects.cosmo_factor(expr: Expr, scale_factor: float)[source]
Bases:
objectCosmology factor class.
For storing and computing conversion between comoving and physical coordinates.
This takes the expected exponent of the array that can be parsed by
sympy, and the current value of the cosmological scale factora.This should be given as the conversion from comoving to physical, i.e. \(r = a^f \times r\) where \(a\) is the scale factor, \(r\) is a physical quantity and :math`r’` a comoving quantity.
- Parameters:
expr (sympy.Expr) – Expression used to convert between comoving and physical coordinates.
scale_factor (float) – The scale factor (a).
- expr
Expression used to convert between comoving and physical coordinates.
- Type:
sympy.Expr
- scale_factor
The scale factor (a).
- Type:
float
Examples
Mass density transforms as \(a^3\). To set up a
cosmo_factor, supposing a currentscale_factor=0.97, we import the scale factoraand initialize as:from swiftsimio.objects import a # the scale factor (a sympy symbol object) density_cosmo_factor = cosmo_factor(a**3, scale_factor=0.97)
cosmo_factorsupports arithmetic, for example:>>> cosmo_factor(a**2, scale_factor=0.5) * cosmo_factor(a**-1, scale_factor=0.5) cosmo_factor(expr=a, scale_factor=0.5)
- classmethod create(scale_factor: float, exponent: Number) cosmo_factor[source]
Create
cosmo_factorfrom scale factor and exponent.- Parameters:
scale_factor (
float) – The scale factor.exponent (
intorfloat) – The exponent defining the scaling with the scale factor.
Examples
>>> cosmo_factor.create(0.5, 2) cosmo_factor(expr=a**2, scale_factor=0.5)
- property a_factor: float
The multiplicative factor for conversion from comoving to physical.
For example, for density this is \(a^{-3}\).
- Returns:
The multiplicative factor for conversion from comoving to physical.
- Return type:
float
- property redshift: float
The redshift computed from the scale factor.
Returns the redshift \(z = \\frac{1}{a} - 1\), where \(a\) is the scale factor.
- Returns:
The redshift.
- Return type:
float
- class swiftsimio.objects.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.objects.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