mutwo.core_utilities¶
Utility functions.
Object |
Documentation |
---|---|
Cache function output to disk via pickle. |
|
Base class for mutwo objects |
|
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. |
|
Delete 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 |
|
Get the local logger of your class. |
|
Find function that, if called with string, may return a number. |
|
Mark a callable as deprecated. |
- 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 import core_utilities >>> @core_utilities.compute_lazy("magic_output", False) ... def my_super_complex_calculation(n_numbers): ... return sum(number for number in range(n_numbers)) >>> N_NUMBERS = 10000000 >>> my_super_complex_calculation(N_NUMBERS) 49999995000000 >>> # takes very little time when calling the function the second time >>> my_super_complex_calculation(N_NUMBERS) 49999995000000 >>> # takes long again, because the input changed >>> my_super_complex_calculation(N_NUMBERS + 10) 50000095000045
- 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 (float | fractions.Fraction | int | quicktions.Fraction) – The value that shall be scaled.
old_min (float | fractions.Fraction | int | quicktions.Fraction) – The minima of the old range.
old_max (float | fractions.Fraction | int | quicktions.Fraction) – The maxima of the old range.
new_min (float | fractions.Fraction | int | quicktions.Fraction) – The minima of the new range.
new_max (float | fractions.Fraction | int | quicktions.Fraction) – The maxima of the new range.
translation_shape (float | fractions.Fraction | int | quicktions.Fraction) – 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:
float | fractions.Fraction | int | quicktions.Fraction
The algorithmic to change the translation with the translation_shape has been copied from expenvelope by M. Evanstein.
Example:
>>> from mutwo import core_utilities >>> core_utilities.scale(1, 0, 1, 0, 100) 100.0 >>> core_utilities.scale(0.5, 0, 1, 0, 100) 50.0 >>> core_utilities.scale(0.2, 0, 1, 0, 100) 20.0 >>> core_utilities.scale(0.2, 0, 1, 0, 100, 1) 12.885124808584155 >>> core_utilities.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[float | fractions.Fraction | int | quicktions.Fraction]
Example:
>>> from mutwo import core_utilities >>> sequence_to_scale = [1, 3, 2] >>> core_utilities.scale_sequence_to_sum(sequence_to_scale, 3) [0.5, 1.5, 1.0]
- accumulate_from_n(iterable, n)[source]¶
Accumulates iterable starting with value n.
- Parameters:
iterable (Iterable[float | fractions.Fraction | int | quicktions.Fraction]) – The iterable which values shall be accumulated.
n (float | fractions.Fraction | int | quicktions.Fraction) – The start number from which shall be accumulated.
- Return type:
Iterator
Example:
>>> from mutwo import core_utilities >>> tuple(core_utilities.accumulate_from_n((4, 2, 3), 0)) (0, 4, 6, 9) >>> tuple(core_utilities.accumulate_from_n((4, 2, 3), 2)) (2, 6, 8, 11)
- accumulate_from_zero(iterable)[source]¶
Accumulates iterable starting from 0.
- Parameters:
iterable (Iterable[float | fractions.Fraction | int | quicktions.Fraction]) – The iterable which values shall be accumulated.
- Return type:
Iterator
Example:
>>> from mutwo import core_utilities >>> tuple(core_utilities.accumulate_from_zero((4, 2, 3))) (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], float | fractions.Fraction | int | quicktions.Fraction]]) –
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 import core_utilities >>> core_utilities.uniqify_sequence([[1, 2], [1], [1]]) [[1], [1, 2]]
- 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 import core_utilities >>> permutations = core_utilities.cyclic_permutations((1, 2, 3, 4)) >>> next(permutations) (1, 2, 3, 4) >>> next(permutations) (2, 3, 4, 1)
- find_closest_index(item, sequence, key=<function <lambda>>)[source]¶
Return index of element in
data
with smallest difference toitem
.- Parameters:
item (float | fractions.Fraction | int | quicktions.Fraction) – 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 import core_utilities >>> core_utilities.find_closest_index(2, (1, 4, 5)) 0 >>> core_utilities.find_closest_index(127, (100, 4, 300, 53, 129)) 4 >>> core_utilities.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 (float | fractions.Fraction | int | quicktions.Fraction) – 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 import core_utilities >>> core_utilities.find_closest_item(2, (1, 4, 5)) 1 >>> core_utilities.find_closest_item(127, (100, 4, 300, 53, 129)) 129 >>> core_utilities.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) – The indices of the nested item.
sequence (Sequence[Any]) – A nested sequence.
- Return type:
Any
Example:
>>> from mutwo import core_utilities >>> nested_sequence = (1, 2, (4, (5, 1), (9, (3,)))) >>> core_utilities.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) – 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 import core_utilities >>> nested_sequence = [1, 2, [4, [5, 1], [9, [3]]]] >>> core_utilities.set_nested_item_from_index_sequence((2, 2, 0), nested_sequence, 100) >>> nested_sequence[2][2][0] = 100 # is equal
- del_nested_item_from_index_sequence(index_sequence, sequence)[source]¶
Delete item in nested Sequence.
- Parameters:
index_sequence (Sequence) – The indices of the nested item which shall be deleted.
sequence (MutableSequence[Any]) – A nested sequence.
- Return type:
None
Example:
>>> from mutwo import core_utilities >>> nested_sequence = [1, 2, [4, [5, 1], [9, [3]]]] >>> core_utilities.del_nested_item_from_index_sequence((2, 2, 0), nested_sequence) >>> nested_sequence [1, 2, [4, [5, 1], [[3]]]]
- 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 import core_utilities >>> core_utilities.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:
float | fractions.Fraction | int | quicktions.Fraction
- 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_utilities >>> 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_utilities.test_if_objects_are_equal_by_parameter_tuple( ... first_object, second_object, ("a",) ... ) True >>> core_utilities.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.
- get_cls_logger(cls, level=None)[source]¶
Get the local logger of your class.
- Parameters:
cls (Type) – The class for which the logger should be returned. Simply call type(o) if you only have the instance.
level (int) – The logging level of the logger. If
None
the level defined in mutwo.core_configurations.LOGGING_LEVEL is used. Default toNone
.
- Returns:
A
logging.Logger
.- Return type:
Logger
- str_to_number_parser(string)[source]¶
Find function that, if called with string, may return a number.
- Parameters:
string (str) – The string for which a suitable function is searched for.
- Returns:
The function that if called with the string as an input may return a number object (int, float, fraction, …). It could be that no suitable function could found and calling the function with the string returns an error or unexpected results.
- Return type:
Callable
Example:
>>> from mutwo import core_utilities >>> # floats are detected >>> core_utilities.str_to_number_parser('3.21')('3.21') 3.21 >>> # int are detected >>> core_utilities.str_to_number_parser('7')('7') 7 >>> # fractions are detected >>> core_utilities.str_to_number_parser('7/4')('7/4') Fraction(7, 4)
- deprecated(info=None)[source]¶
Mark a callable as deprecated.
- Parameters:
info (str) – Deprecation info printed to the user.
- Return type:
Callable
- class CannotSetDurationOfEmptyCompound[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class AlreadyDefinedValueNameError(cls)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class InvalidAverageValueStartAndEndWarning[source]¶
Bases:
RuntimeWarning
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class InvalidStartValueError(start, duration)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class InvalidPointError(point, point_count)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class ImpossibleToPutInError(event_to_be_put_into, event_to_put_in, method_name)[source]¶
Bases:
TypeError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class ImpossibleToSquashInError(event_to_be_squashed_into, event_to_squash_in)[source]¶
Bases:
ImpossibleToPutInError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class ImpossibleToSlideInError(event_to_be_slided_into, event_to_slide_in)[source]¶
Bases:
TypeError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class ImpossibleToExtendUntilError(event_to_extend_until)[source]¶
Bases:
TypeError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class IneffectiveExtendUntilError(event_to_extend_until)[source]¶
Bases:
ValueError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class InvalidStartAndEndValueError(start, end)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class InvalidCutOutStartAndEndValuesError(start, end, chronon, duration)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- Parameters:
absolute_time (core_parameters.abc.Duration) –
- class EmptyEnvelopeError(envelope, method)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class ConcatenationError(ancestor, event)[source]¶
Bases:
TypeError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class NoTagError(event_without_tag)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class SplitError(absolute_time)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- Parameters:
absolute_time (core_parameters.abc.Duration) –
- class InvalidAbsoluteTime(t)[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class NoSplitTimeError[source]¶
Bases:
Exception
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class CannotParseError(o, parse_type)[source]¶
Bases:
NotImplementedError
Public Data Attributes:
Inherited from
BaseException
args
Public Methods:
Inherited from
BaseException
with_traceback
Exception.with_traceback(tb) -- set self.__traceback__ to tb and return self.
- class MutwoObject[source]¶
Bases:
object
Base class for mutwo objects
This class collects functionality that’s useful for any object in the mutwo ecosystem.
Public Methods:
copy
()Return a deep copy of mutwo object.
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.