Parser of berki style problems and generator of latex file
Samo Penic
2018-11-15 e8d6264e6cc2cb055dea30f9498fdcf4e771ebbc
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
from . import Exceptions
from math import floor, log10
 
STRING = 1
FLOAT = 2
 
 
class Variable:
    def __init__(self, value=None, formatting=None):
        self.formatted_value = None
        try:
            self.value = float(value)
            self.type = FLOAT
        except (ValueError, TypeError):
            self.type = STRING
            self.value = value
            self.formatted_value = value
        if formatting is not None:
            self.format_float(formatting)
        self.formatting = formatting
 
    def is_float(self):
        if self.type == FLOAT:
            return True
        else:
            return False
 
    def format_float(self, formatting=None):
        if formatting is None:
            formatting = self.formatting
        formatter = FormatterFactory.get_formatter(formatting)
        self.formatted_value = formatter.getValue(self.value)
 
    def format_as_tex(self, formatting=None, glyph=None, unit=None, dollar="$"):
        if formatting is None:
            formatting = self.formatting
        formatter = FormatterFactory.get_formatter(formatting)
        if formatting.split()[0] == "prefix":
            leading_space = ""
        else:
            leading_space = "~"
        if formatting == "str" or formatting == "string":
            return formatter.toFormat(self.value)
        elif glyph is None and unit is None:
            return ("{}{}{}{}").format(
                dollar, formatter.toFormat(self.value), leading_space, dollar
            )
        elif glyph is None and unit is not None:
            return ("{}{}{}\mathrm{{{}}}{}{}").format(
                dollar, formatter.toFormat(self.value), leading_space, unit, dollar
            )
        elif glyph is not None and unit is None:
            return ("{}{}={}{}{}").format(
                dollar, glyph, formatter.toFormat(self.value), leading_space, dollar
            )
        else:
            return ("{}{}={}{}\mathrm{{{}}}{}").format(
                dollar,
                glyph,
                formatter.toFormat(self.value),
                leading_space,
                unit,
                dollar,
            )
 
    def get_formatted_value(self):
        return self.formatted_value
        # if self.type != STRING else self.value
 
    def __str__(self):
        return str(self.format_as_tex())
 
    def __repr__(self):
        return self.__str__()
 
 
class FormatterFactory:
    @staticmethod
    def get_formatter(formatstring):
        spl = formatstring.split()
        type = spl[0]
        arglist = spl[1:]
 
        if type == "sci" or type == "scientific":
            return SciFloatFormatter(arglist)
        elif type == "str" or type == "string":
            return StringFormatter()
        elif type == "eng" or type == "engineering":
            return EngFloatFormatter(arglist)
        elif type == "prefix":
            return PrefixFloatFormatter(arglist)
        elif type == "dec" or type == "decimal":
            return EngFloatFormatter(arglist)  # fallback to engineering
        else:
            return None
 
    @staticmethod
    def fexp(f):
        return int(floor(log10(abs(f)))) if f != 0 else 0
 
    @staticmethod
    def fman(f):
        return f / 10 ** FormatterFactory.fexp(f)
 
 
class StringFormatter(FormatterFactory):
    def __init__(self):
        pass
 
    def toFormat(self, string):
        return string
 
    def getValue(self, string):
        return string
 
 
class SciFloatFormatter(FormatterFactory):
    def __init__(self, formatparameters):
        if len(formatparameters) != 1:
            raise Exceptions.WrongParameters("Sci format accept only one argument")
        self.precision = int(formatparameters[0])
 
    def toFormat(self, num):
        try:
            num = float(num)
        except ValueError:
            raise ValueError
        except TypeError:
            raise ValueError
 
        exp = self.fexp(num)
        man = self.fman(num)
        if exp == 0:
            return (
                ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
            )
        else:
            return (
                ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
                .format(man, int(exp))
                .replace(".", ",\!")
            )
 
    def getValue(self, num):
        exp = self.fexp(num)
        man = self.fman(num)
        man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
        return float(man)
 
 
class EngFloatFormatter(FormatterFactory):
    def __init__(self, formatparameters):
        if len(formatparameters) != 1:
            raise Exceptions.WrongParameters("Eng format accept only one argument")
        self.precision = int(formatparameters[0])
 
    def realign3(self, exp, man):
        mul = exp % 3
        man = man * 10 ** mul
        exp = exp - mul
        return (exp, man)
 
    def toFormat(self, num):
        try:
            num = float(num)
        except ValueError:
            raise ValueError
        except TypeError:
            raise ValueError
 
        exp = self.fexp(num)
        man = self.fman(num)
        (exp, man) = self.realign3(exp, man)
        if exp == 0:
            return (
                ("{:." + str(self.precision - 1) + "f}").format(man).replace(".", ",\!")
            )
        else:
            return (
                ("{:." + str(self.precision - 1) + "f} \cdot 10^{{{}}}")
                .format(man, int(exp))
                .replace(".", ",\!")
            )
 
    def getValue(self, num):
        exp = self.fexp(num)
        man = self.fman(num)
        man = ("{:." + str(self.precision - 1) + "f}e{}").format(man, int(exp))
        return float(man)
 
 
class PrefixFloatFormatter(EngFloatFormatter):
    def __init__(self, formatparameters):
        if len(formatparameters) != 1:
            raise Exceptions.WrongParameters("Dec format accept only one argument")
        self.precision = int(formatparameters[0])
 
    def exp2prefix(self, exp):
        prefixes = {
            "24": "Y",
            "21": "Z",
            "18": "E",
            "15": "P",
            "12": "T",
            "9": "G",
            "6": "M",
            "3": "k",
            "-3": "m",
            "-6": "\\upmu",
            "-9": "n",
            "-12": "p",
            "-15": "f",
            "-18": "a",
            "-21": "z",
            "-24": "y",
        }
        try:
            prefix = prefixes[str(exp)]
        except KeyError:
            raise Exceptions.PrefixError(
                "Could not change exponent " + str(exp) + " into prefix form!"
            )
        return prefix
 
    def toFormat(self, num):
        try:
            num = float(num)
        except ValueError:
            raise ValueError
        except TypeError:
            raise ValueError
 
        exp = self.fexp(num)
        man = self.fman(num)
        (exp, man) = self.realign3(exp, man)
        if exp == 0:
            return (
                ("{:." + str(self.precision - 1) + "f}~").format(man).replace(".", ",\!")
            )
        else:
            prefix = self.exp2prefix(exp)
            return (
                ("{:." + str(self.precision - 1) + "f}~\mathrm{{{}}}")
                .format(man, prefix)
                .replace(".", ",\!")
            )