-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
1490 lines (1302 loc) · 62.6 KB
/
Copy pathgui.py
File metadata and controls
1490 lines (1302 loc) · 62.6 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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import logging
import os
import numpy as np
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QFileDialog, QGroupBox,
QLabel, QDoubleSpinBox, QTextEdit, QFrame, QSplitter,
QTableWidget, QTableWidgetItem, QTabWidget,
QRadioButton, QCheckBox, QButtonGroup, QSizePolicy)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QObject
from PyQt6.QtGui import QBrush, QColor
from board_view import BoardView
from data_loader import (load_heatsinks, load_components_list,
calculate_q_matrix, rasterise_gerber, project_copper)
from solver import PCBSolver
import config
# --- Logging Handler for GUI ---
class _LogBridge(QObject):
"""Carries log text from any thread into the GUI thread."""
message = pyqtSignal(str)
class QTextEditHandler(logging.Handler):
"""
Routes log records into the console pane.
Records arrive from worker threads as well as the GUI thread - the solver
logs its own convergence and interruption messages from inside run(). A
QTextEdit may only be touched from the thread that owns it, so the text is
handed over through a queued signal instead of being appended in place.
Appending directly killed the process with STATUS_STACK_BUFFER_OVERRUN
(0xC0000409) the first time the solver logged from the worker thread.
"""
def __init__(self, text_edit):
super().__init__()
# Created on the GUI thread, so emitting from elsewhere queues the call.
self._bridge = _LogBridge()
self._bridge.message.connect(text_edit.append)
def emit(self, record):
try:
self._bridge.message.emit(self.format(record))
except RuntimeError:
# The console widget has been destroyed; drop the record.
pass
# --- Worker for Background Calculations ---
class SolverWorker(QObject):
finished = pyqtSignal(object) # Emits final u matrix
progress = pyqtSignal(object, float, float) # Emits (u, current_time, max_temp)
log = pyqtSignal(str)
def __init__(self, nx, ny, Q, material, h_matrix, layers, copper_oz,
mode='steady', t_final=config.t_final, K_matrix=None,
T_amb=None, h_ambient=None, emissivity=0.0):
super().__init__()
self.nx = nx
self.ny = ny
self.Q = Q
self.material = material
self.h_matrix = h_matrix
self.layers = layers
self.copper_oz = copper_oz
self.mode = mode
self.t_final = t_final
self.K_matrix = K_matrix
# FIX L-7: the environment travels with the job instead of being read
# off config from the worker thread while the GUI thread writes it.
self.T_amb = T_amb
self.h_ambient = h_ambient
self.emissivity = emissivity
self._is_running = True
def stop(self):
self._is_running = False
def run(self):
try:
solver = PCBSolver(self.nx, self.ny, self.Q,
material_name=self.material,
h_matrix=self.h_matrix,
layers=self.layers,
copper_oz=self.copper_oz,
K_matrix=self.K_matrix,
T_amb=self.T_amb,
h_ambient=self.h_ambient,
emissivity=self.emissivity)
self.log.emit(f"Starting {self.mode} simulation...")
self.log.emit(f"Average k: {np.mean(solver.K):.4f} W/mK")
if solver.emissivity > 0:
self.log.emit(
f"Radiation on (eps = {solver.emissivity:.2f}); "
f"convection h = {np.min(solver.h_conv):.1f}"
f"..{np.max(solver.h_conv):.1f} W/m2K"
)
else:
self.log.emit(
f"Radiation OFF; convection only, "
f"h = {np.min(solver.h_conv):.1f}..{np.max(solver.h_conv):.1f} W/m2K"
)
if self.mode == 'steady':
# FIX C-5: hand the solver a cancellation probe so Stop and
# window-close interrupt the sweep loop instead of waiting out
# up to 50000 iterations.
u_final, iterations, converged = solver.solve_steady_state(
should_continue=lambda: self._is_running
)
# FIX C-3: only claim convergence when it actually happened.
if not self._is_running:
self.log.emit(
f"Steady-state STOPPED by user after {iterations} "
f"iterations - the result is not a solution."
)
elif converged:
self.log.emit(f"Steady-state converged in {iterations} iterations.")
else:
self.log.emit(
f"WARNING: steady-state did NOT converge in {iterations} "
f"iterations. Temperatures below are a lower bound, not "
f"a solution."
)
self.finished.emit(u_final)
elif self.mode == 'transient':
total_steps = int(self.t_final / solver.dt)
display_interval = 100
for step in range(total_steps):
if not self._is_running:
break
solver.step()
if step % display_interval == 0:
t = step * solver.dt
max_t = np.max(solver.u)
self.progress.emit(np.copy(solver.u), t, max_t)
self.log.emit("Transient simulation complete.")
self.finished.emit(solver.u)
except Exception as e:
self.log.emit(f"Error: {str(e)}")
self.finished.emit(None)
# --- Worker for Gerber rasterisation ---
class GerberWorker(QObject):
"""
Runs load_gerber_to_k_matrix off the GUI thread.
FIX H-4: the solver was already threaded but Gerber parsing was not. It ran
inline in the click handler, preceded by QApplication.processEvents() - an
antipattern that does not make the work asynchronous. It pumps the queue
once BEFORE the blocking call, and allows re-entrancy: the user can trigger
a second load from inside the nested event loop while the first is still
rasterising.
"""
finished = pyqtSignal(object) # (raster, bbox_mm), or None on failure
error = pyqtSignal(str)
log = pyqtSignal(str)
def __init__(self, path, dpmm=40.0):
super().__init__()
self.path = path
self.dpmm = dpmm
def run(self):
try:
self.log.emit(f"Rasterising {os.path.basename(self.path)}...")
# Only the expensive half runs here. Placing the result on the
# grid depends on the board frame, which the window may still
# have to fit around this very file.
self.finished.emit(rasterise_gerber(self.path, dpmm=self.dpmm))
except Exception as exc:
self.error.emit(f"Gerber Load Error: {exc}")
self.finished.emit(None)
# --- Main Window ---
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(f"HFDM Thermal Solver v{config.VERSION}")
self.resize(1200, 800)
self.comp_dict = None
self.components_list = []
# Kept resident so switching layers never has to recompute it, and so
# the renderer stops depending on which action last happened to build it.
self.Q = None
# Grid follows the configured board size and cell size (FIX L-2)
self.nx, self.ny = config.grid_size()
self.H = None
self.K_matrix = None
self.solver_thread = None
self.worker = None
self.gerber_thread = None
self.gerber_worker = None
self._gerber_path = None
# The parsed raster is kept so moving the board frame is a cheap
# reprojection instead of a fresh parse of the Gerber.
self.gerber_raster = None
self.gerber_bbox = None
self.heatsink_path = None # FIX M-2: remembered so H can be rebuilt
# Virtual Probes state (up to 10)
self.u_final = None # Last completed temperature matrix
# What is on screen lives in BoardView; probes read it from there so
# the reading and the picture cannot drift apart (FIX M-4).
self._has_result = False
self._sim_phase = 'idle' # 'idle' | 'running' | 'done'
self._sim_mode = 'steady'
self._sim_t = 0.0
self._sim_tmax = None
self.probes = [] # List of (x_mm, y_mm) probe positions
self.probe_artists = [] # Matplotlib artists (marker + text) for cleanup
self.MAX_PROBES = 10
self.init_ui()
self.setup_logging()
self._sync_board_fields()
self._sync_layer_controls()
def _publish_probe_artists(self):
"""Hands the probe artists to the view so the Probes layer can hide them."""
self.view.set_probe_artists(
[artist for pair in self.probe_artists for artist in pair]
)
self._sync_layer_controls()
# --- Layer controls -----------------------------------------------------
# Base fields are mutually exclusive because there is one full-size image
# and one colorbar; overlays are independent. The split is a consequence of
# how Matplotlib composes a figure, not a stylistic choice.
BASE_FIELD_CHOICES = (
('temperature', 'Temperature'),
('conductivity', 'Copper k'),
('power', 'Power density'),
('none', 'None'),
)
OVERLAY_CHOICES = (
('components', 'Component outlines'),
('copper', 'Copper mask'),
('convection', 'Heatsink zones'),
('probes', 'Probes'),
)
def _build_view_controls(self):
"""Layer panel, placed under the canvas rather than in the left rail.
Switching layers is something you do while looking at the plot, so the
control belongs in the plot's field of view; the left panel stays for
loading data and setting parameters.
"""
group = QGroupBox("View")
# Two tight rows, never more. Without an explicit Fixed height policy
# the group is Preferred like the canvas above it, so a maximised
# window splits the spare vertical space between them and the strip
# grows to half the pane with the rows drifting apart inside it.
group.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
outer = QVBoxLayout()
outer.setContentsMargins(8, 4, 8, 6)
outer.setSpacing(4)
base_row = QHBoxLayout()
base_row.setSpacing(10)
base_row.addWidget(QLabel("Base:"))
self.base_group = QButtonGroup(self)
self.radio_base = {}
for key, text in self.BASE_FIELD_CHOICES:
radio = QRadioButton(text)
self.base_group.addButton(radio)
self.radio_base[key] = radio
radio.toggled.connect(
lambda checked, k=key: self.on_base_field_changed(k) if checked else None
)
base_row.addWidget(radio)
self.radio_base['temperature'].setChecked(True)
base_row.addStretch()
outer.addLayout(base_row)
show_row = QHBoxLayout()
show_row.setSpacing(10)
show_row.addWidget(QLabel("Show:"))
self.chk_layers = {}
for key, text in self.OVERLAY_CHOICES:
check = QCheckBox(text)
check.setChecked(self.view.is_layer_visible(key))
check.toggled.connect(
lambda on, k=key: self.view.set_layer_visible(k, on)
)
self.chk_layers[key] = check
show_row.addWidget(check)
self.chk_lock_scale = QCheckBox("Lock colour scale")
self.chk_lock_scale.setToolTip(
"Hold the colour scale steady during a transient, so the same "
"colour means the same temperature on every frame."
)
self.chk_lock_scale.toggled.connect(self.on_lock_scale_toggled)
show_row.addWidget(self.chk_lock_scale)
show_row.addStretch()
outer.addLayout(show_row)
group.setLayout(outer)
return group
# --- Board frame --------------------------------------------------------
BOARD_FIT_MARGIN_MM = 1.0
def data_extent(self):
"""
Bounding box of everything loaded, in CAD millimetres, or None.
Components and copper are quoted in the same CAD frame, so their union
is the board as far as this program is concerned.
"""
boxes = []
for comp in self.components_list:
w = comp.get('Width_mm') or 0.0
length = comp.get('Length_mm') or 0.0
if w <= 0 or length <= 0:
continue
boxes.append((comp['Center_X_mm'] - w / 2.0,
comp['Center_Y_mm'] - length / 2.0,
comp['Center_X_mm'] + w / 2.0,
comp['Center_Y_mm'] + length / 2.0))
if self.gerber_bbox is not None:
boxes.append(tuple(self.gerber_bbox))
if not boxes:
return None
return (min(b[0] for b in boxes), min(b[1] for b in boxes),
max(b[2] for b in boxes), max(b[3] for b in boxes))
def _data_fits_frame(self):
extent = self.data_extent()
if extent is None:
return True
bx0, by0, bx1, by1 = config.board_extent()
return (extent[0] >= bx0 and extent[1] >= by0
and extent[2] <= bx1 and extent[3] <= by1)
def fit_board_to_data(self, quiet=False):
"""Snaps the board frame around the loaded data, aligned to the grid."""
extent = self.data_extent()
if extent is None:
if not quiet:
self.log("Nothing loaded yet - nothing to fit the board to.")
return False
dx_mm = config.dx * 1000.0
margin = self.BOARD_FIT_MARGIN_MM
x0 = np.floor((extent[0] - margin) / dx_mm) * dx_mm
y0 = np.floor((extent[1] - margin) / dx_mm) * dx_mm
x1 = np.ceil((extent[2] + margin) / dx_mm) * dx_mm
y1 = np.ceil((extent[3] + margin) / dx_mm) * dx_mm
self.apply_board_frame(x0, y0, x1 - x0, y1 - y0)
self.log(
f"Board frame fitted to data: origin ({x0:.2f}, {y0:.2f}) mm, "
f"{x1 - x0:.2f} x {y1 - y0:.2f} mm -> grid {self.nx} x {self.ny} "
f"cells at dx = {dx_mm:.2f} mm."
)
return True
def apply_board_frame(self, origin_x, origin_y, width, height):
"""
Moves/resizes the board and rebuilds everything that depends on it.
The grid, the convection field and the copper projection are all
functions of the frame, so they are recomputed here rather than left
for whoever notices first.
"""
config.set_board_frame(origin_x, origin_y, width, height)
self.nx, self.ny = config.grid_size()
# The grid changed shape: the h field and the copper projection must
# follow, and probe indices no longer mean anything.
self.H = None
self._ensure_h_matrix()
self._project_gerber()
self.clear_probes(redraw=False)
self._has_result = False
self.u_final = None
if self.components_list:
self.Q = calculate_q_matrix(self.components_list, self.nx, self.ny)
self._sync_board_fields()
self.show_layout()
def _sync_board_fields(self):
"""Writes the current frame into the spin boxes without re-triggering."""
values = {
'origin_x': config.BOARD_ORIGIN_X_MM,
'origin_y': config.BOARD_ORIGIN_Y_MM,
'width': config.BOARD_WIDTH_MM,
'height': config.BOARD_HEIGHT_MM,
}
for key, spin in self.board_spins.items():
spin.blockSignals(True)
spin.setValue(values[key])
spin.blockSignals(False)
self.lbl_grid.setText(f"Grid: {self.nx} x {self.ny} cells")
def on_board_frame_edited(self, _value=None):
self.apply_board_frame(
self.board_spins['origin_x'].value(),
self.board_spins['origin_y'].value(),
self.board_spins['width'].value(),
self.board_spins['height'].value(),
)
def _project_gerber(self):
"""Re-places the cached copper raster on the current grid (cheap)."""
if self.gerber_raster is None or self.gerber_bbox is None:
return
try:
self.K_matrix = project_copper(
self.gerber_raster, self.gerber_bbox,
self.nx, self.ny, config.dx, config.dx,
source=os.path.basename(self._gerber_path or "gerber"),
)
except Exception as exc:
self.logger.exception("Copper projection failed")
self.log(f"Copper projection failed: {exc}")
self.K_matrix = None
self.view.set_copper(self.K_matrix)
def on_convection_changed(self, _value=None):
"""Rebuilds the convection field when the base h changes."""
self.H = None
self._ensure_h_matrix()
self._sync_layer_controls()
self.log(
f"Convection set to h = {self.spin_h.value():.2f} W/m2K"
+ (f" (heatsink zones up to {self.H.max():.0f})"
if self.H is not None and self.H.max() > self.spin_h.value() else "")
)
def on_base_field_changed(self, kind):
self.view.set_base_kind(kind)
if kind != 'temperature':
# The axes now carry W/mK or W/m3. A temperature probe on them
# would be reading the wrong quantity and labelling it "°C"
# (FIX M-4), so the probes go with the field they belong to.
self.clear_probes(redraw=False)
self.view.set_title(self._compose_title())
def on_lock_scale_toggled(self, locked):
self.view.set_clim_lock(locked, floor=self.spin_tamb.value())
def _sync_layer_controls(self):
"""
A layer switch is enabled exactly when its data exists.
Disabled-with-a-reason also does the discovery work: a greyed-out
"Copper mask (load a Gerber file)" tells the user what to do next.
"""
available = {
'temperature': self.view.base_array('temperature') is not None,
'conductivity': self.K_matrix is not None,
'power': self.Q is not None,
'none': True,
}
reasons = {
'conductivity': "Load a Gerber file to enable",
'power': "Load or enter components to enable",
}
for key, radio in self.radio_base.items():
radio.setEnabled(available[key])
radio.setToolTip("" if available[key] else reasons.get(key, ""))
if not available[key] and radio.isChecked():
self.radio_base['temperature'].setChecked(True)
overlay_available = {
'components': bool(self.components_list),
'copper': self.view.has_copper(),
'convection': self.view.has_convection_zones(),
'probes': bool(self.probes),
}
overlay_reasons = {
'copper': "Load a Gerber file to enable",
'convection': "Load a heatsinks CSV with a non-uniform h to enable",
'probes': "Click the board after a run to place a probe",
}
for key, check in self.chk_layers.items():
check.setEnabled(overlay_available[key])
check.setToolTip(
"" if overlay_available[key] else overlay_reasons.get(key, "")
)
# --- Plot title ---------------------------------------------------------
def _compose_title(self):
"""
Single composer for the plot title.
Three different methods used to set it and they overwrote each other;
now it is derived from state like everything else on the canvas.
"""
kind = self.view.field_kind()
if kind == 'conductivity':
head = "Copper topology"
if self.K_matrix is not None:
head += (f" - k {self.K_matrix.min():.2f}"
f"..{self.K_matrix.max():.2f} W/mK")
elif kind == 'power':
head = "Power density"
elif kind == 'none':
head = "Board outline"
elif self._sim_phase == 'running':
head = (f"{self._sim_mode.capitalize()} running"
+ (f" - t = {self._sim_t:.1f} s" if self._sim_mode == 'transient' else ""))
if self._sim_tmax is not None:
head += f" - Tmax {self._sim_tmax:.1f} °C"
elif self._sim_phase == 'done':
head = f"{self._sim_mode.capitalize()} result"
if self._sim_tmax is not None:
head += f" - Tmax {self._sim_tmax:.1f} °C"
else:
head = "Component layout"
parts = [head]
if self.components_list:
parts.append(self._power_summary())
return " | ".join(parts)
def _power_summary(self):
"""How much of the nameplate power actually lands on the board (H-3)."""
on_grid = (0.0 if self.Q is None
else float(self.Q.sum()) * (config.dx ** 2) * config.d)
nameplate = sum(c['Power_Watts'] for c in self.components_list)
text = f"{on_grid:.3f} W on the board"
if abs(on_grid - nameplate) > 1e-9:
text += f" of {nameplate:.3f} W declared"
return text
# BoardView owns the figure; these read-only views keep the probe and
# export code readable without handing out a second owner of the canvas.
@property
def figure(self):
return self.view.figure
@property
def canvas(self):
return self.view.canvas
@property
def ax(self):
return self.view.ax
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# Splitter for adjustable panels
splitter = QSplitter(Qt.Orientation.Horizontal)
# --- Left Panel: Tabs ---
left_panel = QFrame()
left_panel.setMinimumWidth(400)
left_layout = QVBoxLayout(left_panel)
self.tabs = QTabWidget()
# Tab 1: Setup
setup_tab = QWidget()
setup_layout = QVBoxLayout(setup_tab)
# Data Group
data_group = QGroupBox("Data Input")
data_layout = QVBoxLayout()
self.btn_load = QPushButton("Load Components CSV")
self.btn_load.clicked.connect(self.load_data)
data_layout.addWidget(self.btn_load)
self.btn_save_csv = QPushButton("Save Edited CSV")
self.btn_save_csv.clicked.connect(self.save_data_to_csv)
self.btn_save_csv.setEnabled(False)
data_layout.addWidget(self.btn_save_csv)
self.lbl_status = QLabel("Status: No data loaded")
data_layout.addWidget(self.lbl_status)
self.btn_load_heatsinks = QPushButton("Load Heatsinks CSV")
self.btn_load_heatsinks.clicked.connect(self.load_heatsinks_csv)
data_layout.addWidget(self.btn_load_heatsinks)
self.lbl_heatsinks_status = QLabel("Heatsinks: None")
data_layout.addWidget(self.lbl_heatsinks_status)
# Gerber Input
self.btn_load_gerber = QPushButton("Load Top Copper (Gerber)")
self.btn_load_gerber.clicked.connect(self.load_gerber)
data_layout.addWidget(self.btn_load_gerber)
self.lbl_gerber_status = QLabel("Gerber: None loaded")
data_layout.addWidget(self.lbl_gerber_status)
# "View Topology" is gone: it was a display MODE, and a mode you can
# enter but not leave is exactly what made the canvas exclusive. Its
# job is now the "Copper conductivity" base-field radio button.
data_group.setLayout(data_layout)
setup_layout.addWidget(data_group)
# Parameters Group
param_group = QGroupBox("Parameters")
param_layout = QVBoxLayout()
# Ambient Temp
h_layout1 = QHBoxLayout()
h_layout1.addWidget(QLabel("T_amb [°C]:"))
self.spin_tamb = QDoubleSpinBox()
self.spin_tamb.setRange(-50, 200)
self.spin_tamb.setValue(config.T_amb)
h_layout1.addWidget(self.spin_tamb)
param_layout.addLayout(h_layout1)
# t_final
h_layout2 = QHBoxLayout()
h_layout2.addWidget(QLabel("t_final [s]:"))
self.spin_tfinal = QDoubleSpinBox()
self.spin_tfinal.setRange(1, 3600)
self.spin_tfinal.setValue(config.t_final)
h_layout2.addWidget(self.spin_tfinal)
param_layout.addLayout(h_layout2)
# Base convection. Previously only reachable by editing config.py, so
# the only way to model anything but still air was a dummy heatsink
# covering the whole board.
h_layout3 = QHBoxLayout()
h_layout3.addWidget(QLabel("h [W/m²K]:"))
self.spin_h = QDoubleSpinBox()
self.spin_h.setRange(0.1, 10000.0)
self.spin_h.setDecimals(2)
self.spin_h.setValue(config.h)
self.spin_h.setKeyboardTracking(False)
self.spin_h.setToolTip(
"Convection coefficient over the whole board. Still air 5-12, "
"gentle airflow 20-30, forced air 40-80. Heatsink zones from the "
"CSV override it locally."
)
self.spin_h.valueChanged.connect(self.on_convection_changed)
h_layout3.addWidget(self.spin_h)
param_layout.addLayout(h_layout3)
h_layout4 = QHBoxLayout()
h_layout4.addWidget(QLabel("Emissivity ε:"))
self.spin_emissivity = QDoubleSpinBox()
self.spin_emissivity.setRange(0.0, 1.0)
self.spin_emissivity.setDecimals(2)
self.spin_emissivity.setSingleStep(0.05)
self.spin_emissivity.setValue(config.EMISSIVITY)
self.spin_emissivity.setKeyboardTracking(False)
self.spin_emissivity.setToolTip(
"Surface emissivity for radiative loss. 0 disables radiation; "
"solder mask and FR-4 are about 0.9. At 100 °C radiation carries "
"more heat than natural convection, so leaving it at 0 makes a "
"board look far hotter than it is."
)
h_layout4.addWidget(self.spin_emissivity)
param_layout.addLayout(h_layout4)
# --- Board frame -----------------------------------------------------
# A CAD export does not place the board at the sheet origin, so the
# frame needs an origin as well as a size. Auto-fitted on load, and
# editable for the case where only part of a board is of interest.
self.board_spins = {}
for key, label, lo, hi in (
('origin_x', "Origin X [mm]:", -100000.0, 100000.0),
('origin_y', "Origin Y [mm]:", -100000.0, 100000.0),
('width', "Width [mm]:", 0.5, 100000.0),
('height', "Height [mm]:", 0.5, 100000.0),
):
row = QHBoxLayout()
row.addWidget(QLabel(label))
spin = QDoubleSpinBox()
spin.setRange(lo, hi)
spin.setDecimals(3)
spin.setSingleStep(1.0)
# Without this, every keystroke re-grids the board mid-typing.
spin.setKeyboardTracking(False)
spin.valueChanged.connect(self.on_board_frame_edited)
self.board_spins[key] = spin
row.addWidget(spin)
param_layout.addLayout(row)
fit_row = QHBoxLayout()
self.lbl_grid = QLabel("Grid: -")
fit_row.addWidget(self.lbl_grid)
self.btn_fit_board = QPushButton("Fit to data")
self.btn_fit_board.setToolTip(
"Set the frame from the loaded components and copper."
)
self.btn_fit_board.clicked.connect(lambda: self.fit_board_to_data())
fit_row.addWidget(self.btn_fit_board)
param_layout.addLayout(fit_row)
param_group.setLayout(param_layout)
setup_layout.addWidget(param_group)
# Execution Group
exec_group = QGroupBox("Execution")
exec_layout = QVBoxLayout()
self.btn_steady = QPushButton("Run Steady-State")
self.btn_steady.clicked.connect(lambda: self.start_simulation('steady'))
self.btn_transient = QPushButton("Run Transient")
self.btn_transient.clicked.connect(lambda: self.start_simulation('transient'))
self.btn_stop = QPushButton("Stop Simulation")
self.btn_stop.setEnabled(False)
self.btn_stop.clicked.connect(self.stop_simulation)
exec_layout.addWidget(self.btn_steady)
exec_layout.addWidget(self.btn_transient)
exec_layout.addWidget(self.btn_stop)
exec_group.setLayout(exec_layout)
setup_layout.addWidget(exec_group)
setup_layout.addStretch()
self.tabs.addTab(setup_tab, "Setup")
# Tab 2: Components
comp_tab = QWidget()
comp_layout = QVBoxLayout(comp_tab)
self.table = QTableWidget()
self.table.setColumnCount(6)
self.table.setHorizontalHeaderLabels(["Designator", "Power [W]", "X [mm]", "Y [mm]", "W [mm]", "L [mm]"])
self.table.cellChanged.connect(self.on_table_edit)
comp_layout.addWidget(self.table)
btn_comp_layout = QHBoxLayout()
self.btn_add_row = QPushButton("Add Component")
self.btn_add_row.clicked.connect(self.add_component_row)
self.btn_del_row = QPushButton("Delete Selected")
self.btn_del_row.clicked.connect(self.delete_component_row)
btn_comp_layout.addWidget(self.btn_add_row)
btn_comp_layout.addWidget(self.btn_del_row)
comp_layout.addLayout(btn_comp_layout)
self.tabs.addTab(comp_tab, "Components")
left_layout.addWidget(self.tabs)
# Log Console
left_layout.addWidget(QLabel("Console Output:"))
self.log_console = QTextEdit()
self.log_console.setReadOnly(True)
self.log_console.setStyleSheet("background-color: #1e1e1e; color: #d4d4d4; font-family: Consolas;")
left_layout.addWidget(self.log_console)
splitter.addWidget(left_panel)
# --- Right Panel: Visualization ---
right_panel = QFrame()
right_layout = QVBoxLayout(right_panel)
# The canvas and every artist on it belong to BoardView. MainWindow
# owns data and threads, and pushes data in; it never draws.
self.view = BoardView()
# The canvas takes every spare pixel; the strips below keep their
# natural height.
right_layout.addWidget(self.view, 1)
# Connect mouse click on canvas for interactive probes
self.view.canvas.mpl_connect('button_press_event', self.on_canvas_click)
right_layout.addWidget(self._build_view_controls(), 0)
# Probe & Export toolbar under the canvas
toolbar_layout = QHBoxLayout()
self.btn_clear_probes = QPushButton("Clear Probes")
# Wrapped: clicked emits checked=False, which would bind to the new
# redraw parameter and clear the probes without repainting the canvas.
self.btn_clear_probes.clicked.connect(lambda: self.clear_probes())
toolbar_layout.addWidget(self.btn_clear_probes)
self.btn_save_image = QPushButton("Save Result Image")
self.btn_save_image.clicked.connect(self.save_result_image)
toolbar_layout.addWidget(self.btn_save_image)
right_layout.addLayout(toolbar_layout)
splitter.addWidget(right_panel)
main_layout.addWidget(splitter)
# Loggers whose records are mirrored into the console pane. data_loader is
# on the list because the H-3 out-of-bounds warnings are only useful if the
# user actually sees them; attaching to the root logger instead would drag
# in matplotlib/PIL/pygerber chatter.
LOGGED_MODULES = ("HFDM_GUI", "data_loader", "solver")
def setup_logging(self):
self.handler = QTextEditHandler(self.log_console)
self.handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s', '%H:%M:%S'))
for name in self.LOGGED_MODULES:
module_logger = logging.getLogger(name)
if self.handler not in module_logger.handlers:
module_logger.addHandler(self.handler)
module_logger.setLevel(logging.INFO)
self.logger = logging.getLogger("HFDM_GUI")
self.logger.info("HFDM GUI Initialized.")
def log(self, message):
self.logger.info(message)
def load_data(self):
path, _ = QFileDialog.getOpenFileName(
self, "Open CSV", "", "CSV Files (*.csv);;All Files (*)"
)
if not path:
return
try:
self.components_list = load_components_list(path)
# Ensure nx, ny are fresh based on current config
self.nx, self.ny = config.grid_size()
# FIX M-2: do NOT rebuild H here. Loading components must not touch
# the convection layer.
self._ensure_h_matrix()
self.populate_table()
if not self._data_fits_frame():
self.log("Components fall outside the current board frame.")
self.fit_board_to_data()
self.lbl_status.setText(f"Loaded: {self.nx}x{self.ny} grid")
self.log(f"Successfully loaded {len(self.components_list)} components and heatsinks.")
self.btn_save_csv.setEnabled(True)
# Show initial empty board or placeholder
self.on_table_edit() # This triggers initial rendering
except Exception as e:
self.logger.exception("Components Load Error")
self.log(f"Load Error: {str(e)}")
def load_heatsinks_csv(self):
path, _ = QFileDialog.getOpenFileName(
self, "Open Heatsinks CSV", "", "CSV Files (*.csv);;All Files (*)"
)
if not path:
return
try:
from data_loader import load_heatsinks, read_csv_rows, HEATSINK_COLUMNS
# FIX H-2: count through the same validated reader instead of a
# second bare open(), which ignored BOM, delimiter and encoding.
count = len(read_csv_rows(path, HEATSINK_COLUMNS))
self.H = load_heatsinks(path, nx=self.nx, ny=self.ny,
base_h=self.spin_h.value())
self.heatsink_path = path # FIX M-2: survives a component reload
self.view.set_convection(self.H)
if self.view.has_convection_zones():
self.chk_layers['convection'].setChecked(True)
self._sync_layer_controls()
self.lbl_heatsinks_status.setText(f"Heatsinks: {count} loaded")
self.log(f"Successfully loaded {count} heatsinks.")
except Exception as e:
self.logger.exception("Heatsinks Load Error")
self.log(f"Heatsinks Load Error: {str(e)}")
# ----- Busy state (FIX H-5) -----
# Only what MUTATES data the worker is reading. View controls are not here
# on purpose - see the note in _set_busy.
BUSY_WIDGETS = (
"btn_load", "btn_save_csv", "btn_load_heatsinks", "btn_load_gerber",
"btn_add_row", "btn_del_row", "btn_steady", "btn_transient",
"btn_fit_board",
)
def _set_busy(self, busy, can_stop=False):
"""
Locks the UI down for the duration of a background job.
FIX H-5: only btn_steady, btn_transient and btn_stop used to change
state, leaving eight controls and the component table live during a
run. Editing a cell mid-transient rebuilt the whole figure, destroying
the AxesImage that the worker's next progress signal then tried to
update through a dangling reference.
That lock is now narrower on purpose. The reason it had to cover the
view was fig.clear(); with artists persistent, changing what is drawn
no longer touches what the worker is driving, and both the click and
the progress signal are handled on the GUI thread, so they serialise.
Toggling the copper mask while watching a transient is a thing people
want to do, so the layer panel, Clear Probes and Save Image stay live.
The table and the loaders stay locked: they change data, not the view.
can_stop is False for jobs that cannot be interrupted, so the Stop
button never offers something the code cannot deliver: the Gerber
rasteriser runs inside PyGerber and has no cancellation point.
"""
for name in self.BUSY_WIDGETS:
widget = getattr(self, name, None)
if widget is not None:
widget.setEnabled(not busy)
self.table.setEnabled(not busy)
self.spin_tamb.setEnabled(not busy)
self.spin_tfinal.setEnabled(not busy)
for spin in self.board_spins.values():
spin.setEnabled(not busy)
self.spin_h.setEnabled(not busy)
self.spin_emissivity.setEnabled(not busy)
self.btn_stop.setEnabled(busy and can_stop)
if not busy:
# Restore the CORRECT idle state, not merely "everything on":
# Save CSV has its own precondition and must not come back enabled
# just because a run ended.
self.btn_save_csv.setEnabled(bool(self.components_list))
# ----- Gerber loading (FIX H-4) -----
def load_gerber(self):
path, _ = QFileDialog.getOpenFileName(
self, "Load Top Copper Gerber", "",
"Gerber Files (*.gbr *.gtl);;All Files (*)"
)
if not path:
return
self._gerber_path = path
self.lbl_gerber_status.setText("Gerber: loading...")
self.log(f"Loading Gerber '{os.path.basename(path)}' in the background...")
self._set_busy(True, can_stop=False)
self.gerber_thread = QThread()
self.gerber_worker = GerberWorker(path)
self.gerber_worker.moveToThread(self.gerber_thread)
self.gerber_thread.started.connect(self.gerber_worker.run)
self.gerber_worker.finished.connect(self.on_gerber_loaded)
self.gerber_worker.finished.connect(self.gerber_thread.quit)
self.gerber_worker.finished.connect(self.gerber_worker.deleteLater)
self.gerber_thread.finished.connect(self.gerber_thread.deleteLater)
self.gerber_worker.log.connect(self.log)
self.gerber_worker.error.connect(self.log)
self.gerber_thread.start()
def on_gerber_loaded(self, result):
# References are deliberately not cleared here - see the note in
# on_simulation_finished about destroying a worker mid-emission.
if result is None:
self.lbl_gerber_status.setText("Gerber: load failed")
else:
self.gerber_raster, self.gerber_bbox = result
filename = os.path.basename(self._gerber_path or "")
self.lbl_gerber_status.setText(f"Gerber: {filename}")
x0, y0, x1, y1 = self.gerber_bbox
self.log(
f"Gerber '{filename}' covers ({x0:.2f}, {y0:.2f})..."
f"({x1:.2f}, {y1:.2f}) mm."
)
# A CAD export rarely sits inside a default 0..100 mm frame; fit
# the board around it rather than silently clipping it away.
if self._data_fits_frame():
self._project_gerber()
else:
self.log("Copper falls outside the current board frame.")
self.fit_board_to_data()
# Show it straight away: the whole point of loading a Gerber is to
# check it against the component coordinates.
self.chk_layers['copper'].setChecked(True)
if self.K_matrix is not None:
self.log(
f"Successfully loaded Gerber: {filename} "
f"(k from {self.K_matrix.min():.2f} to "
f"{self.K_matrix.max():.2f} W/mK)"
)
self._set_busy(False)
self._sync_layer_controls()
self.view.set_title(self._compose_title())
def populate_table(self):
self.table.blockSignals(True)
self.table.setRowCount(len(self.components_list))
for i, comp in enumerate(self.components_list):
self.table.setItem(i, 0, QTableWidgetItem(str(comp['Designator'])))
self.table.setItem(i, 1, QTableWidgetItem(str(comp['Power_Watts'])))
self.table.setItem(i, 2, QTableWidgetItem(str(comp['Center_X_mm'])))
self.table.setItem(i, 3, QTableWidgetItem(str(comp['Center_Y_mm'])))
self.table.setItem(i, 4, QTableWidgetItem(str(comp['Width_mm'])))
self.table.setItem(i, 5, QTableWidgetItem(str(comp['Length_mm'])))
self.table.blockSignals(False)
def _ensure_h_matrix(self):
"""
Guarantees a convection field exists, without ever discarding one.
FIX M-2: load_data() called load_heatsinks() with the DEFAULT filename
on every component load, so a heatsink CSV the user had already