Parser of berki style problems and generator of latex file
Samo Penic
2018-11-24 e0e8d373e6ebd897010753d0259468b68509a5bf
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):
e0e8d3 111         return string.replace("\"", "")
993a25 112
SP 113     def getValue(self, string):
e0e8d3 114         return "\"{}\"".format(str(string.replace("\"", "")))
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
34c8f6 130         num=float(("{:."+str(self.precision-1)+"e}").format(num))
SP 131         places=self.fexp(num)
132
8fe4d9 133         decimal_places=self.precision-places-1
SP 134         if(decimal_places<0):
135             decimal_places=0
136         format_str="{:"+str(places)+"."+str(decimal_places)+"f}"
839d16 137
8fe4d9 138         return format_str.format(num).replace(".", ",\!")
34c8f6 139
839d16 140
SP 141     def getValue(self, num):
34c8f6 142
SP 143
144         num=float(("{:."+str(self.precision-1)+"e}").format(num))
145         places=self.fexp(num)
146
8fe4d9 147         decimal_places=self.precision-places-1
SP 148         if(decimal_places<0):
149             decimal_places=0
150         format_str="{:"+str(places)+"."+str(decimal_places)+"f}"
34c8f6 151         val=format_str.format(num)
839d16 152         return float(val)
SP 153
154
404823 155
d89217 156 class SciFloatFormatter(FormatterFactory):
SP 157     def __init__(self, formatparameters):
404823 158         if len(formatparameters) != 1:
91fb15 159             raise Exceptions.WrongParameters("Sci format accept only one argument")
404823 160         self.precision = int(formatparameters[0])
SP 161
162     def toFormat(self, num):
163         try:
164             num = float(num)
165         except ValueError:
166             raise ValueError
167         except TypeError:
168             raise ValueError
169
7b5760 170         exp = self.fexp(num)
SP 171         man = self.fman(num)
78d798 172         if exp == 0:
08b2a2 173             return (
SP 174                 ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
175             )
78d798 176         else:
08b2a2 177             return (
SP 178                 ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
179                 .format(man, int(exp))
180                 .replace(".", ",\!")
78d798 181             )
d89217 182
33c054 183     def getValue(self, num):
SP 184         exp = self.fexp(num)
185         man = self.fman(num)
78d798 186         man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
33c054 187         return float(man)
d89217 188
78d798 189
ce4fc9 190 class EngFloatFormatter(FormatterFactory):
d89217 191     def __init__(self, formatparameters):
SP 192         if len(formatparameters) != 1:
193             raise Exceptions.WrongParameters("Eng format accept only one argument")
194         self.precision = int(formatparameters[0])
195
ce4fc9 196     def realign3(self, exp, man):
SP 197         mul = exp % 3
198         man = man * 10 ** mul
199         exp = exp - mul
200         return (exp, man)
201
d89217 202     def toFormat(self, num):
SP 203         try:
204             num = float(num)
ce4fc9 205         except ValueError:
d89217 206             raise ValueError
ce4fc9 207         except TypeError:
SP 208             raise ValueError
5288d6 209
ce4fc9 210         exp = self.fexp(num)
SP 211         man = self.fman(num)
212         (exp, man) = self.realign3(exp, man)
213         if exp == 0:
214             return (
215                 ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
216             )
217         else:
218             return (
219                 ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
220                 .format(man, int(exp))
221                 .replace(".", ",\!")
222             )
223
224     def getValue(self, num):
225         exp = self.fexp(num)
226         man = self.fman(num)
227         man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
228         return float(man)
229
230
5bc997 231 class PrefixFloatFormatter(EngFloatFormatter):
ce4fc9 232     def __init__(self, formatparameters):
SP 233         if len(formatparameters) != 1:
234             raise Exceptions.WrongParameters("Dec format accept only one argument")
235         self.precision = int(formatparameters[0])
236
237     def exp2prefix(self, exp):
238         prefixes = {
239             "24": "Y",
240             "21": "Z",
241             "18": "E",
242             "15": "P",
243             "12": "T",
244             "9": "G",
245             "6": "M",
246             "3": "k",
247             "-3": "m",
da1010 248             "-6": "\\upmu",
SP 249             "-9": "n",
250             "-12": "p",
251             "-15": "f",
252             "-18": "a",
253             "-21": "z",
254             "-24": "y",
ce4fc9 255         }
SP 256         try:
257             prefix = prefixes[str(exp)]
258         except KeyError:
da1010 259             raise Exceptions.PrefixError(
SP 260                 "Could not change exponent " + str(exp) + " into prefix form!"
261             )
ce4fc9 262         return prefix
SP 263
264     def toFormat(self, num):
265         try:
266             num = float(num)
267         except ValueError:
268             raise ValueError
269         except TypeError:
270             raise ValueError
271
272         exp = self.fexp(num)
273         man = self.fman(num)
274         (exp, man) = self.realign3(exp, man)
275         if exp == 0:
276             return (
39922f 277                 ("{:." + str(self.precision - 1) + "f}\,").format(man).replace(".", ",\!")
ce4fc9 278             )
SP 279         else:
280             prefix = self.exp2prefix(exp)
281             return (
39922f 282                 ("{:." + str(self.precision - 1) + "f}\,\mathrm{{{}}}")
ce4fc9 283                 .format(man, prefix)
SP 284                 .replace(".", ",\!")
285             )