Parser of berki style problems and generator of latex file
Samo Penic
2018-11-03 c9c8d5997209b1f00b25a6bc2b7fa2b3fb186640
commit | author | age
91fb15 1 from . import Exceptions
5288d6 2 from math import floor, log10
d89217 3
7b5760 4 STRING = 1
SP 5 FLOAT = 2
6
7
8 class Variable:
7e7033 9     def __init__(self, value=None, formatting=None):
993a25 10         self.formatted_value = None
7b5760 11         try:
SP 12             self.value = float(value)
7e7033 13             self.type = FLOAT
7b5760 14         except (ValueError, TypeError):
SP 15             self.type = STRING
08b2a2 16             self.value = value
SP 17             self.formatted_value = value
7b5760 18         if formatting is not None:
33c054 19             self.format_float(formatting)
7b5760 20         self.formatting = formatting
08b2a2 21
SP 22     def is_float(self):
ce4fc9 23         if self.type == FLOAT:
08b2a2 24             return True
SP 25         else:
26             return False
7b5760 27
33c054 28     def format_float(self, formatting=None):
993a25 29         if formatting is None:
SP 30             formatting = self.formatting
31         formatter = FormatterFactory.get_formatter(formatting)
32         self.formatted_value = formatter.getValue(self.value)
7b5760 33
04ee9d 34     def format_as_tex(self, formatting=None, glyph=None, unit=None):
993a25 35         if formatting is None:
SP 36             formatting = self.formatting
04ee9d 37         formatter = FormatterFactory.get_formatter(formatting)
08b2a2 38         if formatting == "str":
04ee9d 39             return formatter.toFormat(self.value)
08b2a2 40         elif glyph is None and unit is None:
04ee9d 41             return ("${}$").format(formatter.toFormat(self.value))
08b2a2 42         elif glyph is None and unit is not None:
SP 43             return ("${}~\mathrm{{{}}}$").format(formatter.toFormat(self.value), unit)
44         elif glyph is not None and unit is None:
45             return ("${}={}$").format(glyph, formatter.toFormat(self.value))
04ee9d 46         else:
08b2a2 47             return ("${}={}~\mathrm{{{}}}$").format(
SP 48                 glyph, formatter.toFormat(self.value), unit
49             )
7b5760 50
04ee9d 51     def format_without_dollar(self, formatting=None):
SP 52         if formatting is None:
53             formatting = self.formatting
993a25 54         formatter = FormatterFactory.get_formatter(formatting)
SP 55         return formatter.toFormat(self.value)
7b5760 56
SP 57     def get_formatted_value(self):
993a25 58         return self.formatted_value
08b2a2 59         # if self.type != STRING else self.value
7b5760 60
ef19a9 61     def __str__(self):
SP 62         return str(self.format_as_tex())
63
78d798 64     def __repr__(self):
SP 65         return self.__str__()
66
7b5760 67
d89217 68 class FormatterFactory:
404823 69     @staticmethod
SP 70     def get_formatter(formatstring):
71         spl = formatstring.split()
72         type = spl[0]
73         arglist = spl[1:]
74
75         if type == "sci":
d89217 76             return SciFloatFormatter(arglist)
08b2a2 77         elif type == "str":
993a25 78             return StringFormatter()
08b2a2 79         elif type == "eng":
993a25 80             return EngFloatFormatter(arglist)
08b2a2 81         elif type == "dec":
993a25 82             return DecFloatFormatter(arglist)
404823 83         else:
SP 84             return None
5288d6 85
SP 86     @staticmethod
87     def fexp(f):
88         return int(floor(log10(abs(f)))) if f != 0 else 0
89
90     @staticmethod
91     def fman(f):
7b5760 92         return f / 10 ** FormatterFactory.fexp(f)
993a25 93
SP 94
95 class StringFormatter(FormatterFactory):
96     def __init__(self):
97         pass
98
99     def toFormat(self, string):
100         return string
101
102     def getValue(self, string):
103         return string
404823 104
SP 105
d89217 106 class SciFloatFormatter(FormatterFactory):
SP 107     def __init__(self, formatparameters):
404823 108         if len(formatparameters) != 1:
91fb15 109             raise Exceptions.WrongParameters("Sci format accept only one argument")
404823 110         self.precision = int(formatparameters[0])
SP 111
112     def toFormat(self, num):
113         try:
114             num = float(num)
115         except ValueError:
116             raise ValueError
117         except TypeError:
118             raise ValueError
119
7b5760 120         exp = self.fexp(num)
SP 121         man = self.fman(num)
78d798 122         if exp == 0:
08b2a2 123             return (
SP 124                 ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
125             )
78d798 126         else:
08b2a2 127             return (
SP 128                 ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
129                 .format(man, int(exp))
130                 .replace(".", ",\!")
78d798 131             )
d89217 132
33c054 133     def getValue(self, num):
SP 134         exp = self.fexp(num)
135         man = self.fman(num)
78d798 136         man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
33c054 137         return float(man)
d89217 138
78d798 139
ce4fc9 140 class EngFloatFormatter(FormatterFactory):
d89217 141     def __init__(self, formatparameters):
SP 142         if len(formatparameters) != 1:
143             raise Exceptions.WrongParameters("Eng format accept only one argument")
144         self.precision = int(formatparameters[0])
145
ce4fc9 146     def realign3(self, exp, man):
SP 147         mul = exp % 3
148         man = man * 10 ** mul
149         exp = exp - mul
150         return (exp, man)
151
d89217 152     def toFormat(self, num):
SP 153         try:
154             num = float(num)
ce4fc9 155         except ValueError:
d89217 156             raise ValueError
ce4fc9 157         except TypeError:
SP 158             raise ValueError
5288d6 159
ce4fc9 160         exp = self.fexp(num)
SP 161         man = self.fman(num)
162         (exp, man) = self.realign3(exp, man)
163         if exp == 0:
164             return (
165                 ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
166             )
167         else:
168             return (
169                 ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
170                 .format(man, int(exp))
171                 .replace(".", ",\!")
172             )
173
174     def getValue(self, num):
175         exp = self.fexp(num)
176         man = self.fman(num)
177         man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
178         return float(man)
179
180
181 class DecFloatFormatter(EngFloatFormatter):
182     def __init__(self, formatparameters):
183         if len(formatparameters) != 1:
184             raise Exceptions.WrongParameters("Dec format accept only one argument")
185         self.precision = int(formatparameters[0])
186
187     def exp2prefix(self, exp):
188         prefixes = {
189             "24": "Y",
190             "21": "Z",
191             "18": "E",
192             "15": "P",
193             "12": "T",
194             "9": "G",
195             "6": "M",
196             "3": "k",
197             "-3": "m",
198             "-6":"\\upmu",
199             "-9":"n",
200             "-12":"p",
201             "-15":"f",
202             "-18":"a",
203             "-21":"z",
204             "-24":"y"
205         }
206         try:
207             prefix = prefixes[str(exp)]
208         except KeyError:
209             raise Exceptions.PrefixError("Could not change exponent " + str(exp) + " into prefix form!")
210         return prefix
211
212
213     def toFormat(self, num):
214         try:
215             num = float(num)
216         except ValueError:
217             raise ValueError
218         except TypeError:
219             raise ValueError
220
221         exp = self.fexp(num)
222         man = self.fman(num)
223         (exp, man) = self.realign3(exp, man)
224         if exp == 0:
225             return (
226                 ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
227             )
228         else:
229             prefix = self.exp2prefix(exp)
230             return (
231                 ("{:." + str(self.precision - 1) + "f}~\mathrm{{{}}}")
232                 .format(man, prefix)
233                 .replace(".", ",\!")
234             )