-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththermal_plugin.py
More file actions
2519 lines (2311 loc) · 98.2 KB
/
Copy paththermal_plugin.py
File metadata and controls
2519 lines (2311 loc) · 98.2 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
"""
ThermalSim - KiCad PCB thermal simulation plugin.
This is the main controller module that orchestrates the thermal simulation
workflow using the specialized sub-modules.
"""
import os
import re
import time
import math
import json
import tempfile
import threading
import traceback
from dataclasses import dataclass, asdict
import pcbnew
import numpy as np
import wx
from .capabilities import HAS_LIBS, HAS_PARDISO, get_pypardiso_optional_dependency
from .stackup_parser import parse_stackup_from_board_file, format_stackup_report_um
from .gui_dialogs import (
DEFAULT_GRID_MAX_CELLS,
DEFAULT_GRID_TARGET_CELLS,
MAX_CUSTOM_GRID_NODES,
SettingsDialog,
prepare_current_groups,
prepare_power_pads,
)
from .electrical_solver import (
CurrentTerminal,
ElectricalConfig,
net_key_from_obj,
net_key_from_values,
solve_electrical_heating,
)
from .adaptive_mesh import build_adaptive_mesh, build_adaptive_system
from .geometry_mapper import build_geometry_state, create_multilayer_maps, get_pad_pixels
from .thermal_solver import (
SolverConfig,
build_stiffness_matrix,
build_structured_operator,
run_simulation,
run_simulation_matrix_free,
)
from .pwl_parser import parse_pwl_file
from .visualization import (
save_snapshot, show_results_top_bot, show_results_all_layers, save_preview_image,
build_interactive_heatmap_payload, save_joule_loss_map
)
from .thermal_report import write_html_report
from .workflow import (
AreaEstimate,
BoardSnapshot,
CancellationToken,
GeometryCache,
ThermalFactorizationCache,
ThermalOperatorCache,
GridEstimate,
PreflightResult,
SimulationArtifacts,
get_process_memory_mb,
geometry_cache_key,
stable_fingerprint,
)
GRID_DETAIL_PRESETS = {
"fast": (300_000, 150_000),
"balanced": (800_000, 400_000),
"detailed": (1_600_000, 800_000),
"very_detailed": (3_000_000, 1_500_000),
}
DEFAULT_GRID_DETAIL = "balanced"
DEFAULT_GRID_NODE_BUDGET = GRID_DETAIL_PRESETS[DEFAULT_GRID_DETAIL][0]
@dataclass
class SparsePadContribution:
"""Sparse per-pad power distribution on the simulation grid."""
indices: np.ndarray
weights: np.ndarray
def _electrical_net_summary_dict(summary):
"""Convert electrical net diagnostics to report-friendly dictionaries."""
data = asdict(summary)
data["net"] = data.get("net_name", "")
return data
def _bbox_to_power_indices(bbox, target_idx, rows, cols, x_min, y_min, res, rc):
"""
Convert a pad bounding box to flattened node indices on one copper layer.
Parameters
----------
bbox : pcbnew.EDA_RECT
Pad bounding box in KiCad internal units.
target_idx : int
Target copper layer index.
rows : int
Number of grid rows.
cols : int
Number of grid columns.
x_min : float
Grid origin x coordinate in millimeters.
y_min : float
Grid origin y coordinate in millimeters.
res : float
Grid resolution in millimeters.
rc : int
Number of nodes per layer.
Returns
-------
np.ndarray
Flattened node indices for the rectangular pad extent.
"""
x0 = bbox.GetX() * 1e-6
y0 = bbox.GetY() * 1e-6
w = bbox.GetWidth() * 1e-6
h = bbox.GetHeight() * 1e-6
cs = max(0, int((x0 - x_min) / res))
rs = max(0, int((y0 - y_min) / res))
ce = min(cols, int((x0 + w - x_min) / res) + 1)
re = min(rows, int((y0 + h - y_min) / res) + 1)
if cs >= ce or rs >= re:
return np.empty(0, dtype=np.int64)
row_offsets = np.arange(rs, re, dtype=np.int64) * cols
col_offsets = np.arange(cs, ce, dtype=np.int64)
return target_idx * rc + (row_offsets[:, None] + col_offsets[None, :]).ravel(order="C")
def _pad_target_layer_index(board, copper_ids, pad, lid_to_idx):
"""
Resolve the solver layer index for a pad.
Parameters
----------
board : pcbnew.BOARD
The active board object.
copper_ids : list of int
Copper layer IDs in stackup order.
pad : pcbnew.PAD
Pad to place on the thermal grid.
lid_to_idx : dict
Mapping from KiCad layer IDs to solver indices.
Returns
-------
int
Target copper layer index for the pad.
"""
pad_lid = pad.GetLayer()
target_idx = lid_to_idx.get(pad_lid)
if target_idx is not None:
return target_idx
try:
lname = board.GetLayerName(pad_lid).upper()
except Exception:
lname = ""
return len(copper_ids) - 1 if ("B." in lname or "BOT" in lname) else 0
def _build_sparse_pad_contributions(board, copper_ids, pads_list, rows, cols, x_min, y_min, res):
"""
Build sparse per-pad unit power distributions.
Parameters
----------
board : pcbnew.BOARD
The active board object.
copper_ids : list of int
Copper layer IDs in stackup order.
pads_list : list
Selected pads used as heat sources.
rows : int
Number of grid rows.
cols : int
Number of grid columns.
x_min : float
Grid origin x coordinate in millimeters.
y_min : float
Grid origin y coordinate in millimeters.
res : float
Grid resolution in millimeters.
Returns
-------
list of SparsePadContribution
Sparse power distributions normalized to 1 W per pad.
"""
rc = rows * cols
lid_to_idx = {lid: idx for idx, lid in enumerate(copper_ids)}
contributions = []
for pad in pads_list:
target_idx = _pad_target_layer_index(board, copper_ids, pad, lid_to_idx)
indices = _bbox_to_power_indices(
pad.GetBoundingBox(),
target_idx=target_idx,
rows=rows,
cols=cols,
x_min=x_min,
y_min=y_min,
res=res,
rc=rc,
)
if indices.size:
weights = np.full(indices.shape, 1.0 / float(indices.size), dtype=np.float64)
else:
weights = np.empty(0, dtype=np.float64)
contributions.append(SparsePadContribution(indices=indices, weights=weights))
return contributions
def _build_power_vector(pad_sources, pad_contributions, total_nodes):
"""
Build the constant power vector and optional time-varying callback.
Parameters
----------
pad_sources : list
Parsed pad source descriptors: ('const', value) or ('pwl', (times, powers)).
pad_contributions : list of SparsePadContribution
Sparse per-pad unit distributions.
total_nodes : int
Total number of thermal nodes.
Returns
-------
tuple
(Q, Q_func) where Q is the initial dense power vector and Q_func is an
optional callback for time-varying inputs.
"""
q_const = np.zeros(total_nodes, dtype=np.float64)
pwl_terms = []
for idx, (source_type, source_value) in enumerate(pad_sources):
if idx >= len(pad_contributions):
break
contribution = pad_contributions[idx]
if contribution.indices.size == 0:
continue
if source_type == 'const':
q_const[contribution.indices] += float(source_value) * contribution.weights
else:
times, powers = source_value
pwl_terms.append((
np.asarray(times, dtype=np.float64),
np.asarray(powers, dtype=np.float64),
contribution.indices,
contribution.weights,
))
if not pwl_terms:
return q_const, None
q_initial = q_const.copy()
for times, powers, indices, weights in pwl_terms:
q_initial[indices] += float(np.interp(0.0, times, powers)) * weights
q_workspace = np.empty_like(q_const)
def q_func(t, _q_const=q_const, _pwl_terms=tuple(pwl_terms), _workspace=q_workspace):
np.copyto(_workspace, _q_const)
for times, powers, indices, weights in _pwl_terms:
_workspace[indices] += float(np.interp(t, times, powers)) * weights
return _workspace
return q_initial, q_func
def _format_timing_summary(timings):
"""Format initialization timings for console output."""
parts = []
for key in (
"zone_refill_s",
"geometry_maps_s",
"capacity_build_s",
"power_vector_build_s",
"electrical_solve_s",
"stiffness_matrix_s",
):
if key in timings:
parts.append(f"{key}={float(timings[key]):.4f}s")
return ", ".join(parts)
def _write_run_manifest(run_dir, status, **details):
"""Persist the lifecycle state of a result directory."""
payload = {"schema_version": 1, "status": str(status), "updated_at": time.time()}
payload.update(details)
try:
with open(os.path.join(run_dir, "run_manifest.json"), "w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2, sort_keys=True, default=str)
except Exception:
pass
def _resolve_grid_limits(settings):
"""
Resolve automatic grid coarsening limits from settings.
Returns
-------
tuple
``(expert_enabled, max_cells, target_cells)`` with safe defaults.
"""
expert_enabled = bool(settings.get("grid_expert_limits", False))
if not expert_enabled:
return False, DEFAULT_GRID_MAX_CELLS, DEFAULT_GRID_TARGET_CELLS
try:
max_cells = int(settings.get("grid_max_cells", DEFAULT_GRID_MAX_CELLS))
target_cells = int(settings.get("grid_target_cells", DEFAULT_GRID_TARGET_CELLS))
except Exception:
return False, DEFAULT_GRID_MAX_CELLS, DEFAULT_GRID_TARGET_CELLS
if max_cells < 1000 or target_cells < 1000 or target_cells > max_cells:
return False, DEFAULT_GRID_MAX_CELLS, DEFAULT_GRID_TARGET_CELLS
return True, max_cells, target_cells
def _resolve_grid_policy(settings, layer_count):
"""Resolve a layer-aware detail preset to legacy 2D cell limits."""
layers = max(1, int(layer_count or 1))
if "grid_detail_level" not in settings:
expert, max_cells, target_cells = _resolve_grid_limits(settings)
detail = "custom" if expert else "legacy"
return detail, expert, max_cells, target_cells, max_cells * layers
detail = str(settings.get("grid_detail_level") or DEFAULT_GRID_DETAIL).strip().lower()
detail = detail.replace(" ", "_").replace("-", "_")
if detail not in set(GRID_DETAIL_PRESETS) | {"custom"}:
detail = DEFAULT_GRID_DETAIL
if detail == "custom":
try:
max_nodes = int(settings.get("grid_node_budget", DEFAULT_GRID_NODE_BUDGET))
except Exception:
max_nodes = DEFAULT_GRID_NODE_BUDGET
max_nodes = min(MAX_CUSTOM_GRID_NODES, max(50_000, max_nodes))
target_nodes = max(25_000, max_nodes // 2)
expert = True
else:
max_nodes, target_nodes = GRID_DETAIL_PRESETS[detail]
expert = False
max_cells = max(1000, max_nodes // layers)
target_cells = max(1000, min(max_cells, target_nodes // layers))
return detail, expert, max_cells, target_cells, max_nodes
def _coarsen_grid_resolution(w_mm, h_mm, requested_res, settings, layer_count=1):
"""
Apply automatic grid coarsening for large boards.
Parameters
----------
w_mm, h_mm : float
Board width and height in millimeters.
requested_res : float
User-requested grid resolution in millimeters.
settings : dict
Simulation settings.
Returns
-------
tuple
``(res, auto_coarsened, expert_enabled, max_cells, target_cells)``.
"""
_, expert_enabled, max_cells, target_cells, _ = _resolve_grid_policy(
settings, layer_count
)
area = w_mm * h_mm
res = float(requested_res)
auto_coarsened = False
if res > 0.0 and area > 0.0 and (w_mm / res) * (h_mm / res) > max_cells:
res = math.sqrt(area / float(target_cells))
auto_coarsened = True
return res, auto_coarsened, expert_enabled, max_cells, target_cells
def _effective_fr4_control_volume_thicknesses(
gap_m, total_thickness_m, layer_count
):
"""Return the FR4 thickness assigned to each copper-plane control volume.
Each dielectric gap is split equally between its two neighboring copper
planes. This conserves the total dielectric volume represented by the
multilayer finite-volume model.
Parameters
----------
gap_m : sequence of float
Dielectric gaps between adjacent copper planes, in meters.
total_thickness_m : float
Fallback board thickness in meters.
layer_count : int
Number of copper planes.
Returns
-------
numpy.ndarray
Effective FR4 thickness per copper-plane control volume, in meters.
"""
count = max(1, int(layer_count))
total = max(float(total_thickness_m), 1e-5)
if count == 1:
return np.asarray([total], dtype=np.float64)
gaps = np.asarray(
list(gap_m) if gap_m is not None else [],
dtype=np.float64,
)
if (
gaps.size != count - 1
or not np.all(np.isfinite(gaps))
or np.any(gaps <= 0.0)
):
gaps = np.full(count - 1, total / float(count - 1), dtype=np.float64)
thicknesses = np.empty(count, dtype=np.float64)
thicknesses[0] = 0.5 * gaps[0]
thicknesses[-1] = 0.5 * gaps[-1]
if count > 2:
thicknesses[1:-1] = 0.5 * (gaps[:-1] + gaps[1:])
return np.clip(thicknesses, 1e-6, 5e-3)
def _bbox_bounds_mm(bbox):
"""Return a KiCad rectangle as absolute millimetre bounds."""
x_min = float(bbox.GetX()) * 1e-6
y_min = float(bbox.GetY()) * 1e-6
return (
x_min,
y_min,
x_min + float(bbox.GetWidth()) * 1e-6,
y_min + float(bbox.GetHeight()) * 1e-6,
)
def _find_pcb_editor_parent(board=None):
"""Return the PCB Editor top-level window for parenting plugin dialogs.
KiCad can run the project manager and PCB Editor in the same wx
application. A dialog created with ``parent=None`` may then be attached to
the project manager even when the plugin was launched from PCB Editor.
"""
try:
active = wx.GetActiveWindow()
except Exception:
active = None
def top_level(window):
current = window
seen = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
try:
parent = current.GetParent()
except Exception:
parent = None
if parent is None:
break
current = parent
return current
active_top = top_level(active)
candidates = []
try:
candidates.extend(list(wx.GetTopLevelWindows()))
except Exception:
pass
if active_top is not None and active_top not in candidates:
candidates.append(active_top)
board_tokens = []
if board is not None:
try:
board_name = os.path.basename(str(board.GetFileName() or "")).lower()
board_stem = os.path.splitext(board_name)[0]
board_tokens = [token for token in (board_name, board_stem) if token]
except Exception:
pass
editor_markers = (
"pcb editor", "pcbnew", "pcb_edit_frame", "pcb editor frame",
"leiterplatteneditor", "platteneditor",
)
manager_markers = ("project manager", "projektmanager")
def window_text(window):
parts = [type(window).__name__]
for getter_name in ("GetTitle", "GetName", "GetClassName"):
try:
value = getattr(window, getter_name)()
if value:
parts.append(str(value))
except Exception:
continue
try:
parts.append(str(window.GetClassInfo().GetClassName()))
except Exception:
pass
return " ".join(parts).lower()
best = None
best_score = -10_000
for window in candidates:
if window is None:
continue
try:
if hasattr(window, "IsBeingDeleted") and window.IsBeingDeleted():
continue
except Exception:
continue
text = window_text(window)
score = 100 if window is active_top else 0
if any(marker in text for marker in editor_markers):
score += 1_000
if any(token in text for token in board_tokens):
score += 500
if any(marker in text for marker in manager_markers):
score -= 1_000
if score > best_score:
best = window
best_score = score
return best if best_score > 0 else active_top
def _estimate_simulation_area(board, bbox, settings, power_pads=None, terminals=None):
"""Build a safe rectangular domain around heat sources and current nets."""
board_x0, board_y0, board_x1, board_y1 = _bbox_bounds_mm(bbox)
board_w = max(0.0, board_x1 - board_x0)
board_h = max(0.0, board_y1 - board_y0)
legacy_limited = bool(settings.get("limit_area", False))
mode = str(settings.get("area_mode") or ("active" if legacy_limited else "full"))
mode = mode.strip().lower()
if mode not in ("full", "active"):
mode = "active" if legacy_limited else "full"
margin = max(0.0, float(settings.get("area_margin_mm", settings.get("pad_dist_mm", 0.0)) or 0.0))
active_terms = [
item for item in (terminals or []) if abs(float(getattr(item, "current_a", 0.0))) > 0.0
]
active_keys = {
net_key_from_values(item.net_code, item.net_name) for item in active_terms
}
active_names = tuple(sorted({
str(item.net_name or net_key_from_values(item.net_code, item.net_name))
for item in active_terms
}))
if mode == "full":
return AreaEstimate(
mode="full", x_min_mm=board_x0, y_min_mm=board_y0,
width_mm=board_w, height_mm=board_h,
board_width_mm=board_w, board_height_mm=board_h,
margin_mm=margin, heat_source_count=len(power_pads or []),
active_net_names=active_names,
)
bounds = []
warnings = []
collection_failed = False
def add_bbox(item):
try:
item_bbox = item.GetBoundingBox() if hasattr(item, "GetBoundingBox") else item
x0, y0, x1, y1 = _bbox_bounds_mm(item_bbox)
if x1 > x0 and y1 > y0:
bounds.append((x0, y0, x1, y1))
except Exception:
return
for pad in power_pads or []:
add_bbox(pad)
if active_keys:
try:
footprints = list(
board.Footprints() if hasattr(board, "Footprints") else board.GetFootprints()
)
for footprint in footprints:
for pad in footprint.Pads():
if net_key_from_obj(pad)[0] in active_keys:
add_bbox(pad)
except Exception:
collection_failed = True
try:
tracks = list(board.Tracks() if hasattr(board, "Tracks") else board.GetTracks())
for track in tracks:
if net_key_from_obj(track)[0] in active_keys:
add_bbox(track)
except Exception:
collection_failed = True
try:
zones = list(board.Zones() if hasattr(board, "Zones") else board.GetZones())
for zone in zones:
if net_key_from_obj(zone)[0] not in active_keys:
continue
if hasattr(zone, "IsFilled") and not zone.IsFilled():
continue
add_bbox(zone)
except Exception:
collection_failed = True
if settings.get("use_heatsink"):
try:
for drawing in list(board.GetDrawings() if hasattr(board, "GetDrawings") else []):
if drawing.GetLayer() == pcbnew.Eco1_User:
add_bbox(drawing)
except Exception:
warnings.append("Thermal-pad geometry could not be included in the area estimate.")
if collection_failed and active_keys:
warnings.append("Current-net geometry could not be inspected safely; the full board is used.")
return AreaEstimate(
mode="full", x_min_mm=board_x0, y_min_mm=board_y0,
width_mm=board_w, height_mm=board_h,
board_width_mm=board_w, board_height_mm=board_h,
margin_mm=margin, heat_source_count=len(power_pads or []),
active_net_names=active_names, fallback_to_full=True,
warnings=tuple(warnings),
)
if not bounds:
warnings.append("No active source geometry was found; the full board is used.")
return AreaEstimate(
mode="full", x_min_mm=board_x0, y_min_mm=board_y0,
width_mm=board_w, height_mm=board_h,
board_width_mm=board_w, board_height_mm=board_h,
margin_mm=margin, heat_source_count=0,
active_net_names=active_names, fallback_to_full=True,
warnings=tuple(warnings),
)
safety = max(0.0, float(settings.get("res", 0.0) or 0.0))
x0 = max(board_x0, min(item[0] for item in bounds) - margin - safety)
y0 = max(board_y0, min(item[1] for item in bounds) - margin - safety)
x1 = min(board_x1, max(item[2] for item in bounds) + margin + safety)
y1 = min(board_y1, max(item[3] for item in bounds) + margin + safety)
area = AreaEstimate(
mode="active", x_min_mm=x0, y_min_mm=y0,
width_mm=max(0.0, x1 - x0), height_mm=max(0.0, y1 - y0),
board_width_mm=board_w, board_height_mm=board_h,
margin_mm=margin, heat_source_count=len(power_pads or []),
active_net_names=active_names, warnings=tuple(warnings),
)
if active_keys and area.area_fraction >= 0.95:
warnings.append("Active current geometry covers almost the full board; area limiting saves little work.")
area = AreaEstimate(
mode=area.mode, x_min_mm=area.x_min_mm, y_min_mm=area.y_min_mm,
width_mm=area.width_mm, height_mm=area.height_mm,
board_width_mm=area.board_width_mm, board_height_mm=area.board_height_mm,
margin_mm=area.margin_mm, heat_source_count=area.heat_source_count,
active_net_names=area.active_net_names, warnings=tuple(warnings),
)
return area
def _estimate_solver_cost(nodes, settings):
"""Return conservative memory bounds and a relative runtime class."""
nodes = max(0, int(nodes))
compute_engine = str(
settings.get("compute_engine", "auto") or "auto"
).lower()
fast_engine = (
compute_engine == "fast_native"
or (compute_engine == "auto" and nodes >= 250_000)
)
if fast_engine:
memory_low = int(math.ceil(nodes * 0.00012))
memory_high = int(math.ceil(nodes * 0.00045))
thresholds = (500_000, 2_000_000, 7_000_000)
else:
memory_low = int(math.ceil(nodes * 0.00035))
memory_high = int(math.ceil(nodes * 0.00120))
thresholds = (150_000, 500_000, 1_000_000)
backend = str(settings.get("solver_backend", "auto") or "auto").lower()
if not fast_engine and (
backend == "pardiso" or (backend == "auto" and HAS_PARDISO)
):
thresholds = (250_000, 800_000, 1_600_000)
if nodes < thresholds[0]:
runtime = "Fast"
elif nodes < thresholds[1]:
runtime = "Moderate"
elif nodes < thresholds[2]:
runtime = "Slow"
else:
runtime = "Very slow"
return memory_low, memory_high, runtime
def _estimate_solver_grid(
bbox, requested_res, settings, layer_count, focus_pads=None, area=None
):
"""Compute the final solver grid after area limiting and coarsening."""
original_x_min, original_y_min, original_x_max, original_y_max = _bbox_bounds_mm(bbox)
x_min, y_min = original_x_min, original_y_min
x_max, y_max = original_x_max, original_y_max
if area is not None:
x_min = float(area.x_min_mm)
y_min = float(area.y_min_mm)
x_max = x_min + float(area.width_mm)
y_max = y_min + float(area.height_mm)
elif settings.get("limit_area") and settings.get("pad_dist_mm", 0.0) > 0:
radius = float(settings["pad_dist_mm"])
pad_xs = []
pad_ys = []
for pad in focus_pads or []:
try:
pos = pad.GetPosition()
pad_xs.append(pos.x * 1e-6)
pad_ys.append(pos.y * 1e-6)
except Exception:
continue
if pad_xs and pad_ys:
x_min = max(original_x_min, min(pad_xs) - radius)
y_min = max(original_y_min, min(pad_ys) - radius)
x_max = min(original_x_max, max(pad_xs) + radius)
y_max = min(original_y_max, max(pad_ys) + radius)
width = max(float(requested_res), x_max - x_min)
height = max(float(requested_res), y_max - y_min)
res, coarsened, expert, max_cells, target_cells = _coarsen_grid_resolution(
width, height, requested_res, settings, layer_count
)
rows = int(height / res) + 4
cols = int(width / res) + 4
nodes = rows * cols * int(layer_count)
detail, _, _, _, node_budget = _resolve_grid_policy(settings, layer_count)
memory_low, memory_high, runtime = _estimate_solver_cost(nodes, settings)
return GridEstimate(
requested_res_mm=float(requested_res),
actual_res_mm=float(res),
x_min_mm=float(x_min),
y_min_mm=float(y_min),
width_mm=float(width),
height_mm=float(height),
rows=rows,
cols=cols,
layer_count=int(layer_count),
auto_coarsened=bool(coarsened),
expert_limits=bool(expert),
max_cells=int(max_cells),
target_cells=int(target_cells),
detail_level=detail,
node_budget=int(node_budget),
memory_mb_low=memory_low,
memory_mb_high=memory_high,
runtime_class=runtime,
)
class ThermalPlugin(pcbnew.ActionPlugin):
"""
KiCad Action Plugin for 2.5D transient thermal simulation.
This plugin simulates heat spreading across multilayer PCBs using
finite volume methods with BDF2 time integration.
"""
def defaults(self):
"""Set plugin metadata and initialize state."""
self.name = "2.5D Thermal Sim"
self.category = "Simulation"
self.description = "Crash-safe Multilayer Sim"
self.show_toolbar_button = True
self.icon_file_name = os.path.join(os.path.dirname(__file__), "ThermalSim_icon.png")
# Store references for preview
self.board = None
self.copper_ids = []
self.bbox = None
self.pads_list = []
self.stack_info = None
self.last_zone_refill_s = 0.0
self.settings_dialog = None
self.geometry_cache = GeometryCache(persistent=True)
self.operator_cache = ThermalOperatorCache()
self.electrical_cache = ThermalOperatorCache()
self.factorization_cache = ThermalFactorizationCache()
self.cancel_token = None
self.last_artifacts = None
self.startup_dialog = None
self.host_window = None
def _show_startup_progress(self, percent, message):
"""Show immediate feedback while the settings dialog is prepared."""
try:
if self.startup_dialog is None:
self.startup_dialog = wx.ProgressDialog(
"ThermalSim",
message,
maximum=100,
parent=self.host_window,
style=getattr(wx, "PD_APP_MODAL", 0),
)
self.startup_dialog.Update(int(percent), message)
app = wx.GetApp()
if app is not None:
app.Yield()
except Exception:
pass
def _close_startup_progress(self):
"""Close the temporary startup progress window."""
if self.startup_dialog is None:
return
try:
self.startup_dialog.Destroy()
except Exception:
pass
self.startup_dialog = None
def _count_unfilled_copper_zones(self, board):
"""Return the number of normal copper zones without a valid fill."""
try:
zones = list(board.Zones() if hasattr(board, "Zones") else board.GetZones())
except Exception:
return 0
unfilled = 0
for zone in zones:
try:
is_rule_area = bool(
getattr(zone, "GetIsRuleArea", lambda: False)()
)
is_keepout = bool(
getattr(zone, "GetIsKeepout", lambda: False)()
)
if is_rule_area or is_keepout:
continue
if hasattr(zone, "IsFilled") and not zone.IsFilled():
unfilled += 1
except Exception:
continue
return unfilled
def _require_filled_zones(self, board):
"""Block geometry work safely when KiCad copper zones are stale."""
unfilled = self._count_unfilled_copper_zones(board)
if unfilled <= 0:
return True
wx.MessageBox(
f"{unfilled} copper zone(s) are not filled.\n\n"
"Please return to PCB Editor, press B to refill all zones, "
"then start Preview or Run again.\n\n"
"ThermalSim no longer refills zones automatically because that "
"can block the UI for a long time and can crash some KiCad builds.",
"ThermalSim - Refill Copper Zones",
)
return False
def _capture_board_snapshot(self, board, copper_ids, bbox):
"""Capture a deterministic identity for safe persistent geometry reuse."""
tracks = list(board.Tracks() if hasattr(board, "Tracks") else board.GetTracks())
footprints = list(board.Footprints() if hasattr(board, "Footprints") else board.GetFootprints())
zones = list(board.Zones() if hasattr(board, "Zones") else board.GetZones())
primitive_rows = []
for item in tracks:
try:
rect = item.GetBoundingBox()
row = [
type(item).__name__, int(item.GetLayer()), rect.GetX(), rect.GetY(),
rect.GetWidth(), rect.GetHeight(),
]
for getter in ("GetStart", "GetMid", "GetEnd", "GetPosition"):
try:
point = getattr(item, getter)()
row.extend((getter, int(point.x), int(point.y)))
except Exception:
continue
try:
row.extend(("width", int(item.GetWidth())))
except Exception:
pass
primitive_rows.append(tuple(row))
except Exception:
continue
for zone in zones:
try:
rect = zone.GetBoundingBox()
zone_row = [
type(zone).__name__, int(zone.GetLayer()),
rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight(),
]
try:
zone_row.extend(
("layers", tuple(int(value) for value in zone.GetLayerSet().IntSeq()))
)
except Exception:
pass
for getter in (
"GetNetCode",
"GetNetname",
"GetAssignedPriority",
"IsFilled",
):
try:
zone_row.extend((getter, str(getattr(zone, getter)())))
except Exception:
continue
primitive_rows.append(tuple(zone_row))
except Exception:
continue
for fp in footprints:
try:
reference = fp.GetReference()
except Exception:
reference = ""
for pad in fp.Pads():
try:
pos = pad.GetPosition()
rect = pad.GetBoundingBox()
row = [
"pad", reference, pad.GetNumber(), pos.x, pos.y,
pad.GetLayer(), rect.GetX(), rect.GetY(),
rect.GetWidth(), rect.GetHeight(),
]
for getter in ("GetShape", "GetSize", "GetOrientationDegrees"):
try:
value = getattr(pad, getter)()
if hasattr(value, "x") and hasattr(value, "y"):
row.extend((getter, int(value.x), int(value.y)))
else:
row.extend((getter, str(value)))
except Exception:
continue
primitive_rows.append(tuple(row))
except Exception:
continue
bbox_mm = (
bbox.GetX() * 1e-6,
bbox.GetY() * 1e-6,
bbox.GetWidth() * 1e-6,
bbox.GetHeight() * 1e-6,
)
filename = str(board.GetFileName() or "")
try:
file_identity = (
os.path.getsize(filename),
os.stat(filename).st_mtime_ns,
)
except OSError:
file_identity = None
return BoardSnapshot(
filename=filename,
fingerprint=stable_fingerprint(
(bbox_mm, file_identity, tuple(primitive_rows))
),
bbox_mm=bbox_mm,
copper_layers=tuple(int(x) for x in copper_ids),
track_count=len(tracks),
footprint_count=len(footprints),
zone_count=len(zones),
)
def _geometry_key(self, board, copper_ids, bbox, grid, settings, pads):
snapshot = self._capture_board_snapshot(board, copper_ids, bbox)
pad_keys = []
for pad in pads or []:
try:
pos = pad.GetPosition()
pad_keys.append((pad.GetNumber(), pad.GetLayer(), pos.x, pos.y))
except Exception:
pad_keys.append(id(pad))
return geometry_cache_key(snapshot, grid, settings, pad_keys)
def _settings_path(self):
"""Return path to settings persistence file."""
try:
base_dir = wx.StandardPaths.Get().GetUserConfigDir()
except Exception:
base_dir = os.environ.get("APPDATA") or os.path.join(os.path.expanduser("~"), ".config")
return os.path.join(base_dir, "ThermalSim", "thermal_sim_last_settings.json")
def _load_settings(self, path=None):
"""Load settings from a JSON file."""
settings_path = path or self._settings_path()
if path is None and not os.path.isfile(settings_path):
legacy_path = os.path.join(os.path.dirname(__file__), "thermal_sim_last_settings.json")
if os.path.isfile(legacy_path):
try:
with open(legacy_path, "r", encoding="utf-8") as f:
legacy = json.load(f)