File size: 10,456 Bytes
389d072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import copy


class Function(object):
    """Basis function class for all functions

    The Function class forms the basis for the functions tokens of all types.
    """

    def __init__(self):
        self.tid = None
        self.scope = None
        self.value = None
        self.coefficient = 1
        self.power = 1
        self.operand = None
        self.operator = None
        self.before = None
        self.after = None
        self.beforeScope = None
        self.afterScope = None

    def __str__(self, nv=None, np=None, nc=None):
        """Equation token to string

        Coverts equation tokens to string for text and LaTeX rendering

        Keyword Arguments:
            nv {int} -- number of values (default: {None})
            np {int} -- number of powers (default: {None})
            nc {int} -- number of coefficients (default: {None})

        Returns:
            represent {string} -- string/latex representation of equation
        """
        # OPTIMIZE: Works but a mess. Organize and add comments
        represent = ""

        if np is None and nv is None and nc is None:
            if self.coefficient != 1:
                represent += str(self.coefficient)
        elif nc is not None:
            if self.coefficient[nc] != 1:
                represent += str(self.coefficient[nc])

        if isinstance(self.value, list):
            if nv is None and np is None:
                for eachValue, eachPower in zip(self.value, self.power):
                    represent += "{" + str(eachValue) + "}"
                    if eachPower != 1:
                        represent += "^" + "{" + str(eachPower) + "}"
            elif nc is None:
                represent += "{" + str(self.value[nv]) + "}"
                if self.power[np] != 1:
                    represent += "^" + "{" + str(self.power[np]) + "}"
            elif nc is not None:
                for i, val in enumerate(self.value):
                    represent += "{" + str(val) + "}"
                    if self.power[np][i] != 1:
                        represent += "^" + "{" + str(self.power[np][i]) + "}"
        elif self.operand is not None:
            represent += "\\" + self.value
            if self.power != 1:
                represent += "^" + "{" + str(self.power) + "}"
            represent += "({" + self.operand.__str__() + "})"
        else:
            represent += "{" + str(self.value) + "}"
            if self.power != 1:
                represent += "^" + "{" + str(self.power) + "}"

        return represent

    def prop(self, tid=None, scope=None, value=None, coeff=None, power=None, operand=None, operator=None):
        """Set function token properties

        Keyword Arguments:
            tid {[type]} -- Token ID (default: {None})
            scope {int} -- Scope (default: {None})
            value {int or list} -- Value (default: {None})
            coeff {int} -- Coefficient (default: {None})
            power {int or list} -- Power (default: {None})
            operand {visma.functions.structure.Function} -- Operand (default: {None})
            operator {visma.functions.structure.Function} -- Operator (default: {None})
        """
        if tid is not None:
            self.tid = tid
        if scope is not None:
            self.scope = scope
        if value is not None:
            self.value = value
        if coeff is not None:
            self.coefficient = coeff
        if power is not None:
            self.power = power
        if operand is not None:
            self.operand = operand
        if operator is not None:
            self.operator = operator

    def differentiate(self):
        """Differentiate function token
        """
        self.power = 1
        self.coefficient = 1

    def level(self):
        """Level of function token
        """
        return (int((len(self.tid)) / 2)), 5

    def functionOf(self):
        inst = copy.deepcopy(self)
        while inst.operand is not None:
            inst = inst.operand
        return inst.value

    def isZero(self):
        """
        It checks if the Function is equal to Zero or not, to decide it should be Added, Subtracted,...etc. or not.
        :returns: bool
        """
        if (self.value == 0 and self.power != 0) or self.coefficient == 0:
            return True
        return False


##########
# FuncOp #
##########

class FuncOp(Function):
    """Defined for functions of form sin(...), log(...), exp(...) etc which take a function(operand) as argument
    """
    def __init__(self, operand=None):
        super().__init__()
        if operand is not None:
            self.operand = operand

    def __str__(self):
        represent = ""
        represent += "\\" + self.value
        if self.power != 1:
            represent += "^" + "{" + str(self.power) + "}"
        if self.operand is not None:
            represent += "{(" + str(self.operand) + ")}"
        return represent

    def inverse(self, rToken, wrtVar, inverseFunction):
        """Returns inverse of function

        Applies inverse of function to RHS and LHS.

        Arguments:
            rToken {visma.functions.structure.Function} -- RHS token
            wrtVar {string} -- with respect to variable
            inverseFunction {visma.functions.structure.Function} -- inverse of the function itself

        Returns:
            self {visma.functions.structure.Function} -- function itself(operand before inverse)
            rToken {visma.functions.structure.Function} -- new RHS token
            comment {string} -- steps comment
        """
        rToken.coefficient /= self.coefficient
        rToken.power /= self.power
        invFunc = copy.deepcopy(inverseFunction)
        invFunc.operand = rToken
        self = self.operand
        comment = "Applying inverse function on LHS and RHS"
        return self, rToken, comment


###################
# Mixed Functions #
###################
# For example: sec(x)*tan(x) or sin(x)*log(x) or e^(x)*cot(x)
# Will be taken care by function Expression


class Expression(Function):
    """Class for expression type
    """

    def __init__(self, tokens=None, coefficient=None, power=None):
        super().__init__()
        if coefficient is not None:
            self.coefficient = coefficient
        else:
            self.coefficient = 1
        if power is not None:
            self.power = power
        else:
            self.power = 1
        self.tokens = []
        if tokens is not None:
            self.tokens.extend(tokens)

    def __str__(self):
        represent = ""
        if self.coefficient != 1:
            represent += str(self.coefficient) + "*"
        represent += "{("
        for token in self.tokens:
            represent += token.__str__()
        represent += ")}"
        if self.power != 1:
            represent += "^" + "{" + str(self.power) + "}"
        if self.operand is not None:
            represent += "{(" + str(self.operand) + ")}"
        return represent

    def __mul__(self, other):
        from visma.functions.constant import Constant
        from visma.functions.variable import Variable

        if isinstance(other, Expression):
            result = Expression()
            for i, _ in enumerate(self.tokens):
                c = copy.deepcopy(self)
                d = copy.deepcopy(other)
                if isinstance(c.tokens[i], Constant) or isinstance(c.tokens[i], Variable):
                    result.tokens.extend([c.tokens[i] * d])
                else:
                    result.tokens.extend([c.tokens[i]])
            return result

    def __add__(self, other):
        from visma.functions.constant import Constant
        from visma.functions.variable import Variable
        from visma.functions.operator import Plus
        if isinstance(other, Expression):
            result = Expression()
            for tok1 in self.tokens:
                result.tokens.append(tok1)
            result.tokens.append(Plus())
            if (other.tokens[0], Constant):
                if (other.tokens[0].value < 0):
                    result.tokens.pop()
            elif (other.tokens[0], Variable):
                if (other.tokens[0].coefficient < 0):
                    result.tokens.pop()
            for tok2 in other.tokens:
                result.tokens.append(tok2)
            return result
        elif isinstance(other, Constant):
            result = self
            constFound = False
            for i, _ in enumerate(self.tokens):
                if isinstance(self.tokens[i], Constant):
                    self.tokens[i] += other
                    constFound = True
            if constFound:
                return result
            else:
                result.tokens += other
                return result
        elif isinstance(other, Variable):
            result = Expression()
            result = other + self
            return result

    def __sub__(self, other):
        from visma.functions.constant import Constant
        from visma.functions.variable import Variable
        from visma.functions.operator import Plus, Minus
        if isinstance(other, Expression):
            result = Expression()
            for tok1 in self.tokens:
                result.tokens.append(tok1)
            for _, x in enumerate(other.tokens):
                if x.value == '+':
                    x.value = '-'
                elif x.value == '-':
                    x.value = '+'
            result.tokens.append(Minus())
            if (isinstance(other.tokens[0], Constant)):
                if (other.tokens[0].value < 0):
                    result.tokens[-1] = Plus()
                    other.tokens[0].value = abs(other.tokens[0].value)
            elif (isinstance(other.tokens[0], Variable)):
                if (other.tokens[0].coefficient < 0):
                    result.tokens[-1] = Plus()
                    other.tokens[0].coefficient = abs(other.tokens[0].coefficient)
            return result
        elif isinstance(other, Constant):
            result = self
            result += (Constant(0) - other)
            return result
        elif isinstance(other, Variable):
            result = self
            a = Constant(0) - other
            result = a + result
            return result


class Equation(Expression):
    """Class for equation type
    """

    def __init__(self):
        super().__init__()
        self.tokens = None