mutwo.core_utilities§
Utility functions.
Object |
Documentation |
---|---|
This decorator adds a copy option for object mutating methods. |
|
This decorator adds a ‘tag’ argument to the init method of a class. |
|
Cache function output to disk via pickle. |
|
|
factorise(integer) -> [list of factors] |
|
Get factor generator |
|
Test if number is prime or not. |
Scale a value from one range to another range. |
|
Scale numbers in a sequence so that the resulting sum fits to the given value. |
|
Accumulates iterable starting with value n. |
|
Accumulates iterable starting from 0. |
|
Insert an item into a list relative to the first item equal to a certain value. |
|
Not-Order preserving function to uniqify any iterable with non-hashable objects. |
|
Cyclic permutation of an iterable. Return a generator object. |
|
Return index of element in |
|
Return element in |
|
Get item in nested Sequence. |
|
Set item in nested Sequence. |
|
Find all combinations of numbers which sum is equal to the given sum. |
|
Run a function with argument as input |
|
Round number if it is an instance of float, otherwise unaltered number. |
|
Transform camel case formatted string to snake case. |
|
|
Check if the parameters of two objects have equal values. |
Fetch from all arguments their __all__ attribute and combine them to one tuple |
- add_copy_option(function)[source]§
This decorator adds a copy option for object mutating methods.
- Parameters:
function (F) – The method which shall be adjusted.
function –
- Return type:
F
The ‘add_copy_option’ decorator adds the ‘mutate’ keyword argument to the decorated method. If ‘mutate’ is set to
False
, the decorator deep copies the respective object, then applies the called method on the new copied object and finally returns the copied object. This can be useful for methods that by default mutate its object. When adding this method, it is up to the user whether the original object shall be changed and returned (for mutate=True) or if a copied version of the object with the respective mutation shall be returned (for mutate=False).
- add_tag_to_class(class_to_decorate)[source]§
This decorator adds a ‘tag’ argument to the init method of a class.
- Parameters:
class_to_decorate (G) – The class which shall be decorated.
class_to_decorate –
- Return type:
G
- compute_lazy(path, force_to_compute=False, pickle_module=None)[source]§
Cache function output to disk via pickle.
- Parameters:
path (str) – Where to save the computed result.
force_to_compute (bool) – Set to
True
if function has to be re-computed.pickle_module (Optional[types.ModuleType]) – Depending on the object which should be pickled the default python pickle module won’t be sufficient. Therefore alternative third party pickle modules (with the same API) can be used. If no argument is provided, the function will first try to use any of the pickle modules given in the
mutwo.core_utilities.configurations.PICKLE_MODULE_TO_SEARCH_TUPLE
. If none of the modules could be imported it will fall back to the buildin pickle module.
The decorator will only run the function if its input changes and otherwise load the return value from the disk.
This function is helpful if there is a complex, long-taking calculation, which should only run once or from time to time if the input changes.
Example:
>>> from mutwo.utilities import decorators >>> @decorators.compute_lazy("magic_output", False) def my_super_complex_calculation(n_numbers): return sum(number for number in range(n_numbers)) >>> N_NUMBERS = 100000000 >>> my_super_complex_calculation(N_NUMBERS) 4999999950000000 >>> # takes very little time when calling the function the second time >>> my_super_complex_calculation(N_NUMBERS) 4999999950000000 >>> # takes long again, because the input changed >>> my_super_complex_calculation(N_NUMBERS + 10) 4999999950000000
- scale(value, old_min, old_max, new_min, new_max, translation_shape=0)[source]§
Scale a value from one range to another range.
- Parameters:
value (Union[float, Fraction, int]) – The value that shall be scaled.
old_min (Union[float, Fraction, int]) – The minima of the old range.
old_max (Union[float, Fraction, int]) – The maxima of the old range.
new_min (Union[float, Fraction, int]) – The minima of the new range.
new_max (Union[float, Fraction, int]) – The maxima of the new range.
translation_shape (Union[float, Fraction, int]) – 0 for a linear translation, values > 0 for a slower change at the beginning, values < 0 for a faster change at the beginning.
- Return type:
Union[float, Fraction, int]
The algorithmic to change the translation with the translation_shape has been copied from expenvelope by M. Evanstein.
Example:
>>> from mutwo.core.utilities import tools >>> tools.scale(1, 0, 1, 0, 100) 100 >>> tools.scale(0.5, 0, 1, 0, 100) 50 >>> tools.scale(0.2, 0, 1, 0, 100) 20 >>> tools.scale(0.2, 0, 1, 0, 100, 1) 12.885124808584155 >>> tools.scale(0.2, 0, 1, 0, 100, -1) 28.67637263023771
- scale_sequence_to_sum(sequence_to_scale, sum_to_scale_to)[source]§
Scale numbers in a sequence so that the resulting sum fits to the given value.
- Parameters:
sequence_to_scale (Sequence[core_constants.Real]) – The sequence filled with real numbers which sum should fit to the given sum_to_scale_to argument.
sum_to_scale_to (core_constants.Real) – The resulting sum of the sequence.
- Return type:
Sequence[Union[float, Fraction, int]]
Example:
>>> from mutwo import utilities >>> sequence_to_scale = [1, 3, 2] >>> utilities.tools.scale_sequence_to_sum(sequence_to_scale, 3) [0.5, 1.5, 1]
- accumulate_from_n(iterable, n)[source]§
Accumulates iterable starting with value n.
- Parameters:
iterable (Iterable[Union[float, Fraction, int]]) – The iterable which values shall be accumulated.
n (Union[float, Fraction, int]) – The start number from which shall be accumulated.
- Return type:
Iterator
Example:
>>> from mutwo.utilities import tools >>> tools.accumulate_from_n((4, 2, 3), 0) (0, 4, 6, 9) >>> tools.accumulate_from_n((4, 2, 3), 2) (2, 6, 8, 11)
- accumulate_from_zero(iterable)[source]§
Accumulates iterable starting from 0.
- Parameters:
iterable (Iterable[Union[float, Fraction, int]]) – The iterable which values shall be accumulated.
- Return type:
Iterator
Example:
>>> from mutwo.utilities import tools >>> tools.accumulate_from_zero((4, 2, 3), 0) (0, 4, 6, 9)
- insert_next_to(mutable_sequence, item_to_find, distance, item_to_insert)[source]§
Insert an item into a list relative to the first item equal to a certain value.
- Parameters:
mutable_sequence (MutableSequence) –
item_to_find (Any) –
distance (int) –
item_to_insert (Any) –
- uniqify_sequence(sequence, sort_key=None, group_by_key=None)[source]§
Not-Order preserving function to uniqify any iterable with non-hashable objects.
- Parameters:
sequence (Sequence) – The iterable which items shall be uniqified.
sort_key (Optional[Callable[[Any], Union[float, Fraction, int]]]) –
group_by_key (Optional[Callable[[Any], Any]]) –
- Returns:
Return uniqified version of the entered iterable. The function will try to return the same type of the passed iterable. If Python raises an error during initialisation of the original iterable type, the function will simply return a tuple.
- Return type:
Iterable
Example:
>>> from mutwo.parameters import pitches >>> from mutwo.utilities import tools >>> tools.uniqify_sequence([pitches.WesternPitch(pitch_name) for pitch_name in 'c d e c d e e f a c a'.split(' ')]) [WesternPitch(c4), WesternPitch(d4), WesternPitch(e4), WesternPitch(f4), WesternPitch(a4)]
- cyclic_permutations(sequence)[source]§
Cyclic permutation of an iterable. Return a generator object.
- Parameters:
sequence (Sequence[Any]) – The sequence from which cyclic permutations shall be generated.
- Return type:
Generator
Example:
>>> from mutwo.utilities import tools >>> permutations = tools.cyclic_permutations((1, 2, 3, 4)) >>> next(permutations) (2, 3, 4, 1) >>> next(permutations) (3, 4, 1, 2)
- find_closest_index(item, sequence, key=<function <lambda>>)[source]§
Return index of element in
data
with smallest difference toitem
.- Parameters:
item (Union[float, Fraction, int]) – The item from which the closest item shall be found.
sequence (Sequence) – The data to which the closest item shall be found.
key (Callable[[Any], T]) –
- Return type:
int
Example:
>>> from mutwo.utilities import tools >>> tools.find_closest_index(2, (1, 4, 5)) 0 >>> tools.find_closest_index(127, (100, 4, 300, 53, 129)) 4 >>> tools.find_closest_index(127, (('hi', 100), ('hey', 4), ('hello', 300)), key=lambda item: item[1]) 0
- find_closest_item(item, sequence, key=<function <lambda>>)[source]§
Return element in
data
with smallest difference toitem
.- Parameters:
item (Union[float, Fraction, int]) – The item from which the closest item shall be found.
sequence (Sequence) – The data to which the closest item shall be found.
key (Callable[[Any], T]) –
- Returns:
The closest number to
item
indata
.- Return type:
T
Example:
>>> from mutwo.utilities import tools >>> tools.find_closest_item(2, (1, 4, 5)) 1 >>> tools.find_closest_item(127, (100, 4, 300, 53, 129)) 129 >>> tools.find_closest_item( >>> 127, >>> (('hi', 100), ('hey', 4), ('hello', 300)), >>> key=lambda item: item[1] >>> ) ('hi', 100)
- get_nested_item_from_index_sequence(index_sequence, sequence)[source]§
Get item in nested Sequence.
- Parameters:
index_sequence (Sequence[int]) – The indices of the nested item.
sequence (Sequence[Any]) – A nested sequence.
- Return type:
Any
Example:
>>> from mutwo.utilities import tools >>> nested_sequence = (1, 2, (4, (5, 1), (9, (3,)))) >>> tools.get_nested_item_from_index_sequence((2, 2, 0), nested_sequence) 9 >>> nested_sequence[2][2][0] # is equal 9
- set_nested_item_from_index_sequence(index_sequence, sequence, item)[source]§
Set item in nested Sequence.
- Parameters:
index_sequence (Sequence[int]) – The indices of the nested item which shall be set.
sequence (MutableSequence[Any]) – A nested sequence.
item (Any) – The new item value.
- Return type:
None
Example:
>>> from mutwo.utilities import tools >>> nested_sequence = [1, 2, [4, [5, 1], [9, [3]]]]] >>> tools.set_nested_item_from_index_sequence((2, 2, 0), nested_sequence, 100) >>> nested_sequence[2][2][0] = 100 # is equal
- find_numbers_which_sums_up_to(given_sum, number_to_choose_from_sequence=None, item_to_sum_up_count_set=None)[source]§
Find all combinations of numbers which sum is equal to the given sum.
- Parameters:
given_sum (float) – The target sum for which different combinations shall be searched.
number_to_choose_from_sequence (Optional[Sequence[float]]) – A sequence of numbers which shall be tried to combine to result in the
given_sum
. If the user doesn’t specify this argument mutwo will use all natural numbers equal or smaller than thegiven_sum
.item_to_sum_up_count_set (Optional[set[int]]) – How many numbers can be combined to result in the
given_sum
. If the user doesn’t specify this argument mutwo will use all natural numbers equal or smaller than thegiven_sum
.
- Return type:
tuple[tuple[float, …], …]
Example:
>>> from mutwo.utilities import tools >>> tools.find_numbers_which_sums_up_to(4) ((4,), (1, 3), (2, 2), (1, 1, 2), (1, 1, 1, 1))
- call_function_except_attribute_error(function, argument, exception_value)[source]§
Run a function with argument as input
- Parameters:
function (Callable[[Any], Any]) – The function to be called.
argument (Any) – The argument with which the function shall be called.
exception_value (Any) – The alternative value if the function call raises an AttributeError.
- Returns:
Return
exception_value
in case an attribute error occurs. In case the function call is successful the function return value will be returned.- Return type:
Any
- round_floats(number_to_round, n_digits)[source]§
Round number if it is an instance of float, otherwise unaltered number.
- Parameters:
number_to_round (core_constants.Real) – The number which shall be rounded.
n_digits (int) – How many digits shall the number be rounded.
- Return type:
Union[float, Fraction, int]
- camel_case_to_snake_case(camel_case_string)[source]§
Transform camel case formatted string to snake case.
- Parameters:
camel_case_string (str) – String which is formatted using camel case (no whitespace, but upper letters at new word start).
- Returns:
string formatted using snake case
- Return type:
str
Example: MyClassName -> my_class_name
- test_if_objects_are_equal_by_parameter_tuple(object0, object1, parameter_to_compare_tuple)[source]§
Check if the parameters of two objects have equal values.
- Parameters:
object0 (Any) – The first object which shall be compared.
object1 (Any) – The second object with which the first object shall be compared.
parameter_to_compare_tuple (tuple[str, ...]) –
- Parameter_to_compare_tuple:
A tuple of attribute names which shall be compared.
- Returns:
True if all values of all parameters of the objects are equal and False if not or if an AttributeError is raised.
- Return type:
bool
Example:
>>> from mutwo import core_utilites >>> class A: pass >>> first_object = A() >>> first_object.a = 100 >>> second_object = A() >>> second_object.a = 100 >>> third_object = A() >>> third_object.a = 200 >>> core_utilites.test_if_objects_are_equal_by_parameter_tuple( >>> first_object, second_object, ("a",) >>> ) True >>> core_utilites.test_if_objects_are_equal_by_parameter_tuple( >>> first_object, third_object, ("a",) >>> ) False
- get_all(*submodule_tuple)[source]§
Fetch from all arguments their __all__ attribute and combine them to one tuple
- Parameters:
submodule_tuple (module) – Submodules which __all__ attribute shall be fetched.
- Return type:
tuple[str, …]
This function is mostly useful in the __init__ code of each
mutwo
module.
- class AlreadyDefinedValueNameError(cls)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(cls)Inherited from
Exception
__init__
(cls)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(cls)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class InvalidAverageValueStartAndEndWarning[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
()Inherited from
RuntimeWarning
__init__
()Inherited from
Warning
__init__
()Inherited from
Exception
__init__
()Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
()__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class InvalidStartValueError(start, duration)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(start, duration)Inherited from
Exception
__init__
(start, duration)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(start, duration)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class InvalidPointError(point, point_count)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(point, point_count)Inherited from
Exception
__init__
(point, point_count)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(point, point_count)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class ImpossibleToSquashInError(event_to_be_squashed_into, event_to_squash_in)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(event_to_be_squashed_into, ...)Inherited from
TypeError
__init__
(event_to_be_squashed_into, ...)Inherited from
Exception
__init__
(event_to_be_squashed_into, ...)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(event_to_be_squashed_into, ...)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class InvalidStartAndEndValueError(start, end)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(start, end)Inherited from
Exception
__init__
(start, end)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(start, end)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
- class InvalidCutOutStartAndEndValuesError(start, end, simple_event, duration)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(start, end, simple_event, duration)Inherited from
Exception
__init__
(start, end, simple_event, duration)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(start, end, simple_event, duration)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(absolute_time)Inherited from
Exception
__init__
(absolute_time)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(absolute_time)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- Parameters:
absolute_time (Union[float, Fraction, int]) –
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class NoSolutionFoundError(message)[source]§
Public Data Attributes:
Inherited from
BaseException
Public Methods:
__init__
(message)Inherited from
Exception
__init__
(message)Inherited from
BaseException
__repr__
()Return repr(self).
__str__
()Return str(self).
__getattribute__
(name, /)Return getattr(self, name).
__setattr__
(name, value, /)Implement setattr(self, name, value).
__delattr__
(name, /)Implement delattr(self, name).
__init__
(message)__reduce__
Helper for pickle.
__setstate__
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- Parameters:
message (str) –
- with_traceback()§
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- args§
mutwo.core_utilities.configurations§
Configure the default behaviour of utility functions
- PICKLE_MODULE_TO_SEARCH_TUPLE = ('cloudpickle', 'dill')§
Define alternative pickle modules which are used in the
mutwo.core_utilites.compute_lazy()
decorator.