unyt.array module

unyt_array class.

class unyt.array.unyt_array(input_array, units=None, registry=None, dtype=None, *, bypass_validation=False, name=None)[source]

Bases: ndarray

An ndarray subclass that attaches a symbolic unit object to the array data.

Parameters:
  • input_array (iterable) – A tuple, list, or array to attach units to

  • units (String unit name, unit symbol object, or astropy unit) – The units of the array. Powers must be specified using python syntax (cm**3, not cm^3).

  • registry (unyt.unit_registry.UnitRegistry) – The registry to create units from. If units is already associated with a unit registry and this is specified, this will be used instead of the registry associated with the unit object.

  • dtype (numpy dtype or dtype name) – The dtype of the array data. Defaults to the dtype of the input data, or, if none is found, uses np.float64

  • bypass_validation (boolean) – If True, all input validation is skipped. Using this option may produce corrupted, invalid units or array data, but can lead to significant speedups in the input validation logic adds significant overhead. If set, units must be a valid unit object. Defaults to False.

  • name (string) – The name of the array. Defaults to None. This attribute does not propagate through mathematical operations, but is preserved under indexing and unit conversions.

Examples

>>> from unyt import unyt_array
>>> a = unyt_array([1, 2, 3], 'cm')
>>> b = unyt_array([4, 5, 6], 'm')
>>> a + b
unyt_array([401., 502., 603.], 'cm')
>>> b + a
unyt_array([4.01, 5.02, 6.03], 'm')

NumPy ufuncs will pass through units where appropriate.

>>> from unyt import g, cm
>>> import numpy as np
>>> a = (np.arange(8) - 4)*g/cm**3
>>> np.abs(a)
unyt_array([4, 3, 2, 1, 0, 1, 2, 3], 'g/cm**3')

and strip them when it would be annoying to deal with them.

>>> np.log10(np.arange(8)+1)
array([0.        , 0.30103   , 0.47712125, 0.60205999, 0.69897   ,
       0.77815125, 0.84509804, 0.90308999])
convert_to_units(units, equivalence=None, **kwargs)[source]

Convert the array to the given units in-place.

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 convert to.

  • 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 cm, km
>>> length = [3000, 2000, 1000]*cm
>>> length.convert_to_units('m')
>>> print(length)
[30. 20. 10.] m
convert_to_base(unit_system=None, equivalence=None, **kwargs)[source]

Convert the array in-place to the equivalent base units in the specified unit system.

Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.

Parameters:
  • unit_system (string, optional) – The unit system to be used in the conversion. If not specified, the configured base units are used (defaults to MKS).

  • 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 erg, s
>>> E = 2.5*erg/s
>>> E.convert_to_base("mks")
>>> E
unyt_quantity(2.5e-07, 'W')
convert_to_cgs(equivalence=None, **kwargs)[source]

Convert the array and in-place to the equivalent cgs units.

Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.

Parameters:
  • 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 Newton
>>> data = [1., 2., 3.]*Newton
>>> data.convert_to_cgs()
>>> data
unyt_array([100000., 200000., 300000.], 'dyn')
convert_to_mks(equivalence=None, **kwargs)[source]

Convert the array and units to the equivalent mks units.

Optionally, an equivalence can be specified to convert to an equivalent quantity which is not in the same dimensions.

Parameters:
  • 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 dyne, erg
>>> data = [1., 2., 3.]*erg
>>> data
unyt_array([1., 2., 3.], 'erg')
>>> data.convert_to_mks()
>>> data
unyt_array([1.e-07, 2.e-07, 3.e-07], 'J')
in_units(units, equivalence=None, **kwargs)[source]

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
to(units, equivalence=None, **kwargs)[source]

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.

Note

All additional keyword arguments are passed to the equivalency, which should be used if that particular equivalency requires them.

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 unitful quantity, try the list_equivalencies() method. Default: None

  • kwargs (optional) – Any additional keywoard 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.to('erg'))
8.987551787368176e+21 erg
>>> print(E.to('J'))
898755178736817.6 J
to_value(units=None, equivalence=None, **kwargs)[source]

Creates a copy of this array with the data in the supplied units, and returns it without units. Output is therefore a bare NumPy array.

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 object or string, optional) – The units you want to get the bare quantity in. If not specified, the value will be returned in the current units.

  • equivalence (string, optional) – The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the list_equivalencies() method. Default: None

Examples

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> print(a.to_value('cm'))
[300000. 400000. 500000.]
in_base(unit_system=None)[source]

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

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

Creates a copy of this array with the data in the equivalent mks units, and returns it.

Return type:

unyt_array object with data in this array converted to mks units.

Example

>>> from unyt import mile
>>> print((1.*mile).in_mks())
1609.344 m
convert_to_equivalent(unit, equivalence, **kwargs)[source]

Convert the array in-place to the specified units, assuming the given equivalency. The dimensions of the specified units and the dimensions of the original array need not match so long as there is an appropriate conversion in the specified equivalency.

Parameters:
  • unit (string) – The unit that you wish to convert to.

  • equivalence (string) – The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the list_equivalencies() method.

Examples

>>> from unyt import K
>>> a = [10, 20, 30]*(1e7*K)
>>> a.convert_to_equivalent("keV", "thermal")
>>> a
unyt_array([ 8.6173324, 17.2346648, 25.8519972], 'keV')
to_equivalent(unit, equivalence, **kwargs)[source]

Return a copy of the unyt_array in the units specified units, assuming the given equivalency. The dimensions of the specified units and the dimensions of the original array need not match so long as there is an appropriate conversion in the specified equivalency.

Parameters:
  • unit (string) – The unit that you wish to convert to.

  • equivalence (string) – The equivalence you wish to use. To see which equivalencies are supported for this unitful quantity, try the list_equivalencies() method.

Examples

>>> from unyt import K
>>> a = 1.0e7*K
>>> print(a.to_equivalent("keV", "thermal"))
0.8617332401096504 keV
list_equivalencies()[source]

Lists the possible equivalencies associated with this unyt_array or unyt_quantity.

Example

>>> from unyt import km
>>> (1.0*km).list_equivalencies()
spectral: length <-> spatial_frequency <-> frequency <-> energy
schwarzschild: mass <-> length
compton: mass <-> length
has_equivalent(equivalence)[source]

Check to see if this unyt_array or unyt_quantity has an equivalent unit in equiv.

Example

>>> from unyt import km, keV
>>> (1.0*km).has_equivalent('spectral')
True
>>> print((1*km).to_equivalent('MHz', equivalence='spectral'))
0.299792458 MHz
>>> print((1*keV).to_equivalent('angstrom', equivalence='spectral'))
12.39841931521966 Å
ndarray_view()[source]

Returns a view into the array as a numpy array

Return type:

View of this array’s data.

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> a.ndarray_view()
array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b = a.ndarray_view()
>>> b.base is a.base
True
>>> b[2] = 4
>>> b
array([3, 4, 4])
>>> a
unyt_array([3, 4, 4], 'km')
to_ndarray()[source]

Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> b = a.to_ndarray()
>>> b
array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base
True
argsort(axis=-1, kind='quicksort', order=None)[source]

Returns the indices that would sort the array.

See the documentation of ndarray.argsort for details about the keyword arguments.

Example

>>> from unyt import km
>>> data = [3, 8, 7]*km
>>> print(np.argsort(data))
[0 2 1]
>>> print(data.argsort())
[0 2 1]
classmethod from_astropy(arr, unit_registry=None)[source]

Convert an AstroPy “Quantity” to a unyt_array or unyt_quantity.

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

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

Example

>>> from astropy.units import km
>>> unyt_quantity.from_astropy(km)
unyt_quantity(1., 'km')
>>> a = [1, 2, 3]*km
>>> a
<Quantity [1., 2., 3.] km>
>>> unyt_array.from_astropy(a)
unyt_array([1., 2., 3.], 'km')
to_astropy(**kwargs)[source]

Creates a new AstroPy quantity with the same unit information.

Example

>>> from unyt import g, cm
>>> data = [3, 4, 5]*g/cm**3
>>> data.to_astropy()
<Quantity [3., 4., 5.] g / cm3>
classmethod from_pint(arr, unit_registry=None)[source]

Convert a Pint “Quantity” to a unyt_array or unyt_quantity.

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

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

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 = unyt_array.from_pint(b)
>>> c
unyt_array([0, 1, 2, 3], 'erg/cm**3')
to_pint(unit_registry=None)[source]

Convert a unyt_array or unyt_quantity to a Pint Quantity.

Parameters:
  • arr (unyt_array or unyt_quantity) – The unitful quantity to convert from.

  • unit_registry (Pint UnitRegistry, optional) – The Pint UnitRegistry to use in the conversion. If one is not supplied, the default one will be used. NOTE: This is not the same as a unyt.UnitRegistry object.

Examples

>>> from unyt import cm, s
>>> a = 4*cm**2/s
>>> print(a)
4 cm**2/s
>>> a.to_pint()
<Quantity(4, 'centimeter ** 2 / second')>
static from_string(s, unit_registry=None)[source]

Parse a string to a unyt_quantity object.

Parameters:
  • s (str) – A string representing a single quantity.

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

Examples

>>> from unyt import unyt_quantity
>>> unyt_quantity.from_string("1cm")
unyt_quantity(1, 'cm')
>>> unyt_quantity.from_string("+1e3 Mearth")
unyt_quantity(1000., 'Mearth')
>>> unyt_quantity.from_string("-10. kg")
unyt_quantity(-10., 'kg')
>>> unyt_quantity.from_string(".66      um")
unyt_quantity(0.66, 'μm')
>>> unyt_quantity.from_string("42")
unyt_quantity(42, '(dimensionless)')
>>> unyt_quantity.from_string("1.0 g/cm**3")
unyt_quantity(1., 'g/cm**3')
to_string()[source]
write_hdf5(filename, dataset_name=None, info=None, group_name=None)[source]

Writes a unyt_array to hdf5 file.

Parameters:
  • filename (string) – The filename to create and write a dataset to

  • dataset_name (string) – The name of the dataset to create in the file.

  • info (dictionary) – A dictionary of supplementary info to write to append as attributes to the dataset.

  • group_name (string) – An optional group to write the arrays to. If not specified, the arrays are datasets at the top level by default.

Examples

>>> from unyt import cm
>>> a = [1,2,3]*cm
>>> myinfo = {'field':'dinosaurs', 'type':'field_data'}
>>> a.write_hdf5('test_array_data.h5', dataset_name='dinosaurs',
...              info=myinfo)  
classmethod from_hdf5(filename, dataset_name=None, group_name=None)[source]

Attempts read in and convert a dataset in an hdf5 file into a unyt_array.

Parameters:
  • filename (string) –

  • file. (The filename to of the hdf5) –

  • dataset_name (string) – The name of the dataset to read from. If the dataset has a units attribute, attempt to infer units as well.

  • group_name (string) – An optional group to read the arrays from. If not specified, the arrays are datasets at the top level by default.

property value

Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> b = a.value
>>> b
array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base
True
property v

Creates a copy of this array with the unit information stripped

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> b = a.v
>>> b
array([3, 4, 5])

The returned array will contain a copy of the data contained in the original array.

>>> a.base is not b.base
True
property ndview

Returns a view into the array as a numpy array

Return type:

View of this array’s data.

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> a.ndview
array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b = a.ndview
>>> b.base is a.base
True
>>> b[2] = 4
>>> b
array([3, 4, 4])
>>> a
unyt_array([3, 4, 4], 'km')
property d

Returns a view into the array as a numpy array

Return type:

View of this array’s data.

Example

>>> from unyt import km
>>> a = [3, 4, 5]*km
>>> a
unyt_array([3, 4, 5], 'km')
>>> a.d
array([3, 4, 5])

This function returns a view that shares the same underlying memory as the original array.

>>> b = a.d
>>> b.base is a.base
True
>>> b[2] = 4
>>> b
array([3, 4, 4])
>>> a
unyt_array([3, 4, 4], 'km')
property unit_quantity

Return a quantity with a value of 1 and the same units as this array

Example

>>> from unyt import km
>>> a = [4, 5, 6]*km
>>> a.unit_quantity
unyt_quantity(1, 'km')
>>> print(a + 7*a.unit_quantity)
[11 12 13] km
property uq

Return a quantity with a value of 1 and the same units as this array

Example

>>> from unyt import km
>>> a = [4, 5, 6]*km
>>> a.uq
unyt_quantity(1, 'km')
>>> print(a + 7*a.uq)
[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
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
copy(order='C')[source]

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

numpy.copy, numpy.copyto

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
dot(b, out=None)[source]

dot product of two arrays.

Refer to numpy.dot for full documentation.

See also

numpy.dot

equivalent function

Examples

>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(a.dot(b))
[[2. 2.]
 [2. 2.]] km*s

This array method can be conveniently chained:

>>> print(a.dot(b).dot(b))
[[8. 8.]
 [8. 8.]] km*s**2
class unyt.array.unyt_quantity(input_scalar, units=None, registry=None, dtype=None, *, bypass_validation=False, name=None)[source]

Bases: unyt_array

A scalar associated with a unit.

Parameters:
  • input_scalar (an integer or floating point scalar) – The scalar to attach units to

  • units (String unit specification, unit symbol object, or astropy units) – The units of the quantity. Powers must be specified using python syntax (cm**3, not cm^3).

  • registry (A UnitRegistry object) – The registry to create units from. If units is already associated with a unit registry and this is specified, this will be used instead of the registry associated with the unit object.

  • dtype (data-type) – The dtype of the array data.

  • bypass_validation (boolean) – If True, all input validation is skipped. Using this option may produce corrupted, invalid units or array data, but can lead to significant speedups in the input validation logic adds significant overhead. If set, units must be a valid unit object. Defaults to False.

  • name (string) – The name of the scalar. Defaults to None. This attribute does not propagate through mathematical operations, but is preserved under indexing and unit conversions.

Examples

>>> a = unyt_quantity(3., 'cm')
>>> b = unyt_quantity(2., 'm')
>>> print(a + b)
203.0 cm
>>> print(b + a)
2.03 m

NumPy ufuncs will pass through units where appropriate.

>>> import numpy as np
>>> from unyt import g, cm
>>> a = 12*g/cm**3
>>> print(np.abs(a))
12 g/cm**3

and strip them when it would be annoying to deal with them.

>>> print(np.log10(a))
1.0791812460476249
reshape(shape, order='C')[source]

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

unyt.array.uconcatenate(arrs, axis=0)[source]

Concatenate a sequence of arrays.

This wrapper around numpy.concatenate preserves units. All input arrays must have the same units. See the documentation of numpy.concatenate for full details.

Examples

>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uconcatenate((A, B)) 
Traceback (most recent call last):
DeprecationWarning: ...
unyt_array([1, 2, 3, 2, 3, 4], 'cm')
unyt.array.ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None)[source]

Applies the cross product to two YT arrays.

This wrapper around numpy.cross preserves units. See the documentation of numpy.cross for full details.

unyt.array.uintersect1d(arr1, arr2, assume_unique=False)[source]

Find the sorted unique elements of the two input arrays.

A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details.

Examples

>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uintersect1d(A, B) 
Traceback (most recent call last):
DeprecationWarning: ...
unyt_array([2, 3], 'cm')
unyt.array.uunion1d(arr1, arr2)[source]

Find the union of two arrays.

A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details.

Examples

>>> from unyt import cm
>>> A = [1, 2, 3]*cm
>>> B = [2, 3, 4]*cm
>>> uunion1d(A, B) 
Traceback (most recent call last):
DeprecationWarning: ...
unyt_array([1, 2, 3, 4], 'cm')
unyt.array.unorm(data, ord=None, axis=None, keepdims=False)[source]

Matrix or vector norm that preserves units

This is a wrapper around np.linalg.norm that preserves units. See the documentation for that function for descriptions of the keyword arguments.

Examples

>>> from unyt import km
>>> data = [1, 2, 3]*km
>>> print(unorm(data)) 
Traceback (most recent call last):
DeprecationWarning: ...
3.7416573867739413 km
unyt.array.udot(op1, op2)[source]

Matrix or vector dot product that preserves units

This is a wrapper around np.dot that preserves units.

Examples

>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b)) 
Traceback (most recent call last):
DeprecationWarning: ...
[[2. 2.]
 [2. 2.]] km*s
unyt.array.uvstack(arrs)[source]

Stack arrays in sequence vertically (row wise) while preserving units

This is a wrapper around np.vstack that preserves units.

Examples

>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uvstack([a, b])) 
Traceback (most recent call last):
DeprecationWarning: ...
[[1 2 3]
 [2 3 4]] km
unyt.array.uhstack(arrs)[source]

Stack arrays in sequence horizontally while preserving units

This is a wrapper around np.hstack that preserves units.

Examples

>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(uhstack([a, b])) 
Traceback (most recent call last):
DeprecationWarning: ...
[1 2 3 2 3 4] km
>>> a = [[1],[2],[3]]*km
>>> b = [[2],[3],[4]]*km
>>> print(uhstack([a, b])) 
Traceback (most recent call last):
DeprecationWarning: ...
[[1 2]
 [2 3]
 [3 4]] km
unyt.array.ustack(arrs, axis=0)[source]

Join a sequence of arrays along a new axis while preserving units

The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

This is a wrapper around np.stack that preserves units. See the documentation for np.stack for full details.

Examples

>>> from unyt import km
>>> a = [1, 2, 3]*km
>>> b = [2, 3, 4]*km
>>> print(ustack([a, b])) 
Traceback (most recent call last):
DeprecationWarning: ...
[[1 2 3]
 [2 3 4]] km
unyt.array.loadtxt(fname, dtype='float', delimiter='\t', usecols=None, comments='#')[source]

Load unyt_arrays with unit information from a text file. Each row in the text file must have the same number of values.

Parameters:
  • fname (str) – Filename to read.

  • dtype (data-type, optional) – Data-type of the resulting array; default: float.

  • delimiter (str, optional) – The string used to separate values. By default, this is any whitespace.

  • usecols (sequence, optional) – Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read.

  • comments (str, optional) – The character used to indicate the start of a comment; default: ‘#’.

Examples

>>> temp, velx = loadtxt(
...    "sphere.dat", usecols=(1,2), delimiter="\t")  
unyt.array.savetxt(fname, arrays, fmt='%.18e', delimiter='\t', header='', footer='', comments='#')[source]

Write unyt_arrays with unit information to a text file.

Parameters:
  • fname (str) – The file to write the unyt_arrays to.

  • arrays (list of unyt_arrays or single unyt_array) – The array(s) to write to the file.

  • fmt (str or sequence of strs, optional) – A single format (%10.5f), or a sequence of formats.

  • delimiter (str, optional) – String or character separating columns.

  • header (str, optional) – String that will be written at the beginning of the file, before the unit header.

  • footer (str, optional) – String that will be written at the end of the file.

  • comments (str, optional) – String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. unyt.loadtxt.

Examples

>>> import unyt as u
>>> a = [1, 2, 3]*u.cm
>>> b = [8, 10, 12]*u.cm/u.s
>>> c = [2, 85, 9]*u.g
>>> savetxt("sphere.dat", [a,b,c], header='My sphere stuff',
...          delimiter="\t")  
unyt.array.allclose_units(actual, desired, rtol=1e-07, atol=0, **kwargs)[source]

Returns False if two objects are not equal up to desired tolerance

This is a wrapper for numpy.allclose() that also verifies unit consistency

Parameters:
  • actual (array-like) – Array obtained (possibly with attached units)

  • desired (array-like) – Array to compare with (possibly with attached units)

  • rtol (float, optional) – Relative tolerance, defaults to 1e-7

  • atol (float or quantity, optional) – Absolute tolerance. If units are attached, they must be consistent with the units of actual and desired. If no units are attached, assumes the same units as desired. Defaults to zero.

Raises:

RuntimeError – If units of rtol are not dimensionless

Notes

Also accepts additional keyword arguments accepted by numpy.allclose(), see the documentation of that function for details.

Examples

>>> import unyt as u
>>> actual = [1e-5, 1e-3, 1e-1]*u.m
>>> desired = actual.to("cm")
>>> allclose_units(actual, desired)
True