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