File size: 36,160 Bytes
488ed84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

5-Layer PCB Design Simulator for x86 Platforms

Signal integrity, PDN, thermal, and stackup analysis.

"""

import math
import os
from typing import Optional

import numpy as np
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field

app = FastAPI(title="x86 PCB Design Simulator")

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")

# ═══════════════════════════════════════════════════════════════════════════
# CONSTANTS & DEFAULTS
# ═══════════════════════════════════════════════════════════════════════════

# Physical constants
C_LIGHT = 2.998e8          # m/s
EPSILON_0 = 8.854e-12      # F/m
MU_0 = 4 * math.pi * 1e-7  # H/m
COPPER_RESISTIVITY = 1.68e-8  # Ω·m
COPPER_CONDUCTIVITY = 5.96e7  # S/m
COPPER_THERMAL_K = 385.0      # W/(mΒ·K)
FR4_THERMAL_K = 0.3           # W/(mΒ·K)
COPPER_DENSITY = 8960.0       # kg/mΒ³

# Default 5-layer stackup for x86 (thicknesses in mils β†’ converted to metres)
MIL = 25.4e-6  # 1 mil in metres

DEFAULT_STACKUP = [
    {"name": "L1 - Signal Top",   "type": "signal",  "copper_oz": 1.0, "thickness_mil": 1.4,  "material": "Copper"},
    {"name": "Prepreg 1",         "type": "dielectric", "thickness_mil": 4.0,  "material": "FR-4 Prepreg", "er": 4.2, "loss_tangent": 0.02},
    {"name": "L2 - Ground Plane", "type": "plane",   "copper_oz": 1.0, "thickness_mil": 1.4,  "material": "Copper", "net": "GND"},
    {"name": "Core 1",            "type": "dielectric", "thickness_mil": 20.0, "material": "FR-4 Core", "er": 4.5, "loss_tangent": 0.02},
    {"name": "L3 - Signal Inner", "type": "signal",  "copper_oz": 0.5, "thickness_mil": 0.7,  "material": "Copper"},
    {"name": "Core 2",            "type": "dielectric", "thickness_mil": 20.0, "material": "FR-4 Core", "er": 4.5, "loss_tangent": 0.02},
    {"name": "L4 - Power Plane",  "type": "plane",   "copper_oz": 1.0, "thickness_mil": 1.4,  "material": "Copper", "net": "VCC_SPLIT"},
    {"name": "Prepreg 2",         "type": "dielectric", "thickness_mil": 4.0,  "material": "FR-4 Prepreg", "er": 4.2, "loss_tangent": 0.02},
    {"name": "L5 - Signal Bottom","type": "signal",  "copper_oz": 1.0, "thickness_mil": 1.4,  "material": "Copper"},
]

# x86 platform typical interfaces
X86_INTERFACES = {
    "DDR5-4800": {"data_rate_gbps": 4.8, "type": "differential", "impedance_target": 40, "pairs": 64, "bus": "DDR5", "voltage": 1.1},
    "DDR5-5600": {"data_rate_gbps": 5.6, "type": "differential", "impedance_target": 40, "pairs": 64, "bus": "DDR5", "voltage": 1.1},
    "DDR4-3200": {"data_rate_gbps": 3.2, "type": "single-ended", "impedance_target": 40, "pairs": 64, "bus": "DDR4", "voltage": 1.2},
    "PCIe-5.0":  {"data_rate_gbps": 32.0, "type": "differential", "impedance_target": 85, "pairs": 16, "bus": "PCIe 5.0", "voltage": 0.9},
    "PCIe-4.0":  {"data_rate_gbps": 16.0, "type": "differential", "impedance_target": 85, "pairs": 16, "bus": "PCIe 4.0", "voltage": 0.9},
    "PCIe-3.0":  {"data_rate_gbps": 8.0,  "type": "differential", "impedance_target": 85, "pairs": 16, "bus": "PCIe 3.0", "voltage": 0.9},
    "USB3.2-G2": {"data_rate_gbps": 10.0, "type": "differential", "impedance_target": 90, "pairs": 2, "bus": "USB 3.2", "voltage": 0.9},
    "SATA-III":  {"data_rate_gbps": 6.0,  "type": "differential", "impedance_target": 90, "pairs": 2, "bus": "SATA III", "voltage": 0.6},
    "DMI-4.0":   {"data_rate_gbps": 16.0, "type": "differential", "impedance_target": 85, "pairs": 8, "bus": "DMI 4.0", "voltage": 0.9},
    "LPC":       {"data_rate_gbps": 0.033,"type": "single-ended", "impedance_target": 50, "pairs": 4, "bus": "LPC", "voltage": 3.3},
    "SPI":       {"data_rate_gbps": 0.05, "type": "single-ended", "impedance_target": 50, "pairs": 4, "bus": "SPI", "voltage": 3.3},
}

# Common x86 voltage rails
X86_POWER_RAILS = [
    {"name": "VCORE",   "voltage": 1.0,  "current_max_a": 150, "description": "CPU Core"},
    {"name": "VCC_SA",  "voltage": 1.05, "current_max_a": 20,  "description": "System Agent"},
    {"name": "VDDQ",   "voltage": 1.1,  "current_max_a": 10,  "description": "DDR5 Memory"},
    {"name": "VCC_IO",  "voltage": 1.05, "current_max_a": 15,  "description": "I/O Ring"},
    {"name": "V3P3",    "voltage": 3.3,  "current_max_a": 5,   "description": "3.3V Legacy I/O"},
    {"name": "V5P0",    "voltage": 5.0,  "current_max_a": 3,   "description": "5V USB / Legacy"},
    {"name": "V1P8",    "voltage": 1.8,  "current_max_a": 3,   "description": "1.8V Aux"},
    {"name": "V12P0",   "voltage": 12.0, "current_max_a": 20,  "description": "12V Input"},
]


# ═══════════════════════════════════════════════════════════════════════════
# REQUEST MODELS
# ═══════════════════════════════════════════════════════════════════════════

class StackupRequest(BaseModel):
    layers: Optional[list[dict]] = None  # custom stackup or use default

class ImpedanceRequest(BaseModel):
    trace_width_mil: float = Field(default=5.0, ge=1.0, le=100.0)
    trace_spacing_mil: float = Field(default=5.0, ge=1.0, le=100.0)
    dielectric_thickness_mil: float = Field(default=4.0, ge=1.0, le=50.0)
    copper_thickness_oz: float = Field(default=1.0, ge=0.5, le=3.0)
    er: float = Field(default=4.2, ge=2.0, le=12.0)
    frequency_ghz: float = Field(default=1.0, ge=0.01, le=50.0)
    trace_type: str = Field(default="microstrip")  # microstrip, stripline, differential_microstrip, differential_stripline

class SignalIntegrityRequest(BaseModel):
    interface: str = Field(default="PCIe-5.0")
    trace_length_mm: float = Field(default=100.0, ge=1.0, le=500.0)
    trace_width_mil: float = Field(default=5.0, ge=1.0, le=50.0)
    layer: str = Field(default="L1")  # L1, L3, L5
    via_count: int = Field(default=0, ge=0, le=20)
    er: float = Field(default=4.2, ge=2.0, le=12.0)
    loss_tangent: float = Field(default=0.02, ge=0.001, le=0.1)

class PDNRequest(BaseModel):
    rail: str = Field(default="VCORE")
    load_current_a: float = Field(default=100.0, ge=0.1, le=300.0)
    plane_area_sq_in: float = Field(default=4.0, ge=0.5, le=50.0)
    decap_count: int = Field(default=20, ge=0, le=200)
    decap_value_uf: float = Field(default=0.1, ge=0.001, le=1000.0)
    bulk_cap_uf: float = Field(default=470.0, ge=1.0, le=10000.0)
    bulk_cap_count: int = Field(default=4, ge=0, le=50)
    target_impedance_mohm: Optional[float] = None

class ThermalRequest(BaseModel):
    cpu_tdp_w: float = Field(default=125.0, ge=5.0, le=400.0)
    board_area_sq_in: float = Field(default=50.0, ge=10.0, le=200.0)
    ambient_temp_c: float = Field(default=25.0, ge=-40.0, le=85.0)
    copper_coverage_pct: float = Field(default=60.0, ge=10.0, le=95.0)
    airflow_lfm: float = Field(default=200.0, ge=0.0, le=1000.0)
    heatsink: bool = True

class CrosstalkRequest(BaseModel):
    aggressor_width_mil: float = Field(default=5.0, ge=1.0, le=50.0)
    victim_width_mil: float = Field(default=5.0, ge=1.0, le=50.0)
    spacing_mil: float = Field(default=5.0, ge=1.0, le=100.0)
    parallel_length_mm: float = Field(default=50.0, ge=1.0, le=500.0)
    dielectric_height_mil: float = Field(default=4.0, ge=1.0, le=50.0)
    er: float = Field(default=4.2, ge=2.0, le=12.0)
    frequency_ghz: float = Field(default=5.0, ge=0.01, le=50.0)
    trace_type: str = Field(default="microstrip")


# ═══════════════════════════════════════════════════════════════════════════
# SIMULATION ENGINES
# ═══════════════════════════════════════════════════════════════════════════

def analyze_stackup(layers):
    """Analyze PCB stackup properties."""
    if not layers:
        layers = DEFAULT_STACKUP

    total_thickness_mil = sum(l["thickness_mil"] for l in layers)
    copper_layers = [l for l in layers if l["type"] in ("signal", "plane")]
    dielectric_layers = [l for l in layers if l["type"] == "dielectric"]

    # Build detailed analysis
    analyzed = []
    cumulative_mil = 0.0
    for l in layers:
        entry = {**l, "cumulative_mil": cumulative_mil}
        cumulative_mil += l["thickness_mil"]

        if l["type"] in ("signal", "plane"):
            oz = l.get("copper_oz", 1.0)
            entry["thickness_um"] = round(oz * 35.0, 1)  # 1oz β‰ˆ 35Β΅m
            entry["sheet_resistance_mohm_sq"] = round(COPPER_RESISTIVITY / (oz * 35e-6) * 1000, 3)
        elif l["type"] == "dielectric":
            er = l.get("er", 4.5)
            entry["capacitance_pf_per_sq_in"] = round(EPSILON_0 * er / (l["thickness_mil"] * MIL) * (25.4e-3)**2 * 1e12, 2)

        entry["cumulative_top_mil"] = round(entry["cumulative_mil"], 2)
        entry["cumulative_bot_mil"] = round(cumulative_mil, 2)
        analyzed.append(entry)

    # Signal layer pairs and reference planes
    signal_layers_info = []
    for i, l in enumerate(layers):
        if l["type"] == "signal":
            ref_above = None
            ref_below = None
            dist_above = 0
            dist_below = 0
            # Search upward
            for j in range(i - 1, -1, -1):
                dist_above += layers[j]["thickness_mil"]
                if layers[j]["type"] == "plane":
                    ref_above = layers[j]["name"]
                    break
            # Search downward
            for j in range(i + 1, len(layers)):
                dist_below += layers[j]["thickness_mil"]
                if layers[j]["type"] == "plane":
                    ref_below = layers[j]["name"]
                    break
            signal_layers_info.append({
                "layer": l["name"],
                "ref_above": ref_above,
                "ref_below": ref_below,
                "dist_to_ref_above_mil": round(dist_above, 2) if ref_above else None,
                "dist_to_ref_below_mil": round(dist_below, 2) if ref_below else None,
                "routing_type": "microstrip" if (ref_above is None or ref_below is None) else "stripline",
            })

    return {
        "layers": analyzed,
        "total_thickness_mil": round(total_thickness_mil, 2),
        "total_thickness_mm": round(total_thickness_mil * 0.0254, 3),
        "copper_layer_count": len(copper_layers),
        "dielectric_layer_count": len(dielectric_layers),
        "signal_layers": signal_layers_info,
    }


def calc_impedance(req: ImpedanceRequest):
    """Calculate trace impedance using empirical formulas."""
    w = req.trace_width_mil * MIL       # trace width in m
    t = req.copper_thickness_oz * 35e-6  # copper thickness in m
    h = req.dielectric_thickness_mil * MIL  # dielectric height in m
    s = req.trace_spacing_mil * MIL      # spacing for differential
    er = req.er
    f = req.frequency_ghz * 1e9

    # Effective width accounting for copper thickness
    w_eff = w + t * (1 + math.log(2 * h / t)) / math.pi if t > 0 else w
    w_over_h = (w_eff / h) if h > 0 else 1

    results = {}

    if req.trace_type in ("microstrip", "differential_microstrip"):
        # Microstrip impedance (Hammerstad & Jensen)
        if w_over_h <= 1:
            er_eff = (er + 1) / 2 + (er - 1) / 2 * (1 / math.sqrt(1 + 12 / w_over_h) + 0.04 * (1 - w_over_h) ** 2)
            z0 = (60 / math.sqrt(er_eff)) * math.log(8 / w_over_h + w_over_h / 4)
        else:
            er_eff = (er + 1) / 2 + (er - 1) / 2 * (1 / math.sqrt(1 + 12 / w_over_h))
            z0 = (120 * math.pi) / (math.sqrt(er_eff) * (w_over_h + 1.393 + 0.667 * math.log(w_over_h + 1.444)))

        # Propagation delay
        prop_delay_ps_per_inch = 85 * math.sqrt(0.475 * er + 0.67)

        results["single_ended_impedance_ohm"] = round(z0, 2)
        results["effective_er"] = round(er_eff, 3)
        results["propagation_delay_ps_per_inch"] = round(prop_delay_ps_per_inch, 2)
        results["velocity_mm_per_ns"] = round(C_LIGHT / math.sqrt(er_eff) * 1e-6, 2)

        if req.trace_type == "differential_microstrip":
            # Differential microstrip (coupled)
            s_over_h = s / h if h > 0 else 1
            k_diff = 1 - 0.48 * math.exp(-0.96 * s_over_h)
            z_diff = 2 * z0 * k_diff
            results["differential_impedance_ohm"] = round(z_diff, 2)
            results["coupling_factor_k"] = round(k_diff, 4)

    elif req.trace_type in ("stripline", "differential_stripline"):
        # Stripline impedance (symmetric)
        er_eff = er
        z0 = (60 / math.sqrt(er)) * math.log(4 * h / (0.67 * math.pi * (0.8 * w_eff + t)))

        prop_delay_ps_per_inch = 85 * math.sqrt(er)

        results["single_ended_impedance_ohm"] = round(z0, 2)
        results["effective_er"] = round(er_eff, 3)
        results["propagation_delay_ps_per_inch"] = round(prop_delay_ps_per_inch, 2)
        results["velocity_mm_per_ns"] = round(C_LIGHT / math.sqrt(er_eff) * 1e-6, 2)

        if req.trace_type == "differential_stripline":
            s_over_h = s / h if h > 0 else 1
            k_diff = 1 - 0.347 * math.exp(-2.9 * s_over_h)
            z_diff = 2 * z0 * k_diff
            results["differential_impedance_ohm"] = round(z_diff, 2)
            results["coupling_factor_k"] = round(k_diff, 4)

    # Frequency-dependent skin effect loss
    skin_depth_um = math.sqrt(COPPER_RESISTIVITY / (math.pi * f * MU_0)) * 1e6
    conductor_loss_db_per_inch = 0.0  # simplified
    if z0 > 0:
        rs = math.sqrt(math.pi * f * MU_0 / COPPER_CONDUCTIVITY)
        conductor_loss_db_per_inch = (rs / (z0 * w_eff)) * 25.4e-3 * 8.686

    # Dielectric loss
    loss_tan = req.er * 0.005  # approximate
    dielectric_loss_db_per_inch = 2.3 * f * math.sqrt(er) * loss_tan / C_LIGHT * 25.4e-3

    results["skin_depth_um"] = round(skin_depth_um, 3)
    results["conductor_loss_db_per_inch"] = round(conductor_loss_db_per_inch, 4)
    results["dielectric_loss_db_per_inch"] = round(dielectric_loss_db_per_inch, 4)
    results["total_loss_db_per_inch"] = round(conductor_loss_db_per_inch + dielectric_loss_db_per_inch, 4)
    results["trace_type"] = req.trace_type
    results["frequency_ghz"] = req.frequency_ghz

    # Impedance vs frequency sweep
    sweep = []
    for fghz in [0.1, 0.5, 1, 2, 5, 8, 10, 16, 20, 32]:
        fg = fghz * 1e9
        sd = math.sqrt(COPPER_RESISTIVITY / (math.pi * fg * MU_0)) * 1e6
        rs_f = math.sqrt(math.pi * fg * MU_0 / COPPER_CONDUCTIVITY)
        cl = (rs_f / (z0 * w_eff)) * 25.4e-3 * 8.686 if z0 > 0 else 0
        dl = 2.3 * fg * math.sqrt(er) * loss_tan / C_LIGHT * 25.4e-3
        sweep.append({
            "freq_ghz": fghz,
            "skin_depth_um": round(sd, 3),
            "conductor_loss_db_in": round(cl, 4),
            "dielectric_loss_db_in": round(dl, 4),
            "total_loss_db_in": round(cl + dl, 4),
        })
    results["frequency_sweep"] = sweep

    return results


def analyze_signal_integrity(req: SignalIntegrityRequest):
    """Analyze signal integrity for a specific x86 interface."""
    iface = X86_INTERFACES.get(req.interface)
    if not iface:
        return {"error": f"Unknown interface: {req.interface}"}

    data_rate = iface["data_rate_gbps"] * 1e9
    f_nyquist = data_rate / 2
    f_3rd = f_nyquist * 3
    f_5th = f_nyquist * 5

    # Propagation
    er_eff = 0.475 * req.er + 0.67 if req.layer in ("L1", "L5") else req.er
    velocity = C_LIGHT / math.sqrt(er_eff)  # m/s
    trace_len_m = req.trace_length_mm * 1e-3
    prop_delay_ns = trace_len_m / velocity * 1e9
    prop_delay_ps_per_in = 85 * math.sqrt(er_eff)

    # Wavelength at Nyquist
    wavelength_mm = velocity / f_nyquist * 1e3
    trace_as_wavelengths = trace_len_m * 1e3 / wavelength_mm

    # Loss calculation
    w_mil = req.trace_width_mil
    h_mil = 4.0 if req.layer in ("L1", "L5") else 20.0
    z0 = 50.0  # approximate for calculations
    w_m = w_mil * MIL

    # Loss at multiple harmonics
    loss_data = []
    for f_hz, label in [(f_nyquist, "Nyquist"), (f_3rd, "3rd Harmonic"), (f_5th, "5th Harmonic")]:
        rs = math.sqrt(math.pi * f_hz * MU_0 / COPPER_CONDUCTIVITY)
        cond_loss_per_m = (rs / (z0 * w_m)) * 8.686 if w_m > 0 else 0
        diel_loss_per_m = 2.3 * f_hz * math.sqrt(req.er) * req.loss_tangent / C_LIGHT

        total_per_m = cond_loss_per_m + diel_loss_per_m
        total_trace = total_per_m * trace_len_m

        # Via loss estimate (~0.1-0.5 dB per via at high freq)
        via_loss = req.via_count * min(0.5, 0.1 * (f_hz / 1e9) ** 0.5)

        loss_data.append({
            "frequency_ghz": round(f_hz / 1e9, 2),
            "label": label,
            "conductor_loss_db": round(cond_loss_per_m * trace_len_m, 3),
            "dielectric_loss_db": round(diel_loss_per_m * trace_len_m, 3),
            "via_loss_db": round(via_loss, 3),
            "total_loss_db": round(total_trace + via_loss, 3),
        })

    # Eye diagram estimation
    total_insertion_loss = loss_data[0]["total_loss_db"]  # at Nyquist
    eye_height_pct = max(0, 100 * math.exp(-0.15 * total_insertion_loss))
    eye_width_pct = max(0, 100 * (1 - total_insertion_loss / 30))

    # Timing
    bit_period_ps = 1e12 / data_rate
    rise_time_ps = bit_period_ps * 0.3  # ~30% of bit period

    # Length matching requirement
    if "DDR" in iface["bus"]:
        length_match_mil = 50  # tight matching for DDR
    elif "PCIe" in iface["bus"]:
        length_match_mil = 100  # lane-to-lane
    else:
        length_match_mil = 500  # relaxed

    skew_budget_ps = length_match_mil * MIL / velocity * 1e12

    # Pass/fail checks
    checks = []

    # Loss budget
    if "PCIe 5.0" in iface["bus"]:
        loss_budget_db = 28
    elif "PCIe 4.0" in iface["bus"]:
        loss_budget_db = 28
    elif "DDR" in iface["bus"]:
        loss_budget_db = 6
    else:
        loss_budget_db = 20

    checks.append({
        "check": "Insertion Loss Budget",
        "value": f"{total_insertion_loss:.2f} dB",
        "limit": f"< {loss_budget_db} dB",
        "pass": total_insertion_loss < loss_budget_db,
    })

    # Trace length
    max_length_mm = 400 if "PCIe" in iface["bus"] else 150 if "DDR" in iface["bus"] else 300
    checks.append({
        "check": "Trace Length",
        "value": f"{req.trace_length_mm:.1f} mm",
        "limit": f"< {max_length_mm} mm",
        "pass": req.trace_length_mm < max_length_mm,
    })

    # Via count
    max_vias = 2 if data_rate > 10e9 else 4
    checks.append({
        "check": "Via Transitions",
        "value": str(req.via_count),
        "limit": f"≀ {max_vias}",
        "pass": req.via_count <= max_vias,
    })

    return {
        "interface": req.interface,
        "interface_info": iface,
        "trace_length_mm": req.trace_length_mm,
        "layer": req.layer,
        "propagation_delay_ns": round(prop_delay_ns, 4),
        "prop_delay_ps_per_in": round(prop_delay_ps_per_in, 2),
        "velocity_mm_per_ns": round(velocity * 1e-6, 2),
        "wavelength_at_nyquist_mm": round(wavelength_mm, 2),
        "trace_electrical_length_wavelengths": round(trace_as_wavelengths, 3),
        "bit_period_ps": round(bit_period_ps, 2),
        "rise_time_ps": round(rise_time_ps, 2),
        "loss_breakdown": loss_data,
        "total_insertion_loss_db": round(total_insertion_loss, 3),
        "eye_height_pct": round(eye_height_pct, 1),
        "eye_width_pct": round(eye_width_pct, 1),
        "length_match_tolerance_mil": length_match_mil,
        "skew_budget_ps": round(skew_budget_ps, 3),
        "design_checks": checks,
    }


def analyze_pdn(req: PDNRequest):
    """Power Delivery Network impedance and noise analysis."""
    rail_info = None
    for r in X86_POWER_RAILS:
        if r["name"] == req.rail:
            rail_info = r
            break
    if not rail_info:
        return {"error": f"Unknown rail: {req.rail}"}

    voltage = rail_info["voltage"]
    load_a = req.load_current_a

    # Target impedance: Z_target = V_ripple / I_transient
    # Typically 5% ripple allowed
    ripple_pct = 5.0
    if req.target_impedance_mohm:
        z_target = req.target_impedance_mohm / 1000
    else:
        z_target = (voltage * ripple_pct / 100) / load_a

    z_target_mohm = z_target * 1000

    # Plane capacitance (parallel plate)
    area_m2 = req.plane_area_sq_in * (25.4e-3) ** 2
    dielectric_h = 20 * MIL  # core between power/ground planes
    er_core = 4.5
    plane_cap_pf = EPSILON_0 * er_core * area_m2 / (dielectric_h) * 1e12
    plane_cap_nf = plane_cap_pf / 1000

    # Decoupling capacitors
    decap_total_uf = req.decap_count * req.decap_value_uf
    decap_esl_nh = 0.5  # typical MLCC ESL
    decap_esr_mohm = 5.0  # typical MLCC ESR

    # Bulk caps
    bulk_total_uf = req.bulk_cap_count * req.bulk_cap_uf
    bulk_esl_nh = 2.0
    bulk_esr_mohm = 10.0

    # PDN impedance profile across frequency
    freq_sweep = []
    freqs = np.logspace(3, 10, 50)  # 1kHz to 10GHz
    for f in freqs:
        omega = 2 * math.pi * f

        # VRM (acts as low-frequency source, ~1mΞ© up to ~10kHz)
        z_vrm = complex(0.001, 0) if f < 1e4 else complex(0.001, omega * 1e-6)

        # Bulk caps (effective below ~1MHz)
        if req.bulk_cap_count > 0:
            c_bulk = bulk_total_uf * 1e-6
            z_bulk_cap = 1 / (omega * c_bulk) if omega * c_bulk > 0 else 1e6
            z_bulk_esl = omega * bulk_esl_nh * 1e-9 / req.bulk_cap_count
            z_bulk_esr = bulk_esr_mohm * 1e-3 / req.bulk_cap_count
            z_bulk = complex(z_bulk_esr, z_bulk_esl - z_bulk_cap)
        else:
            z_bulk = complex(1e6, 0)

        # MLCC decaps (effective ~100kHz to ~100MHz)
        if req.decap_count > 0:
            c_decap = decap_total_uf * 1e-6
            z_decap_cap = 1 / (omega * c_decap) if omega * c_decap > 0 else 1e6
            z_decap_esl = omega * decap_esl_nh * 1e-9 / req.decap_count
            z_decap_esr = decap_esr_mohm * 1e-3 / req.decap_count
            z_decap = complex(z_decap_esr, z_decap_esl - z_decap_cap)
        else:
            z_decap = complex(1e6, 0)

        # Plane capacitance (high frequency)
        c_plane = plane_cap_pf * 1e-12
        z_plane_cap = 1 / (omega * c_plane) if omega * c_plane > 0 else 1e6
        z_plane = complex(0.0005, -z_plane_cap)  # very low ESR

        # Parallel combination
        z_values = [z_bulk, z_decap, z_plane]
        z_total = z_values[0]
        for zv in z_values[1:]:
            if abs(z_total) + abs(zv) > 0:
                z_total = (z_total * zv) / (z_total + zv)

        freq_sweep.append({
            "freq_hz": float(f),
            "freq_label": format_freq(f),
            "z_magnitude_mohm": round(abs(z_total) * 1000, 4),
            "z_target_mohm": round(z_target_mohm, 4),
            "meets_target": abs(z_total) * 1000 <= z_target_mohm,
        })

    # Anti-resonance peaks
    anti_res = []
    for i in range(1, len(freq_sweep) - 1):
        if freq_sweep[i]["z_magnitude_mohm"] > freq_sweep[i-1]["z_magnitude_mohm"] and \
           freq_sweep[i]["z_magnitude_mohm"] > freq_sweep[i+1]["z_magnitude_mohm"] and \
           freq_sweep[i]["z_magnitude_mohm"] > z_target_mohm:
            anti_res.append({
                "frequency": freq_sweep[i]["freq_label"],
                "impedance_mohm": freq_sweep[i]["z_magnitude_mohm"],
            })

    # DC resistance of power plane
    copper_t = 1.0 * 35e-6  # 1oz copper
    r_plane = COPPER_RESISTIVITY * math.sqrt(area_m2) / (copper_t * math.sqrt(area_m2))
    dc_drop_mv = r_plane * load_a * 1000

    # Power dissipation in plane
    plane_power_w = load_a ** 2 * r_plane

    violations = sum(1 for s in freq_sweep if not s["meets_target"])

    return {
        "rail": req.rail,
        "rail_info": rail_info,
        "target_impedance_mohm": round(z_target_mohm, 3),
        "ripple_budget_pct": ripple_pct,
        "plane_capacitance_nf": round(plane_cap_nf, 2),
        "total_decap_uf": round(decap_total_uf, 2),
        "total_bulk_uf": round(bulk_total_uf, 1),
        "dc_plane_resistance_mohm": round(r_plane * 1000, 4),
        "dc_voltage_drop_mv": round(dc_drop_mv, 2),
        "plane_power_dissipation_w": round(plane_power_w, 3),
        "impedance_profile": freq_sweep,
        "anti_resonance_peaks": anti_res,
        "target_violations": violations,
        "total_freq_points": len(freq_sweep),
        "verdict": "PASS" if violations < 5 else "MARGINAL" if violations < 15 else "FAIL",
    }


def analyze_thermal(req: ThermalRequest):
    """Simplified thermal analysis of PCB with x86 CPU."""
    board_area_m2 = req.board_area_sq_in * (25.4e-3) ** 2
    copper_pct = req.copper_coverage_pct / 100

    # Effective thermal conductivity of PCB
    # Weighted average of copper and FR-4
    total_thickness = 52.8 * MIL  # ~1.34mm for 5-layer
    k_eff = copper_pct * COPPER_THERMAL_K + (1 - copper_pct) * FR4_THERMAL_K  # lateral
    k_through = 1.0 / (copper_pct / COPPER_THERMAL_K + (1 - copper_pct) / FR4_THERMAL_K)  # through-plane

    # Thermal vias under CPU
    via_diameter_mm = 0.3
    via_plating_um = 25
    via_pitch_mm = 1.0
    cpu_area_mm2 = 37.5 * 37.5  # typical IHS
    vias_under_cpu = int(cpu_area_mm2 / (via_pitch_mm ** 2))
    via_copper_area = vias_under_cpu * math.pi * via_diameter_mm * 1e-3 * via_plating_um * 1e-6
    k_via_array = COPPER_THERMAL_K * via_copper_area / (cpu_area_mm2 * 1e-6)

    # Convection coefficient
    # Natural convection: ~5-10 W/(mΒ²Β·K), forced: ~25-100 W/(mΒ²Β·K)
    if req.airflow_lfm > 0:
        h_conv = 10 + 0.1 * req.airflow_lfm  # W/(mΒ²Β·K)
    else:
        h_conv = 8.0  # natural convection

    # Heatsink thermal resistance
    if req.heatsink:
        r_heatsink = 0.3  # Β°C/W typical tower cooler
    else:
        r_heatsink = 1e6  # no heatsink

    # Thermal resistances
    r_jc = 0.2  # junction to case (CPU IHS)
    r_cs = 0.1 if req.heatsink else 1e6  # case to sink (TIM)
    r_sa_heatsink = r_heatsink  # sink to ambient

    # Board spreading resistance
    r_pcb_lateral = math.sqrt(board_area_m2) / (k_eff * total_thickness)
    r_pcb_through = total_thickness / (k_through * cpu_area_mm2 * 1e-6)
    r_conv_board = 1 / (h_conv * board_area_m2)

    # CPU temperature path through heatsink
    r_total_hs = r_jc + r_cs + r_sa_heatsink
    t_junction_hs = req.ambient_temp_c + req.cpu_tdp_w * r_total_hs

    # Board temperature (power spreading through PCB)
    board_power_fraction = 0.05  # ~5% of TDP dissipated into board
    board_power = req.cpu_tdp_w * board_power_fraction
    r_total_board = r_pcb_through + r_conv_board
    t_board_under_cpu = req.ambient_temp_c + board_power * r_total_board
    t_board_avg = req.ambient_temp_c + board_power * r_conv_board * 0.3

    # VRM thermal (estimate 90% efficiency, losses = 10% of total power)
    vrm_loss_w = req.cpu_tdp_w * 0.10
    vrm_area_m2 = 4e-4  # ~20mm x 20mm
    t_vrm = req.ambient_temp_c + vrm_loss_w / (h_conv * vrm_area_m2)

    # Thermal map (simplified grid)
    grid_size = 15
    thermal_map = []
    for row in range(grid_size):
        map_row = []
        for col in range(grid_size):
            # Distance from CPU center (assume CPU at center)
            dx = (col - grid_size / 2) / (grid_size / 2)
            dy = (row - grid_size / 2) / (grid_size / 2)
            dist = math.sqrt(dx ** 2 + dy ** 2)

            # Temperature decreases with distance
            base_temp = req.ambient_temp_c
            cpu_contrib = max(0, (t_board_under_cpu - base_temp) * math.exp(-2.5 * dist))

            # VRM hotspot (top-left area)
            vrm_dx = (col - grid_size * 0.2) / (grid_size / 2)
            vrm_dy = (row - grid_size * 0.2) / (grid_size / 2)
            vrm_dist = math.sqrt(vrm_dx ** 2 + vrm_dy ** 2)
            vrm_contrib = max(0, (t_vrm - base_temp) * 0.3 * math.exp(-3 * vrm_dist))

            temp = base_temp + cpu_contrib + vrm_contrib
            map_row.append(round(temp, 1))
        thermal_map.append(map_row)

    return {
        "cpu_tdp_w": req.cpu_tdp_w,
        "ambient_temp_c": req.ambient_temp_c,
        "board_area_sq_in": req.board_area_sq_in,
        "copper_coverage_pct": req.copper_coverage_pct,
        "airflow_lfm": req.airflow_lfm,
        "heatsink_installed": req.heatsink,
        "junction_temp_c": round(t_junction_hs, 1),
        "board_temp_under_cpu_c": round(t_board_under_cpu, 1),
        "board_avg_temp_c": round(t_board_avg, 1),
        "vrm_surface_temp_c": round(min(t_vrm, 150), 1),
        "thermal_vias_under_cpu": vias_under_cpu,
        "convection_coeff_w_m2k": round(h_conv, 2),
        "r_junction_case": round(r_jc, 3),
        "r_case_sink": round(r_cs, 3) if req.heatsink else "N/A",
        "r_sink_ambient": round(r_sa_heatsink, 3) if req.heatsink else "N/A",
        "r_pcb_through": round(r_pcb_through, 3),
        "effective_k_lateral_w_mk": round(k_eff, 2),
        "effective_k_through_w_mk": round(k_through, 4),
        "thermal_map": thermal_map,
        "tj_max_verdict": "SAFE" if t_junction_hs < 100 else ("WARNING" if t_junction_hs < 105 else "CRITICAL"),
        "vrm_verdict": "SAFE" if t_vrm < 110 else ("WARNING" if t_vrm < 125 else "CRITICAL"),
    }


def analyze_crosstalk(req: CrosstalkRequest):
    """Near-end and far-end crosstalk analysis."""
    w = req.aggressor_width_mil * MIL
    s = req.spacing_mil * MIL
    h = req.dielectric_height_mil * MIL
    L = req.parallel_length_mm * 1e-3
    er = req.er
    f = req.frequency_ghz * 1e9

    # Coupling coefficients (empirical)
    s_over_h = s / h if h > 0 else 10
    w_over_h = w / h if h > 0 else 1

    # Mutual capacitance / self capacitance ratio
    if req.trace_type == "microstrip":
        # For microstrip, coupling is higher since fields in air
        kb = 0.67 * math.exp(-1.18 * s_over_h)
        kf = 0.45 * math.exp(-0.96 * s_over_h)
    else:
        # Stripline has less coupling
        kb = 0.35 * math.exp(-1.8 * s_over_h)
        kf = 0.25 * math.exp(-1.5 * s_over_h)

    # NEXT (Near-End Crosstalk)
    next_coeff = kb / 4
    next_db = 20 * math.log10(max(next_coeff, 1e-10))

    # FEXT (Far-End Crosstalk)
    velocity = C_LIGHT / math.sqrt(er)
    wavelength = velocity / f
    electrical_length = L / wavelength

    fext_coeff = kf * electrical_length * math.pi
    fext_coeff = min(fext_coeff, 0.99)
    fext_db = 20 * math.log10(max(fext_coeff, 1e-10))

    # Crosstalk vs spacing sweep
    spacing_sweep = []
    for sp_mil in [3, 4, 5, 6, 8, 10, 12, 15, 20, 25, 30, 40, 50]:
        sp = sp_mil * MIL
        soh = sp / h if h > 0 else 10
        if req.trace_type == "microstrip":
            kb_s = 0.67 * math.exp(-1.18 * soh)
            kf_s = 0.45 * math.exp(-0.96 * soh)
        else:
            kb_s = 0.35 * math.exp(-1.8 * soh)
            kf_s = 0.25 * math.exp(-1.5 * soh)

        next_s = kb_s / 4
        fext_s = min(kf_s * electrical_length * math.pi, 0.99)

        spacing_sweep.append({
            "spacing_mil": sp_mil,
            "next_db": round(20 * math.log10(max(next_s, 1e-10)), 2),
            "fext_db": round(20 * math.log10(max(fext_s, 1e-10)), 2),
        })

    # 3W rule check (spacing >= 3Γ— width)
    three_w_rule = s >= 3 * w
    # Guard trace effectiveness
    guard_trace_reduction_db = 10 if three_w_rule else 6

    return {
        "aggressor_width_mil": req.aggressor_width_mil,
        "victim_width_mil": req.victim_width_mil,
        "spacing_mil": req.spacing_mil,
        "parallel_length_mm": req.parallel_length_mm,
        "dielectric_height_mil": req.dielectric_height_mil,
        "trace_type": req.trace_type,
        "frequency_ghz": req.frequency_ghz,
        "next_coefficient": round(next_coeff, 6),
        "next_db": round(next_db, 2),
        "fext_coefficient": round(fext_coeff, 6),
        "fext_db": round(fext_db, 2),
        "electrical_length_wavelengths": round(electrical_length, 4),
        "three_w_rule_met": three_w_rule,
        "guard_trace_reduction_db": guard_trace_reduction_db,
        "spacing_sweep": spacing_sweep,
        "recommendation": get_crosstalk_recommendation(next_db, fext_db, s_over_h),
    }


def get_crosstalk_recommendation(next_db, fext_db, s_over_h):
    issues = []
    if next_db > -25:
        issues.append(f"NEXT too high ({next_db:.1f} dB). Increase spacing or use guard traces.")
    if fext_db > -30:
        issues.append(f"FEXT too high ({fext_db:.1f} dB). Reduce parallel run length or increase spacing.")
    if s_over_h < 2:
        issues.append("Spacing/height ratio < 2. Consider wider trace spacing or thinner dielectric.")
    if not issues:
        return "Crosstalk levels are within acceptable limits."
    return " ".join(issues)


def format_freq(f):
    if f >= 1e9:
        return f"{f/1e9:.1f} GHz"
    elif f >= 1e6:
        return f"{f/1e6:.1f} MHz"
    elif f >= 1e3:
        return f"{f/1e3:.1f} kHz"
    return f"{f:.0f} Hz"


# ═══════════════════════════════════════════════════════════════════════════
# API ENDPOINTS
# ═══════════════════════════════════════════════════════════════════════════

@app.post("/api/stackup")
async def api_stackup(req: StackupRequest):
    return analyze_stackup(req.layers)

@app.post("/api/impedance")
async def api_impedance(req: ImpedanceRequest):
    return calc_impedance(req)

@app.post("/api/signal-integrity")
async def api_si(req: SignalIntegrityRequest):
    return analyze_signal_integrity(req)

@app.post("/api/pdn")
async def api_pdn(req: PDNRequest):
    return analyze_pdn(req)

@app.post("/api/thermal")
async def api_thermal(req: ThermalRequest):
    return analyze_thermal(req)

@app.post("/api/crosstalk")
async def api_crosstalk(req: CrosstalkRequest):
    return analyze_crosstalk(req)

@app.get("/api/interfaces")
async def api_interfaces():
    return {"interfaces": X86_INTERFACES}

@app.get("/api/power-rails")
async def api_rails():
    return {"rails": X86_POWER_RAILS}


# ─── Static Files ───────────────────────────────────────────────────────

app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")

@app.get("/")
async def root():
    return FileResponse(os.path.join(STATIC_DIR, "index.html"))

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))