Debian Codegraph @

ResistorDecoder/src/helpers.py

raw symbols SCIP
1 import re
2
3 SI_units = {
4 "-24": (-24, "y", "yocto"),
5 "-21": (-21, "z", "zepto"),
6 "-18": (-18, "a", "atto"),
7 "-15": (-15, "f", "femto"),
8 "-12": (-12, "p", "pico"),
9 "-9" : (-9, "n", "nano"),
10 "-6" : (-6, "µ", "micro"),
11 "-3" : (-3, "m", "milli"),
12 "-2" : (-2, "c", "centi"),
13 "-1" : (-1, "d", "deci"),
14 "0" : (0, "", ""),
15 "1" : (1, "da", "deka"),
16 "2" : (2, "h", "hecto"),
17 "3" : (3, "k", "kilo"),
18 "6" : (6, "M", "mega"),
19 "9" : (9, "G", "giga"),
20 "12" : (12, "T", "tera"),
21 "15" : (15, "P", "peta"),
22 "18" : (18, "E", "exa"),
23 "21" : (21, "Z", "zetta"),
24 "24" : (24, "Y", "yotta"),
25 # Binary
26 "10" : (10, "Ki", "kibi"),
27 "20" : (20, "Mi", "mebi"),
28 "30" : (30, "Gi", "gibi"),
29 "40" : (40, "Ti", "tebi"),
30 "50" : (50, "Pi", "pebi"),
31 "60" : (60, "Ei", "exbi"),
32 "70" : (70, "Zi", "zebi"),
33 "80" : (80, "Yi", "yobi")
34 }
35
36
37
38 def format_metric(value, precision=3, decimal=True, valid_prefixes=(9, 6, 3, 0, -3, -6, -9)):
39 import math
40
41 try:
42 if decimal:
43 exponent = math.floor(math.log10(value))
44 else:
45 exponent = math.floor(math.log2(value))
46 except ValueError:
47 # log of 0 is -inf
48 return "0 "
49
50 # Find first prefix exponent smaller than the given exponent, in descending order.
51 # Use the last good enough value if nothing was found.
52 best_prefix = 0
53 for prefix in sorted(valid_prefixes, reverse=True):
54 best_prefix = prefix
55 if prefix <= exponent:
56 break
57
58 if decimal:
59 value /= 10 ** best_prefix
60 else:
61 value /= 2 ** best_prefix
62
63 # Rounds the value and places a reasonable metric prefix
64 format_str = "{:." + str(precision) + "}"
65 value = float(format_str.format(float(value)))
66 prefix = SI_units[str(int(best_prefix))][1]
67 # Round off trailing decimal when possible
68 if value == math.floor(value):
69 value = int(value)
70 return f"{value} {prefix}"
71
72
73
74 def format_resistance(_value, _precision):
75 # Allow the Giga, Mega, kilo, none, milli prefixes
76 value_str = format_metric(_value, _precision, True, (9, 6, 3, 0, -3))
77 return f"{value_str}Ω"
78
79
80
81 def calculate_values(_tolerance, _mantissa, _multiplier):
82 tolerance_val = float(re.match(r"\d+\.?\d*", _tolerance).group(0)) * 0.01
83 actual_value = _mantissa * 10 ** _multiplier
84 min_value = actual_value * (1 - tolerance_val)
85 max_value = actual_value * (1 + tolerance_val)
86 return actual_value, min_value, max_value