-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sphere.py
397 lines (318 loc) · 16.1 KB
/
Sphere.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
from PyQt5.QtWidgets import (
QAction,
QGridLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QToolBar,
QVBoxLayout,
QWidget,
)
from PyQt5 import QtCore
from PyQt5.QtGui import (
QDoubleValidator,
QIcon,
QRegExpValidator,
)
import numpy as np
import SphereCalc
import CanvasThreeD
import SaveFig
from Shape import *
class WindowSphere(QWidget, ShapeFunctionality):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
"""
Initializes the user interface of the window.
This method sets up the window layout, widgets, and their connections.
"""
# Create a 3D Matplotlib canvas for plotting the sphere
sc = CanvasThreeD.MplCanvas(self, width=6, height=5, dpi=100)
self.setWindowIcon(QIcon('D:\\Programovani\\Python\\naucse\\PyQtMathApp\\Shape_ico.png'))
# Button to solve and plot the sphere
self.buttonplotSphere = QPushButton('Solve and Plot')
self.buttonplotSphere.clicked.connect(lambda: self.plot_sphere(sc, self.combo_color.currentText()))
self.buttonplotSphere.setToolTip("Solve and plot picture")
# Button to export the graph as an image
self.buttonPicture = QPushButton('Graph Export')
self.buttonPicture.clicked.connect(lambda: SaveFig.save_fig(self, self.fig, 'Sphere.png'))
self.buttonPicture.setEnabled(False)
# Button to export data to Excel
self.buttonExport = QPushButton('Excel Export')
self.buttonExport.clicked.connect(lambda: self.export_excel('Sphere'))
self.buttonExport.setEnabled(False)
# Button to clear all inputs, results, and the graph
self.buttonClear = QPushButton('Clear')
self.buttonClear.clicked.connect(lambda: self.clear_inputs(sc))
# Button to close the window
self.buttonClose = QPushButton('Close')
self.buttonClose.clicked.connect(self.close)
# Create a toolbar for frequently used actions
toolbar = QToolBar()
toolbar.setIconSize(QtCore.QSize(50, 50))
self.setFixedSize(850, 488)
hbox1 = QHBoxLayout()
hbox2 = QHBoxLayout()
hbox2.addStretch(1)
hbox2.addWidget(self.buttonplotSphere)
hbox2.addWidget(self.buttonPicture)
hbox2.addWidget(self.buttonExport)
hbox2.addWidget(self.buttonClear)
hbox2.addWidget(self.buttonClose)
# Create layout and group box for input parameters
layout_param = QGridLayout()
groupBoxParameters = QGroupBox("Parameters")
groupBoxParameters.setLayout(layout_param)
# Create layout and group box for results
layout_res = QGridLayout()
groupBoxResults = QGroupBox("Results")
groupBoxResults.setLayout(layout_res)
vbox1 = QVBoxLayout()
vbox1.addWidget(groupBoxParameters)
vbox1.addWidget(groupBoxResults)
vbox1.addStretch(1)
# Create horizontal layout for the graph and the group boxes with input/results
hbox1.addLayout(vbox1)
hbox1.addWidget(sc)
# vertical box layout for:
# 1. menu
# 2. horizontal box layout for vbox1 with groupboxes and graph
# 3. horizontal box layout with buttons
vbox2 = QVBoxLayout()
vbox2.setMenuBar(toolbar)
vbox2.addLayout(hbox1)
vbox2.addStretch(1)
vbox2.addLayout(hbox2)
self.setLayout(vbox2)
self.setWindowTitle('Sphere')
validator_double = QDoubleValidator(-10000000,10000000,5)
locale = QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.UnitedStates)
validator_double.setLocale(locale)
validator_double.setNotation(QDoubleValidator.StandardNotation)
validator_possitive = QRegExpValidator(QtCore.QRegExp(r'([1-9][0-9]{0,6})|([0][.][0-9]{1,6})|([1-9]{1,6}[.][0-9]{1,6})'))
validator_double = QRegExpValidator(QtCore.QRegExp(r'([-][1-9][0-9]{0,6})|([-][1-9][0-9]{0,6}[.])|([-][0][.][0-9]{1,6})|([-][1-9]{1,6}[.][0-9]{1,6})|([1-9][0-9]{0,6})|([1-9][0-9]{0,6}[.])|([0][.][0-9]{1,6})|([1-9]{1,6}[.][0-9]{1,6})'))
# Create input field for radius
self.label_radius = QLabel("Radius (r):")
self.label_radius.setAlignment(QtCore.Qt.AlignLeft)
self.label_radius.setFixedWidth(150)
layout_param.addWidget(self.label_radius,0,0)
self.edit_radius = QLineEdit(self)
self.edit_radius.setValidator(validator_possitive)
self.edit_radius.setAlignment(QtCore.Qt.AlignRight)
self.edit_radius.setFixedWidth(150)
layout_param.addWidget(self.edit_radius,0,1)
self.label_dim_radius = QLabel("cm")
self.label_dim_radius.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_radius.setFixedWidth(30)
layout_param.addWidget(self.label_dim_radius,0,2)
# Create input field for center coordinate x₀
self.label_centerX = QLabel("X coordinate (x₀):")
self.label_centerX.setAlignment(QtCore.Qt.AlignLeft)
self.label_centerX.setFixedWidth(150)
layout_param.addWidget(self.label_centerX,1,0)
self.edit_centerX = QLineEdit(self)
self.edit_centerX.setValidator(validator_double)
self.edit_centerX.setAlignment(QtCore.Qt.AlignRight)
self.edit_centerX.setFixedWidth(150)
layout_param.addWidget(self.edit_centerX,1,1)
self.label_dim_x = QLabel("cm")
self.label_dim_x.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_x.setFixedWidth(30)
layout_param.addWidget(self.label_dim_x,1,2)
# Create input field for center coordinate y₀
self.label_centerY = QLabel("Y coordinate (y₀):")
self.label_centerY.setAlignment(QtCore.Qt.AlignLeft)
self.label_centerY.setFixedWidth(150)
layout_param.addWidget(self.label_centerY,2,0)
self.edit_centerY = QLineEdit(self)
self.edit_centerY.setValidator(validator_double)
self.edit_centerY.setAlignment(QtCore.Qt.AlignRight)
self.edit_centerY.setFixedWidth(150)
layout_param.addWidget(self.edit_centerY,2,1)
self.label_dim_y = QLabel("cm")
self.label_dim_y.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_y.setFixedWidth(30)
layout_param.addWidget(self.label_dim_y,2,2)
# Create input field for center coordinate z₀
self.label_centerZ = QLabel("Z coordinate (z₀):")
self.label_centerZ.setAlignment(QtCore.Qt.AlignLeft)
self.label_centerZ.setFixedWidth(150)
layout_param.addWidget(self.label_centerZ,3,0)
self.edit_centerZ = QLineEdit(self)
self.edit_centerZ.setValidator(validator_double)
self.edit_centerZ.setAlignment(QtCore.Qt.AlignRight)
self.edit_centerZ.setFixedWidth(150)
layout_param.addWidget(self.edit_centerZ,3,1)
self.label_dim_z = QLabel("cm")
self.label_dim_z.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_z.setFixedWidth(30)
layout_param.addWidget(self.label_dim_z,3,2)
self.label_combo_color = QLabel("Sphere Color:")
self.label_combo_color.setAlignment(QtCore.Qt.AlignLeft)
self.label_combo_color.setFixedWidth(150)
layout_param.addWidget(self.label_combo_color,4,0)
# Create combo for color
self.combo_color = self.custom_combo()
layout_param.addWidget(self.combo_color,4,1)
# Create field for result - Volume (V)
self.label_volume = QLabel("Sphere Volume (V):")
self.label_volume.setAlignment(QtCore.Qt.AlignLeft)
self.label_volume.setFixedWidth(150)
layout_res.addWidget(self.label_volume,0,0)
self.label_res_volume = QLabel('0.0')
self.label_res_volume.setAlignment(QtCore.Qt.AlignRight)
self.label_res_volume.setFixedWidth(150)
layout_res.addWidget(self.label_res_volume,0,1)
self.label_dim_vol = QLabel("cm<sup>3</sup>")
self.label_dim_vol.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_vol.setFixedWidth(30)
layout_res.addWidget(self.label_dim_vol,0,2)
# Create field for result - Surface (S)
self.label_surface = QLabel("Sphere Surface (S):")
self.label_surface.setAlignment(QtCore.Qt.AlignLeft)
self.label_surface.setFixedWidth(150)
layout_res.addWidget(self.label_surface,1,0)
self.label_res_surface = QLabel('0.0')
self.label_res_surface.setAlignment(QtCore.Qt.AlignRight)
self.label_res_surface.setFixedWidth(150)
layout_res.addWidget(self.label_res_surface,1,1)
self.label_dim_surface = QLabel("cm<sup>2</sup>")
self.label_dim_surface.setAlignment(QtCore.Qt.AlignLeft)
self.label_dim_surface.setFixedWidth(30)
layout_res.addWidget(self.label_dim_surface,1,2)
# Solve and plot picture - button in the top toolbar
self.exportPictAction = QAction(self)
self.exportPictAction.setToolTip("Solve and plot picture")
self.exportPictAction.setIcon(QIcon('CalculateIcon.svg'))
self.exportPictAction.triggered.connect(lambda: self.plot_sphere(sc, self.combo_color.currentText()))
toolbar.addAction(self.exportPictAction)
# Export graph as PNG - button in the top toolbar
self.exportPictAction = QAction(self)
self.exportPictAction.setToolTip("Save graph as picture")
self.exportPictAction.setIcon(QIcon('SavePictureIcon.svg'))
self.exportPictAction.triggered.connect(lambda: SaveFig.save_fig(self, self.fig, 'Sphere.png'))
self.exportPictAction.setEnabled(False)
toolbar.addAction(self.exportPictAction)
# Export inputs, results and graph into Excel file - button in the top toolbar
self.exportXlsxAction = QAction(self)
self.exportXlsxAction.setToolTip("Export input data, results\nand graph into Excel")
self.exportXlsxAction.setIcon(QIcon('ExportXLSIcon.svg'))
self.exportXlsxAction.triggered.connect(lambda: self.export_excel('Sphere'))
self.exportXlsxAction.setEnabled(False)
toolbar.addAction(self.exportXlsxAction)
# Clear all - inputs, results and graph - button in the top toolbar
# Button is disable, when result are not allowable
self.clearAction = QAction(self)
self.clearAction.setToolTip("Clear all data and results")
self.clearAction.setIcon(QIcon('ClearResultsIcon.svg'))
self.clearAction.triggered.connect(lambda: self.clear_inputs(sc))
self.clearAction.setEnabled(False)
toolbar.addAction(self.clearAction)
# Close window - - button in the top toolbar
self.closeAction = QAction(self)
self.closeAction.setToolTip("Close window")
self.closeAction.setIcon(QIcon('CloseAppIcon.svg'))
self.closeAction.triggered.connect(self.close)
toolbar.addAction(self.closeAction)
self.edit_radius.textChanged.connect(self.check_state_rad_and_set_color)
self.edit_radius.textChanged.connect(lambda: self.clear_results_3D(sc))
self.edit_radius.textChanged.emit(self.edit_radius.text())
self.edit_centerX.textChanged.connect(self.check_state_and_set_color)
self.edit_centerX.textChanged.connect(lambda: self.clear_results_3D(sc))
self.edit_centerX.textChanged.emit(self.edit_centerX.text())
self.edit_centerY.textChanged.connect(self.check_state_and_set_color)
self.edit_centerY.textChanged.connect(lambda: self.clear_results_3D(sc))
self.edit_centerY.textChanged.emit(self.edit_centerY.text())
self.edit_centerZ.textChanged.connect(self.check_state_and_set_color)
self.edit_centerZ.textChanged.connect(lambda: self.clear_results_3D(sc))
self.edit_centerZ.textChanged.emit(self.edit_centerZ.text())
self.combo_color.currentIndexChanged.connect(lambda: self.clear_results_3D(sc))
def plot_sphere(self, sphere_plot, sphere_color):
"""
Plots a sphere based on user input and updates related UI elements.
This method clears the plot, resets the result labels, and performs input validation. If all inputs
are valid, it calculates sphere coordinates, plots the sphere, updates the figure reference,
calculates sphere properties, and enables relevant UI elements.
Args:
sphere_plot: The plot object to be used for drawing the sphere.
sphere_color: The color of the plotted sphere.
"""
# Clear the plot and reset result labels
sphere_plot.axes.cla()
sphere_plot.draw()
self.label_res_surface.setText("0.0")
self.label_res_volume.setText("0.0")
# Input validation
if self.edit_radius.text() in ["", "0", "0.", "+", "-"]:
self.custom_messagebox("Radius can be only a positive number!")
elif self.edit_centerX.text() in ["", "+", "-"]:
self.custom_messagebox("X coordinate (x₀) is missing!")
elif self.edit_centerY.text() in ["", "+", "-"]:
self.custom_messagebox("Y coordinate (y₀) is missing!")
elif self.edit_centerZ.text() in ["", "+", "-"]:
self.custom_messagebox("Z coordinate (z₀) is missing!")
else:
# Convert input values to floats
center_x = float(self.edit_centerX.text())
center_y = float(self.edit_centerY.text())
center_z = float(self.edit_centerZ.text())
r = float(self.edit_radius.text())
# Generate sphere coordinates
u, v = np.mgrid[0:2 * np.pi:30j, 0:np.pi:30j]
x = r * np.outer(np.cos(u), np.sin(v)) + center_x
y = r * np.outer(np.sin(u), np.sin(v)) + center_y
z = r * np.outer(np.ones(np.size(u)), np.cos(v)) + center_z
# Plot the sphere
sphere_plot.axes.plot_surface(x, y, z, color=sphere_color)
sphere_plot.draw()
# Update figure reference and perform additional actions
self.fig = sphere_plot.figure
self.calculate_sphere()
self.clearAction.setEnabled(True)
self.buttonClear.setEnabled(True)
self.exportPictAction.setEnabled(True)
self.buttonPicture.setEnabled(True)
self.exportXlsxAction.setEnabled(True)
self.buttonExport.setEnabled(True)
def calculate_sphere(self):
"""
Calculates the volume and surface area of a sphere based on user input.
This method retrieves the radius value entered by the user in the `edit_radius` text field,
creates a `SphereCalc.Sphere` object with that radius, calculates the sphere's volume and surface area
rounded to five decimal places, and updates the corresponding labels (`label_res_volume` and
`label_res_surface`) with the results.
Raises:
ValueError: If the user enters a non-numeric value for the radius.
"""
try:
# Get the radius from the UI as a float
radius_sphere = float(self.edit_radius.text())
except ValueError:
# Handle non-numeric input gracefully (e.g., display an error message)
raise ValueError("Please enter a valid numeric value for the radius.")
# Create a Sphere object with the given radius
mySphere = SphereCalc.Sphere(radius_sphere)
# Calculate the volume and surface area, rounding to 5 decimal places
sphere_volume = round(mySphere.volume(),5)
sphere_surface = round(mySphere.surface_area(),5)
# Update the UI with the calculated results
self.label_res_volume.setText(str(sphere_volume))
self.label_res_surface.setText(str(sphere_surface))
def clear_inputs(self, sc):
"""
Clears input fields.
This method clears the text in the radius, x, y and z coordinate fields.
It then calls the `clear_results_3D` method to clear the results and plot.
Args:
sc: The Matplotlib canvas object used for plotting.
"""
self.edit_radius.clear()
self.edit_centerX.clear()
self.edit_centerY.clear()
self.edit_centerZ.clear()
# Clears results and the plot using a helper function
self.clear_results_3D(sc)