4.6.7. pde.tools.misc module

Miscellaneous python functions

module_available

check whether a python module is available

ensure_directory_exists

creates a folder if it not already exists

preserve_scalars

decorator that makes vectorized methods work with scalars

decorator_arguments

make a decorator usable with and without arguments:

skipUnlessModule

decorator that skips a test when a module is not available

import_class

import a class or module given an identifier

classproperty

decorator that can be used to define read-only properties for classes.

hybridmethod

descriptor that can be used as a decorator to allow calling a method both as a classmethod and an instance method

estimate_computation_speed

estimates the computation speed of a function

hdf_write_attributes

write (JSON-serialized) attributes to a hdf file

number

convert a value into a float or complex number

get_common_dtype

returns a dtype in which all arguments can be represented

number_array

convert an array with arbitrary dtype either to np.double or np.cdouble

class classproperty(fget=None, doc=None)[source]

Bases: property

decorator that can be used to define read-only properties for classes.

This is inspired by the implementation of astropy, see astropy.org.

Example

The decorator can be used much like the property decorator:

class Test():

    item: str = 'World'

    @classproperty
    def message(cls):
        return 'Hello ' + cls.item

print(Test.message)
deleter(fdel)[source]

Descriptor to change the deleter on a property.

getter(fget)[source]

Descriptor to change the getter on a property.

setter(fset)[source]

Descriptor to change the setter on a property.

decorator_arguments(decorator: Callable) Callable[source]

make a decorator usable with and without arguments:

The resulting decorator can be used like @decorator or @decorator(*args, **kwargs)

Inspired by https://stackoverflow.com/a/14412901/932593

Parameters

decorator – the decorator that needs to be modified

Returns

the decorated function

ensure_directory_exists(folder: Union[str, pathlib.Path])[source]

creates a folder if it not already exists

Parameters

folder (str) – path of the new folder

estimate_computation_speed(func: Callable, *args, **kwargs) float[source]

estimates the computation speed of a function

Parameters

func (callable) – The function to call

Returns

the number of times the function can be calculated in one second. The inverse is thus the runtime in seconds per function call

Return type

float

get_common_dtype(*args)[source]

returns a dtype in which all arguments can be represented

Parameters

*args – All items (arrays, scalars, etc) to be checked

Returns: numpy.cdouble if any entry is complex, otherwise np.double

hdf_write_attributes(hdf_path, attributes: dict = None, raise_serialization_error: bool = False) None[source]

write (JSON-serialized) attributes to a hdf file

Parameters
  • hdf_path – Path to a group or dataset in an open HDF file

  • attributes (dict) – Dictionary with values written as attributes

  • raise_serialization_error (bool) – Flag indicating whether serialization errors are raised or silently ignored

class hybridmethod(fclass, finstance=None, doc=None)[source]

Bases: object

descriptor that can be used as a decorator to allow calling a method both as a classmethod and an instance method

Adapted from https://stackoverflow.com/a/28238047

classmethod(fclass)[source]
instancemethod(finstance)[source]
import_class(identifier: str)[source]

import a class or module given an identifier

Parameters

identifier (str) – The identifier can be a module or a class. For instance, calling the function with the string identifier == ‘numpy.linalg.norm’ is roughly equivalent to running from numpy.linalg import norm and would return a reference to norm.

module_available(module_name: str) bool[source]

check whether a python module is available

Parameters

module_name (str) – The name of the module

Returns

True if the module can be imported and False otherwise

number(value: Union[int, float, complex, str]) Number[source]

convert a value into a float or complex number

Parameters

value (Number or str) – The value which needs to be converted

Result:

Number: A complex number or a float if the imaginary part vanishes

number_array(data: ArrayLike, dtype=None, copy: bool = True) numpy.ndarray[source]

convert an array with arbitrary dtype either to np.double or np.cdouble

Parameters
  • data (ndarray) – The data that needs to be converted to a float array. This can also be any iterable of numbers.

  • dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be determined from data automatically.

  • copy (bool) – Whether the data must be copied (in which case the original array is left untouched). Note that data will always be copied when changing the dtype.

Returns

An array with the correct dtype

Return type

ndarray

preserve_scalars(method: TFunc) TFunc[source]

decorator that makes vectorized methods work with scalars

This decorator allows to call functions that are written to work on numpy arrays to also accept python scalars, like int and float. Essentially, this wrapper turns them into an array and unboxes the result.

Parameters

method – The method being decorated

Returns

The decorated method

skipUnlessModule(module_names: Union[Sequence[str], str]) Callable[[TFunc], TFunc][source]

decorator that skips a test when a module is not available

Parameters

module_names (str) – The name of the required module(s)

Returns

A function, so this can be used as a decorator