colour.utilities Package

Module Contents

colour.utilities.handle_numpy_errors(**kwargs)

Decorator for handling Numpy errors.

Parameters:**kwargs (**) – Keywords arguments.
Return type:object

References

[1]Kienzle, P., Patel, N., & Krycka, J. (2011). refl1d.numpyerrors - Refl1D v0.6.19 documentation. Retrieved January 30, 2015, from http://www.reflectometry.org/danse/docs/refl1d/_modules/refl1d/numpyerrors.html

Examples

>>> import numpy
>>> @handle_numpy_errors(all='ignore')
... def f():
...     1 / numpy.zeros(3)
>>> f()
colour.utilities.ignore_numpy_errors(function)
colour.utilities.raise_numpy_errors(function)
colour.utilities.print_numpy_errors(function)
colour.utilities.warn_numpy_errors(function)
colour.utilities.ignore_python_warnings(function)

Decorator for ignoring Python warnings.

Parameters:function (object) – Object to decorate.
Return type:object

Examples

>>> @ignore_python_warnings
... def f():
...     warnings.warn('This is an ignored warning!')
>>> f()
colour.utilities.batch(iterable, k=3)

Returns a batch generator from given iterable.

Parameters:
  • iterable (iterable) – Iterable to create batches from.
  • k (integer) – Batches size.
Returns:

Is string_like variable.

Return type:

bool

Examples

>>> batch(tuple(range(10)))  
<generator object batch at 0x...>
colour.utilities.is_openimageio_installed(raise_exception=False)

Returns if OpenImageIO is installed and available.

Parameters:raise_exception (bool) – Raise exception if OpenImageIO is unavailable.
Returns:Is OpenImageIO installed.
Return type:bool
Raises:ImportError – If OpenImageIO is not installed.
colour.utilities.is_scipy_installed(raise_exception=False)

Returns if scipy is installed and available.

Parameters:raise_exception (bool) – Raise exception if scipy is unavailable.
Returns:Is scipy installed.
Return type:bool
Raises:ImportError – If scipy is not installed.
colour.utilities.is_iterable(x)

Returns if given \(x\) variable is iterable.

Parameters:x (object) – Variable to check the iterability.
Returns:\(x\) variable iterability.
Return type:bool

Examples

>>> is_iterable([1, 2, 3])
True
>>> is_iterable(1)
False
colour.utilities.is_string(data)

Returns if given data is a string_like variable.

Parameters:data (object) – Data to test.
Returns:Is string_like variable.
Return type:bool

Examples

>>> is_string('I`m a string!')
True
>>> is_string(['I`m a string!'])
False
colour.utilities.is_numeric(x)

Returns if given \(x\) variable is a number.

Parameters:x (object) – Variable to check.
Returns:Is \(x\) variable a number.
Return type:bool

See also

is_integer()

Examples

>>> is_numeric(1)
True
>>> is_numeric((1,))
False
colour.utilities.is_integer(x)

Returns if given \(x\) variable is an integer under given threshold.

Parameters:x (object) – Variable to check.
Returns:Is \(x\) variable an integer.
Return type:bool

Notes

  • The determination threshold is defined by the colour.algebra.common.INTEGER_THRESHOLD attribute.

See also

is_numeric()

Examples

>>> is_integer(1)
True
>>> is_integer(1.01)
False
colour.utilities.as_numeric(x)

Converts given \(x\) variable to numeric. In the event where \(x\) cannot be converted, it is passed as is.

Parameters:x (object) – Variable to convert.
Returns:\(x\) variable converted to numeric.
Return type:ndarray

See also

as_stack(), as_shape(), auto_axis()

Examples

>>> as_numeric(np.array([1]))
1.0
>>> as_numeric(np.arange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
colour.utilities.closest(y, x)

Returns closest \(y\) variable element to reference \(x\) variable.

Parameters:
  • y (array_like) – Variable to search for the closest element.
  • x (numeric) – Reference variable.
Returns:

Closest \(y\) variable element.

Return type:

numeric

Examples

>>> y = np.array([24.31357115,
...               63.62396289,
...               55.71528816,
...               62.70988028,
...               46.84480573,
...               25.40026416])
>>> closest(y, 63)
62.70988028
colour.utilities.normalise(x, axis=None, factor=1, clip=True)

Normalises given array_like \(x\) variable values and optionally clip them between.

Parameters:
  • x (array_like) – \(x\) variable to normalise.
  • axis (numeric, optional) – Normalization axis.
  • factor (numeric, optional) – Normalization factor.
  • clip (bool, optional) – Clip values between in domain [0, ‘factor’].
Returns:

Normalised \(x\) variable.

Return type:

ndarray

Examples

>>> x = np.array([0.48224885, 0.31651974, 0.22070513])
>>> normalise(x)  
array([ 1.        ,  0.6563411...,  0.4576581...])
colour.utilities.steps(distribution)

Returns the steps of given distribution.

Parameters:distribution (array_like) – Distribution to retrieve the steps.
Returns:Distribution steps.
Return type:ndarray

Examples

Uniformly spaced variable:

>>> y = np.array([1, 2, 3, 4, 5])
>>> steps(y)
array([1])

Non-uniformly spaced variable:

>>> y = np.array([1, 2, 3, 4, 8])
>>> steps(y)
array([1, 4])
colour.utilities.is_uniform(distribution)

Returns if given distribution is uniform.

Parameters:distribution (array_like) – Distribution to check for uniformity.
Returns:Is distribution uniform.
Return type:bool

Examples

Uniformly spaced variable:

>>> y = np.array([1, 2, 3, 4, 5])
>>> is_uniform(y)
True

Non-uniformly spaced variable:

>>> y = np.array([1, 2, 3.1415, 4, 5])
>>> is_uniform(y)
False
colour.utilities.in_array(a, b, tolerance=1e-15)

Tests whether each element of an array is also present in a second array within given tolerance.

Parameters:
  • a (array_like) – Array to test the elements from.
  • b (array_like) – The values against which to test each value of array a.
Returns:

A boolean array with a shape describing whether an element of a is present in b within given tolerance.

Return type:

ndarray

References

[1]Yorke, R. (2014). Python: Change format of np.array or allow tolerance in in1d function. Retrieved March 27, 2015, from http://stackoverflow.com/a/23521245/931625

Examples

>>> a = np.array([0.50, 0.60])
>>> b = np.linspace(0, 10, 101)
>>> np.in1d(a, b)
array([ True, False], dtype=bool)
>>> in_array(a, b)
array([ True,  True], dtype=bool)
colour.utilities.tstack(a)

Stacks arrays in sequence along the last axis (tail).

Rebuilds arrays divided by tsplit().

Parameters:a (array_like) – Array to perform the stacking.
Return type:ndarray

See also

tsplit()

Examples

>>> a = 0
>>> tstack((a, a, a))
array([0, 0, 0])
>>> a = np.arange(0, 6)
>>> tstack((a, a, a))
array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4],
       [5, 5, 5]])
>>> a = np.reshape(a, (1, 6))
>>> tstack((a, a, a))
array([[[0, 0, 0],
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4],
        [5, 5, 5]]])
>>> a = np.reshape(a, (1, 1, 6))
>>> tstack((a, a, a))
array([[[[0, 0, 0],
         [1, 1, 1],
         [2, 2, 2],
         [3, 3, 3],
         [4, 4, 4],
         [5, 5, 5]]]])
colour.utilities.tsplit(a)

Splits arrays in sequence along the last axis (tail).

Parameters:a (array_like) – Array to perform the splitting.
Return type:ndarray

See also

tstack()

Examples

>>> a = np.array([0, 0, 0])
>>> tsplit(a)
array([0, 0, 0])
>>> a = np.array([[0, 0, 0],
...               [1, 1, 1],
...               [2, 2, 2],
...               [3, 3, 3],
...               [4, 4, 4],
...               [5, 5, 5]])
>>> tsplit(a)
array([[0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5],
       [0, 1, 2, 3, 4, 5]])
>>> a = np.array([[[0, 0, 0],
...                [1, 1, 1],
...                [2, 2, 2],
...                [3, 3, 3],
...                [4, 4, 4],
...                [5, 5, 5]]])
>>> tsplit(a)
array([[[0, 1, 2, 3, 4, 5]],

       [[0, 1, 2, 3, 4, 5]],

       [[0, 1, 2, 3, 4, 5]]])
colour.utilities.row_as_diagonal(a)

Returns the per row diagonal matrices of the given array.

Parameters:a (array_like) – Array to perform the diagonal matrices computation.
Return type:ndarray

References

[1]Castro, S. (2014). Numpy: Fastest way of computing diagonal for each row of a 2d array. Retrieved August 22, 2014, from http://stackoverflow.com/questions/26511401/numpy-fastest-way-of-computing-diagonal-for-each-row-of-a-2d-array/26517247#26517247

Examples

>>> a = np.array([[0.25891593, 0.07299478, 0.36586996],
...               [0.30851087, 0.37131459, 0.16274825],
...               [0.71061831, 0.67718718, 0.09562581],
...               [0.71588836, 0.76772047, 0.15476079],
...               [0.92985142, 0.22263399, 0.88027331]])
>>> row_as_diagonal(a)
array([[[ 0.25891593,  0.        ,  0.        ],
        [ 0.        ,  0.07299478,  0.        ],
        [ 0.        ,  0.        ,  0.36586996]],

       [[ 0.30851087,  0.        ,  0.        ],
        [ 0.        ,  0.37131459,  0.        ],
        [ 0.        ,  0.        ,  0.16274825]],

       [[ 0.71061831,  0.        ,  0.        ],
        [ 0.        ,  0.67718718,  0.        ],
        [ 0.        ,  0.        ,  0.09562581]],

       [[ 0.71588836,  0.        ,  0.        ],
        [ 0.        ,  0.76772047,  0.        ],
        [ 0.        ,  0.        ,  0.15476079]],

       [[ 0.92985142,  0.        ,  0.        ],
        [ 0.        ,  0.22263399,  0.        ],
        [ 0.        ,  0.        ,  0.88027331]]])
colour.utilities.dot_vector(m, v)

Convenient wrapper around np.einsum() with the following subscripts: ‘...ij,...j->...i’.

It performs the dot product of two arrays where m parameter is expected to be an array of 3x3 matrices and parameter v an array of vectors.

Parameters:
  • m (array_like) – Array of 3x3 matrices.
  • v (array_like) – Array of vectors.
Return type:

ndarray

See also

dot_matrix()

Examples

>>> m = np.array([[0.7328, 0.4296, -0.1624],
...               [-0.7036, 1.6975, 0.0061],
...               [0.0030, 0.0136, 0.9834]])
>>> m = np.reshape(np.tile(m, (6, 1)), (6, 3, 3))
>>> v = np.array([0.07049534, 0.10080000, 0.09558313])
>>> v = np.tile(v, (6, 1))
>>> dot_vector(m, v)  
array([[ 0.0794399...,  0.1220905...,  0.0955788...],
       [ 0.0794399...,  0.1220905...,  0.0955788...],
       [ 0.0794399...,  0.1220905...,  0.0955788...],
       [ 0.0794399...,  0.1220905...,  0.0955788...],
       [ 0.0794399...,  0.1220905...,  0.0955788...],
       [ 0.0794399...,  0.1220905...,  0.0955788...]])
colour.utilities.dot_matrix(a, b)

Convenient wrapper around np.einsum() with the following subscripts: ‘...ij,...jk->...ik’.

It performs the dot product of two arrays where a parameter is expected to be an array of 3x3 matrices and parameter b another array of of 3x3 matrices.

Parameters:
  • a (array_like) – Array of 3x3 matrices.
  • b (array_like) – Array of 3x3 matrices.
Return type:

ndarray

See also

dot_matrix()

Examples

>>> a = np.array([[0.7328, 0.4296, -0.1624],
...               [-0.7036, 1.6975, 0.0061],
...               [0.0030, 0.0136, 0.9834]])
>>> a = np.reshape(np.tile(a, (6, 1)), (6, 3, 3))
>>> b = a
>>> dot_matrix(a, b)  
array([[[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]],

       [[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]],

       [[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]],

       [[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]],

       [[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]],

       [[ 0.2342420...,  1.0418482..., -0.2760903...],
        [-1.7099407...,  2.5793226...,  0.1306181...],
        [-0.0044203...,  0.0377490...,  0.9666713...]]])
class colour.utilities.ArbitraryPrecisionMapping(data=None, key_decimals=0, **kwargs)

Bases: _abcoll.MutableMapping

Implements a mutable mapping / dict like object where numeric keys are stored with an arbitrary precision.

Parameters:
  • data (dict, optional) – dict of data to store into the mapping at initialisation.
  • key_decimals (int, optional) – Decimals count the keys will be rounded at
  • **kwargs (dict) – Key / Value pairs to store into the mapping at initialisation.
key_decimals
__setitem__()
__getitem__()
__delitem__()
__contains__()
__iter__()
__len__()

Examples

>>> data1 = {0.1999999998: 'Nemo', 0.2000000000: 'John'}
>>> apm1 = ArbitraryPrecisionMapping(data1, key_decimals=10)
>>> # Doctests skip for Python 2.x compatibility.
>>> tuple(apm1.keys())  
(0.1999999998, 0.2)
>>> apm2 = ArbitraryPrecisionMapping(data1, key_decimals=7)
>>> # Doctests skip for Python 2.x compatibility.
>>> tuple(apm2.keys())  
(0.2,)
__contains__(item)

Returns if the mapping contains given item (rounded if numeric).

Parameters:item (unicode) – Item (rounded if numeric) name.
Returns:Is item in mapping.
Return type:bool

Notes

  • Reimplements the MutableMapping.__contains__() method.
__delitem__(item)

Deletes the item (rounded if numeric) with given value.

Parameters:item (unicode) – Item (rounded if numeric) name.

Notes

  • Reimplements the MutableMapping.__delitem__() method.
__getitem__(item)

Returns the value of given item (rounded if numeric).

Parameters:item (unicode) – Item (rounded if numeric) name.
Returns:Item value.
Return type:object

Notes

  • Reimplements the MutableMapping.__getitem__() method.
__iter__()

Iterates over the items (rounded if numeric) names in the mapping.

Returns:Item names.
Return type:generator

Notes

  • Reimplements the MutableMapping.__iter__() method.
__len__()

Returns the items count.

Returns:Items count.
Return type:int

Notes

  • Reimplements the MutableMapping.__iter__() method.
__setitem__(item, value)

Sets given item (rounded if numeric) with given value.

Parameters:
  • item (object) – Attribute.
  • value (object) – Value.
Returns:

Item value (rounded if numeric).

Return type:

object

Notes

  • Reimplements the MutableMapping.__setitem__() method.
key_decimals

Property for self.__key_decimals private attribute.

Returns:self.__key_decimals.
Return type:unicode
class colour.utilities.Lookup

Bases: dict

Extends dict type to provide a lookup by value(s).

first_key_from_value()
keys_from_value()

References

[2]Mansencal, T. (n.d.). Lookup. Retrieved from https://github.com/KelSolaar/Foundations/blob/develop/foundations/data_structures.py

Examples

>>> person = Lookup(first_name='Doe', last_name='John', gender='male')
>>> person.first_key_from_value('Doe')
'first_name'
>>> persons = Lookup(John='Doe', Jane='Doe', Luke='Skywalker')
>>> sorted(persons.keys_from_value('Doe'))
['Jane', 'John']
first_key_from_value(value)

Gets the first key with given value.

Parameters:value (object) – Value.
Returns:Key.
Return type:object
keys_from_value(value)

Gets the keys with given value.

Parameters:value (object) – Value.
Returns:Keys.
Return type:object
class colour.utilities.Structure(*args, **kwargs)

Bases: dict

Defines an object similar to C/C++ structured type.

Parameters:
  • *args (*) – Arguments.
  • **kwargs (dict) – Key / Value pairs.
__getattr__()
__setattr__()
__delattr__()
update()

References

[1]Mansencal, T. (n.d.). Structure. Retrieved from https://github.com/KelSolaar/Foundations/blob/develop/foundations/data_structures.py

Examples

>>> person = Structure(first_name='Doe', last_name='John', gender='male')
>>> # Doctests skip for Python 2.x compatibility.
>>> person.first_name  
'Doe'
>>> sorted(person.keys())
['first_name', 'gender', 'last_name']
>>> # Doctests skip for Python 2.x compatibility.
>>> person['gender']  
'male'
__delattr__(attribute)

Deletes both key and sibling attribute.

Parameters:attribute (object) – Attribute.

Notes

  • Reimplements the dict.__delattr__() method.
__delitem__(attribute)

Deletes both key and sibling attribute.

Parameters:attribute (object) – Attribute.

Notes

  • Reimplements the dict.__delattr__() method.
__getattr__(attribute)

Returns given attribute value.

Parameters:attribute (unicode) – Attribute name.

Notes

  • Reimplements the dict.__getattr__() method.
Returns:Attribute value.
Return type:object
Raises:AttributeError – If the attribute is not defined.
__setattr__(attribute, value)

Sets both key and sibling attribute with given value.

Parameters:
  • attribute (object) – Attribute.
  • value (object) – Value.

Notes

  • Reimplements the dict.__setattr__() method.
__setitem__(attribute, value)

Sets both key and sibling attribute with given value.

Parameters:
  • attribute (object) – Attribute.
  • value (object) – Value.

Notes

  • Reimplements the dict.__setattr__() method.
update(*args, **kwargs)

Updates both keys and sibling attributes.

Parameters:
  • *args (*) – Arguments.
  • **kwargs (**) – Keywords arguments.

Notes

  • Reimplements the dict.update() method.
class colour.utilities.CaseInsensitiveMapping(data=None, **kwargs)

Bases: _abcoll.MutableMapping

Implements a case-insensitive mutable mapping / dict object.

Allows values retrieving from keys while ignoring the key case. The keys are expected to be unicode or string-like objects supporting the str.lower() method.

Parameters:
  • data (dict) – dict of data to store into the mapping at initialisation.
  • **kwargs (dict) – Key / Value pairs to store into the mapping at initialisation.
__setitem__()
__getitem__()
__delitem__()
__contains__()
__iter__()
__len__()
__eq__()
__ne__()
__repr__()
copy()
lower_items()

Warning

The keys are expected to be unicode or string-like objects.

References

[3]Reitz, K. (n.d.). CaseInsensitiveDict. Retrieved from https://github.com/kennethreitz/requests/blob/v1.2.3/requests/structures.py#L37

Examples

>>> methods = CaseInsensitiveMapping({'McCamy': 1, 'Hernandez': 2})
>>> methods['mccamy']
1
__contains__(item)

Returns if the mapping contains given item.

Parameters:item (unicode) – Item name.
Returns:Is item in mapping.
Return type:bool

Notes

  • Reimplements the MutableMapping.__contains__() method.
__delitem__(item)

Deletes the item with given name.

The item is deleted from the mapping using its lower name.

Parameters:item (unicode) – Item name.

Notes

  • Reimplements the MutableMapping.__delitem__() method.
__eq__(item)

Returns the equality with given object.

Parameters:item – Object item.
Returns:Equality.
Return type:bool

Notes

  • Reimplements the MutableMapping.__eq__() method.
__getitem__(item)

Returns the value of given item.

The item value is retrieved using its lower name in the mapping.

Parameters:item (unicode) – Item name.
Returns:Item value.
Return type:object

Notes

  • Reimplements the MutableMapping.__getitem__() method.
__iter__()

Iterates over the items names in the mapping.

The item names returned are the original input ones.

Returns:Item names.
Return type:generator

Notes

  • Reimplements the MutableMapping.__iter__() method.
__len__()

Returns the items count.

Returns:Items count.
Return type:int

Notes

  • Reimplements the MutableMapping.__iter__() method.
__ne__(item)

Returns the inequality with given object.

Parameters:item – Object item.
Returns:Inequality.
Return type:bool

Notes

  • Reimplements the MutableMapping.__ne__() method.
__repr__()

Returns the mapping representation with the original item names.

Returns:Mapping representation.
Return type:unicode

Notes

  • Reimplements the MutableMapping.__repr__() method.
__setitem__(item, value)

Sets given item with given value.

The item is stored as lower in the mapping while the original name and its value are stored together as the value in a tuple:

{“item.lower()”: (“item”, value)}

Parameters:
  • item (object) – Attribute.
  • value (object) – Value.

Notes

  • Reimplements the MutableMapping.__setitem__() method.
copy()

Returns a copy of the mapping.

Returns:Mapping copy.
Return type:CaseInsensitiveMapping

Notes

lower_items()

Iterates over the lower items names.

Returns:Lower item names.
Return type:generator
colour.utilities.message_box(message, width=79, padding=3)

Prints a message inside a box.

Parameters:
  • message (unicode) – Message to print.
  • width (int, optional) – Message box width.
  • padding (unicode) – Padding on each sides of the message.
Returns:

Definition success.

Return type:

bool

Examples

>>> message = ('Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
...     'sed do eiusmod tempor incididunt ut labore et dolore magna '
...     'aliqua.')
>>> message_box(message, width=75)
===========================================================================
*                                                                         *
*   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do       *
*   eiusmod tempor incididunt ut labore et dolore magna aliqua.           *
*                                                                         *
===========================================================================
True
>>> message_box(message, width=60)
============================================================
*                                                          *
*   Lorem ipsum dolor sit amet, consectetur adipiscing     *
*   elit, sed do eiusmod tempor incididunt ut labore et    *
*   dolore magna aliqua.                                   *
*                                                          *
============================================================
True
>>> message_box(message, width=75, padding=16)
===========================================================================
*                                                                         *
*                Lorem ipsum dolor sit amet, consectetur                  *
*                adipiscing elit, sed do eiusmod tempor                   *
*                incididunt ut labore et dolore magna                     *
*                aliqua.                                                  *
*                                                                         *
===========================================================================
True
colour.utilities.warning(*args, **kwargs)

Issues a warning.

Parameters:
  • *args (*) – Arguments.
  • **kwargs (**) – Keywords arguments.
Returns:

Definition success.

Return type:

bool

Examples

>>> colour.utilities.warning('This is a warning!')  
/Users/.../colour/utilities/verbose.py:42: UserWarning: This is a warning!