-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
217 lines (164 loc) · 7.76 KB
/
app.py
File metadata and controls
217 lines (164 loc) · 7.76 KB
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
import sys
from PySide2 import QtWidgets,QtGui
from MainWindow import Ui_MainWindow
import sympy as sp
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
import numpy as np
class MplCanvas(FigureCanvasQTAgg):
''' this class used for embedding matplotlib plots inside a Qt application '''
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super().__init__(fig)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
# setup ui that generated from Qt designer
self.setupUi(self)
self.setWindowIcon(QtGui.QIcon("./image/acorn.png")) # Set the app icon
self.setWindowTitle("function solver")
self.setMinimumWidth(1200)
self.pushButtonSubmit.clicked.connect(self.submitButtonWasClicked)
self.labelInvalidFunctionTwo.setText("")
self.labelInvalidFunctionOne.setText("")
# create instance to get the Figure then we can add it to the layout
self.canvas = MplCanvas(self, width=5, height=4, dpi=100)
# Apply dark mode styling to the plot
self.canvas.figure.patch.set_facecolor('#0c0e16')
self.canvas.axes.set_facecolor('#0c0e16')
self.canvas.axes.tick_params(axis='both', colors='white')
self.canvas.axes.spines['top'].set_color('white')
self.canvas.axes.spines['right'].set_color('white')
self.canvas.axes.spines['left'].set_color('white')
self.canvas.axes.spines['bottom'].set_color('white')
self.canvas.axes.grid(True, color='gray', linestyle='--', linewidth=0.5)
# add plot Figure to Qt app and set stretch equal between input form and figure
self.horizontalLayout.addWidget(self.canvas)
self.horizontalLayout.setStretch(0, 1)
self.horizontalLayout.setStretch(1, 1)
def submitButtonWasClicked(self):
# Clear the canvas.
self.canvas.axes.cla()
self.canvas.axes.grid(True, color='gray', linestyle='--', linewidth=0.5)
self.canvas.draw()
# get function input from user
FunctionOne = self.lineEditFunctionOne.text()
FunctionTwo = self.lineEditFunctionTwo.text()
# check validity of (operators & brackets)
FunctionOneValidity = self.functionValidation(FunctionOne, self.labelInvalidFunctionOne)
FunctionTwoValidity = self.functionValidation(FunctionTwo, self.labelInvalidFunctionTwo)
# convert string to match sympy by converting (^ -> **)
FunctionOneString=""
FunctionTwoString=""
if(FunctionOneValidity and FunctionTwoValidity):
for char in FunctionOne:
if char == '^':
FunctionOneString += "**"
else :
FunctionOneString+=char
for char in FunctionTwo:
if char == '^':
FunctionTwoString += "**"
else :
FunctionTwoString+=char
# now we are ready to solve two functions
self.solveFunctions(FunctionOneString, FunctionTwoString)
def functionValidation(self, s, label):
# valid operators
valid_characters = {'+', '-', '*', '/', '^', '(', ')', ' ', 'x', 'X'}
i = 0
# first we make sure that user write equation
if len(s) == 0:
label.setText("Write equation.")
return False
''' simply we check if we have valid strings (operators) between the function using substr and we make sure that sqrt() and log10() not empty '''
while i < len(s):
char = s[i]
if char.isdigit() or char in valid_characters:
i+=1
continue
elif (s[i:i+5] == "sqrt(" and s[i+5].isdigit()) or (s[i:i+6] == "log10(" and s[i+5].isdigit()):
i+=5
else :
label.setText("supported operators: + - / * ^ log10() sqrt().")
return False
# here to check if there is any missing bracket
cnt=0
for char in s:
if char != ')' and char != '(':
continue
if char == '(':
cnt +=1
elif char == ')' and cnt:
cnt -=1
else :
label.setText("invalid input: there's a missing bracket.")
return False
if(cnt):
label.setText("invalid input: there's a missing bracket.")
return False
# function is valid
label.setText("")
return True
def solveFunctions(self, FunctionOneString, FunctionTwoString):
# first we define symbol
x = sp.symbols('x')
# i put it in try-except to catch any invalid syntax
try :
self.firstFunction_symbolic = sp.sympify(FunctionOneString)
except (sp.SympifyError, Exception) as e:
self.labelInvalidFunctionOne.setText("Invalid syntax")
return
try :
self.secondFunction_symbolic = sp.sympify(FunctionTwoString)
except (sp.SympifyError, Exception) as e:
self.labelInvalidFunctionTwo.setText("Invalid syntax")
return
# setup the equation
equation = sp.Eq(self.firstFunction_symbolic, self.secondFunction_symbolic)
# solve the equation
self.solution = sp.solve(equation, x)
# get rid of complex number
real_solutions = [sol for sol in self.solution if sol.is_real]
self.solution=real_solutions
# we are ready to plot the graph
self.plotGraph(x)
def plotGraph(self, x):
# get solution points in (x, y) form x in x_points_answer , y in y_points_answer
x_points_answer = self.solution
x_points_answer = [int(float(val)) if float(val).is_integer() else round(float(val),1) for val in x_points_answer]
y_points_answer = [float(self.firstFunction_symbolic.subs(x, val)) for val in x_points_answer]
y_points_answer = [int(val) if val.is_integer() else round(val,1) for val in y_points_answer]
# setup minmum and maximux point in x-axis
mn=-10
mx=10
if len(self.solution) > 0:
mn=float(min(x_points_answer)-3)
mx=float(max(x_points_answer)+3)
# get values of for x to draw the graph
x_vals = np.linspace(mn, mx, 400)
# get y values for first and second function
y_firstFunction = [float(self.firstFunction_symbolic.subs(x, val)) for val in x_vals]
y_secondFunction = [float(self.secondFunction_symbolic.subs(x, val)) for val in x_vals]
# plot two functions
self.canvas.axes.plot(x_vals, y_firstFunction, color='blue', label=f'F(x):{self.lineEditFunctionOne.text()}')
self.canvas.axes.plot(x_vals, y_secondFunction, color='red',label=f'S(x):{self.lineEditFunctionTwo.text()}')
# show labels of functions
self.canvas.axes.legend(loc='upper center', fontsize=12)
# draw solution poits
self.canvas.axes.scatter(x_points_answer, y_points_answer,marker='x',color='green',s=100,zorder=5)
# mark solution points with it's coordinates
for i in range(len(x_points_answer)):
self.canvas.axes.text(x_points_answer[i], y_points_answer[i] + .2,
f'({(x_points_answer[i])}, {(y_points_answer[i])})',
color='white', fontsize=15)
# draw the graph
self.canvas.draw()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()