-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse_cases.py
More file actions
982 lines (819 loc) · 43.8 KB
/
use_cases.py
File metadata and controls
982 lines (819 loc) · 43.8 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
"""
use_cases.py — Production Use Cases for the Coherent Fiber Neural Network
==========================================================================
Three real-world optical networking problems solved by the same physical
substrate: coherent IQ modulation + WDM + homodyne detection.
UC1 Multi-Impairment Classifier (MIC)
Live diagnosis of the dominant link impairment.
Input : 8 receiver-side signal quality metrics
Output: 5 classes (Normal / CD / PMD / OSNR / Nonlinear)
UC2 Adaptive Modulation & Coding Controller (AMC)
Select the highest-throughput MCS the channel can support.
Input : 8 channel-state parameters
Output: 6 classes (OOK / PAM-4 / PAM-8 / QPSK / QAM-16 / QAM-64)
UC3 OTDR Fault Diagnosis Engine (FDE)
Identify fault type from optical time-domain reflectometry traces.
Input : 8 OTDR-derived features
Output: 5 classes (Normal / ConnectorLoss / Splice / Break / MacroBend)
Key insight
───────────
The SAME coherent fiber NN architecture (different trained weights)
solves all three problems. The optical ring computes Σwᵢxᵢ at the
speed of light regardless of what those weights represent.
This is the photonic universal-function-approximation principle.
Physical substrate (unchanged across all use cases):
1550 nm CW laser → IQ modulator (φ=0/π) → SMF G.652
→ EDFA → DCF coherent sum → 90°-hybrid + balanced PD
Output: I ∝ Re(Σwᵢxᵢ·e^jφ) = Σwᵢxᵢ (exact, single pass)
"""
import numpy as np
import sys
import os
import json
import csv
# ── path fix so we can import from same directory ────────────────────────────
sys.path.insert(0, os.path.dirname(__file__))
from coherent_nn import CoherentFiberNetwork, minmax_norm
from recursive_prompt import MetaMetaPrompt
from recursive_dev import CrossEntropyTrainer
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# SHARED UTILITIES
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def _train_and_transfer(layer_sizes, X_tr, Y_tr, X_te, Y_te,
epochs=600, lr=1e-3, l2=5e-5, seed=42,
mp: MetaMetaPrompt = None, verbose=True):
"""
Train theoretic CE model → transfer weights to coherent fiber NN.
Returns (fiber_nn, test_accuracy, trainer).
"""
trainer = CrossEntropyTrainer(layer_sizes, lr=lr, l2=l2)
trainer.rng = np.random.default_rng(seed)
losses = []
best_loss = float('inf')
step = max(1, epochs // 5)
for ep in range(epochs):
# Cosine LR decay
lr_ep = lr * 0.01 + 0.99 * lr * 0.5 * (1 + np.cos(np.pi * ep / epochs))
trainer.lr = lr_ep
idx = np.random.default_rng(ep + seed).permutation(len(X_tr))
ep_loss = 0.0
for i in idx:
x_n = minmax_norm(X_tr[i])
y_hat = trainer.forward(x_n)
ep_loss += trainer._ce(y_hat, Y_tr[i])
gW, gb = trainer.backward_ce(Y_tr[i])
trainer._adam(gW, gb)
ep_loss /= len(X_tr)
losses.append(ep_loss)
if verbose and (ep % step == 0 or ep == epochs - 1):
print(f" ep {ep+1:>4}/{epochs} CE={ep_loss:.5f} lr={lr_ep:.2e}")
# Transfer to coherent fiber NN
shapes = [(layer_sizes[i+1], layer_sizes[i]) for i in range(len(layer_sizes)-1)]
if mp is None:
mp = MetaMetaPrompt(seed_dim=64, max_depth=16, rng_seed=seed)
_, encs = mp.recursive_unfold(shapes)
fiber_nn = CoherentFiberNetwork(layer_sizes, noisy=False)
fiber_nn.load_trained_weights(trainer.W, trainer.b)
fiber_nn.optical_encodings = encs
# Per-layer calibration
n_hidden = len(fiber_nn.layers) - 1
for i in range(n_hidden):
th_vals, fi_vals = [], []
for x in X_tr:
x_n = minmax_norm(x)
trainer.forward(x_n)
th_vals.append(float(np.mean(np.abs(trainer._z[i]))))
fiber_nn.forward(x)
fi_vals.append(float(np.mean(np.abs(
fiber_nn._layer_outputs[i + 1]))) + 1e-8)
sc = float(np.clip(np.mean(th_vals) / (np.mean(fi_vals) + 1e-8), 0.1, 8.0))
fiber_nn.layers[i].W *= sc
acc = fiber_nn.evaluate(X_te, Y_te)
th_acc = trainer.evaluate(X_te, Y_te)
return fiber_nn, acc, th_acc, trainer
def _print_conf_matrix(fiber_nn, X_te, Y_te, class_names):
"""Print confusion matrix for a fiber NN."""
n = len(class_names)
cm = np.zeros((n, n), dtype=int)
for x, y in zip(X_te, Y_te):
true_c = int(np.argmax(y))
pred_c = fiber_nn.predict(x)
cm[true_c][pred_c] += 1
w = max(len(c) for c in class_names) + 1
print(f"\n Confusion matrix (row=true, col=pred):")
print(" " + " " * w + " " + " ".join(f"{c:>{w}}" for c in class_names))
for i, row in enumerate(cm):
vals = " ".join(
f"\033[1m{v:>{w}}\033[0m" if j == i else f"{v:>{w}}"
for j, v in enumerate(row))
print(f" {class_names[i]:>{w}} {vals}")
def _optical_probe(fiber_nn, x_raw, class_names):
"""Show per-class optical output probabilities as a bar chart."""
out = fiber_nn.forward(x_raw)
pred = int(np.argmax(out))
w = max(len(c) for c in class_names)
BAR = "█"
print(f"\n Optical probability readout (homodyne detection):")
for i, (name, p) in enumerate(zip(class_names, out)):
bar = BAR * int(p * 30)
mark = " ◄ PREDICTED" if i == pred else ""
print(f" {name:>{w}} {bar:<30} {p:.4f}{mark}")
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# USE CASE 1 — MULTI-IMPAIRMENT CLASSIFIER (MIC)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MIC_CLASSES = ['Normal', 'CD-dominant', 'PMD-dominant', 'OSNR-limited', 'Nonlinear']
MIC_FEATURES = ['EVM(%)', 'Q-factor(dB)', 'Eye-open', 'BER(log)',
'Spec-skew', 'RMS-jitter(ps)', 'CD-est(ps/nm)', 'DGD(ps)']
def _mic_sample(rng, label):
"""
Generate one signal quality measurement vector for a given impairment class.
Values are physically motivated ranges from coherent optical comms.
"""
noise = lambda s: rng.normal(0, s)
if label == 0: # Normal
evm = 2.0 + noise(0.3)
q = 14.0 + noise(0.5)
eye = 0.85 + noise(0.03)
ber = -7.0 + noise(0.2)
skew = 0.1 + noise(0.05)
jitt = 3.0 + noise(0.5)
cd = 10.0 + noise(2.0)
dgd = 1.0 + noise(0.2)
elif label == 1: # CD-dominant (chromatic dispersion)
evm = 8.0 + noise(1.0)
q = 10.0 + noise(0.8)
eye = 0.55 + noise(0.05)
ber = -4.5 + noise(0.3)
skew = 0.3 + noise(0.1)
jitt = 12.0 + noise(2.0) # jitter high — ISI from CD
cd = 800.0+ noise(50.0) # high residual CD
dgd = 1.5 + noise(0.3)
elif label == 2: # PMD-dominant (polarisation mode dispersion)
evm = 7.0 + noise(1.0)
q = 10.5 + noise(0.8)
eye = 0.60 + noise(0.05)
ber = -4.8 + noise(0.3)
skew = 0.15 + noise(0.05)
jitt = 8.0 + noise(1.5)
cd = 15.0 + noise(5.0)
dgd = 25.0 + noise(5.0) # DGD high — PMD signature
elif label == 3: # OSNR-limited (amplifier noise dominant)
evm = 12.0 + noise(1.5)
q = 8.0 + noise(0.8)
eye = 0.40 + noise(0.05)
ber = -3.0 + noise(0.3)
skew = 0.2 + noise(0.08)
jitt = 5.0 + noise(1.0)
cd = 12.0 + noise(3.0)
dgd = 2.0 + noise(0.5)
else: # Nonlinear (SPM/XPM/FWM)
evm = 9.0 + noise(1.2)
q = 9.5 + noise(0.8)
eye = 0.50 + noise(0.05)
ber = -3.8 + noise(0.3)
skew = 0.8 + noise(0.15) # spectral skew — nonlinear signature
jitt = 6.0 + noise(1.0)
cd = 20.0 + noise(5.0)
dgd = 1.8 + noise(0.4)
return np.array([evm, q, eye, ber, skew, jitt, cd, dgd])
def generate_mic_dataset(n=300, seed=42):
rng = np.random.default_rng(seed)
n_cls = len(MIC_CLASSES)
X, Y = [], []
for label in range(n_cls):
for _ in range(n // n_cls):
X.append(_mic_sample(rng, label))
y = np.zeros(n_cls); y[label] = 1.0
Y.append(y)
X, Y = np.array(X), np.array(Y)
idx = rng.permutation(len(X))
return X[idx], Y[idx]
def run_uc1(mp, verbose=True):
print("\n" + "━"*62)
print(" USE CASE 1 — MULTI-IMPAIRMENT CLASSIFIER (MIC)")
print(" Real-time fiber link health monitor (no signal interruption)")
print("━"*62)
print(f" Classes : {' | '.join(MIC_CLASSES)}")
print(f" Features : {', '.join(MIC_FEATURES)}")
print(f" Dataset : 300 samples · 80/20 split")
print(f" Network : [8, 20, 10, 5] coherent fiber NN")
X, Y = generate_mic_dataset(n=300)
split = int(0.8 * len(X))
X_tr, Y_tr = X[:split], Y[:split]
X_te, Y_te = X[split:], Y[split:]
print(f"\n [Training theoretic model → coherent fiber NN]")
fiber_nn, acc, th_acc, trainer = _train_and_transfer(
[8, 20, 10, 5], X_tr, Y_tr, X_te, Y_te,
epochs=600, lr=1e-3, mp=mp, verbose=verbose)
print(f"\n Theory accuracy : {th_acc*100:.1f}%")
print(f" Fiber accuracy : {acc*100:.1f}%")
print(f" WDM λ-channels : {fiber_nn.total_lambda_channels()}")
_print_conf_matrix(fiber_nn, X_te, Y_te, MIC_CLASSES)
# Live probe: synthetic "PMD event" arriving on the network
print(f"\n ── Live probe: PMD event entering the optical ring ──")
probe = _mic_sample(np.random.default_rng(99), label=2) # PMD
probe += np.random.default_rng(7).normal(0, 0.5, probe.shape)
print(f" Sensor reading: {dict(zip(MIC_FEATURES, np.round(probe, 2)))}")
_optical_probe(fiber_nn, probe, MIC_CLASSES)
return fiber_nn, acc
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# USE CASE 2 — ADAPTIVE MODULATION & CODING CONTROLLER (AMC)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
AMC_CLASSES = ['OOK', 'PAM-4', 'PAM-8', 'QPSK', 'QAM-16', 'QAM-64']
AMC_FEATURES = ['OSNR(dB)', 'PathLoss(dB)', 'Spans(#)',
'NoiseFig(dB)', 'ResCDisp(ps/nm)', 'PMD(ps)',
'NonlinCoef(1/W/km)', 'Margin(dB)']
# Each class has distinct, well-separated channel-state signatures
# Generated label-first (same strategy as UC1/UC3) for clean boundaries
def _amc_sample(rng, label):
"""
Generate channel-state vector for a given optimal modulation class.
Physical interpretation: the channel conditions that make each
format the best choice are physically distinct enough to classify.
OOK → very poor channel (short reach, high loss, low OSNR)
PAM-4 → moderate loss, some PMD
PAM-8 → decent OSNR, low PMD, some dispersion
QPSK → good OSNR, moderate loss, coherent-friendly
QAM-16 → high OSNR, low loss, controlled impairments
QAM-64 → excellent OSNR, low loss, low noise, metro-core
"""
n = lambda mu, s: float(rng.normal(mu, s))
if label == 0: # OOK — very challenged channel
return np.array([n(9,0.5), n(28,1.5), n(18,1), n(7.5,0.3),
n(180,10), n(9,0.5), n(2.8,0.1), n(-1.5,0.2)])
elif label == 1: # PAM-4 — moderate channel
return np.array([n(13,0.5), n(22,1.2), n(12,1), n(6.5,0.3),
n(120,8), n(6,0.4), n(2.0,0.1), n(0.5,0.2)])
elif label == 2: # PAM-8 — good channel, intensity-based
return np.array([n(17,0.5), n(18,1.0), n(8,1), n(5.5,0.3),
n(60,6), n(3,0.3), n(1.5,0.1), n(1.5,0.2)])
elif label == 3: # QPSK — coherent, tolerates more PMD
return np.array([n(15,0.5), n(20,1.0), n(10,1), n(6.0,0.3),
n(90,8), n(5,0.4), n(1.8,0.1), n(1.0,0.2)])
elif label == 4: # QAM-16 — high OSNR, metro/regional
return np.array([n(22,0.5), n(14,0.8), n(5,0.8), n(5.0,0.2),
n(25,4), n(1.5,0.2),n(1.0,0.1), n(3.0,0.2)])
else: # QAM-64 — premium metro-core
return np.array([n(30,0.5), n(10,0.6), n(3,0.5), n(4.2,0.2),
n(8,2), n(0.5,0.1), n(0.7,0.05), n(4.0,0.2)])
def generate_amc_dataset(n=360, seed=42):
rng = np.random.default_rng(seed)
n_cls = len(AMC_CLASSES)
X, Y = [], []
for label in range(n_cls):
for _ in range(n // n_cls):
X.append(_amc_sample(rng, label))
y = np.zeros(n_cls); y[label] = 1.0
Y.append(y)
X, Y = np.array(X), np.array(Y)
idx = rng.permutation(len(X))
return X[idx], Y[idx]
def run_uc2(mp, verbose=True):
print("\n" + "━"*62)
print(" USE CASE 2 — ADAPTIVE MODULATION & CODING CONTROLLER (AMC)")
print(" Maximise spectral efficiency from real-time channel state")
print("━"*62)
print(f" Classes : {' | '.join(AMC_CLASSES)}")
print(f" Features : {', '.join(AMC_FEATURES)}")
print(f" Dataset : 360 samples · 80/20 split")
print(f" Network : [8, 24, 12, 6] coherent fiber NN")
X, Y = generate_amc_dataset(n=360)
split = int(0.8 * len(X))
X_tr, Y_tr = X[:split], Y[:split]
X_te, Y_te = X[split:], Y[split:]
print(f"\n [Training theoretic model → coherent fiber NN]")
fiber_nn, acc, th_acc, trainer = _train_and_transfer(
[8, 24, 12, 6], X_tr, Y_tr, X_te, Y_te,
epochs=600, lr=1e-3, mp=mp, verbose=verbose)
print(f"\n Theory accuracy : {th_acc*100:.1f}%")
print(f" Fiber accuracy : {acc*100:.1f}%")
print(f" WDM λ-channels : {fiber_nn.total_lambda_channels()}")
_print_conf_matrix(fiber_nn, X_te, Y_te, AMC_CLASSES)
# Scenario: network operator checks three candidate routes
rng_probe = np.random.default_rng(77)
scenarios = [
("Short metro link (QAM-64?)",
_amc_sample(rng_probe, 5)), # QAM-64 conditions
("Regional backbone (QAM-16?)",
_amc_sample(rng_probe, 4)), # QAM-16 conditions
("Long-haul transoce. (PAM-4?)",
_amc_sample(rng_probe, 1)), # PAM-4 conditions
]
print(f"\n ── Route optimisation: 3 candidate links ──")
for name, x_raw in scenarios:
out = fiber_nn.forward(x_raw)
pred = int(np.argmax(out))
bps = [1, 2, 3, 2, 4, 6][pred] # bits per symbol
print(f" {name:<28} → {AMC_CLASSES[pred]:<7}"
f" ({bps} b/sym) p={out[pred]:.3f}")
return fiber_nn, acc
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# USE CASE 3 — OTDR FAULT DIAGNOSIS ENGINE (FDE)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FDE_CLASSES = ['Normal', 'ConnectorLoss', 'SpliceLoss', 'FiberBreak', 'MacroBend']
FDE_FEATURES = ['BackscatterSlope(dB/km)', 'EventPower(dB)', 'EventDist(km)',
'PulseWidth(ns)', 'DeadZone(m)', 'SNR(dB)',
'Reflectance(dB)', 'LossRate(dB/km)']
def _fde_sample(rng, label, noise_std=0.0):
"""Physically motivated OTDR trace feature vector per fault type.
noise_std adds a small global Gaussian floor across all features,
forcing the model to learn robust decision boundaries rather than
memorising individual sample values.
"""
n = lambda s: rng.normal(0, s)
if label == 0: # Normal — clean trace, low event power, no reflectance peak
v = np.array([0.20+n(0.01), 0.0+n(0.08), 50+n(5), 10+n(1),
1.0+n(0.1), 30+n(2), -60+n(2), 0.20+n(0.01)])
elif label == 1: # Connector loss — distinct event + partial Fresnel
v = np.array([0.20+n(0.01), 1.5+n(0.25), 25+n(3), 10+n(1),
1.0+n(0.1), 28+n(2), -35+n(2.5), 0.20+n(0.01)])
elif label == 2: # Splice loss — low power, no air gap → very low reflectance
v = np.array([0.20+n(0.01), 0.6+n(0.08), 30+n(4), 10+n(1),
0.4+n(0.04), 29+n(2), -70+n(2.5), 0.20+n(0.01)])
# key separators vs Normal: EventPower↑, DeadZone↓, Reflectance↓↓
elif label == 3: # Fiber break — full Fresnel reflection, loss of backscatter
v = np.array([0.20+n(0.01), 10.0+n(0.4), 40+n(2), 10+n(1),
1.0+n(0.1), 20+n(2), -14+n(1.5), 0.20+n(0.01)])
else: # Macro-bend — elevated slope + loss rate
v = np.array([0.40+n(0.025), 3.0+n(0.35), 15+n(3), 10+n(1),
1.0+n(0.1), 25+n(2), -55+n(2.5), 0.80+n(0.04)])
if noise_std > 0.0:
v += rng.normal(0.0, noise_std, v.shape)
return v
def generate_fde_dataset(n=300, seed=42, noise_std=0.02):
rng = np.random.default_rng(seed)
n_cls = len(FDE_CLASSES)
X, Y = [], []
for label in range(n_cls):
for _ in range(n // n_cls):
X.append(_fde_sample(rng, label, noise_std=noise_std))
y = np.zeros(n_cls); y[label] = 1.0
Y.append(y)
X, Y = np.array(X), np.array(Y)
idx = rng.permutation(len(X))
return X[idx], Y[idx]
def run_uc3(mp, verbose=True):
print("\n" + "━"*62)
print(" USE CASE 3 — OTDR FAULT DIAGNOSIS ENGINE (FDE)")
print(" Sub-second fault identification from OTDR trace features")
print("━"*62)
print(f" Classes : {' | '.join(FDE_CLASSES)}")
print(f" Features : {', '.join(FDE_FEATURES)}")
print(f" Dataset : 300 samples · 80/20 split")
print(f" Network : [8, 20, 10, 5] coherent fiber NN")
X, Y = generate_fde_dataset(n=300, noise_std=0.02)
split = int(0.8 * len(X))
X_tr, Y_tr = X[:split], Y[:split]
X_te, Y_te = X[split:], Y[split:]
print(f"\n [Training theoretic model → coherent fiber NN]")
fiber_nn, acc, th_acc, trainer = _train_and_transfer(
[8, 20, 10, 5], X_tr, Y_tr, X_te, Y_te,
epochs=800, lr=1e-3, mp=mp, verbose=verbose)
print(f"\n Theory accuracy : {th_acc*100:.1f}%")
print(f" Fiber accuracy : {acc*100:.1f}%")
print(f" WDM λ-channels : {fiber_nn.total_lambda_channels()}")
_print_conf_matrix(fiber_nn, X_te, Y_te, FDE_CLASSES)
# Live fault event sequence (simulated NOC alert stream)
events = [
("Alert #1 14:02:31", _fde_sample(np.random.default_rng(10), 3)), # break
("Alert #2 14:02:45", _fde_sample(np.random.default_rng(11), 1)), # connector
("Alert #3 14:03:02", _fde_sample(np.random.default_rng(12), 0)), # normal
("Alert #4 14:03:19", _fde_sample(np.random.default_rng(13), 4)), # bend
]
print(f"\n ── NOC alert stream — optical diagnosis in real time ──")
for label, x_raw in events:
out = fiber_nn.forward(x_raw)
pred = int(np.argmax(out))
sev = ['✓ OK', '⚠ WARN', '⚠ WARN', '✗ CRIT', '⚠ WARN'][pred]
print(f" {label} → {FDE_CLASSES[pred]:<15} {sev} "
f"confidence={out[pred]*100:.1f}%")
return fiber_nn, acc
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# USE CASE 4 — DATACENTER INTERCONNECT LINK STATE CLASSIFIER (DCI)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
DCI_CLASSES = ['Optimal', 'Degraded', 'Marginal', 'Critical', 'Failed']
DCI_FEATURES = ['TXPower(dBm)', 'RXPower(dBm)', 'PreFEC_BER(log)',
'PostFEC_BER(log)', 'CDPenalty(dB)', 'PMDPenalty(dB)',
'Temperature(C)', 'WavDrift(pm)']
def _dci_sample(rng, label, noise_std=0.02):
"""
Generate a DCI transceiver measurement vector per link-state class.
Models coherent 400ZR/ZR+ pluggable optics on metro/DCI spans.
Optimal → clean, well-powered, low penalties, stable wavelength
Degraded → slight RX power drop, minor BER increase, mild CD/PMD
Marginal → marginal power budget, elevated BER, thermal stress
Critical → near-threshold BER, high penalties, wavelength drift
Failed → below RX sensitivity, FEC overload, out-of-lock
"""
n = lambda mu, s: float(rng.normal(mu, s))
if label == 0: # Optimal
v = np.array([n(2.0,0.2), n(-15.0,0.3), n(-5.5,0.2), n(-12.0,0.3),
n(0.5,0.1), n(0.1,0.03), n(44.0,1.0), n(2.0,0.3)])
elif label == 1: # Degraded
v = np.array([n(1.0,0.2), n(-18.5,0.4), n(-4.5,0.2), n(-8.5,0.4),
n(1.2,0.15), n(0.4,0.08), n(47.0,1.0), n(4.5,0.5)])
elif label == 2: # Marginal
v = np.array([n(0.0,0.3), n(-21.5,0.5), n(-3.5,0.2), n(-4.0,0.5),
n(2.5,0.2), n(0.9,0.1), n(51.5,1.5), n(9.0,1.0)])
elif label == 3: # Critical
v = np.array([n(-1.5,0.3), n(-25.5,0.6), n(-2.5,0.2), n(-1.0,0.4),
n(4.5,0.3), n(1.8,0.15), n(57.0,2.0), n(20.0,2.0)])
else: # Failed
v = np.array([n(-6.0,0.5), n(-35.0,1.0), n(-1.0,0.1), n(0.0,0.1),
n(9.0,0.5), n(5.0,0.3), n(64.0,2.0), n(55.0,5.0)])
if noise_std > 0.0:
v += rng.normal(0.0, noise_std, v.shape)
return v
def generate_dci_dataset(n=300, seed=42):
rng = np.random.default_rng(seed)
n_cls = len(DCI_CLASSES)
X, Y = [], []
for label in range(n_cls):
for _ in range(n // n_cls):
X.append(_dci_sample(rng, label))
y = np.zeros(n_cls); y[label] = 1.0
Y.append(y)
X, Y = np.array(X), np.array(Y)
idx = rng.permutation(len(X))
return X[idx], Y[idx]
def run_uc4(mp, verbose=True):
print("\n" + "━"*62)
print(" USE CASE 4 — DATACENTER INTERCONNECT LINK STATE (DCI)")
print(" Classify 400ZR/ZR+ transceiver health from live PM counters")
print("━"*62)
print(f" Classes : {' | '.join(DCI_CLASSES)}")
print(f" Features : {', '.join(DCI_FEATURES)}")
print(f" Dataset : 300 samples · 80/20 split")
print(f" Network : [8, 20, 10, 5] coherent fiber NN")
X, Y = generate_dci_dataset(n=300)
split = int(0.8 * len(X))
X_tr, Y_tr = X[:split], Y[:split]
X_te, Y_te = X[split:], Y[split:]
print(f"\n [Training theoretic model → coherent fiber NN]")
fiber_nn, acc, th_acc, trainer = _train_and_transfer(
[8, 20, 10, 5], X_tr, Y_tr, X_te, Y_te,
epochs=700, lr=1e-3, mp=mp, verbose=verbose)
print(f"\n Theory accuracy : {th_acc*100:.1f}%")
print(f" Fiber accuracy : {acc*100:.1f}%")
print(f" WDM λ-channels : {fiber_nn.total_lambda_channels()}")
_print_conf_matrix(fiber_nn, X_te, Y_te, DCI_CLASSES)
# Cloud operator scenario: real-time fleet health sweep
rng_probe = np.random.default_rng(201)
fleet = [
("AMS-LON spine #1", _dci_sample(rng_probe, 0)), # Optimal
("AMS-LON spine #2", _dci_sample(rng_probe, 1)), # Degraded
("FRA-PAR metro #1", _dci_sample(rng_probe, 2)), # Marginal
("LHR-DUB access #1", _dci_sample(rng_probe, 3)), # Critical
("NYC-BOS backup #1", _dci_sample(rng_probe, 4)), # Failed
]
actions = {
'Optimal': '✓ No action',
'Degraded': '⚠ Schedule maintenance',
'Marginal': '⚠ Re-route traffic',
'Critical': '✗ Immediate failover',
'Failed': '✗ Dispatch engineer',
}
print(f"\n ── Cloud operator fleet sweep — optical PM analysis ──")
for link, x_raw in fleet:
out = fiber_nn.forward(x_raw)
pred = int(np.argmax(out))
cls = DCI_CLASSES[pred]
print(f" {link:<22} → {cls:<8} {actions[cls]} "
f"(p={out[pred]:.3f})")
return fiber_nn, acc
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# MAIN
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def main():
print("\n" + "█"*62)
print("█ █")
print("█ COHERENT FIBER NN — USE CASE DEMONSTRATION █")
print("█ Universal optical substrate · 4 production tasks █")
print("█ █")
print("█"*62)
print("""
Same physical hardware — different trained weights:
Laser 1550 nm → IQ mod (φ=0/π) → SMF+EDFA+DCF
→ 90°-hybrid → balanced PD → I = Σwᵢxᵢ
""")
# Shared MetaMetaPrompt across all use cases
mp = MetaMetaPrompt(seed_dim=64, max_depth=16, rng_seed=42)
results = {}
# ── UC1 ───────────────────────────────────────────────────────────────
nn1, acc1 = run_uc1(mp, verbose=True)
results['MIC'] = acc1
# ── UC2 ───────────────────────────────────────────────────────────────
nn2, acc2 = run_uc2(mp, verbose=True)
results['AMC'] = acc2
# ── UC3 ───────────────────────────────────────────────────────────────
nn3, acc3 = run_uc3(mp, verbose=True)
results['FDE'] = acc3
# ── UC4 ───────────────────────────────────────────────────────────────
nn4, acc4 = run_uc4(mp, verbose=True)
results['DCI'] = acc4
# ── Summary ───────────────────────────────────────────────────────────
print(f"\n{'█'*62}")
print(f" COHERENT FIBER NN — USE CASE SUMMARY")
print(f"{'━'*62}")
print(f" {'Use Case':<38} {'Fiber Acc':>10} {'λ-ch':>5}")
print(f" {'─'*56}")
specs = [
("UC1 Multi-Impairment Classifier", nn1, acc1),
("UC2 Adaptive Modulation Controller", nn2, acc2),
("UC3 OTDR Fault Diagnosis Engine", nn3, acc3),
("UC4 DCI Link State Classifier", nn4, acc4),
]
for name, nn, acc in specs:
print(f" {name:<38} {acc*100:>9.1f}% {nn.total_lambda_channels():>5}")
print(f"{'━'*62}")
mean_acc = np.mean(list(results.values()))
print(f" Mean fiber accuracy : {mean_acc*100:.1f}%")
print(f" Shared substrate : Coherent IQ · 1550 nm · DWDM")
print(f" Prompt : MetaMetaPrompt (3-level hierarchy)")
print(f" Layers generated : {len(mp.history)}")
print(f"\n One photon. Four minds. All at light speed.")
print(f"{'█'*62}\n")
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# T1 — REAL DATA BRIDGE: CSV / JSON ingestion + domain-shift detection
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
def load_csv_dataset(path: str,
feature_cols: list[str] | None = None,
label_col: str | None = None,
class_map: dict | None = None,
max_rows: int | None = None) -> tuple[np.ndarray, np.ndarray, list[str]]:
"""
T1: Load any OSNR/BER/OTDR CSV and return (X, Y, class_names) in <10s.
Args:
path : path to CSV file
feature_cols : list of column names to use as features.
If None, all numeric columns except label_col are used.
label_col : column name for class labels. If None, last column is used.
class_map : dict mapping raw label strings to integer class indices.
If None, labels are auto-enumerated alphabetically.
max_rows : if set, only load this many rows (for streaming preview)
Returns:
X : (N, n_features) float array
Y : (N, n_classes) one-hot float array
class_names : list of class name strings
Usage:
X, Y, classes = load_csv_dataset('network_telemetry.csv',
feature_cols=['OSNR','BER','EVM'],
label_col='fault_type')
"""
rows = []
with open(path, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
headers = reader.fieldnames or []
for k, row in enumerate(reader):
if max_rows is not None and k >= max_rows:
break
rows.append(row)
if not rows:
raise ValueError(f"CSV file is empty or has no data rows: {path}")
# Determine label column
if label_col is None:
label_col = headers[-1]
# Determine feature columns
if feature_cols is None:
feature_cols = [h for h in headers
if h != label_col and _is_numeric_col(rows, h)]
# Build class map
raw_labels = [r[label_col] for r in rows]
if class_map is None:
unique_labels = sorted(set(raw_labels))
class_map = {lbl: i for i, lbl in enumerate(unique_labels)}
class_names = [k for k, v in sorted(class_map.items(), key=lambda x: x[1])]
n_classes = len(class_names)
X_list, Y_list = [], []
for row in rows:
try:
x_row = np.array([float(row[c]) for c in feature_cols], dtype=float)
except (ValueError, KeyError):
continue
label_int = class_map.get(row[label_col], 0)
y_row = np.zeros(n_classes)
y_row[label_int] = 1.0
X_list.append(x_row)
Y_list.append(y_row)
return np.array(X_list), np.array(Y_list), class_names
def _is_numeric_col(rows: list[dict], col: str) -> bool:
"""Check if a CSV column is numeric (float-parseable)."""
for row in rows[:20]:
try:
float(row.get(col, ''))
except (ValueError, TypeError):
return False
return True
def load_json_stream(path: str,
feature_keys: list[str],
label_key: str,
class_map: dict | None = None,
max_records: int | None = None) -> tuple[np.ndarray, np.ndarray, list[str]]:
"""
T1: Load a newline-delimited JSON stream (NDJSON/gRPC-style telemetry).
Each line must be a JSON object with numeric feature fields and a label field.
Tolerates extra fields. Empty/malformed lines are skipped.
Args:
path : path to .json or .ndjson file
feature_keys : list of keys to extract as features
label_key : key for class label (string or integer)
class_map : optional {label_string: class_index} mapping
max_records : max lines to read
Returns:
X, Y, class_names
Usage:
X, Y, cls = load_json_stream('telemetry.ndjson',
feature_keys=['osnr','ber','evm','dgd'],
label_key='impairment')
"""
records = []
with open(path, encoding='utf-8') as f:
for k, line in enumerate(f):
if max_records is not None and k >= max_records:
break
line = line.strip()
if not line:
continue
try:
records.append(json.loads(line))
except json.JSONDecodeError:
continue
raw_labels = [str(r.get(label_key, 'unknown')) for r in records]
if class_map is None:
unique_labels = sorted(set(raw_labels))
class_map = {lbl: i for i, lbl in enumerate(unique_labels)}
class_names = [k for k, v in sorted(class_map.items(), key=lambda x: x[1])]
n_classes = len(class_names)
X_list, Y_list = [], []
for r, raw_lbl in zip(records, raw_labels):
try:
x_row = np.array([float(r[k]) for k in feature_keys], dtype=float)
except (KeyError, ValueError, TypeError):
continue
label_int = class_map.get(raw_lbl, 0)
y_row = np.zeros(n_classes)
y_row[label_int] = 1.0
X_list.append(x_row)
Y_list.append(y_row)
return np.array(X_list), np.array(Y_list), class_names
def detect_domain_shift(X_ref: np.ndarray, X_new: np.ndarray,
threshold: float = 2.0) -> dict:
"""
T1: Lightweight domain-shift detector.
Compares per-feature mean and std of a reference dataset vs new batch.
Uses z-score: |μ_new - μ_ref| / σ_ref.
Returns dict with:
shifted : bool — True if any feature exceeds threshold
z_scores : per-feature z-score of mean shift
feature_alerts : list of feature indices where z > threshold
max_z : maximum z-score observed
drift_summary : human-readable string
"""
mu_ref = X_ref.mean(axis=0)
std_ref = X_ref.std(axis=0) + 1e-8
mu_new = X_new.mean(axis=0)
z = np.abs(mu_new - mu_ref) / std_ref
alerts = [int(i) for i in np.where(z > threshold)[0]]
return {
'shifted': bool(len(alerts) > 0),
'z_scores': z.tolist(),
'feature_alerts': alerts,
'max_z': float(z.max()),
'drift_summary': (f"Domain shift detected on {len(alerts)} features "
f"(max z={z.max():.2f})" if alerts
else f"No shift detected (max z={z.max():.2f})"),
}
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# T2 — SCALE BREAKOUT: MIC-64 (64-feature ITU-T G.826/G.829 measurement)
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
MIC64_FEATURES = [
# Block A — Signal quality (8)
'EVM(%)', 'Q-factor(dB)', 'Eye-open', 'BER(log)',
'Spec-skew', 'RMS-jitter(ps)', 'CD-est(ps/nm)', 'DGD(ps)',
# Block B — OSNR hierarchy (8)
'OSNR(dB)', 'OSNR-NB(dB)', 'SNR-elec(dB)', 'ASE-power(dBm)',
'NF-path(dB)', 'NF-avg(dB)', 'Pol-dep-loss(dB)', 'OCSR(dB)',
# Block C — Nonlinear diagnostics (8)
'SPM-coef', 'XPM-coef', 'FWM-eff', 'SRS-tilt(dB/THz)',
'Xpol-mod-idx', 'NLI-coef', 'GN-noise(dBm)', 'NL-phase(rad)',
# Block D — Chromatic & PMD (8)
'CD-residual(ps/nm)', 'CD-slope(ps/nm²)', 'SOPMD(ps²)',
'PDL(dB)', 'DGD-avg(ps)', 'DGD-max(ps)', 'PSP-angle(deg)', 'Pol-rotation(deg)',
# Block E — Power & gain (8)
'TX-power(dBm)', 'RX-power(dBm)', 'Path-loss(dB)', 'Span-loss(dB)',
'EDFA-gain(dB)', 'EDFA-NF(dB)', 'Launch-pow(dBm)', 'OSC-pow(dBm)',
# Block F — Spectral (8)
'Wavelength(nm)', 'Freq-offset(GHz)', 'BW-3dB(GHz)', 'BW-10dB(GHz)',
'Side-lobe-rej(dB)', 'Spec-flatness(dB)', 'Comb-spacing(GHz)', 'Guard-band(GHz)',
# Block G — OTDR / physical (8)
'Backscatter-slope(dB/km)', 'Event-power(dB)', 'Event-dist(km)',
'Pulse-width(ns)', 'Dead-zone(m)', 'Reflectance(dB)', 'Loss-rate(dB/km)', 'ORL(dB)',
# Block H — G.826/G.829 performance (8)
'ES-ratio', 'SES-ratio', 'BBE-ratio', 'UNAVAIL-ratio',
'G826-margin(dB)', 'FEC-overhead(%)', 'Corrected-errors(log)', 'Uncorr-errors(log)',
]
def _mic64_sample(rng, label: int) -> np.ndarray:
"""
Generate a 64-feature ITU-T G.826/G.829 measurement vector.
Extends _mic_sample() with realistic physical cross-correlations.
"""
n = lambda mu, s: float(rng.normal(mu, s))
# Base 8 features (same as MIC-8 for continuity)
base = _mic_sample(rng, label)
if label == 0: # Normal
blk_b = [n(28,1), n(26,1), n(20,1), n(-30,1), n(5,0.3), n(5.5,0.3), n(0.3,0.05), n(40,1)]
blk_c = [n(0.1,0.02),n(0.05,0.01),n(0.02,0.005),n(0.1,0.02), n(0.01,0.002),n(0.05,0.01),n(-40,1), n(0.05,0.01)]
blk_d = [n(10,2), n(0.05,0.01),n(0.1,0.02), n(0.3,0.05), n(1.0,0.2), n(2.5,0.5), n(45,5), n(10,2)]
blk_e = [n(2,0.2), n(-15,0.3), n(17,0.5), n(0.2,0.05), n(20,0.5), n(5,0.3), n(1,0.2), n(-35,1)]
blk_f = [n(1550,0.01),n(0.1,0.05),n(37,0.5),n(60,1), n(30,1), n(0.5,0.1), n(50,0.1), n(12,0.2)]
blk_g = [n(0.20,0.01),n(0,0.05), n(50,5), n(10,1), n(1.0,0.1), n(-60,2), n(0.20,0.01),n(40,1)]
blk_h = [n(0.001,0.0002),n(0.0001,0.00002),n(0.00001,0.000002),n(0,0),
n(5,0.5), n(7,0.2), n(-5,0.3), n(-15,0.5)]
elif label == 1: # CD-dominant
blk_b = [n(20,1.5), n(18,1.5), n(12,1.5), n(-25,1.5), n(7,0.5), n(7,0.5), n(0.5,0.1), n(38,1)]
blk_c = [n(0.15,0.03),n(0.08,0.02),n(0.03,0.01),n(0.2,0.05), n(0.02,0.005),n(0.1,0.02),n(-38,1), n(0.1,0.02)]
blk_d = [n(800,50), n(0.5,0.1),n(0.5,0.1), n(0.5,0.1), n(1.5,0.3), n(4,1), n(45,10), n(15,3)]
blk_e = [n(1.5,0.3), n(-18,0.5),n(19,0.5), n(0.5,0.1), n(20,0.5), n(5.5,0.3), n(1,0.2), n(-35,1)]
blk_f = [n(1550,0.02),n(0.5,0.1),n(35,1), n(62,2), n(27,2), n(1.0,0.3), n(50,0.2), n(12,0.3)]
blk_g = [n(0.22,0.01),n(1.5,0.25),n(25,3), n(10,1), n(1.0,0.1), n(-35,2.5), n(0.20,0.01),n(38,1)]
blk_h = [n(0.005,0.001),n(0.001,0.0002),n(0.0001,0.00002),n(0,0),
n(3,0.5), n(7,0.2), n(-3,0.3), n(-10,0.5)]
elif label == 2: # PMD-dominant
blk_b = [n(21,1.5), n(19,1.5), n(13,1.5), n(-26,1.5), n(6.5,0.5), n(6.5,0.5), n(0.8,0.1), n(37,1)]
blk_c = [n(0.12,0.03),n(0.07,0.02),n(0.025,0.008),n(0.15,0.04),n(0.015,0.004),n(0.08,0.02),n(-38,1),n(0.08,0.02)]
blk_d = [n(15,5), n(0.07,0.02),n(8,2), n(1.5,0.3), n(25,5), n(40,10), n(60,15), n(25,5)]
blk_e = [n(1.5,0.3), n(-17.5,0.5),n(19,0.5), n(0.5,0.1), n(20,0.5), n(5.5,0.3), n(1,0.2), n(-35,1)]
blk_f = [n(1550,0.01),n(0.2,0.05),n(36,0.8), n(61,1.5), n(28,1.5), n(0.8,0.2), n(50,0.15), n(12,0.25)]
blk_g = [n(0.21,0.01),n(0.8,0.15),n(30,4), n(10,1), n(0.4,0.04), n(-70,2.5), n(0.20,0.01),n(39,1)]
blk_h = [n(0.004,0.001),n(0.0008,0.0002),n(0.00008,0.00002),n(0,0),
n(3.5,0.5), n(7,0.2), n(-3.5,0.3), n(-11,0.5)]
elif label == 3: # OSNR-limited
blk_b = [n(16,2), n(14,2), n(8,2), n(-22,2), n(8,0.6), n(8.5,0.6), n(1.2,0.2), n(35,1.5)]
blk_c = [n(0.12,0.03),n(0.06,0.015),n(0.025,0.008),n(0.15,0.04),n(0.015,0.004),n(0.08,0.02),n(-37,1),n(0.08,0.02)]
blk_d = [n(12,3), n(0.06,0.015),n(0.2,0.05), n(0.4,0.08), n(2.0,0.4), n(5,1), n(50,10), n(12,3)]
blk_e = [n(0.5,0.3), n(-22,0.6), n(22.5,0.6), n(1.5,0.3), n(20,0.5), n(6.5,0.4), n(0.5,0.2), n(-35,1)]
blk_f = [n(1550,0.01),n(0.3,0.08),n(35,1), n(62,2), n(26,2), n(1.2,0.3), n(50,0.2), n(12,0.3)]
blk_g = [n(0.21,0.01),n(0.2,0.05),n(40,5), n(10,1), n(1.0,0.1), n(-58,2.5), n(0.20,0.01),n(39,1)]
blk_h = [n(0.008,0.001),n(0.002,0.0005),n(0.0002,0.00005),n(0,0),
n(2.5,0.5), n(7,0.2), n(-2.5,0.3), n(-8,0.5)]
else: # Nonlinear
blk_b = [n(19,1.5), n(17,1.5), n(11,1.5), n(-24,1.5), n(7.5,0.5), n(7,0.5), n(0.9,0.15), n(36,1)]
blk_c = [n(0.5,0.05),n(0.3,0.04),n(0.15,0.02),n(0.8,0.1), n(0.1,0.02),n(0.4,0.05),n(-35,1.5),n(0.5,0.05)]
blk_d = [n(20,5), n(0.1,0.02),n(0.3,0.06), n(0.6,0.1), n(1.8,0.4), n(4.5,1), n(50,10), n(15,3)]
blk_e = [n(3,0.3), n(-14,0.4), n(17,0.5), n(0.3,0.06), n(20,0.5), n(5,0.3), n(2,0.2), n(-35,1)]
blk_f = [n(1550,0.02),n(0.4,0.1),n(36,1), n(62,2), n(27,2), n(1.5,0.4), n(50,0.2), n(12,0.3)]
blk_g = [n(0.22,0.01),n(0.8,0.15),n(35,4), n(10,1), n(1.0,0.1), n(-55,2.5), n(0.20,0.01),n(38,1)]
blk_h = [n(0.006,0.001),n(0.0015,0.0003),n(0.00015,0.00003),n(0,0),
n(2.8,0.5), n(7,0.2), n(-2.8,0.3), n(-9,0.5)]
return np.concatenate([base, blk_b, blk_c, blk_d, blk_e, blk_f, blk_g, blk_h])
def generate_mic64_dataset(n: int = 500, seed: int = 42) -> tuple[np.ndarray, np.ndarray]:
"""Generate a 64-feature MIC dataset (N samples, 5 classes)."""
rng = np.random.default_rng(seed)
n_cls = len(MIC_CLASSES)
X, Y = [], []
for label in range(n_cls):
for _ in range(n // n_cls):
X.append(_mic64_sample(rng, label))
y = np.zeros(n_cls); y[label] = 1.0
Y.append(y)
X, Y = np.array(X), np.array(Y)
idx = rng.permutation(len(X))
return X[idx], Y[idx]
def run_uc5_mic64(mp, verbose: bool = True):
"""
T2: Run UC5 — MIC with 64 ITU-T G.826/G.829 features.
Network: [64, 128, 64, 32, 5] coherent fiber NN.
"""
print("\n" + "━"*62)
print(" USE CASE 5 — MIC-64 (ITU-T G.826/G.829 Full Feature Set)")
print(" 64-feature broadband impairment classifier")
print("━"*62)
print(f" Classes : {' | '.join(MIC_CLASSES)}")
print(f" Features : 64 (8 blocks × 8 ITU-T metrics)")
print(f" Dataset : 500 samples · 80/20 split")
print(f" Network : [64, 128, 64, 32, 5] coherent fiber NN")
X, Y = generate_mic64_dataset(n=500)
split = int(0.8 * len(X))
X_tr, Y_tr = X[:split], Y[:split]
X_te, Y_te = X[split:], Y[split:]
print(f"\n [Training theoretic model → coherent fiber NN]")
fiber_nn, acc, th_acc, trainer = _train_and_transfer(
[64, 128, 64, 32, 5], X_tr, Y_tr, X_te, Y_te,
epochs=800, lr=1e-3, mp=mp, verbose=verbose)
print(f"\n Theory accuracy : {th_acc*100:.1f}%")
print(f" Fiber accuracy : {acc*100:.1f}%")
print(f" WDM λ-channels : {fiber_nn.total_lambda_channels()}")
_print_conf_matrix(fiber_nn, X_te, Y_te, MIC_CLASSES)
# Domain-shift probe: slight mean shift on OSNR features (block B)
rng_probe = np.random.default_rng(77)
x_probe = _mic64_sample(rng_probe, 2) # PMD event
print(f"\n ── Live MIC-64 probe (PMD event) ──")
_optical_probe(fiber_nn, x_probe, MIC_CLASSES)
# Domain shift detection
X_shifted = X_te + rng_probe.normal(0, 3.0, X_te.shape)
shift = detect_domain_shift(X_tr, X_shifted)
print(f"\n Domain-shift detector: {shift['drift_summary']}")
print(f" Alerted features : {shift['feature_alerts'][:8]} (showing first 8)")
return fiber_nn, acc
if __name__ == "__main__":
main()