-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
423 lines (376 loc) · 17.7 KB
/
main.py
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import importlib
import matplotlib.pyplot as plt
import numpy as np
from PyQt4 import QtGui, QtCore, uic
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from sympy import *
from sympy.core.sympify import SympifyError
from methods_options import Ui_Dialog
from resultset import ResultSet
from util import sliceEquations, parseFloats, matrixToVector, load, cloneMatrix, save
plt.rc('text', usetex=True)
plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'
qtCreatorFile = "window.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class NewNavigationToolbar(NavigationToolbar):
toolitems = [t for t in NavigationToolbar.toolitems if
t[0] in ('Home', 'Pan', 'Zoom', 'Save')]
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
solveButtonTrigger = QtCore.pyqtSignal()
methodsCheckMap = None
Dialog = None
dialogUI = None
rootPlot = None
text = None
isValidEquation = False
methodsCheckMapAlias = {}
tempResultSets = []
tempTables = []
tempFloatA = []
tempFloatB = []
tempVars = []
initialGaussSeidel = []
figs = []
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.setWindowTitle("Linear-Equation-Solver by M&H")
self.figs = [(Figure(), [self.rootPlot, self.mplvl3, self.mplwindow3])]
self.init_Figure()
intValidator = QtGui.QIntValidator()
intValidator.setBottom(1)
self.maxItersField.setValidator(intValidator)
self.maxItersField.setPlaceholderText("50 by default")
floatValidator = QtGui.QDoubleValidator()
floatValidator.setBottom(0)
self.epsField.setValidator(floatValidator)
self.epsField.setPlaceholderText("0.00001 by default")
self.solveButton.setEnabled(False)
self.solveButton.clicked.connect(self.solveEquations)
self.resultsTabWidget.clear()
self.resultsTabWidget.currentChanged.connect(self.handleResultTabChanging)
self.methodsButton.clicked.connect(self.handleMethodsButton)
self.textAreaRadio.toggled.connect(self.handleRadioButtons)
self.textAreaRadio.toggle()
number_group = QtGui.QButtonGroup(self) # Number group
number_group.addButton(self.textAreaRadio)
number_group.addButton(self.fileRadio)
self.exportButton.setDisabled(True)
self.exportButton.clicked.connect(self.openSaveFileDialog)
self.loadFileButton.setDisabled(True)
self.loadFileButton.clicked.connect(self.openLoadFileDialog)
self.fileRadio.toggled.connect(self.handleRadioButtons)
self.matrixInputArea.textChanged.connect(self.drawMatrix)
self.Dialog = QtGui.QDialog()
self.dialogUI = Ui_Dialog()
self.dialogUI.setupUi(self.Dialog)
self.methodsCheckMap = {self.dialogUI.gaussEliminationCheckBox: [],
self.dialogUI.gaussJordanCheckBox: [],
self.dialogUI.luDecompositionCheckBox: [],
self.dialogUI.gaussSeidelCheckBox: [self.dialogUI.gaussSeidelInitialGuessField]}
self.solveButtonTrigger.connect(self.handleSolveButton)
self.cloneOptionsMapInfo()
self.initOptionsHandlers()
self.variablesComboBox.currentIndexChanged.connect(self.updateTables)
@QtCore.pyqtSlot()
def solveEquations(self):
self.clearAll()
errs = ''
((A, vars), B) = sliceEquations(str(self.matrixInputArea.toPlainText()))
self.tempFloatA = parseFloats(A)
self.tempFloatB = parseFloats(B)
self.tempVars = vars
for (key, val) in self.methodsCheckMapAlias.items():
if val[0]:
method = str(key.objectName())
try:
if method == 'gauss_seidel':
self.drawResultSet(
getattr(importlib.import_module('methods.' + method), method)(cloneMatrix(self.tempFloatA),
cloneMatrix(self.tempFloatB),
self.initialGaussSeidel,
variables=matrixToVector(
vars),
iterations=int(
self.maxItersField.text() if self.maxItersField.text() else 50),
eps=float(
self.epsField.text() if self.epsField.text() else 0.00001)))
else:
self.drawResultSet(
getattr(importlib.import_module('methods.' + method), method)(cloneMatrix(self.tempFloatA),
cloneMatrix(self.tempFloatB),
variables=matrixToVector(
vars),
iterations=int(
self.maxItersField.text() if self.maxItersField.text() else 50),
eps=float(
self.epsField.text() if self.epsField.text() else 0.00001)))
except:
if not errs:
errs += method
else:
errs += ', ' + method
if errs:
self.showErrorMessage(errs + '.')
if len(self.tempResultSets) != 0:
self.exportButton.setDisabled(len(self.tempResultSets) == 0)
self.variablesComboBox.addItems([vars[i][0] for i in xrange(len(vars))])
@QtCore.pyqtSlot()
def handleMethodsButton(self):
if self.Dialog.exec_():
self.cloneOptionsMapInfo()
self.solveButtonTrigger.emit()
else:
self.pasteToOptionsMapInfo()
@QtCore.pyqtSlot(int)
def handleResultTabChanging(self, index):
for tab in self.tempTables:
tab.clearSelection()
try:
vars = []
for i in xrange(len(self.tempVars)):
subVar = []
for j in xrange(len(self.tempVars[i])):
subVar.append(self.tempVars[i][j] + '=' + str(self.tempResultSets[index].getSolution()[i][j]))
vars.append(subVar)
# print latex(Eq(
# MatMul(Matrix(self.tempFloatA),
# Matrix(self.tempResultSets[index].getSolution()), evaluate=False),
# Matrix(self.tempFloatB), evaluate=False), mode='inline')
self.text.set_text(latex(Eq(
MatMul(Matrix(self.tempFloatA),
Matrix(self.tempResultSets[index].getSolution()), evaluate=False),
Matrix(self.tempFloatB), evaluate=False), mode='inline'))
except (SympifyError, ValueError) as e:
print e
self.figure.canvas.draw()
@QtCore.pyqtSlot()
def openSaveFileDialog(self):
fname = QtGui.QFileDialog.getSaveFileName(self, 'Save equation',
'', "All (*.*)")
if fname:
save(fname, self.tempResultSets)
@QtCore.pyqtSlot()
def openLoadFileDialog(self):
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open equation',
'', "All (*.*)")
if fname:
load(fname, self, self.dialogUI)
self.cloneOptionsMapInfo()
self.solveButtonTrigger.emit()
@QtCore.pyqtSlot()
def handleRadioButtons(self):
self.matrixInputArea.setReadOnly(
True) if not self.textAreaRadio.isChecked() else self.matrixInputArea.setReadOnly(
False)
self.loadFileButton.setDisabled(True) if not self.fileRadio.isChecked() else self.loadFileButton.setDisabled(
False)
@QtCore.pyqtSlot()
def drawMatrix(self):
((A, vars), B) = sliceEquations(str(self.matrixInputArea.toPlainText()))
try:
self.text.set_text(latex(Eq(
MatMul(Matrix(A),
Matrix(vars), evaluate=False),
Matrix(B), evaluate=False), mode='inline'))
except (SympifyError, ValueError) as e:
print e
self.figure.canvas.draw()
self.solveButtonTrigger.emit()
@QtCore.pyqtSlot()
def handleSolveButton(self):
chosenMethod = False
validInputs = False
((A, vars), B) = sliceEquations(str(self.matrixInputArea.toPlainText()))
for (state, val) in self.methodsCheckMapAlias.values():
if state:
chosenMethod = True
try:
parseFloats(A)
parseFloats(B)
lis = []
if len(val) != 0:
lis = val[0].split(',')
for i in xrange(len(lis)):
if not lis[i]:
lis[i] = 0.0
else:
lis[i] = float(lis[i])
self.initialGaussSeidel = lis[:]
validInputs = True and (len(lis) == 0 or len(lis) == len(vars)) and (len(vars) <= len(A))
except:
validInputs = False
self.solveButton.setEnabled(validInputs and chosenMethod)
@QtCore.pyqtSlot(int)
def updateTables(self, index):
item = str(self.variablesComboBox.itemText(index))
self.clearPlots()
for i in xrange(len(self.tempResultSets)):
if len(self.tempResultSets[i].getRoots().keys()) != 0:
self.plotRoot(self.tempResultSets[i].getRoots()[item])
table = self.tempResultSets[i].getTables()[item]
qTable = self.tempTables[i]
qTable.parentWidget().findChild(QtGui.QLineEdit, "Precision").setText(
str(self.tempResultSets[i].getPrecisions()[item]))
qTable.setColumnCount(len(table.getHeader()))
qTable.setRowCount(len(table.getData()))
qTable.setHorizontalHeaderLabels(table.getHeader())
for row in xrange(len(table.getData())):
for column in xrange(len(table.getHeader())):
qTable.setItem(row, column,
QtGui.QTableWidgetItem(str(('%g' % table.getData()[row][column]) if type(
table.getData()[row][column]) is float else table.getData()[row][column])))
self.plotAll()
def plotAll(self):
for i in xrange(1):
self.graphTabWidget.findChild(FigureCanvas, 'canvas' + str(i)).draw()
def clearAll(self):
count = self.resultsTabWidget.count()
for i in xrange(count):
self.resultsTabWidget.widget(i).deleteLater()
self.tempTables[:] = []
self.tempResultSets[:] = []
self.text.set_text('')
self.variablesComboBox.clear()
self.clearPlots()
def clearPlots(self):
self.rootPlot.cla()
self.rootPlot.grid(true)
self.rootPlot.autoscale(true, tight=false)
def cloneOptionsMapInfo(self):
for (key, val) in self.methodsCheckMap.items():
vals = []
for va in val:
vals.append(str(va.text()))
self.methodsCheckMapAlias[key] = (key.isChecked(), vals)
def pasteToOptionsMapInfo(self):
for (key, val) in self.methodsCheckMapAlias.items():
key.setChecked(val[0])
for i in range(len(val[1])):
self.methodsCheckMap[key][i].setText(val[1][i])
def initOptionsHandlers(self):
for (key, val) in self.methodsCheckMap.items():
key.stateChanged.connect(self.assignReadOnlyHandler)
key.stateChanged.connect(self.checkForValidInputs)
for va in val:
va.textChanged.connect(self.checkForValidInputs)
def assignReadOnlyHandler(self, state):
checkBox = self.Dialog.sender()
for val in self.methodsCheckMap[checkBox]:
val.setReadOnly(True) if not checkBox.isChecked() else val.setReadOnly(False)
def checkForValidInputs(self, text):
buttonState = False
for (key, vals) in self.methodsCheckMap.items():
if key.isChecked():
tempState = True
for val in vals:
if not val.text():
tempState = False
break
if not tempState:
buttonState = False
break
else:
buttonState = True
self.dialogUI.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(buttonState)
def init_Figure(self):
self.figure = plt.figure()
self.figure.patch.set_facecolor('white')
self.canvas = FigureCanvas(self.figure)
self.toolbar = NewNavigationToolbar(self.canvas, self.mplwindow1, coordinates=False)
self.text = plt.text(0, 0.5, 'WELCOME', fontsize=20)
plt.axis('off')
self.figure.text(0, 0.5, "", fontsize=30)
self.mplvl1.addWidget(self.canvas)
self.mplvl1.addWidget(self.toolbar)
self.toolbar._actions['pan'].trigger()
self.toolbar._actions['pan'].setVisible(False)
self.toolbar._actions['zoom'].setVisible(False)
self.init_Drawing_Figures()
def init_Drawing_Figures(self):
i = 0
for (fig, ls) in self.figs:
ls[0] = fig.add_subplot(111)
ls[0].grid(true)
canvas = FigureCanvas(fig)
canvas.setObjectName("canvas" + str(i))
ls[1].addWidget(canvas)
toolbar = NavigationToolbar(canvas,
ls[2], coordinates=True)
ls[1].addWidget(toolbar)
ls[0].autoscale(true, tight=false)
i += 1
self.rootPlot = self.figs[0][1][0]
def drawResultSet(self, resultSet):
assert type(resultSet) is ResultSet, "resultSet is not of type ResultSet!: " + str(type(resultSet))
self.tempResultSets.append(resultSet)
qWidget = self.drawTable(resultSet.getName())
self.drawTime(resultSet.getExecutionTime(), qWidget.findChild(QtGui.QLineEdit, "Time"))
# self.plotRoot(resultSet.getRoots())
def drawTable(self, identifier):
qWidget = self.initTableWidget()
self.resultsTabWidget.addTab(qWidget, QtCore.QString(identifier))
qTable = self.resultsTabWidget.findChild(QtGui.QTableWidget, "Table")
self.tempTables.append(qTable)
qTable.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
qTable.setSelectionBehavior(QtGui.QTableWidget.SelectRows)
qTable.setSelectionMode(QtGui.QTableWidget.SingleSelection)
return qWidget
def initTableWidget(self):
qWidget = QtGui.QWidget()
qVbox = QtGui.QVBoxLayout()
qTable = QtGui.QTableWidget()
qTable.setObjectName("Table")
qWidget3 = QtGui.QWidget()
hBox2 = QtGui.QHBoxLayout()
hBox2.setMargin(0)
precisionLabel = QtGui.QLabel()
precisionLabel.setText("Precision")
precisionField = QtGui.QLineEdit()
precisionField.setObjectName("Precision")
precisionField.setReadOnly(True)
timeLabel = QtGui.QLabel()
timeLabel.setText("Time")
timeField = QtGui.QLineEdit()
timeField.setObjectName("Time")
timeField.setReadOnly(True)
hBox2.addWidget(precisionLabel)
hBox2.addWidget(precisionField)
hBox2.addWidget(timeLabel)
hBox2.addWidget(timeField)
qWidget3.setLayout(hBox2)
qVbox.addWidget(qTable)
qVbox.addWidget(qWidget3)
qWidget.setLayout(qVbox)
return qWidget
def drawTime(self, time, timeField):
assert type(time) is float or int, "time is not of type float nor int!: " + str(type(time))
assert type(timeField) is QtGui.QLineEdit, "timeField is not of type QtGui.QLineEdit!: " + str(
type(timeField))
timeField.setText(str(('%g' % time)))
def plotRoot(self, roots):
root = []
its = []
for (i, r) in roots:
root.append(r)
its.append(i)
self.rootPlot.plot(its, root, c=np.random.rand(3, 1))
def showErrorMessage(self, error):
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Critical)
msg.setText("Evaluation failure")
msg.setInformativeText("An error occurred while trying to evaluate the root(s)")
msg.setWindowTitle("Error!")
msg.setDetailedText('A division by zero occured in the following method(s):\n' + error)
msg.setStandardButtons(QtGui.QMessageBox.Ok)
msg.exec_()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
window.showMaximized()
sys.exit(app.exec_())