swiftsimio.objects module

Contains global objects, e.g. the superclass version of the unyt_array that we use, called cosmo_array.

exception swiftsimio.objects.InvalidScaleFactor(message=None, *args)[source]

Bases: Exception

Raised when a scale factor is invalid, such as when adding two cosmo_factors with inconsistent scale factors.

class swiftsimio.objects.cosmo_factor(expr, scale_factor)[source]

Bases: object

Cosmology 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 factor a.

This should be given as the conversion from comoving to physical, i.e.

r = cosmo_factor * r’ with r in physical and r’ comoving

Examples

Typically this would make cosmo_factor = a for the conversion between comoving positions r’ and physical co-ordinates r.

To do this, use the a imported from objects multiplied as you’d like:

density_cosmo_factor = cosmo_factor(a**3, scale_factor=0.97)

property a_factor

The a-factor for the unit.

e.g. for density this is 1 / a**3.

Returns:

the a-factor for given unit

Return type:

float

property redshift

Compute the redshift from the scale factor.

Returns:

redshift from the given scale factor

Return type:

float

Notes

Returns the redshift ..math:: z = frac{1}{a} - 1, where :math: a is the scale factor

class swiftsimio.objects.cosmo_array(input_array, units=None, registry=None, dtype=None, bypass_validation=False, input_units=None, name=None, cosmo_factor=None, comoving=True, compression=None)[source]

Bases: unyt_array

Cosmology array class.

This inherits from the unyt.unyt_array, and adds three variables: compression, cosmo_factor, and comoving. Data is assumed to be comoving when passed to the object but you can override this by setting the latter flag to be False.

Parameters:

unyt_array (unyt.unyt_array) – the inherited unyt_array

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:

string

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', '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.

  • 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

Notes

Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not.

Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the max integer/float value converted.

Raises:

ComplexWarning – When casting from complex to float or int. To avoid this, one should use a.real.astype(t).

Examples

>>> x = np.array([1, 2, 2.5])
>>> x
array([1. ,  2. ,  2.5])
>>> x.astype(int)
array([1, 2, 2])
in_units(*args, **kwargs)

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_equivalencies method. Default: None

  • kwargs (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 is False.

Returns:

out – The byteswapped array. If inplace is True, this is a view to self.

Return type:

ndarray

Examples

>>> 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.newbyteorder().byteswap() produces an array with the same values

but different representation in memory

>>> A = np.array([1, 2, 3])
>>> 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.newbyteorder().byteswap(inplace=True)
array([1, 2, 3])
>>> 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.compress

equivalent 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.diagonal

equivalent 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

ravel

Return a flattened array.

flat

A 1-D flat iterator over the array.

Examples

>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
newbyteorder(new_order='S', /)

Return the array with the same data viewed with a different byte order.

Equivalent to:

arr.view(arr.dtype.newbytorder(new_order))

Changes are also made in all fields and sub-arrays of the array data type.

Parameters:

new_order (string, optional) –

Byte order to force; a value from the byte order specifications below. new_order codes can be any of:

  • ’S’ - swap dtype from current to opposite endian

  • {‘<’, ‘little’} - little endian

  • {‘>’, ‘big’} - big endian

  • {‘=’, ‘native’} - native order, equivalent to sys.byteorder

  • {‘|’, ‘I’} - ignore (no change to byte order)

The default value (‘S’) results in swapping the current byte order.

Returns:

new_arr – New array object with the dtype reflecting given change to the byte order.

Return type:

array

ravel([order])

Return a flattened array.

Refer to numpy.ravel for full documentation.

See also

numpy.ravel

equivalent function

ndarray.flat

a flat iterator on the array.

repeat(repeats, axis=None)

Repeat elements of an array.

Refer to numpy.repeat for full documentation.

See also

numpy.repeat

equivalent function

reshape(shape, order='C')

Returns an array containing the same data with a new shape.

Refer to numpy.reshape for full documentation.

See also

numpy.reshape

equivalent 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(10, 11) is equivalent to a.reshape((10, 11)).

swapaxes(axis1, axis2)

Return a view of the array with axis1 and axis2 interchanged.

Refer to numpy.swapaxes for full documentation.

See also

numpy.swapaxes

equivalent function

take(indices, axis=None, out=None, mode='raise')

Return an array formed from the elements of a at the given indices.

Refer to numpy.take for full documentation.

See also

numpy.take

equivalent 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

transpose

Equivalent function.

ndarray.T

Array property returning the array transposed.

ndarray.reshape

Give a new shape to an array without changing its data.

Examples

>>> 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 dtype is different from omitting the parameter, since the former invokes dtype(None) which is an alias for dtype('float_').

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 type parameter).

  • 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) or a.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) or a.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), if some_dtype has 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 of a must 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

>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])

Viewing array data using a different type and dtype:

>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print(type(y))
<class 'numpy.matrix'>

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]
(9, 10)

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)
property T

View of the transposed array.

Same as self.transpose().

Examples

>>> 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

transpose

property ua

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

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() None[source]

Convert the internal data to be in comoving units.

convert_to_physical() None[source]

Convert the internal data to be in physical units.

to_physical()[source]

Creates a copy of the data in physical units.

Returns:

copy of cosmo_array in physical units

Return type:

cosmo_array

to_comoving()[source]

Creates a copy of the data in comoving units.

Returns:

copy of cosmo_array in comoving units

Return type:

cosmo_array

compatible_with_comoving()[source]

Is this cosmo_array compatible with a comoving cosmo_array?

This is the case if the cosmo_array is comoving, or if the scale factor exponent is 0 (cosmo_factor.a_factor() == 1)

compatible_with_physical()[source]

Is this cosmo_array compatible with a physical cosmo_array?

This is the case if the cosmo_array is physical, or if the scale factor exponent is 0 (cosmo_factor.a_factor == 1)

classmethod from_astropy(arr, unit_registry=None, comoving=True, cosmo_factor=None, compression=None)[source]

Convert an AstroPy “Quantity” to a cosmo_array.

Parameters:
  • arr (AstroPy Quantity) – The Quantity to convert from.

  • unit_registry (yt UnitRegistry, optional) – A yt unit registry to use in the conversion. If one is not supplied, the default one will be used.

  • comoving (bool) – if True then the array is in comoving co-ordinates, and if False then it is in physical units.

  • cosmo_factor (float) – Object to store conversion data between comoving and physical coordinates

  • compression (string) – String describing any compression that was applied to this array in the hdf5 file.

Example

>>> from astropy.units import kpc
>>> cosmo_array.from_astropy([1, 2, 3] * kpc)
cosmo_array([1., 2., 3.], 'kpc')
classmethod from_pint(arr, unit_registry=None, comoving=True, cosmo_factor=None, compression=None)[source]

Convert a Pint “Quantity” to a cosmo_array.

Parameters:
  • arr (Pint Quantity) – The Quantity to convert from.

  • unit_registry (yt UnitRegistry, optional) – A yt unit registry to use in the conversion. If one is not supplied, the default one will be used.

  • comoving (bool) – if True then the array is in comoving co-ordinates, and if False then it is in physical units.

  • cosmo_factor (float) – Object to store conversion data between comoving and physical coordinates

  • compression (string) – String describing any compression that was applied to this array in the hdf5 file.

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')