aboutsummaryrefslogtreecommitdiff
path: root/src/argaze/utils/MiscFeatures.py
blob: 09c289d11e0dc0b9986d01d4c8f4207b16c39f93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python

""" """

__author__ = "Théo de la Hogue"
__credits__ = []
__copyright__ = "Copyright 2023, Ecole Nationale de l'Aviation Civile (ENAC)"
__license__ = "BSD"

import time 

def printProgressBar (iteration:int, total:int, prefix:str = '', suffix:str = '', decimals:int = 1, length:int = 100, fill:str = '█', printEnd:str = "\r"):
    """Print iterations progress.  
    Call in a loop to create terminal progress bar.  
    - current iteration  
    - total iterations  
    - prefix string  
    - suffix string  
    - positive number of decimals in percent complete  
    - character length of bar  
    - bar fill character  
    - end character (e.g. "\r", "\r\n")
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)

    # Print New Line on Complete
    if iteration == total: 
        print()

def importFromTestPackage(module: str):
    """Import module from ArGaze test package.
    * **Returns:**
        - a module named <Module>Test"""

    import argaze
    import importlib.util
    import sys
    import os

    source_directory = os.path.dirname(os.path.dirname(os.path.abspath(argaze.__file__)))
    module_directory = os.path.join(source_directory, 'argaze.test', f'{module}.py')

    spec = importlib.util.spec_from_file_location(f'{module}Test', module_directory)
    TestModule = importlib.util.module_from_spec(spec)
    sys.modules[f'{module}Test'] = TestModule
    spec.loader.exec_module(TestModule)

    return TestModule

class ExitSignalHandler():
    """Handle exit event"""
    def __init__(self):

        import signal
        import threading

        global __exit_event
        global __on_exit_signal

        __exit_event = threading.Event()

        def __on_exit_signal(signo, _frame):
            __exit_event.set()

        for sig in ('TERM', 'HUP', 'INT'):
            signal.signal(getattr(signal, 'SIG'+sig), __on_exit_signal)

    def status(self):
        return __exit_event.is_set()

class TimeProbe():
    """Assess temporal performance"""

    def __init__(self):

        self.start()

    def start(self):
        """Start chronometer."""

        self.__last_time = time.perf_counter()
        self.__lap_counter = 0
        self.__elapsed_time = 0

    def lap(self):
        """Get the last lap time, number of laps and total elapsed time in millisecond."""

        lap_time = time.perf_counter() - self.__last_time

        self.__last_time = time.perf_counter()
        self.__lap_counter += 1
        self.__elapsed_time += lap_time

        return lap_time * 1e3, self.__lap_counter, self.__elapsed_time * 1e3

    def end(self):
        """Stop chronometer and get elapsed time in millisecond."""

        self.__elapsed_time += time.perf_counter() - self.__last_time

        return self.__elapsed_time * 1e3, self.__lap_counter

    def restart(self):

        self.start()