Skip to content

plot_proc

PROCESS plot_proc using process_io_lib functions and MFILE.DAT

24/11/2021: Global dictionary variables moved within the functions to avoid cyclic dependencies. This is because the dicts generation script imports, and inspects, process.

SOLENOID_COLOUR = ['pink', '#1764ab'] module-attribute

CSCOMPRESSION_COLOUR = ['maroon', '#33CCCC'] module-attribute

TFC_COLOUR = ['cyan', '#084a91'] module-attribute

THERMAL_SHIELD_COLOUR = ['gray', '#e3eef9'] module-attribute

VESSEL_COLOUR = ['green', '#b7d4ea'] module-attribute

SHIELD_COLOUR = ['green', '#94c4df'] module-attribute

BLANKET_COLOUR = ['magenta', '#4a98c9'] module-attribute

PLASMA_COLOUR = ['khaki', '#cc8acc'] module-attribute

CRYOSTAT_COLOUR = ['red', '#2e7ebc'] module-attribute

FIRSTWALL_COLOUR = ['darkblue', 'darkblue'] module-attribute

NBSHIELD_COLOUR = ['black', 'black'] module-attribute

thin = 0.0 module-attribute

RADIAL_BUILD = ['dr_bore', 'dr_cs', 'dr_cs_precomp', 'dr_cs_tf_gap', 'dr_tf_inboard', 'dr_tf_shld_gap', 'dr_shld_thermal_inboard', 'dr_shld_vv_gap_inboard', 'dr_vv_inboard', 'dr_shld_inboard', 'vvblgapi', 'dr_blkt_inboard', 'dr_fw_inboard', 'dr_fw_plasma_gap_inboard', 'rminori', 'rminoro', 'dr_fw_plasma_gap_outboard', 'dr_fw_outboard', 'dr_blkt_outboard', 'vvblgapo', 'dr_shld_outboard', 'dr_vv_outboard', 'dr_shld_vv_gap_outboard', 'dr_shld_thermal_outboard', 'dr_tf_shld_gap', 'dr_tf_outboard'] module-attribute

vertical_lower = ['z_plasma_xpoint_lower', 'dz_xpoint_divertor', 'dz_divertor', 'dz_shld_lower', 'dz_vv_lower', 'dz_shld_vv_gap', 'dz_shld_thermal', 'dr_tf_shld_gap', 'dr_tf_inboard'] module-attribute

ANIMATION_INFO = [('rmajor', 'Major radius', 'm'), ('rminor', 'Minor radius', 'm'), ('aspect', 'Aspect ratio', '')] module-attribute

rtangle = np.pi / 2 module-attribute

rtangle2 = 2 * rtangle module-attribute

RadialBuild dataclass

Source code in process/core/io/plot_proc.py
70
71
72
73
74
75
76
77
78
@dataclass
class RadialBuild:
    upper: dict[str, float]
    lower: dict[str, float]
    radial: dict[str, float]

    cumulative_upper: dict[str, float]
    cumulative_lower: dict[str, float]
    cumulative_radial: dict[str, float]

upper instance-attribute

lower instance-attribute

radial instance-attribute

cumulative_upper instance-attribute

cumulative_lower instance-attribute

cumulative_radial instance-attribute

parse_args(args)

Parse supplied arguments.

Parameters:

Name Type Description Default
args (list, None)

arguments to parse

required

Returns:

Type Description
Namespace

parsed arguments

Source code in process/core/io/plot_proc.py
 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
def parse_args(args):
    """Parse supplied arguments.

    Parameters
    ----------
    args : list, None
        arguments to parse

    Returns
    -------
    Namespace
        parsed arguments
    """
    # Setup command line arguments
    parser = argparse.ArgumentParser(
        description="Produces a summary of the PROCESS MFILE output, using the MFILE.  "
        "For info please see https://github.com/ukaea/PROCESS?tab=readme-ov-file#contacts ",
        formatter_class=RawTextHelpFormatter,
    )

    parser.add_argument(
        "-f",
        metavar="FILENAME",
        type=str,
        default="",
        help="specify input/output file path",
    )
    parser.add_argument("-s", "--show", help="show plot", action="store_true")

    parser.add_argument("-n", type=int, help="Which scan to plot?")

    parser.add_argument(
        "-d",
        "--DEMO-ranges",
        help="Uses the DEMO dimensions as ranges for all graphics",
        action="store_true",
    )

    parser.add_argument(
        "-c",
        "--colour",
        type=int,
        help=(
            "Which colour scheme to use for cross-section plots\n"
            "1: Original PROCESS (default)\n"
            "2: BLUEMIRA"
        ),
        default=1,
        choices=[1, 2],
    )
    parser.add_argument(
        "-o",
        "--output-format",
        type=str,
        help=(
            "Output file format\npdf: pdf output (default)\npng: png output\nnone: no output file written"
        ),
        default="pdf",
        choices=["pdf", "png", "none"],
    )

    return parser.parse_args(args)

plot_plasma(axis, mfile, scan, colour_scheme)

Plots the plasma boundary arcs.

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required
colour_scheme Literal[1, 2]

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
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
def plot_plasma(
    axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]
):
    """Plots the plasma boundary arcs.

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    colour_scheme :
        colour scheme to use for plots
    """

    (r_0, a, triang, kappa, i_single_null, i_plasma_shape, plasma_square) = (
        mfile.get_variables(
            "rmajor",
            "rminor",
            "triang",
            "kappa",
            "i_single_null",
            "i_plasma_shape",
            "plasma_square",
            scan=scan,
        )
    )

    pg = plasma_geometry(
        rmajor=r_0,
        rminor=a,
        triang=triang,
        kappa=kappa,
        i_single_null=i_single_null,
        i_plasma_shape=i_plasma_shape,
        square=plasma_square,
    )
    if i_plasma_shape == 0:
        # Plot the 2 plasma outline arcs.
        axis.plot(pg.rs[0], pg.zs[0], color="black")
        axis.plot(pg.rs[1], pg.zs[1], color="black")

        # Set triang_95 to stop plotting plasma past boundary
        # Assume IPDG scaling
        triang_95 = triang / 1.5

        # Colour in right side of plasma
        axis.fill_between(
            x=pg.rs[0],
            y1=pg.zs[0],
            where=(pg.rs[0] > r_0 - (triang_95 * a * 1.5)),
            color=PLASMA_COLOUR[colour_scheme - 1],
        )
        # Colour in left side of plasma
        axis.fill_between(
            x=pg.rs[1],
            y1=pg.zs[1],
            where=(pg.rs[1] < r_0 - (triang_95 * a * 1.5)),
            color=PLASMA_COLOUR[colour_scheme - 1],
        )

    elif i_plasma_shape == 1:
        axis.plot(pg.rs, pg.zs, color="black")
        axis.fill(pg.rs, pg.zs, color=PLASMA_COLOUR[colour_scheme - 1])

plot_centre_cross(axis, mfile, scan)

Function to plot centre cross on plot

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def plot_centre_cross(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot centre cross on plot

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    """
    rmajor = mfile.get("rmajor", scan=scan)
    axis.plot(
        [rmajor - 0.25, rmajor + 0.25, rmajor, rmajor, rmajor],
        [0, 0, 0, 0.25, -0.25],
        color="black",
    )

cumulative_radial_build(section, mfile, scan)

Function for calculating the cumulative radial build up to and including the given section.

Parameters:

Name Type Description Default
section

section of the radial build to go up to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required

Returns:

Type Description

cumulative_build:cumulative radial build up to section given

Source code in process/core/io/plot_proc.py
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
def cumulative_radial_build(section, mfile: mf.MFile, scan: int):
    """Function for calculating the cumulative radial build up to and
    including the given section.

    Parameters
    ----------
    section :
        section of the radial build to go up to
    mfile :
        MFILE data object
    scan :
        scan number to use

    Returns
    -------
    :
        cumulative_build:cumulative radial build up to section given
    """
    complete = False
    cumulative_build = 0
    for item in RADIAL_BUILD:
        if item == "rminori" or item == "rminoro":
            cumulative_build += mfile.get("rminor", scan=scan)
        elif item == "vvblgapi" or item == "vvblgapo":
            cumulative_build += mfile.get("dr_shld_blkt_gap", scan=scan)
        elif "dr_vv_inboard" in item:
            cumulative_build += mfile.get("dr_vv_inboard", scan=scan)
        elif "dr_vv_outboard" in item:
            cumulative_build += mfile.get("dr_vv_outboard", scan=scan)
        else:
            cumulative_build += mfile.get(item, scan=scan)
        if item == section:
            complete = True
            break

    if complete is False:
        print("radial build parameter ", section, " not found")
    return cumulative_build

cumulative_radial_build2(section, mfile, scan)

Function for calculating the cumulative radial build up to and including the given section.

Parameters:

Name Type Description Default
section

section of the radial build to go up to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required

Returns:

Type Description

cumulative_build → cumulative radial build up to and including section given previous → cumulative radial build up to section given

Source code in process/core/io/plot_proc.py
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
def cumulative_radial_build2(section, mfile: mf.MFile, scan: int):
    """Function for calculating the cumulative radial build up to and
    including the given section.

    Parameters
    ----------
    section :
        section of the radial build to go up to
    mfile :
        MFILE data object
    scan :
        scan number to use

    Returns
    -------
    :
        cumulative_build --> cumulative radial build up to and including
        section given
        previous         --> cumulative radial build up to section given
    """
    cumulative_build = 0
    build = 0
    for item in RADIAL_BUILD:
        if item == "rminori" or item == "rminoro":
            build = mfile.get("rminor", scan=scan)
        elif item == "vvblgapi" or item == "vvblgapo":
            build = mfile.get("dr_shld_blkt_gap", scan=scan)
        elif "dr_vv_inboard" in item:
            build = mfile.get("dr_vv_inboard", scan=scan)
        elif "dr_vv_outboard" in item:
            build = mfile.get("dr_vv_outboard", scan=scan)
        else:
            build = mfile.get(item, scan=scan)
        cumulative_build += build
        if item == section:
            break
    previous = cumulative_build - build
    return (cumulative_build, previous)

poloidal_cross_section(axis, mfile, scan, demo_ranges, radial_build, colour_scheme)

Function to plot poloidal cross-section

Parameters:

Name Type Description Default
axis Axes

axis object to add plot to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required
demo_ranges bool
required
colour_scheme Literal[1, 2]

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
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
def poloidal_cross_section(
    axis: plt.Axes,
    mfile: mf.MFile,
    scan: int,
    demo_ranges: bool,
    radial_build: RadialBuild,
    colour_scheme: Literal[1, 2],
):
    """Function to plot poloidal cross-section

    Parameters
    ----------
    axis :
        axis object to add plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    demo_ranges:

    colour_scheme :
        colour scheme to use for plots
    """

    axis.set_xlabel("R / m")
    axis.set_ylabel("Z / m")
    axis.set_title("Poloidal cross-section")
    axis.minorticks_on()

    plot_vacuum_vessel_and_divertor(axis, mfile, scan, radial_build, colour_scheme)
    plot_shield(axis, mfile, scan, radial_build, colour_scheme)
    plot_blanket(axis, mfile, scan, radial_build, colour_scheme)
    plot_firstwall(axis, mfile, scan, radial_build, colour_scheme)

    plot_plasma(axis, mfile, scan, colour_scheme)
    plot_centre_cross(axis, mfile, scan)
    plot_cryostat(axis, mfile, scan, colour_scheme)

    plot_tf_coils(axis, mfile, scan, colour_scheme)
    plot_pf_coils(axis, mfile, scan, colour_scheme)

    # Ranges
    # ---
    # DEMO : Fixed ranges for comparison
    if demo_ranges:
        axis.set_ylim([-15, 15])
        axis.set_xlim([0, 20])

    # Adapatative ranges
    else:
        axis.set_xlim([0, axis.get_xlim()[1]])

plot_main_power_flow(axis, mfile, scan, fig)

Plots the main power flow diagram for the fusion reactor, including plasma, heating and current drive, first wall, blanket, vacuum vessel, divertor, coolant pumps, turbine, generator, and auxiliary systems. Annotates the diagram with power values and draws arrows to indicate power flows.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis object to plot on.

required
mfile MFile

The MFILE data object containing power flow parameters.

required
scan int

The scan number to use for extracting data.

required
fig Figure

The matplotlib figure object for additional annotations.

required
Source code in process/core/io/plot_proc.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
def plot_main_power_flow(axis: plt.Axes, mfile: mf.MFile, scan: int, fig: plt.Figure):
    """Plots the main power flow diagram for the fusion reactor, including plasma, heating and current drive,
    first wall, blanket, vacuum vessel, divertor, coolant pumps, turbine, generator, and auxiliary systems.
    Annotates the diagram with power values and draws arrows to indicate power flows.

    Parameters
    ----------
    axis:
        The matplotlib axis object to plot on.
    mfile:
        The MFILE data object containing power flow parameters.
    scan:
        The scan number to use for extracting data.
    fig:
        The matplotlib figure object for additional annotations.
    """

    axis.text(
        0.05,
        0.95,
        "* Components do not represent the design",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=11,
    )

    # ==========================================
    # Plasma
    # ===========================================

    # Load the plasma image
    with resources.path("process.core.io", "plasma.png") as img_path:
        plasma = mpimg.imread(img_path.open("rb"))

    # Display the plasma image over the figure, not the axes
    new_ax = axis.inset_axes(
        [-0.15, 0.6, 0.45, 0.45], transform=axis.transAxes, zorder=1
    )
    new_ax.imshow(plasma)
    new_ax.axis("off")

    # Add fusion power to plasma
    axis.text(
        0.22,
        0.75,
        f"$P_{{{{fus}}}}$\n{mfile.get('p_fusion_total_mw', scan=scan):.2f} MW",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=11,
    )
    # Load the neutron image
    with resources.path("process.core.io", "neutron.png") as img_path:
        neutron = mpimg.imread(img_path.open("rb"))

    new_ax = axis.inset_axes(
        [0.2, 0.85, 0.03, 0.03], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(neutron)
    new_ax.axis("off")

    # Add lost alpha power
    axis.text(
        0.22,
        0.81,
        f"$P_{{\\alpha,{{loss}}}}$\n{mfile.get('p_fw_alpha_mw', scan=scan):,.2f} MW",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=11,
    )

    # Add radiation power to plasma
    axis.text(
        0.22,
        0.69,
        f"$P_{{{{rad}}}}$\n{mfile.get('p_plasma_rad_mw', scan=scan):,.2f} MW",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=11,
    )

    # Add photon image to plasma
    axis.text(
        0.34,
        0.71,
        "$\\gamma$",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=12,
    )

    # Draw from gamma arrow bend towards divertor
    axis.annotate(
        "",
        xy=(0.35, 0.55),
        xytext=(0.35, 0.695),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "blue",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Add separatrix power to plasma
    axis.text(
        0.22,
        0.63,
        f"$P_{{{{sep}}}}$\n{mfile.get('p_plasma_separatrix_mw', scan=scan):,.2f} MW",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=2,
        fontsize=11,
    )

    # Draw from separatrix power to arrow bend
    axis.annotate(
        "",
        xy=(0.3725, 0.65),
        xytext=(0.3, 0.65),
        xycoords=fig.transFigure,
        arrowprops={
            "color": "pink",
            "arrowstyle": "-",  # No arrow head
            "linewidth": 2.0,
        },
    )

    # Draw from separatrix arrow bend to the divertor
    axis.annotate(
        "",
        xy=(0.37, 0.55),
        xytext=(0.37, 0.65),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",  # solid filled head
            "color": "pink",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw neutron arrow from plasma
    axis.annotate(
        "",
        xy=(0.95, 0.76),
        xytext=(0.31, 0.76),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "grey",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw arrow from main neutron arrow down to divertor
    axis.annotate(
        "",
        xy=(0.39, 0.55),
        xytext=(0.39, 0.76),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "grey",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw radiation arrow from plasma
    axis.annotate(
        "",
        xy=(0.56, 0.695),
        xytext=(0.3, 0.695),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "blue",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Load the alpha particle image
    with resources.path("process.core.io", "alpha_particle.png") as img_path:
        alpha = mpimg.imread(img_path.open("rb"))

    # Display the alpha particle image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.16, 0.95, 0.025, 0.025], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(alpha)
    new_ax.axis("off")

    # Hide the axes for a cleaner look
    axis.axis("off")

    # Draw alpha particle arrow from plasma
    axis.annotate(
        "",
        xy=(0.56, 0.83),
        xytext=(0.3, 0.83),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "red",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plot neutron power from plasma to box
    axis.text(
        0.37,
        0.775,
        f"$P_{{\\text{{neutron}}}}$:\n{mfile.get('p_neutron_total_mw', scan=scan):,.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # ===========================================

    # =========================================
    # Heating and current drive systems
    # =========================================

    # Add HCD primary injected power
    axis.text(
        0.0725,
        0.83,
        f"$P_{{\\text{{HCD,primary}}}}$: {mfile.get('p_hcd_primary_injected_mw', scan=scan) + mfile.get('p_hcd_primary_extra_heat_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add HCD secondary injected power
    axis.text(
        0.0725,
        0.725,
        f"$P_{{\\text{{HCD,secondary}}}}$: {mfile.get('p_hcd_secondary_injected_mw', scan=scan) + mfile.get('p_hcd_secondary_extra_heat_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Load the HCD injector image
    with resources.path("process.core.io", "hcd_injector.png") as img_path:
        hcd_injector_1 = hcd_injector_2 = mpimg.imread(img_path.open("rb"))

    # Display the injector image over the figure, not the axes
    new_ax = axis.inset_axes(
        [-0.2, 0.8, 0.15, 0.15], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(hcd_injector_1)
    new_ax.axis("off")
    new_ax = axis.inset_axes([-0.2, 0.5, 0.15, 0.5], transform=axis.transAxes, zorder=10)
    new_ax.imshow(hcd_injector_2)
    new_ax.axis("off")

    # Draw a dashed line with an arrow tip coming from the left of each injector
    for y in [0.875, 0.75]:
        axis.annotate(
            "",
            xy=(-0.2, y),
            xytext=(-0.28, y),
            xycoords=axis.transAxes,
            arrowprops={
                "arrowstyle": "-|>,head_length=1,head_width=0.3",
                "color": "black",
                "linewidth": 1.5,
                "zorder": 11,
            },
            annotation_clip=False,
        )

    # Plot line from HCD power supply to bend for injected
    axis.plot(
        [-0.28, -0.28],
        [0.875, 0.5],
        transform=axis.transAxes,
        color="black",
        linewidth=1.5,
        zorder=3,
        clip_on=False,
    )

    # Plot the HCD power supply box
    axis.text(
        0.04,
        0.45,
        "\n\nH&CD Power Supply\n\n",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
        zorder=4,
    )

    # Draw arrow from HCD box going to primary HCD losses
    axis.annotate(
        "",
        xy=(0.2, 0.5),
        xytext=(0.1, 0.5),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.2",
            "color": "black",
            "linestyle": "--",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plot electric power losses for secondary HCD
    axis.text(
        0.2,
        0.435,
        f"$P_{{\\text{{secondary,loss}}}}$:\n{mfile.get('p_hcd_secondary_electric_mw', scan=scan) * (1.0 - mfile.get('eta_hcd_secondary_injector_wall_plug', scan=scan)):.2f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Draw an arrow from HCD secondary losses to the total secondary heat power
    axis.annotate(
        "",
        xy=(0.25, 0.3),
        xytext=(0.25, 0.43),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Draw an arrow from HCD primary losses bend to the total secondary heat power
    axis.annotate(
        "",
        xy=(0.28, 0.3),
        xytext=(0.28, 0.5),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Draw line from HCD primary losses to the arrow bend
    axis.annotate(
        "",
        xy=(0.26, 0.5),
        xytext=(0.28, 0.5),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "black",
            "linestyle": "--",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw arrow frim HCD power supply to secondary HCD losses
    axis.annotate(
        "",
        xy=(0.2, 0.46),
        xytext=(0.1, 0.46),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.2",
            "color": "black",
            "linestyle": "--",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plot electric power losses for primary HCD
    axis.text(
        0.2,
        0.485,
        f"$P_{{\\text{{primary,loss}}}}$:\n{mfile.get('p_hcd_primary_electric_mw', scan=scan) * (1.0 - mfile.get('eta_hcd_primary_injector_wall_plug', scan=scan)):.2f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Draw arrow from HCD primary electric box to HCD power supply box
    axis.annotate(
        "",
        xy=(0.06, 0.45),
        xytext=(0.06, 0.38),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "->",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
        },
    )

    # Draw arrow from HCD secondary electric box to HCD power supply box
    axis.annotate(
        "",
        xy=(0.12, 0.45),
        xytext=(0.12, 0.38),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "->",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
        },
    )

    # Plot HCD secondary losses box
    axis.text(
        0.12,
        0.35,
        f"$P_{{\\text{{secondary}}}}$:\n{mfile.get('p_hcd_secondary_electric_mw', scan=scan):.2f} MWe \n$\\eta$: {mfile.get('eta_hcd_secondary_injector_wall_plug', scan=scan):.2f}",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Plot HCD primary electric box
    axis.text(
        0.025,
        0.35,
        f"$P_{{\\text{{primary}}}}$:\n{mfile.get('p_hcd_primary_electric_mw', scan=scan):.2f} MWe\n$\\eta$: {mfile.get('eta_hcd_primary_injector_wall_plug', scan=scan):.2f}",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # =============================================

    # =============================================
    # Low grade heat total
    # =============================================

    # Plot box of total low grade secondary heat
    axis.text(
        0.325,
        0.225,
        f"\n\nTotal Low Grade Secondary Heat\n\n {mfile.get('p_plant_secondary_heat_mw', scan=scan):,.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="center",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
        zorder=4,
    )

    # =============================================

    # ==========================================
    # Power conversion systems
    # ===========================================

    # Load the turbine image
    with resources.path("process.core.io", "turbine.png") as img_path:
        turbine = mpimg.imread(img_path.open("rb"))

    # Display the turbine image over the figure, not the axes
    new_ax = axis.inset_axes([1.1, 0.0, 0.15, 0.15], transform=axis.transAxes, zorder=10)
    new_ax.imshow(turbine)
    new_ax.axis("off")

    # Plot the total primary thermal power box
    axis.text(
        0.9,
        0.25,
        f"$P_{{\\text{{primary,thermal}}}}$:\n{mfile.get('p_plant_primary_heat_mw', scan=scan):,.2f} MW \n$\\eta_{{\\text{{turbine}}}}$: {mfile.get('eta_turbine', scan=scan):.3f}",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Draw arrow from bend to turbine inlet
    axis.annotate(
        "",
        xy=(0.925, 0.165),
        xytext=(0.96, 0.165),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Total primary thermal to turbine inlet line bend
    axis.annotate(
        "",
        xy=(0.96, 0.245),
        xytext=(0.96, 0.1625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Load the generator image
    with resources.path("process.core.io", "generator.png") as img_path:
        generator = mpimg.imread(img_path.open("rb"))

    # Display the generator image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.96, 0.0, 0.15, 0.15], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(generator)
    new_ax.axis("off")

    # Generator to gross electric power
    axis.annotate(
        "",
        xy=(0.745, 0.17),
        xytext=(0.79, 0.17),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Generator labels
    axis.text(
        0.79,
        0.16,
        "Generator",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        zorder=20,
    )

    # Connector from turbine to generator
    axis.annotate(
        "",
        xy=(0.85, 0.17),
        xytext=(0.925, 0.17),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "black",
            "linewidth": 7.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Turbine to loss power
    axis.annotate(
        "",
        xy=(0.91, 0.08),
        xytext=(0.91, 0.13),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "dashed",
        },
    )

    # Load the pylon image
    with resources.path("process.core.io", "pylon.png") as img_path:
        pylon = mpimg.imread(img_path.open("rb"))

    # Display the pylon image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.925, -0.1, 0.1, 0.1], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(pylon)
    new_ax.axis("off")

    # Plot the gross electric power box
    axis.text(
        0.68,
        0.15,
        f"$P_{{\\text{{gross}}}}$:\n{mfile.get('p_plant_electric_gross_mw', scan=scan):,.2f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lime",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Gross to net electric power
    axis.annotate(
        "",
        xy=(0.72, 0.08),
        xytext=(0.72, 0.15),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plot the turbine loss box
    axis.text(
        0.875,
        0.05,
        f"$P_{{\\text{{loss}}}}$:\n{mfile.get('p_turbine_loss_mw', scan=scan):,.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Shield primary thermal to plant total primary thermal arrow
    axis.annotate(
        "",
        xy=(0.95, 0.3),
        xytext=(0.95, 0.55),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plot the net electric power box
    axis.text(
        0.68,
        0.05,
        f"$P_{{\\text{{net,electric}}}}$:\n{mfile.get('p_plant_electric_net_mw', scan=scan):,.2f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lime",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Plot the recirculated electric power box
    axis.text(
        0.575,
        0.14,
        (
            f"$P_{{\\text{{recirc,electric}}}}$:\n{mfile.get('p_plant_electric_recirc_mw', scan=scan):,.2f} MWe\n"
            f"$f_{{\\text{{recirc}}}}$:\n{mfile.get('f_p_plant_electric_recirc', scan=scan):,.2f}"
        ),
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lime",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Gross to recirculated power arrow
    axis.annotate(
        "",
        xy=(0.64, 0.17),
        xytext=(0.675, 0.17),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Recirculated to pumps electric
    axis.annotate(
        "",
        xy=(0.7, 0.225),
        xytext=(0.645, 0.185),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Recirculated power to HCD secondary electric arrow bend
    axis.annotate(
        "",
        xy=(0.14, 0.2),
        xytext=(0.57, 0.2),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Recirculated power to HCD primary electric arrow bend
    axis.annotate(
        "",
        xy=(0.08, 0.18),
        xytext=(0.57, 0.18),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Arrow to primary HCD electric from bend
    axis.annotate(
        "",
        xy=(0.08, 0.35),
        xytext=(0.08, 0.1775),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Arrow to secondary HCD electric from bend
    axis.annotate(
        "",
        xy=(0.14, 0.35),
        xytext=(0.14, 0.2),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # ==========================================

    # ================================
    # First wall, blanket and shield
    # ================================

    # Load the first wall image
    with resources.path("process.core.io", "fw.png") as img_path:
        fw = mpimg.imread(img_path.open("rb"))

    # Display the first wall image over the figure, not the axes
    new_ax = axis.inset_axes([0.4, 0.625, 0.4, 0.4], transform=axis.transAxes, zorder=10)
    new_ax.imshow(fw)
    new_ax.axis("off")

    # Add first wall label above image
    axis.text(
        0.5,
        0.9,
        "First Wall",
        fontsize=11,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
    )

    # Alpha power incident on first wall box
    axis.text(
        0.46,
        0.85,
        f"$P_{{\\text{{FW, }}\\alpha}}$:\n{mfile.get('p_fw_alpha_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "red",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Neutron power incident on first wall box
    axis.text(
        0.46,
        0.775,
        f"$P_{{\\text{{FW,nuclear}}}}$:\n{mfile.get('p_fw_nuclear_heat_total_mw', scan=scan):,.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Plot radiation power incident on first wall box
    axis.text(
        0.46,
        0.71,
        f"$P_{{\\text{{FW,rad}}}}$:\n{mfile.get('p_fw_rad_total_mw', scan=scan):,.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "dodgerblue",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Draw arrow from FW to heat depsoited box
    axis.annotate(
        "",
        xy=(0.61, 0.585),
        xytext=(0.61, 0.65),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw arrow from Blanket to heat deposited box
    axis.annotate(
        "",
        xy=(0.81, 0.585),
        xytext=(0.81, 0.63),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw arrow from shield to heat deposited box
    axis.annotate(
        "",
        xy=(0.92, 0.59),
        xytext=(0.92, 0.62),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # First wall heat deposited box
    axis.text(
        0.5,
        0.555,
        f"Primary thermal\n(inc pump): {mfile.get('p_fw_heat_deposited_mw', scan=scan):,.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "linewidth": 2,
        },
    )

    # Blanket heat deposited box
    axis.text(
        0.7,
        0.555,
        f"Primary thermal\n(inc pump): {mfile.get('p_blkt_heat_deposited_mw', scan=scan):,.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "linewidth": 2,
        },
    )

    # Shield heat deposited box
    axis.text(
        0.875,
        0.555,
        f"Primary thermal:\n{mfile.get('p_shld_heat_deposited_mw', scan=scan):.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "linewidth": 2,
        },
    )

    # Draw arrow from FW primary heat box to blanket and FW primary heat deposited box
    axis.annotate(
        "",
        xy=(0.65, 0.52),
        xytext=(0.62, 0.55),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw arrow from blanket primary heat box to blanket and FW primary heat deposited box
    axis.annotate(
        "",
        xy=(0.68, 0.52),
        xytext=(0.7, 0.55),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Draw a downward arrow from the primary thermal box to the right side of the generator
    axis.annotate(
        "",
        xy=(0.825, 0.57),
        xytext=(0.87, 0.57),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Connect blanket thermal heat deposited to the shield heat deposited
    axis.annotate(
        "",
        xy=(0.625, 0.57),
        xytext=(0.695, 0.57),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Connect first wall thermal heat deposited to the blanket heat deposited
    axis.annotate(
        "",
        xy=(0.56, 0.52),
        xytext=(0.56, 0.55),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "orange",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # FW and blanket heat deposited box
    axis.text(
        0.6,
        0.49,
        f"Primary thermal (inc pump): {mfile.get('p_fw_blkt_heat_deposited_mw', scan=scan):,.2f} MWth\n",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Load the blanket image
    with resources.path("process.core.io", "blanket_with_coolant.png") as img_path:
        blanket = mpimg.imread(img_path.open("rb"))

    # Display the blanket image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.75, 0.625, 0.4, 0.4], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(blanket)
    new_ax.axis("off")

    # Add blanket label above image
    axis.text(
        0.7,
        0.9,
        "Blanket",
        fontsize=11,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
    )

    # Plot the nuclear heat total from blanket
    axis.text(
        0.625,
        0.775,
        (
            f"$P_{{\\text{{Blkt,nuclear}}}}$:\n{mfile.get('p_blkt_nuclear_heat_total_mw', scan=scan):,.2f} MW \n"
            f"$P_{{\\text{{Blkt,multiplication}}}}$:\n{mfile.get('p_blkt_multiplication_mw', scan=scan):,.2f} MW\n"
            f"$f_{{\\text{{multiplication}}}}$:\n{mfile.get('f_p_blkt_multiplication', scan=scan):,.2f}"
        ),
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Load the vacuum vessel image
    with resources.path("process.core.io", "vv.png") as img_path:
        vv = mpimg.imread(img_path.open("rb"))

    # Display the vacuum vessel image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.975, 0.625, 0.4, 0.4], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(vv)
    new_ax.axis("off")

    # Add vacuum vessel label above image
    axis.text(
        0.85,
        0.9,
        "Vacuum Vessel",
        fontsize=11,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
    )

    # Plot the secondary heat from the shield
    axis.text(
        0.38,
        0.375,
        f"$P_{{\\text{{shld,secondary}}}}$:\n{mfile.get('p_shld_secondary_heat_mw', scan=scan):,.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Shield secondary power box to secondary heat total
    axis.annotate(
        "",
        xy=(0.4, 0.3),
        xytext=(0.4, 0.37),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Arrow from shield bend to sheidl secondary heat
    axis.annotate(
        "",
        xy=(0.445, 0.39),
        xytext=(0.85, 0.39),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Line from shield to arrow bend for secondary heat
    axis.annotate(
        "",
        xy=(0.85, 0.385),
        xytext=(0.85, 0.625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # ============================================
    # Divertor
    # ============================================

    axis.text(
        0.325,
        0.48,
        "Divertor",
        transform=fig.transFigure,
        horizontalalignment="left",
        verticalalignment="bottom",
        zorder=1000,  # bring to front
        fontsize=11,
        color="white",  # make text white
    )

    # Load the divertor image
    with resources.path("process.core.io", "divertor.png") as img_path:
        divertor = mpimg.imread(img_path.open("rb"))

    # Display the divertor image over the figure, not the axes
    new_ax = axis.inset_axes([0.1, 0.4, 0.3, 0.25], transform=axis.transAxes, zorder=10)
    new_ax.imshow(divertor)
    new_ax.axis("off")

    # Total divertor radiation power box
    axis.text(
        0.29,
        0.57,
        f"$P_{{\\text{{div,rad}}}}$:\n{mfile.get('p_div_rad_total_mw', scan=scan):,.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "dodgerblue",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Divertor nuclear heat total box
    axis.text(
        0.4,
        0.58,
        f"$P_{{\\text{{div,nuclear}}}}$:\n{mfile.get('p_div_nuclear_heat_total_mw', scan=scan):,.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Divertor primary thermal heat deposited box
    axis.text(
        0.44,
        0.46,
        (
            f"Primary thermal (inc pump):\n{mfile.get('p_div_heat_deposited_mw', scan=scan):.2f} MWth\n"
            f"Solid angle fraction: {mfile.get('f_ster_div_single', scan=scan):.3f}\n"
            f"Primary heat fraction: {mfile.get('f_p_div_primary_heat', scan=scan):.3f}"
        ),
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "linewidth": 2,
        },
        zorder=100,
    )

    # Divertor secondary heat box
    axis.text(
        0.3,
        0.375,
        f"$P_{{\\text{{div,secondary}}}}$:\n{mfile.get('p_div_secondary_heat_mw', scan=scan):.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Divertor to divertor secondary heat arrow
    axis.annotate(
        "",
        xy=(0.33, 0.405),
        xytext=(0.33, 0.5),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Divertor to divertor primary thermal heat arrow
    axis.annotate(
        "",
        xy=(0.445, 0.5),
        xytext=(0.4, 0.5),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "orange",
            "linewidth": 2.0,
            "zorder": 50,
            "fill": True,
        },
    )

    # Divertor secondary heat to total secondary heat arrow
    axis.annotate(
        "",
        xy=(0.33, 0.3),
        xytext=(0.33, 0.375),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # ===========================================

    # ===========================================
    # Coolant pumps
    # ===========================================

    # Divertor coolant pump box
    axis.text(
        0.55,
        0.33,
        f"$P_{{\\text{{div,pump}}}}$: {mfile.get('p_div_coolant_pump_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Divertor pump box to divertor primary heat deposited box
    axis.annotate(
        "",
        xy=(0.57, 0.46),
        xytext=(0.57, 0.35),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Coolant pumps total to divertor pump box
    axis.annotate(
        "",
        xy=(0.64, 0.34),
        xytext=(0.7, 0.34),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Pumps total to shield bump box arrow
    axis.annotate(
        "",
        xy=(0.875, 0.34),
        xytext=(0.81, 0.34),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Shield coolant pump box
    axis.text(
        0.875,
        0.325,
        f"$P_{{\\text{{shld,pump}}}}$:\n{mfile.get('p_shld_coolant_pump_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # FW and Blanket coolant pumps total
    axis.text(
        0.725,
        0.4,
        f"$P_{{\\text{{FW + Blkt}}}}$:\n{mfile.get('p_fw_blkt_coolant_pump_mw', scan=scan):.2f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # FW and Blanket coolant pumps total to FW and Blanket heat deposited box
    axis.annotate(
        "",
        xy=(0.75, 0.49),
        xytext=(0.75, 0.44),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 3.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Coolant pumps total to blanket and FW pump
    axis.annotate(
        "",
        xy=(0.75, 0.4),
        xytext=(0.75, 0.36),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Shield pump to sheild primary thermal
    axis.annotate(
        "",
        xy=(0.9, 0.54),
        xytext=(0.9, 0.36),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Coolant pumps total electric box
    axis.text(
        0.7,
        0.225,
        (
            f"Coolant pumps electric:\n{mfile.get('p_coolant_pump_elec_total_mw', scan=scan):.3f} MWe\n"
            f"$\\eta$: {mfile.get('eta_coolant_pump_electric', scan=scan):.3f}"
        ),
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lime",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Coolant pumps total
    axis.text(
        0.7,
        0.325,
        f"Coolant pumps total:\n{mfile.get('p_coolant_pump_total_mw', scan=scan):.3f} MW",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Electric recirculated to pumps total arrow
    axis.annotate(
        "",
        xy=(0.75, 0.325),
        xytext=(0.75, 0.275),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Coolant pumps losses total box
    axis.text(
        0.5,
        0.235,
        f"Coolant pumps losses total:\n{mfile.get('p_coolant_pump_loss_total_mw', scan=scan):.3f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 0.8,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # Coolant electric to pump losses arrow
    axis.annotate(
        "",
        xy=(0.645, 0.25),
        xytext=(0.695, 0.25),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # Coolant losses to secondary heat total arrow
    axis.annotate(
        "",
        xy=(0.405, 0.25),
        xytext=(0.4975, 0.25),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # ============================================

    # ===========================================
    # Plant core systems
    # ===========================================

    # Cryo Plant box
    axis.text(
        0.49,
        0.05,
        f"Cryo Plant:\n{mfile.get('p_cryo_plant_electric_mw', scan=scan):.3f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Recirculated power to cryo plant arrow
    axis.annotate(
        "",
        xy=(0.525, 0.075),
        xytext=(0.525, 0.1625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Tritium Plant box
    axis.text(
        0.4,
        0.05,
        f"Tritium Plant:\n{mfile.get('p_tritium_plant_electric_mw', scan=scan):.3f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # # Recirculated power to tritium plant arrow
    axis.annotate(
        "",
        xy=(0.44, 0.075),
        xytext=(0.44, 0.1625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Vacuum Pumps box
    axis.text(
        0.575,
        0.05,
        f"Vacuum pumps:\n{mfile.get('vachtmw', scan=scan):.3f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Recirculated power to vacuum pumps arrow
    axis.annotate(
        "",
        xy=(0.62, 0.08),
        xytext=(0.62, 0.1375),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Plant base load box
    axis.text(
        0.085,
        0.075,
        (
            f"Plant base load:\n{mfile.get('p_plant_electric_base_total_mw', scan=scan):.3f} MWe\n"
            f"Minimum base load:\n{mfile.get('p_plant_electric_base', scan=scan) * 1.0e-6:.3f} MWe\n"
            f"Plant floor power density:\n{mfile.get('pflux_plant_floor_electric', scan=scan) * 1.0e-3:.3f} kW$\\text{{m}}^{{-2}}$"
        ),
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # TF coil power box
    axis.text(
        0.325,
        0.075,
        f"TF coils:\n{mfile.get('p_tf_electric_supplies_mw', scan=scan):.3f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # PF coil power box
    axis.text(
        0.25,
        0.05,
        f"PF coils:\n{mfile.get('p_pf_electric_supplies_mw', scan=scan):.3f} MWe",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "burlywood",
            "alpha": 0.8,
            "linewidth": 2,
        },
    )

    # Recirculated power to TF,PF and plant base arrow bend
    axis.annotate(
        "",
        xy=(0.22, 0.16),
        xytext=(0.574, 0.16),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 1.5,
            "zorder": 5,
            "fill": True,
        },
    )

    # Recirculated power to  PF
    axis.annotate(
        "",
        xy=(0.28, 0.075),
        xytext=(0.28, 0.1625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # Recirculated power to TF
    axis.annotate(
        "",
        xy=(0.35, 0.1),
        xytext=(0.35, 0.1625),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
        },
    )

    # HCD secondary heat box
    axis.text(
        0.46,
        0.285,
        f"$P_{{\\text{{HCD,loss}}}}$:\n{mfile.get('p_hcd_secondary_heat_mw', scan=scan):.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 0.8,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # FW to HCD secondary heat arrow
    axis.annotate(
        "",
        xy=(0.47, 0.32),
        xytext=(0.47, 0.65),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # HCD loss to total secondary heat
    axis.annotate(
        "",
        xy=(0.41, 0.295),
        xytext=(0.455, 0.295),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

    # TF nuclear heat box
    axis.text(
        0.155,
        0.25,
        f"$P_{{\\text{{TF,nuclear}}}}$:\n{mfile.get('p_tf_nuclear_heat_mw', scan=scan):.2f} MWth",
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
            "linestyle": "dashed",
        },
    )

    # TF nuclear heat to secondary heat total box arrow
    axis.annotate(
        "",
        xy=(0.245, 0.265),
        xytext=(0.215, 0.265),
        xycoords=fig.transFigure,
        arrowprops={
            "arrowstyle": "-|>,head_length=1,head_width=0.3",
            "color": "black",
            "linewidth": 2.0,
            "zorder": 5,
            "fill": True,
            "linestyle": "--",
        },
    )

plot_main_plasma_information(axis, mfile, scan, colour_scheme, fig)

Plots the main plasma information including plasma shape, geometry, currents, heating, confinement, and other relevant plasma parameters.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis object to plot on.

required
mfile MFile

The MFILE data object containing plasma parameters.

required
scan int

The scan number to use for extracting data.

required
colour_scheme int

The colour scheme to use for plots.

required
fig Figure

The matplotlib figure object for additional annotations.

required
Source code in process/core/io/plot_proc.py
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
def plot_main_plasma_information(
    axis: plt.Axes,
    mfile: mf.MFile,
    scan: int,
    colour_scheme: Literal[1, 2],
    fig: plt.Figure,
):
    """Plots the main plasma information including plasma shape, geometry, currents, heating,
    confinement, and other relevant plasma parameters.

    Parameters
    ----------
    axis : plt.Axes
        The matplotlib axis object to plot on.
    mfile : mf.MFile
        The MFILE data object containing plasma parameters.
    scan : int
        The scan number to use for extracting data.
    colour_scheme : int
        The colour scheme to use for plots.
    fig : plt.Figure
        The matplotlib figure object for additional annotations.
    """
    # Import key variables
    triang = mfile.get("triang", scan=scan)
    kappa = mfile.get("kappa", scan=scan)

    # Remove the axes
    axis.axis("off")

    # Plot the main plasma shape
    plot_plasma(axis, mfile, scan, colour_scheme)

    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)
    # Get the plasma permieter points for the core plasma region
    pg = plasma_geometry(
        rmajor=rmajor,
        rminor=mfile.get("rminor", scan=scan)
        * mfile.get("radius_plasma_core_norm", scan=scan),
        triang=mfile.get("triang", scan=scan),
        kappa=mfile.get("kappa", scan=scan),
        i_single_null=mfile.get("i_single_null", scan=scan),
        i_plasma_shape=1,
        square=mfile.get("plasma_square", scan=scan),
    )
    # Plot the core plasma boundary line
    axis.plot(pg.rs, pg.zs, color="black", linestyle="--")

    # Plot the centre of the plasma
    axis.plot(rmajor, 0, "r+", markersize=20, markeredgewidth=2)

    # Add injected power label
    axis.text(
        0.325,
        0.925,
        f"$Q_{{\\text{{plasma}}}}$: {mfile.get('big_q_plasma', scan=scan):.2f}",
        fontsize=15,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
        transform=fig.transFigure,
    )

    # =========================================

    # Draw a double-ended arrow from the inner plasma edge to the center
    axis.annotate(
        "",
        xy=(rmajor - rminor, 0),  # Inner plasma edge
        xytext=(rmajor, 0),  # Center
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Add a label for the minor radius
    axis.text(
        rmajor - rminor / 2,
        -rminor * kappa * 0.08,
        f"$a$: {rminor:.2f} m",
        fontsize=9,
        color="black",
        ha="center",
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
    )

    # ============================================

    # Draw a single-ended arrow from the machien centre to the plasma center
    axis.annotate(
        "",
        xy=(axis.get_xlim()[0], -rminor * 0.3 * kappa),  # Inner plasma edge
        xytext=(rmajor, -rminor * 0.3 * kappa),  # Center
        arrowprops={"arrowstyle": "<-", "color": "black"},
    )

    # Add a label for the major radius
    axis.text(
        rmajor - rminor / 2,
        -rminor * kappa * 0.25,
        f"$R_0$: {rmajor:.2f} m",
        fontsize=9,
        color="black",
        ha="center",
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
    )

    # ============================================

    # Draw a double-ended arrow from the xpoint to the center to show elongation
    axis.annotate(
        "",
        xy=(rmajor - rminor * triang, kappa * rminor),  # Inner plasma edge
        xytext=(rmajor - rminor * triang, 0),  # Center
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Write the elongation beside the vertical line, position relative to figure axes
    axis.text(
        0.3,
        0.75,
        f"$\\kappa$: {mfile.get('kappa', scan=scan):.2f}",
        fontsize=9,
        color="black",
        rotation=270,
        verticalalignment="center",
        transform=axis.transAxes,
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
    )

    # =============================================

    # Draw a double-ended arrow from the inner plasma edge to the center
    axis.annotate(
        "",
        xy=(rmajor - rminor * triang, kappa * rminor * 0.25),  # Inner plasma edge
        xytext=(rmajor, kappa * rminor * 0.25),  # Center
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Write the triangularity to the left of the cross, position relative to figure axes
    axis.text(
        rmajor - (rminor * triang * 0.75),
        kappa * rminor * 0.3,
        f"$\\delta$: {mfile.get('triang', scan=scan):.2f}",
        fontsize=9,
        color="black",
        rotation=0,
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
    )

    # =============================================

    radius_plasma_core_norm = mfile.get("radius_plasma_core_norm", scan=scan)

    # Draw a double-ended arrow for the plasma core region
    axis.annotate(
        "",
        xy=(rmajor, -rminor * 0.1 * kappa),  # Inner plasma edge
        xytext=(rmajor + (rminor * radius_plasma_core_norm), -rminor * 0.1 * kappa),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )
    # Add a label for core region
    axis.text(
        rmajor + (rminor * radius_plasma_core_norm / 4),
        -rminor * kappa * 0.15,
        f"$\\rho_{{\\text{{core}}}}$: {radius_plasma_core_norm:.2f}",
        fontsize=9,
        color="black",
        rotation=0,
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "white", "alpha": 1.0},
    )

    # ================================================

    # Add plasma volume, areas and shaping information
    textstr_plasma = (
        f"$\\mathbf{{Shaping:}}$\n \n"
        f"$\\kappa_{{95}}$: {mfile.get('kappa95', scan=scan):.2f} | $\\delta_{{95}}$: {mfile.get('triang95', scan=scan):.2f} | $\\zeta$: {mfile.get('plasma_square', scan=scan):.2f}\n"
        f"A: {mfile.get('aspect', scan=scan):.2f}\n"
        f"$ V_{{\\text{{p}}}}:$ {mfile.get('vol_plasma', scan=scan):,.2f}$ \\ \\text{{m}}^3$\n"
        f"$ A_{{\\text{{p,surface}}}}:$ {mfile.get('a_plasma_surface', scan=scan):,.2f}$ \\ \\text{{m}}^2$\n"
        f"$ A_{{\\text{{p_poloidal}}}}:$ {mfile.get('a_plasma_poloidal', scan=scan):,.2f}$ \\ \\text{{m}}^2$\n"
        f"$ L_{{\\text{{p_poloidal}}}}:$ {mfile.get('len_plasma_poloidal', scan=scan):,.2f}$ \\ \\text{{m}}$"
    )

    axis.text(
        0.55,
        0.975,
        textstr_plasma,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # ============================================

    # Draw a red arrow coming from the right and pointing at the plasma
    axis.annotate(
        "",
        xy=(rmajor + (rminor * 0.8), kappa * rminor * 0.2),  # Pointing at the plasma
        xytext=(
            rmajor + (rminor * 1.4),
            kappa * rminor * 0.2,
        ),  # Starting point of the arrow
        arrowprops={"facecolor": "red", "edgecolor": "red", "lw": 2},
    )

    # Draw a red arrow coming from the right and pointing at the plasma
    axis.annotate(
        "",
        xy=(rmajor + (rminor * 0.8), -kappa * rminor * 0.2),  # Pointing at the plasma
        xytext=(
            rmajor + (rminor * 1.4),
            -kappa * rminor * 0.2,
        ),  # Starting point of the arrow
        arrowprops={"facecolor": "red", "edgecolor": "red", "lw": 2},
    )

    i_hcd_primary = mfile.get("i_hcd_primary", scan=scan)
    i_hcd_secondary = mfile.get("i_hcd_secondary", scan=scan)

    # Determine heating type for primary and secondary systems
    if i_hcd_primary in [5, 8]:
        primary_heating = "NBI"
    elif i_hcd_primary in [3, 7, 10, 11, 13]:
        primary_heating = "ECRH"
    elif i_hcd_primary == 12:
        primary_heating = "EBW"
    elif i_hcd_primary in [1, 4, 6]:
        primary_heating = "LHCD"
    elif i_hcd_primary == 2:
        primary_heating = "ICCD"
    else:
        primary_heating = ""

    if i_hcd_secondary in [5, 8]:
        secondary_heating = "NBI"
    elif i_hcd_secondary in [3, 7, 10, 11, 13]:
        secondary_heating = "ECRH"
    elif i_hcd_secondary == 12:
        secondary_heating = "EBW"
    elif i_hcd_secondary in [1, 4, 6]:
        secondary_heating = "LHCD"
    elif i_hcd_secondary == 2:
        secondary_heating = "ICCD"
    else:
        secondary_heating = ""

    # Add heating and current drive information
    textstr_hcd = (
        f"$\\mathbf{{Heating \\ & \\ current \\ drive:}}$\n \n"
        f"Total injected heat: {mfile.get('p_hcd_injected_total_mw', scan=scan):.3f} MW                       \n"
        f"Ohmic heating power: {mfile.get('p_plasma_ohmic_mw', scan=scan):.3f} MW         \n\n"
        f"$\\mathbf{{Primary \\ system: {primary_heating}}}$ \n"
        f"Current driving power {mfile.get('p_hcd_primary_injected_mw', scan=scan):.4f} MW\n"
        f"Extra heat power: {mfile.get('p_hcd_primary_extra_heat_mw', scan=scan):.4f} MW\n"
        f"$\\gamma_{{\\text{{CD,prim}}}}$: {mfile.get('eta_cd_hcd_primary', scan=scan):.4f} A/W  |   $\\langle\\zeta_{{\\text{{CD,prim}}}}\\rangle$: {mfile.get('eta_cd_dimensionless_hcd_primary', scan=scan):.4f}  \n"
        f"$\\eta_{{\\text{{CD,prim}}}}$: {mfile.get('eta_cd_norm_hcd_primary', scan=scan):.4f} $\\times 10^{{20}}  \\mathrm{{A}} / \\mathrm{{Wm}}^2$\n"
        f"Current driven by primary: {mfile.get('c_hcd_primary_driven', scan=scan) / 1e6:.3f} MA\n\n"
        f"$\\mathbf{{Secondary \\ system: {secondary_heating}}}$ \n"
        f"Current driving power {mfile.get('p_hcd_secondary_injected_mw', scan=scan):.4f} MW\n"
        f"Extra heat power: {mfile.get('p_hcd_secondary_extra_heat_mw', scan=scan):.4f} MW\n"
        f"$\\gamma_{{\\text{{CD,sec}}}}$: {mfile.get('eta_cd_hcd_secondary', scan=scan):.4f} A/W  |   $\\langle\\zeta_{{\\text{{CD,sec}}}}\\rangle$: {mfile.get('eta_cd_dimensionless_hcd_secondary', scan=scan):.4f}  \n"
        f"$\\eta_{{\\text{{CD,sec}}}}$: {mfile.get('eta_cd_norm_hcd_secondary', scan=scan):.4f} $\\times 10^{{20}}  \\mathrm{{A}} / \\mathrm{{Wm}}^2$\n"
        f"Current driven by secondary: {mfile.get('c_hcd_secondary_driven', scan=scan) / 1e6:.3f} MA\n"
    )

    axis.text(
        0.66,
        0.6,
        textstr_hcd,
        fontsize=9,
        verticalalignment="top",
        transform=plt.gcf().transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "paleturquoise",
            "alpha": 1.0,
            "linewidth": 2,
            "edgecolor": "black",
        },
    )

    # Add injected power label
    axis.text(
        0.92,
        0.625,
        "$P_{\\text{inj}}$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # ================================================

    # Add beta information
    textstr_beta = (
        f"$\\mathbf{{Beta \\ Information:}}$\n \n"
        f"Total beta,$ \\ \\langle \\beta \\rangle$: {mfile.get('beta_total_vol_avg', scan=scan):.4f}\n"
        f"Thermal beta,$ \\ \\langle \\beta_{{\\text{{thermal}}}} \\rangle$: {mfile.get('beta_thermal_vol_avg', scan=scan):.4f}\n"
        f"Toroidal beta,$ \\ \\langle \\beta_{{\\text{{t}}}} \\rangle$: {mfile.get('beta_toroidal_vol_avg', scan=scan):.4f}\n"
        f"Poloidal beta,$ \\ \\langle \\beta_{{\\text{{p}}}} \\rangle$: {mfile.get('beta_poloidal_vol_avg', scan=scan):.4f}\n"
        f"Fast-alpha beta,$ \\ \\langle \\beta_{{\\alpha}} \\rangle$: {mfile.get('beta_fast_alpha', scan=scan):.4f}\n"
        f"Normalised total beta,$ \\ \\beta_{{\\text{{N}}}}$: {mfile.get('beta_norm_total', scan=scan):.4f}\n"
        f"Normalised thermal beta,$ \\ \\beta_{{\\text{{N,thermal}}}}$: {mfile.get('beta_norm_thermal', scan=scan):.4f}\n"
    )

    axis.text(
        0.025,
        0.96,
        textstr_beta,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightblue",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add beta label
    axis.text(
        0.215,
        0.94,
        "$\\beta$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # ================================================

    # Add volt-second information
    textstr_volt_second = (
        f"$\\mathbf{{Volt-second \\ requirements:}}$\n \n"
        f"Total volt-second consumption: {mfile.get('vs_plasma_total_required', scan=scan):.4f} Vs                \n"
        f"  - Internal volt-seconds: {mfile.get('vs_plasma_internal', scan=scan):.4f} Vs\n"
        f"  - Volt-seconds needed for burn: {mfile.get('vs_plasma_burn_required', scan=scan):.4f} Vs\n"
        f"  - Volt-seconds needed for ramp: {mfile.get('vs_plasma_ramp_required', scan=scan):.4f} Vs | $C_{{\\text{{ejima}}}}$: {mfile.get('ejima_coeff', scan=scan):.4f}\n"
        f"$V_{{\\text{{loop}}}}$: {mfile.get('v_plasma_loop_burn', scan=scan):.4f} V\n"
        f"$\\Omega_{{\\text{{p}}}}$: {mfile.get('res_plasma', scan=scan):.4e} $\\Omega$\n"
        f"Plasma resistive diffusion time: {mfile.get('t_plasma_res_diffusion', scan=scan):,.4f} s\n"
        f"Plasma inductance: {mfile.get('ind_plasma', scan=scan):.4e} H | ITER $l_i(3)$: {mfile.get('ind_plasma_internal_norm_iter_3', scan=scan):.4f}\n"
        f"Plasma stored magnetic energy: {mfile.get('e_plasma_magnetic_stored', scan=scan) / 1e9:.4f} GJ\n"
        f"Plasma normalised internal inductance: {mfile.get('ind_plasma_internal_norm', scan=scan):.4f}"
    )

    axis.text(
        0.025,
        0.785,
        textstr_volt_second,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightgreen",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add volt second label
    axis.text(
        0.30,
        0.77,
        "Vs",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =========================================

    # Add divertor information
    textstr_div = (
        f"\n$P_{{\\text{{sep}}}}$: {mfile.get('p_plasma_separatrix_mw', scan=scan):.2f} MW           \n"
        f"$\\frac{{P_{{\\text{{sep}}}}}}{{R}}$: {mfile.get('p_plasma_separatrix_mw/rmajor', scan=scan):.2f} MW/m               \n"
        f"$\\frac{{P_{{\\text{{sep}}}}}}{{B_T  q_a  R}}$: {mfile.get('pdivtbt_over_qar', scan=scan):.2f} MW T/m               "
    )

    axis.text(
        0.35,
        0.12,
        textstr_div,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "orange",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add divertor label
    axis.text(
        0.45,
        0.1,
        "$P_{\\text{div}}$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # ================================================

    # Add confinement information
    textstr_confinement = (
        f"$\\mathbf{{Confinement:}}$\n \n"
        f"Confinement scaling law: {mfile.get('tauelaw', scan=scan)}\n"
        f"Confinement $H$ factor: {mfile.get('hfact', scan=scan):.4f}\n"
        f"Energy confinement time from scaling: {mfile.get('t_energy_confinement', scan=scan):.4f} s\n"
        f"Fusion double product: {mfile.get('ntau', scan=scan):.4e} s/m³\n"
        f"Lawson Triple product: {mfile.get('nttau', scan=scan):.4e} keV·s/m³\n"
        f"Transport loss power assumed in scaling law: {mfile.get('p_plasma_loss_mw', scan=scan):.4f} MW\n"
        f"Plasma thermal energy (inc. $\\alpha$), $W$: {mfile.get('e_plasma_beta', scan=scan) / 1e9:.4f} GJ\n"
        f"Alpha particle confinement time: {mfile.get('t_alpha_confinement', scan=scan):.4f} s"
    )

    axis.text(
        0.025,
        0.575,
        textstr_confinement,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "gainsboro",  # Changed to a not normal color (Aquamarine)
            "alpha": 1.0,
            "linewidth": 2,
            "edgecolor": "black",
        },
    )

    # Add tau label
    axis.text(
        0.3,
        0.55,
        "$\\tau_{\\text{e}} $",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =========================================

    # Load the neutron image
    with resources.path(
        "process.core.io", "alpha_particle.png"
    ) as alpha_particle_image_path:
        # Use importlib.resources to locate the image
        alpha_particle = mpimg.imread(alpha_particle_image_path.open("rb"))

    # Display the neutron image over the figure, not the axes
    new_ax = axis.inset_axes(
        [0.975, 0.275, 0.075, 0.075], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(alpha_particle)
    new_ax.axis("off")

    axis.annotate(
        "",
        xy=(rmajor + rminor, -rminor * kappa * 0.55),  # Pointing at the plasma
        xytext=(rmajor + 0.2 * rminor, -rminor * kappa * 0.25),
        arrowprops={"facecolor": "red", "edgecolor": "grey", "lw": 1},
    )

    textstr_alpha = (
        f"$P_{{\\alpha,\\text{{loss}}}}$ {mfile.get('p_fw_alpha_mw', scan=scan):.2f} MW \n"
        f"$f_{{\\alpha,\\text{{coupled}}}}$ {mfile.get('f_p_alpha_plasma_deposited', scan=scan):.2f}"
    )

    axis.text(
        1.0,
        0.275,
        textstr_alpha,
        fontsize=9,
        verticalalignment="top",
        transform=axis.transAxes,
        bbox={"boxstyle": "round", "facecolor": "red", "alpha": 1.0, "linewidth": 2},
    )

    # =========================================
    with resources.path("process.core.io", "neutron.png") as neutron_image_path:
        neutron = mpimg.imread(neutron_image_path.open("rb"))
    new_ax = axis.inset_axes(
        [0.975, 0.75, 0.075, 0.075], transform=axis.transAxes, zorder=10
    )
    new_ax.imshow(neutron)
    new_ax.axis("off")

    # Draw a red arrow coming from the right and pointing at the plasma
    axis.annotate(
        "",
        xy=(rmajor + rminor, rminor * kappa * 0.65),  # Pointing at the plasma
        xytext=(rmajor, rminor * kappa * 0.5),
        arrowprops={"facecolor": "grey", "edgecolor": "grey", "lw": 1},
    )

    textstr_neutron = (
        f"$P_{{\\text{{n,total}}}}$ {mfile.get('p_neutron_total_mw', scan=scan):.2f} MW \n"
        f"$\\phi_{{\\text{{n,avg}}}}$ {mfile.get('plfux_plasma_surface_neutron_avg_mw', scan=scan):.3f} MW/m²"
    )

    axis.text(
        0.775,
        0.875,
        textstr_neutron,
        fontsize=9,
        verticalalignment="top",
        transform=axis.transAxes,
        bbox={"boxstyle": "round", "facecolor": "grey", "alpha": 0.8, "linewidth": 2},
    )

    # ===============================================

    # Add fusion reaction information
    textstr_reactions = (
        f"$\\mathbf{{Fusion \\ Reactions:}}$\n \n"
        f"Fuel mixture: \n"
        f"|  D: {mfile.get('f_plasma_fuel_deuterium', scan=scan):.2f}  |  T: {mfile.get('f_plasma_fuel_tritium', scan=scan):.2f}  |  3He: {mfile.get('f_plasma_fuel_helium3', scan=scan):.2f}  |\n\n"
        f"Fusion Power, $P_{{\\text{{fus}}}}:$ {mfile.get('p_fusion_total_mw', scan=scan):,.2f} MW\n"
        f"D-T Power, $P_{{\\text{{fus,DT}}}}:$ {mfile.get('p_dt_total_mw', scan=scan):,.2f} MW\n"
        f"D-D Power, $P_{{\\text{{fus,DD}}}}:$ {mfile.get('p_dd_total_mw', scan=scan):,.2f} MW\n"
        f"D-3He Power, $P_{{\\text{{fus,D3He}}}}:$ {mfile.get('p_dhe3_total_mw', scan=scan):,.2f} MW\n"
        f"Alpha Power, $P_{{\\alpha}}:$ {mfile.get('p_alpha_total_mw', scan=scan):,.2f} MW"
    )

    axis.text(
        0.025,
        0.4,
        textstr_reactions,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "red", "alpha": 0.6, "linewidth": 2},
    )

    # ================================================

    # Add fuelling information
    textstr_fuelling = (
        f"$\\mathbf{{Fuelling:}}$\n \n"
        f"Plasma mass: {mfile.get('m_plasma', scan=scan) * 1000:.4f} g\n"
        f"   - Average mass of all plasma ions: {mfile.get('m_ions_total_amu', scan=scan):.3f} amu\n"
        f"Fuel mass: {mfile.get('m_plasma_fuel_ions', scan=scan) * 1000:.4f} g\n"
        f"   - Average mass of all fuel ions: {mfile.get('m_fuel_amu', scan=scan):.3f} amu\n\n"
        f"Fueling rate: {mfile.get('molflow_plasma_fuelling_required', scan=scan):.3e} nucleus-pairs/s\n"
        f"Fuel burn-up rate: {mfile.get('rndfuel', scan=scan):.3e} reactions/s \n"
        f"Burn-up fraction: {mfile.get('burnup', scan=scan):.4f} \n"
    )

    axis.text(
        0.025,
        0.22,
        textstr_fuelling,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "khaki",
            "alpha": 1.0,
            "linewidth": 2,
            "edgecolor": "black",
        },
    )

    # ================================================

    # Add ion density information
    textstr_ions = (
        f"             $\\mathbf{{Ion \\ to \\ electron}}$\n"
        f"             $\\mathbf{{relative \\ number}}$\n"
        f"             $\\mathbf{{densities:}}$\n \n"
        f"             Effective charge: {mfile.get('n_charge_plasma_effective_vol_avg', scan=scan):.3f}\n\n"
        f"             H:    {mfile.get('f_nd_impurity_electrons(01)', scan=scan):.4e}\n"
        f"             He:  {mfile.get('f_nd_impurity_electrons(02)', scan=scan):.4e}\n"
        f"             Be:  {mfile.get('f_nd_impurity_electrons(03)', scan=scan):.4e}\n"
        f"             C:    {mfile.get('f_nd_impurity_electrons(04)', scan=scan):.4e}\n"
        f"             N:    {mfile.get('f_nd_impurity_electrons(05)', scan=scan):.4e}\n"
        f"             O:    {mfile.get('f_nd_impurity_electrons(06)', scan=scan):.4e}\n"
        f"             Ne:  {mfile.get('f_nd_impurity_electrons(07)', scan=scan):.4e}\n"
        f"             Si:   {mfile.get('f_nd_impurity_electrons(08)', scan=scan):.4e}\n"
        f"             Ar:  {mfile.get('f_nd_impurity_electrons(09)', scan=scan):.4e}\n"
        f"             Fe:  {mfile.get('f_nd_impurity_electrons(10)', scan=scan):.4e}\n"
        f"             Ni:   {mfile.get('f_nd_impurity_electrons(11)', scan=scan):.4e}\n"
        f"             Kr:   {mfile.get('f_nd_impurity_electrons(12)', scan=scan):.4e}\n"
        f"             Xe:  {mfile.get('f_nd_impurity_electrons(13)', scan=scan):.4e}\n"
        f"             W:   {mfile.get('f_nd_impurity_electrons(14)', scan=scan):.4e}"
    )

    axis.text(
        0.805,
        0.335,
        textstr_ions,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "olivedrab",
            "alpha": 0.7,
            "linewidth": 2,
        },
    )

    # Add ion charge label
    axis.text(
        0.815,
        0.29,
        "$Z$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # ================================================

    # Add plasma current information
    textstr_currents = (
        f"          $\\mathbf{{Plasma\\ currents:}}$\n\n"
        f"          Plasma current {mfile.get('plasma_current_ma', scan=scan):.4f} MA\n"
        f"            - Bootstrap fraction {mfile.get('f_c_plasma_bootstrap', scan=scan):.4f}\n"
        f"            - Diamagnetic fraction {mfile.get('f_c_plasma_diamagnetic', scan=scan):.4f}\n"
        f"            - Pfirsch-Schlüter fraction {mfile.get('f_c_plasma_pfirsch_schluter', scan=scan):.4f}\n"
        f"            - Auxiliary fraction {mfile.get('f_c_plasma_auxiliary', scan=scan):.4f}\n"
        f"            - Inductive fraction {mfile.get('f_c_plasma_inductive', scan=scan):.4f}"
    )

    axis.text(
        0.765,
        0.975,
        textstr_currents,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#C8A2C8",  # Hex code for lilac color
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add plasma current label
    axis.text(
        0.78,
        0.925,
        "$I_{\\text{p}} $",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # Add magnetic field information
    textstr_fields = (
        f"$\\mathbf{{Magnetic\\ fields:}}$\n\n"
        f"Toroidal field at $R_0$, $B_{{T}}$: {mfile.get('b_plasma_toroidal_on_axis', scan=scan):.4f} T                  \n"
        f"  Ripple at outboard , $\\delta$: {mfile.get('ripple_b_tf_plasma_edge', scan=scan):.2f}%                  \n"
        f"Average poloidal field, $B_{{p}}$: {mfile.get('b_plasma_poloidal_average', scan=scan):.4f} T              \n"
        f"Total field, $B_{{tot}}$: {mfile.get('b_plasma_total', scan=scan):.4f} T                \n"
        f"Vertical field, $B_{{vert}}$: {mfile.get('b_plasma_vertical_required', scan=scan):.4f} T"
    )

    axis.text(
        0.55,
        0.13,
        textstr_fields,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "royalblue",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add magnetic field label
    axis.text(
        0.75,
        0.1,
        "$B$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # Add radiation information
    textstr_radiation = (
        f"           $\\mathbf{{Radiation:}}$\n\n"
        f"           Total radiation power {mfile.get('p_plasma_rad_mw', scan=scan):.4f} MW\n"
        f"           Separatrix radiation fraction {mfile.get('f_p_plasma_separatrix_rad', scan=scan):.4f}\n"
        f"           Core radiation power {mfile.get('p_plasma_inner_rad_mw', scan=scan):.4f} MW\n"
        f"              - $f_{{\\text{{core,reduce}}}}$ {mfile.get('f_p_plasma_core_rad_reduction', scan=scan):.4f}\n"
        f"           Edge radiation power {mfile.get('p_plasma_outer_rad_mw', scan=scan):.4f} MW\n"
        f"           Synchrotron radiation power {mfile.get('p_plasma_sync_mw', scan=scan):.4f} MW\n"
        f"           Synchrotron wall reflectivity {mfile.get('f_sync_reflect', scan=scan):.4f}"
    )

    axis.text(
        0.72,
        0.83,
        textstr_radiation,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lavender",
            "alpha": 1.0,
            "linewidth": 2,
            "edgecolor": "black",
        },
    )

    # Add radiation label
    axis.text(
        0.725,
        0.78,
        "$\\gamma$",
        fontsize=23,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # Add L-H threshold information
    textstr_lh = (
        f"$\\mathbf{{L-H \\ threshold:}}$\n\n"
        f"$P_{{\\text{{L-H}}}}:$ {mfile.get('p_l_h_threshold_mw', scan=scan):.4f} MW\n"
    )

    axis.text(
        0.22,
        0.4,
        textstr_lh,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "peachpuff",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add density limit information
    textstr_density_limit = (
        f"$\\mathbf{{Density \\ limit:}}$\n\n"
        f"$n_{{\\text{{e,limit}}}}: {mfile.get('nd_plasma_electrons_max', scan=scan):.3e} \\ m^{{-3}}$\n"
    )

    axis.text(
        0.22,
        0.32,
        textstr_density_limit,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "pink",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

plot_current_profiles_over_time(axis, mfile, scan)

Plots the current profiles over time for PF circuits, CS coil, and plasma.

Source code in process/core/io/plot_proc.py
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
def plot_current_profiles_over_time(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Plots the current profiles over time for PF circuits, CS coil, and plasma."""
    t_plant_pulse_coil_precharge = mfile.get("t_plant_pulse_coil_precharge", scan=scan)
    t_plant_pulse_plasma_current_ramp_up = mfile.get(
        "t_plant_pulse_plasma_current_ramp_up", scan=scan
    )
    t_plant_pulse_fusion_ramp = mfile.get("t_plant_pulse_fusion_ramp", scan=scan)
    t_plant_pulse_burn = mfile.get("t_plant_pulse_burn", scan=scan)
    t_plant_pulse_plasma_current_ramp_down = mfile.get(
        "t_plant_pulse_plasma_current_ramp_down", scan=scan
    )

    # Define a cumulative sum list for each point in the pulse
    t_steps = np.cumsum([
        0,
        t_plant_pulse_coil_precharge,
        t_plant_pulse_plasma_current_ramp_up,
        t_plant_pulse_fusion_ramp,
        t_plant_pulse_burn,
        t_plant_pulse_plasma_current_ramp_down,
    ])

    # Find the number of PF circuits, n_pf_cs_plasma_circuits includes the CS and plasma circuits
    n_pf_cs_plasma_circuits = mfile.get("n_pf_cs_plasma_circuits", scan=scan)

    # Extract PF circuit times
    # n_pf_cs_plasma_circuits contains the CS and plasma at the end so we subtract 2
    pf_circuits = {}
    for i in range(int(n_pf_cs_plasma_circuits - 2)):
        pf_circuits[f"PF Circuit {i}"] = [
            mfile.get(f"pfc{i}t{j}", scan=scan) for j in range(6)
        ]
        # Change from 0 to 1 index to align with poloidal cross-section plot numbering
        axis.plot(
            t_steps,
            pf_circuits[f"PF Circuit {i}"],
            label=f"PF Coil {i + 1}",
            linestyle="--",
        )

    # Since CS may not always be present try to retireve values
    try:
        cs_circuit = [mfile.get(f"cs_t{i}", scan=scan) for i in range(6)]
        axis.plot(t_steps, cs_circuit, label="CS Coil", linestyle="--")
    except KeyError:
        pass

    # Plasma current values
    plasmat1 = mfile.get("plasmat1", scan=scan)
    plasmat2 = mfile.get("plasmat2", scan=scan)
    plasmat3 = mfile.get("plasmat3", scan=scan)
    plasmat4 = mfile.get("plasmat4", scan=scan)
    plasmat5 = mfile.get("plasmat5", scan=scan)

    # x-coirdinates for the plasma current
    x_plasma = t_steps[1:]
    # x-coirdinates for the plasma current
    y_plasma = [plasmat1, plasmat2, plasmat3, plasmat4, plasmat5]

    # Plot the plasma current
    axis.plot(x_plasma, y_plasma, "black", linewidth=2, label="Plasma")

    # Move the x-axis to 0 on the y-axis
    axis.spines["bottom"].set_position("zero")

    # Annotate key points
    # Create a secondary x-axis for annotations
    secax = axis.secondary_xaxis("bottom")
    secax.set_xticks(t_steps)
    secax.set_xticklabels(
        [
            "Precharge",
            r"$I_{\text{P}}$ Ramp-Up",
            "Fusion Ramp",
            "Burn",
            "Ramp Down",
            "Between Pulse",
        ],
        rotation=60,
    )
    secax.tick_params(axis="x", which="major")

    # Add axis labels
    axis.set_xlabel("Time [s]", fontsize=12)
    axis.xaxis.set_label_coords(1.05, 0.5)
    axis.set_ylabel("Current [A]", fontsize=12)

    # Add a title
    axis.set_title("Current Profiles Over Time", fontsize=14)

    # Add a legend
    axis.legend()

    axis.set_yscale("symlog")

    # Add a grid for better readability
    axis.grid(True, linestyle="--", alpha=0.6)

plot_system_power_profiles_over_time(axis, mfile, scan, fig)

Plots the power profiles over time for various systems.

Source code in process/core/io/plot_proc.py
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
def plot_system_power_profiles_over_time(
    axis: plt.Axes, mfile: mf.MFile, scan: int, fig
):
    """Plots the power profiles over time for various systems."""

    t_precharge = mfile.get("t_plant_pulse_coil_precharge", scan=scan)
    t_current_ramp_up = mfile.get("t_plant_pulse_plasma_current_ramp_up", scan=scan)
    t_fusion_ramp = mfile.get("t_plant_pulse_fusion_ramp", scan=scan)
    t_burn = mfile.get("t_plant_pulse_burn", scan=scan)
    t_ramp_down = mfile.get("t_plant_pulse_plasma_current_ramp_down", scan=scan)
    t_between_pulse = mfile.get("t_plant_pulse_dwell", scan=scan)

    # Define a cumulative sum list for each point in the pulse
    t_steps = np.cumsum([
        0,
        t_precharge,
        t_current_ramp_up,
        t_fusion_ramp,
        t_burn,
        t_ramp_down,
        t_between_pulse,
    ])

    # Create empty arrays for the power at each time step for each system
    power_profiles = {
        "Fusion Power": np.zeros(len(t_steps)),
        "Plant Base Load": np.zeros(len(t_steps)),
        "Cryo Plant": np.zeros(len(t_steps)),
        "Tritium Plant": np.zeros(len(t_steps)),
        "Vacuum Pumps": np.zeros(len(t_steps)),
        "TF Coil Supplies": np.zeros(len(t_steps)),
        "PF Coil Supplies": np.zeros(len(t_steps)),
        "Coolant Pump Elec Total": np.zeros(len(t_steps)),
        "HCD Electric Total": np.zeros(len(t_steps)),
        "Gross Electric Power": np.zeros(len(t_steps)),
        "Net Electric Power": np.zeros(len(t_steps)),
    }

    # Fill power_profiles arrays using vectorized assignment
    for label, key in [
        ("Fusion Power", "p_fusion_total_profile_mw"),
        ("Gross Electric Power", "p_plant_electric_gross_profile_mw"),
        ("Net Electric Power", "p_plant_electric_net_profile_mw"),
        ("Plant Base Load", "p_plant_electric_base_total_profile_mw"),
        ("Cryo Plant", "p_cryo_plant_electric_profile_mw"),
        ("Tritium Plant", "p_tritium_plant_electric_profile_mw"),
        ("Vacuum Pumps", "vachtmw_profile_mw"),
        ("TF Coil Supplies", "p_tf_electric_supplies_profile_mw"),
        ("PF Coil Supplies", "p_pf_electric_supplies_profile_mw"),
        ("Coolant Pump Elec Total", "p_coolant_pump_elec_total_profile_mw"),
        ("HCD Electric Total", "p_hcd_electric_total_profile_mw"),
    ]:
        for time in range(len(t_steps)):
            power_profiles[label][time] = mfile.get(f"{key}{time}", scan=scan)

    # Define line styles for each system
    # All net drains (negative power flows) use the same line style: dashed
    line_styles = {
        "Fusion Power": ":",
        "Plant Base Load": "--",
        "Cryo Plant": "--",
        "Tritium Plant": "--",
        "Vacuum Pumps": "--",
        "TF Coil Supplies": "--",
        "PF Coil Supplies": "--",
        "Coolant Pump Elec Total": "--",
        "HCD Electric Total": "--",
        "Gross Electric Power": "-",
        "Net Electric Power": "-",
    }

    # Plot each system's power profile over time with different line styles
    for label, powers in power_profiles.items():
        style = line_styles.get(label, "-")
        axis.plot(t_steps, powers, label=label, linestyle=style)

    # Move the x-axis to 0 on the y-axis
    axis.spines["bottom"].set_position("zero")

    # Annotate key points
    # Create a secondary x-axis for annotations
    secax = axis.secondary_xaxis("bottom")
    secax.set_xticks(t_steps)
    secax.set_xticklabels(
        [
            "Precharge",
            r"$I_{\text{P}}$ Ramp-Up",
            "Fusion Ramp",
            "Burn",
            "Ramp Down",
            "Between Pulse",
            "Restart Pulse",
        ],
        rotation=60,
    )
    secax.tick_params(axis="x", which="major")

    # Add axis labels
    axis.set_xlabel("Time [s]", fontsize=12)
    axis.xaxis.set_label_coords(1.05, 0.5)
    axis.set_ylabel("Power [MW]", fontsize=12)

    # Add a title
    axis.set_title("System Power Over Time", fontsize=14)

    # Add a legend
    axis.legend()

    axis.set_yscale("symlog")
    # axis.set_xscale()
    axis.minorticks_on()
    axis.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)

    # Add a grid for better readability
    axis.grid(True, linestyle="--", alpha=0.6)

    # Add energy produced info
    textstr_energy = (
        f"$\\mathbf{{Energy \\ Production:}}$\n\n"
        f"Energy produced over whole pulse: {mfile.get('e_plant_net_electric_pulse_mj', scan=scan):,.4f} MJ \n"
        f"Energy produced over whole pulse: {mfile.get('e_plant_net_electric_pulse_kwh', scan=scan):,.4f} kWh \n"
    )

    axis.text(
        0.075,
        0.2,
        textstr_energy,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add energy produced info

    textstr_times = (
        f"$\\mathbf{{Pulse \\ Timings:}}$\n\n"
        f"Coil precharge, $t_{{\\text{{precharge}}}}$:        {mfile.get('t_plant_pulse_coil_precharge', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_coil_precharge', scan=scan))})\n"
        f"Current ramp up, $t_{{\\text{{current ramp}}}}$:  {mfile.get('t_plant_pulse_plasma_current_ramp_up', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_plasma_current_ramp_up', scan=scan))})\n"
        f"Fusion ramp, $t_{{\\text{{fusion ramp}}}}$:          {mfile.get('t_plant_pulse_fusion_ramp', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_fusion_ramp', scan=scan))})\n"
        f"Burn, $t_{{\\text{{burn}}}}$:                              {mfile.get('t_plant_pulse_burn', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_burn', scan=scan))})\n"
        f"Ramp down, $t_{{\\text{{ramp down}}}}$:           {mfile.get('t_plant_pulse_plasma_current_ramp_down', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_plasma_current_ramp_down', scan=scan))})\n"
        f"Between pulse, $t_{{\\text{{between pulse}}}}$:   {mfile.get('t_plant_pulse_dwell', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_dwell', scan=scan))})\n\n"
        f"Total pulse length, $t_{{\\text{{cycle}}}}$:        {mfile.get('t_plant_pulse_total', scan=scan):,.1f} s  ({secs_to_hms(mfile.get('t_plant_pulse_total', scan=scan))})\n"
    )

    axis.text(
        0.6,
        0.225,
        textstr_times,
        fontsize=9,
        verticalalignment="top",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "grey", "alpha": 1.0, "linewidth": 2},
    )

plot_cryostat(axis, mfile, scan, colour_scheme)

Function to plot cryostat in poloidal cross-section

Source code in process/core/io/plot_proc.py
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
def plot_cryostat(
    axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]
):
    """Function to plot cryostat in poloidal cross-section"""

    rects = cryostat_geometry(
        r_cryostat_inboard=mfile.get("r_cryostat_inboard", scan=scan),
        dr_cryostat=mfile.get("dr_cryostat", scan=scan),
        z_cryostat_half_inside=mfile.get("z_cryostat_half_inside", scan=scan),
    )

    for rec in rects:
        axis.add_patch(
            patches.Rectangle(
                xy=(rec.anchor_x, rec.anchor_z),
                width=rec.width,
                height=rec.height,
                facecolor=CRYOSTAT_COLOUR[colour_scheme - 1],
            )
        )

color_key(axis, mfile, scan, colour_scheme)

Function to plot the colour key

Source code in process/core/io/plot_proc.py
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
def color_key(axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]):
    """Function to plot the colour key"""

    axis.set_ylim([0, 10])
    axis.set_xlim([0, 10])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    labels = [
        ("CS coil", SOLENOID_COLOUR[colour_scheme - 1]),
        ("CS comp", CSCOMPRESSION_COLOUR[colour_scheme - 1]),
        (
            "TF coil",
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=scan) != 0
            else "#b87333",
        ),
        ("Thermal shield", THERMAL_SHIELD_COLOUR[colour_scheme - 1]),
        ("VV & shield", VESSEL_COLOUR[colour_scheme - 1]),
        ("Blanket", BLANKET_COLOUR[colour_scheme - 1]),
        ("First wall", FIRSTWALL_COLOUR[colour_scheme - 1]),
        ("Plasma", PLASMA_COLOUR[colour_scheme - 1]),
        ("PF coils", "none"),
        ("Divertor", "black"),
    ]

    if (mfile.get("i_hcd_primary", scan=scan) in [5, 8]) or (
        mfile.get("i_hcd_secondary", scan=scan) in [5, 8]
    ):
        labels.extend((
            ("NB duct shield", NBSHIELD_COLOUR[colour_scheme - 1]),
            ("Cryostat", CRYOSTAT_COLOUR[colour_scheme - 1]),
        ))
    else:
        labels.append(("Cryostat", CRYOSTAT_COLOUR[colour_scheme - 1]))

    for i, (text, color) in enumerate(labels):
        row = i // 4
        col = i % 4
        y_pos = 9 - row * 1.5
        x_pos = col * 2.5

        axis.text(x_pos, y_pos, text, ha="left", va="top", size="small")
        axis.add_patch(
            patches.Rectangle(
                [x_pos + 1.5, y_pos - 0.35],
                0.5,
                0.4,
                lw=0 if color != "none" else 1,
                facecolor=color if color != "none" else "none",
                edgecolor="black" if color == "none" else "none",
            )
        )

secs_to_hms(s)

Convert seconds to 'Hh Mm Ss' string.

Source code in process/core/io/plot_proc.py
3516
3517
3518
3519
def secs_to_hms(s):
    """Convert seconds to 'Hh Mm Ss' string."""
    s = float(s)
    return f"{int(s // 3600)}h {int((s % 3600) // 60)}m {int(s % 60)}s"

toroidal_cross_section(axis, mfile, scan, demo_ranges, colour_scheme)

Function to plot toroidal cross-section

Source code in process/core/io/plot_proc.py
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
def toroidal_cross_section(
    axis: plt.Axes,
    mfile: mf.MFile,
    scan: int,
    demo_ranges: bool,
    colour_scheme: Literal[1, 2],
):
    """Function to plot toroidal cross-section"""

    axis.set_xlabel("x / m")
    axis.set_ylabel("y / m")
    axis.set_title("Toroidal cross-section")
    axis.minorticks_on()

    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)
    r_cryostat_inboard = mfile.get("r_cryostat_inboard", scan=scan)
    dr_cryostat = mfile.get("dr_cryostat", scan=scan)
    dr_tf_outboard = mfile.get("dr_tf_outboard", scan=scan)
    n_tf_coils = mfile.get("n_tf_coils", scan=scan)
    dx_beam_shield = mfile.get("dx_beam_shield", scan=scan)
    dx_beam_duct = mfile.get("dx_beam_duct", scan=scan)
    radius_beam_tangency = mfile.get("radius_beam_tangency", scan=scan)
    arc(axis, rmajor, style="dashed")

    # Colour in the main components
    for v, colours in [
        ("dr_cs", SOLENOID_COLOUR[colour_scheme - 1]),
        ("dr_cs_precomp", CSCOMPRESSION_COLOUR[colour_scheme - 1]),
        (
            "dr_tf_inboard",
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=scan) != 0
            else "#b87333",
        ),
        ("dr_shld_thermal_inboard", THERMAL_SHIELD_COLOUR[colour_scheme - 1]),
        ("dr_vv_inboard", VESSEL_COLOUR[colour_scheme - 1]),
        ("dr_shld_inboard", VESSEL_COLOUR[colour_scheme - 1]),
        ("dr_blkt_inboard", BLANKET_COLOUR[colour_scheme - 1]),
        ("dr_fw_inboard", FIRSTWALL_COLOUR[colour_scheme - 1]),
        ("dr_fw_outboard", FIRSTWALL_COLOUR[colour_scheme - 1]),
        ("dr_blkt_outboard", BLANKET_COLOUR[colour_scheme - 1]),
        ("dr_shld_outboard", SHIELD_COLOUR[colour_scheme - 1]),
        ("dr_vv_outboard", VESSEL_COLOUR[colour_scheme - 1]),
        ("dr_shld_thermal_outboard", THERMAL_SHIELD_COLOUR[colour_scheme - 1]),
    ]:
        r2, r1 = cumulative_radial_build2(v, mfile, scan)
        arc_fill(axis, r1, r2, color=colours)

    arc_fill(
        axis, rmajor - rminor, rmajor + rminor, color=PLASMA_COLOUR[colour_scheme - 1]
    )

    arc_fill(
        axis,
        r_cryostat_inboard,
        r_cryostat_inboard + dr_cryostat,
        color=CRYOSTAT_COLOUR[colour_scheme - 1],
    )

    # Segment the TF coil inboard
    # Calculate centrelines
    n = int(n_tf_coils / 4) + 1
    spacing = 2 * np.pi / n_tf_coils
    i = np.arange(0, n)

    ang = i * spacing
    angl = ang - spacing / 2
    angu = ang + spacing / 2
    r1, _null = cumulative_radial_build2("dr_cs_tf_gap", mfile, scan)
    r2, _null = cumulative_radial_build2("dr_tf_inboard", mfile, scan)
    r4, r3 = cumulative_radial_build2("dr_tf_outboard", mfile, scan)

    # Coil width
    w = r2 * np.tan(spacing / 2)
    xi = r1 * np.cos(angl)
    yi = r1 * np.sin(angl)
    xo = r2 * np.cos(angl)
    yo = r2 * np.sin(angl)
    axis.plot((xi, xo), (yi, yo), color="black")
    xi = r1 * np.cos(angu)
    yi = r1 * np.sin(angu)
    xo = r2 * np.cos(angu)
    yo = r2 * np.sin(angu)
    axis.plot((xi, xo), (yi, yo), color="black")

    for item in i:
        # Neutral beam shielding
        TF_outboard(
            axis,
            item,
            n_tf_coils=n_tf_coils,
            r3=r3,
            r4=r4,
            w=w + dx_beam_shield,
            facecolor=NBSHIELD_COLOUR[colour_scheme - 1],
        )
        # Overlay TF coil segments
        TF_outboard(
            axis,
            item,
            n_tf_coils=n_tf_coils,
            r3=r3,
            r4=r4,
            w=w,
            facecolor=TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=scan) != 0
            else "#b87333",
        )

    i_hcd_primary = mfile.get("i_hcd_primary", scan=scan)
    if (i_hcd_primary == 5) or (i_hcd_primary == 8):
        # Neutral beam geometry
        a = w
        b = dr_tf_outboard
        c = dx_beam_duct + 2 * dx_beam_shield
        d = r3
        e = np.sqrt(a**2 + (d + b) ** 2)
        # Coordinates of the inner and outer edges of the beam at its tangency point
        rinner = radius_beam_tangency - dx_beam_duct
        router = radius_beam_tangency + dx_beam_duct
        beta = np.arccos(rinner / e)
        xinner = rinner * np.cos(beta)
        yinner = rinner * np.sin(beta)
        xouter = router * np.cos(beta)
        youter = router * np.sin(beta)
        # Corner of TF coils
        xcorner = r4
        ycorner = w + dx_beam_shield
        axis.plot(
            [xinner, xcorner], [yinner, ycorner], linestyle="dotted", color="black"
        )
        x = xcorner + c * np.cos(beta) - dx_beam_shield * np.cos(beta)
        y = ycorner + c * np.sin(beta) - dx_beam_shield * np.sin(beta)
        axis.plot([xouter, x], [youter, y], linestyle="dotted", color="black")

    # Draw dividing lines in the blanket (inboard modules, toroidal direction)
    n_blkt_inboard_modules_toroidal = mfile.get(
        "n_blkt_inboard_modules_toroidal", scan=scan
    )
    if n_blkt_inboard_modules_toroidal > 1:
        # Calculate the angular spacing for each module
        spacing = rtangle / (n_blkt_inboard_modules_toroidal / 4)
        r1, _ = cumulative_radial_build2("dr_shld_inboard", mfile, scan)
        r2, _ = cumulative_radial_build2("dr_blkt_inboard", mfile, scan)
        for i in range(1, int(n_blkt_inboard_modules_toroidal / 4)):
            ang = i * spacing
            # Draw a line from r1 to r2 at angle ang
            axis.plot(
                [r1 * np.cos(ang), r2 * np.cos(ang)],
                [r1 * np.sin(ang), r2 * np.sin(ang)],
                color="black",
                linestyle="-",
                linewidth=1.5,
                zorder=100,
            )

    # Draw dividing lines in the blanket (outboard modules, toroidal direction)
    n_blkt_outboard_modules_toroidal = mfile.get(
        "n_blkt_outboard_modules_toroidal", scan=scan
    )
    if n_blkt_outboard_modules_toroidal > 1:
        # Calculate the angular spacing for each module
        spacing = rtangle / (n_blkt_outboard_modules_toroidal / 4)
        r1, _ = cumulative_radial_build2("dr_fw_outboard", mfile, scan)
        r2, _ = cumulative_radial_build2("dr_blkt_outboard", mfile, scan)
        for i in range(1, int(n_blkt_outboard_modules_toroidal / 4)):
            ang = i * spacing
            # Draw a line from r1 to r2 at angle ang
            axis.plot(
                [r1 * np.cos(ang), r2 * np.cos(ang)],
                [r1 * np.sin(ang), r2 * np.sin(ang)],
                color="black",
                linestyle="-",
                linewidth=1.5,
                zorder=100,
            )

    # Ranges
    # ---
    # DEMO : Fixed ranges for comparison
    if demo_ranges:
        axis.set_ylim([0, 20])
        axis.set_xlim([0, 20])

    # Adapatative ranges
    else:
        axis.set_ylim([0.0, axis.get_ylim()[1]])
        axis.set_xlim([0.0, axis.get_xlim()[1]])

TF_outboard(axis, item, n_tf_coils, r3, r4, w, facecolor)

Source code in process/core/io/plot_proc.py
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
def TF_outboard(axis: plt.Axes, item, n_tf_coils, r3, r4, w, facecolor):
    spacing = 2 * np.pi / n_tf_coils
    ang = item * spacing
    dx = w * np.sin(ang)
    dy = w * np.cos(ang)
    x1 = r3 * np.cos(ang) + dx
    y1 = r3 * np.sin(ang) - dy
    x2 = r4 * np.cos(ang) + dx
    y2 = r4 * np.sin(ang) - dy
    x3 = r4 * np.cos(ang) - dx
    y3 = r4 * np.sin(ang) + dy
    x4 = r3 * np.cos(ang) - dx
    y4 = r3 * np.sin(ang) + dy
    verts = [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)]
    path = Path(verts, closed=True)
    patch = patches.PathPatch(path, facecolor=facecolor, lw=0)
    axis.add_patch(patch)

arc(axis, r, theta1=0, theta2=rtangle, style='solid')

Plots an arc.

Parameters:

Name Type Description Default
axis Axes

plot object

required
r

radius

required
theta1

starting polar angle (Default value = 0)

0
theta2

finishing polar angle (Default value = rtangle)

rtangle
axis Axes
required
style

(Default value = "solid")

'solid'
Source code in process/core/io/plot_proc.py
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
def arc(axis: plt.Axes, r, theta1=0, theta2=rtangle, style="solid"):
    """Plots an arc.

    Parameters
    ----------
    axis :
        plot object
    r :
        radius
    theta1 :
        starting polar angle (Default value = 0)
    theta2 :
        finishing polar angle (Default value = rtangle)
    axis: plt.Axes :

    style :
         (Default value = "solid")
    """
    angs = np.linspace(theta1, theta2)
    xs = r * np.cos(angs)
    ys = r * np.sin(angs)
    axis.plot(xs, ys, linestyle=style, color="black", lw=0.2)

arc_fill(axis, r1, r2, color='pink')

Fills the space between two quarter circles.

Parameters:

Name Type Description Default
axis Axes

plot object

required
r1

r2 radii to be filled

required
axis Axes
required
r2
required
color

(Default value = "pink")

'pink'
Source code in process/core/io/plot_proc.py
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
def arc_fill(axis: plt.Axes, r1, r2, color="pink"):
    """Fills the space between two quarter circles.

    Parameters
    ----------
    axis :
        plot object
    r1 :
        r2 radii to be filled
    axis: plt.Axes :

    r2 :

    color :
         (Default value = "pink")
    """
    angs = np.linspace(0, rtangle, endpoint=True)
    xs1 = r1 * np.cos(angs)
    ys1 = r1 * np.sin(angs)
    angs = np.linspace(rtangle, 0, endpoint=True)
    xs2 = r2 * np.cos(angs)
    ys2 = r2 * np.sin(angs)
    verts = list(zip(xs1, ys1, strict=False))
    verts.extend(list(zip(xs2, ys2, strict=False)))
    endpoint = [(r2, 0)]
    verts.extend(endpoint)
    path = Path(verts, closed=True)
    patch = patches.PathPatch(path, facecolor=color, lw=0)
    axis.add_patch(patch)

plot_n_profiles(prof, demo_ranges, mfile, scan)

Function to plot density profile

Parameters:

Name Type Description Default
prof

axis object to add plot to

required
demo_ranges bool
required
mfile MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
def plot_n_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int):
    """Function to plot density profile

    Parameters
    ----------
    prof :
        axis object to add plot to
    demo_ranges: bool :

    mfile: mf.MFile :

    scan: int :

    """
    nd_alphas = mfile.get("nd_plasma_alphas_vol_avg", scan=scan)
    nd_protons = mfile.get("nd_plasma_protons_vol_avg", scan=scan)
    nd_impurities = mfile.get("nd_plasma_impurities_vol_avg", scan=scan)
    nd_ions_total = mfile.get("nd_plasma_ions_total_vol_avg", scan=scan)
    nd_fuel_ions = mfile.get("nd_plasma_fuel_ions_vol_avg", scan=scan)
    alphan = mfile.get("alphan", scan=scan)
    fgwped_out = mfile.get("fgwped_out", scan=scan)
    fgwsep_out = mfile.get("fgwsep_out", scan=scan)
    nd_plasma_electrons_vol_avg = mfile.get("nd_plasma_electrons_vol_avg", scan=scan)

    nd_plasma_separatrix_electron = mfile.get("nd_plasma_separatrix_electron", scan=scan)

    prof.set_xlabel(r"$\rho \quad [r/a]$")
    prof.set_ylabel(r"$n \ [10^{19}\ \mathrm{m}^{-3}]$")
    prof.set_title("Density profile")

    i_plasma_pedestal = mfile.get("i_plasma_pedestal", scan=scan)
    nd_plasma_pedestal_electron = mfile.get("nd_plasma_pedestal_electron", scan=scan)
    ne0 = mfile.get("nd_plasma_electron_on_axis", scan=scan)
    nd_plasma_electrons_vol_avg = mfile.get("nd_plasma_electrons_vol_avg", scan=scan)
    radius_plasma_pedestal_density_norm = mfile.get(
        "radius_plasma_pedestal_density_norm", scan=scan
    )
    ne0 = mfile.get("nd_plasma_electron_on_axis", scan=scan)

    # build electron profile and species profiles (scale with electron profile shape)
    if i_plasma_pedestal == 1:
        rhocore = np.linspace(0, radius_plasma_pedestal_density_norm)
        necore = (
            nd_plasma_pedestal_electron
            + (ne0 - nd_plasma_pedestal_electron)
            * (1 - rhocore**2 / radius_plasma_pedestal_density_norm**2) ** alphan
        )

        rhosep = np.linspace(radius_plasma_pedestal_density_norm, 1)
        neesep = nd_plasma_separatrix_electron + (
            nd_plasma_pedestal_electron - nd_plasma_separatrix_electron
        ) * (1 - rhosep) / (1 - min(0.9999, radius_plasma_pedestal_density_norm))

        rho = np.append(rhocore, rhosep)
        ne = np.append(necore, neesep)

    else:
        rho1 = np.linspace(0, 0.95)
        rho2 = np.linspace(0.95, 1)
        rho = np.append(rho1, rho2)
        ne = ne0 * (1 - rho**2) ** alphan

    # species profiles scaled by their average fraction relative to electrons

    if nd_plasma_electrons_vol_avg != 0:
        fracs = (
            np.array([
                nd_fuel_ions,
                nd_alphas,
                nd_protons,
                nd_impurities,
                nd_ions_total,
                nd_plasma_electrons_vol_avg,
            ])
            / nd_plasma_electrons_vol_avg
        )
    else:
        fracs = np.zeros(5)

    # build species density profiles from electron profile and fractions
    # fracs = [fuel, alpha, protons, impurities, ions_total]
    # Create a density profile for each species by multiplying ne by each fraction in fracs
    density_profiles = np.array([ne * frac for frac in fracs])

    # convert to 1e19 m^-3 units for plotting (vectorised)
    density_profiles_plotting = density_profiles / 1e19

    prof.plot(
        rho,
        density_profiles_plotting[0],
        label=r"$n_{\text{fuel}}$",
        color="#2ca02c",
        linewidth=1.5,
    )
    prof.plot(
        rho,
        density_profiles_plotting[1],
        label=r"$n_{\alpha}$",
        color="#d62728",
        linewidth=1.5,
    )
    prof.plot(
        rho,
        density_profiles_plotting[2],
        label=r"$n_{p}$",
        color="#17becf",
        linewidth=1.5,
    )
    prof.plot(
        rho,
        density_profiles_plotting[3],
        label=r"$n_{Z}$",
        color="#9467bd",
        linewidth=1.5,
    )
    prof.plot(
        rho,
        density_profiles_plotting[4],
        label=r"$n_{i,total}$",
        color="#ff7f0e",
        linewidth=1.5,
    )
    prof.plot(
        rho, density_profiles_plotting[5], label=r"$n_{e}$", color="blue", linewidth=1.5
    )

    # make legend use multiple columns (up to 4) and place it to the right to avoid overlapping the plots
    _handles, labels = prof.get_legend_handles_labels()
    ncol = min(4, max(1, len(labels)))
    prof.legend(loc="upper center", bbox_to_anchor=(0.5, -0.1), ncol=ncol)

    # Ranges
    # ---
    # DEMO : Fixed ranges for comparison
    prof.set_xlim([0, 1])
    if demo_ranges:
        prof.set_ylim([0, 20])

    # Adapatative ranges
    else:
        prof.set_ylim([0, prof.get_ylim()[1]])

    if i_plasma_pedestal != 0:
        # Print pedestal lines
        prof.axhline(
            y=nd_plasma_pedestal_electron / 1e19,
            xmax=radius_plasma_pedestal_density_norm,
            color="r",
            linestyle="-",
            linewidth=0.4,
            alpha=0.4,
        )
        prof.vlines(
            x=radius_plasma_pedestal_density_norm,
            ymin=0.0,
            ymax=nd_plasma_pedestal_electron / 1e19,
            color="r",
            linestyle="-",
            linewidth=0.4,
            alpha=0.4,
        )
    prof.minorticks_on()

    # Add text box with density profile parameters
    textstr_density = "\n".join((
        rf"$\langle n_{{\text{{e}}}} \rangle$: {nd_plasma_electrons_vol_avg:.3e} m$^{{-3}}$",
        rf"$n_{{\text{{e,0}}}}$: {ne0:.3e} m$^{{-3}}$"
        rf"$\hspace{{4}} \alpha_{{\text{{n}}}}$: {alphan:.3f}",
        rf"$n_{{\text{{e,ped}}}}$: {nd_plasma_pedestal_electron:.3e} m$^{{-3}}$"
        r"$ \hspace{3} \frac{\langle n_i \rangle}{\langle n_e \rangle}$: "
        f"{nd_fuel_ions / nd_plasma_electrons_vol_avg:.3f}",
        rf"$f_{{\text{{GW e,ped}}}}$: {fgwped_out:.3f}"
        r"$ \hspace{7} \frac{n_{e,0}}{\langle n_e \rangle}$: "
        f"{ne0 / nd_plasma_electrons_vol_avg:.3f}",
        rf"$\rho_{{\text{{ped,n}}}}$: {radius_plasma_pedestal_density_norm:.3f}"
        r"$ \hspace{8} \frac{\overline{n_{e}}}{n_{\text{GW}}}$: "
        f"{mfile.get('nd_plasma_electron_line', scan=scan) / mfile.get('nd_plasma_electron_max_array(7)', scan=scan):.3f}",
        rf"$n_{{\text{{e,sep}}}}$: {nd_plasma_separatrix_electron:.3e} m$^{{-3}}$",
        rf"$f_{{\text{{GW e,sep}}}}$: {fgwsep_out:.3f}",
    ))

    props_density = {"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5}
    prof.text(
        0.0,
        -0.25,
        textstr_density,
        transform=prof.transAxes,
        fontsize=9,
        verticalalignment="top",
        bbox=props_density,
    )

    textstr_ions = "\n".join((
        r"$\langle n_{\text{ions-total}} \rangle $: "
        f"{mfile.get('nd_plasma_ions_total_vol_avg', scan=scan):.3e} m$^{{-3}}$",
        r"$\langle n_{\text{fuel}} \rangle $: "
        f"{mfile.get('nd_plasma_fuel_ions_vol_avg', scan=scan):.3e} m$^{{-3}}$",
        r"$\langle n_{\text{alpha}} \rangle $: "
        f"{mfile.get('nd_plasma_alphas_vol_avg', scan=scan):.3e} m$^{{-3}}$",
        r"$\langle n_{\text{impurities}} \rangle $: "
        f"{mfile.get('nd_plasma_impurities_vol_avg', scan=scan):.3e} m$^{{-3}}$",
        r"$\langle n_{\text{protons}} \rangle $:"
        f"{mfile.get('nd_plasma_protons_vol_avg', scan=scan):.3e} m$^{{-3}}$",
    ))

    prof.text(
        1.2,
        -0.725,
        textstr_ions,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=prof.transAxes,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.5,
        },
    )

    prof.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)

plot_jprofile(prof, mfile, scan)

Function to plot density profile

Parameters:

Name Type Description Default
prof

axis object to add plot to

required
mfile MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
def plot_jprofile(prof, mfile: mf.MFile, scan: int):
    """Function to plot density profile

    Parameters
    ----------
    prof :
        axis object to add plot to
    mfile: mf.MFile :

    scan: int :

    """
    alphaj = mfile.get("alphaj", scan=scan)
    j_plasma_0 = mfile.get("j_plasma_on_axis", scan=scan)

    j_plasma_bootstrap_sauter_profile = [
        mfile.get(f"j_plasma_bootstrap_sauter_profile{i}", scan=scan) / 1000.0
        for i in range(498)
    ]

    prof.set_xlabel(r"$\rho \quad [r/a]$")
    prof.set_ylabel(r"Current density $[kA/m^2]$")
    prof.set_title("$J$ profile")
    prof.minorticks_on()
    prof.set_xlim([0, 1.0])

    rho = np.linspace(0, 1)
    y2 = (j_plasma_0 * (1 - rho**2) ** alphaj) / 1e3

    prof.plot(rho, y2, color="red")

    prof.plot(
        np.linspace(0, 1, 498),
        j_plasma_bootstrap_sauter_profile,
        label="Sauter Bootstrap",
        color="green",
        linestyle="--",
    )
    prof.legend()

    textstr_j = "\n".join((
        r"$j_0$: " + f"{y2[0]:.3f} kA m$^{{-2}}$\n",
        r"$\alpha_J$: " + f"{alphaj:.3f}",
    ))

    props_j = {"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5}
    prof.text(
        1.1,
        0.75,
        textstr_j,
        transform=prof.transAxes,
        fontsize=9,
        verticalalignment="top",
        bbox=props_j,
    )

    prof.text(
        0.05,
        0.04,
        "*Current profile is assumed to be parabolic",
        fontsize=10,
        ha="left",
        transform=plt.gcf().transFigure,
    )
    prof.text(
        0.05,
        0.02,
        "*Bootstrap profile is for representation only",
        fontsize=10,
        ha="left",
        transform=plt.gcf().transFigure,
    )
    prof.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)

plot_t_profiles(prof, demo_ranges, mfile, scan)

Function to plot temperature profile

Parameters:

Name Type Description Default
prof

axis object to add plot to

required
demo_ranges bool
required
mfile MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
def plot_t_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int):
    """Function to plot temperature profile

    Parameters
    ----------
    prof :
        axis object to add plot to
    demo_ranges: bool :

    mfile: mf.MFile :

    scan: int :

    """

    prof.set_xlabel(r"$\rho \quad [r/a]$")
    prof.set_ylabel("$T$ [keV]")
    prof.set_title("Temperature profile")

    alphat = mfile.get("alphat", scan=scan)
    radius_plasma_pedestal_temp_norm = mfile.get(
        "radius_plasma_pedestal_temp_norm", scan=scan
    )

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))
    i_plasma_pedestal = mfile.get("i_plasma_pedestal", scan=scan)
    rho = np.linspace(0, 1.0, n_plasma_profile_elements)
    temp_plasma_pedestal_kev = mfile.get("temp_plasma_pedestal_kev", scan=scan)
    temp_plasma_separatrix_kev = mfile.get("temp_plasma_separatrix_kev", scan=scan)
    f_temp_plasma_ion_electron = mfile.get("f_temp_plasma_ion_electron", scan=scan)
    tbeta = mfile.get("tbeta", scan=scan)
    te0 = mfile.get("temp_plasma_electron_on_axis_kev", scan=scan)

    if i_plasma_pedestal == 1:
        rhocore = np.linspace(0.0, radius_plasma_pedestal_temp_norm)
        tcore = (
            temp_plasma_pedestal_kev
            + (te0 - temp_plasma_pedestal_kev)
            * (1 - (rhocore / radius_plasma_pedestal_temp_norm) ** tbeta) ** alphat
        )

        rhosep = np.linspace(radius_plasma_pedestal_temp_norm, 1)
        tsep = temp_plasma_separatrix_kev + (
            temp_plasma_pedestal_kev - temp_plasma_separatrix_kev
        ) * (1 - rhosep) / (1 - min(0.9999, radius_plasma_pedestal_temp_norm))

        rho = np.append(rhocore, rhosep)
        te = np.append(tcore, tsep)
    else:
        rho1 = np.linspace(0, 0.95)
        rho2 = np.linspace(0.95, 1)
        rho = np.append(rho1, rho2)
        te = te0 * (1 - rho**2) ** alphat
    prof.plot(rho, te, color="blue", label="$T_{e}$")
    prof.plot(rho, te[:] * f_temp_plasma_ion_electron, color="red", label="$T_{i}$")
    prof.legend()

    # Ranges
    # ---
    prof.set_xlim([0, 1])
    # DEMO : Fixed ranges for comparison
    if demo_ranges:
        prof.set_ylim([0, 50])

    # Adapatative ranges
    else:
        prof.set_ylim([0, prof.get_ylim()[1]])

    if i_plasma_pedestal != 0:
        # Plot pedestal lines
        prof.axhline(
            y=temp_plasma_pedestal_kev,
            xmax=radius_plasma_pedestal_temp_norm,
            color="r",
            linestyle="-",
            linewidth=0.4,
            alpha=0.4,
        )
        prof.vlines(
            x=radius_plasma_pedestal_temp_norm,
            ymin=0.0,
            ymax=temp_plasma_pedestal_kev,
            color="r",
            linestyle="-",
            linewidth=0.4,
            alpha=0.4,
        )
        prof.minorticks_on()

    te = mfile.get("temp_plasma_electron_vol_avg_kev", scan=scan)
    # Add text box with temperature profile parameters
    textstr_temperature = "\n".join((
        rf"$\langle T_{{\text{{e}}}} \rangle_\text{{V}}$: {mfile.get('temp_plasma_electron_vol_avg_kev', scan=scan):.3f} keV"
        rf"$\hspace{{3}} \langle T_{{\text{{e}}}} \rangle_\text{{n}}$: {mfile.get('temp_plasma_electron_density_weighted_kev', scan=scan):.3f} keV",
        rf"$T_{{\text{{e,0}}}}$: {te0:.3f} keV"
        rf"$\hspace{{4}} \alpha_{{\text{{T}}}}$: {alphat:.3f}",
        rf"$T_{{\text{{e,ped}}}}$: {temp_plasma_pedestal_kev:.3f} keV"
        r"$ \hspace{4} \frac{\langle T_i \rangle}{\langle T_e \rangle}$: "
        f"{f_temp_plasma_ion_electron:.3f}",
        rf"$\rho_{{\text{{ped,T}}}}$: {radius_plasma_pedestal_temp_norm:.3f}"
        r"$ \hspace{6} \frac{T_{e,0}}{\langle T_e \rangle}$: "
        f"{te0 / te:.3f}",
        rf"$T_{{\text{{e,sep}}}}$: {temp_plasma_separatrix_kev:.3f} keV"
        r"$ \hspace{4} \frac{{{\langle T_e \rangle_n}}}{{{\langle T_e \rangle_V}}}$: "
        f"{mfile.get('f_temp_plasma_electron_density_vol_avg', scan=scan):.3f}",
    ))

    props_temperature = {"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5}
    prof.text(
        0.0,
        -0.16,
        textstr_temperature,
        transform=prof.transAxes,
        fontsize=9,
        verticalalignment="top",
        bbox=props_temperature,
    )
    prof.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)

plot_qprofile(prof, demo_ranges, mfile, scan)

Function to plot q profile, formula taken from Nevins bootstrap model.

Parameters:

Name Type Description Default
prof

axis object to add plot to

required
demo_ranges bool
required
mfile MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
def plot_qprofile(prof, demo_ranges: bool, mfile: mf.MFile, scan: int):
    """Function to plot q profile, formula taken from Nevins bootstrap model.

    Parameters
    ----------
    prof :
        axis object to add plot to
    demo_ranges: bool :

    mfile: mf.MFile :

    scan: int :

    """
    prof.set_xlabel(r"$\rho \quad [r/a]$")
    prof.set_ylabel("$q$")
    prof.set_title("$q$ profile")
    prof.minorticks_on()

    rho = np.linspace(0, 1)
    q0 = mfile.get("q0", scan=scan)
    q95 = mfile.get("q95", scan=scan)

    q_r_nevin = q0 + (q95 - q0) * (rho + rho * rho + rho**3) / (3.0)
    q_r_sauter = q0 + (q95 - q0) * (rho * rho)

    prof.plot(rho, q_r_nevin, label="Nevins")
    prof.plot(rho, q_r_sauter, label="Sauter")
    prof.legend()

    # Ranges
    # ---
    prof.set_xlim([0, 1])
    # DEMO : Fixed ranges for comparison
    if demo_ranges:
        prof.set_ylim([0, 10])

    # Adapatative ranges
    else:
        prof.set_ylim([0, q95 * 1.2])

    prof.text(
        0.6,
        0.04,
        "*Profile is not calculated, only $q_0$ and $q_{95}$ are known.",
        fontsize=10,
        ha="left",
        transform=plt.gcf().transFigure,
    )
    prof.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)
    # ---

    textstr_q = "\n".join((
        r"$q_0$: " + f"{q0:.3f}\n",
        r"$q_{95}$: " + f"{q95:.3f}\n",
        r"$q_{\text{cyl}}$: " + f"{mfile.get('qstar', scan=scan):.3f}",
    ))

    props_q = {"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5}
    prof.text(
        -0.4,
        0.75,
        textstr_q,
        transform=prof.transAxes,
        fontsize=9,
        verticalalignment="top",
        bbox=props_q,
    )

read_imprad_data(_skiprows, data_path)

Function to read all data needed for creation of radiation profile

Parameters:

Name Type Description Default
skiprows

number of rows to skip when reading impurity data files

required
data_path

path to impurity data

required
_skiprows
required
Source code in process/core/io/plot_proc.py
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
def read_imprad_data(_skiprows, data_path):
    """Function to read all data needed for creation of radiation profile

    Parameters
    ----------
    skiprows :
        number of rows to skip when reading impurity data files
    data_path :
        path to impurity data
    _skiprows :

    """
    label = [
        "H_",
        "He",
        "Be",
        "C_",
        "N_",
        "O_",
        "Ne",
        "Si",
        "Ar",
        "Fe",
        "Ni",
        "Kr",
        "Xe",
        "W_",
    ]
    lzdata = [0.0 for x in range(len(label))]

    for i in range(len(label)):
        file_iden = data_path + label[i].ljust(3, "_")

        Te = None
        lz = None
        zav = None

        for header in read_impurity_file(file_iden + "lz_tau.dat"):
            if "Te[eV]" in header.content:
                Te = np.asarray(header.data, dtype=float)

            if "infinite confinement" in header.content:
                lz = np.asarray(header.data, dtype=float)
        for header in read_impurity_file(file_iden + "z_tau.dat"):
            if "infinite confinement" in header.content:
                zav = np.asarray(header.data, dtype=float)

        lzdata[i] = np.column_stack((Te, lz, zav))

    # then switch string to floats
    return np.array(lzdata, dtype=float)

profiles_with_pedestal(mfile, scan)

Source code in process/core/io/plot_proc.py
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
def profiles_with_pedestal(mfile, scan: int):
    alphan = mfile.get("alphan", scan=scan)
    alphat = mfile.get("alphat", scan=scan)
    nd_plasma_electron_on_axis = mfile.get("nd_plasma_electron_on_axis", scan=scan)
    temp_plasma_electron_on_axis_kev = mfile.get(
        "temp_plasma_electron_on_axis_kev", scan=scan
    )
    radius_plasma_pedestal_density_norm = mfile.get(
        "radius_plasma_pedestal_density_norm", scan=scan
    )
    radius_plasma_pedestal_temp_norm = mfile.get(
        "radius_plasma_pedestal_temp_norm", scan=scan
    )

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))
    i_plasma_pedestal = mfile.get("i_plasma_pedestal", scan=scan)
    nd_plasma_pedestal_electron = mfile.get("nd_plasma_pedestal_electron", scan=scan)
    ne0 = mfile.get("nd_plasma_electron_on_axis", scan=scan)
    radius_plasma_pedestal_density_norm = mfile.get(
        "radius_plasma_pedestal_density_norm", scan=scan
    )
    ne0 = mfile.get("nd_plasma_electron_on_axis", scan=scan)
    rho = np.linspace(0, 1.0, n_plasma_profile_elements)
    nd_plasma_separatrix_electron = mfile.get("nd_plasma_separatrix_electron", scan=scan)
    temp_plasma_pedestal_kev = mfile.get("temp_plasma_pedestal_kev", scan=scan)
    temp_plasma_separatrix_kev = mfile.get("temp_plasma_separatrix_kev", scan=scan)
    tbeta = mfile.get("tbeta", scan=scan)
    te0 = mfile.get("temp_plasma_electron_on_axis_kev", scan=scan)

    if i_plasma_pedestal == 0:
        # Intialise the radius

        # The density profile
        ne = nd_plasma_electron_on_axis * (1 - rho**2) ** alphan

        # The temperature profile
        te = temp_plasma_electron_on_axis_kev * (1 - rho**2) ** alphat

    # Profiles with pedestal
    elif i_plasma_pedestal == 1:
        # The density and temperature profile
        # Initiliase empty normalised array with zeros
        ne = np.zeros_like(rho)
        te = np.zeros_like(rho)
        # Reconstruct the temperature and density profiles with pedestal
        for q in range(rho.shape[0]):
            # Core density region
            if rho[q] <= radius_plasma_pedestal_density_norm:
                ne[q] = (
                    nd_plasma_pedestal_electron
                    + (ne0 - nd_plasma_pedestal_electron)
                    * (1 - rho[q] ** 2 / radius_plasma_pedestal_density_norm**2)
                    ** alphan
                )
            else:
                # Pedestal density region
                ne[q] = nd_plasma_separatrix_electron + (
                    nd_plasma_pedestal_electron - nd_plasma_separatrix_electron
                ) * (1 - rho[q]) / (1 - radius_plasma_pedestal_density_norm)

            # Core temperature region
            if rho[q] <= radius_plasma_pedestal_temp_norm:
                te[q] = (
                    temp_plasma_pedestal_kev
                    + (te0 - temp_plasma_pedestal_kev)
                    * (1 - (rho[q] / radius_plasma_pedestal_temp_norm) ** tbeta)
                    ** alphat
                )
            else:
                # Pedestal temperature region
                te[q] = temp_plasma_separatrix_kev + (
                    temp_plasma_pedestal_kev - temp_plasma_separatrix_kev
                ) * (1 - rho[q]) / (1 - radius_plasma_pedestal_temp_norm)

    return rho, ne, te

plot_radprofile(prof, mfile, scan, impp, demo_ranges)

Function to plot radiation profile, formula taken from ???.

Parameters:

Name Type Description Default
prof

axis object to add plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
impp

impurity path

required
mfile MFile
required
scan int
required
demo_ranges bool
required
Source code in process/core/io/plot_proc.py
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
def plot_radprofile(prof, mfile: mf.MFile, scan: int, impp, demo_ranges: bool):
    """Function to plot radiation profile, formula taken from ???.

    Parameters
    ----------
    prof :
        axis object to add plot to
    mfile :
        MFILE
    scan :
        scan number to use
    impp :
        impurity path
    mfile: mf.MFile :

    scan: int :

    demo_ranges: bool :

    """

    prof.set_xlabel(r"$\rho \quad [r/a]$")
    prof.set_ylabel(r"$P_{\mathrm{rad}}$ $[\mathrm{MW.m}^{-3}]$")
    prof.set_title("Raw Data: Line & Bremsstrahlung radiation profile")

    # read in the impurity data
    imp_data = read_imprad_data(_skiprows=2, data_path=impp)

    # find impurity densities
    imp_frac = np.array([
        mfile.get(f"f_nd_impurity_electrons({i:02d})", scan=scan) for i in range(1, 15)
    ])

    rho, ne, te = profiles_with_pedestal(mfile, scan)

    # Intailise the radiation profile arrays
    pimpden = np.zeros([imp_data.shape[0], te.shape[0]])
    lz = np.zeros([imp_data.shape[0], te.shape[0]])
    prad = np.zeros(te.shape[0])

    # Intailise the impurity radiation profile
    for k in range(te.shape[0]):
        for i in range(imp_data.shape[0]):
            if te[k] <= imp_data[i][0][0]:
                lz[i][k] = imp_data[i][0][1]
            elif te[k] >= imp_data[i][imp_data.shape[1] - 1][0]:
                lz[i][k] = imp_data[i][imp_data.shape[1] - 1][1]
            else:
                # Use np.interp for log-log interpolation
                log_te_data = np.log([row[0] for row in imp_data[i]])
                log_lz_data = np.log([row[1] for row in imp_data[i]])
                lz[i][k] = np.exp(np.interp(np.log(te[k]), log_te_data, log_lz_data))
            pimpden[i][k] = imp_frac[i] * ne[k] * ne[k] * lz[i][k]

        for l in range(imp_data.shape[0]):  # noqa: E741
            prad[k] = prad[k] + pimpden[l][k] * 1.0e-6

    prof.plot(rho, prad, label="Total", linestyle="dotted")
    prof.plot(rho, pimpden[0] * 1.0e-6, label="H")
    prof.plot(rho, pimpden[1] * 1.0e-6, label="He")
    if imp_frac[2] > 1.0e-30:
        prof.plot(rho, pimpden[2] * 1.0e-6, label="Be")
    if imp_frac[3] > 1.0e-30:
        prof.plot(rho, pimpden[3] * 1.0e-6, label="C")
    if imp_frac[4] > 1.0e-30:
        prof.plot(rho, pimpden[4] * 1.0e-6, label="N")
    if imp_frac[5] > 1.0e-30:
        prof.plot(rho, pimpden[5] * 1.0e-6, label="O")
    if imp_frac[6] > 1.0e-30:
        prof.plot(rho, pimpden[6] * 1.0e-6, label="Ne")
    if imp_frac[7] > 1.0e-30:
        prof.plot(rho, pimpden[7] * 1.0e-6, label="Si")
    if imp_frac[8] > 1.0e-30:
        prof.plot(rho, pimpden[8] * 1.0e-6, label="Ar")
    if imp_frac[9] > 1.0e-30:
        prof.plot(rho, pimpden[9] * 1.0e-6, label="Fe")
    if imp_frac[10] > 1.0e-30:
        prof.plot(rho, pimpden[10] * 1.0e-6, label="Ni")
    if imp_frac[11] > 1.0e-30:
        prof.plot(rho, pimpden[11] * 1.0e-6, label="Kr")
    if imp_frac[12] > 1.0e-30:
        prof.plot(rho, pimpden[12] * 1.0e-6, label="Xe")
    if imp_frac[13] > 1.0e-30:
        prof.plot(rho, pimpden[13] * 1.0e-6, label="W")
    prof.legend(loc="upper left", bbox_to_anchor=(-0.1, -0.1), ncol=4)
    prof.minorticks_on()
    # Plot a vertical line at the core region radius
    core_radius = mfile.get("radius_plasma_core_norm", scan=scan)

    # Plot a vertical line at the core region radius
    prof.axvline(x=core_radius, color="black", linestyle="--", linewidth=1.0, alpha=0.7)
    # Plot a box in the bottom left with f_{core,reduce}
    props_core_reduce = {"boxstyle": "round", "facecolor": "khaki", "alpha": 0.8}
    prof.text(
        0.02,
        0.02,
        rf"$f_{{\text{{core,reduce}}}}$ =  {1.0}",
        transform=prof.transAxes,
        fontsize=8,
        verticalalignment="bottom",
        bbox=props_core_reduce,
    )

    # Ranges
    # ---
    prof.set_xlim([0, 1.0])
    prof.set_yscale("log")
    prof.yaxis.grid(True, which="both", alpha=0.2)
    # DEMO : Fixed ranges for comparison
    if demo_ranges:
        prof.set_ylim([1e-6, 0.5])

    # Adapatative ranges
    else:
        prof.set_ylim([1e-6, prof.get_ylim()[1]])

plot_rad_contour(axis, mfile, scan, impp)

Plots the contour of line and bremsstrahlung radiation density for a plasma cross-section.

This function reads impurity and plasma profile data, computes the radiation density profile, interpolates it onto a 2D grid, and plots the upper and lower half contours on the provided axis.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis object to plot the contours on.

required
mfile Any

Data object containing plasma and impurity profile information.

required
scan int

The scan index to extract profile data for plotting.

required
impp str

The impurity data path

required

Returns:

Type Description
None

This function modifies the provided axis in-place and does not return any value.

Notes
  • The function assumes the existence of several global or previously defined variables and functions, such as read_imprad_data, interp1d_profile, and plasma pedestal parameters.
  • The plotted contours represent the radiation density in units of MW.m^-3.
  • The function adds colorbar, axis labels, title, and core reduction annotation to the plot.
Source code in process/core/io/plot_proc.py
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
def plot_rad_contour(axis: "mpl.axes.Axes", mfile: "Any", scan: int, impp: str):
    """Plots the contour of line and bremsstrahlung radiation density for a plasma cross-section.

    This function reads impurity and plasma profile data, computes the radiation density profile,
    interpolates it onto a 2D grid, and plots the upper and lower half contours on the provided axis.

    Parameters
    ----------
    axis : matplotlib.axes.Axes
        The matplotlib axis object to plot the contours on.
    mfile : Any
        Data object containing plasma and impurity profile information.
    scan : int
        The scan index to extract profile data for plotting.
    impp : str
        The impurity data path

    Returns
    -------
    None
        This function modifies the provided axis in-place and does not return any value.

    Notes
    -----
    - The function assumes the existence of several global or previously defined variables and functions,
        such as `read_imprad_data`, `interp1d_profile`, and plasma pedestal parameters.
    - The plotted contours represent the radiation density in units of MW.m^-3.
    - The function adds colorbar, axis labels, title, and core reduction annotation to the plot.
    """
    rminor = mfile.get("rminor", scan=scan)
    rmajor = mfile.get("rmajor", scan=scan)
    # Read in the impurity data
    imp_data = read_imprad_data(2, impp)
    # imp data is a 3D array with shape (num_impurities, num_temp_points, (temp, lz, zav))

    # Find the relative number density of each impurity
    imp_frac = np.array([
        mfile.get(f"f_nd_impurity_electrons({i:02d})", scan=scan) for i in range(1, 15)
    ])

    # Initialize the radius
    rho, ne, te = profiles_with_pedestal(mfile, scan)

    # Intailise the radiation profile arrays
    pimpden = np.zeros([imp_data.shape[0], te.shape[0]])
    lz = np.zeros([imp_data.shape[0], te.shape[0]])
    prad = np.zeros(te.shape[0])

    # Intailise the impurity radiation profile
    for rho in range(te.shape[0]):
        # imp data is a 3D array with shape (num_impurities, num_temp_points, (temp, lz, zav))
        for impurity in range(imp_data.shape[0]):
            # Check if profile temperature is lower than dataset minimum.
            # If so, use the minimum loss function value
            if te[rho] <= imp_data[impurity][0][0]:
                lz[impurity][rho] = imp_data[impurity][0][1]

            # Check if profile temperature is higher than dataset maximum.
            # If so, use the maximum loss function value
            elif te[rho] >= imp_data[impurity][imp_data.shape[1] - 1][0]:
                lz[impurity][rho] = imp_data[impurity][imp_data.shape[1] - 1][1]
            else:
                # If profile valie is within dataset range, use log-log interpolation to find value for loss function
                log_te_data = np.log([row[0] for row in imp_data[impurity]])
                log_lz_data = np.log([row[1] for row in imp_data[impurity]])
                lz[impurity][rho] = np.exp(
                    np.interp(np.log(te[rho]), log_te_data, log_lz_data)
                )
            # Find the power density for each impurity at each rho
            pimpden[impurity][rho] = (
                imp_frac[impurity] * ne[rho] * ne[rho] * lz[impurity][rho]
            )

        for impurity in range(imp_data.shape[0]):
            prad[rho] = prad[rho] + pimpden[impurity][rho] * 1.0e-6

    p_rad_grid, r_grid, z_grid = interp1d_profile(prad, mfile, scan)

    # Plot the upper half contour
    p_rad_upper = axis.contourf(
        r_grid, z_grid, p_rad_grid, levels=50, cmap="plasma", zorder=2
    )
    # Plot the lower half contour (mirror)
    axis.contourf(r_grid, -z_grid, p_rad_grid, levels=50, cmap="plasma", zorder=2)

    axis.figure.colorbar(
        p_rad_upper,
        ax=axis,
        label=r"$P_{\mathrm{rad}}$ $[\mathrm{MW.m}^{-3}]$",
        location="left",
        anchor=(-0.25, 0.5),
    )

    axis.set_xlabel("R [m]")
    axis.set_xlim(rmajor - 1.2 * rminor, rmajor + 1.2 * rminor)
    axis.set_ylim(
        -1.2 * rminor * mfile.get("kappa", scan=scan),
        1.2 * mfile.get("kappa", scan=scan) * rminor,
    )
    axis.set_ylabel("Z [m]")
    axis.set_title("Line & Bremsstrahlung Radiation Density Contours")
    axis.plot(
        rmajor,
        0,
        marker="o",
        color="red",
        markersize=6,
        markeredgecolor="black",
        zorder=100,
    )
    # enable minor ticks and grid for clearer reading
    axis.minorticks_on()
    axis.grid(True, which="major", linestyle="--", linewidth=0.8, alpha=0.7, zorder=1)

    axis.grid(True, which="minor", linestyle=":", linewidth=0.4, alpha=0.5, zorder=1)
    props_core_reduce = {"boxstyle": "round", "facecolor": "khaki", "alpha": 0.8}
    axis.text(
        0.02,
        0.02,
        rf"$f_{{\text{{core,reduce}}}}$ =  {1.0}",
        transform=axis.transAxes,
        fontsize=8,
        verticalalignment="bottom",
        bbox=props_core_reduce,
    )
    # make minor ticks visible on all sides and draw ticks inward for compact look
    axis.tick_params(which="both", direction="in", top=True, right=True)

plot_vacuum_vessel_and_divertor(axis, mfile, scan, radial_build, colour_scheme)

Function to plot vacuum vessel and divertor boxes

Parameters:

Name Type Description Default
axis

axis object to plot to

required
mfile MFile

MFILE data object

required
scan

scan number to use

required
radial_build
required
colour_scheme

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
def plot_vacuum_vessel_and_divertor(
    axis, mfile: mf.MFile, scan, radial_build, colour_scheme
):
    """Function to plot vacuum vessel and divertor boxes

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    radial_build :

    colour_scheme :
        colour scheme to use for plots
    """
    cumulative_upper = radial_build.cumulative_upper
    cumulative_lower = radial_build.cumulative_lower
    upper = radial_build.upper
    lower = radial_build.lower

    i_single_null = mfile.get("i_single_null", scan=scan)
    triang_95 = mfile.get("triang95", scan=scan)
    dz_divertor = mfile.get("dz_divertor", scan=scan)
    dz_xpoint_divertor = mfile.get("dz_xpoint_divertor", scan=scan)
    kappa = mfile.get("kappa", scan=scan)
    rminor = mfile.get("rminor", scan=scan)
    dr_vv_inboard = mfile.get("dr_vv_inboard", scan=scan)
    dr_vv_outboard = mfile.get("dr_vv_outboard", scan=scan)
    dr_shld_inboard = mfile.get("dr_shld_inboard", scan=scan)
    dr_shld_outboard = mfile.get("dr_shld_outboard", scan=scan)
    dr_blkt_inboard = mfile.get("dr_blkt_inboard", scan=scan)
    dr_blkt_outboard = mfile.get("dr_blkt_outboard", scan=scan)

    # Outer side (furthest from plasma)
    radx_outer = (
        cumulative_radial_build("dr_vv_outboard", mfile, scan)
        + cumulative_radial_build("dr_shld_vv_gap_inboard", mfile, scan)
    ) / 2.0
    rminx_outer = (
        cumulative_radial_build("dr_vv_outboard", mfile, scan)
        - cumulative_radial_build("dr_shld_vv_gap_inboard", mfile, scan)
    ) / 2.0

    # Inner side (nearest to the plasma)
    radx_inner = (
        cumulative_radial_build("dr_shld_outboard", mfile, scan)
        + cumulative_radial_build("dr_vv_inboard", mfile, scan)
    ) / 2.0
    rminx_inner = (
        cumulative_radial_build("dr_shld_outboard", mfile, scan)
        - cumulative_radial_build("dr_vv_inboard", mfile, scan)
    ) / 2.0

    z_divertor_lower_top = (-kappa * rminor) - dz_xpoint_divertor
    z_divertor_lower_bottom = z_divertor_lower_top - dz_divertor

    if i_single_null == 0:
        z_divertor_upper_bottom = (kappa * rminor) + dz_xpoint_divertor
        z_divertor_upper_top = z_divertor_upper_bottom + dz_divertor

    if i_single_null == 1:
        vvg_single_null = vacuum_vessel_geometry_single_null(
            cumulative_upper=cumulative_upper,
            upper=upper,
            triang=triang_95,
            radx_outer=radx_outer,
            rminx_outer=rminx_outer,
            radx_inner=radx_inner,
            rminx_inner=rminx_inner,
            cumulative_lower=cumulative_lower,
            lower=lower,
        )

        axis.plot(
            vvg_single_null.rs,
            vvg_single_null.zs,
            color="black",
            lw=thin,
            zorder=5,
        )

        axis.fill(
            vvg_single_null.rs,
            vvg_single_null.zs,
            color=VESSEL_COLOUR[colour_scheme - 1],
            lw=0.01,
            zorder=5,
        )

        # Find indices where vessel boundary is between z_divertor_bottom and z_divertor_top
        # Find the min and max R values of the vessel boundary between the divertor lines
        mask = (vvg_single_null.zs >= z_divertor_lower_bottom) & (
            vvg_single_null.zs <= z_divertor_lower_top
        )
        # Get the min/max R for the region between the divertor lines
        r_min = (
            np.min(vvg_single_null.rs[mask])
            + dr_vv_inboard
            + dr_shld_inboard
            + (dr_blkt_inboard * 0.5)
        )
        r_max = (
            np.max(vvg_single_null.rs[mask])
            - dr_vv_outboard
            - dr_shld_outboard
            - (dr_blkt_outboard * 0.5)
        )
        # Draw a rectangle (box) between the two lines and inside the vessel
        axis.add_patch(
            patches.Rectangle(
                (r_min, z_divertor_lower_bottom),
                r_max - r_min,
                z_divertor_lower_top - z_divertor_lower_bottom,
                facecolor="black",
                alpha=0.8,
                zorder=1,
            )
        )

    if i_single_null == 0:
        vvg_double_null = vacuum_vessel_geometry_double_null(
            cumulative_lower=cumulative_lower,
            lower=lower,
            radx_inner=radx_inner,
            radx_outer=radx_outer,
            rminx_inner=rminx_inner,
            rminx_outer=rminx_outer,
            triang=triang_95,
        )
        axis.plot(
            vvg_double_null.rs, vvg_double_null.zs, color="black", lw=thin, zorder=5
        )

        axis.fill(
            vvg_double_null.rs,
            vvg_double_null.zs,
            color=VESSEL_COLOUR[colour_scheme - 1],
            lw=0.01,
            zorder=5,
        )

        # Plot lower divertor
        # Find indices where vessel boundary is between z_divertor_bottom and z_divertor_top
        # Find the min and max R values of the vessel boundary between the divertor lines
        mask = (vvg_double_null.zs >= z_divertor_lower_bottom) & (
            vvg_double_null.zs <= z_divertor_lower_top
        )
        # Get the min/max R for the region between the divertor lines
        r_min = (
            np.min(vvg_double_null.rs[mask])
            + dr_vv_inboard
            + dr_shld_inboard
            + (dr_blkt_inboard * 0.5)
        )
        r_max = (
            np.max(vvg_double_null.rs[mask])
            - dr_vv_outboard
            - dr_shld_outboard
            - (dr_blkt_outboard * 0.5)
        )
        # Draw a rectangle (box) between the two lines and inside the vessel
        axis.add_patch(
            patches.Rectangle(
                (r_min, z_divertor_lower_bottom),
                r_max - r_min,
                z_divertor_lower_top - z_divertor_lower_bottom,
                facecolor="black",
                alpha=0.8,
                zorder=1,
            )
        )
        # Plot upper divertor
        # Find indices where vessel boundary is between z_divertor_bottom and z_divertor_top
        # Find the min and max R values of the vessel boundary between the divertor lines
        mask = (vvg_double_null.zs >= z_divertor_upper_bottom) & (
            vvg_double_null.zs <= z_divertor_upper_top
        )
        # Get the min/max R for the region between the divertor lines
        r_min = (
            np.min(vvg_double_null.rs[mask])
            + dr_vv_inboard
            + dr_shld_inboard
            + (dr_blkt_inboard * 0.5)
        )
        r_max = (
            np.max(vvg_double_null.rs[mask])
            - dr_vv_outboard
            - dr_shld_outboard
            - (dr_blkt_outboard * 0.5)
        )
        # Draw a rectangle (box) between the two lines and inside the vessel
        axis.add_patch(
            patches.Rectangle(
                (r_min, z_divertor_upper_bottom),
                r_max - r_min,
                z_divertor_upper_top - z_divertor_upper_bottom,
                facecolor="black",
                alpha=0.8,
                zorder=1,
            )
        )

plot_shield(axis, mfile, scan, radial_build, colour_scheme)

Function to plot shield

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required
radial_build
required
colour_scheme

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
def plot_shield(axis: plt.Axes, mfile: mf.MFile, scan: int, radial_build, colour_scheme):
    """Function to plot shield

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    radial_build :

    colour_scheme :
        colour scheme to use for plots

    """
    cumulative_upper = radial_build.cumulative_upper
    cumulative_lower = radial_build.cumulative_lower

    i_single_null = mfile.get("i_single_null", scan=scan)
    triang_95 = mfile.get("triang95", scan=scan)

    # Side furthest from plasma
    radx_far = (
        cumulative_radial_build("dr_shld_outboard", mfile, scan)
        + cumulative_radial_build("dr_vv_inboard", mfile, scan)
    ) / 2.0
    rminx_far = (
        cumulative_radial_build("dr_shld_outboard", mfile, scan)
        - cumulative_radial_build("dr_vv_inboard", mfile, scan)
    ) / 2.0

    # Side nearest to the plasma
    radx_near = (
        cumulative_radial_build("vvblgapo", mfile, scan)
        + cumulative_radial_build("dr_shld_inboard", mfile, scan)
    ) / 2.0
    rminx_near = (
        cumulative_radial_build("vvblgapo", mfile, scan)
        - cumulative_radial_build("dr_shld_inboard", mfile, scan)
    ) / 2.0

    if i_single_null == 1:
        shield_geometry = shield_geometry_single_null(
            cumulative_upper=cumulative_upper,
            radx_far=radx_far,
            rminx_far=rminx_far,
            radx_near=radx_near,
            rminx_near=rminx_near,
            triang=triang_95,
            cumulative_lower=cumulative_lower,
        )
    else:
        shield_geometry = shield_geometry_double_null(
            cumulative_lower=cumulative_lower,
            radx_far=radx_far,
            radx_near=radx_near,
            rminx_far=rminx_far,
            rminx_near=rminx_near,
            triang=triang_95,
        )

    axis.plot(shield_geometry.rs, shield_geometry.zs, color="black", lw=thin)
    axis.fill(
        shield_geometry.rs,
        shield_geometry.zs,
        color=SHIELD_COLOUR[colour_scheme - 1],
        lw=0.01,
    )

plot_blanket(axis, mfile, scan, radial_build, colour_scheme)

Function to plot blanket

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan

scan number to use

required
radial_build
required
colour_scheme

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
def plot_blanket(axis: plt.Axes, mfile: mf.MFile, scan, radial_build, colour_scheme):
    """Function to plot blanket

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    radial_build :

    colour_scheme :
        colour scheme to use for plots
    """
    cumulative_upper = radial_build.cumulative_upper
    cumulative_lower = radial_build.cumulative_lower

    dr_blkt_inboard = mfile.get("dr_blkt_inboard", scan=scan)
    dr_blkt_outboard = mfile.get("dr_blkt_outboard", scan=scan)
    # Single null: Draw top half from output
    # Double null: Reflect bottom half to top
    i_single_null = mfile.get("i_single_null", scan=scan)
    triang_95 = mfile.get("triang95", scan=scan)
    if int(i_single_null) == 1:
        dz_blkt_upper = mfile.get("dz_blkt_upper", scan=scan)
    else:
        dz_blkt_upper = 0.0

    c_shldith = cumulative_radial_build("dr_shld_inboard", mfile, scan)
    c_blnkoth = cumulative_radial_build("dr_blkt_outboard", mfile, scan)

    if i_single_null == 1:
        # Upper blanket: outer surface
        radx_outer = (
            cumulative_radial_build("dr_blkt_outboard", mfile, scan)
            + cumulative_radial_build("vvblgapi", mfile, scan)
        ) / 2.0
        rminx_outer = (
            cumulative_radial_build("dr_blkt_outboard", mfile, scan)
            - cumulative_radial_build("vvblgapi", mfile, scan)
        ) / 2.0

        # Upper blanket: inner surface
        radx_inner = (
            cumulative_radial_build("dr_fw_outboard", mfile, scan)
            + cumulative_radial_build("dr_blkt_inboard", mfile, scan)
        ) / 2.0
        rminx_inner = (
            cumulative_radial_build("dr_fw_outboard", mfile, scan)
            - cumulative_radial_build("dr_blkt_inboard", mfile, scan)
        ) / 2.0
        bg_single_null = blanket_geometry_single_null(
            radx_outer=radx_outer,
            rminx_outer=rminx_outer,
            radx_inner=radx_inner,
            rminx_inner=rminx_inner,
            cumulative_upper=cumulative_upper,
            triang=triang_95,
            cumulative_lower=cumulative_lower,
            dz_blkt_upper=dz_blkt_upper,
            c_shldith=c_shldith,
            c_blnkoth=c_blnkoth,
            dr_blkt_inboard=dr_blkt_inboard,
            dr_blkt_outboard=dr_blkt_outboard,
        )

        # Plot blanket
        axis.plot(
            bg_single_null.rs,
            bg_single_null.zs,
            color="black",
            lw=thin,
            zorder=5,
        )

        axis.fill(
            bg_single_null.rs,
            bg_single_null.zs,
            color=BLANKET_COLOUR[colour_scheme - 1],
            lw=0.01,
            zorder=5,
        )

    if i_single_null == 0:
        bg_double_null = blanket_geometry_double_null(
            cumulative_lower=cumulative_lower,
            triang=triang_95,
            dz_blkt_upper=dz_blkt_upper,
            c_shldith=c_shldith,
            c_blnkoth=c_blnkoth,
            dr_blkt_inboard=dr_blkt_inboard,
            dr_blkt_outboard=dr_blkt_outboard,
        )
        # Plot blanket
        axis.plot(bg_double_null.rs[0], bg_double_null.zs[0], color="black", lw=thin)
        axis.fill(
            bg_double_null.rs[0],
            bg_double_null.zs[0],
            color=BLANKET_COLOUR[colour_scheme - 1],
            lw=0.01,
            zorder=5,
        )
        if dr_blkt_inboard > 0.0:
            # only plot inboard blanket if inboard blanket thickness > 0
            axis.plot(
                bg_double_null.rs[1],
                bg_double_null.zs[1],
                color="black",
                lw=thin,
                zorder=5,
            )
            axis.fill(
                bg_double_null.rs[1],
                bg_double_null.zs[1],
                color=BLANKET_COLOUR[colour_scheme - 1],
                lw=0.01,
                zorder=5,
            )

plot_first_wall_top_down_cross_section(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
def plot_first_wall_top_down_cross_section(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Import required variables
    radius_fw_channel = mfile.get("radius_fw_channel", scan=scan) * 100
    dr_fw_wall = mfile.get("dr_fw_wall", scan=scan) * 100
    dx_fw_module = mfile.get("dx_fw_module", scan=scan) * 100

    # Flot first module
    axis.add_patch(
        patches.Rectangle(
            xy=(0, 0),
            width=dx_fw_module,
            height=2 * (dr_fw_wall + radius_fw_channel),
            edgecolor="black",
            facecolor="gray",
        )
    )

    # Plot cooling channel in first module
    axis.add_patch(
        patches.Circle(
            xy=(dx_fw_module / 2, dr_fw_wall + radius_fw_channel),
            radius=radius_fw_channel,
            edgecolor="black",
            facecolor="#b87333",
        )
    )

    # Plot second module
    axis.add_patch(
        patches.Rectangle(
            xy=(dx_fw_module, 0),
            width=dx_fw_module,
            height=2 * (dr_fw_wall + radius_fw_channel),
            edgecolor="black",
            facecolor="gray",
        )
    )

    # Plot cooling channel in second module
    axis.add_patch(
        patches.Circle(
            xy=(dx_fw_module + dx_fw_module / 2, dr_fw_wall + radius_fw_channel),
            radius=radius_fw_channel,
            edgecolor="black",
            facecolor="#b87333",
        )
    )

    # Draw radius line in the second circle
    axis.plot(
        [
            dx_fw_module + dx_fw_module / 2,
            dx_fw_module + dx_fw_module / 2 + radius_fw_channel * np.cos(np.pi / 4),
        ],
        [
            dr_fw_wall + radius_fw_channel,
            dr_fw_wall + radius_fw_channel + radius_fw_channel * np.sin(np.pi / 4),
        ],
        color="black",
        linestyle="--",
        label=f"$r_{{channel}}$ = {radius_fw_channel:.3f} cm",
    )

    # Draw width line below the second module
    axis.plot(
        [0, 0],
        [0, 0],
        color="black",
        label=f"$w_{{module}}$ = {dx_fw_module:.3f} cm",
    )
    axis.annotate(
        "",
        xy=(dx_fw_module, -0.2),
        xytext=(2 * dx_fw_module, -0.2),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Draw dotted line above the channel
    axis.plot(
        [dx_fw_module * 1.5, dx_fw_module * 1.5],
        [2 * radius_fw_channel + dr_fw_wall, 2 * (radius_fw_channel + dr_fw_wall)],
        color="black",
        linestyle="dotted",
        label=rf"$\Delta r_{{wall}}$ = {dr_fw_wall:.3f} cm",
    )

    # Draw dotted line below the channel
    axis.plot(
        [dx_fw_module * 1.5, dx_fw_module * 1.5],
        [0, dr_fw_wall],
        color="black",
        linestyle="dotted",
    )
    # Plot a dot in the center of the second channel
    axis.plot(
        dx_fw_module + dx_fw_module / 2,
        dr_fw_wall + radius_fw_channel,
        marker="o",
        color="black",
    )

    # Add the legend to the plot
    axis.legend()
    axis.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)
    axis.set_xlabel("X [cm]")
    axis.set_ylabel("R [cm]")
    axis.set_title("First Wall Top-Down Cross Section")
    axis.set_xlim([-1, 2 * dx_fw_module + 1])
    axis.set_ylim([-1, 2 * (dr_fw_wall + radius_fw_channel) + 1])

plot_first_wall_poloidal_cross_section(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
def plot_first_wall_poloidal_cross_section(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Import required variables
    radius_fw_channel = mfile.get("radius_fw_channel", scan=scan)
    dr_fw_wall = mfile.get("dr_fw_wall", scan=scan)
    dx_fw_module = mfile.get("dx_fw_module", scan=scan)
    len_fw_channel = mfile.get("len_fw_channel", scan=scan)
    temp_fw_coolant_in = mfile.get("temp_fw_coolant_in", scan=scan)
    temp_fw_coolant_out = mfile.get("temp_fw_coolant_out", scan=scan)
    i_fw_coolant_type = mfile.get("i_fw_coolant_type", scan=scan)
    temp_fw_peak = mfile.get("temp_fw_peak", scan=scan)
    pres_fw_coolant = mfile.get("pres_fw_coolant", scan=scan)
    n_fw_outboard_channels = mfile.get("n_fw_outboard_channels", scan=scan)
    n_fw_inboard_channels = mfile.get("n_fw_inboard_channels", scan=scan)

    # Plot first wall structure facing plasma
    axis.add_patch(
        patches.Rectangle(
            xy=(0, 0),
            width=dr_fw_wall,
            height=len_fw_channel,
            edgecolor="black",
            facecolor="gray",
        )
    )

    # Plot the cooling channel
    axis.add_patch(
        patches.Rectangle(
            xy=(dr_fw_wall, 0),
            width=2 * radius_fw_channel,
            height=len_fw_channel,
            edgecolor="black",
            facecolor="#b87333",  # Copper color
        )
    )

    # Plot the back wall of the first wall
    axis.add_patch(
        patches.Rectangle(
            xy=(dr_fw_wall + 2 * radius_fw_channel, 0),
            width=dr_fw_wall,
            height=len_fw_channel,
            edgecolor="black",
            facecolor="grey",
        )
    )

    # Draw an upward pointing arrow
    axis.arrow(
        dx_fw_module + 0.5 * dr_fw_wall,
        dr_fw_wall + radius_fw_channel,
        0,
        len_fw_channel / 6,
        head_width=dr_fw_wall,
        head_length=len_fw_channel / 20,
        fc="black",
        ec="black",
    )

    # Add the inlet temperature beside the arrow
    axis.text(
        dx_fw_module + 2 * dr_fw_wall,
        dr_fw_wall + radius_fw_channel + len_fw_channel / 6,
        f"$T_{{inlet}} = ${temp_fw_coolant_in:.2f} K",
        ha="left",
        va="bottom",
        fontsize=10,
        color="black",
    )

    # Draw a right pointing arrow
    axis.arrow(
        dx_fw_module + 0.5 * dr_fw_wall,
        len_fw_channel,
        2 * dr_fw_wall,
        0,
        head_width=len_fw_channel / 30,
        head_length=dr_fw_wall,
        fc="black",
        ec="black",
        linewidth=5,  # Thicker stem
    )

    # Add the outlet temperature beside the arrow
    axis.text(
        dx_fw_module + 0.5 * dr_fw_wall,
        len_fw_channel * 0.9,
        f"$T_{{outlet}} = ${temp_fw_coolant_out:.2f} K",
        ha="left",
        va="bottom",
        fontsize=10,
        color="black",
    )

    textstr_fw = "\n".join((
        rf"Coolant type: {i_fw_coolant_type}",
        rf"$T_{{FW,peak}}$: {temp_fw_peak:,.3f} K",
        rf"$P_{{FW}}$: {pres_fw_coolant / 1e3:,.3f} kPa",
        rf"$P_{{FW}}$: {pres_fw_coolant / 1e5:,.3f} bar",
        rf"$N_{{outboard}}$: {n_fw_outboard_channels}",
        rf"$N_{{inboard}}$: {n_fw_inboard_channels}",
    ))

    props_fw = {"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5}
    axis.text(
        -0.5,
        0.05,
        textstr_fw,
        transform=axis.transAxes,
        fontsize=11,
        verticalalignment="bottom",
        bbox=props_fw,
    )

    axis.set_xlabel("R [m]")
    axis.set_ylabel("Z [m]")
    axis.set_title("First Wall Poloidal Cross Section")
    axis.set_xlim([-0.01, (dx_fw_module + radius_fw_channel * 2) + 0.01])
    axis.set_ylim([-0.2, len_fw_channel + 0.2])

plot_firstwall(axis, mfile, scan, radial_build, colour_scheme)

Function to plot first wall

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
radial_build
required
colour_scheme

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
def plot_firstwall(
    axis: plt.Axes, mfile: mf.MFile, scan: int, radial_build, colour_scheme
):
    """Function to plot first wall

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    radial_build :

    colour_scheme :
        colour scheme to use for plots
    """
    cumulative_upper = radial_build.cumulative_upper
    cumulative_lower = radial_build.cumulative_lower

    i_single_null = mfile.get("i_single_null", scan=scan)
    triang_95 = mfile.get("triang95", scan=scan)
    if int(i_single_null) == 1:
        dz_blkt_upper = mfile.get("dz_blkt_upper", scan=scan)
        tfwvt = mfile.get("dz_fw_upper", scan=scan)
    else:
        dz_blkt_upper = tfwvt = 0.0

    c_blnkith = cumulative_radial_build("dr_blkt_inboard", mfile, scan)
    c_fwoth = cumulative_radial_build("dr_fw_outboard", mfile, scan)

    dr_fw_inboard = mfile.get("dr_fw_inboard", scan=scan)
    dr_fw_outboard = mfile.get("dr_fw_outboard", scan=scan)
    if i_single_null == 1:
        # Upper first wall: outer surface
        radx_outer = (
            cumulative_radial_build("dr_fw_outboard", mfile, scan)
            + cumulative_radial_build("dr_blkt_inboard", mfile, scan)
        ) / 2.0
        rminx_outer = (
            cumulative_radial_build("dr_fw_outboard", mfile, scan)
            - cumulative_radial_build("dr_blkt_inboard", mfile, scan)
        ) / 2.0

        # Upper first wall: inner surface
        radx_inner = (
            cumulative_radial_build("dr_fw_plasma_gap_outboard", mfile, scan)
            + cumulative_radial_build("dr_fw_inboard", mfile, scan)
        ) / 2.0
        rminx_inner = (
            cumulative_radial_build("dr_fw_plasma_gap_outboard", mfile, scan)
            - cumulative_radial_build("dr_fw_inboard", mfile, scan)
        ) / 2.0

        fwg_single_null = first_wall_geometry_single_null(
            radx_outer=radx_outer,
            rminx_outer=rminx_outer,
            radx_inner=radx_inner,
            rminx_inner=rminx_inner,
            cumulative_upper=cumulative_upper,
            triang=triang_95,
            cumulative_lower=cumulative_lower,
            dz_blkt_upper=dz_blkt_upper,
            c_blnkith=c_blnkith,
            c_fwoth=c_fwoth,
            dr_fw_inboard=dr_fw_inboard,
            dr_fw_outboard=dr_fw_outboard,
            tfwvt=tfwvt,
        )

        # Plot first wall
        axis.plot(fwg_single_null.rs, fwg_single_null.zs, color="black", lw=thin)
        axis.fill(
            fwg_single_null.rs,
            fwg_single_null.zs,
            color=FIRSTWALL_COLOUR[colour_scheme - 1],
            lw=0.01,
        )

    if i_single_null == 0:
        fwg_double_null = first_wall_geometry_double_null(
            cumulative_lower=cumulative_lower,
            triang=triang_95,
            dz_blkt_upper=dz_blkt_upper,
            c_blnkith=c_blnkith,
            c_fwoth=c_fwoth,
            dr_fw_inboard=dr_fw_inboard,
            dr_fw_outboard=dr_fw_outboard,
            tfwvt=tfwvt,
        )
        # Plot first wall
        axis.plot(fwg_double_null.rs[0], fwg_double_null.zs[0], color="black", lw=thin)
        axis.plot(fwg_double_null.rs[1], fwg_double_null.zs[1], color="black", lw=thin)
        axis.fill(
            fwg_double_null.rs[0],
            fwg_double_null.zs[0],
            color=FIRSTWALL_COLOUR[colour_scheme - 1],
            lw=0.01,
        )
        axis.fill(
            fwg_double_null.rs[1],
            fwg_double_null.zs[1],
            color=FIRSTWALL_COLOUR[colour_scheme - 1],
            lw=0.01,
        )

plot_tf_coils(axis, mfile, scan, colour_scheme)

Function to plot TF coils

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
colour_scheme Literal[1, 2]

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
def plot_tf_coils(
    axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]
):
    """Function to plot TF coils

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    colour_scheme :
        colour scheme to use for plots
    """

    # Arc points
    # MDK Only 4 points now required for elliptical arcs
    x1 = mfile.get("r_tf_arc(1)", scan=scan)
    y1 = mfile.get("z_tf_arc(1)", scan=scan)
    x2 = mfile.get("r_tf_arc(2)", scan=scan)
    y2 = mfile.get("z_tf_arc(2)", scan=scan)
    x3 = mfile.get("r_tf_arc(3)", scan=scan)
    y3 = mfile.get("z_tf_arc(3)", scan=scan)
    x4 = mfile.get("r_tf_arc(4)", scan=scan)
    y4 = mfile.get("z_tf_arc(4)", scan=scan)
    x5 = mfile.get("r_tf_arc(5)", scan=scan)
    y5 = mfile.get("z_tf_arc(5)", scan=scan)

    dr_tf_inboard = mfile.get("dr_tf_inboard", scan=scan)
    dr_tf_outboard = mfile.get("dr_tf_outboard", scan=scan)
    dr_shld_thermal_inboard = mfile.get("dr_shld_thermal_inboard", scan=scan)
    dr_shld_thermal_outboard = mfile.get("dr_shld_thermal_outboard", scan=scan)
    dr_tf_shld_gap = mfile.get("dr_tf_shld_gap", scan=scan)
    if y3 != 0:
        print("TF coil geometry: The value of z_tf_arc(3) is not zero, but should be.")

    if dr_shld_thermal_inboard != dr_shld_thermal_outboard:
        print(
            "dr_shld_thermal_inboard and dr_shld_thermal_outboard are different. Using dr_shld_thermal_inboard"
            "for the poloidal plot of the thermal shield."
        )

    for offset, colour in (
        (
            dr_shld_thermal_inboard + dr_tf_shld_gap,
            THERMAL_SHIELD_COLOUR[colour_scheme - 1],
        ),
        (dr_tf_shld_gap, "white"),
        (
            0.0,
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=scan) != 0
            else "#b87333",
        ),
    ):
        # Check for TF coil shape
        if "i_tf_shape" in mfile.data:
            i_tf_shape = int(mfile.get("i_tf_shape", scan=scan))
        else:
            i_tf_shape = 1

        if i_tf_shape == 2:
            rects = tfcoil_geometry_rectangular_shape(
                x1=x1,
                x2=x2,
                x4=x4,
                x5=x5,
                y1=y1,
                y2=y2,
                y4=y4,
                y5=y5,
                dr_tf_inboard=dr_tf_inboard,
                dr_tf_outboard=dr_tf_outboard,
                offset_in=offset,
            )

        else:
            rects, verts = tfcoil_geometry_d_shape(
                x1=x1,
                x2=x2,
                x3=x3,
                x4=x4,
                x5=x5,
                y1=y1,
                y2=y2,
                y4=y4,
                y5=y5,
                dr_tf_inboard=dr_tf_inboard,
                rtangle=rtangle,
                rtangle2=rtangle2,
                offset_in=offset,
            )

            for vert in verts:
                path = Path(vert, closed=True)
                patch = patches.PathPatch(path, facecolor=colour, lw=0)
                axis.add_patch(patch)

        for rec in rects:
            axis.add_patch(
                patches.Rectangle(
                    xy=(rec.anchor_x, rec.anchor_z),
                    width=rec.width,
                    height=rec.height,
                    facecolor=colour,
                )
            )

plot_superconducting_tf_wp(axis, mfile, scan, fig)

Plots inboard TF coil and winding pack.

Parameters:

Name Type Description Default
axis matplotlib.axes object

Axis object to plot to.

required
mfile MFILE data object

Object containing data for the plot.

required
scan int

Scan number to use.

required
Source code in process/core/io/plot_proc.py
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
def plot_superconducting_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig):
    """Plots inboard TF coil and winding pack.

    Parameters
    ----------
    axis : matplotlib.axes object
        Axis object to plot to.
    mfile : MFILE data object
        Object containing data for the plot.
    scan : int
        Scan number to use.
    """

    # Import the TF variables
    r_tf_inboard_in = mfile.get("r_tf_inboard_in", scan=scan)
    r_tf_inboard_out = mfile.get("r_tf_inboard_out", scan=scan)
    dx_tf_wp_primary_toroidal = mfile.get("dx_tf_wp_primary_toroidal", scan=scan)
    dx_tf_side_case_peak = mfile.get("dx_tf_side_case_peak", scan=scan)
    dx_tf_wp_secondary_toroidal = mfile.get("dx_tf_wp_secondary_toroidal", scan=scan)
    dr_tf_wp_with_insulation = mfile.get("dr_tf_wp_with_insulation", scan=scan)
    r_tf_wp_inboard_inner = mfile.get("r_tf_wp_inboard_inner", scan=scan)
    dx_tf_wp_insulation = mfile.get("dx_tf_wp_insulation", scan=scan)
    n_tf_coil_turns = round(mfile.get("n_tf_coil_turns", scan=scan))
    i_tf_wp_geom = round(mfile.get("i_tf_wp_geom", scan=scan))
    i_tf_sup = round(mfile.get("i_tf_sup", scan=scan))
    i_tf_case_geom = mfile.get("i_tf_case_geom", scan=scan)
    i_tf_turns_integer = mfile.get("i_tf_turns_integer", scan=scan)
    b_tf_inboard_peak_symmetric = mfile.get("b_tf_inboard_peak_symmetric", scan=scan)
    b_tf_inboard_peak_with_ripple = mfile.get("b_tf_inboard_peak_with_ripple", scan=scan)
    f_b_tf_inboard_peak_ripple_symmetric = mfile.get(
        "f_b_tf_inboard_peak_ripple_symmetric", scan=scan
    )
    r_b_tf_inboard_peak = mfile.get("r_b_tf_inboard_peak", scan=scan)
    dx_tf_wp_insertion_gap = mfile.get("dx_tf_wp_insertion_gap", scan=scan)
    r_tf_wp_inboard_outer = mfile.get("r_tf_wp_inboard_outer", scan=scan)
    r_tf_wp_inboard_centre = mfile.get("r_tf_wp_inboard_centre", scan=scan)

    if i_tf_turns_integer == 1:
        turn_layers = mfile.get("n_tf_wp_layers", scan=scan)
        turn_pancakes = mfile.get("n_tf_wp_pancakes", scan=scan)

    # Superconducting coil check
    if i_tf_sup == 1:
        axis.add_patch(
            Circle(
                [0, 0],
                r_tf_inboard_in,
                facecolor="none",
                edgecolor="black",
                linestyle="--",
            ),
        )

        if i_tf_case_geom == 0:
            axis.add_patch(
                Circle(
                    [0, 0],
                    r_tf_inboard_out,
                    facecolor="none",
                    edgecolor="black",
                    linestyle="--",
                ),
            )

        # Equations for plotting the TF case
        rad_tf_coil_inboard_toroidal_half = mfile.get(
            "rad_tf_coil_inboard_toroidal_half", scan=scan
        )

        # X points for inboard case curve
        x11 = r_tf_inboard_in * np.cos(
            np.linspace(
                rad_tf_coil_inboard_toroidal_half,
                -rad_tf_coil_inboard_toroidal_half,
                256,
                endpoint=True,
            )
        )
        # Y points for inboard case curve
        y11 = r_tf_inboard_in * np.sin(
            np.linspace(
                rad_tf_coil_inboard_toroidal_half,
                -rad_tf_coil_inboard_toroidal_half,
                256,
                endpoint=True,
            )
        )
        # Check for plasma side case type
        if i_tf_case_geom == 0:
            # Rounded case

            # X points for outboard case curve
            x12 = r_tf_inboard_out * np.cos(
                np.linspace(
                    rad_tf_coil_inboard_toroidal_half,
                    -rad_tf_coil_inboard_toroidal_half,
                    256,
                    endpoint=True,
                )
            )

        elif i_tf_case_geom == 1:
            # Flat case

            # X points for outboard case
            x12 = np.full(256, r_tf_inboard_out)
        else:
            raise NotImplementedError("i_tf_case_geom must be 0 or 1")

        # Y points for outboard case
        y12 = r_tf_inboard_out * np.sin(
            np.linspace(
                rad_tf_coil_inboard_toroidal_half,
                -rad_tf_coil_inboard_toroidal_half,
                256,
                endpoint=True,
            )
        )

        # Cordinates of the top and bottom of case curves,
        # used to plot the lines connecting the inside and outside of the case
        y13 = [y11[0], y12[0]]
        x13 = [x11[0], x12[0]]
        y14 = [y11[-1], y12[-1]]
        x14 = [x11[-1], x12[-1]]

        # Plot the case outline
        axis.plot(x11, y11, color="black")
        axis.plot(x12, y12, color="black")
        axis.plot(x13, y13, color="black")
        axis.plot(x14, y14, color="black")

        # Fill in the case segemnts

        # Upper main
        if i_tf_case_geom == 0:
            axis.fill_between(
                [
                    (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                    (r_tf_inboard_out * np.cos(rad_tf_coil_inboard_toroidal_half)),
                ],
                y13,
                color="grey",
                alpha=0.25,
            )
            # Lower main
            axis.fill_between(
                [
                    (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                    (r_tf_inboard_out * np.cos(rad_tf_coil_inboard_toroidal_half)),
                ],
                y14,
                color="grey",
                alpha=0.25,
            )
            axis.fill_between(
                x12,
                y12,
                color="grey",
                alpha=0.25,
            )
        elif i_tf_case_geom == 1:
            axis.fill_between(
                [
                    (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                    (r_tf_inboard_out),
                ],
                y13,
                color="grey",
                alpha=0.25,
            )
            # Lower main
            axis.fill_between(
                [
                    (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                    (r_tf_inboard_out),
                ],
                y14,
                color="grey",
                alpha=0.25,
            )

        # Removes ovelapping colours on inner nose case
        axis.fill_between(
            x11,
            y11,
            color="white",
            alpha=1.0,
        )

        # Centre line for relative reference
        axis.axhline(y=0.0, color="r", linestyle="--", linewidth=0.25)

        # ================================================================

        # Plot the rectangular WP
        if i_tf_wp_geom == 0:
            if i_tf_turns_integer == 1:
                long_turns = round(turn_layers)
                short_turns = round(turn_pancakes)
            else:
                wp_side_ratio = (
                    dr_tf_wp_with_insulation
                    - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap))
                ) / (
                    dx_tf_wp_primary_toroidal
                    - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap))
                )  # row to height
                side_unit = n_tf_coil_turns / wp_side_ratio
                root_turns = round(np.sqrt(side_unit), 1)
                long_turns = round(root_turns * wp_side_ratio)
                short_turns = round(root_turns)

            # Plots the surrounding insualtion
            axis.add_patch(
                Rectangle(
                    (r_tf_wp_inboard_inner, -(0.5 * dx_tf_wp_primary_toroidal)),
                    dr_tf_wp_with_insulation,
                    dx_tf_wp_primary_toroidal,
                    color="darkgreen",
                ),
            )
            # Plots the WP inside the insulation
            axis.add_patch(
                Rectangle(
                    (
                        r_tf_wp_inboard_inner
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                        -(0.5 * dx_tf_wp_primary_toroidal)
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                    ),
                    (
                        dr_tf_wp_with_insulation
                        - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap))
                    ),
                    (
                        dx_tf_wp_primary_toroidal
                        - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap))
                    ),
                    color="blue",
                )
            )
            # Dvides the WP up into the turn segments
            for i in range(1, long_turns):
                axis.plot(
                    [
                        (
                            r_tf_wp_inboard_inner
                            + dx_tf_wp_insulation
                            + dx_tf_wp_insertion_gap
                        )
                        + i
                        * (
                            (
                                dr_tf_wp_with_insulation
                                - dx_tf_wp_insulation
                                - dx_tf_wp_insertion_gap
                            )
                            / long_turns
                        ),
                        (
                            r_tf_wp_inboard_inner
                            + dx_tf_wp_insulation
                            + dx_tf_wp_insertion_gap
                        )
                        + i
                        * (
                            (
                                dr_tf_wp_with_insulation
                                - dx_tf_wp_insulation
                                - dx_tf_wp_insertion_gap
                            )
                            / long_turns
                        ),
                    ],
                    [
                        -0.5 * dx_tf_wp_primary_toroidal
                        + (dx_tf_wp_insulation + dx_tf_wp_insertion_gap),
                        0.5 * dx_tf_wp_primary_toroidal
                        - (dx_tf_wp_insulation + dx_tf_wp_insertion_gap),
                    ],
                    color="white",
                    linewidth="0.25",
                    linestyle="dashed",
                )

            for i in range(1, short_turns):
                axis.plot(
                    [
                        (
                            r_tf_wp_inboard_inner
                            + dx_tf_wp_insulation
                            + dx_tf_wp_insertion_gap
                        ),
                        (
                            r_tf_wp_inboard_outer
                            - dx_tf_wp_insulation
                            - dx_tf_wp_insertion_gap
                        ),
                    ],
                    [
                        (
                            -0.5 * dx_tf_wp_primary_toroidal
                            + dx_tf_wp_insulation
                            + dx_tf_wp_insertion_gap
                        )
                        + (
                            i
                            * (
                                dx_tf_wp_primary_toroidal
                                - dx_tf_wp_insulation
                                - dx_tf_wp_insertion_gap
                            )
                            / short_turns
                        ),
                        (
                            -0.5 * dx_tf_wp_primary_toroidal
                            + dx_tf_wp_insulation
                            + dx_tf_wp_insertion_gap
                        )
                        + (
                            i
                            * (
                                dx_tf_wp_primary_toroidal
                                - dx_tf_wp_insulation
                                - dx_tf_wp_insertion_gap
                            )
                            / short_turns
                        ),
                    ],
                    color="white",
                    linewidth="0.25",
                    linestyle="dashed",
                )

        # ================================================================

        # Plot the double rectangle winding pack
        if i_tf_wp_geom == 1:
            # Inner WP insulation
            axis.add_patch(
                Rectangle(
                    (
                        r_tf_wp_inboard_inner,
                        -(0.5 * dx_tf_wp_secondary_toroidal),
                    ),
                    (dr_tf_wp_with_insulation / 2) + (dx_tf_wp_insulation),
                    dx_tf_wp_secondary_toroidal,
                    color="darkgreen",
                ),
            )

            # Outer WP insulation
            axis.add_patch(
                Rectangle(
                    (
                        r_tf_wp_inboard_centre,
                        -(0.5 * dx_tf_wp_primary_toroidal),
                    ),
                    (dr_tf_wp_with_insulation / 2),
                    dx_tf_wp_primary_toroidal,
                    color="darkgreen",
                ),
            )

            # Outer WP
            axis.add_patch(
                Rectangle(
                    (
                        r_tf_wp_inboard_centre
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                        -(0.5 * dx_tf_wp_primary_toroidal)
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                    ),
                    (dr_tf_wp_with_insulation / 2)
                    - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap)),
                    dx_tf_wp_primary_toroidal
                    - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap)),
                    color="blue",
                ),
            )
            # Inner WP
            axis.add_patch(
                Rectangle(
                    (
                        r_tf_wp_inboard_inner
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                        -(0.5 * dx_tf_wp_secondary_toroidal)
                        + dx_tf_wp_insulation
                        + dx_tf_wp_insertion_gap,
                    ),
                    (dr_tf_wp_with_insulation / 2),
                    dx_tf_wp_secondary_toroidal
                    - (2 * (dx_tf_wp_insulation + dx_tf_wp_insertion_gap)),
                    color="blue",
                ),
            )

        # ================================================================

        # Trapezium WP
        if i_tf_wp_geom == 2:
            # WP insulation
            x = [
                r_tf_wp_inboard_inner,
                r_tf_wp_inboard_inner,
                r_tf_wp_inboard_outer,
                r_tf_wp_inboard_outer,
            ]
            y = [
                (-0.5 * dx_tf_wp_secondary_toroidal),
                (0.5 * dx_tf_wp_secondary_toroidal),
                (0.5 * dx_tf_wp_primary_toroidal),
                (-0.5 * dx_tf_wp_primary_toroidal),
            ]
            axis.add_patch(
                patches.Polygon(
                    xy=list(zip(x, y, strict=False)),
                    color="darkgreen",
                )
            )

            # WP
            x = [
                r_tf_wp_inboard_inner + dx_tf_wp_insulation + dx_tf_wp_insertion_gap,
                r_tf_wp_inboard_inner + dx_tf_wp_insulation + dx_tf_wp_insertion_gap,
                (r_tf_wp_inboard_outer - dx_tf_wp_insulation - dx_tf_wp_insertion_gap),
                (r_tf_wp_inboard_outer - dx_tf_wp_insulation - dx_tf_wp_insertion_gap),
            ]
            y = [
                (
                    -0.5 * dx_tf_wp_secondary_toroidal
                    + dx_tf_wp_insulation
                    + dx_tf_wp_insertion_gap
                ),
                (
                    0.5 * dx_tf_wp_secondary_toroidal
                    - dx_tf_wp_insulation
                    - dx_tf_wp_insertion_gap
                ),
                (
                    0.5 * dx_tf_wp_primary_toroidal
                    - dx_tf_wp_insulation
                    - dx_tf_wp_insertion_gap
                ),
                (
                    -0.5 * dx_tf_wp_primary_toroidal
                    + dx_tf_wp_insulation
                    + dx_tf_wp_insertion_gap
                ),
            ]
            axis.add_patch(
                patches.Polygon(
                    xy=list(zip(x, y, strict=False)),
                    color="blue",
                )
            )

        # Plot a dot for the location of the peak field
        axis.plot(
            r_b_tf_inboard_peak,
            0,
            marker="o",
            color="red",
            label=(
                f"Peak axisymmetric field: {b_tf_inboard_peak_symmetric:.3f} T\n"
                f"Peak non-axisymmetric field with ripple: "
                f"{b_tf_inboard_peak_with_ripple:.3f} T\n"
                f"$\\frac{{B_{{\\text{{axisymmetric}}}}}}{{B_{{\\text{{non-axisymmetric}}}}}}$: "
                f"{f_b_tf_inboard_peak_ripple_symmetric:.3f}\n"
                f"$r_{{\\text{{peak}}}}$={r_b_tf_inboard_peak:.3f} m"
            ),
        )

        # Plot a horizontal line at y = dx_tf_wp_inner_toroidal
        axis.axhline(
            y=dx_tf_wp_secondary_toroidal / 2,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        # Plot a horizontal line at y = dx_tf_wp_inner_toroidal
        axis.axhline(
            y=-dx_tf_wp_secondary_toroidal / 2,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axhline(
            y=dx_tf_wp_primary_toroidal / 2,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axhline(
            y=-dx_tf_wp_primary_toroidal / 2,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        # Max toroidal width including side case
        axis.axhline(
            y=(dx_tf_wp_primary_toroidal / 2) + dx_tf_side_case_peak,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )

        axis.axhline(
            y=-(dx_tf_wp_primary_toroidal / 2) - dx_tf_side_case_peak,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )

        axis.axvline(
            x=r_tf_inboard_in,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axvline(
            x=r_tf_wp_inboard_inner,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axvline(
            x=r_tf_wp_inboard_outer,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axvline(
            x=r_tf_wp_inboard_centre,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )
        axis.axvline(
            x=r_tf_inboard_out,
            color="black",
            linestyle="--",
            linewidth=0.6,
            alpha=0.5,
        )

        # Add info about the steel casing surrounding the WP
        textstr_casing = (
            f"$\\mathbf{{Casing:}}$\n \n"
            f"Coil half angle: {mfile.get('rad_tf_coil_inboard_toroidal_half', scan=scan):.3f} radians\n\n"
            f"$\\text{{Full Coil Case:}}$\n"
            f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_inboard_in', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_inboard_out', scan=scan):.3f} m\n"
            f"$\\Delta r$: {mfile.get('dr_tf_inboard', scan=scan):.3f} m\n"
            f"Area of casing around WP: {mfile.get('a_tf_coil_inboard_case', scan=scan):.3f} $\\mathrm{{m}}^2$\n\n"
            f"$\\text{{Nose Case:}}$\n"
            f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_inboard_in', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_wp_inboard_inner', scan=scan):.3f} m\n"
            f"$\\Delta r$: {mfile.get('dr_tf_nose_case', scan=scan):.3f} m\n"
            f"$A$: {mfile.get('a_tf_coil_nose_case', scan=scan):.3f} $\\mathrm{{m}}^2$\n\n"
            f"$\\text{{Plasma Case:}}$\n"
            f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_wp_inboard_outer', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_inboard_out', scan=scan):.3f} m\n"
            f"$\\Delta r$: {mfile.get('dr_tf_plasma_case', scan=scan):.3f} m\n"
            f"$A$: {mfile.get('a_tf_plasma_case', scan=scan):.3f} $\\mathrm{{m}}^2$\n\n"
            f"$\\text{{Side Case:}}$\n"
            f"Minimum $\\Delta r$: {mfile.get('dx_tf_side_case_min', scan=scan):.3f} m\n"
            f"Average $\\Delta r$: {mfile.get('dx_tf_side_case_average', scan=scan):.3f} m\n"
            f"Max $\\Delta r$: {mfile.get('dx_tf_side_case_peak', scan=scan):.3f} m"
        )
        axis.text(
            0.55,
            0.975,
            textstr_casing,
            fontsize=9,
            verticalalignment="top",
            horizontalalignment="left",
            transform=fig.transFigure,
            bbox={
                "boxstyle": "round",
                "facecolor": "grey",
                "alpha": 1.0,
                "linewidth": 2,
            },
        )

        # Add info about the steel casing surrounding the WP
        textstr_wp_insulation = (
            f"$\\mathbf{{Ground \\ Insulation:}}$\n \n"
            f"Area of insulation around WP: {mfile.get('a_tf_wp_ground_insulation', scan=scan):.3f} $\\mathrm{{m}}^2$\n"
            f"$\\Delta r$: {mfile.get('dx_tf_wp_insulation', scan=scan):.4f} m\n\n"
            f"WP Insertion Gap:\n"
            f"$\\Delta r$: {mfile.get('dx_tf_wp_insertion_gap', scan=scan):.4f} m"
        )
        axis.text(
            0.55,
            0.575,
            textstr_wp_insulation,
            fontsize=9,
            verticalalignment="top",
            horizontalalignment="left",
            transform=fig.transFigure,
            bbox={
                "boxstyle": "round",
                "facecolor": "green",
                "alpha": 1.0,
                "linewidth": 2,
            },
        )

        # Add info about the Winding Pack
        textstr_wp = (
            f"$\\mathbf{{Winding \\  Pack:}}$\n \n"
            f"$N_{{\\text{{turns}}}}$: "
            f"{int(mfile.get('n_tf_coil_turns', scan=scan))} turns\n"
            f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_wp_inboard_inner', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_wp_inboard_outer', scan=scan):.3f} m\n"
            f"$\\Delta r$: {mfile.get('dr_tf_wp_with_insulation', scan=scan):.3f} m\n\n"
            f"$A$, with insulation: {mfile.get('a_tf_wp_with_insulation', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"$A$, no insulation: {mfile.get('a_tf_wp_no_insulation', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"$A$, total turn insulation: {mfile.get('a_tf_coil_wp_turn_insulation', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"$A$, total turn steel: {mfile.get('a_tf_wp_steel', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"$A$, total conductor: {mfile.get('a_tf_wp_conductor', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"$A$, total non-cooling void: {mfile.get('a_tf_wp_extra_void', scan=scan):.4f} $\\mathrm{{m}}^2$\n\n"
            f"Primary WP:\n"
            f"$\\Delta x$: {mfile.get('dx_tf_wp_primary_toroidal', scan=scan):.4f} m\n\n"
            f"Secondary WP:\n"
            f"$\\Delta x$: {mfile.get('dx_tf_wp_secondary_toroidal', scan=scan):.4f} m\n\n"
            f"$J$ no insulation: {mfile.get('j_tf_wp', scan=scan) / 1e6:.4f} MA/m$^2$"
        )

        axis.text(
            0.775,
            0.95,
            textstr_wp,
            fontsize=9,
            verticalalignment="top",
            horizontalalignment="left",
            color="white",
            transform=fig.transFigure,
            bbox={
                "boxstyle": "round",
                "facecolor": "blue",
                "alpha": 1.0,
                "linewidth": 2,
            },
        )

        # Add info about the Winding Pack
        textstr_general_info = (
            f"$\\mathbf{{General \\ info:}}$\n \n"
            f"$N_{{\\text{{TF,coil}}}}$: {mfile.get('n_tf_coils', scan=scan)}\n"
            f"Self inductance of single coil: {mfile.get('ind_tf_coil', scan=scan) * 1e6:.4f} $\\mu$H\n"
            f"Stored energy of all coils: {mfile.get('e_tf_magnetic_stored_total_gj', scan=scan):.4f} GJ\n"
            f"Stored energy of a single coil: {mfile.get('e_tf_coil_magnetic_stored', scan=scan) / 1e9:.2f} GJ\n"
            f"Total area of steel in coil: {mfile.get('a_tf_coil_inboard_steel', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
            f"Total area fraction of steel: {mfile.get('f_a_tf_coil_inboard_steel', scan=scan):.4f}\n"
            f"Total area fraction of insulation: {mfile.get('f_a_tf_coil_inboard_insulation', scan=scan):.4f}\n"
            f"$A$, all insulation in coil: {mfile.get('a_tf_coil_inboard_insulation', scan=scan):.4f} $\\mathrm{{m}}^2$\n"
        )
        axis.text(
            0.775,
            0.58,
            textstr_general_info,
            fontsize=9,
            verticalalignment="top",
            horizontalalignment="left",
            transform=fig.transFigure,
            bbox={
                "boxstyle": "round",
                "facecolor": "wheat",
                "alpha": 1.0,
                "linewidth": 2,
            },
        )

        axis.minorticks_on()
        axis.set_xlim(r_tf_inboard_in * 0.8, r_tf_inboard_out * 1.1)
        axis.set_ylim((y14[-1] * 1.25), (-y14[-1] * 1.25))

        axis.set_title("Top-down view of inboard TF coil at midplane")
        axis.set_xlabel("Radial distance [m]")
        axis.set_ylabel("Toroidal distance [m]")
        axis.legend(loc="upper left")

plot_resistive_tf_wp(axis, mfile, scan, fig)

Plots inboard TF coil and winding pack.

Parameters:

Name Type Description Default
axis matplotlib.axes object

Axis object to plot to.

required
mfile MFILE data object

Object containing data for the plot.

required
scan int

Scan number to use.

required
Source code in process/core/io/plot_proc.py
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
def plot_resistive_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig):
    """Plots inboard TF coil and winding pack.

    Parameters
    ----------
    axis : matplotlib.axes object
        Axis object to plot to.
    mfile : MFILE data object
        Object containing data for the plot.
    scan : int
        Scan number to use.
    """

    # Import the TF variables
    r_tf_inboard_in = mfile.get("r_tf_inboard_in", scan=scan)
    r_tf_inboard_out = mfile.get("r_tf_inboard_out", scan=scan)

    r_tf_wp_inboard_inner = mfile.get("r_tf_wp_inboard_inner", scan=scan)
    i_tf_case_geom = mfile.get("i_tf_case_geom", scan=scan)
    b_tf_inboard_peak_symmetric = mfile.get("b_tf_inboard_peak_symmetric", scan=scan)
    r_b_tf_inboard_peak = mfile.get("r_b_tf_inboard_peak", scan=scan)
    r_tf_wp_inboard_outer = mfile.get("r_tf_wp_inboard_outer", scan=scan)
    r_tf_wp_inboard_centre = mfile.get("r_tf_wp_inboard_centre", scan=scan)
    dx_tf_wp_insulation = mfile.get("dx_tf_wp_insulation", scan=scan)

    axis.add_patch(
        Circle(
            [0, 0],
            r_tf_inboard_in,
            facecolor="none",
            edgecolor="black",
            linestyle="--",
        ),
    )

    if i_tf_case_geom == 0:
        axis.add_patch(
            Circle(
                [0, 0],
                r_tf_inboard_out,
                facecolor="none",
                edgecolor="black",
                linestyle="--",
            ),
        )

    # Equations for plotting the TF case
    rad_tf_coil_inboard_toroidal_half = mfile.get(
        "rad_tf_coil_inboard_toroidal_half", scan=scan
    )

    # X points for inboard case curve
    x11 = r_tf_inboard_in * np.cos(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            256,
            endpoint=True,
        )
    )
    # Y points for inboard case curve
    y11 = r_tf_inboard_in * np.sin(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            256,
            endpoint=True,
        )
    )
    # Check for plasma side case type
    if i_tf_case_geom == 0:
        # Rounded case

        # X points for outboard case curve
        x12 = r_tf_inboard_out * np.cos(
            np.linspace(
                rad_tf_coil_inboard_toroidal_half,
                -rad_tf_coil_inboard_toroidal_half,
                256,
                endpoint=True,
            )
        )

    elif i_tf_case_geom == 1:
        # Flat case

        # X points for outboard case
        x12 = np.full(256, r_tf_inboard_out)
    else:
        raise NotImplementedError("i_tf_case_geom must be 0 or 1")

    # Y points for outboard case
    y12 = r_tf_inboard_out * np.sin(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            256,
            endpoint=True,
        )
    )

    # Cordinates of the top and bottom of case curves,
    # used to plot the lines connecting the inside and outside of the case
    y13 = [y11[0], y12[0]]
    x13 = [x11[0], x12[0]]
    y14 = [y11[-1], y12[-1]]
    x14 = [x11[-1], x12[-1]]

    # Plot the case outline
    axis.plot(x11, y11, color="black")
    axis.plot(x12, y12, color="black")
    axis.plot(x13, y13, color="black")
    axis.plot(x14, y14, color="black")

    # Fill in the case segemnts

    # Upper main
    if i_tf_case_geom == 0:
        axis.fill_between(
            [
                (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_inboard_out * np.cos(rad_tf_coil_inboard_toroidal_half)),
            ],
            y13,
            color="grey",
            alpha=0.25,
        )
        # Lower main
        axis.fill_between(
            [
                (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_inboard_out * np.cos(rad_tf_coil_inboard_toroidal_half)),
            ],
            y14,
            color="grey",
            alpha=0.25,
        )
        axis.fill_between(
            x12,
            y12,
            color="grey",
            alpha=0.25,
        )
    elif i_tf_case_geom == 1:
        axis.fill_between(
            [
                (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_inboard_out),
            ],
            y13,
            color="grey",
            alpha=0.25,
        )
        # Lower main
        axis.fill_between(
            [
                (r_tf_inboard_in * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_inboard_out),
            ],
            y14,
            color="grey",
            alpha=0.25,
        )

    # Removes ovelapping colours on inner nose case
    axis.fill_between(
        x11,
        y11,
        color="white",
        alpha=1.0,
    )

    # Centre line for relative reference
    axis.axhline(y=0.0, color="r", linestyle="--", linewidth=0.25)

    # ================================================================

    # Plot the WP insulation

    # X points for inboard insulation curve
    x11 = r_tf_wp_inboard_inner * np.cos(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            500,
            endpoint=True,
        )
    )
    # Y points for inboard insulation curve
    y11 = r_tf_wp_inboard_inner * np.sin(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            500,
            endpoint=True,
        )
    )

    # X points for outboard insulation curve
    x12 = r_tf_wp_inboard_outer * np.cos(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            500,
            endpoint=True,
        )
    )

    # Y points for outboard insulation curve
    y12 = r_tf_wp_inboard_outer * np.sin(
        np.linspace(
            rad_tf_coil_inboard_toroidal_half,
            -rad_tf_coil_inboard_toroidal_half,
            500,
            endpoint=True,
        )
    )

    # Cordinates of the top and bottom of WP insulation curves,
    y13 = [y11[0], y12[0]]
    x13 = [x11[0], x12[0]]
    y14 = [y11[-1], y12[-1]]
    x14 = [x11[-1], x12[-1]]

    # Plot the insualtion outline
    axis.plot(x11, y11, color="black")
    axis.plot(x12, y12, color="black")
    axis.plot(x13, y13, color="black")
    axis.plot(x14, y14, color="black")

    # Upper main
    if i_tf_case_geom == 0:
        axis.fill_between(
            [
                (r_tf_wp_inboard_inner * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_wp_inboard_outer * np.cos(rad_tf_coil_inboard_toroidal_half)),
            ],
            y13,
            color="green",
        )
        # Lower main
        axis.fill_between(
            [
                (r_tf_wp_inboard_inner * np.cos(rad_tf_coil_inboard_toroidal_half)),
                (r_tf_wp_inboard_outer * np.cos(rad_tf_coil_inboard_toroidal_half)),
            ],
            y14,
            color="green",
        )
        axis.fill_between(
            x12,
            y12,
            color="green",
        )

    # ================================================================

    # Plot the WP

    # The winding pack should be inside the insulation, so subtract dx_tf_wp_insulation from both the inner and outer radii.
    # The angular extent should also be reduced by the insulation thickness, i.e., the winding pack does not extend all the way to the top/bottom.

    # Calculate the reduced angle for the winding pack (subtract insulation thickness in arc length, convert to angle)
    # arc_length = r * angle => angle = arc_length / r
    # So, for both inner and outer radii, compute the angle offset due to insulation thickness
    angle_offset_inner = (
        dx_tf_wp_insulation / r_tf_wp_inboard_inner if r_tf_wp_inboard_inner > 0 else 0
    )
    angle_offset_outer = (
        dx_tf_wp_insulation / r_tf_wp_inboard_outer if r_tf_wp_inboard_outer > 0 else 0
    )

    # Use the maximum angle offset to ensure the winding pack stays within the insulation
    angle_offset = max(angle_offset_inner, angle_offset_outer)

    # Define the angular range for the winding pack
    theta_start = rad_tf_coil_inboard_toroidal_half - angle_offset
    theta_end = -rad_tf_coil_inboard_toroidal_half + angle_offset
    theta_vals = np.linspace(theta_start, theta_end, 256, endpoint=True)

    # X and Y points for inboard and outboard winding pack curves
    x11 = (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.cos(theta_vals)
    y11 = (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.sin(theta_vals)
    x12 = (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.cos(theta_vals)
    y12 = (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.sin(theta_vals)

    # Cordinates of the top and bottom of WP curves,
    y13 = [y11[0], y12[0]]
    x13 = [x11[0], x12[0]]
    y14 = [y11[-1], y12[-1]]
    x14 = [x11[-1], x12[-1]]

    # Plot the winding pack outline
    axis.plot(x11, y11, color="black")
    axis.plot(x12, y12, color="black")
    axis.plot(x13, y13, color="black")
    axis.plot(x14, y14, color="black")

    # Choose color based on i_tf_sup: copper for resistive, aluminium for cryo
    # light steel blue (cryo aluminium) or copper color
    wp_color = "#b0c4de" if mfile.get("i_tf_sup", scan=scan) == 2 else "#b87333"

    axis.fill_between(
        [
            (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.cos(theta_vals[0]),
            (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.cos(theta_vals[0]),
        ],
        y13,
        color=wp_color,
    )
    # Lower main
    axis.fill_between(
        [
            (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.cos(theta_vals[-1]),
            (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.cos(theta_vals[-1]),
        ],
        y14,
        color=wp_color,
    )
    axis.fill_between(x12, y12, color=wp_color)

    # ================================================================

    # Divide the winding pack into toroidal segments based on n_tf_coil_turns
    n_turns = int(mfile.get("n_tf_coil_turns", scan=scan))
    if n_turns > 0:
        # Calculate the angular extent for each turn
        theta_start = rad_tf_coil_inboard_toroidal_half - angle_offset
        theta_end = -rad_tf_coil_inboard_toroidal_half + angle_offset
        theta_vals = np.linspace(theta_start, theta_end, 256, endpoint=True)

        # For each turn, plot a radial line at the corresponding angle
        turn_angles = np.linspace(theta_start, theta_end, n_turns + 1)
        for t in range(1, n_turns):
            angle = turn_angles[t]
            # Inner and outer points for this turn
            x_in = (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.cos(angle)
            y_in = (r_tf_wp_inboard_inner + dx_tf_wp_insulation) * np.sin(angle)
            x_out = (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.cos(angle)
            y_out = (r_tf_wp_inboard_outer - dx_tf_wp_insulation) * np.sin(angle)
            axis.plot(
                [x_in, x_out],
                [y_in, y_out],
                color="white",
                linewidth=0.5,
                linestyle="--",
            )

    # ================================================================

    # Plot a dot for the location of the peak field
    axis.plot(
        r_b_tf_inboard_peak,
        0,
        marker="o",
        color="red",
        label=f"Peak Field: {b_tf_inboard_peak_symmetric:.2f} T\nr={r_b_tf_inboard_peak:.3f} m",
    )

    x_kwargs = {"color": "black", "linestyle": "--", "linewidth": 0.6, "alpha": 0.5}
    axis.axvline(x=r_tf_inboard_in, **x_kwargs)
    axis.axvline(x=r_tf_wp_inboard_inner, **x_kwargs)
    axis.axvline(x=r_tf_wp_inboard_outer, **x_kwargs)
    axis.axvline(x=r_tf_wp_inboard_centre, **x_kwargs)
    axis.axvline(x=r_tf_inboard_out, **x_kwargs)

    axis.minorticks_on()
    axis.set_xlim(0.0, r_tf_inboard_out * 1.1)
    axis.set_ylim((y14[-1] * 1.65), (-y14[-1] * 1.65))

    axis.set_title("Top-down view of inboard TF coil at midplane")
    axis.set_xlabel("Radial distance [m]")
    axis.set_ylabel("Toroidal distance [m]")
    axis.legend(loc="upper left")

    axis.text(
        0.05,
        0.975,
        "*Turn insulation and cooling pipes not shown",
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        color="black",
        transform=fig.transFigure,
    )

plot_resistive_tf_info(axis, mfile, scan, fig)

Source code in process/core/io/plot_proc.py
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
def plot_resistive_tf_info(axis: plt.Axes, mfile: mf.MFile, scan: int, fig):
    # Add info about the steel casing surrounding the WP
    textstr_casing = (
        f"$\\mathbf{{Casing:}}$\n \n"
        f"Coil half angle: {mfile.get('rad_tf_coil_inboard_toroidal_half', scan=scan):.3f} radians\n\n"
        f"$\\text{{Full Coil Case:}}$\n"
        f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_inboard_in', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_inboard_out', scan=scan):.3f} m\n"
        f"$\\Delta r$: {mfile.get('dr_tf_inboard', scan=scan):.3f} m\n"
        f"Area of casing around WP: {mfile.get('a_tf_coil_inboard_case', scan=scan):.3f} $\\mathrm{{m}}^2$\n\n"
        f"$\\text{{Nose Case:}}$\n"
        f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_inboard_in', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_wp_inboard_inner', scan=scan):.3f} m\n"
        f"$\\Delta r$: {mfile.get('dr_tf_nose_case', scan=scan):.3f} m\n"
        f"$A$: {mfile.get('a_tf_coil_nose_case', scan=scan):.4f} $\\mathrm{{m}}^2$\n\n"
        f"$\\text{{Plasma Case:}}$\n"
        f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_wp_inboard_outer', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_inboard_out', scan=scan):.3f} m\n"
        f"$\\Delta r$: {mfile.get('dr_tf_plasma_case', scan=scan):.3f} m\n"
        f"$A$: {mfile.get('a_tf_plasma_case', scan=scan):.3f} $\\mathrm{{m}}^2$"
    )
    axis.text(
        0.775,
        0.925,
        textstr_casing,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "grey", "alpha": 1.0, "linewidth": 2},
    )

    # Add info about the steel casing surrounding the WP
    textstr_wp_insulation = (
        f"$\\mathbf{{Insulation:}}$\n \n"
        f"Area of insulation around WP: {mfile.get('a_tf_wp_ground_insulation', scan=scan):.3f} $\\mathrm{{m}}^2$\n"
        f"$\\Delta r$: {mfile.get('dx_tf_wp_insulation', scan=scan):.4f} m\n\n"
        f"$\\text{{Turn Insulation:}}$\n"
        f"$\\Delta r$: {mfile.get('dx_tf_turn_insulation', scan=scan):.4f} m"
    )
    axis.text(
        0.775,
        0.62,
        textstr_wp_insulation,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "green", "alpha": 1.0, "linewidth": 2},
    )

    # Add info about the Winding Pack
    textstr_wp = (
        f"$\\mathbf{{Winding Pack:}}$\n \n"
        f"$N_{{\\text{{turns}}}}$: "
        f"{int(mfile.get('n_tf_coil_turns', scan=scan))} turns\n"
        f"$r_{{start}} \\rightarrow r_{{end}}$: {mfile.get('r_tf_wp_inboard_inner', scan=scan):.3f} $\\rightarrow$ {mfile.get('r_tf_wp_inboard_outer', scan=scan):.3f} m\n"
        f"$\\Delta r$: {mfile.get('dr_tf_wp_with_insulation', scan=scan):.3f} m\n"
        f"$A$, with insulation: {mfile.get('a_tf_wp_with_insulation', scan=scan):.3f} $\\mathrm{{m}}^2$\n"
        f"$A$, no insulation: {mfile.get('a_tf_wp_no_insulation', scan=scan):.3f} $\\mathrm{{m}}^2$\n\n"
        f"Current per turn: {mfile.get('c_tf_turn', scan=scan) / 1e3:.3f} $\\mathrm{{kA}}$\n"
        f"Resistive conductor per coil: {mfile.get('a_res_tf_coil_conductor', scan=scan):.3f} $\\mathrm{{m}}^2$\n"
        f"Coolant area void fraction per turn: {mfile.get('fcoolcp', scan=scan):.3f}"
    )
    axis.text(
        0.77,
        0.475,
        textstr_wp,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        color="white",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "blue", "alpha": 1.0, "linewidth": 2},
    )

    # Add info about the Winding Pack
    textstr_general_info = (
        f"$\\mathbf{{General \\ info:}}$\n \n"
        f"Self inductance: {mfile.get('ind_tf_coil', scan=scan) * 1e6:.4f} $\\mu$H\n"
        f"Stored energy of all coils: {mfile.get('e_tf_magnetic_stored_total_gj', scan=scan):.4f} GJ\n"
    )
    axis.text(
        0.55,
        0.475,
        textstr_general_info,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={"boxstyle": "round", "facecolor": "wheat", "alpha": 1.0, "linewidth": 2},
    )

    # Add info about the Winding Pack
    textstr_cooling = (
        f"$\\mathbf{{Cooling \\ info:}}$\n \n"
        f"Coolant inlet temperature: {mfile.get('temp_cp_coolant_inlet', scan=scan):.2f} K\n"
        f"Coolant temperature rise: {mfile.get('dtemp_cp_coolant', scan=scan):.2f} K\n"
        f"Coolant velocity: {mfile.get('vel_cp_coolant_midplane', scan=scan):.2f} $\\mathrm{{ms^{{-1}}}}$\n\n"
        f"Average CP temperature: {mfile.get('temp_cp_average', scan=scan):.2f} K\n"
        f"CP resistivity: {mfile.get('rho_cp', scan=scan):.2e} $\\Omega \\mathrm{{m}}$\n"
        f"Leg resistivity: {mfile.get('rho_tf_leg', scan=scan):.2e} $\\Omega \\mathrm{{m}}$\n"
        f"Leg resistance: {mfile.get('res_tf_leg', scan=scan):.2e} $\\Omega$\n"
        f"CP resistive losses: {mfile.get('p_cp_resistive', scan=scan):,.2f} $\\mathrm{{W}}$\n"
        f"Leg resistive losses: {mfile.get('p_tf_leg_resistive', scan=scan):,.2f} $\\mathrm{{W}}$\n"
        f"Joints resistive losses: {mfile.get('p_tf_joints_resistive', scan=scan):,.2f} $\\mathrm{{W}}$\n"
    )
    axis.text(
        0.55,
        0.35,
        textstr_cooling,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

plot_tf_cable_in_conduit_turn(axis, fig, mfile, scan)

Plots inboard TF coil CICC individual turn structure.

Parameters:

Name Type Description Default
axis matplotlib.axes object

Axis object to plot to.

required
mfile MFILE data object

Object containing data for the plot.

required
scan int

Scan number to use.

required
Source code in process/core/io/plot_proc.py
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
def plot_tf_cable_in_conduit_turn(axis: plt.Axes, fig, mfile: mf.MFile, scan: int):
    """Plots inboard TF coil CICC individual turn structure.

    Parameters
    ----------
    axis : matplotlib.axes object
        Axis object to plot to.
    mfile : MFILE data object
        Object containing data for the plot.
    scan : int
        Scan number to use.
    """

    def _pack_strands_rectangular_with_obstacles(
        cable_space_bounds,
        pipe_center,
        pipe_radius,
        strand_diameter,
        void_fraction,
        n_strands,
        axis,
        corner_radius,
        f_a_tf_turn_cable_copper,
    ):
        """Pack circular strands in rectangular space with cooling pipe obstacle

        Parameters
        ----------
        cable_space_bounds :

        pipe_center :

        pipe_radius :

        strand_diameter :

        void_fraction :

        n_strands :

        axis :

        corner_radius :

        f_a_tf_turn_cable_copper :

        """

        x, y, width, height = cable_space_bounds

        radius = strand_diameter / 2
        placed_strands = []
        attempts = 0

        pipe_x, pipe_y = pipe_center

        # Hexagonal packing parameters
        # Calculate the spacing between strand centers for the desired void fraction
        # For hexagonal packing, packing fraction = pi/(2*sqrt(3)) ~ 0.9069
        # To achieve a lower packing fraction (higher void fraction), increase spacing
        ideal_packing_fraction = np.pi / (2 * np.sqrt(3))
        target_packing_fraction = 1 - void_fraction
        spacing_factor = np.sqrt(ideal_packing_fraction / target_packing_fraction)
        strand_spacing = strand_diameter * spacing_factor

        # Number of rows and columns that fit in the cable space
        n_rows = int((height - 2 * radius) // (strand_spacing * np.sqrt(3) / 2))
        n_cols = int((width - 2 * radius) // strand_spacing)

        # Calculate the radius of the inner superconductor circle based on the copper area fraction
        # Area_superconductor = f_a_tf_turn_cable_copper * Area_strand
        # Area_strand = pi * radius^2
        # So, radius_superconductor = sqrt(f_a_tf_turn_cable_copper) * radius
        radius_superconductor = np.sqrt(f_a_tf_turn_cable_copper) * radius

        # Generate hexagonal grid positions
        for row in range(n_rows):
            y_pos = (y + radius + row * strand_spacing * np.sqrt(3) / 2) * 1.07
            x_offset = strand_spacing / 2 if row % 2 else 0
            for col in range(n_cols):
                candidate_x = (x + radius + col * strand_spacing + x_offset) * 1.05
                candidate_y = y_pos

                # Check if within bounds
                if candidate_x > x + width - radius or candidate_y > y + height - radius:
                    continue

                # Check collision with cooling pipe
                pipe_distance = np.sqrt(
                    (candidate_x - pipe_x) ** 2 + (candidate_y - pipe_y) ** 2
                )
                if pipe_distance < (pipe_radius + radius):
                    continue

                # Check collision with corners if rounded
                if corner_radius > 0:
                    corners = [
                        (x + corner_radius, y + corner_radius),  # bottom-left
                        (x + width - corner_radius, y + corner_radius),  # bottom-right
                        (
                            x + width - corner_radius,
                            y + height - corner_radius,
                        ),  # top-right
                        (x + corner_radius, y + height - corner_radius),  # top-left
                    ]
                    if (
                        (
                            candidate_x < corners[0][0]
                            and candidate_y < corners[0][1]
                            and np.sqrt(
                                (candidate_x - corners[0][0]) ** 2
                                + (candidate_y - corners[0][1]) ** 2
                            )
                            > corner_radius - radius
                        )
                        or (
                            candidate_x > corners[1][0]
                            and candidate_y < corners[1][1]
                            and np.sqrt(
                                (candidate_x - corners[1][0]) ** 2
                                + (candidate_y - corners[1][1]) ** 2
                            )
                            > corner_radius - radius
                        )
                        or (
                            candidate_x > corners[2][0]
                            and candidate_y > corners[2][1]
                            and np.sqrt(
                                (candidate_x - corners[2][0]) ** 2
                                + (candidate_y - corners[2][1]) ** 2
                            )
                            > corner_radius - radius
                        )
                        or (
                            candidate_x < corners[3][0]
                            and candidate_y > corners[3][1]
                            and np.sqrt(
                                (candidate_x - corners[3][0]) ** 2
                                + (candidate_y - corners[3][1]) ** 2
                            )
                            > corner_radius - radius
                        )
                    ):
                        continue

                # Check collision with existing strands
                collision = False
                for existing_x, existing_y in placed_strands:
                    distance = np.sqrt(
                        (candidate_x - existing_x) ** 2 + (candidate_y - existing_y) ** 2
                    )
                    if distance < strand_diameter:
                        collision = True
                        break

                if not collision:
                    placed_strands.append((candidate_x, candidate_y))
                    # Plot the strand
                    circle_copper_surrounding = Circle(
                        (candidate_x, candidate_y),
                        radius,
                        facecolor="#b87333",  # copper color
                        edgecolor="#8B4000",  # darker copper edge
                        linewidth=0.1,
                        alpha=0.8,
                    )
                    axis.add_patch(circle_copper_surrounding)

                    circle_central_conductor = Circle(
                        (candidate_x, candidate_y),
                        radius_superconductor,
                        facecolor="black",
                        linewidth=0.3,
                        alpha=0.5,
                    )
                    axis.add_patch(circle_central_conductor)

                if len(placed_strands) >= n_strands:
                    break
            if len(placed_strands) >= n_strands:
                break

        attempts = n_rows * n_cols

        return len(placed_strands), attempts

    # Import the TF turn variables then multiply into mm
    i_tf_turns_integer = mfile.get("i_tf_turns_integer", scan=scan)
    # If integer turns switch is on then the turns can have non square dimensions
    if i_tf_turns_integer == 1:
        turn_width = mfile.get("dr_tf_turn", scan=scan)
        turn_height = mfile.get("dx_tf_turn", scan=scan)
        cable_space_width_radial = mfile.get("dr_tf_turn_cable_space", scan=scan)
        cable_space_width_toroidal = mfile.get("dx_tf_turn_cable_space", scan=scan)

    elif i_tf_turns_integer == 0:
        turn_width = mfile.get("dx_tf_turn_general", scan=scan)
        cable_space_width = mfile.get("dx_tf_turn_cable_space_average", scan=scan)

    he_pipe_diameter = mfile.get("dia_tf_turn_coolant_channel", scan=scan)
    steel_thickness = mfile.get("dx_tf_turn_steel", scan=scan)
    insulation_thickness = mfile.get("dx_tf_turn_insulation", scan=scan)

    a_tf_turn_cable_space_no_void = mfile.get("a_tf_turn_cable_space_no_void", scan=scan)
    radius_tf_turn_cable_space_corners = mfile.get(
        "radius_tf_turn_cable_space_corners", scan=scan
    )

    a_tf_wp_coolant_channels = mfile.get("a_tf_wp_coolant_channels", scan=scan)

    f_a_tf_turn_cable_space_extra_void = mfile.get(
        "f_a_tf_turn_cable_space_extra_void", scan=scan
    )
    a_tf_turn_steel = mfile.get("a_tf_turn_steel", scan=scan)
    a_tf_turn_cable_space_effective = mfile.get(
        "a_tf_turn_cable_space_effective", scan=scan
    )

    # Plot the total turn shape
    if i_tf_turns_integer == 0:
        axis.add_patch(
            Rectangle(
                [0, 0],
                turn_width,
                turn_width,
                facecolor="red",
                edgecolor="black",
            ),
        )
        # Plot the steel conduit
        axis.add_patch(
            Rectangle(
                [insulation_thickness, insulation_thickness],
                (turn_width - 2 * insulation_thickness),
                (turn_width - 2 * insulation_thickness),
                facecolor="grey",
                edgecolor="black",
            ),
        )

        # Plot the cable space with rounded corners
        axis.add_patch(
            patches.FancyBboxPatch(
                [
                    insulation_thickness + steel_thickness,
                    insulation_thickness + steel_thickness,
                ],
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                boxstyle=patches.BoxStyle(
                    "Round", pad=0, rounding_size=radius_tf_turn_cable_space_corners
                ),
                facecolor="royalblue",
                edgecolor="black",
            ),
        )

        # Plot dashed line around the cable space
        axis.add_patch(
            Rectangle(
                [
                    insulation_thickness + steel_thickness,
                    insulation_thickness + steel_thickness,
                ],
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                facecolor="none",
                edgecolor="black",
                linestyle="--",
                linewidth=1.2,
                alpha=0.5,
            ),
        )
        # Plot the coolant channel
        axis.add_patch(
            Circle(
                [(turn_width / 2), (turn_width / 2)],
                he_pipe_diameter / 2,
                facecolor="white",
                edgecolor="black",
            ),
        )

        # Cable strand packing parameters
        strand_diameter = mfile.get("dia_tf_turn_superconducting_cable", scan=scan)
        void_fraction = mfile.get("f_a_tf_turn_cable_space_extra_void", scan=scan)

        # Cable space bounds
        cable_bounds = [
            insulation_thickness + steel_thickness,
            insulation_thickness + steel_thickness,
            turn_width - 2 * (insulation_thickness + steel_thickness),
            turn_width - 2 * (insulation_thickness + steel_thickness),
        ]

        # Pack strands if significant void fraction
        if void_fraction > 0.001:
            _n_strands, _attempts = _pack_strands_rectangular_with_obstacles(
                cable_space_bounds=cable_bounds,
                pipe_center=(
                    turn_width / 2,
                    (turn_width if i_tf_turns_integer == 0 else turn_height) / 2,
                ),
                pipe_radius=he_pipe_diameter / 2,
                strand_diameter=strand_diameter,
                void_fraction=void_fraction,
                axis=axis,
                corner_radius=radius_tf_turn_cable_space_corners,
                n_strands=mfile.get("n_tf_turn_superconducting_cables", scan=scan),
                f_a_tf_turn_cable_copper=mfile.get(
                    "f_a_tf_turn_cable_copper", scan=scan
                ),
            )

        axis.set_xlim(-turn_width * 0.05, turn_width * 1.05)
        axis.set_ylim(-turn_width * 0.05, turn_width * 1.05)

    # Non square turns
    elif i_tf_turns_integer == 1:
        axis.add_patch(
            Rectangle(
                [0, 0],
                turn_width,
                turn_height,
                facecolor="red",
                edgecolor="black",
            ),
        )

        # Plot the steel conduit
        axis.add_patch(
            Rectangle(
                [insulation_thickness, insulation_thickness],
                (turn_width - 2 * insulation_thickness),
                (turn_height - 2 * insulation_thickness),
                facecolor="grey",
                edgecolor="black",
            ),
        )

        # Plot the cable space with rounded corners
        axis.add_patch(
            patches.FancyBboxPatch(
                [
                    insulation_thickness + steel_thickness,
                    insulation_thickness + steel_thickness,
                ],
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                (turn_height - 2 * (insulation_thickness + steel_thickness)),
                boxstyle=patches.BoxStyle(
                    "Round", pad=0, rounding_size=radius_tf_turn_cable_space_corners
                ),
                facecolor="royalblue",
                edgecolor="black",
            ),
        )
        # Plot dashed line around the cable space
        axis.add_patch(
            Rectangle(
                [
                    insulation_thickness + steel_thickness,
                    insulation_thickness + steel_thickness,
                ],
                (turn_width - 2 * (insulation_thickness + steel_thickness)),
                (turn_height - 2 * (insulation_thickness + steel_thickness)),
                facecolor="none",
                edgecolor="black",
                linestyle="--",
                linewidth=1.0,
                alpha=0.5,
            ),
        )
        axis.add_patch(
            Circle(
                [(turn_width / 2), (turn_height / 2)],
                he_pipe_diameter / 2,
                facecolor="white",
                edgecolor="black",
            ),
        )

        # Cable space bounds
        cable_bounds = [
            insulation_thickness + steel_thickness,
            insulation_thickness + steel_thickness,
            turn_width - 2 * (insulation_thickness + steel_thickness),
            turn_height - 2 * (insulation_thickness + steel_thickness),
        ]

        # Cable strand packing parameters
        strand_diameter = mfile.get("dia_tf_turn_superconducting_cable", scan=scan)
        void_fraction = mfile.get("f_a_tf_turn_cable_space_extra_void", scan=scan)

        # Pack strands if significant void fraction
        if void_fraction > 0.001:
            _, _ = _pack_strands_rectangular_with_obstacles(
                cable_space_bounds=cable_bounds,
                pipe_center=(
                    turn_width / 2,
                    turn_height / 2,
                ),
                pipe_radius=he_pipe_diameter / 2,
                strand_diameter=strand_diameter,
                void_fraction=void_fraction,
                axis=axis,
                corner_radius=radius_tf_turn_cable_space_corners,
                n_strands=mfile.get("n_tf_turn_superconducting_cables", scan=scan),
                f_a_tf_turn_cable_copper=mfile.get(
                    "f_a_tf_turn_cable_copper", scan=scan
                ),
            )

        axis.set_xlim(-turn_width * 0.05, turn_width * 1.05)
        axis.set_ylim(-turn_height * 0.05, turn_height * 1.05)

    axis.minorticks_on()
    axis.set_title("WP Turn Structure")
    axis.set_xlabel("r [m]")
    axis.set_ylabel("x [m]")

    # Add info about the steel casing surrounding the WP
    textstr_turn_insulation = (
        f"$\\mathbf{{Turn \\ Insulation:}}$\n\n$\\Delta r:${insulation_thickness:.3e} m"
    )

    axis.text(
        0.4,
        0.9,
        textstr_turn_insulation,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "red",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add info about the steel casing surrounding the WP
    textstr_turn_steel = (
        f"$\\mathbf{{Steel \\ Conduit:}}$\n\n$\\Delta r:${steel_thickness:.3e} m\n"
        f"$A$: {a_tf_turn_steel:.3e} m$^2$"
    )

    axis.text(
        0.65,
        0.9,
        textstr_turn_steel,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    if i_tf_turns_integer == 0:
        # Add info about the steel casing surrounding the WP
        textstr_turn_cable_space = (
            f"$\\mathbf{{Cable \\ Space:}}$\n\n"
            f"$\\Delta r:$ {cable_space_width:.3e} m\n"
            f"Corner radius, $r$: {radius_tf_turn_cable_space_corners:.3e} m\n"
            f"Cable area with no cooling \nchannel or gaps: {a_tf_turn_cable_space_no_void:.3e} m$^2$\n"
            f"Extra cable space area void fraction: {f_a_tf_turn_cable_space_extra_void}\n"
            f"True cable space area: {a_tf_turn_cable_space_effective:.3e} m$^2$"
        )
    elif i_tf_turns_integer == 1:
        textstr_turn_cable_space = (
            f"$\\mathbf{{Cable \\ Space:}}$\n\n"
            f"Cable space: \n$\\Delta r$: {cable_space_width_radial:.3e} m \n"
            f"$\\Delta x$: {cable_space_width_toroidal:.3e} m \n"
            f"Corner radius, $r$: {radius_tf_turn_cable_space_corners:.3e} m\n"
            f"Cable area with no cooling channel or gaps: {a_tf_turn_cable_space_no_void:.3e} m$^2$\n"
            f"Extra cable space area void fraction: {f_a_tf_turn_cable_space_extra_void}\n"
            f"True cable space area: {a_tf_turn_cable_space_effective:.3e} m$^2$"
        )

    axis.text(
        0.40,
        0.7,
        textstr_turn_cable_space,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "royalblue",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    if i_tf_turns_integer == 0:
        textstr_turn = (
            f"$\\mathbf{{Turn:}}$\n\n"
            f"$\\Delta r$: {turn_width:.3e} m\n"
            f"$\\Delta x$: {turn_width:.3e} m"
        )

    if i_tf_turns_integer == 1:
        textstr_turn = (
            f"$\\mathbf{{Turn:}}$\n\n"
            f"$\\Delta r$: {turn_width:.3e} m\n"
            f"$\\Delta x$: {turn_height:.3e} m"
        )

    axis.text(
        0.525,
        0.9,
        textstr_turn,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Add info about the steel casing surrounding the WP
    textstr_turn_cooling = (
        f"$\\mathbf{{Cooling:}}$\n\n"
        f"$\\varnothing$: {he_pipe_diameter:.3e} m\n"
        f"Total area of all coolant channels: {a_tf_wp_coolant_channels:.4f} m$^2$"
    )

    axis.text(
        0.45,
        0.8,
        textstr_turn_cooling,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "white",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    textstr_superconductor = (
        f"$\\mathbf{{Superconductor:}}$\n \n"
        f"Superconductor used: {sctf.SUPERCONDUCTING_TF_TYPES[mfile.get('i_tf_sc_mat', scan=scan)]}\n"
        f"Critical field at zero \ntemperature and strain: {mfile.get('b_tf_superconductor_critical_zero_temp_strain', scan=scan):.4f} T\n"
        f"Critical temperature at \nzero field and strain: {mfile.get('temp_tf_superconductor_critical_zero_field_strain', scan=scan):.4f} K\n"
        f"Temperature at conductor: {mfile.get('tftmp', scan=scan):.4f} K\n"
        f"$I_{{\\text{{TF,turn critical}}}}$: {mfile.get('c_turn_cables_critical', scan=scan):,.2f} A\n"
        f"$I_{{\\text{{TF,turn}}}}$: {mfile.get('c_tf_turn', scan=scan):,.2f} A\n"
        f"Critcal current ratio: {mfile.get('f_c_tf_turn_operating_critical', scan=scan):,.4f}\n"
        f"Superconductor temperature \nmargin: {mfile.get('temp_tf_superconductor_margin', scan=scan):,.4f} K\n"
        f"\n$\\mathbf{{Quench:}}$\n \n"
        f"Quench dump time: {mfile.get('t_tf_superconductor_quench', scan=scan):.4e} s\n"
        f"Quench detection time: {mfile.get('t_tf_quench_detection', scan=scan):.4e} s\n"
        f"User input max temperature \nduring quench: {mfile.get('temp_tf_conductor_quench_max', scan=scan):.2f} K\n"
        f"Required maxium WP current \ndensity for heat protection:\n{mfile.get('j_tf_wp_quench_heat_max', scan=scan):.2e} A/m$^2$\n"
    )
    axis.text(
        0.75,
        0.9,
        textstr_superconductor,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#6dd3f7",  # light blue for superconductors
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

plot_cable_in_conduit_cable(axis, fig, mfile, scan)

Plots TF coil CICC cable cross-section.

Parameters:

Name Type Description Default
axis Axes
required
fig
required
mfile MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
def plot_cable_in_conduit_cable(axis: plt.Axes, fig, mfile: mf.MFile, scan: int):
    """Plots TF coil CICC cable cross-section.

    Parameters
    ----------
    axis: plt.Axes :

    fig :

    mfile: mf.MFile :

    scan: int :

    """

    dia_tf_turn_superconducting_cable = mfile.get(
        "dia_tf_turn_superconducting_cable", scan=scan
    )
    f_a_tf_turn_cable_copper = mfile.get("f_a_tf_turn_cable_copper", scan=scan)

    # Convert to mm
    dia_mm = dia_tf_turn_superconducting_cable * 1000
    radius_superconductor_mm = np.sqrt(f_a_tf_turn_cable_copper) * (dia_mm / 2)

    # Draw the outer copper circle
    circle_copper_surrounding = patches.Circle(
        (0, 0),
        dia_mm / 2,
        facecolor="#b87333",  # copper color
        edgecolor="#8B4000",  # darker copper edge
        linewidth=0.1,
        alpha=0.8,
        label="Copper",
        zorder=1,
    )
    axis.add_patch(circle_copper_surrounding)

    # Draw the inner superconductor circle
    circle_central_conductor = patches.Circle(
        (0, 0),
        radius_superconductor_mm,
        facecolor="black",
        linewidth=0.3,
        alpha=0.7,
        label="Superconductor",
        zorder=2,
    )
    axis.add_patch(circle_central_conductor)

    # Convert cable diameter to mm
    cable_diameter_mm = mfile.get("dia_tf_turn_superconducting_cable", scan=scan) * 1000
    # Convert lengths from meters to kilometers for display
    len_tf_coil_superconductor_km = (
        mfile.get("len_tf_coil_superconductor", scan=scan) / 1000.0
    )
    len_tf_superconductor_total_km = (
        mfile.get("len_tf_superconductor_total", scan=scan) / 1000.0
    )

    textstr_cable = (
        f"$\\mathbf{{Cable:}}$\n \n"
        f"Cable diameter: {cable_diameter_mm:,.4f} mm\n"
        f"Copper area fraction: {mfile.get('f_a_tf_turn_cable_copper', scan=scan):.4f}\n"
        f"Number of strands per turn: {int(mfile.get('n_tf_turn_superconducting_cables', scan=scan)):,}\n"
        f"Length of superconductor per coil: {len_tf_coil_superconductor_km:,.2f} km\n"
        f"Total length of superconductor in all coils: {len_tf_superconductor_total_km:,.2f} km\n"
    )
    axis.text(
        0.4,
        0.3,
        textstr_cable,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#cccccc",  # grayish color
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.set_aspect("equal")
    axis.set_xlim(-dia_mm / 1.5, dia_mm / 1.5)
    axis.set_ylim(-dia_mm / 1.5, dia_mm / 1.5)
    axis.set_title("TF CICC Cable Cross-Section")
    axis.minorticks_on()
    axis.legend(loc="upper right")
    axis.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)
    axis.set_xlabel("X [mm]")
    axis.set_ylabel("Y [mm]")

plot_pf_coils(axis, mfile, scan, colour_scheme)

Function to plot PF coils

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
colour_scheme Literal[1, 2]

colour scheme to use for plots

required
Source code in process/core/io/plot_proc.py
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
def plot_pf_coils(
    axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]
):
    """Function to plot PF coils

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    colour_scheme :
        colour scheme to use for plots
    """

    coils_r = []
    coils_z = []
    coils_dr = []
    coils_dz = []
    coil_text = []

    dr_bore = mfile.get("dr_bore", scan=scan)
    dr_cs = mfile.get("dr_cs", scan=scan)
    dz_cs_full = mfile.get("dz_cs_full", scan=scan)

    # Number of coils, both PF and CS
    number_of_coils = 0
    for item in mfile.data:
        if "r_pf_coil_middle[" in item:
            number_of_coils += 1

    # Check for Central Solenoid
    iohcl = mfile.get("iohcl", scan=scan) if "iohcl" in mfile.data else 1

    # If Central Solenoid present, ignore last entry in for loop
    # The last entry will be the OH coil in this case
    noc = number_of_coils - 1 if iohcl == 1 else number_of_coils

    for coil in range(noc):
        coils_r.append(mfile.get(f"r_pf_coil_middle[{coil:01}]", scan=scan))
        coils_z.append(mfile.get(f"z_pf_coil_middle[{coil:01}]", scan=scan))
        coils_dr.append(mfile.get(f"pfdr({coil:01})", scan=scan))
        coils_dz.append(mfile.get(f"pfdz({coil:01})", scan=scan))
        coil_text.append(str(coil + 1))

    r_points, z_points, central_coil = pfcoil_geometry(
        coils_r=coils_r,
        coils_z=coils_z,
        coils_dr=coils_dr,
        coils_dz=coils_dz,
        dr_bore=dr_bore,
        dr_cs=dr_cs,
        ohdz=dz_cs_full,
    )

    # Plot CS compression structure
    r_precomp_outer, r_precomp_inner = cumulative_radial_build2(
        "dr_cs_precomp", mfile, scan
    )
    axis.add_patch(
        patches.Rectangle(
            xy=(r_precomp_inner, central_coil.anchor_z),
            width=r_precomp_outer - r_precomp_inner,
            height=central_coil.height,
            facecolor=CSCOMPRESSION_COLOUR[colour_scheme - 1],
        )
    )

    # Get axis height for fontsize scaling
    bbox = axis.get_window_extent().transformed(axis.figure.dpi_scale_trans.inverted())
    axis_height = bbox.height

    for i in range(len(coils_r)):
        axis.plot(r_points[i], z_points[i], color="black")
        # Scale fontsize relative to axis height and coil size
        fontsize = max(6, axis_height * abs(coils_dr[i] * coils_dz[i]) * 1.5)
        axis.text(
            coils_r[i],
            coils_z[i] - 0.05,
            coil_text[i],
            ha="center",
            va="center",
            fontsize=fontsize,
        )
    axis.add_patch(
        patches.Rectangle(
            xy=(central_coil.anchor_x, central_coil.anchor_z),
            width=central_coil.width,
            height=central_coil.height,
            facecolor=SOLENOID_COLOUR[colour_scheme - 1],
        )
    )

plot_info(axis, data, mfile, scan)

Function to plot data in written form on a matplotlib plot.

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
data

plot information

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
def plot_info(axis: plt.Axes, data, mfile: mf.MFile, scan: int):
    """Function to plot data in written form on a matplotlib plot.

    Parameters
    ----------
    axis :
        axis object to plot to
    data :
        plot information
    mfile :
        MFILE
    scan :
        scan number to use
    """
    eqpos = 0.75
    for i in range(len(data)):
        colorflag = "black"
        if mfile.data[data[i][0]].exists:
            if mfile.data[data[i][0]].var_flag == "ITV":
                colorflag = "red"
            elif mfile.data[data[i][0]].var_flag == "OP":
                colorflag = "blue"
        axis.text(0, -i, data[i][1], color=colorflag, ha="left", va="center")
        if isinstance(data[i][0], str):
            if data[i][0] == "":
                axis.text(eqpos, -i, "\n", ha="left", va="center")
            elif data[i][0][0] == "#":
                axis.text(-0.05, -i, f"{data[i][0][1:]}\n", ha="left", va="center")
            elif data[i][0][0] == "!":
                value = data[i][0][1:].replace('"', "")
                axis.text(
                    0.4,
                    -i,
                    f"-->  {value} {data[i][2]}",
                    ha="left",
                    va="center",
                )
            else:
                if mfile.data[data[i][0]].exists:
                    dat = mfile.get(data[i][0], scan=scan)
                    if isinstance(dat, str):
                        value = dat
                    else:
                        value = f"{mfile.get(data[i][0], scan=scan):.4g}"
                    if "alpha" in data[i][0]:
                        value = str(float(value) + 1.0)
                    axis.text(
                        eqpos,
                        -i,
                        f"= {value} {data[i][2]}",
                        color=colorflag,
                        ha="left",
                        va="center",
                    )
                else:
                    mfile.get(data[i][0], scan=-1)
                    axis.text(
                        eqpos,
                        -i,
                        "= ERROR! Var missing",
                        color=colorflag,
                        ha="left",
                        va="center",
                    )
        else:
            dat = data[i][0]
            value = dat if isinstance(dat, str) else f"{data[i][0]:.4g}"
            axis.text(
                eqpos,
                -i,
                f"= {value} {data[i][2]}",
                color=colorflag,
                ha="left",
                va="center",
            )

plot_header(axis, mfile, scan)

Function to plot header info: date, rutitle etc

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
def plot_header(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot header info: date, rutitle etc

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """
    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1

    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    data2 = [
        (f"!{mfile.get('runtitle', scan=-1)}", "Run title", ""),
        (f"!{mfile.get('procver', scan=-1)}", "PROCESS Version", ""),
        (f"!{mfile.get('date', scan=-1)}", "Date:", ""),
        (f"!{mfile.get('time', scan=-1)}", "Time:", ""),
        (f"!{mfile.get('username', scan=-1)}", "User:", ""),
        ("!Evaluation", "Run type", "")
        if isinstance(mfile.data["minmax"], MFileErrorClass)
        else (
            f"!{OBJECTIVE_NAMES[abs(int(mfile.get('minmax', scan=-1)))]}",
            "Optimising:",
            "",
        ),
    ]

    axis.text(-0.05, 4.0, "Colour Legend:", ha="left", va="center")
    axis.text(
        0.0, 3.0, "ITR --> Iteration variable", color="red", ha="left", va="center"
    )
    axis.text(0.0, 2.0, "OP  --> Output variable", color="blue", ha="left", va="center")

    H = mfile.get("f_nd_impurity_electrons(01)", scan=scan)
    He = mfile.get("f_nd_impurity_electrons(02)", scan=scan)
    Be = mfile.get("f_nd_impurity_electrons(03)", scan=scan)
    C = mfile.get("f_nd_impurity_electrons(04)", scan=scan)
    N = mfile.get("f_nd_impurity_electrons(05)", scan=scan)
    O = mfile.get("f_nd_impurity_electrons(06)", scan=scan)  # noqa: E741
    Ne = mfile.get("f_nd_impurity_electrons(07)", scan=scan)
    Si = mfile.get("f_nd_impurity_electrons(08)", scan=scan)
    Ar = mfile.get("f_nd_impurity_electrons(09)", scan=scan)
    Fe = mfile.get("f_nd_impurity_electrons(10)", scan=scan)
    Ni = mfile.get("f_nd_impurity_electrons(11)", scan=scan)
    Kr = mfile.get("f_nd_impurity_electrons(12)", scan=scan)
    Xe = mfile.get("f_nd_impurity_electrons(13)", scan=scan)
    W = mfile.get("f_nd_impurity_electrons(14)", scan=scan)

    data = [("", "", ""), ("", "", "")]
    count = 0

    data = [*data, (H, "D + T", "")]
    count += 1

    data = [*data, (He, "He", "")]
    count += 1
    if Be > 1e-10:
        data = [*data, (Be, "Be", "")]
        count += +1
    if C > 1e-10:
        data = [*data, (C, "C", "")]
        count += 1
    if N > 1e-10:
        data = [*data, (N, "N", "")]
        count += 1
    if O > 1e-10:
        data = [*data, (O, "O", "")]
        count += 1
    if Ne > 1e-10:
        data = [*data, (Ne, "Ne", "")]
        count += 1
    if Si > 1e-10:
        data = [*data, (Si, "Si", "")]
        count += 1
    if Ar > 1e-10:
        data = [*data, (Ar, "Ar", "")]
        count += 1
    if Fe > 1e-10:
        data = [*data, (Fe, "Fe", "")]
        count += 1
    if Ni > 1e-10:
        data = [*data, (Ni, "Ni", "")]
        count += 1
    if Kr > 1e-10:
        data = [*data, (Kr, "Kr", "")]
        count += 1
    if Xe > 1e-10:
        data = [*data, (Xe, "Xe", "")]
        count += 1
    if W > 1e-10:
        data = [*data, (W, "W", "")]
        count += 1

    if count > 11:
        data = [("", "", ""), ("", "", ""), ("", "More than 11 impurities", "")]
    else:
        axis.text(-0.05, -6.4, "Plasma composition:", ha="left", va="center")
        axis.text(
            -0.05,
            -7.2,
            "Number densities relative to electron density:",
            ha="left",
            va="center",
        )
    data2 = data2 + data

    plot_info(axis, data2, mfile, scan)

plot_geometry_info(axis, mfile, scan)

Function to plot geometry info

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
def plot_geometry_info(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot geometry info

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """
    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1

    axis.text(-0.05, 1, "Geometry:", ha="left", va="center")
    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    in_blanket_thk = mfile.get("dr_shld_inboard", scan=scan) + mfile.get(
        "dr_blkt_inboard", scan=scan
    )
    out_blanket_thk = mfile.get("dr_shld_outboard", scan=scan) + mfile.get(
        "dr_blkt_outboard", scan=scan
    )

    data = [
        ("rmajor", "$R_0$", "m"),
        ("rminor", "a", "m"),
        ("aspect", "A", ""),
        ("kappa95", r"$\kappa_{95}$", ""),
        ("triang95", r"$\delta_{95}$", ""),
        ("a_plasma_surface", "Plasma surface area", "m$^2$"),
        ("a_plasma_poloidal", "Plasma cross-sectional area", "m$^2$"),
        ("vol_plasma", "Plasma volume", "m$^3$"),
        ("n_tf_coils", "No. of TF coils", ""),
        (in_blanket_thk, "Inboard blanket+shield", "m"),
        ("dr_inboard_build", "Inboard build thickness", "m"),
        (out_blanket_thk, "Outboard blanket+shield", "m"),
    ]

    plot_info(axis, data, mfile, scan)

plot_physics_info(axis, mfile, scan)

Function to plot geometry info

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
def plot_physics_info(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot geometry info

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """
    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1

    axis.text(-0.05, 1, "Physics:", ha="left", va="center")
    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    nong = mfile.get("nd_plasma_electron_line", scan=scan) / mfile.get(
        "nd_plasma_electron_max_array(7)", scan=scan
    )

    nd_plasma_impurities_vol_avg = mfile.get(
        "nd_plasma_impurities_vol_avg", scan=scan
    ) / mfile.get("nd_plasma_electrons_vol_avg", scan=scan)

    tepeak = mfile.get("temp_plasma_electron_on_axis_kev", scan=scan) / mfile.get(
        "temp_plasma_electron_vol_avg_kev", scan=scan
    )

    nepeak = mfile.get("nd_plasma_electron_on_axis", scan=scan) / mfile.get(
        "nd_plasma_electrons_vol_avg", scan=scan
    )

    # Assume Martin scaling if pthresh is not printed
    # Accounts for pthresh not being written prior to issue #679 and #680
    if "p_l_h_threshold_mw" in mfile.data:
        pthresh = mfile.get("p_l_h_threshold_mw", scan=scan)
    else:
        pthresh = mfile.get("l_h_threshold_powers(6)", scan=scan)

    data = [
        ("p_fusion_total_mw", "Fusion power", "MW"),
        ("big_q_plasma", "$Q_{p}$", ""),
        ("plasma_current_ma", "$I_p$", "MA"),
        ("b_plasma_toroidal_on_axis", "Vacuum $B_T$ at $R_0$", "T"),
        ("q95", r"$q_{\mathrm{95}}$", ""),
        ("beta_norm_thermal", r"$\beta_N$, thermal", "% m T MA$^{-1}$"),
        ("beta_norm_toroidal", r"$\beta_N$, toroidal", "% m T MA$^{-1}$"),
        ("beta_thermal_poloidal_vol_avg", r"$\beta_P$, thermal", ""),
        ("beta_poloidal_vol_avg", r"$\beta_P$, total", ""),
        ("temp_plasma_electron_vol_avg_kev", r"$\langle T_e \rangle$", "keV"),
        ("nd_plasma_electrons_vol_avg", r"$\langle n_e \rangle$", "m$^{-3}$"),
        (nong, r"$\langle n_{\mathrm{e,line}} \rangle \ / \ n_G$", ""),
        (tepeak, r"$T_{e0} \ / \ \langle T_e \rangle$", ""),
        (nepeak, r"$n_{e0} \ / \ \langle n_{\mathrm{e, vol}} \rangle$", ""),
        ("n_charge_plasma_effective_vol_avg", r"$Z_{\mathrm{eff}}$", ""),
        (
            nd_plasma_impurities_vol_avg,
            r"$n_Z \ / \  \langle n_{\mathrm{e, vol}} \rangle$",
            "",
        ),
        ("t_energy_confinement", r"$\tau_e$", "s"),
        ("hfact", "H-factor", ""),
        (pthresh, "H-mode threshold", "MW"),
        ("tauelaw", "Scaling law", ""),
    ]

    plot_info(axis, data, mfile, scan)

plot_magnetics_info(axis, mfile, scan)

Function to plot magnet info

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
def plot_magnetics_info(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot magnet info

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """
    # Check for Copper magnets
    i_tf_sup = int(mfile.get("i_tf_sup", scan=scan)) if "i_tf_sup" in mfile.data else 1

    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1

    axis.text(-0.05, 1, "Coil currents etc:", ha="left", va="center")
    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    # Number of coils (1 is OH coil)
    number_of_coils = 0
    for item in mfile.data:
        if "r_pf_coil_middle[" in item:
            number_of_coils += 1

    pf_info = [
        (
            mfile.get(f"c_pf_cs_coils_peak_ma[{i:01}]", scan=scan),
            f"PF {i}",
        )
        for i in range(1, number_of_coils)
        if i % 2 != 0
    ]

    if len(pf_info) > 2:
        pf_info_3_a = pf_info[2][0]
        pf_info_3_b = pf_info[2][1]
    else:
        pf_info_3_a = ""
        pf_info_3_b = ""

    t_plant_pulse_burn = mfile.get("t_plant_pulse_burn", scan=scan) / 3600.0

    if "i_tf_bucking" in mfile.data:
        i_tf_bucking = int(mfile.get("i_tf_bucking", scan=scan))
    else:
        i_tf_bucking = 1

    # Get superconductor material (i_tf_sc_mat)
    # If i_tf_sc_mat not present, assume resistive
    if "i_tf_sc_mat" in mfile.data:
        i_tf_sc_mat = int(mfile.get("i_tf_sc_mat", scan=scan))
    else:
        i_tf_sc_mat = 0

    if i_tf_sc_mat > 0:
        tftype = SUPERCONDUCTING_TF_TYPES[int(mfile.get("i_tf_sc_mat", scan=scan))]
    else:
        tftype = "Resistive Copper"

    vssoft = mfile.get("vs_plasma_res_ramp", scan=scan) + mfile.get(
        "vs_plasma_ind_ramp", scan=scan
    )

    sig_case = 1.0e-6 * mfile.get(f"s_shear_tf_peak({i_tf_bucking})", scan=scan)
    sig_cond = 1.0e-6 * mfile.get(f"s_shear_tf_peak({i_tf_bucking + 1})", scan=scan)

    if i_tf_sup == 1:
        data = [
            (pf_info[0][0], pf_info[0][1], "MA"),
            (pf_info[1][0], pf_info[1][1], "MA"),
            (pf_info_3_a, pf_info_3_b, "MA"),
            (vssoft, "Startup flux swing", "Wb"),
            ("vs_cs_pf_total_pulse", "Available flux swing", "Wb"),
            (t_plant_pulse_burn, "Burn time", "hrs"),
            ("", "", ""),
            (f"#TF coil type is {tftype}", "", ""),
            ("b_tf_inboard_peak_with_ripple", "Peak field at conductor (w. rip.)", "T"),
            ("f_c_tf_turn_operating_critical", r"I/I$_{\mathrm{crit}}$", ""),
            ("temp_tf_superconductor_margin", "TF Temperature margin", "K"),
            ("temp_cs_superconductor_margin", "CS Temperature margin", "K"),
            (sig_cond, "TF Cond max TRESCA stress", "MPa"),
            (sig_case, "TF Case max TRESCA stress", "MPa"),
            ("m_tf_coils_total/n_tf_coils", "Mass per TF coil", "kg"),
        ]

    else:
        p_cp_resistive = 1.0e-6 * mfile.get("p_cp_resistive", scan=scan)
        p_tf_leg_resistive = 1.0e-6 * mfile.get("p_tf_leg_resistive", scan=scan)
        p_tf_joints_resistive = 1.0e-6 * mfile.get("p_tf_joints_resistive", scan=scan)
        fcoolcp = 100.0 * mfile.get("fcoolcp", scan=scan)

        data = [
            (pf_info[0][0], pf_info[0][1], "MA"),
            (pf_info[1][0], pf_info[1][1], "MA"),
            (pf_info_3_a, pf_info_3_b, "MA"),
            (vssoft, "Startup flux swing", "Wb"),
            ("vs_cs_pf_total_pulse", "Available flux swing", "Wb"),
            (t_plant_pulse_burn, "Burn time", "hrs"),
            ("", "", ""),
            (f"#TF coil type is {tftype}", "", ""),
            ("b_tf_inboard_peak_symmetric", "Peak field at conductor (w. rip.)", "T"),
            ("c_tf_total", "TF coil currents sum", "A"),
            ("", "", ""),
            ("#TF coil forces/stresses", "", ""),
            (sig_cond, "TF conductor max TRESCA stress", "MPa"),
            (sig_case, "TF bucking max TRESCA stress", "MPa"),
            (fcoolcp, "CP cooling fraction", "%"),
            ("vel_cp_coolant_midplane", "Maximum coolant flow speed", "ms$^{-1}$"),
            (p_cp_resistive, "CP Resisitive heating", "MW"),
            (
                p_tf_leg_resistive,
                "legs Resisitive heating (all legs)",
                "MW",
            ),
            (p_tf_joints_resistive, "TF joints resisitive heating ", "MW"),
        ]

    plot_info(axis, data, mfile, scan)

plot_power_info(axis, mfile, scan)

Function to plot power info

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
def plot_power_info(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot power info

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """

    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1

    axis.text(-0.05, 1, "Power flows:", ha="left", va="center")
    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    gross_eff = 100.0 * (
        mfile.get("p_plant_electric_gross_mw", scan=scan)
        / mfile.get("p_plant_primary_heat_mw", scan=scan)
    )

    net_eff = 100.0 * (
        (
            mfile.get("p_plant_electric_gross_mw", scan=scan)
            - mfile.get("p_coolant_pump_elec_total_mw", scan=scan)
        )
        / (
            mfile.get("p_plant_primary_heat_mw", scan=scan)
            - mfile.get("p_coolant_pump_elec_total_mw", scan=scan)
        )
    )

    plant_eff = 100.0 * (
        mfile.get("p_plant_electric_net_mw", scan=scan)
        / mfile.get("p_fusion_total_mw", scan=scan)
    )

    # Define appropriate pedestal and impurity parameters
    coredescription = (
        "radius_plasma_core_norm",
        "Normalised radius of 'core' region",
        "",
    )
    if mfile.get("i_plasma_pedestal", scan=scan) == 1:
        ped_height = (
            "nd_plasma_pedestal_electron",
            "Electron density at pedestal",
            "m$^{-3}$",
        )
        ped_pos = ("radius_plasma_pedestal_density_norm", "r/a at density pedestal", "")
    else:
        ped_height = ("", "No pedestal model used", "")
        ped_pos = ("", "", "")

    p_cryo_plant_electric_mw = mfile.get("p_cryo_plant_electric_mw", scan=scan)

    data = [
        ("pflux_fw_neutron_mw", "Nominal neutron wall load", "MW m$^{-2}$"),
        coredescription,
        ped_height,
        ped_pos,
        ("p_plasma_inner_rad_mw", "Inner zone radiation", "MW"),
        ("p_plasma_rad_mw", "Total radiation in LCFS", "MW"),
        ("p_blkt_nuclear_heat_total_mw", "Nuclear heating in blanket", "MW"),
        ("p_shld_nuclear_heat_mw", "Nuclear heating in shield", "MW"),
        (p_cryo_plant_electric_mw, "TF cryogenic power", "MW"),
        ("p_plasma_separatrix_mw", "Power to divertor", "MW"),
        ("life_div_fpy", "Divertor life", "years"),
        ("p_plant_primary_heat_mw", "Primary (high grade) heat", "MW"),
        (gross_eff, "Gross cycle efficiency", "%"),
        (net_eff, "Net cycle efficiency", "%"),
        ("p_plant_electric_gross_mw", "Gross electric power", "MW"),
        ("p_plant_electric_net_mw", "Net electric power", "MW"),
        (
            plant_eff,
            r"Fusion-to-electric efficiency $\frac{P_{\mathrm{e,net}}}{P_{\mathrm{fus}}}$",
            "%",
        ),
    ]

    plot_info(axis, data, mfile, scan)

plot_current_drive_info(axis, mfile, scan)

Function to plot current drive info

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
def plot_current_drive_info(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot current drive info

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    """

    xmin = 0
    xmax = 1
    ymin = -16
    ymax = 1
    i_hcd_primary = mfile.get("i_hcd_primary", scan=scan)
    nbi = False
    ecrh = False
    ebw = False
    lhcd = False
    iccd = False

    if (i_hcd_primary == 5) or (i_hcd_primary == 8):
        nbi = True
        axis.text(-0.05, 1, "Neutral Beam Current Drive:", ha="left", va="center")
    if (
        (i_hcd_primary == 3)
        or (i_hcd_primary == 7)
        or (i_hcd_primary == 10)
        or (i_hcd_primary == 11)
        or (i_hcd_primary == 13)
    ):
        ecrh = True
        axis.text(-0.05, 1, "Electron Cyclotron Current Drive:", ha="left", va="center")
    if i_hcd_primary == 12:
        ebw = True
        axis.text(-0.05, 1, "Electron Bernstein Wave Drive:", ha="left", va="center")
    if i_hcd_primary in [1, 4, 6]:
        lhcd = True
        axis.text(
            -0.05,
            1,
            "Lower Hybrid Current Drive:",
            ha="left",
            va="center",
        )
    if i_hcd_primary == 2:
        iccd = True
        axis.text(-0.05, 1, "Ion Cyclotron Current Drive:", ha="left", va="center")

    if "i_hcd_secondary" in mfile.data:
        secondary_heating = ""
        i_hcd_secondary = mfile.get("i_hcd_secondary", scan=scan)

        if (i_hcd_secondary == 5) or (i_hcd_secondary == 8):
            secondary_heating = "NBI"
        if (
            (i_hcd_secondary == 3)
            or (i_hcd_secondary == 7)
            or (i_hcd_secondary == 10)
            or (i_hcd_secondary == 11)
            or (i_hcd_secondary == 13)
        ):
            secondary_heating = "ECH"
        if i_hcd_secondary == 12:
            secondary_heating = "EBW"
        if i_hcd_secondary in [1, 4, 6]:
            secondary_heating = "LHCD"
        if i_hcd_secondary == 2:
            secondary_heating = "ICCD"

    axis.set_ylim([ymin, ymax])
    axis.set_xlim([xmin, xmax])
    axis.set_axis_off()
    axis.set_autoscaley_on(False)
    axis.set_autoscalex_on(False)

    pinjie = mfile.get("p_hcd_injected_total_mw", scan=scan)
    p_plasma_separatrix_mw = mfile.get("p_plasma_separatrix_mw", scan=scan)
    pdivr = p_plasma_separatrix_mw / mfile.get("rmajor", scan=scan)

    if mfile.get("i_hcd_secondary", scan=scan) != 0:
        pinjmwfix = mfile.get("pinjmwfix", scan=scan)

    pdivnr = (
        1.0e20
        * mfile.get("p_plasma_separatrix_mw", scan=scan)
        / (
            mfile.get("rmajor", scan=scan)
            * mfile.get("nd_plasma_electrons_vol_avg", scan=scan)
        )
    )

    # Assume Martin scaling if pthresh is not printed
    # Accounts for pthresh not being written prior to issue #679 and #680
    if "p_l_h_threshold_mw" in mfile.data:
        pthresh = mfile.get("p_l_h_threshold_mw", scan=scan)
    else:
        pthresh = mfile.get("l_h_threshold_powers(6)", scan=scan)
    flh = p_plasma_separatrix_mw / pthresh

    hstar = mfile.get("hstar", scan=scan)

    if ecrh:
        data = [
            (pinjie, "Steady state auxiliary power", "MW"),
            ("p_hcd_primary_extra_heat_mw", "Power for heating only", "MW"),
            ("f_c_plasma_bootstrap", "Bootstrap fraction", ""),
            ("f_c_plasma_auxiliary", "Auxiliary fraction", ""),
            ("f_c_plasma_inductive", "Inductive fraction", ""),
            ("p_plasma_loss_mw", "Plasma heating used for H factor", "MW"),
            (
                "eta_cd_hcd_primary",
                "Current drive efficiency",
                "A W$^{-1}$",
            ),
            (pdivr, r"$\frac{P_{\mathrm{div}}}{R_{0}}$", "MW m$^{-1}$"),
            (
                pdivnr,
                r"$\frac{P_{\mathrm{div}}}{\langle n \rangle R_{0}}$",
                r"$\times 10^{-20}$ MW m$^{2}$",
            ),
            (flh, r"$\frac{P_{\mathrm{div}}}{P_{\mathrm{LH}}}$", ""),
            (hstar, "H* (non-rad. corr.)", ""),
        ]
        # i_hcd_secondary is now always in the MFILE with = 0 meaning no fixed heating
        if mfile.get("i_hcd_secondary", scan=scan) != 0:
            data.insert(
                1, ("pinjmwfix", f"{secondary_heating} secondary auxiliary power", "MW")
            )
            data[0] = ((pinjie - pinjmwfix), "Primary auxiliary power", "MW")
            data.insert(2, (pinjie, "Total auxillary power", "MW"))

    if nbi:
        data = [
            (pinjie, "Steady state auxiliary power", "MW"),
            ("p_hcd_primary_extra_heat_mw", "Power for heating only", "MW"),
            ("f_c_plasma_bootstrap", "Bootstrap fraction", ""),
            ("f_c_plasma_auxiliary", "Auxiliary fraction", ""),
            ("f_c_plasma_inductive", "Inductive fraction", ""),
            ("gamnb", "NB gamma", "$10^{20}$ A W$^{-1}$ m$^{-2}$"),
            ("e_beam_kev", "NB energy", "keV"),
            ("p_plasma_loss_mw", "Plasma heating used for H factor", "MW"),
            (pdivr, r"$\frac{P_{\mathrm{div}}}{R_{0}}$", "MW m$^{-1}$"),
            (
                pdivnr,
                r"$\frac{P_{\mathrm{div}}}{\langle n \rangle R_{0}}$",
                r"$\times 10^{-20}$ MW m$^{2}$",
            ),
            (flh, r"$\frac{P_{\mathrm{div}}}{P_{\mathrm{LH}}}$", ""),
            (hstar, "H* (non-rad. corr.)", ""),
        ]
        if mfile.get("i_hcd_secondary", scan=scan) != 0:
            data.insert(
                1, ("pinjmwfix", f"{secondary_heating} secondary auxiliary power", "MW")
            )
            data[0] = ((pinjie - pinjmwfix), "Primary auxiliary power", "MW")
            data.insert(2, (pinjie, "Total auxillary power", "MW"))

    if ebw:
        data = [
            (pinjie, "Steady state auxiliary power", "MW"),
            ("p_hcd_primary_extra_heat_mw", "Power for heating only", "MW"),
            ("f_c_plasma_bootstrap", "Bootstrap fraction", ""),
            ("f_c_plasma_auxiliary", "Auxiliary fraction", ""),
            ("f_c_plasma_inductive", "Inductive fraction", ""),
            ("p_plasma_loss_mw", "Plasma heating used for H factor", "MW"),
            (
                "eta_cd_norm_hcd_primary",
                "Normalised current drive efficiency of primary HCD system",
                "(10$^{20}$ A/(Wm$^{2}$))",
            ),
            (pdivr, r"$\frac{P_{\mathrm{div}}}{R_{0}}$", "MW m$^{-1}$"),
            (
                pdivnr,
                r"$\frac{P_{\mathrm{div}}}{\langle n \rangle R_{0}}$",
                r"$\times 10^{-20}$ MW m$^{2}$",
            ),
            (flh, r"$\frac{P_{\mathrm{div}}}{P_{\mathrm{LH}}}$", ""),
            (hstar, "H* (non-rad. corr.)", ""),
        ]
        if "i_hcd_secondary" in mfile.data:
            data.insert(
                1, ("pinjmwfix", f"{secondary_heating} secondary auxiliary power", "MW")
            )
            data[0] = ((pinjie - pinjmwfix), "Primary auxiliary power", "MW")
            data.insert(2, (pinjie, "Total auxillary power", "MW"))

    if lhcd:
        data = [
            (pinjie, "Steady state auxiliary power", "MW"),
            ("p_hcd_primary_extra_heat_mw", "Power for heating only", "MW"),
            ("f_c_plasma_bootstrap", "Bootstrap fraction", ""),
            ("f_c_plasma_auxiliary", "Auxiliary fraction", ""),
            ("f_c_plasma_inductive", "Inductive fraction", ""),
            ("p_plasma_loss_mw", "Plasma heating used for H factor", "MW"),
            (
                "eta_cd_norm_hcd_primary",
                "Normalised current drive efficiency",
                "(10$^{20}$ A/(Wm$^{2}$))",
            ),
            (pdivr, r"$\frac{P_{\mathrm{div}}}{R_{0}}$", "MW m$^{-1}$"),
            (
                pdivnr,
                r"$\frac{P_{\mathrm{div}}}{\langle n \rangle R_{0}}$",
                r"$\times 10^{-20}$ MW m$^{2}$",
            ),
            (flh, r"$\frac{P_{\mathrm{div}}}{P_{\mathrm{LH}}}$", ""),
            (hstar, "H* (non-rad. corr.)", ""),
        ]
        if "i_hcd_secondary" in mfile.data:
            data.insert(
                1, ("pinjmwfix", f"{secondary_heating} secondary auxiliary power", "MW")
            )
            data[0] = ((pinjie - pinjmwfix), "Primary auxiliary power", "MW")
            data.insert(2, (pinjie, "Total auxillary power", "MW"))

    if iccd:
        data = [
            (pinjie, "Steady state auxiliary power", "MW"),
            ("p_hcd_primary_extra_heat_mw", "Power for heating only", "MW"),
            ("f_c_plasma_bootstrap", "Bootstrap fraction", ""),
            ("f_c_plasma_auxiliary", "Auxiliary fraction", ""),
            ("f_c_plasma_inductive", "Inductive fraction", ""),
            ("p_plasma_loss_mw", "Plasma heating used for H factor", "MW"),
            (
                "eta_cd_norm_hcd_primary",
                "Normalised current drive efficiency",
                "(10$^{20}$ A/(Wm$^{2}$))",
            ),
            (pdivr, r"$\frac{P_{\mathrm{div}}}{R_{0}}$", "MW m$^{-1}$"),
            (
                pdivnr,
                r"$\frac{P_{\mathrm{div}}}{\langle n \rangle R_{0}}$",
                r"$\times 10^{-20}$ MW m$^{2}$",
            ),
            (flh, r"$\frac{P_{\mathrm{div}}}{P_{\mathrm{LH}}}$", ""),
            (hstar, "H* (non-rad. corr.)", ""),
        ]
        if "i_hcd_secondary" in mfile.data:
            data.insert(
                1, ("pinjmwfix", f"{secondary_heating} secondary auxiliary power", "MW")
            )
            data[0] = ((pinjie - pinjmwfix), "Primary auxiliary power", "MW")
            data.insert(2, (pinjie, "Total auxillary power", "MW"))

    coe = mfile.get("coe", scan=scan)
    if coe == 0.0:
        data.append(("", "", ""))
        data.append(("#Costs", "", ""))
        data.append(("", "Cost output not selected", ""))
    else:
        data.append(("", "", ""))
        data.append(("#Costs", "", ""))
        data.append((coe, "Cost of electricity", r"\$/MWh"))

    plot_info(axis, data, mfile, scan)

plot_bootstrap_comparison(axis, mfile, scan)

Function to plot a scatter box plot of bootstrap current fractions.

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE data object

required
scan int

scan number to use

required
Source code in process/core/io/plot_proc.py
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
def plot_bootstrap_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot a scatter box plot of bootstrap current fractions.

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE data object
    scan :
        scan number to use
    """

    boot_ipdg = mfile.get("f_c_plasma_bootstrap_iter89", scan=scan)
    boot_sauter = mfile.get("f_c_plasma_bootstrap_sauter", scan=scan)
    boot_nenins = mfile.get("f_c_plasma_bootstrap_nevins", scan=scan)
    boot_wilson = mfile.get("f_c_plasma_bootstrap_wilson", scan=scan)
    boot_sakai = mfile.get("f_c_plasma_bootstrap_sakai", scan=scan)
    boot_aries = mfile.get("f_c_plasma_bootstrap_aries", scan=scan)
    boot_andrade = mfile.get("f_c_plasma_bootstrap_andrade", scan=scan)
    boot_hoang = mfile.get("f_c_plasma_bootstrap_hoang", scan=scan)
    boot_wong = mfile.get("f_c_plasma_bootstrap_wong", scan=scan)
    boot_gi_I = mfile.get("bscf_gi_i", scan=scan)  # noqa: N806
    boot_gi_II = mfile.get("bscf_gi_ii", scan=scan)  # noqa: N806
    boot_sugiyama_l = mfile.get("f_c_plasma_bootstrap_sugiyama_l", scan=scan)
    boot_sugiyama_h = mfile.get("f_c_plasma_bootstrap_sugiyama_h", scan=scan)

    # Data for the box plot
    data = {
        "IPDG": boot_ipdg,
        "Sauter": boot_sauter,
        "Nevins": boot_nenins,
        "Wilson": boot_wilson,
        "Sakai": boot_sakai,
        "ARIES": boot_aries,
        "Andrade": boot_andrade,
        "Hoang": boot_hoang,
        "Wong": boot_wong,
        "Gi-I": boot_gi_I,
        "Gi-II": boot_gi_II,
        "Sugiyama (L-mode)": boot_sugiyama_l,
        "Sugiyama (H-mode)": boot_sugiyama_h,
    }
    # Create the violin plot
    axis.violinplot(data.values(), showextrema=False)

    # Create the box plot
    axis.boxplot(
        data.values(), showfliers=True, showmeans=True, meanline=True, widths=0.3
    )

    # Scatter plot for each data point
    colors = plt.cm.plasma(np.linspace(0, 1, len(data.values())))
    for index, (key, value) in enumerate(data.items()):
        axis.scatter(1, value, color=colors[index], label=key, alpha=1.0)
    axis.legend(loc="upper left", bbox_to_anchor=(1, 1))

    # Calculate average, standard deviation, and median
    data_values = list(data.values())
    avg_bootstrap = np.mean(data_values)
    std_bootstrap = np.std(data_values)
    median_bootstrap = np.median(data_values)

    # Plot average, standard deviation, and median as text
    axis.text(
        1.02, 0.2, f"Average: {avg_bootstrap:.4f}", transform=axis.transAxes, fontsize=9
    )
    axis.text(
        1.02,
        0.15,
        f"Standard Dev: {std_bootstrap:.4f}",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        1.02,
        0.1,
        f"Median: {median_bootstrap:.4f}",
        transform=axis.transAxes,
        fontsize=9,
    )

    axis.set_title("Bootstrap Current Fraction Comparison")
    axis.set_ylabel("Bootstrap Current Fraction")
    axis.set_xlim([0.5, 1.5])
    axis.set_xticks([])
    axis.set_xticklabels([])
    axis.set_facecolor("#f0f0f0")

plot_h_threshold_comparison(axis, mfile, scan, u_seed=None)

Function to plot a scatter box plot of L-H threshold power comparisons.

Parameters:

Name Type Description Default
axis Axes

Axis object to plot to.

required
mfile MFile

MFILE data object.

required
scan int

Scan number to use.

required
u_seed

(Default value = None)

None
Source code in process/core/io/plot_proc.py
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
def plot_h_threshold_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int, u_seed=None):
    """Function to plot a scatter box plot of L-H threshold power comparisons.

    Parameters
    ----------
    axis :
        Axis object to plot to.
    mfile :
         MFILE data object.
    scan :
        Scan number to use.
    u_seed :
         (Default value = None)
    """
    iter_nominal = mfile.get("l_h_threshold_powers(1)", scan=scan)
    iter_upper = mfile.get("l_h_threshold_powers(2)", scan=scan)
    iter_lower = mfile.get("l_h_threshold_powers(3)", scan=scan)
    iter_1997_1 = mfile.get("l_h_threshold_powers(4)", scan=scan)
    iter_1997_2 = mfile.get("l_h_threshold_powers(5)", scan=scan)
    martin_nominal = mfile.get("l_h_threshold_powers(6)", scan=scan)
    martin_upper = mfile.get("l_h_threshold_powers(7)", scan=scan)
    martin_lower = mfile.get("l_h_threshold_powers(8)", scan=scan)
    snipes_nominal = mfile.get("l_h_threshold_powers(9)", scan=scan)
    snipes_upper = mfile.get("l_h_threshold_powers(10)", scan=scan)
    snipes_lower = mfile.get("l_h_threshold_powers(11)", scan=scan)
    snipes_closed_nominal = mfile.get("l_h_threshold_powers(12)", scan=scan)
    snipes_closed_upper = mfile.get("l_h_threshold_powers(13)", scan=scan)
    snipes_closed_lower = mfile.get("l_h_threshold_powers(14)", scan=scan)
    hubbard_nominal = mfile.get("l_h_threshold_powers(15)", scan=scan)
    hubbard_lower = mfile.get("l_h_threshold_powers(16)", scan=scan)
    hubbard_upper = mfile.get("l_h_threshold_powers(17)", scan=scan)
    hubbard_2017 = mfile.get("l_h_threshold_powers(18)", scan=scan)
    martin_aspect_nominal = mfile.get("l_h_threshold_powers(19)", scan=scan)
    martin_aspect_upper = mfile.get("l_h_threshold_powers(20)", scan=scan)
    martin_aspect_lower = mfile.get("l_h_threshold_powers(21)", scan=scan)

    # Data for the box plot
    data = {
        "ITER 1996 Nominal": iter_nominal,
        "ITER 1996 Upper": iter_upper,
        "ITER 1996 Lower": iter_lower,
        "ITER 1997 (1)": iter_1997_1,
        "ITER 1997 (2)": iter_1997_2,
        "Martin Nominal": martin_nominal,
        "Martin Upper": martin_upper,
        "Martin Lower": martin_lower,
        "Snipes Nominal": snipes_nominal,
        "Snipes Upper": snipes_upper,
        "Snipes Lower": snipes_lower,
        "Snipes Closed Divertor Nominal": snipes_closed_nominal,
        "Snipes Closed Divertor Upper": snipes_closed_upper,
        "Snipes Closed Divertor Lower": snipes_closed_lower,
        "Hubbard Nominal (I-mode)": hubbard_nominal,
        "Hubbard Lower (I-mode)": hubbard_lower,
        "Hubbard Upper (I-mode)": hubbard_upper,
        "Hubbard 2017 (I-mode)": hubbard_2017,
        "Martin Aspect Corrected Nominal": martin_aspect_nominal,
        "Martin Aspect Corrected Upper": martin_aspect_upper,
        "Martin Aspect Corrected Lower": martin_aspect_lower,
    }

    # Create the violin plot
    axis.violinplot(data.values(), showextrema=False)

    # Create the box plot
    axis.boxplot(
        data.values(), showfliers=True, showmeans=True, meanline=True, widths=0.3
    )

    # Scatter plot for each data point
    colors = plt.cm.plasma(np.linspace(0, 1, len(data.values())))
    generator = np.random.default_rng(seed=u_seed)
    x_values = generator.normal(loc=1, scale=0.01, size=len(data.values()))
    for index, (key, value) in enumerate(data.items()):
        if "ITER 1996" in key:
            color = "blue"
        elif "ITER 1997" in key:
            color = "cyan"
        elif "Martin" in key and "Aspect" not in key:
            color = "green"
        elif "Snipes" in key and "Closed" not in key:
            color = "red"
        elif "Snipes Closed" in key:
            color = "orange"
        elif "Martin Aspect" in key:
            color = "yellow"
        elif "Hubbard" in key and "2017" not in key:
            color = "purple"
        elif "Hubbard 2017" in key:
            color = "magenta"
        else:
            color = colors[index]
        axis.scatter(x_values[index], value, color=color, label=key, alpha=1.0)
        axis.legend(loc="upper left", bbox_to_anchor=(-1.1, 1), ncol=2)

    # Calculate average, standard deviation, and median
    data_values = list(data.values())
    avg_threshold = np.mean(data_values)
    std_threshold = np.std(data_values)
    median_threshold = np.median(data_values)

    # Plot average, standard deviation, and median as text
    axis.text(
        -0.45,
        0.15,
        f"Average: {avg_threshold:.4f}",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        -0.45,
        0.1,
        f"Standard Dev: {std_threshold:.4f}",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        -0.45,
        0.05,
        f"Median: {median_threshold:.4f}",
        transform=axis.transAxes,
        fontsize=9,
    )

    axis.set_title("L-H Threshold Comparison")
    axis.set_ylabel("L-H threshold power [MW]")
    axis.set_xlim([0.5, 1.5])
    axis.set_xticks([])
    axis.set_xticklabels([])

    # Add background color
    axis.set_facecolor("#f0f0f0")

plot_confinement_time_comparison(axis, mfile, scan, u_seed=None)

Function to plot a scatter box plot of confinement time comparisons.

Parameters:

Name Type Description Default
axis Axes

Axis object to plot to.

required
mfile MFile

MFILE data object.

required
scan int

Scan number to use.

required
u_seed

(Default value = None)

None
Source code in process/core/io/plot_proc.py
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
def plot_confinement_time_comparison(
    axis: plt.Axes, mfile: mf.MFile, scan: int, u_seed=None
):
    """Function to plot a scatter box plot of confinement time comparisons.

    Parameters
    ----------
    axis :
        Axis object to plot to.
    mfile :
         MFILE data object.
    scan :
        Scan number to use.
    u_seed :
         (Default value = None)
    """
    rminor = mfile.get("rminor", scan=scan)
    rmajor = mfile.get("rmajor", scan=scan)
    c_plasma_ma = mfile.get("plasma_current_ma", scan=scan)
    kappa95 = mfile.get("kappa95", scan=scan)
    dnla20 = mfile.get("nd_plasma_electron_line", scan=scan) / 1e20
    afuel = mfile.get("m_fuel_amu", scan=scan)
    b_plasma_toroidal_on_axis = mfile.get("b_plasma_toroidal_on_axis", scan=scan)
    p_plasma_separatrix_mw = mfile.get("p_plasma_separatrix_mw", scan=scan)
    kappa = mfile.get("kappa", scan=scan)
    aspect = mfile.get("aspect", scan=scan)
    dnla19 = mfile.get("nd_plasma_electron_line", scan=scan) / 1e19
    kappa_ipb = mfile.get("kappa_ipb", scan=scan)
    triang = mfile.get("triang", scan=scan)
    m_ions_total_amu = mfile.get("m_ions_total_amu", scan=scan)

    # Calculate confinement times using the scan data
    iter_89p = confine.iter_89p_confinement_time(
        pcur=c_plasma_ma,
        rmajor=rmajor,
        rminor=rminor,
        kappa=kappa,
        dnla20=dnla20,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        afuel=afuel,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
    )
    iter_89_0 = confine.iter_89_0_confinement_time(
        pcur=c_plasma_ma,
        rmajor=rmajor,
        rminor=rminor,
        kappa=kappa,
        dnla20=dnla20,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        afuel=afuel,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
    )
    iter_h90_p = confine.iter_h90_p_confinement_time(
        pcur=c_plasma_ma,
        rmajor=rmajor,
        rminor=rminor,
        kappa=kappa,
        dnla20=dnla20,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        afuel=afuel,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
    )
    iter_h90_p_amended = confine.iter_h90_p_amended_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        afuel=afuel,
        rmajor=rmajor,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        kappa=kappa,
    )
    iter_93h = confine.iter_93h_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        afuel=afuel,
        rmajor=rmajor,
        dnla20=dnla20,
        aspect=aspect,
        kappa=kappa,
    )
    iter_h97p = confine.iter_h97p_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        dnla19=dnla19,
        rmajor=rmajor,
        aspect=aspect,
        kappa=kappa,
        afuel=afuel,
    )
    iter_h97p_elmy = confine.iter_h97p_elmy_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        dnla19=dnla19,
        rmajor=rmajor,
        aspect=aspect,
        kappa=kappa,
        afuel=afuel,
    )
    iter_96p = confine.iter_96p_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        kappa95=kappa95,
        rmajor=rmajor,
        aspect=aspect,
        dnla19=dnla19,
        afuel=afuel,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
    )
    iter_pb98py = confine.iter_pb98py_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa=kappa,
        aspect=aspect,
        afuel=afuel,
    )
    iter_ipb98y = confine.iter_ipb98y_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa=kappa,
        aspect=aspect,
        afuel=afuel,
    )
    iter_ipb98y1 = confine.iter_ipb98y1_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    iter_ipb98y2 = confine.iter_ipb98y2_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    iter_ipb98y3 = confine.iter_ipb98y3_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    iter_ipb98y4 = confine.iter_ipb98y4_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    petty08 = confine.petty08_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
    )
    menard_nstx = confine.menard_nstx_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    menard_nstx_petty08 = confine.menard_nstx_petty08_hybrid_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        kappa_ipb=kappa_ipb,
        aspect=aspect,
        afuel=afuel,
    )
    itpa20 = confine.itpa20_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        dnla19=dnla19,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        rmajor=rmajor,
        triang=triang,
        kappa_ipb=kappa_ipb,
        eps=(1 / aspect),
        aion=m_ions_total_amu,
    )
    itpa20_ilc = confine.itpa20_il_confinement_time(
        pcur=c_plasma_ma,
        b_plasma_toroidal_on_axis=b_plasma_toroidal_on_axis,
        p_plasma_loss_mw=p_plasma_separatrix_mw,
        dnla19=dnla19,
        aion=m_ions_total_amu,
        rmajor=rmajor,
        triang=triang,
        kappa_ipb=kappa_ipb,
    )

    # Data for the box plot
    data = {
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[6]}": iter_89p,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[7]}": iter_89_0,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[13]}": iter_h90_p,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[20]}": iter_h90_p_amended,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[24]}": iter_93h,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[26]}": iter_h97p,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[27]}": iter_h97p_elmy,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[28]}": iter_96p,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[31]}": iter_pb98py,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[32]}": iter_ipb98y,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[33]}": iter_ipb98y1,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[34]}": iter_ipb98y2,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[35]}": iter_ipb98y3,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[36]}": iter_ipb98y4,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[41]}": petty08,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[46]}": menard_nstx,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[47]}": menard_nstx_petty08,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[49]}": itpa20,
        rf"{physics_variables.LABELS_CONFINEMENT_SCALINGS[50]}": itpa20_ilc,
    }

    # Create the violin plot
    axis.violinplot(data.values(), showextrema=False)

    # Create the box plot
    axis.boxplot(
        data.values(), showfliers=True, showmeans=True, meanline=True, widths=0.3
    )

    # Scatter plot for each data point
    # Use a set of distinct colors for better differentiation
    distinct_colors = [
        "#1f77b4",  # blue
        "#ff7f0e",  # orange
        "#2ca02c",  # green
        "#d62728",  # red
        "#9467bd",  # purple
        "#8c564b",  # brown
        "#e377c2",  # pink
        "#7f7f7f",  # gray
        "#bcbd22",  # olive
        "#17becf",  # cyan
        "#aec7e8",  # light blue
        "#ffbb78",  # light orange
        "#98df8a",  # light green
        "#ff9896",  # light red
        "#c5b0d5",  # light purple
        "#c49c94",  # light brown
        "#f7b6d2",  # light pink
        "#c7c7c7",  # light gray
        "#dbdb8d",  # light olive
        "#9edae5",  # light cyan
    ]
    generator = np.random.default_rng(seed=u_seed)
    x_values = generator.normal(loc=1, scale=0.035, size=len(data.values()))
    for index, (key, value) in enumerate(data.items()):
        if "Hubbard" in key and "2017" not in key:
            color = "#800080"  # strong purple
        else:
            color = distinct_colors[index % len(distinct_colors)]
        axis.scatter(
            x_values[index],
            value,
            color=color,
            label=key,
            alpha=1.0,
            edgecolor="black",
            linewidth=0.7,
        )
    axis.legend(loc="upper left", bbox_to_anchor=(-1.3, 0.75), ncol=2)

    # Calculate average, standard deviation, and median
    data_values = list(data.values())
    avg_threshold = np.mean(data_values)
    std_threshold = np.std(data_values)
    median_threshold = np.median(data_values)

    # Plot average, standard deviation, and median as text
    axis.text(
        0.7,
        1.25,
        f"Average: {avg_threshold:.4f} s",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        0.7,
        1.2,
        f"Standard Dev: {std_threshold:.4f} s",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        0.7,
        1.15,
        f"Median: {median_threshold:.4f} s",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        0.75,
        -0.05,
        r"$H \ factor = 1.0$",
        transform=axis.transAxes,
        fontsize=9,
    )

    axis.set_title("Confinement time ($\\tau_{\\text{E}}$) Comparison")
    axis.set_ylabel("Confinement time, $\\tau_{\\text{E}}$ [s]")
    axis.set_xlim([0.5, 1.5])
    axis.set_xticks([])
    axis.set_xticklabels([])

    # Add background color
    axis.set_facecolor("#f0f0f0")

plot_radial_build(axis, mfile, colour_scheme)

Plots the radial build of a fusion device on the given matplotlib axis.

This function visualizes the different layers/components of the machine's radial build (such as central solenoid, toroidal field coils, vacuum vessel, shields, blankets, etc.) as a horizontal stacked bar chart. The thickness of each layer is extracted from the provided mfile, and each segment is color-coded and labeled accordingly.

If the toroidal field coil is inside the central solenoid (as indicated by the "i_tf_inside_cs" flag in mfile), the order and labels of the components are adjusted accordingly.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis on which to plot the radial build.

required
mfile MFile

An object containing the machine build data, with required fields for each radial component and the "i_tf_inside_cs" flag.

required
colour_scheme Literal[1, 2]
required
Notes

This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component.

Source code in process/core/io/plot_proc.py
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
def plot_radial_build(axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2]):
    """Plots the radial build of a fusion device on the given matplotlib axis.

    This function visualizes the different layers/components of the machine's radial build
    (such as central solenoid, toroidal field coils, vacuum vessel, shields, blankets, etc.)
    as a horizontal stacked bar chart. The thickness of each layer is extracted from the
    provided `mfile`, and each segment is color-coded and labeled accordingly.

    If the toroidal field coil is inside the central solenoid (as indicated by the
    "i_tf_inside_cs" flag in `mfile`), the order and labels of the components are
    adjusted accordingly.

    Parameters
    ----------
    axis : matplotlib.axes.Axes
        The matplotlib axis on which to plot the radial build.
    mfile : mf.MFile
        An object containing the machine build data, with required fields for each
        radial component and the "i_tf_inside_cs" flag.
    colour_scheme:

    Notes
    -----
    This function modifies the provided axis in-place and does not return a value.
    - Components with zero thickness are omitted from the plot.
    - The legend displays the name and thickness (in meters) of each component.
    """
    radial_variables = [
        "dr_bore",
        "dr_cs",
        "dr_cs_precomp",
        "dr_cs_tf_gap",
        "dr_tf_inboard",
        "dr_tf_shld_gap",
        "dr_shld_thermal_inboard",
        "dr_shld_vv_gap_inboard",
        "dr_vv_inboard",
        "dr_shld_inboard",
        "dr_shld_blkt_gap",
        "dr_blkt_inboard",
        "dr_fw_inboard",
        "dr_fw_plasma_gap_inboard",
        "rminor",
        "dr_fw_plasma_gap_outboard",
        "dr_fw_outboard",
        "dr_blkt_outboard",
        "dr_shld_blkt_gap",
        "dr_vv_outboard",
        "dr_shld_outboard",
        "dr_shld_vv_gap_outboard",
        "dr_shld_thermal_outboard",
        "dr_tf_shld_gap",
        "dr_tf_outboard",
    ]
    if int(mfile.get("i_tf_inside_cs", scan=-1)) == 1:
        radial_variables[1] = "dr_tf_inboard"
        radial_variables[2] = "dr_cs_tf_gap"
        radial_variables[3] = "dr_cs"
        radial_variables[4] = "dr_cs_precomp"
        radial_variables[5] = "dr_tf_shld_gap"

    radial_build = [[mfile.get(rl, scan=-1) for rl in radial_variables]]

    radial_build = np.array(radial_build)

    for kk in range(radial_build.shape[0]):
        radial_build[kk, 14] = 2.0 * radial_build[kk, 14]

    radial_build = np.transpose(radial_build)
    # ====================

    radial_labels = [
        "Machine Bore",
        "Central Solenoid",
        "CS precompression",
        "CS Coil gap",
        "TF Coil Inboard Leg",
        "TF Coil gap",
        "Inboard Thermal Shield",
        "Gap",
        "Inboard VV",
        "Inboard Shield",
        "Gap",
        "Inboard Blanket",
        "Inboard First Wall",
        "Inboard SOL",
        "Plasma",
        "Outboard SOL",
        "Outboard First Wall",
        "Outboard Blanket",
        "Gap",
        "Outboard VV",
        "Outboard Shield",
        "Gap",
        "Outboard Thermal Shield",
        "Gap",
        "TF Coil Outboard Leg",
    ]
    if int(mfile.get("i_tf_inside_cs", scan=-1)) == 1:
        radial_labels[1] = "TF Coil Inboard Leg"
        radial_labels[2] = "CS Coil gap"
        radial_labels[3] = "Central Solenoid"
        radial_labels[4] = "CS precompression"
        radial_labels[5] = "TF Coil gap"

    radial_color = [
        "white",
        SOLENOID_COLOUR[colour_scheme - 1],
        CSCOMPRESSION_COLOUR[colour_scheme - 1],
        "white",
        TFC_COLOUR[colour_scheme - 1]
        if mfile.get("i_tf_sup", scan=-1) != 0
        else "#b87333",
        "white",
        THERMAL_SHIELD_COLOUR[colour_scheme - 1],
        "white",
        VESSEL_COLOUR[colour_scheme - 1],
        SHIELD_COLOUR[colour_scheme - 1],
        "white",
        BLANKET_COLOUR[colour_scheme - 1],
        FIRSTWALL_COLOUR[colour_scheme - 1],
        "white",
        PLASMA_COLOUR[colour_scheme - 1],
        "white",
        FIRSTWALL_COLOUR[colour_scheme - 1],
        BLANKET_COLOUR[colour_scheme - 1],
        "white",
        VESSEL_COLOUR[colour_scheme - 1],
        SHIELD_COLOUR[colour_scheme - 1],
        "white",
        THERMAL_SHIELD_COLOUR[colour_scheme - 1],
        "white",
        TFC_COLOUR[colour_scheme - 1]
        if mfile.get("i_tf_sup", scan=-1) != 0
        else "#b87333",
    ]
    if int(mfile.get("i_tf_inside_cs", scan=-1)) == 1:
        radial_color[1] = (
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=-1) != 0
            else "#b87333"
        )
        radial_color[2] = "white"
        radial_color[3] = SOLENOID_COLOUR[colour_scheme - 1]
        radial_color[4] = CSCOMPRESSION_COLOUR[colour_scheme - 1]
        radial_color[5] = "white"

    lower = np.zeros(radial_build.shape[1])
    for kk in range(radial_build.shape[0]):
        axis.barh(
            0,
            radial_build[kk, :],
            left=lower,
            height=0.8,
            label=f"{radial_labels[kk]}\n[{radial_variables[kk]}]\n{radial_build[kk][0]:.3f} m",
            color=radial_color[kk],
            edgecolor="black",
            linewidth=0.05,
        )
        lower += radial_build[kk, :]

    axis.set_yticks([])

    axis.legend(
        bbox_to_anchor=(0.5, -0.1),
        loc="upper center",
        ncol=5,
    )
    # Plot a vertical dashed line at rmajor
    axis.axvline(
        mfile.get("rmajor", scan=-1),
        color="black",
        linestyle="--",
        linewidth=1.2,
        label="Major Radius $R_0$",
    )
    axis.minorticks_on()
    axis.set_xlabel("Radius [m]")

plot_lower_vertical_build(axis, mfile, colour_scheme)

Plots the lower vertical build of a fusion device on the given matplotlib axis.

This function visualizes the different layers/components of the machine's vertical build (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.) as a vertical stacked bar chart. The thickness of each layer is extracted from the provided mfile, and each segment is color-coded and labeled accordingly.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis on which to plot the vertical build.

required
mfile MFile

An object containing the machine build data, with required fields for each vertical component.

required
colour_scheme Literal[1, 2]

Colour scheme index to use for component colors.

required
Notes

This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component.

Source code in process/core/io/plot_proc.py
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
def plot_lower_vertical_build(
    axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2]
):
    """Plots the lower vertical build of a fusion device on the given matplotlib axis.

    This function visualizes the different layers/components of the machine's vertical build
    (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.)
    as a vertical stacked bar chart. The thickness of each layer is extracted from the
    provided `mfile`, and each segment is color-coded and labeled accordingly.

    Parameters
    ----------
    axis :
        The matplotlib axis on which to plot the vertical build.
    mfile :
        An object containing the machine build data, with required fields for each
        vertical component.
    colour_scheme :
        Colour scheme index to use for component colors.


    Notes
    -----
    This function modifies the provided axis in-place and does not return a value.
    - Components with zero thickness are omitted from the plot.
    - The legend displays the name and thickness (in meters) of each component.
    """

    lower_vertical_variables = [
        "z_plasma_xpoint_upper",
        "dz_xpoint_divertor",
        "dz_divertor",
        "dz_shld_upper",
        "dz_vv_upper",
        "dz_shld_vv_gap",
        "dz_shld_thermal",
        "dr_tf_shld_gap",
        "dr_tf_inboard",
        "dz_tf_cryostat",
    ]

    lower_vertical_build = [[mfile.get(rl, scan=-1) for rl in lower_vertical_variables]]

    lower_vertical_build = np.array(lower_vertical_build)

    lower_vertical_build = np.transpose(lower_vertical_build)

    lower_vertical_labels = [
        "Plasma Height",
        "Plasma - Divertor Gap",
        "Divertor",
        "Shield",
        "Vacuum Vessel",
        "Shield - VV Gap",
        "Thermal shield",
        "TF Coil - Shield Gap",
        "TF Coil",
        "TF Coil - Cryostat gap",
    ]

    lower_vertical_color = [
        PLASMA_COLOUR[colour_scheme - 1],
        "white",
        "black",
        SHIELD_COLOUR[colour_scheme - 1],
        VESSEL_COLOUR[colour_scheme - 1],
        "white",
        THERMAL_SHIELD_COLOUR[colour_scheme - 1],
        "white",
        TFC_COLOUR[colour_scheme - 1]
        if mfile.get("i_tf_sup", scan=-1) != 0
        else "#b87333",
        "white",
    ]

    # Remove build parts equal to zero
    mask = ~(lower_vertical_build[:, 0] == 0.0)
    filtered_vertical_build = lower_vertical_build[mask]
    filtered_labels = [lbl for i, lbl in enumerate(lower_vertical_labels) if mask[i]]
    filtered_colors = [col for i, col in enumerate(lower_vertical_color) if mask[i]]

    bottom = np.zeros(filtered_vertical_build.shape[1])
    for kk in range(filtered_vertical_build.shape[0]):
        axis.bar(
            np.arange(filtered_vertical_build.shape[1]),
            -filtered_vertical_build[kk, :],
            bottom=bottom,
            width=0.8,
            label=f"{filtered_labels[kk]}\n[{lower_vertical_variables[kk]}]\n{filtered_vertical_build[kk][0]:.3f} m",
            color=filtered_colors[kk],
            edgecolor="black",
            linewidth=0.05,
        )
        bottom -= filtered_vertical_build[kk, :]

    axis.set_xticks([])
    axis.legend(
        bbox_to_anchor=(0, 0),
        loc="upper left",
        ncol=5,
    )
    axis.minorticks_on()
    axis.set_ylabel("Height [m]")
    axis.title.set_text("Lower Vertical Build")

plot_upper_vertical_build(axis, mfile, colour_scheme)

Plots the upper vertical build of a fusion device on the given matplotlib axis.

This function visualizes the different layers/components of the machine's vertical build (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.) as a vertical stacked bar chart. The thickness of each layer is extracted from the provided mfile, and each segment is color-coded and labeled accordingly.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis on which to plot the vertical build.

required
mfile MFile

An object containing the machine build data, with required fields for each vertical component.

required
colour_scheme Literal[1, 2]

Colour scheme index to use for component colors.

required
Notes

This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component.

Source code in process/core/io/plot_proc.py
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
def plot_upper_vertical_build(
    axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2]
):
    """Plots the upper vertical build of a fusion device on the given matplotlib axis.

    This function visualizes the different layers/components of the machine's vertical build
    (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.)
    as a vertical stacked bar chart. The thickness of each layer is extracted from the
    provided `mfile`, and each segment is color-coded and labeled accordingly.

    Parameters
    ----------
    axis:
        The matplotlib axis on which to plot the vertical build.
    mfile:
        An object containing the machine build data, with required fields for each
        vertical component.
    colour_scheme:
        Colour scheme index to use for component colors.

    Notes
    -----
    This function modifies the provided axis in-place and does not return a value.
    - Components with zero thickness are omitted from the plot.
    - The legend displays the name and thickness (in meters) of each component.
    """
    if mfile.get("i_single_null", scan=-1) == 1:
        upper_vertical_variables = [
            "z_plasma_xpoint_upper",
            "dz_fw_plasma_gap",
            "dz_fw_upper",
            "dz_blkt_upper",
            "dr_shld_blkt_gap",
            "dz_shld_upper",
            "dz_vv_upper",
            "dz_shld_vv_gap",
            "dz_shld_thermal",
            "dr_tf_shld_gap",
            "dr_tf_inboard",
            "dz_tf_cryostat",
        ]
        upper_vertical_labels = [
            "Plasma Height",
            "First Wall - Plasma Gap",
            "First Wall Upper",
            "Blanket Upper",
            "Shield-Blanket Gap",
            "Shield Upper",
            "Vacuum Vessel Upper",
            "Shield-VV Gap",
            "Thermal Shield",
            "TF Coil - Shield Gap",
            "TF Coil",
            "TF Coil - Cryostat gap",
        ]
        upper_vertical_colours = [
            PLASMA_COLOUR[colour_scheme - 1],
            "white",
            FIRSTWALL_COLOUR[colour_scheme - 1],
            BLANKET_COLOUR[colour_scheme - 1],
            "white",
            SHIELD_COLOUR[colour_scheme - 1],
            VESSEL_COLOUR[colour_scheme - 1],
            "white",
            THERMAL_SHIELD_COLOUR[colour_scheme - 1],
            "white",
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=-1) != 0
            else "#b87333",
            "white",
        ]
    # Double null case
    else:
        upper_vertical_variables = [
            "z_plasma_xpoint_upper",
            "dz_xpoint_divertor",
            "dz_divertor",
            "dz_shld_upper",
            "dz_vv_upper",
            "dz_shld_vv_gap",
            "dz_shld_thermal",
            "dr_tf_shld_gap",
            "dr_tf_inboard",
            "dz_tf_cryostat",
        ]
        upper_vertical_labels = [
            "Plasma Height",
            "Plasma - Divertor Gap",
            "Divertor Upper",
            "Shield Upper",
            "Vacuum Vessel Upper",
            "Shield-VV Gap",
            "Thermal Shield",
            "TF Coil - Shield Gap",
            "TF Coil",
            "TF Coil - Cryostat gap",
        ]
        upper_vertical_colours = [
            PLASMA_COLOUR[colour_scheme - 1],
            "white",
            "black",
            SHIELD_COLOUR[colour_scheme - 1],
            VESSEL_COLOUR[colour_scheme - 1],
            "white",
            THERMAL_SHIELD_COLOUR[colour_scheme - 1],
            "white",
            TFC_COLOUR[colour_scheme - 1]
            if mfile.get("i_tf_sup", scan=-1) != 0
            else "#b87333",
            "white",
        ]

    # Get thicknesses for each layer
    upper_vertical_build = np.array([
        mfile.get(rl, scan=-1) for rl in upper_vertical_variables
    ])

    # Remove build parts equal to zero
    mask = ~(upper_vertical_build == 0.0)
    filtered_build = upper_vertical_build[mask]
    filtered_labels = [lbl for i, lbl in enumerate(upper_vertical_labels) if mask[i]]
    filtered_colors = [col for i, col in enumerate(upper_vertical_colours) if mask[i]]
    filtered_vars = [v for i, v in enumerate(upper_vertical_variables) if mask[i]]

    # Compute cumulative positions (bottoms) for stacking
    bottoms = np.zeros_like(filtered_build)
    for i in range(1, len(filtered_build)):
        bottoms[i] = bottoms[i - 1] + filtered_build[i - 1]

    # Plot each layer as a bar, stacking upwards from zero
    for kk in range(len(filtered_build)):
        axis.bar(
            0,
            filtered_build[kk],
            bottom=bottoms[kk],
            width=0.8,
            label=f"{filtered_labels[kk]}\n[{filtered_vars[kk]}]\n{filtered_build[kk]:.3f} m",
            color=filtered_colors[kk],
            edgecolor="black",
            linewidth=0.05,
        )

    axis.set_xticks([])
    axis.legend(
        bbox_to_anchor=(0, 0),
        loc="upper left",
        ncol=6,
    )
    axis.minorticks_on()
    axis.set_ylabel("Height [m]")
    axis.title.set_text("Upper Vertical Build")

plot_density_limit_comparison(axis, mfile, scan)

Function to plot a scatter box plot of different density limit comparisons.

Parameters:

Name Type Description Default
axis Axes

Axis object to plot to.

required
mfile MFile

MFILE data object.

required
scan int

Scan number to use.

required
Source code in process/core/io/plot_proc.py
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
def plot_density_limit_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Function to plot a scatter box plot of different density limit comparisons.

    Parameters
    ----------
    axis :
        Axis object to plot to.
    mfile :
         MFILE data object.
    scan :
        Scan number to use.
    """
    old_asdex = mfile.get("nd_plasma_electron_max_array(1)", scan=scan)
    borrass_iter_i = mfile.get("nd_plasma_electron_max_array(2)", scan=scan)
    borrass_iter_ii = mfile.get("nd_plasma_electron_max_array(3)", scan=scan)
    jet_edge_radiation = mfile.get("nd_plasma_electron_max_array(4)", scan=scan)
    jet_simplified = mfile.get("nd_plasma_electron_max_array(5)", scan=scan)
    hugill_murakami = mfile.get("nd_plasma_electron_max_array(6)", scan=scan)
    greenwald = mfile.get("nd_plasma_electron_max_array(7)", scan=scan)
    asdex_new = mfile.get("nd_plasma_electron_max_array(8)", scan=scan)

    # Data for the box plot
    data = {
        "Old ASDEX": old_asdex,
        "Borrass ITER I": borrass_iter_i,
        "Borrass ITER II": borrass_iter_ii,
        "JET Edge Radiation": jet_edge_radiation,
        "JET Simplified": jet_simplified,
        "Hugill-Murakami": hugill_murakami,
        "Greenwald": greenwald,
        "ASDEX New": asdex_new,
    }

    # Create the violin plot
    axis.violinplot(data.values(), showextrema=False)

    # Create the box plot
    axis.boxplot(
        data.values(), showfliers=True, showmeans=True, meanline=True, widths=0.3
    )

    # Scatter plot for each data point
    colors = plt.cm.plasma(np.linspace(0, 1, len(data.values())))
    for index, (key, value) in enumerate(data.items()):
        axis.scatter(1, value, color=colors[index], label=key, alpha=1.0)
    axis.legend(loc="upper left", bbox_to_anchor=(1, 1))

    # Calculate average, standard deviation, and median
    data_values = list(data.values())
    avg_density_limit = np.mean(data_values)
    std_density_limit = np.std(data_values)
    median_density_limit = np.median(data_values)

    # Plot average, standard deviation, and median as text
    axis.text(
        1.02,
        0.2,
        rf"Average: {avg_density_limit * 1e-20:.4f} $\times 10^{{20}}$",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        1.02,
        0.15,
        rf"Standard Dev: {std_density_limit * 1e-20:.4f} $\times 10^{{20}}$",
        transform=axis.transAxes,
        fontsize=9,
    )
    axis.text(
        1.02,
        0.1,
        rf"Median: {median_density_limit * 1e-20:.4f} $\times 10^{{20}}$",
        transform=axis.transAxes,
        fontsize=9,
    )

    axis.set_yscale("log")
    axis.set_title("Density Limit Comparison")
    axis.set_ylabel(r"Density Limit [$10^{20}$ m$^{-3}$]")
    axis.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x * 1e-20:.1f}"))
    axis.set_xlim([0.5, 1.5])
    axis.set_xticks([])
    axis.set_xticklabels([])
    axis.set_facecolor("#f0f0f0")

plot_cs_coil_structure(axis, fig, mfile, scan, colour_scheme=1)

Function to plot the coil structure of the CS.

Parameters:

Name Type Description Default
axis Axes

axis object to plot to

required
mfile MFile

MFILE

required
scan int

scan number to use

required
demo_ranges

whether to use demo ranges for the plot

required
colour_scheme

colour scheme to use for the plot (Default value = 1)

1
Source code in process/core/io/plot_proc.py
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
def plot_cs_coil_structure(
    axis: plt.Axes, fig, mfile: mf.MFile, scan: int, colour_scheme=1
):
    """Function to plot the coil structure of the CS.

    Parameters
    ----------
    axis :
        axis object to plot to
    mfile :
        MFILE
    scan :
        scan number to use
    demo_ranges :
        whether to use demo ranges for the plot
    colour_scheme :
        colour scheme to use for the plot (Default value = 1)

    """
    # Get CS coil parameters
    dr_cs = mfile.get("dr_cs", scan=scan)
    dr_cs_full = mfile.get("dr_cs_full", scan=scan)
    dz_cs_full = mfile.get("dz_cs_full", scan=scan)
    dz_cs = mfile.get("dz_cs_full", scan=scan)
    dr_bore = mfile.get("dr_bore", scan=scan)
    r_cs_current_filaments_array = [
        mfile.get(f"r_pf_cs_current_filaments{i}", scan=scan)
        for i in range(pfcoil_variables.NFIXMX)
    ]
    z_cs_current_filaments_array = [
        mfile.get(f"z_pf_cs_current_filaments{i}", scan=scan)
        for i in range(pfcoil_variables.NFIXMX)
    ]

    # Plot the right side of the CS
    right_cs = patches.Rectangle(
        (dr_bore, -dz_cs / 2),
        dr_cs,
        dz_cs,
        edgecolor="black",
        facecolor=SOLENOID_COLOUR[colour_scheme - 1],
        lw=1.5,
    )
    axis.add_patch(right_cs)

    # Plot the bore of the machine
    bore_rect = patches.Rectangle(
        (-dr_bore, -dz_cs / 2),
        dr_bore * 2,
        dz_cs,
        edgecolor="black",
        facecolor="lightgrey",
        lw=1.0,
    )
    axis.add_patch(bore_rect)

    left_cs = patches.Rectangle(
        (-dr_bore - dr_cs, -dz_cs / 2),
        dr_cs,
        dz_cs,
        edgecolor="black",
        facecolor=SOLENOID_COLOUR[colour_scheme - 1],
        lw=1.5,
    )
    axis.add_patch(left_cs)

    # Draw vertical lines to represent CS turns
    # Get the turn width (radial thickness of each turn)
    dr_cs_turn = mfile.get("dr_cs_turn", scan=scan)
    dz_cs_turn = mfile.get("dz_cs_turn", scan=scan)
    # Number of vertical lines (number of turns)
    t_kwargs = {"color": "black", "linestyle": "--", "linewidth": 0.2}
    if dr_cs_turn > 0:
        n_lines = int(dr_cs / dr_cs_turn)
        for i in range(1, n_lines):
            x = dr_bore + i * dr_cs_turn
            axis.plot([x, x], [-dz_cs / 2, dz_cs / 2], **t_kwargs)
            x_left = -dr_bore - dr_cs + i * dr_cs_turn
            axis.plot([x_left, x_left], [-dz_cs / 2, dz_cs / 2], **t_kwargs)
    # Plot horizontal lines (along Z) for each turn
    if dz_cs_turn > 0:
        n_hlines = int(dz_cs / dz_cs_turn)
        for j in range(1, n_hlines):
            y = -dz_cs / 2 + j * dz_cs_turn
            # Right CS
            axis.plot([dr_bore, dr_bore + dr_cs], [y, y], **t_kwargs)
            # Left CS
            axis.plot([-dr_bore - dr_cs, -dr_bore], [y, y], **t_kwargs)

        l_kwargs = {"color": "black", "linestyle": "--", "linewidth": 0.6, "alpha": 0.5}

        # Plot a horizontal line at y = 0.0
        axis.axhline(y=0.0, **l_kwargs)
        # Plot a vertical line at x = 0.0
        axis.axvline(x=0.0, **l_kwargs)
        # Plot a vertical line at x = dr_bore
        axis.axvline(x=dr_bore, **l_kwargs)
        # Plot a vertical line at x = -dr_bore
        axis.axvline(x=-dr_bore, **l_kwargs)
        # Plot a vertical line at x = dr_bore + dr_cs
        axis.axvline(x=(dr_bore + dr_cs), **l_kwargs)
        # Plot a vertical line at x = -dr_bore - dr_cs
        axis.axvline(x=-(dr_bore + dr_cs), **l_kwargs)
        # Plot a vertical line at y= dz_cs / 2
        axis.axhline(y=(dz_cs / 2), **l_kwargs)
        # Plot a vertical line at y= -dz_cs / 2
        axis.axhline(y=-(dz_cs / 2), **l_kwargs)

        # Plot a vertical line at x = r_cs_middle
        axis.axvline(x=mfile.get("r_cs_middle", scan=scan), **l_kwargs)
        # Plot a vertical line at x= -r_cs_middle
        axis.axvline(x=-mfile.get("r_cs_middle", scan=scan), **l_kwargs)

        # Arrow for coil width
        axis.annotate(
            "",
            xy=(0, (dz_cs_full / 2)),
            xytext=(0, -(dz_cs_full / 2)),
            arrowprops={"arrowstyle": "<->", "color": "black"},
        )

        # Add a label for full coil width
        axis.text(
            0.0,
            -(dz_cs_full / 4),
            f"{dz_cs_full:.3f} m",
            fontsize=7,
            color="black",
            rotation=270,
            verticalalignment="center",
            horizontalalignment="center",
            bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        )

        # Arrow for coil width
        axis.annotate(
            "",
            xy=(-(dr_cs_full / 2), (dz_cs_full / 4)),
            xytext=((dr_cs_full / 2), (dz_cs_full / 4)),
            arrowprops={"arrowstyle": "<->", "color": "black"},
        )

        # Add a label for full coil width
        axis.text(
            0.0,
            (dz_cs_full / 4),
            f"{dr_cs_full:.3f} m",
            fontsize=7,
            color="black",
            rotation=0,
            verticalalignment="center",
            horizontalalignment="center",
            bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        )

    textstr_cs = (
        f"$\\mathbf{{Coil \\ parameters:}}$\n \n"
        f"CS height vs TF internal height: {mfile.get('f_z_cs_tf_internal', scan=scan):.2f}\n"
        f"CS thickness: {mfile.get('dr_cs', scan=scan):.4f} m\n"
        f"CS radial middle: {mfile.get('r_cs_middle', scan=scan):.4f} m\n"
        f"CS full height: {mfile.get('dz_cs_full', scan=scan):.4f} m\n"
        f"CS full width: {mfile.get('dr_cs_full', scan=scan):.4f} m\n"
        f"CS poloidal area: {mfile.get('a_cs_poloidal', scan=scan):.4f} m$^2$\n"
        f"$N_{{\\text{{turns}}}}:$ {mfile.get('n_pf_coil_turns[n_cs_pf_coils-1]', scan=scan):,.2f}\n"
        f"$I_{{\\text{{peak}}}}:$ {mfile.get('c_pf_cs_coils_peak_ma[n_cs_pf_coils-1]', scan=scan):.3f}$ \\ MA$\n"
        f"$B_{{\\text{{peak}}}}:$ {mfile.get('b_pf_coil_peak[n_cs_pf_coils-1]', scan=scan):.3f}$ \\ T$\n"
        f"$F_{{\\text{{z,self,peak}}}}:$ {mfile.get('forc_z_cs_self_peak_midplane', scan=scan) / 1e6:.3f}$ \\ MN$\n"
        f"$\\sigma_{{\\text{{z,self,peak}}}}:$ {mfile.get('stress_z_cs_self_peak_midplane', scan=scan) / 1e6:.3f}$ \\ MPa$ "
    )

    axis.text(
        0.6,
        0.75,
        textstr_cs,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Plot the current filament points as blue dots and label them

    axis.plot(
        r_cs_current_filaments_array,
        z_cs_current_filaments_array,
        "bo",
        markersize=2,
        label="CS, PF and Plasma Current Filaments",
    )

    axis.plot(0, 0, marker="o", color="red", markersize=8)

    axis.set_xlabel("R [m]")
    axis.set_ylabel("Z [m]")
    axis.set_title("Central Solenoid Poloidal Cross-Section")
    axis.grid(True, linestyle="--", alpha=0.3)
    axis.minorticks_on()
    axis.legend()

plot_cs_turn_structure(axis, fig, mfile, scan)

Source code in process/core/io/plot_proc.py
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
def plot_cs_turn_structure(axis: plt.Axes, fig, mfile: mf.MFile, scan: int):
    a_cs_turn = mfile.get("a_cs_turn", scan=scan)
    dz_cs_turn = mfile.get("dz_cs_turn", scan=scan)
    dr_cs_turn = mfile.get("dr_cs_turn", scan=scan)

    f_dr_dz_cs_turn = mfile.get("f_dr_dz_cs_turn", scan=scan)
    radius_cs_turn_cable_space = mfile.get("radius_cs_turn_cable_space", scan=scan)
    dz_cs_turn_conduit = mfile.get("dz_cs_turn_conduit", scan=scan)
    dr_cs_turn_conduit = mfile.get("dr_cs_turn_conduit", scan=scan)
    radius_cs_turn_corners = mfile.get("radius_cs_turn_corners", scan=scan)
    f_a_cs_turn_steel = mfile.get("f_a_cs_turn_steel", scan=scan)

    # Plot the CS turn as a rectangle representing the conductor cross-section
    # Assume dz_cs_turn is the diameter and dr_cs_turn is the length of the conductor cross-section

    # Draw the conductor cross-section as a rectangle
    axis.add_patch(
        patches.FancyBboxPatch(
            (0, 0),
            dr_cs_turn,
            dz_cs_turn,
            boxstyle=patches.BoxStyle(
                "Round", pad=0, rounding_size=radius_cs_turn_corners
            ),
            edgecolor="black",
            facecolor="grey",
            lw=1.5,
            label="CS Turn Steel conduit",
        )
    )

    # Draw the conductor cross-section as a rectangle
    axis.add_patch(
        patches.Rectangle(
            (dr_cs_turn_conduit + radius_cs_turn_cable_space, dz_cs_turn_conduit),
            dr_cs_turn - ((2 * dr_cs_turn_conduit) + (2 * radius_cs_turn_cable_space)),
            2 * radius_cs_turn_cable_space,
            facecolor="white",
            lw=1.5,
            label="CS Turn Cable Space",
            zorder=2,
        )
    )
    # Plot the right hand circle for the CS turn cable space
    axis.add_patch(
        patches.Circle(
            (
                (dr_cs_turn - dr_cs_turn_conduit - radius_cs_turn_cable_space),
                dz_cs_turn / 2,
            ),
            radius_cs_turn_cable_space,
            facecolor="white",
            lw=1.5,
            zorder=3,
        )
    )
    # Plot the left hand circle for the CS turn cable space
    axis.add_patch(
        patches.Circle(
            ((dr_cs_turn_conduit + radius_cs_turn_cable_space), dz_cs_turn / 2),
            radius_cs_turn_cable_space,
            facecolor="white",
            lw=1.5,
            zorder=3,
        )
    )

    # Add plasma volume, areas and shaping information
    textstr_turn = (
        f"$\\mathbf{{Turn \\ structure:}}$\n\n$A:$ {a_cs_turn:.4e}$ \\ \\text{{m}}^2$\n"
        f"Turn width: {dr_cs_turn:.4e}$ \\ \\text{{m}}$\n"
        f"Turn height: {dz_cs_turn:.4e}$ \\ \\text{{m}}$\n"
        f"Turn width to height ratio: {f_dr_dz_cs_turn:.3f}\n"
        f"Steel conduit width: {dr_cs_turn_conduit:.4e}$ \\ \\text{{m}}$\n"
        f"Radius of turn cable space: {radius_cs_turn_cable_space:.4e}$ \\ \\text{{m}}$\n"
        f"Radius of turn corner: {radius_cs_turn_corners:.4e}$ \\ \\text{{m}}$\n"
        f"Fraction of turn area that is steel: {f_a_cs_turn_steel:.4f}\n"
    )

    axis.text(
        0.6,
        0.5,
        textstr_turn,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.set_xlim(-dr_cs_turn * 0.2, dr_cs_turn * 1.2)
    axis.set_ylim(-dz_cs_turn * 0.3, dz_cs_turn * 1.3)
    axis.set_aspect("equal")
    axis.set_xlabel("Length [m]")
    axis.set_ylabel("Height [m]")
    axis.set_title("CS Turn Conductor Cross-Section")
    axis.legend()
    axis.grid(True, linestyle="--", alpha=0.3)

plot_tf_coil_structure(axis, mfile, scan, colour_scheme=1)

Source code in process/core/io/plot_proc.py
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
def plot_tf_coil_structure(axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme=1):
    # Plot the TF coil poloidal cross-section
    plot_tf_coils(axis, mfile, scan, colour_scheme)

    x1 = mfile.get("r_tf_arc(1)", scan=scan)
    y1 = mfile.get("z_tf_arc(1)", scan=scan)
    x2 = mfile.get("r_tf_arc(2)", scan=scan)
    y2 = mfile.get("z_tf_arc(2)", scan=scan)
    x3 = mfile.get("r_tf_arc(3)", scan=scan)
    y3 = mfile.get("z_tf_arc(3)", scan=scan)
    x4 = mfile.get("r_tf_arc(4)", scan=scan)
    y4 = mfile.get("z_tf_arc(4)", scan=scan)
    x5 = mfile.get("r_tf_arc(5)", scan=scan)
    y5 = mfile.get("z_tf_arc(5)", scan=scan)

    z_tf_inside_half = mfile.get("z_tf_inside_half", scan=scan)
    z_tf_top = mfile.get("z_tf_top", scan=scan)
    dr_tf_inboard = mfile.get("dr_tf_inboard", scan=scan)
    r_tf_inboard_out = mfile.get("r_tf_inboard_out", scan=scan)
    r_tf_outboard_in = mfile.get("r_tf_outboard_in", scan=scan)
    r_tf_inboard_in = mfile.get("r_tf_inboard_in", scan=scan)
    dr_tf_outboard = mfile.get("dr_tf_outboard", scan=scan)
    len_tf_coil = mfile.get("len_tf_coil", scan=scan)
    dz_tf_upper_lower_midplane = mfile.get("dz_tf_upper_lower_midplane", scan=scan)

    # Plot the points as black dots, number them, and connect them with lines
    xs = [x1, x2, x3, x4, x5]
    ys = [y1, y2, y3, y4, y5]
    labels = []
    for i, (x, y) in enumerate(zip(xs, ys, strict=False), 1):
        axis.plot(x, y, "ko", markersize=8)
        axis.text(
            x,
            y,
            str(i),
            color="red",
            fontsize=5,
            ha="center",
            va="center",
            fontweight="bold",
        )
        labels.append(f"TF Arc Point {i}: ({x:.2f}, {y:.2f})")

    # =========================================================

    # If D-shaped coil, plot the full internal height arrow
    if mfile.get("i_tf_shape", scan=scan) == 1:
        # Arrow for internal coil width
        axis.annotate(
            "",
            xy=(x2, y2),
            xytext=(x4, y4),
            arrowprops={"arrowstyle": "<->", "color": "black"},
        )

        # Add a label for the internal coil width
        axis.text(
            x2,
            0.0,
            f"{y2 - y4:.3f} m",
            fontsize=7,
            color="black",
            rotation=270,
            verticalalignment="center",
            horizontalalignment="center",
            bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
            zorder=100,  # Ensure label is on top of all plots
        )

    # ==========================================================

    # Arrow for the full TF coil height
    if mfile.get("i_tf_shape", scan=scan) == 1:
        x = x2 * 0.9
    elif mfile.get("i_tf_shape", scan=scan) == 2:
        x = (x2 - x1) / 2

    axis.annotate(
        "",
        xy=(x, y2 + dr_tf_inboard),
        xytext=(x, y4 - dr_tf_inboard),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Add a label for the full TF coil height
    axis.text(
        x,
        0.0,
        f"{((y2 + 2 * dr_tf_inboard) - y4):.3f} m",
        fontsize=7,
        color="black",
        rotation=270,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        zorder=101,  # Ensure label is on top of all plots
    )

    # ==========================================================

    # Arrow for top half height of TF coil
    axis.annotate(
        "",
        xy=(-2.0, 0),
        xytext=(-2.0, y2 + dr_tf_inboard),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )
    axis.axhline(y=y2 + dr_tf_inboard, color="black", linestyle="--", linewidth=1)

    # Add a label for top of TF coil
    axis.text(
        -2.0,
        (y2 + dr_tf_inboard) / 2,
        f"{y2 + dr_tf_inboard:.3f} m",
        fontsize=7,
        color="black",
        rotation=270,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # ==========================================================

    # Arrow for bottom half height of TF coil
    axis.annotate(
        "",
        xy=(-2.0, 0),
        xytext=(-2.0, y4 - dr_tf_inboard),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )
    axis.axhline(y=y4 - dr_tf_inboard, color="black", linestyle="--", linewidth=1)

    # Add a label for top of TF coil
    axis.text(
        -2.0,
        -z_tf_top / 2,
        f"{y4 - dr_tf_inboard:.3f} m",
        fontsize=7,
        color="black",
        rotation=270,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # Arrow for top inside internal height
    axis.annotate(
        "",
        xy=(-1.0, 0),
        xytext=(-1.0, y2),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )
    axis.axhline(y=y2, color="black", linestyle="--", linewidth=1)

    # Add a label for height of top internal height
    axis.text(
        -1.0,
        y2 / 2,
        f"{y2:.3f} m",
        fontsize=7,
        color="black",
        rotation=270,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # =========================================================

    # Arrow for coil internal height
    axis.annotate(
        "",
        xy=(-1.0, 0),  # Inner plasma edge
        xytext=(-1.0, -z_tf_inside_half),  # Center
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )
    axis.axhline(y=-z_tf_inside_half, color="black", linestyle="--", linewidth=1)

    # Add a label for coil internal height
    axis.text(
        -1.0,
        -z_tf_inside_half / 2,
        f"{z_tf_inside_half:.3f} m",
        fontsize=7,
        color="black",
        rotation=270,
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )
    # =========================================================

    # Arrow for internal coil width
    axis.annotate(
        "",
        xy=(r_tf_inboard_out, -z_tf_inside_half / 12),
        xytext=(r_tf_outboard_in, -z_tf_inside_half / 12),
        arrowprops={"arrowstyle": "<->", "color": "black"},
    )

    # Add a label for the internal coil width
    axis.text(
        (r_tf_inboard_out + r_tf_outboard_in) / 1.5,
        -z_tf_inside_half / 12,
        f"{r_tf_outboard_in - r_tf_inboard_in:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        zorder=100,  # Ensure label is on top of all plots
    )

    # =============================================================

    # Arrow for full coil width
    axis.annotate(
        "",
        xy=(r_tf_inboard_in, 0.0),
        xytext=(r_tf_outboard_in + dr_tf_outboard, 0.0),
        arrowprops={"arrowstyle": "<|-|>", "color": "black"},
        zorder=100,  # Ensure label is on top of all plots
    )

    # Add a label for the full coil width
    axis.text(
        (r_tf_inboard_out + r_tf_outboard_in) / 1.5,
        0.0,
        f"{(r_tf_outboard_in + dr_tf_outboard) - r_tf_inboard_in:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        zorder=100,  # Ensure label is on top of all plots
    )

    # =============================================================

    # Plot vertical lines for the inboard TF coil start and end
    axis.axvline(
        r_tf_inboard_in,
        color="black",
        linestyle="--",
        linewidth=1,
        alpha=0.5,
        label="TF Inboard Start",
    )
    axis.axvline(
        r_tf_inboard_out,
        color="black",
        linestyle="--",
        linewidth=1,
        alpha=0.5,
        label="TF Inboard End",
    )
    # Plot vertical lines for the outboard TF coil start and end
    axis.axvline(
        r_tf_outboard_in,
        color="black",
        linestyle="--",
        linewidth=1,
        alpha=0.5,
        label="TF Outboard Start",
    )
    axis.axvline(
        r_tf_outboard_in + dr_tf_outboard,
        color="black",
        linestyle="--",
        linewidth=1,
        alpha=0.5,
        label="TF Outboard End",
    )

    # Add a label for the inboard thickness
    axis.text(
        r_tf_inboard_in,
        (y4 - dr_tf_inboard) * 1.1,
        rf"$\Delta r = ${dr_tf_inboard:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # Add a label for the outboard thickness
    axis.text(
        r_tf_outboard_in,
        (y4 - dr_tf_inboard) * 1.1,
        rf"$\Delta r = ${dr_tf_outboard:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # ==============================================================

    # Add a label for the length of the coil
    axis.text(
        (r_tf_outboard_in + 2 * dr_tf_outboard),
        0.0,
        rf"Length of coil = {len_tf_coil:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        zorder=100,  # Ensure label is on top of all plots
    )

    # ==============================================================

    # Add a label for the length of the coil
    axis.text(
        (r_tf_outboard_in + 2 * dr_tf_outboard),
        -1.0,
        f"$\\Delta Z$ upper and lower to midplane = {dz_tf_upper_lower_midplane:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # ==============================================================

    # Add arow for inboard coil radius
    axis.annotate(
        "",
        xy=(r_tf_inboard_in, 0),
        xytext=(0, 0),
        arrowprops={"arrowstyle": "->", "color": "black"},
    )

    # Add label for inboard coil radius
    axis.text(
        r_tf_inboard_in / 2,
        0.0,
        f"{r_tf_inboard_in:.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        zorder=101,  # Ensure label is on top of all plots
    )

    # =============================================================

    # ==============================================================

    if mfile.get("i_tf_shape", scan=scan) == 1:
        # Add arow for inboard coil radius
        axis.annotate(
            "",
            xy=(r_tf_outboard_in + dr_tf_outboard, y2 + dr_tf_inboard),
            xytext=(0, y2 + dr_tf_inboard),
            arrowprops={"arrowstyle": "->", "color": "black"},
        )

        # Add label for inboard coil radius
        axis.text(
            r_tf_inboard_in / 2,
            y2 + dr_tf_inboard,
            f"{r_tf_outboard_in + dr_tf_outboard:.3f} m",
            fontsize=7,
            color="black",
            verticalalignment="center",
            horizontalalignment="center",
            bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
        )

        axis.plot(
            0, y2 + dr_tf_inboard, marker="o", color="black", markersize=7, zorder=100
        )

    # ==============================================================

    y_center = y2 - ((y2 - y4) / 2)
    # also draw a red horizontal line at the same vertical centre
    axis.axhline(y=y_center, color="red", linestyle="--", linewidth=1.0, zorder=5)

    # Add a label the plasma and TF vertical centre distance offset
    axis.text(
        (r_tf_outboard_in + 2 * dr_tf_outboard),
        -2.0,
        f"$\\Delta Z$ coil centre to plasma centre = {mfile.get('dz_tf_plasma_centre_offset', scan=scan):.3f} m",
        fontsize=7,
        color="black",
        verticalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "pink", "alpha": 1.0},
    )

    # =============================================================

    # Plot a red dot at (0,0)
    axis.plot(0, 0, marker="o", color="red", markersize=7)

    # Plot a red dashed vertical line at R=0
    axis.axvline(0, color="red", linestyle="--", linewidth=1)

    # Add centre line at
    axis.axhline(y=0, color="red", linestyle="--", linewidth=1)
    axis.set_xlim(-3.0, (r_tf_outboard_in + dr_tf_outboard) * 1.4)
    axis.set_ylim((y4 - dr_tf_inboard) * 1.2, (y2 + dr_tf_inboard) * 1.2)
    axis.set_xlabel("R [m]")
    axis.set_ylabel("Z [m]")
    axis.set_title("TF Coil Poloidal Cross-Section")
    axis.minorticks_on()
    axis.grid(True, which="both", linestyle="--", linewidth=0.5, alpha=0.2)
    # Move the legend to above the plot
    axis.legend(labels, loc="upper center", bbox_to_anchor=(1.01, 0.85), ncol=1)

plot_iteration_variables(axis, m_file, scan)

Plot the iteration variables and where they lay in their bounds on a given axes

Parameters:

Name Type Description Default
axis Axes
required
m_file MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
def plot_iteration_variables(axis: plt.Axes, m_file: mf.MFile, scan: int):
    """Plot the iteration variables and where they lay in their bounds on a given axes

    Parameters
    ----------
    axis: plt.Axes :

    m_file: mf.MFile :

    scan: int :

    """

    # Get total number of iteration variables
    n_itvars = int(m_file.get("nvar", scan=scan))

    y_labels = []
    y_pos = []
    n_plot = 0

    # Build a mapping from itvar index to its name (description)
    itvar_names = {}
    for var in m_file.data:
        if var.startswith("itvar"):
            idx = int(var[5:])  # e.g. "itvar001" -> 1
            itvar_names[idx] = m_file.data[var].var_description

    for n_plot, n in enumerate(range(1, n_itvars + 1)):
        # Get the final value of the iteration variable, its bounds, and relative change
        itvar_final = m_file.get(f"itvar{n:03d}", scan=scan)
        itvar_upper = m_file.get(f"boundu{n:03d}", scan=scan)
        itvar_lower = m_file.get(f"boundl{n:03d}", scan=scan)
        itvar_relative_change = m_file.get(f"xcm{n:03d}", scan=scan)
        final_value_normalised = m_file.get(f"nitvar{n:03d}", scan=scan)

        # Use the variable name if available, else fallback to "itvarXXX"
        var_label = itvar_names.get(n, f"itvar{n:03d}")

        norm_relative_change = (
            ((itvar_final / itvar_relative_change) - itvar_lower)
            / (itvar_upper - itvar_lower)
            if itvar_final != itvar_lower
            else 0
        )

        # Plot square marker at the final value if at bounds
        if np.isclose(final_value_normalised, 1.0, atol=1e-3):
            axis.plot(
                1,
                n_plot,
                "s",
                color="black",
                markersize=8,
                label="Lower Bound" if n_plot == 0 else "",
            )
        elif np.isclose(final_value_normalised, 0.0, atol=1e-3):
            axis.plot(
                0,
                n_plot,
                "s",
                color="black",
                markersize=8,
                label="Upper Bound" if n_plot == 0 else "",
            )
        # Draw a horizontal bar from 0 to norm_final at y=n_plot
        else:
            axis.barh(
                n_plot,
                final_value_normalised,
                left=0,
                height=1.0,
                color="blue",
                edgecolor="black",
                linewidth=1.5,
                alpha=0.7,
                label="Final Value" if n_plot == 0 else "",
            )

        # Plot scatter point for normalised relative change
        axis.scatter(
            norm_relative_change,
            n_plot,
            color="black",
            marker="o",
            linewidths=2,
            alpha=1.0,
            label="Initial Value" if n_plot == 0 else "",
        )

        # Draw an arrow from the initial value to the final value
        axis.annotate(
            "",
            xy=(final_value_normalised, n_plot),
            xytext=(norm_relative_change, n_plot),
            arrowprops={
                "arrowstyle": "->",
                "color": "black",
                "linestyle": "--",
                "linewidth": 1.0,
                "alpha": 0.9,
            },
        )
        # Plot the value as a number at x = 0.5
        axis.text(
            0.5,
            n_plot,
            f"{itvar_final:,.8g}",
            va="center",
            ha="center",
            fontsize=10,
            color=(
                "orange"
                if np.isclose(final_value_normalised, 1.0, atol=1e-3)
                or np.isclose(final_value_normalised, 0.0, atol=1e-3)
                else "green"
            ),
            bbox={
                "boxstyle": "round",
                "facecolor": "white",
                "alpha": 0.8,
                "edgecolor": "white",
                "linewidth": 1,
            },
        )

        # Plot the value of the upper bound to the right of x=1
        axis.text(
            1.05,
            n_plot,
            f"{itvar_upper:,.3g}",
            va="center",
            ha="left",
            fontsize=10,
            color="gray",
        )
        # Plot the value of the lower bound to the left of x=0
        axis.text(
            -0.05,
            n_plot,
            f"{itvar_lower:,.3g}",
            va="center",
            ha="right",
            fontsize=10,
            color="gray",
        )
        y_labels.append(var_label)
        y_pos.append(n_plot)

    # Plot vertical lines at x=0 and x=1 to indicate bounds
    axis.axvline(0, color="darkgreen", linewidth=2, zorder=0)
    axis.axvline(1, color="red", linewidth=2, zorder=0)
    axis.set_yticks(y_pos)
    axis.set_yticklabels(y_labels)
    axis.set_xticks([])
    axis.set_xticklabels([])
    axis.set_facecolor("#f5f5f5")
    axis.set_xlim(-0.2, 1.2)  # Normalised bounds
    axis.set_title("Iteration Variables Bounds")
    axis.set_xticks(np.arange(0, 1.0, 0.1))
    axis.grid(True, axis="x", linestyle="--", alpha=0.3)
    axis.legend(loc="upper left", bbox_to_anchor=(-0.15, 1.05), ncol=1)

plot_tf_stress(axis, mfile)

Function to plot the TF coil stress from the SIG_TF.json file.

Input file: SIG_TF.json

Parameters:

Name Type Description Default
axis Axes
required
mfile MFile
required
Source code in process/core/io/plot_proc.py
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
def plot_tf_stress(axis: plt.Axes, mfile: mf.MFile):
    """Function to plot the TF coil stress from the SIG_TF.json file.

    Input file:
    SIG_TF.json

    Parameters
    ----------
    axis: plt.Axes :

    mfile: mf.MFile :

    """

    # Step 1 : Data extraction
    # ----------------------------------------------------------------------------------------------
    # Number of physical quantity value per coil layer
    n_radial_array_layer = 0

    # Physical quantities : full vectors
    radius = []
    radial_smeared_stress = []
    toroidal_smeared_stress = []
    vertical_smeared_stress = []
    tresca_smeared_stress = []
    radial_stress = []
    toroidal_stress = []
    vertical_stress = []
    vm_stress = []
    tresca_stress = []
    cea_tresca_stress = []
    radial_strain = []
    toroidal_strain = []
    vertical_strain = []
    radial_displacement = []

    # Physical quantity : WP stress
    wp_vertical_stress = []

    # Physical quantity : values at layer border
    bound_radius = []
    bound_radial_smeared_stress = []
    bound_toroidal_smeared_stress = []
    bound_vertical_smeared_stress = []
    bound_tresca_smeared_stress = []
    bound_radial_stress = []
    bound_toroidal_stress = []
    bound_vertical_stress = []
    bound_vm_stress = []
    bound_tresca_stress = []
    bound_cea_tresca_stress = []
    bound_radial_strain = []
    bound_toroidal_strain = []
    bound_vertical_strain = []
    bound_radial_displacement = []

    with open(mfile.filename.replace("MFILE.DAT", "SIG_TF.json")) as f:
        sig_data = json.load(f)

    # Getting the data to be plotted
    n_radial_array_layer = sig_data["Points per layers"]
    n_points = len(sig_data["Radius (m)"])
    n_layers = int(n_points / n_radial_array_layer)
    for ii in range(n_layers):
        # Full vector
        radius.append([])
        radial_stress.append([])
        toroidal_stress.append([])
        vertical_stress.append([])
        radial_smeared_stress.append([])
        toroidal_smeared_stress.append([])
        vertical_smeared_stress.append([])
        vm_stress.append([])
        tresca_stress.append([])
        cea_tresca_stress.append([])
        radial_displacement.append([])

        for jj in range(n_radial_array_layer):
            radius[ii].append(sig_data["Radius (m)"][ii * n_radial_array_layer + jj])
            radial_stress[ii].append(
                sig_data["Radial stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            toroidal_stress[ii].append(
                sig_data["Toroidal stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            if len(sig_data["Vertical stress (MPa)"]) == 1:
                vertical_stress[ii].append(sig_data["Vertical stress (MPa)"][0])
            else:
                vertical_stress[ii].append(
                    sig_data["Vertical stress (MPa)"][ii * n_radial_array_layer + jj]
                )
            radial_smeared_stress[ii].append(
                sig_data["Radial smear stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            toroidal_smeared_stress[ii].append(
                sig_data["Toroidal smear stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            vertical_smeared_stress[ii].append(
                sig_data["Vertical smear stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            vm_stress[ii].append(
                sig_data["Von-Mises stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            tresca_stress[ii].append(
                sig_data["CEA Tresca stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            cea_tresca_stress[ii].append(
                sig_data["CEA Tresca stress (MPa)"][ii * n_radial_array_layer + jj]
            )
            radial_displacement[ii].append(
                sig_data["rad. displacement (mm)"][ii * n_radial_array_layer + jj]
            )

        # Layer lower boundaries values
        bound_radius.append(sig_data["Radius (m)"][ii * n_radial_array_layer])
        bound_radial_stress.append(
            sig_data["Radial stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_toroidal_stress.append(
            sig_data["Toroidal stress (MPa)"][ii * n_radial_array_layer]
        )
        if len(sig_data["Vertical stress (MPa)"]) == 1:
            bound_vertical_stress.append(sig_data["Vertical stress (MPa)"][0])
        else:
            bound_vertical_stress.append(
                sig_data["Vertical stress (MPa)"][ii * n_radial_array_layer]
            )
        bound_radial_smeared_stress.append(
            sig_data["Radial smear stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_toroidal_smeared_stress.append(
            sig_data["Toroidal smear stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_vertical_smeared_stress.append(
            sig_data["Vertical smear stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_vm_stress.append(
            sig_data["Von-Mises stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_tresca_stress.append(
            sig_data["CEA Tresca stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_cea_tresca_stress.append(
            sig_data["CEA Tresca stress (MPa)"][ii * n_radial_array_layer]
        )
        bound_radial_displacement.append(
            sig_data["rad. displacement (mm)"][ii * n_radial_array_layer]
        )

        # Layer upper boundaries values
        bound_radius.append(sig_data["Radius (m)"][(ii + 1) * n_radial_array_layer - 1])
        bound_radial_stress.append(
            sig_data["Radial stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_toroidal_stress.append(
            sig_data["Toroidal stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        if len(sig_data["Vertical stress (MPa)"]) == 1:
            bound_vertical_stress.append(sig_data["Vertical stress (MPa)"][0])
        else:
            bound_vertical_stress.append(
                sig_data["Vertical stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
            )
        bound_radial_smeared_stress.append(
            sig_data["Radial smear stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_toroidal_smeared_stress.append(
            sig_data["Toroidal smear stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_vertical_smeared_stress.append(
            sig_data["Vertical smear stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_vm_stress.append(
            sig_data["Von-Mises stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_tresca_stress.append(
            sig_data["CEA Tresca stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_cea_tresca_stress.append(
            sig_data["CEA Tresca stress (MPa)"][(ii + 1) * n_radial_array_layer - 1]
        )
        bound_radial_displacement.append(
            sig_data["rad. displacement (mm)"][(ii + 1) * n_radial_array_layer - 1]
        )

    # TRESCA smeared stress [MPa]
    for ii in range(n_layers):
        tresca_smeared_stress.append([])

        bound_tresca_smeared_stress.extend([
            max(abs(radial_smeared_stress[ii][0]), abs(toroidal_smeared_stress[ii][0]))
            + vertical_smeared_stress[ii][0],
            max(
                abs(radial_smeared_stress[ii][n_radial_array_layer - 1]),
                abs(toroidal_smeared_stress[ii][n_radial_array_layer - 1]),
            )
            + vertical_smeared_stress[ii][n_radial_array_layer - 1],
        ])
        for jj in range(n_radial_array_layer):
            tresca_smeared_stress[ii].append(
                max(
                    abs(radial_smeared_stress[ii][jj]),
                    abs(toroidal_smeared_stress[ii][jj]),
                )
                + vertical_smeared_stress[ii][jj]
            )

    # Strains
    if len(sig_data) > 16:
        for ii in range(n_layers):
            radial_strain.append([])
            toroidal_strain.append([])
            vertical_strain.append([])

            bound_radial_strain.extend([
                sig_data["Radial strain"][ii * n_radial_array_layer],
                sig_data["Radial strain"][(ii + 1) * n_radial_array_layer - 1],
            ])
            bound_toroidal_strain.extend([
                sig_data["Toroidal strain"][ii * n_radial_array_layer],
                sig_data["Toroidal strain"][(ii + 1) * n_radial_array_layer - 1],
            ])
            bound_vertical_strain.extend([
                sig_data["Vertical strain"][ii * n_radial_array_layer],
                sig_data["Vertical strain"][(ii + 1) * n_radial_array_layer - 1],
            ])
            for jj in range(n_radial_array_layer):
                radial_strain[ii].append(
                    sig_data["Radial strain"][ii * n_radial_array_layer + jj]
                )
                toroidal_strain[ii].append(
                    sig_data["Toroidal strain"][ii * n_radial_array_layer + jj]
                )
                vertical_strain[ii].append(
                    sig_data["Vertical strain"][ii * n_radial_array_layer + jj]
                )

                if "WP smeared stress (MPa)" in sig_data:
                    wp_vertical_stress.append(sig_data["WP smeared stress (MPa)"][jj])

    axis_tick_size = 12
    legend_size = 10
    mark_size = 10
    line_width = 3.5

    # PLOT 1 : Stress summary
    # ------------------------

    ax = axis[0]
    for ii in range(n_layers):
        ax.plot(
            radius[ii],
            radial_stress[ii],
            "-",
            linewidth=line_width,
            color="lightblue",
        )
        ax.plot(
            radius[ii],
            toroidal_stress[ii],
            "-",
            linewidth=line_width,
            color="wheat",
        )
        ax.plot(
            radius[ii],
            vertical_stress[ii],
            "-",
            linewidth=line_width,
            color="lightgrey",
        )
        ax.plot(radius[ii], tresca_stress[ii], "-", linewidth=line_width, color="pink")
        ax.plot(radius[ii], vm_stress[ii], "-", linewidth=line_width, color="violet")
    ax.plot(
        radius[0],
        radial_stress[0],
        "--",
        color="dodgerblue",
        label=r"$\sigma_{rr}$",
    )
    ax.plot(
        radius[0],
        toroidal_stress[0],
        "--",
        color="orange",
        label=r"$\sigma_{\theta\theta}$",
    )
    ax.plot(
        radius[0],
        vertical_stress[0],
        "--",
        color="mediumseagreen",
        label=r"$\sigma_{zz}$",
    )
    ax.plot(
        radius[0],
        tresca_stress[0],
        "-",
        color="crimson",
        label=r"$\sigma_{TRESCA}$",
    )
    ax.plot(
        radius[0],
        vm_stress[0],
        "-",
        color="darkviolet",
        label=r"$\sigma_{Von\ mises}$",
    )
    for ii in range(1, n_layers):
        ax.plot(radius[ii], radial_stress[ii], "--", color="dodgerblue")
        ax.plot(radius[ii], toroidal_stress[ii], "--", color="orange")
        ax.plot(radius[ii], vertical_stress[ii], "--", color="mediumseagreen")
        ax.plot(radius[ii], tresca_stress[ii], "-", color="crimson")
        ax.plot(radius[ii], vm_stress[ii], "-", color="darkviolet")
    ax.plot(
        bound_radius,
        bound_radial_stress,
        "|",
        markersize=mark_size,
        color="dodgerblue",
    )
    ax.plot(
        bound_radius,
        bound_toroidal_stress,
        "|",
        markersize=mark_size,
        color="orange",
    )
    ax.plot(
        bound_radius,
        bound_vertical_stress,
        "|",
        markersize=mark_size,
        color="mediumseagreen",
    )
    ax.plot(
        bound_radius,
        bound_tresca_stress,
        "|",
        markersize=mark_size,
        color="crimson",
    )
    ax.plot(bound_radius, bound_vm_stress, "|", markersize=mark_size, color="darkviolet")
    ax.grid(True)
    ax.set_ylabel(r"$\sigma$ [$MPa$]", fontsize=axis_tick_size)
    ax.set_title("Structure Stress Summary")
    ax.legend(loc="center left", bbox_to_anchor=(1, 0.5), fontsize=legend_size)

    # PLOT 2 : Smeared stress summary
    # ------------------------
    ax = axis[1]
    for ii in range(n_layers):
        ax.plot(
            radius[ii],
            radial_smeared_stress[ii],
            "-",
            linewidth=line_width,
            color="lightblue",
        )
        ax.plot(
            radius[ii],
            toroidal_smeared_stress[ii],
            "-",
            linewidth=line_width,
            color="wheat",
        )
        ax.plot(
            radius[ii],
            vertical_smeared_stress[ii],
            "-",
            linewidth=line_width,
            color="lightgrey",
        )
        ax.plot(
            radius[ii],
            tresca_smeared_stress[ii],
            "-",
            linewidth=line_width,
            color="pink",
        )
    ax.plot(
        radius[0],
        radial_smeared_stress[0],
        "--",
        color="dodgerblue",
        label=r"$\sigma_{rr}^\mathrm{smeared}$",
    )
    ax.plot(
        radius[0],
        toroidal_smeared_stress[0],
        "--",
        color="orange",
        label=r"$\sigma_{\theta\theta}^\mathrm{smeared}$",
    )
    ax.plot(
        radius[0],
        vertical_smeared_stress[0],
        "--",
        color="mediumseagreen",
        label=r"$\sigma_{zz}^\mathrm{smeared}$",
    )
    ax.plot(
        radius[0],
        tresca_smeared_stress[0],
        "-",
        color="crimson",
        label=r"$\sigma_{TRESCA}^\mathrm{smeared}$",
    )
    for ii in range(1, n_layers):
        ax.plot(radius[ii], radial_smeared_stress[ii], "--", color="dodgerblue")
        ax.plot(radius[ii], toroidal_smeared_stress[ii], "--", color="orange")
        ax.plot(radius[ii], vertical_smeared_stress[ii], "--", color="mediumseagreen")
        ax.plot(radius[ii], tresca_smeared_stress[ii], "-", color="crimson")
    ax.plot(
        bound_radius,
        bound_radial_smeared_stress,
        "|",
        markersize=mark_size,
        color="dodgerblue",
    )
    ax.plot(
        bound_radius,
        bound_toroidal_smeared_stress,
        "|",
        markersize=mark_size,
        color="orange",
    )
    ax.plot(
        bound_radius,
        bound_vertical_smeared_stress,
        "|",
        markersize=mark_size,
        color="mediumseagreen",
    )
    ax.plot(
        bound_radius,
        bound_tresca_smeared_stress,
        "|",
        markersize=mark_size,
        color="crimson",
    )
    ax.grid(True)
    ax.set_ylabel(r"$\sigma$ [$MPa$]", fontsize=axis_tick_size)
    ax.set_title("Smeared Stress Summary")
    ax.legend(loc="center left", bbox_to_anchor=(1, 0.5), fontsize=legend_size)

    # PLOT 4 : Displacement
    # ----------------------
    ax = axis[2]
    ax.plot(radius[0], radial_displacement[0], color="dodgerblue")
    for ii in range(1, n_layers):
        ax.plot(radius[ii], radial_displacement[ii], color="dodgerblue")
    ax.grid(True)
    ax.set_ylabel(r"$u_{r}$ [mm]", fontsize=axis_tick_size)
    ax.set_xlabel(r"$R$ [$m$]", fontsize=axis_tick_size)
    ax.set_title("Radial Displacement")
    # Only set legend for the last plot if needed

    # Set x-label only on the last axis
    axis[2].set_xlabel(r"$R$ [$m$]", fontsize=axis_tick_size)

    # Set minor ticks on for all axes
    for ax in axis:
        ax.minorticks_on()
    # Set x-ticks and y-ticks font size for all axes
    for ax in axis:
        ax.tick_params(axis="x", labelsize=axis_tick_size)
        ax.tick_params(axis="y", labelsize=axis_tick_size)
    plt.tight_layout()

plot_blkt_pipe_bends(fig, m_file, scan)

Plot the blanket pipe bends on the given axis, with axes in mm.

Parameters:

Name Type Description Default
fig
required
m_file
required
scan int
required
Source code in process/core/io/plot_proc.py
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
def plot_blkt_pipe_bends(fig, m_file, scan: int):
    """Plot the blanket pipe bends on the given axis, with axes in mm.

    Parameters
    ----------
    fig :

    m_file :

    scan: int :

    """

    ax_90 = fig.add_subplot(331)
    ax_180 = fig.add_subplot(334)

    # Get pipe radius from m_file, fallback to 0.1 m
    r = m_file.get("radius_blkt_channel", scan=scan)
    elbow_radius_90 = m_file.get("radius_blkt_channel_90_bend", scan=scan)

    # --- 90 degree bend ---
    theta_90 = np.linspace(0, np.pi / 2, 100)
    # Convert coordinates from meters to millimeters
    x_center_90 = elbow_radius_90 * np.cos(theta_90) * 1000
    y_center_90 = elbow_radius_90 * np.sin(theta_90) * 1000
    x_outer_90 = (elbow_radius_90 + r) * np.cos(theta_90) * 1000
    y_outer_90 = (elbow_radius_90 + r) * np.sin(theta_90) * 1000
    x_inner_90 = (elbow_radius_90 - r) * np.cos(theta_90) * 1000
    y_inner_90 = (elbow_radius_90 - r) * np.sin(theta_90) * 1000

    ax_90.plot(
        x_center_90, y_center_90, color="black", linestyle="--", label="Centerline"
    )
    ax_90.plot(x_outer_90, y_outer_90, color="black")
    ax_90.plot(x_inner_90, y_inner_90, color="black")
    ax_90.fill(
        np.concatenate([x_outer_90, x_inner_90[::-1]]),
        np.concatenate([y_outer_90, y_inner_90[::-1]]),
        color="lightgrey",
        alpha=1.0,
    )
    ax_90.set_aspect("equal")
    ax_90.set_xlabel("X [mm]")
    ax_90.set_ylabel("Y [mm]")
    ax_90.set_title("Blanket Pipe 90° Bend")
    ax_90.grid(True, linestyle="--", alpha=0.3)
    # Add legend with radius values
    ax_90.legend(
        [
            f"Centerline\nPipe radius: {r * 1000:.2f} mm\nElbow radius: {elbow_radius_90 * 1000:.2f} mm"
        ],
        loc="upper right",
    )

    # --- 180 degree bend ---

    elbow_radius_180 = m_file.get("radius_blkt_channel_180_bend", scan=scan)

    theta_180 = np.linspace(0, np.pi, 100)
    x_center_180 = elbow_radius_180 * np.cos(theta_180) * 1000
    y_center_180 = elbow_radius_180 * np.sin(theta_180) * 1000
    x_outer_180 = (elbow_radius_180 + r) * np.cos(theta_180) * 1000
    y_outer_180 = (elbow_radius_180 + r) * np.sin(theta_180) * 1000
    x_inner_180 = (elbow_radius_180 - r) * np.cos(theta_180) * 1000
    y_inner_180 = (elbow_radius_180 - r) * np.sin(theta_180) * 1000

    ax_180.plot(
        x_center_180, y_center_180, color="black", linestyle="--", label="Centerline"
    )
    ax_180.plot(x_outer_180, y_outer_180, color="black")
    ax_180.plot(x_inner_180, y_inner_180, color="black")
    ax_180.fill(
        np.concatenate([x_outer_180, x_inner_180[::-1]]),
        np.concatenate([y_outer_180, y_inner_180[::-1]]),
        color="lightgrey",
        alpha=1.0,
    )

    ax_180.set_aspect("equal")
    ax_180.set_xlabel("X [mm]")
    ax_180.set_ylabel("Y [mm]")
    ax_180.set_title("Blanket Pipe 180° Bend")
    ax_180.grid(True, linestyle="--", alpha=0.3)
    # Add legend with radius values
    ax_180.legend(
        [
            f"Centerline\nPipe radius: {r * 1000:.2f} mm\nElbow radius: {elbow_radius_180 * 1000:.2f} mm"
        ],
        loc="upper right",
    )

plot_fw_90_deg_pipe_bend(ax, m_file, scan)

Plot the first wall pipe 90 degree bend on the given axis, with axes in mm.

Parameters:

Name Type Description Default
ax
required
m_file
required
scan int
required
Source code in process/core/io/plot_proc.py
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
def plot_fw_90_deg_pipe_bend(ax, m_file, scan: int):
    """Plot the first wall pipe 90 degree bend on the given axis, with axes in mm.

    Parameters
    ----------
    ax :

    m_file :

    scan: int :

    """

    # Get pipe radius from m_file, fallback to 0.1 m
    r = m_file.get("radius_fw_channel", scan=scan)
    elbow_radius = m_file.get("radius_fw_channel_90_bend", scan=scan)

    # --- 90 degree bend ---
    theta_90 = np.linspace(0, np.pi / 2, 100)
    # Convert coordinates from meters to millimeters
    x_center_90 = elbow_radius * np.cos(theta_90) * 1000
    y_center_90 = elbow_radius * np.sin(theta_90) * 1000
    x_outer_90 = (elbow_radius + r) * np.cos(theta_90) * 1000
    y_outer_90 = (elbow_radius + r) * np.sin(theta_90) * 1000
    x_inner_90 = (elbow_radius - r) * np.cos(theta_90) * 1000
    y_inner_90 = (elbow_radius - r) * np.sin(theta_90) * 1000

    ax.plot(x_center_90, y_center_90, color="black", linestyle="--", label="Centerline")
    ax.plot(x_outer_90, y_outer_90, color="black")
    ax.plot(x_inner_90, y_inner_90, color="black")
    ax.fill(
        np.concatenate([x_outer_90, x_inner_90[::-1]]),
        np.concatenate([y_outer_90, y_inner_90[::-1]]),
        color="lightgrey",
        alpha=1.0,
    )
    ax.set_aspect("equal")
    ax.set_xlabel("X [mm]")
    ax.set_ylabel("Y [mm]")
    ax.set_title("First Wall Pipe 90° Bend")
    ax.grid(True, linestyle="--", alpha=0.3)
    ax.legend(
        [
            f"Centerline\nPipe radius: {r * 1000:.2f} mm\nElbow radius: {elbow_radius * 1000:.2f} mm"
        ],
        loc="upper right",
    )

plot_fusion_rate_profiles(axis, fig, mfile, scan)

Source code in process/core/io/plot_proc.py
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
def plot_fusion_rate_profiles(axis: plt.Axes, fig, mfile: mf.MFile, scan: int):
    # Plot the fusion rate profiles on the given axis
    fusrat_plasma_dt_profile = []
    fusrat_plasma_dd_triton_profile = []
    fusrat_plasma_dd_helion_profile = []
    fusrat_plasma_dhe3_profile = []

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    fusrat_plasma_dt_profile = [
        mfile.get(f"fusrat_plasma_dt_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    fusrat_plasma_dd_triton_profile = [
        mfile.get(f"fusrat_plasma_dd_triton_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    fusrat_plasma_dd_helion_profile = [
        mfile.get(f"fusrat_plasma_dd_helion_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    fusrat_plasma_dhe3_profile = [
        mfile.get(f"fusrat_plasma_dhe3_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    fusrat_plasma_total_profile = [
        fusrat_plasma_dt_profile[i]
        + fusrat_plasma_dd_triton_profile[i]
        + fusrat_plasma_dd_helion_profile[i]
        + fusrat_plasma_dhe3_profile[i]
        for i in range(len(fusrat_plasma_dt_profile))
    ]

    axis.spines["left"].set_color("red")
    axis.yaxis.label.set_color("black")
    axis.tick_params(axis="y", colors="red")

    # Plot fusion rates (dashed lines, left axis) with axis color and different linestyles
    axis.plot(
        np.linspace(0, 1, len(fusrat_plasma_dt_profile)),
        fusrat_plasma_dt_profile,
        color=axis.spines["left"].get_edgecolor(),
        linestyle="-",
        label=r"$\mathrm{D-T}$",
    )
    axis.plot(
        np.linspace(0, 1, len(fusrat_plasma_dd_triton_profile)),
        fusrat_plasma_dd_triton_profile,
        color=axis.spines["left"].get_edgecolor(),
        linestyle=":",
        label=r"$\mathrm{D-D \ Triton}$",
    )
    axis.plot(
        np.linspace(0, 1, len(fusrat_plasma_dd_helion_profile)),
        fusrat_plasma_dd_helion_profile,
        color=axis.spines["left"].get_edgecolor(),
        linestyle="-.",
        label=r"$\mathrm{D-D \ Helion}$",
    )
    axis.plot(
        np.linspace(0, 1, len(fusrat_plasma_dhe3_profile)),
        fusrat_plasma_dhe3_profile,
        color=axis.spines["left"].get_edgecolor(),
        linestyle="--",
        label=r"$\mathrm{D-3He}$",
    )
    axis.plot(
        np.linspace(0, 1, len(fusrat_plasma_total_profile)),
        fusrat_plasma_total_profile,
        color=axis.spines["left"].get_edgecolor(),
        linestyle="None",
        marker="d",
        markersize=1,
        label=r"Total",
    )

    # Plot fusion power (solid lines, right axis) with axis color and different linestyles
    ax2 = axis.twinx()
    ax2.spines["right"].set_color("blue")
    ax2.yaxis.label.set_color("black")
    ax2.tick_params(axis="y", colors="blue")
    ax2.plot(
        np.linspace(0, 1, len(fusrat_plasma_dt_profile)),
        np.array(fusrat_plasma_dt_profile) * constants.D_T_ENERGY,
        color=ax2.spines["right"].get_edgecolor(),
        linestyle="-",
    )

    ax2.plot(
        np.linspace(0, 1, len(fusrat_plasma_dd_triton_profile)),
        np.array(fusrat_plasma_dd_triton_profile) * constants.DD_TRITON_ENERGY,
        color=ax2.spines["right"].get_edgecolor(),
        linestyle=":",
    )
    ax2.plot(
        np.linspace(0, 1, len(fusrat_plasma_dd_helion_profile)),
        np.array(fusrat_plasma_dd_helion_profile) * constants.DD_HELIUM_ENERGY,
        color=ax2.spines["right"].get_edgecolor(),
        linestyle="-.",
    )
    ax2.plot(
        np.linspace(0, 1, len(fusrat_plasma_dhe3_profile)),
        np.array(fusrat_plasma_dhe3_profile) * constants.D_HELIUM_ENERGY,
        color=ax2.spines["right"].get_edgecolor(),
        linestyle="--",
    )
    ax2.plot(
        np.linspace(0, 1, len(fusrat_plasma_total_profile)),
        (
            np.array(fusrat_plasma_dhe3_profile) * constants.D_HELIUM_ENERGY
            + np.array(fusrat_plasma_dd_helion_profile) * constants.DD_HELIUM_ENERGY
            + np.array(fusrat_plasma_dd_triton_profile) * constants.DD_TRITON_ENERGY
            + np.array(fusrat_plasma_dt_profile) * constants.D_T_ENERGY
        ),
        color=ax2.spines["right"].get_edgecolor(),
        linestyle="None",
        marker="d",
        markersize=1,
        label=r"Total",
    )

    # =================================================

    # Compute cumulative integral (trapezoidal) of the total fusion rate profile vs normalised radius
    rho_c = np.linspace(0.0, 1.0, len(fusrat_plasma_total_profile))
    y_total = np.asarray(fusrat_plasma_total_profile, dtype=float)

    # handle degenerate case
    if y_total.size < 2:
        cum_trap = np.array([0.0, y_total.sum()])
    else:
        dx = rho_c[1] - rho_c[0]
        # cumulative trapezoid: integral from 0 to rho[i]
        cum_trap_mid = np.cumsum((y_total[1:] + y_total[:-1]) * 0.5 * dx)
        cum_trap = np.concatenate(([0.0], cum_trap_mid))

    # Normalize to reported total fusion rate if available, otherwise keep raw integral
    reported_total = mfile.data.get("fusrat_total")
    if reported_total is not None:
        total_reported = float(reported_total.get_scan(scan))
        # avoid division by zero
        norm_factor = cum_trap[-1] if cum_trap[-1] > 0 else 1.0
        cum_reactions = cum_trap / norm_factor * total_reported
    else:
        cum_reactions = cum_trap

    # Plot cumulative reactions on a separate right-hand axis (offset)

    axis.plot(
        rho_c,
        cum_reactions,
        color="black",
        linewidth=2,
        label="Cumulative total reactions",
    )

    # mark the rho location where cumulative reactions reach 50% of the total
    total_reactions = float(cum_reactions[-1]) if np.size(cum_reactions) > 0 else 0.0
    if total_reactions > 0.0:
        target = 0.5 * total_reactions
        idxs = np.where(cum_reactions >= target)[0]
        rho50 = float(rho_c[idxs[0]]) if idxs.size > 0 else float(rho_c[-1])

        # vertical line at 50% cumulative reactions
        axis.axvline(
            rho50,
            color="black",
            linestyle="--",
            linewidth=1.5,
            zorder=1,
            label="50% total\nreactions",
        )

    # =================================================

    axis.set_xlabel("$\\rho \\ [r/a]$")
    axis.set_ylabel("Fusion Rate [reactions/second]")
    axis.legend(
        loc="lower left",
        edgecolor="black",
        facecolor="white",
        labelcolor="black",
        framealpha=1.0,
        frameon=True,
    )
    axis.set_yscale("log")
    axis.grid(True, which="both", linestyle="--", alpha=0.5)
    axis.set_xlim([0, 1.025])
    axis.minorticks_on()
    axis.set_ylim([1e10, 1e23])
    axis.yaxis.set_major_locator(plt.LogLocator(base=10.0, numticks=10))
    axis.yaxis.set_minor_locator(
        plt.LogLocator(base=10.0, subs=np.arange(1, 10) * 0.1, numticks=100)
    )
    axis.tick_params(axis="y", which="minor", colors="red")

    ax2.set_title("Fusion Rate and Fusion Power Profiles")
    ax2.set_ylabel("Fusion Power [W]")
    ax2.set_yscale("log")
    ax2.minorticks_on()
    ax2.yaxis.set_major_locator(plt.LogLocator(base=10.0, numticks=10))
    ax2.yaxis.set_minor_locator(
        plt.LogLocator(base=10.0, subs=np.arange(1, 10) * 0.1, numticks=100)
    )
    ax2.tick_params(axis="y", which="minor", colors="blue")

    # =================================================

    # Add plasma volume, areas and shaping information
    textstr_general = (
        f"Total fusion rate: {mfile.get('fusrat_total', scan=scan):.4e} reactions/s\n"
        f"Total fusion rate density: {mfile.get('fusden_total', scan=scan):.4e} reactions/m3/s\n"
        f"Plasma fusion rate density: {mfile.get('fusden_plasma', scan=scan):.4e} reactions/m3/s\n"
    )

    axis.text(
        0.05,
        0.85,
        textstr_general,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # ============================================================================

    textstr_dt = (
        f"Total fusion power: {mfile.get('p_dt_total_mw', scan=scan):,.2f} MW\n"
        f"Plasma fusion power: {mfile.get('p_plasma_dt_mw', scan=scan):,.2f} MW                     \n"
        f"Beam fusion power: {mfile.get('p_beam_dt_mw', scan=scan):,.2f} MW\n"
    )

    axis.text(
        0.05,
        0.75,
        textstr_dt,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.24,
        0.8,
        "$\\text{D - T}$",
        fontsize=20,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =================================================

    textstr_dd = (
        f"Total fusion power: {mfile.get('p_dd_total_mw', scan=scan):,.2f} MW\n"
        f"Tritium branching ratio: {mfile.get('f_dd_branching_trit', scan=scan):.4f}                      \n"
    )

    axis.text(
        0.05,
        0.65,
        textstr_dd,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.22,
        0.685,
        "$\\text{D - D}$",
        fontsize=20,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =================================================

    textstr_dhe3 = f"Total fusion power: {mfile.get('p_dhe3_total_mw', scan=scan):,.2f} MW                                 \n\n"

    axis.text(
        0.05,
        0.55,
        textstr_dhe3,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "lightyellow",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.21,
        0.59,
        "$\\text{D - 3He}$",
        fontsize=20,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =================================================

    textstr_alpha = (
        f"Total power: {mfile.get('p_alpha_total_mw', scan=scan):.2f} MW\n"
        f"Plasma power: {mfile.get('p_plasma_alpha_mw', scan=scan):.2f} MW\n"
        f"Beam power: {mfile.get('p_beam_alpha_mw', scan=scan):.2f} MW\n\n"
        f"Rate density total: {mfile.get('fusden_alpha_total', scan=scan):.4e} particles/m3/sec\n"
        f"Rate density, plasma: {mfile.get('fusden_plasma_alpha', scan=scan):.4e} particles/m3/sec\n\n"
        f"Total power density: {mfile.get('pden_alpha_total_mw', scan=scan):.4e} MW/m3\n"
        f"Plasma power density: {mfile.get('pden_plasma_alpha_mw', scan=scan):.4e} MW/m3\n\n"
        f"Power per unit volume transferred to electrons: {mfile.get('f_pden_alpha_electron_mw', scan=scan):.4e} MW/m3\n"
        f"Power per unit volume transferred to ions: {mfile.get('f_pden_alpha_ions_mw', scan=scan):.4e} MW/m3\n\n"
    )

    axis.text(
        0.05,
        0.25,
        textstr_alpha,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "red",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.35,
        0.45,
        "$\\alpha$",
        fontsize=22,
        verticalalignment="top",
        transform=fig.transFigure,
    )

    # =================================================

    textstr_neutron = (
        f"Total power: {mfile.get('p_neutron_total_mw', scan=scan):,.2f} MW\n"
        f"Plasma power: {mfile.get('p_plasma_neutron_mw', scan=scan):,.2f} MW\n"
        f"Beam power: {mfile.get('p_beam_neutron_mw', scan=scan):,.2f} MW\n\n"
        f"Total power density: {mfile.get('pden_neutron_total_mw', scan=scan):,.4e} MW/m3\n"
        f"Plasma power density: {mfile.get('pden_plasma_neutron_mw', scan=scan):,.4e} MW/m3\n"
    )

    axis.text(
        0.05,
        0.1,
        textstr_neutron,
        fontsize=9,
        verticalalignment="bottom",
        horizontalalignment="left",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "grey",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.25,
        0.2,
        "$n$",
        fontsize=20,
        verticalalignment="top",
        transform=fig.transFigure,
    )

plot_cover_page(axis, mfile, scan, fig, radial_build, colour_scheme)

Plots a cover page for the PROCESS run, including run title, date, user, and summary info.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis object to plot on.

required
mfile MFile

The MFILE data object containing run info.

required
scan int

The scan number to use for extracting data.

required
fig Figure

The matplotlib figure object for additional annotations.

required
radial_build RadialBuild
required
colour_scheme Literal[1, 2]
required
Source code in process/core/io/plot_proc.py
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
def plot_cover_page(
    axis: plt.Axes,
    mfile: mf.MFile,
    scan: int,
    fig,
    radial_build: RadialBuild,
    colour_scheme: Literal[1, 2],
):
    """Plots a cover page for the PROCESS run, including run title, date, user, and summary info.

    Parameters
    ----------
    axis : plt.Axes
        The matplotlib axis object to plot on.
    mfile : mf.MFile
        The MFILE data object containing run info.
    scan : int
        The scan number to use for extracting data.
    fig : plt.Figure
        The matplotlib figure object for additional annotations.
    radial_build:

    colour_scheme:

    """
    axis.axis("off")
    title = mfile.get("runtitle", scan=-1)
    date = mfile.get("date", scan=-1)
    time = mfile.get("time", scan=-1)
    user = mfile.get("username", scan=-1)
    procver = mfile.get("procver", scan=-1)
    tagno = mfile.get("tagno", scan=-1)
    branch_name = mfile.get("branch_name", scan=-1)
    fileprefix = mfile.get("fileprefix", scan=-1)
    optmisation_switch = mfile.get("ioptimz", scan=-1)
    minmax_switch = mfile.get("minmax", scan=-1) or "N/A"
    ifail = mfile.get("ifail", scan=-1)
    nvars = mfile.get("nvar", scan=-1)
    # Objective_function_name
    objf_name = mfile.get("objf_name", scan=-1)
    # Square_root_of_the_sum_of_squares_of_the_constraint_residuals
    sqsumsq = mfile.get("sqsumsq", scan=-1)
    # VMCON_convergence_parameter
    convergence_parameter = mfile.get("convergence_parameter", scan=-1) or "N/A"
    # Number_of_optimising_solver_iterations
    nviter = int(mfile.get("nviter", scan=-1)) or "N/A"

    # Objective name with minimising/maximising
    if isinstance(minmax_switch, str):
        objective_text = ""
    elif minmax_switch >= 0:
        minmax_switch = int(minmax_switch)
        objective_text = f"• Minimising {objf_name}"
    else:
        minmax_switch = int(minmax_switch)
        objective_text = f"• Maximising {objf_name}"

    axis.text(
        0.1,
        0.85,
        "PROCESS Run Summary",
        fontsize=28,
        ha="left",
        va="center",
        transform=fig.transFigure,
    )

    # Box 1: Run Info
    run_info = (
        f"• Run Title: {title}\n"
        f"• Date: {date}   Time: {time}\n"
        f"• User: {user}\n"
        f"• PROCESS Version: {procver}"
    )
    axis.text(
        0.1,
        0.72,
        run_info,
        fontsize=16,
        ha="left",
        va="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#e0f7fa",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Box 2: File/Branch Info
    # Wrap the whole "Branch Name: ..." line if too long
    max_line_len = 60
    branch_line = textwrap.fill(f"• Branch Name: {branch_name}", max_line_len)
    fileprefix = textwrap.fill(f"File Prefix: {fileprefix}", max_line_len)

    file_info = f"• Tag Number: {tagno}\n{branch_line}\n{fileprefix}"
    axis.text(
        0.1,
        0.57,
        file_info,
        fontsize=14,
        ha="left",
        va="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#fffde7",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    # Box 3: Run Settings
    settings_info = (
        f"• Optimisation Switch: {int(optmisation_switch)}\n"
        f"• Figure of Merit Switch (minmax): {minmax_switch}\n"
        f"• Fail Status (ifail): {int(ifail)}\n"
        f"• Number of Iteration Variables: {int(nvars)}\n"
        f"{objective_text}\n"
        f"• Constraint Residuals (sqrt sum sq): {sqsumsq}\n"
        f"• Convergence Parameter: {convergence_parameter}\n"
        f"• Solver Iterations: {nviter}"
    )
    axis.text(
        0.1,
        0.41,
        settings_info,
        fontsize=14,
        ha="left",
        va="top",
        transform=fig.transFigure,
        bbox={
            "boxstyle": "round",
            "facecolor": "#f3e5f5",
            "alpha": 1.0,
            "linewidth": 2,
        },
    )

    axis.text(
        0.1,
        0.15,
        "For more information, see the following pages.",
        fontsize=12,
        ha="left",
        va="center",
        transform=fig.transFigure,
        color="gray",
    )

    # Add a small poloidal cross-section inset on the cover page
    inset_ax = fig.add_axes([0.55, 0.2, 0.55, 0.55], aspect="equal")
    poloidal_cross_section(
        inset_ax,
        mfile,
        scan,
        demo_ranges=False,
        radial_build=radial_build,
        colour_scheme=colour_scheme,
    )
    inset_ax.set_title("")  # Remove the plot title
    inset_ax.axis("off")

plot_plasma_pressure_profiles(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
def plot_plasma_pressure_profiles(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Plot the plasma pressure profiles on the given axis
    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    pres_plasma_profile = [
        mfile.get(f"pres_plasma_electron_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_ion = [
        mfile.get(f"pres_plasma_ion_total_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_thermal_total_profile = [
        mfile.get(f"pres_plasma_thermal_total_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_fuel = [
        mfile.get(f"pres_plasma_fuel_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_kpa = [p / 1000.0 for p in pres_plasma_profile]
    pres_plasma_profile_ion_kpa = [p / 1000.0 for p in pres_plasma_profile_ion]
    pres_plasma_profile_fuel_kpa = [p / 1000.0 for p in pres_plasma_profile_fuel]
    pres_plasma_profile_total_kpa = [
        p / 1000.0 for p in pres_plasma_thermal_total_profile
    ]

    axis.plot(
        np.linspace(0, 1, len(pres_plasma_profile_kpa)),
        pres_plasma_profile_kpa,
        color="blue",
        label="Electron",
    )
    axis.plot(
        np.linspace(0, 1, len(pres_plasma_profile_ion_kpa)),
        pres_plasma_profile_ion_kpa,
        color="Red",
        label="Ion-total",
    )
    axis.plot(
        np.linspace(0, 1, len(pres_plasma_profile_fuel_kpa)),
        pres_plasma_profile_fuel_kpa,
        color="orange",
        label="Fuel",
    )
    axis.plot(
        np.linspace(0, 1, len(pres_plasma_profile_total_kpa)),
        pres_plasma_profile_total_kpa,
        color="green",
        label="Total",
    )

    # Plot horizontal line for volume-average thermal pressure (converted to kPa)
    p_vol_kpa = mfile.get("pres_plasma_thermal_vol_avg", scan=scan) / 1000.0
    axis.axhline(
        p_vol_kpa,
        color="black",
        linestyle="--",
        linewidth=1.2,
        label="Volume avg",
        zorder=5,
    )

    axis.set_xlabel("$\\rho$ [r/a]")
    axis.set_ylabel("Thermal Pressure [kPa]")
    axis.minorticks_on()
    axis.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.5)
    axis.set_title("Plasma Thermal Pressure Profiles")
    axis.grid(True, linestyle="--", alpha=0.5)
    axis.set_xlim([0, 1.025])
    axis.set_ylim(bottom=0)
    axis.legend()

    textstr_pressure = "\n".join((
        rf"$p_0$: {mfile.get('pres_plasma_thermal_on_axis', scan=scan) / 1000:,.3f} kPa",
        rf"$\langle p_{{\text{{total}}}} \rangle_\text{{V}}$: {mfile.get('pres_plasma_thermal_vol_avg', scan=scan) / 1000:,.3f} kPa",
    ))

    axis.text(
        0.5,
        1.2,
        textstr_pressure,
        transform=axis.transAxes,
        fontsize=9,
        verticalalignment="top",
        horizontalalignment="center",
        bbox={"boxstyle": "round", "facecolor": "wheat", "alpha": 0.5},
    )

plot_plasma_pressure_gradient_profiles(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
def plot_plasma_pressure_gradient_profiles(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Get the plasma pressure profiles
    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    pres_plasma_profile = [
        mfile.get(f"pres_plasma_electron_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_ion = [
        mfile.get(f"pres_plasma_ion_total_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_total = [
        mfile.get(f"pres_plasma_thermal_total_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_fuel = [
        mfile.get(f"pres_plasma_fuel_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_kpa = np.array(pres_plasma_profile) / 1000.0
    pres_plasma_profile_ion_kpa = np.array(pres_plasma_profile_ion) / 1000.0
    pres_plasma_profile_fuel_kpa = np.array(pres_plasma_profile_fuel) / 1000.0
    pres_plasma_profile_total_kpa = np.array(pres_plasma_profile_total) / 1000.0

    # Calculate the normalised radius
    rho = np.linspace(0, 1, len(pres_plasma_profile_kpa))

    # Compute gradients using numpy.gradient
    grad_electron = np.gradient(pres_plasma_profile_kpa, rho)
    grad_ion = np.gradient(pres_plasma_profile_ion_kpa, rho)
    grad_total = np.gradient(pres_plasma_profile_total_kpa, rho)
    grad_fuel = np.gradient(pres_plasma_profile_fuel_kpa, rho)

    axis.plot(rho, grad_electron, color="blue", label="Electron")
    axis.plot(rho, grad_ion, color="red", label="Ion")
    axis.plot(rho, grad_total, color="green", label="Total")
    axis.plot(rho, grad_fuel, color="orange", label="Fuel")
    axis.set_xlabel("$\\rho$ [r/a]")
    axis.set_ylabel("$dP/dr$ [kPa / m]")
    axis.minorticks_on()
    axis.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.5)
    axis.set_title("Plasma Thermal Pressure Gradient Profiles")
    axis.grid(True, linestyle="--", alpha=0.5)
    axis.set_xlim([0, 1.025])
    axis.legend()

plot_plasma_poloidal_pressure_contours(axis, mfile, scan)

Plot plasma poloidal pressure contours inside the plasma boundary.

This function visualizes the poloidal pressure distribution inside the plasma boundary by interpolating the pressure profile onto a grid defined by the plasma geometry. The pressure is shown as filled contours, with the plasma boundary overlaid.

Parameters:

Name Type Description Default
axis Axes

Matplotlib axis object to plot on.

required
mfile mfile: mf.MFile

MFILE data object containing plasma and geometry data.

required
scan int

Scan number to use for extracting data.

required
Source code in process/core/io/plot_proc.py
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
def plot_plasma_poloidal_pressure_contours(axis: plt.Axes, mfile: mf.MFile, scan: int):
    """Plot plasma poloidal pressure contours inside the plasma boundary.

    This function visualizes the poloidal pressure distribution inside the plasma boundary
    by interpolating the pressure profile onto a grid defined by the plasma geometry.
    The pressure is shown as filled contours, with the plasma boundary overlaid.

    Parameters
    ----------
    axis : matplotlib.axes.Axes
        Matplotlib axis object to plot on.
    mfile : mfile: mf.MFile
        MFILE data object containing plasma and geometry data.
    scan : int
        Scan number to use for extracting data.
    """

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    # Get pressure profile (function of normalised radius rho, 0..1)
    pres_plasma_electron_profile = [
        mfile.get(f"pres_plasma_electron_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    pres_plasma_profile_ion = [
        mfile.get(f"pres_plasma_ion_total_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    # Convert pressure to kPa
    pres_plasma_electron_profile_kpa = [p / 1000.0 for p in pres_plasma_electron_profile]
    pres_plasma_profile_ion_kpa = [p / 1000.0 for p in pres_plasma_profile_ion]
    pres_plasma_profile = [
        e + i
        for e, i in zip(
            pres_plasma_electron_profile_kpa, pres_plasma_profile_ion_kpa, strict=False
        )
    ]

    pressure_grid, r_grid, z_grid = interp1d_profile(pres_plasma_profile, mfile, scan)

    # Mask points outside the plasma boundary (optional, but grid is inside by construction)
    # Plot filled contour
    c = axis.contourf(r_grid, z_grid, pressure_grid, levels=50, cmap="plasma")
    c = axis.contourf(r_grid, -z_grid, pressure_grid, levels=50, cmap="plasma")

    # Add colorbar for pressure (now in kPa)
    # You can control the location using the 'location' argument ('left', 'right', 'top', 'bottom')
    # For more control, use 'ax' or 'fraction', 'pad', etc.
    # Example: location="right", pad=0.05, fraction=0.05
    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)

    axis.figure.colorbar(
        c, ax=axis, label="Pressure [kPa]", location="left", anchor=(-0.25, 0.5)
    )

    axis.set_aspect("equal")
    axis.set_xlabel("R [m]")
    axis.set_xlim(rmajor - 1.2 * rminor, rmajor + 1.2 * rminor)
    axis.set_ylim(
        -1.2 * rminor * mfile.get("kappa", scan=scan),
        1.2 * mfile.get("kappa", scan=scan) * rminor,
    )
    axis.set_ylabel("Z [m]")
    axis.set_title("Plasma Poloidal Pressure Contours")
    axis.plot(
        rmajor,
        0,
        marker="o",
        color="red",
        markersize=6,
        markeredgecolor="black",
        zorder=100,
    )

interp1d_profile(profile, mfile, scan)

Source code in process/core/io/plot_proc.py
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
def interp1d_profile(profile, mfile: mf.MFile, scan: int):
    # Get plasma geometry and boundary
    pg = plasma_geometry(
        rmajor=mfile.get("rmajor", scan=scan),
        rminor=mfile.get("rminor", scan=scan),
        triang=mfile.get("triang", scan=scan),
        kappa=mfile.get("kappa", scan=scan),
        i_single_null=mfile.get("i_single_null", scan=scan),
        i_plasma_shape=mfile.get("i_plasma_shape", scan=scan),
        square=mfile.get("plasma_square", scan=scan),
    )

    # Create a grid of (R, Z) points inside the plasma boundary
    n_rho = 500
    n_theta = 720
    rho = np.linspace(0, 1, n_rho)
    theta = np.linspace(0, 2 * np.pi, n_theta)
    rho_grid, theta_grid = np.meshgrid(rho, theta)

    # Map (rho, theta) to (R, Z) using plasma boundary shape
    # For each theta, get boundary (R, Z), then scale by rho
    boundary_r = pg.rs
    boundary_z = pg.zs
    # Interpolate boundary for all theta
    boundary_theta = np.arctan2(boundary_z - pg.zs.mean(), boundary_r - pg.rs.mean())
    # Ensure boundary_theta is monotonic and covers [0, 2pi]
    boundary_theta = np.unwrap(boundary_theta)
    # Sort boundary_theta and corresponding r/z for monotonic interpolation
    sort_idx = np.argsort(boundary_theta)
    boundary_theta = boundary_theta[sort_idx]
    boundary_r = boundary_r[sort_idx]
    boundary_z = boundary_z[sort_idx]
    # Extend boundary to cover full [0, 2pi] if needed
    if boundary_theta[0] > 0 or boundary_theta[-1] < 2 * np.pi:
        boundary_theta = np.concatenate(([0], boundary_theta, [2 * np.pi]))
        boundary_r = np.concatenate(([boundary_r[0]], boundary_r, [boundary_r[-1]]))
        boundary_z = np.concatenate(([boundary_z[0]], boundary_z, [boundary_z[-1]]))
    # Map theta to boundary r/z
    f_r = interp1d(
        boundary_theta,
        boundary_r,
        kind="linear",
        fill_value="extrapolate",
        assume_sorted=True,
    )
    # Map theta to boundary z
    f_z = interp1d(
        boundary_theta,
        boundary_z,
        kind="linear",
        fill_value="extrapolate",
        assume_sorted=True,
    )
    # For each (theta, rho), get boundary (R, Z), then scale by rho
    # Use the boundary center for scaling, not mean, to avoid vertical offset
    r_center = mfile.get("rmajor", scan=scan)
    z_center = pg.zs.mean()
    r_grid = r_center + (f_r(theta_grid) - r_center) * rho_grid
    z_grid = z_center + (f_z(theta_grid) - z_center) * rho_grid

    # Interpolate profile for each rho
    profile_grid = np.interp(rho_grid, np.linspace(0, 1, len(profile)), profile)

    return profile_grid, r_grid, z_grid

plot_corc_cable_geometry(axis, dia_croco_strand, dx_croco_strand_copper, dr_hts_tape, dx_croco_strand_tape_stack, n_croco_strand_hts_tapes)

Plot the geometry of a CroCo strand cable.

Parameters:

Name Type Description Default
axis Axes

The matplotlib axis to plot on.

required
dia_croco_strand float

Diameter of the CroCo strand (in meters).

required
dx_croco_strand_copper float

Thickness of the copper layer (in meters).

required
dr_hts_tape float

Radius of the HTS tape stack (in meters).

required
dx_croco_strand_tape_stack float

Height of the HTS tape stack (in meters).

required
n_croco_strand_hts_tapes int

Number of HTS tape layers in the stack.

required
Source code in process/core/io/plot_proc.py
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
def plot_corc_cable_geometry(
    axis,
    dia_croco_strand: float,
    dx_croco_strand_copper: float,
    dr_hts_tape: float,
    dx_croco_strand_tape_stack: float,
    n_croco_strand_hts_tapes: int,
):
    """Plot the geometry of a CroCo strand cable.

    Parameters
    ----------
    axis : matplotlib.axes._axes.Axes
        The matplotlib axis to plot on.
    dia_croco_strand : float
        Diameter of the CroCo strand (in meters).
    dx_croco_strand_copper : float
        Thickness of the copper layer (in meters).
    dr_hts_tape : float
        Radius of the HTS tape stack (in meters).
    dx_croco_strand_tape_stack : float
        Height of the HTS tape stack (in meters).
    n_croco_strand_hts_tapes : int
        Number of HTS tape layers in the stack.
    """
    # Plot a circle with the given diameter and copper edges
    circle = Circle(
        (0, 0),
        radius=(dia_croco_strand / 2) * 1000,
        edgecolor="#B87333",
        facecolor="#B87333",
        linewidth=2,
        label="Copper jacket",
    )
    axis.add_patch(circle)

    # Plot an inner circle with copper edges
    circle = Circle(
        (0, 0),
        radius=((dia_croco_strand / 2) - dx_croco_strand_copper) * 1000,
        edgecolor="grey",
        facecolor="grey",
        linewidth=2,
        label="Solder",
    )
    axis.add_patch(circle)

    # Plot a rectangular tape stack in the middle
    rect = Rectangle(
        (-dr_hts_tape / 2 * 1000, -(dx_croco_strand_tape_stack / 2) * 1000),
        width=dr_hts_tape * 1000,
        height=dx_croco_strand_tape_stack * 1000,
        edgecolor="blue",
        facecolor="blue",
        linewidth=2,
        label="HTS Tape Stack",
    )
    axis.add_patch(rect)

    # Slice the tape stack into n_croco_strand_hts_tapes layers
    for i in range(int(n_croco_strand_hts_tapes)):
        y_start = -(dx_croco_strand_tape_stack / 2) * 1000 + i * (
            dx_croco_strand_tape_stack / n_croco_strand_hts_tapes * 1000
        )
        rect = Rectangle(
            (-dr_hts_tape / 2 * 1000, y_start),
            width=dr_hts_tape * 1000,
            height=(dx_croco_strand_tape_stack / n_croco_strand_hts_tapes) * 1000,
            edgecolor="black",
            facecolor="blue",
            linewidth=1,
        )
        axis.add_patch(rect)

    axis.set_xlim(-dia_croco_strand * 0.75 * 1000, dia_croco_strand * 0.75 * 1000)
    axis.set_ylim(-dia_croco_strand * 1000, dia_croco_strand * 1000)
    axis.set_aspect("equal", adjustable="datalim")
    axis.set_title("CroCo Strand Geometry")
    axis.grid(True)
    axis.set_xlabel("X-axis (mm)")
    axis.set_ylabel("Y-axis (mm)")
    axis.minorticks_on()
    axis.legend(loc="upper right")

reaction_plot_grid(rminor, rmajor, kappa, r_grid, z_grid, grid, ax, fractions=(0.25, 0.5, 0.75), colours=('blue', 'yellow', 'red'))

Source code in process/core/io/plot_proc.py
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
def reaction_plot_grid(
    rminor,
    rmajor,
    kappa,
    r_grid,
    z_grid,
    grid,
    ax,
    fractions=(0.25, 0.5, 0.75),
    colours=("blue", "yellow", "red"),
):
    # Mask points outside the plasma boundary (optional, but grid is inside by construction)
    # Plot filled contour

    upper = ax.contourf(r_grid, z_grid, grid, levels=50, cmap="plasma", zorder=2)
    ax.contourf(r_grid, -z_grid, grid, levels=50, cmap="plasma", zorder=2)

    ax.figure.colorbar(
        upper,
        ax=ax,
        label="Fusion Rate [reactions/second]",
        location="left",
        anchor=(-0.25, 0.5),
    )

    ax.set_xlabel("R [m]")
    ax.set_xlim(rmajor - 1.2 * rminor, rmajor + 1.2 * rminor)
    ax.set_ylim(
        -1.2 * rminor * kappa,
        1.2 * kappa * rminor,
    )
    ax.set_ylabel("Z [m]")
    ax.plot(
        rmajor,
        0,
        marker="o",
        color="red",
        markersize=6,
        markeredgecolor="black",
        zorder=100,
    )
    # enable minor ticks and grid for clearer reading
    ax.minorticks_on()
    ax.grid(True, which="major", linestyle="--", linewidth=0.8, alpha=0.7, zorder=1)
    ax.grid(True, which="minor", linestyle=":", linewidth=0.4, alpha=0.5, zorder=1)
    # make minor ticks visible on all sides and draw ticks inward for compact look
    ax.tick_params(which="both", direction="in", top=True, right=True)

    # draw contours at % of the DT peak value (both top and mirrored bottom)
    peak = np.nanmax(grid)
    if peak > 0:
        c_kwargs = {
            "levels": [f * peak for f in fractions],
            "colors": colours,
            "linewidths": 1.5,
        }
        # distinct colours for each level

        # top and mirrored bottom contours (no clabel calls — keep only legend)
        ax.contour(r_grid, z_grid, grid, **c_kwargs)
        ax.contour(r_grid, -z_grid, grid, **c_kwargs)

        # create legend entries (use Line2D proxies so we get one entry per requested level)
        legend_handles = [mpl.lines.Line2D([0], [0], color=c, lw=2) for c in colours]
        legend_labels = ["25% peak", "50% peak", "75% peak"]
        ax.legend(legend_handles, legend_labels, loc="upper right", fontsize=8)

plot_fusion_rate_contours(fig1, fig2, mfile, scan)

Source code in process/core/io/plot_proc.py
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
def plot_fusion_rate_contours(
    fig1,
    fig2,
    mfile: mf.MFile,
    scan: int,
):
    fusrat_plasma_dt_profile = []
    fusrat_plasma_dd_triton_profile = []
    fusrat_plasma_dd_helion_profile = []
    fusrat_plasma_dhe3_profile = []

    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)
    kappa = mfile.get("kappa", scan=scan)
    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    fusrat_plasma_dt_profile = [
        mfile.get(f"fusrat_plasma_dt_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    fusrat_plasma_dd_triton_profile = [
        mfile.get(f"fusrat_plasma_dd_triton_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    fusrat_plasma_dd_helion_profile = [
        mfile.get(f"fusrat_plasma_dd_helion_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]
    fusrat_plasma_dhe3_profile = [
        mfile.get(f"fusrat_plasma_dhe3_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    dt_grid, _r_grid, _z_grid = interp1d_profile(fusrat_plasma_dt_profile, mfile, scan)

    dd_triton_grid, _r_grid, _z_grid = interp1d_profile(
        fusrat_plasma_dd_triton_profile, mfile, scan
    )
    dd_helion_grid, _r_grid, _z_grid = interp1d_profile(
        fusrat_plasma_dd_helion_profile, mfile, scan
    )
    dhe3_grid, r_grid, z_grid = interp1d_profile(fusrat_plasma_dhe3_profile, mfile, scan)

    dt_axes = fig1.add_subplot(121, aspect="equal")
    dd_triton_axes = fig1.add_subplot(122, aspect="equal")
    dd_helion_axes = fig2.add_subplot(121, aspect="equal")
    dhe3_axes = fig2.add_subplot(122, aspect="equal")

    dt_axes.set_title("D+T -> 4He + n Fusion Rate Density Contours")
    reaction_plot_grid(rminor, rmajor, kappa, r_grid, z_grid, dt_grid, dt_axes)

    dd_triton_axes.set_title("D+D -> T + p Fusion Rate Density Contours")
    reaction_plot_grid(
        rminor, rmajor, kappa, r_grid, z_grid, dd_triton_grid, dd_triton_axes
    )
    dd_helion_axes.set_title("D+D -> 3He + n Fusion Rate Density Contours")
    reaction_plot_grid(
        rminor, rmajor, kappa, r_grid, z_grid, dd_helion_grid, dd_helion_axes
    )
    dhe3_axes.set_title("D+3He -> 4He + n Fusion Rate Density Contours")
    reaction_plot_grid(rminor, rmajor, kappa, r_grid, z_grid, dhe3_grid, dhe3_axes)

plot_magnetic_fields_in_plasma(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
def plot_magnetic_fields_in_plasma(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Plot magnetic field profiles inside the plasma boundary

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    # Get toroidal magnetic field profile (in Tesla)
    b_plasma_toroidal_profile = [
        mfile.get(f"b_plasma_toroidal_profile{i}", scan=scan)
        for i in range(2 * n_plasma_profile_elements)
    ]

    # Get major and minor radius for x-axis in metres
    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)

    # Plot magnetic field first (background)
    axis.plot(
        np.linspace(rmajor - rminor, rmajor + rminor, len(b_plasma_toroidal_profile)),
        b_plasma_toroidal_profile,
        color="blue",
        label="Toroidal B-field [T]",
        linewidth=2,
    )

    # Plot plasma on top of magnetic field, displaced vertically by bt
    plot_plasma(axis, mfile, scan, colour_scheme=1)

    # Plot plasma centre dot
    axis.plot(rmajor, 0, marker="o", color="red", markersize=8, label="Plasma Centre")

    v_kwargs = {"color": "green", "linestyle": "--", "linewidth": 1.0}

    # Plot vertical lines at plasma edge
    axis.axvline(rmajor - rminor, **v_kwargs)
    axis.axvline(rmajor + rminor, **v_kwargs)

    h_kwargs = {"color": "blue", "linestyle": "--", "linewidth": 1.0}

    # Plot horizontal line for toroidal magnetic field at plasma inboard
    axis.axhline(mfile.get(f"b_plasma_toroidal_profile{0}", scan=scan), **h_kwargs)

    # Plot horizontal line for toroidal magnetic field at plasma centre
    axis.axhline(mfile.get("b_plasma_toroidal_on_axis", scan=scan), **h_kwargs)

    # Plot horizontal line for toroidal magnetic field at plasma outboard
    axis.axhline(b_plasma_toroidal_profile[-1], **h_kwargs)

    # Text box for inboard toroidal field
    axis.text(
        0.1,
        0.025,
        f"$B_{{\\text{{T,inboard}}}}={mfile.get('b_plasma_inboard_toroidal', scan=scan):.2f}$ T",
        verticalalignment="center",
        horizontalalignment="center",
        transform=axis.transAxes,
        bbox={"boxstyle": "round", "facecolor": "wheat", "alpha": 1.0, "linewidth": 2},
    )

    # Text box for outboard toroidal field
    axis.text(
        0.9,
        0.1,
        f"$B_{{\\text{{T,outboard}}}}={mfile.get('b_plasma_outboard_toroidal', scan=scan):.2f}$ T",
        verticalalignment="center",
        horizontalalignment="center",
        transform=axis.transAxes,
        bbox={"boxstyle": "round", "facecolor": "wheat", "alpha": 1.0, "linewidth": 2},
    )

    axis.set_xlabel("Radial Position [m]")
    axis.set_ylabel("Toroidal Magnetic Field [T]")
    axis.set_title("Toroidal Magnetic Field Profile in Plasma")
    axis.minorticks_on()
    # Enable grid for both major and minor ticks
    axis.grid(which="both", linestyle="--", alpha=0.5)
    axis.grid(which="minor", linestyle=":", alpha=0.3)
    axis.legend(loc="lower right")
    axis.set_xlim(rmajor - 1.25 * rminor, rmajor + 1.25 * rminor)

plot_beta_profiles(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
def plot_beta_profiles(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Plot the beta profiles on the given axis

    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    beta_plasma_toroidal_profile = [
        mfile.get(f"beta_thermal_toroidal_profile{i}", scan=scan)
        for i in range(2 * n_plasma_profile_elements)
    ]

    axis.plot(
        np.linspace(-1, 1, 2 * n_plasma_profile_elements),
        beta_plasma_toroidal_profile,
        color="blue",
        label="$\\beta_t$",
    )

    axis.axhline(
        mfile.get("beta_thermal_toroidal_vol_avg", scan=scan),
        color="blue",
        linestyle="--",
        linewidth=1.0,
        label="$\\langle \\beta_t \\rangle_{\\text{V}}$",
    )

    axis.set_xlabel("$\\rho$ [r/a]")
    axis.set_ylabel("$\\beta$")
    axis.minorticks_on()
    axis.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.5)
    axis.set_title("Thermal Beta Profiles")
    axis.legend()
    axis.axvline(x=0, color="black", linestyle="--", linewidth=1)
    axis.grid(True, linestyle="--", alpha=0.5)
    axis.set_ylim(bottom=0.0)

plot_plasma_outboard_toroidal_ripple_map(fig, mfile, scan)

Source code in process/core/io/plot_proc.py
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
def plot_plasma_outboard_toroidal_ripple_map(fig, mfile: mf.MFile, scan: int):
    r_tf_outboard_mid = mfile.get("r_tf_outboard_mid", scan=scan)
    n_tf_coils = mfile.get("n_tf_coils", scan=scan)
    rmajor = mfile.get("rmajor", scan=scan)
    rminor = mfile.get("rminor", scan=scan)
    r_tf_wp_inboard_inner = mfile.get("r_tf_wp_inboard_inner", scan=scan)
    r_tf_wp_inboard_centre = mfile.get("r_tf_wp_inboard_centre", scan=scan)
    r_tf_wp_inboard_outer = mfile.get("r_tf_wp_inboard_outer", scan=scan)
    dx_tf_wp_primary_toroidal = mfile.get("dx_tf_wp_primary_toroidal", scan=scan)
    i_tf_shape = mfile.get("i_tf_shape", scan=scan)
    i_tf_sup = mfile.get("i_tf_sup", scan=scan)
    dx_tf_wp_insulation = mfile.get("dx_tf_wp_insulation", scan=scan)
    dx_tf_wp_insertion_gap = mfile.get("dx_tf_wp_insertion_gap", scan=scan)
    ripple_b_tf_plasma_edge_max = mfile.get("ripple_b_tf_plasma_edge_max", scan=scan)

    build = Build()

    r_nom = r_tf_outboard_mid
    dx_nom = dx_tf_wp_primary_toroidal if dx_tf_wp_primary_toroidal is not None else 0.0

    # Simple ±20% scan around nominal values for r and dx
    r_min = r_nom * 0.9
    r_max = r_nom * 1.1

    if dx_nom > 0:
        dx_min = dx_nom * 0.8
        dx_max = dx_nom * 1.2
    else:
        # fallback sensible small range if nominal is zero
        dx_min = 1e-3
        dx_max = 1e-2

    n_r = 50
    n_dx = 50
    r_vals = np.linspace(r_min, r_max, n_r)
    dx_vals = np.linspace(dx_min, dx_max, n_dx)

    rg, dxg = np.meshgrid(r_vals, dx_vals)

    # prepare metric array to hold ripple metric for each (r, dx) pair
    metric = np.full(rg.shape, np.nan, dtype=float)

    for ii in range(rg.shape[0]):
        for jj in range(rg.shape[1]):
            r_test = float(rg[ii, jj])
            dx_test = float(dxg[ii, jj])

            try:
                rip, _, _ = build.plasma_outboard_edge_toroidal_ripple(
                    ripple_b_tf_plasma_edge_max=0.05,
                    r_tf_outboard_mid=r_test,
                    n_tf_coils=int(n_tf_coils),
                    rmajor=rmajor,
                    rminor=rminor,
                    r_tf_wp_inboard_inner=r_tf_wp_inboard_inner,
                    r_tf_wp_inboard_centre=r_tf_wp_inboard_centre,
                    r_tf_wp_inboard_outer=r_tf_wp_inboard_outer,
                    dx_tf_wp_primary_toroidal=dx_test,
                    i_tf_shape=i_tf_shape,
                    i_tf_sup=i_tf_sup,
                    dx_tf_wp_insulation=dx_tf_wp_insulation,
                    dx_tf_wp_insertion_gap=dx_tf_wp_insertion_gap,
                )
            except (ValueError, ZeroDivisionError, OverflowError, TypeError):
                # Only catch expected numeric/validation errors from the ripple calculation;
                # let other exceptions propagate so they can be diagnosed.
                rip = np.nan
            metric[ii, jj] = rip

    # Create two subplots that share the same x axis
    ax1 = fig.add_subplot(2, 1, 1)
    ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

    # Make contour plot of the ripple metric (r vs dx) on ax1
    if np.all(np.isnan(metric)):
        ax1.text(0.5, 0.5, "No valid ripple data (r vs dx)", ha="center", va="center")
    else:
        vmin = np.nanmin(metric)
        vmax = np.nanmax(metric)

        # Guard against degenerate range
        if np.isclose(vmin, vmax, atol=1e-12) or np.isnan(vmin) or np.isnan(vmax):
            vmin = vmin - 0.25
            vmax = vmax + 0.25

        # Smooth filled contour levels
        levels = np.linspace(vmin, vmax, 50)
        cf = ax1.contourf(rg, dxg, metric, levels=levels, cmap="plasma", extend="both")

        # Contour lines only at 0.5 increments
        step = 0.5
        start = np.floor(vmin / step) * step
        end = np.ceil(vmax / step) * step
        contour_levels = np.arange(start, end + 1e-12, step)

        # Fallback if contour_levels is empty for some reason
        if contour_levels.size < 2:
            contour_levels = np.array([vmin, vmax])

        contours = ax1.contour(
            rg,
            dxg,
            metric,
            levels=contour_levels,
            colors="k",
            linewidths=0.5,
            alpha=0.7,
        )
        ax1.clabel(contours, inline=True, fontsize=8, fmt="%.2f%%", colors="white")
        # Overlay contour line at the specified target ripple value

        target = float(ripple_b_tf_plasma_edge_max)

        if target is not None and not np.isnan(target):
            # Check if target lies within computed metric range
            if (target >= vmin) and (target <= vmax):
                c_target = ax1.contour(
                    rg,
                    dxg,
                    metric,
                    levels=[target],
                    colors="white",
                    linewidths=2.0,
                    linestyles="--",
                    zorder=20,
                )
                ax1.clabel(
                    c_target,
                    inline=True,
                    fmt={target: f"Input Max {target:.2f}%"},
                    fontsize=8,
                    colors="white",
                )
            else:
                # annotate that target is outside plotted range
                ax1.text(
                    0.02,
                    0.98,
                    f"Target ripple {target:.2f}% outside plot range [{vmin:.2f},{vmax:.2f}]",
                    transform=ax1.transAxes,
                    color="white",
                    fontsize=8,
                    va="top",
                    bbox={"facecolor": "black", "alpha": 0.6, "pad": 2},
                )

        # Colourbar with 0.5 increments (use the same contour_levels as for the contour lines)
        ticks = contour_levels
        # Fallback to sensible ticks if contour_levels is not appropriate
        if ticks.size == 0 or np.isnan(ticks).all():
            ticks = np.linspace(vmin, vmax, 5)
        cb = ax1.figure.colorbar(
            cf, ax=ax1, label="Plasma Outboard Toroidal Ripple", ticks=ticks
        )
        cb.ax.set_yticklabels([f"{t:.2f}%" for t in ticks])

        # mark nominal point
        ax1.scatter(
            [r_nom],
            [dx_nom],
            color="white",
            edgecolor="black",
            s=200,
            linewidths=1.5,
            marker="o",
            zorder=10,
            label="Design Point",
        )
        ax1.set_xlabel("Outboard TF leg centre [m]")
        ax1.set_ylabel("WP Toroidal Width [m]")
        ax1.legend(loc="upper right")

    # ---------------------------------------------------------------------
    # Second plot: scan number of TF coils vs r_tf_outboard_mid (keep dx at nominal)
    # ---------------------------------------------------------------------
    # Determine a sensible integer range of TF coils to scan around nominal
    n_nom = int(n_tf_coils)
    span = max(2, int(min(12, n_nom // 2)))  # choose a span based on nominal
    n_min = max(10, n_nom - span)
    n_max = n_nom + span
    n_vals = np.arange(n_min, n_max + 1, dtype=int)

    n_r2 = 60
    r_vals2 = np.linspace(r_min, r_max, n_r2)
    rg2, ng2 = np.meshgrid(r_vals2, n_vals)

    metric2 = np.full(rg2.shape, np.nan, dtype=float)

    for ii in range(rg2.shape[0]):
        for jj in range(rg2.shape[1]):
            r_test = float(rg2[ii, jj])
            n_test = int(ng2[ii, jj])
            try:
                rip, *_ = build.plasma_outboard_edge_toroidal_ripple(
                    ripple_b_tf_plasma_edge_max=0.05,
                    r_tf_outboard_mid=r_test,
                    n_tf_coils=n_test,
                    rmajor=rmajor,
                    rminor=rminor,
                    r_tf_wp_inboard_inner=r_tf_wp_inboard_inner,
                    r_tf_wp_inboard_centre=r_tf_wp_inboard_centre,
                    r_tf_wp_inboard_outer=r_tf_wp_inboard_outer,
                    dx_tf_wp_primary_toroidal=dx_nom,
                    i_tf_shape=i_tf_shape,
                    i_tf_sup=i_tf_sup,
                    dx_tf_wp_insulation=dx_tf_wp_insulation,
                    dx_tf_wp_insertion_gap=dx_tf_wp_insertion_gap,
                )
            except (ValueError, ZeroDivisionError, OverflowError, TypeError):
                # Only catch expected numeric/validation errors from the ripple calculation;
                # let other exceptions propagate so they can be diagnosed.
                rip = np.nan
            metric2[ii, jj] = rip

    # Plot the second metric on the bottom axes (ax2) so it shares x-axis with ax1
    if np.all(np.isnan(metric2)):
        ax2.text(
            0.5, 0.5, "No valid ripple data (r vs n_tf_coils)", ha="center", va="center"
        )
    else:
        vmin2 = np.nanmin(metric2)
        vmax2 = np.nanmax(metric2)

        # filled contour levels (smooth shading)
        levels2 = np.linspace(vmin2, vmax2, 40)
        cf2 = ax2.contourf(
            rg2, ng2, metric2, levels=levels2, cmap="viridis", extend="both"
        )

        # contour lines only at 0.5 steps
        step = 0.5
        start = np.floor(vmin2 / step) * step
        end = np.ceil(vmax2 / step) * step
        contour_levels = np.arange(start, end + 1e-12, step)

        # fallback if arange returned empty (very small range)
        if contour_levels.size == 0:
            contour_levels = np.array([vmin2, vmax2])

        contours2 = ax2.contour(
            rg2,
            ng2,
            metric2,
            levels=contour_levels,
            colors="k",
            linewidths=0.5,
            alpha=0.7,
        )
        ax2.clabel(contours2, inline=True, fontsize=8, fmt="%.2f%%", colors="white")

        target2 = float(ripple_b_tf_plasma_edge_max)

        if target2 is not None and not np.isnan(target2):
            if (target2 >= vmin2) and (target2 <= vmax2):
                c_target2 = ax2.contour(
                    rg2,
                    ng2,
                    metric2,
                    levels=[target2],
                    colors="white",
                    linewidths=2.0,
                    linestyles="--",
                    zorder=20,
                )
            ax2.clabel(
                c_target2,
                inline=True,
                fmt={target2: f"Input Max {target2:.2f}%"},
                fontsize=8,
                colors="white",
            )
        else:
            ax2.text(
                0.02,
                0.98,
                f"Target ripple {target2:.2f}% outside plot range [{vmin2:.2f},{vmax2:.2f}]",
                transform=ax2.transAxes,
                color="white",
                fontsize=8,
                va="top",
                bbox={"facecolor": "black", "alpha": 0.6, "pad": 2},
            )
        # colorbar with 0.5 increments
        # ensure contour_levels exists and is in 0.5 steps (constructed above)
        ticks = contour_levels
        cb2 = ax2.figure.colorbar(
            cf2, ax=ax2, label="Plasma Outboard Toroidal Ripple", ticks=ticks
        )
        cb2.ax.set_yticklabels([f"{t:.2f}%" for t in ticks])

        # nominal markers
        ax2.scatter(
            [r_nom],
            [n_nom],
            color="white",
            edgecolor="black",
            s=300,
            linewidths=1.5,
            marker="o",
            zorder=10,
            label="Design Point",
        )
        ax2.set_xlabel("Outboard TF leg centre [m]")
        ax2.set_ylabel("Number of TF coils")
        ax2.set_yticks(n_vals)
        ax2.legend(loc="upper right")

    # Improve layout
    fig.tight_layout()

plot_plasma_effective_charge_profile(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
def plot_plasma_effective_charge_profile(axis: plt.Axes, mfile: mf.MFile, scan: int):
    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    n_charge_plasma_effective_vol_avg = mfile.get(
        "n_charge_plasma_effective_vol_avg", scan=scan
    )

    n_charge_plasma_effective_profile = [
        mfile.get(f"n_charge_plasma_effective_profile{i}", scan=scan)
        for i in range(n_plasma_profile_elements)
    ]

    axis.plot(
        np.linspace(0, 1, n_plasma_profile_elements),
        n_charge_plasma_effective_profile,
    )

    axis.hlines(
        n_charge_plasma_effective_vol_avg,
        xmin=0,
        xmax=1,
        colors="red",
        linestyles="--",
        label=f"Volume-Averaged $Z_{{\\text{{eff}}}}$ = {n_charge_plasma_effective_vol_avg:.2f}",
    )

    axis.set_xlabel(r"$\rho \quad [r/a]$")
    axis.set_ylabel("Effective Charge ($Z_{\\text{eff}}$)")
    axis.set_title("Plasma Effective Charge Profile")
    axis.minorticks_on()
    axis.set_xlim(0, 1.025)
    axis.grid(which="both", linestyle="--", alpha=0.5)
    axis.legend()

plot_ion_charge_profile(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
def plot_ion_charge_profile(axis: plt.Axes, mfile: mf.MFile, scan: int):
    n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan))

    # find impurity densities
    imp_frac = np.array([
        mfile.get("f_nd_impurity_electrons(01)", scan=scan),
        mfile.get("f_nd_impurity_electrons(02)", scan=scan),
        mfile.get("f_nd_impurity_electrons(03)", scan=scan),
        mfile.get("f_nd_impurity_electrons(04)", scan=scan),
        mfile.get("f_nd_impurity_electrons(05)", scan=scan),
        mfile.get("f_nd_impurity_electrons(06)", scan=scan),
        mfile.get("f_nd_impurity_electrons(07)", scan=scan),
        mfile.get("f_nd_impurity_electrons(08)", scan=scan),
        mfile.get("f_nd_impurity_electrons(09)", scan=scan),
        mfile.get("f_nd_impurity_electrons(10)", scan=scan),
        mfile.get("f_nd_impurity_electrons(11)", scan=scan),
        mfile.get("f_nd_impurity_electrons(12)", scan=scan),
        mfile.get("f_nd_impurity_electrons(13)", scan=scan),
        mfile.get("f_nd_impurity_electrons(14)", scan=scan),
    ])

    imp_label = [
        "H",
        "He",
        "Be",
        "C",
        "N",
        "O",
        "Ne",
        "Si",
        "Ar",
        "Fe",
        "Ni",
        "Kr",
        "Xe",
        "W",
    ]
    full_charge_array = [1, 2, 4, 6, 7, 8, 10, 14, 18, 26, 28, 36, 54, 74]

    n_charge_plasma_profile = []
    avg_ionisation_percentages = []
    for imp in range(impurity_radiation_module.N_IMPURITIES):
        if imp_frac[imp] > 1.0e-30:
            profile = [
                mfile.get(f"n_charge_plasma_profile{imp}_{i}", scan=scan)
                for i in range(n_plasma_profile_elements)
            ]
            n_charge_plasma_profile.append(profile)
            z_max = full_charge_array[imp]
            # Calculate relative ionisation state as percent of full ionisation
            rel_ion_state = [
                100.0 * (val / z_max if z_max > 0 else 0) for val in profile
            ]
            avg_ionisation = np.mean(rel_ion_state)
            avg_ionisation_percentages.append((imp_label[imp], avg_ionisation))
            axis.plot(
                np.linspace(0, 1, n_plasma_profile_elements),
                rel_ion_state,
                label=f"{imp_label[imp]} (Z={z_max}): avg {avg_ionisation:.1f}%",
            )
    axis.set_ylabel("Relative Ionisation State [% of $Z$]")
    axis.legend()
    axis.set_xlim(0, 1.025)
    axis.set_xlabel(r"$\rho \quad [r/a]$")
    axis.set_title("Impurity Ion Charge State Profiles")
    axis.minorticks_on()
    axis.grid(which="both", linestyle="--", alpha=0.5)

plot_ebw_ecrh_coupling_graph(axis, mfile, scan)

Source code in process/core/io/plot_proc.py
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
def plot_ebw_ecrh_coupling_graph(axis: plt.Axes, mfile: mf.MFile, scan: int):
    # Plot EBW and ECRH coupling efficiency graph
    ebw = ElectronBernstein(plasma_profile=0)
    ecrg = ElectronCyclotron(plasma_profile=0)
    b_on_axis = mfile.get("b_plasma_toroidal_on_axis", scan=scan)
    bs = np.linspace(0.0, b_on_axis + 2.0, 500)
    # Use a color map for harmonics
    colors = ["red", "green", "blue"]
    linestyles = ["-", "--"]  # EBW: solid, ECRH: dashed

    for idx, n_harmonic in enumerate(range(1, 4)):
        eta_ebw_vals = []
        # For ECRH, store results for both wave modes (0: O-mode, 1: X-mode)
        eta_ecrh_vals_omode = []
        eta_ecrh_vals_xmode = []
        for b in bs:
            eta_ebw = ebw.electron_bernstein_freethy(
                te=mfile.get("temp_plasma_electron_vol_avg_kev", scan=scan),
                rmajor=mfile.get("rmajor", scan=scan),
                dene20=mfile.get("nd_plasma_electrons_vol_avg", scan=scan) / 1e20,
                b_plasma_toroidal_on_axis=b,
                n_ecrh_harmonic=n_harmonic,
                xi_ebw=mfile.get("xi_ebw", scan=scan),
            )
            eta_ecrh_omode = ecrg.electron_cyclotron_freethy(
                te=mfile.get("temp_plasma_electron_vol_avg_kev", scan=scan),
                zeff=mfile.get("n_charge_plasma_effective_vol_avg", scan=scan),
                rmajor=mfile.get("rmajor", scan=scan),
                nd_plasma_electrons_vol_avg=mfile.get(
                    "nd_plasma_electrons_vol_avg", scan=scan
                ),
                b_plasma_toroidal_on_axis=b,
                n_ecrh_harmonic=n_harmonic,
                i_ecrh_wave_mode=0,  # O-mode
            )
            eta_ecrh_xmode = ecrg.electron_cyclotron_freethy(
                te=mfile.get("temp_plasma_electron_vol_avg_kev", scan=scan),
                zeff=mfile.get("n_charge_plasma_effective_vol_avg", scan=scan),
                rmajor=mfile.get("rmajor", scan=scan),
                nd_plasma_electrons_vol_avg=mfile.get(
                    "nd_plasma_electrons_vol_avg", scan=scan
                ),
                b_plasma_toroidal_on_axis=b,
                n_ecrh_harmonic=n_harmonic,
                i_ecrh_wave_mode=1,  # X-mode
            )
            eta_ebw_vals.append(eta_ebw)
            eta_ecrh_vals_omode.append(eta_ecrh_omode)
            eta_ecrh_vals_xmode.append(eta_ecrh_xmode)
        # EBW: solid, ECRH O-mode: dashed, ECRH X-mode: dotted, same color for same harmonic
        axis.plot(
            bs,
            eta_ebw_vals,
            label=f"EBW (harmonic {n_harmonic})",
            color=colors[idx],
            linestyle=linestyles[0],
        )
        axis.plot(
            bs,
            eta_ecrh_vals_omode,
            label=f"ECRH O-mode (harmonic {n_harmonic})",
            color=colors[idx],
            linestyle="--",
        )
        axis.plot(
            bs,
            eta_ecrh_vals_xmode,
            label=f"ECRH X-mode (harmonic {n_harmonic})",
            color=colors[idx],
            linestyle=":",
        )
    axis.set_xlabel("On axis toroidal B-field [T]")
    axis.set_ylabel("Current drive efficiency [A/W]")
    axis.set_title("EBW/ECRH Coupling Efficiency vs Toroidal B-field")
    axis.legend()
    axis.grid(True)
    # Plot a vertical line at the on-axis value of the toroidal B-field
    b_on_axis = mfile.get("b_plasma_toroidal_on_axis", scan=scan)
    axis.axvline(
        b_on_axis, color="black", linestyle="-", linewidth=2.5, label="On-axis $B_T$"
    )
    axis.minorticks_on()

plot_debye_length_profile(axis, mfile_data, scan)

Plot the Debye length profile on the given axis.

Parameters:

Name Type Description Default
axis Axes
required
mfile_data MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
def plot_debye_length_profile(axis: plt.Axes, mfile_data: mf.MFile, scan: int):
    """Plot the Debye length profile on the given axis.

    Parameters
    ----------
    axis :

    mfile_data :

    scan :

    """
    len_plasma_debye_electron_profile = [
        mfile_data.data[f"len_plasma_debye_electron_profile{i}"].get_scan(scan)
        for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan)))
    ]

    # Convert to micrometres (1e-6 m)
    len_plasma_debye_electron_profile_um = [
        length * 1e6 for length in len_plasma_debye_electron_profile
    ]

    axis.plot(
        np.linspace(0, 1, len(len_plasma_debye_electron_profile_um)),
        len_plasma_debye_electron_profile_um,
        color="blue",
        linestyle="-",
        label=r"$\lambda_{Debye,e}$",
    )

    axis.set_ylabel(r"Debye Length [$\mu$m]")

    axis.set_xlabel("$\\rho \\ [r/a]$")
    axis.grid(True, which="both", linestyle="--", alpha=0.5)
    axis.set_xlim([0, 1.025])
    axis.minorticks_on()
    axis.legend()

plot_velocity_profile(axis, mfile_data, scan)

Plot the electron thermal velocity profile on the given axis.

Parameters:

Name Type Description Default
axis
required
mfile_data
required
scan
required
Source code in process/core/io/plot_proc.py
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
def plot_velocity_profile(axis, mfile_data, scan):
    """Plot the electron thermal velocity profile on the given axis.

    Parameters
    ----------
    axis :

    mfile_data :

    scan :

    """
    vel_plasma_electron_profile = [
        mfile_data.data[f"vel_plasma_electron_profile{i}"].get_scan(scan)
        for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan)))
    ]
    vel_plasma_deuteron_profile = [
        mfile_data.data[f"vel_plasma_deuteron_profile{i}"].get_scan(scan)
        for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan)))
    ]
    vel_plasma_triton_profile = [
        mfile_data.data[f"vel_plasma_triton_profile{i}"].get_scan(scan)
        for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan)))
    ]

    axis.plot(
        np.linspace(0, 1, len(vel_plasma_electron_profile)),
        vel_plasma_electron_profile,
        color="blue",
        linestyle="-",
        label=r"$v_{e}$",
    )
    axis.plot(
        np.linspace(0, 1, len(vel_plasma_deuteron_profile)),
        vel_plasma_deuteron_profile,
        color="red",
        linestyle="-",
        label=r"$v_{D}$",
    )
    axis.plot(
        np.linspace(0, 1, len(vel_plasma_triton_profile)),
        vel_plasma_triton_profile,
        color="green",
        linestyle="-",
        label=r"$v_{T}$",
    )

    axis.set_yscale("log")
    axis.set_ylabel("Velocity [m/s]")
    axis.set_xlabel("$\\rho \\ [r/a]$")
    axis.grid(True, which="both", linestyle="--", alpha=0.5)
    axis.set_xlim([0, 1.025])
    axis.minorticks_on()
    axis.legend()

plot_electron_frequency_profile(axis, mfile_data, scan)

Plot the electron thermal frequency profile on the given axis.

Parameters:

Name Type Description Default
axis
required
mfile_data
required
scan
required
Source code in process/core/io/plot_proc.py
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
def plot_electron_frequency_profile(axis, mfile_data, scan):
    """Plot the electron thermal frequency profile on the given axis.

    Parameters
    ----------
    axis :

    mfile_data :

    scan :

    """
    freq_plasma_electron_profile = [
        mfile_data.data[f"freq_plasma_electron_profile{i}"].get_scan(scan)
        for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan)))
    ]
    freq_plasma_larmor_toroidal_electron_profile = [
        mfile_data.data[f"freq_plasma_larmor_toroidal_electron_profile{i}"].get_scan(
            scan
        )
        for i in range(
            2 * int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))
        )
    ]

    axis.plot(
        np.linspace(-1, 1, len(freq_plasma_larmor_toroidal_electron_profile)),
        np.array(freq_plasma_larmor_toroidal_electron_profile) / 1e9,
        color="red",
        linestyle="-",
        label=r"$f_{Larmor,toroidal,e}$",
    )
    x = np.linspace(0, 1, len(freq_plasma_electron_profile))
    y = np.array(freq_plasma_electron_profile) / 1e9
    # original curve
    axis.plot(x, y, color="blue", linestyle="-", label=r"$\omega_{p,e}$")
    # mirrored across the y-axis (drawn at negative rho)
    axis.plot(-x, y, color="blue", linestyle="-", label="_nolegend_")
    axis.set_xlim(-1.025, 1.025)

    axis.set_ylabel("Frequency [GHz]")
    axis.grid(True, which="both", linestyle="--", alpha=0.5)

    axis.legend()

plot_ion_frequency_profile(axis, mfile_data, scan)

Source code in process/core/io/plot_proc.py
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
def plot_ion_frequency_profile(axis, mfile_data, scan):
    freq_plasma_larmor_toroidal_deuteron_profile = [
        mfile_data.data[f"freq_plasma_larmor_toroidal_deuteron_profile{i}"].get_scan(
            scan
        )
        for i in range(
            2 * int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))
        )
    ]

    freq_plasma_larmor_toroidal_triton_profile = [
        mfile_data.data[f"freq_plasma_larmor_toroidal_triton_profile{i}"].get_scan(scan)
        for i in range(
            2 * int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))
        )
    ]

    axis.plot(
        np.linspace(-1, 1, len(freq_plasma_larmor_toroidal_deuteron_profile)),
        np.array(freq_plasma_larmor_toroidal_deuteron_profile) / 1e6,
        color="red",
        linestyle="-",
        label=r"$f_{Larmor,toroidal,D}$",
    )
    axis.plot(
        np.linspace(-1, 1, len(freq_plasma_larmor_toroidal_triton_profile)),
        np.array(freq_plasma_larmor_toroidal_triton_profile) / 1e6,
        color="green",
        linestyle="-",
        label=r"$f_{Larmor,toroidal,T}$",
    )

    axis.set_ylabel("Frequency [MHz]")
    axis.set_xlabel("$\\rho \\ [r/a]$")
    axis.grid(True, which="both", linestyle="--", alpha=0.5)
    axis.minorticks_on()
    axis.legend()

plot_equality_constraint_equations(axis, m_file_data, scan)

Plot the equality constraints for a solution and their normalised residuals

Parameters:

Name Type Description Default
axis Axes
required
m_file_data MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
def plot_equality_constraint_equations(axis: plt.Axes, m_file_data: mf.MFile, scan: int):
    """Plot the equality constraints for a solution and their normalised residuals

    Parameters
    ----------
    axis: plt.Axes :

    m_file_data: mf.MFile :

    scan: int :

    """

    y_labels = []
    y_pos = []
    n_plot = 0

    # Build a mapping from itvar index to its name (description)
    con_names = {}
    con_numbers = {}
    for var in m_file_data.data:
        if var.startswith("eq_con"):
            idx = int(var[6:])  # e.g. "itvar001" -> 1
            con_names[idx] = m_file_data.data[var].var_description
            con_numbers[idx] = idx

    for n_plot, n in enumerate(con_numbers.values()):
        # Constraint value needed
        con_value = m_file_data.data[f"val_eq_con{n:03d}"].get_scan(scan)

        # Use the variable name if available, else fallback to "eq_conXXX"
        var_label = con_names.get(n, f"eq_con{n:03d}")

        # Normalized residual of the constraint
        con_norm_residual = m_file_data.data[f"eq_con{n:03d}"].get_scan(scan)

        # Unit type of the constraint
        con_units_raw = m_file_data.data[f"eq_units_con{n:03d}"].get_scan(scan)
        con_units = str(con_units_raw).strip("'`")

        # Remove '_normalised_residue' from the label if present
        if isinstance(var_label, str) and var_label.endswith("_normalised_residue"):
            var_label = var_label.replace("_normalised_residue", "")

            # Remove trailing underscores and replace underscores between words with spaces
            var_label = var_label.rstrip("_").replace("_", " ")

        # Plot the normalised residual as a bar
        axis.barh(
            n_plot,
            con_norm_residual,
            height=0.6,
            color="blue",
            label="Normalized Residual" if n_plot == 0 else "",
            align="center",
        )

        # Add the value as a number to the right of the bar
        axis.text(
            con_norm_residual + 0.02,
            n_plot,
            f"{con_norm_residual:.8g}",
            va="center",
            ha="left",
            fontsize=8,
            color="blue",
        )

        # Add the constraint value as text to the left of the y-axis
        axis.text(
            -0.05,
            n_plot,
            f"{con_value:.8g} {con_units}",
            va="center",
            ha="right",
            fontsize=10,
            color="black",
        )

        y_labels.append(var_label)
        y_pos.append(n_plot)

    axis.axvline(0, color="red", linewidth=2, zorder=0)
    axis.set_yticks(y_pos)
    axis.set_yticklabels(y_labels)
    axis.set_xlim(-0.4, 1.2)  # Normalised bounds
    axis.set_title("Equality Constraint Equations")
    axis.set_xticks([])
    axis.legend()

plot_inequality_constraint_equations(axis, m_file, scan)

Plot the inequality constraints for a solution and where they lay within their bounds

Parameters:

Name Type Description Default
axis Axes
required
m_file MFile
required
scan int
required
Source code in process/core/io/plot_proc.py
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: int):
    """Plot the inequality constraints for a solution and where they lay within their bounds

    Parameters
    ----------
    axis: plt.Axes :

    m_file: mf.MFile :

    scan: int :

    """

    y_labels = []
    y_pos = []
    n_plot = 0

    # Build a mapping from itvar index to its name (description)
    con_names = {}
    con_numbers = {}
    for var in m_file.data:
        if var.startswith("ineq_con"):
            idx = int(var[8:])  # e.g. "ineq_con001" -> 1
            con_names[idx] = m_file.data[var].var_description
            con_numbers[idx] = idx

    for n_plot, n in enumerate(con_numbers.values()):
        # Constraint value/bound
        con_bound = m_file.data[f"ineq_bound_con{n:03d}"].get_scan(scan)

        # Value of constraint variable
        con_value = m_file.data[f"ineq_value_con{n:03d}"].get_scan(scan)

        # Constraint symbol can be `<=` for an upper limit or `>=` for a lower limit
        con_symbol = m_file.data[f"ineq_symbol_con{n:03d}"].get_scan(scan)

        # Use the variable name if available, else fallback to "ineq_conXXX"
        var_label = con_names.get(n, f"ineq_con{n:03d}")

        # Normalized residual of the constraint
        con_residual_norm = m_file.data[f"ineq_con{n:03d}"].get_scan(scan)

        # Unit type of the constraint
        con_units = m_file.data[f"ineq_units_con{n:03d}"].get_scan(scan).strip("'`")

        # Add a vertical line at the normalised constraint bounds of 0 and 1
        axis.axvline(
            0.0,
            color="red",
            linestyle="--",
            linewidth=1.5,
            zorder=0,
        )

        axis.axvline(
            1.0,
            color="red",
            linestyle="--",
            linewidth=1.5,
            zorder=0,
        )

        # Remove '_normalised_residue' from the label if present
        if isinstance(var_label, str) and var_label.endswith("_normalised_residue"):
            var_label = var_label.replace("_normalised_residue", "")
            var_label = var_label.rstrip("_").replace("_", " ")

        # Calculate the normalised constraint threshold depending if the constraint is an upper
        # or lower limit
        if con_symbol == "'<='":
            normalised_value = 1 - con_residual_norm
            bar_left = normalised_value
            bar_width = 1 - normalised_value
        else:
            normalised_value = con_residual_norm
            bar_left = 0
            bar_width = normalised_value

        # If the constraint value is very close to the bound then plot a square marker at the bound
        if np.isclose(normalised_value, 1.0, atol=1e-3):
            axis.plot(
                1,
                n_plot,
                "s",
                color="black",
                markersize=8,
                zorder=5,
            )
        elif np.isclose(normalised_value, 0.0, atol=1e-3):
            axis.plot(
                0,
                n_plot,
                "s",
                color="black",
                markersize=8,
                zorder=5,
            )

        else:
            # If constraint value is not very close to bound then plot bar as normal
            axis.barh(
                n_plot,
                bar_width,
                left=bar_left,
                color="blue",
                edgecolor="black",
                linewidth=1.5,
                height=1.0,
                alpha=0.7,
                label="Constraint Value" if n_plot == 0 else "",
            )

        # Plot the value as a number at x = 0.5
        axis.text(
            0.5,
            n_plot,
            f"{con_value:,.8g} {con_units}",
            va="center",
            ha="center",
            fontsize=8,
            color=(
                "orange"
                if np.isclose(normalised_value, 1.0, atol=1e-3)
                or np.isclose(normalised_value, 0.0, atol=1e-3)
                else "green"
            ),
            bbox={
                "boxstyle": "round",
                "facecolor": "white",
                "alpha": 0.8,
                "edgecolor": "white",
                "linewidth": 1,
            },
        )
        # Annoate the bound value depending if it is an upper or lower limit
        if con_symbol == "'<='":
            # Add the constraint symbol and bound as text
            axis.text(
                1.02,  # Position text slightly to the right of the normalised bound
                n_plot,
                f"$\\leq$ {con_bound:,.8g} {con_units}",
                va="center",
                ha="left",
                fontsize=8,
                color="black",
            )
        else:  # con_symbol == ">="
            axis.text(
                -0.025,  # Position text slightly to the left of the normalised bound
                n_plot,
                f"$\\geq$ {con_bound:,.8g} {con_units}",
                va="center",
                ha="right",
                fontsize=8,
                color="black",
            )

        y_labels.append(var_label)
        y_pos.append(n_plot)

    axis.set_yticks(y_pos)
    axis.set_yticklabels(y_labels)
    axis.set_title("Inequality Constraint Equations")
    axis.set_xlim(-0.3, 1.275)
    axis.set_xticks([])
    axis.set_facecolor("#f5f5f5")
    axis.set_xticks(np.arange(0, 1.0, 0.1))
    axis.grid(True, axis="x", linestyle="--", alpha=0.3)
    axis.set_xticklabels([])

main_plot(figs, m_file, scan, imp='../data/lz_non_corona_14_elements/', demo_ranges=False, colour_scheme=1)

Function to create radial and vertical build plot on given figure.

Parameters:

Name Type Description Default
figs list[Axes]

figure object to add plot to

required
m_file MFile

MFILE

required
scan int

scan to read from MFILE

required
imp str

path to impurity data

'../data/lz_non_corona_14_elements/'
demo_ranges bool

(Default value = False)

False
colour_scheme Literal[1, 2]
1
Source code in process/core/io/plot_proc.py
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
def main_plot(
    figs: list[Axes],
    m_file: mf.MFile,
    scan: int,
    imp: str = "../data/lz_non_corona_14_elements/",
    demo_ranges: bool = False,
    colour_scheme: Literal[1, 2] = 1,
):
    """Function to create radial and vertical build plot on given figure.

    Parameters
    ----------
    figs :
        figure object to add plot to
    m_file :
        MFILE
    scan :
        scan to read from MFILE
    imp :
        path to impurity data
    demo_ranges: bool :
         (Default value = False)
    colour_scheme:

    """

    # Checking the impurity data folder
    # Get path to impurity data dir
    # TODO use Path objects throughout module, not strings

    with resources.path(
        "process.data.lz_non_corona_14_elements", "Ar_lz_tau.dat"
    ) as imp_path:
        data_folder = str(imp_path.parent) + "/"

    if os.path.isdir(data_folder):
        imp = data_folder
    else:
        print(
            "\033[91m Warning : Impossible to recover impurity data, try running the macro in the main/utility folder"
        )
        print("          -> No impurity plot done\033[0m")
    i_shape = int(m_file.get("i_plasma_shape", scan=scan))
    # Setup params for text plots
    plt.rcParams.update({"font.size": 8})

    plot_0 = figs[0].add_subplot(111)

    radial_build = create_thickness_builds(m_file, scan)

    plot_cover_page(plot_0, m_file, scan, figs[0], radial_build, colour_scheme)

    # Plot header info
    plot_header(figs[1].add_subplot(231), m_file, scan)

    # Geometry
    plot_geometry_info(figs[1].add_subplot(232), m_file, scan)

    # Physics
    plot_physics_info(figs[1].add_subplot(233), m_file, scan)

    # Magnetics
    plot_magnetics_info(figs[1].add_subplot(234), m_file, scan)

    # power/flow economics
    plot_power_info(figs[1].add_subplot(235), m_file, scan)

    # Current drive
    # plot_current_drive_info(figs[1].add_subplot(236), m_file_data, scan)
    figs[1].subplots_adjust(wspace=0.25, hspace=0.25)

    ax7 = figs[2].add_subplot(111)
    ax7.set_position([0.25, 0.1, 0.7, 0.8])  # Move plot slightly to the right
    plot_iteration_variables(ax7, m_file, scan)

    ax7_5 = figs[3].add_subplot(313)
    ax7_5.set_position([0.3, 0.1, 0.6, 0.1])
    plot_equality_constraint_equations(ax7_5, m_file, scan)
    ax7_6 = figs[3].add_subplot(111)
    ax7_6.set_position([0.3, 0.25, 0.65, 0.7])
    plot_inequality_constraint_equations(ax7_6, m_file, scan)

    # Plot main plasma information
    plot_main_plasma_information(
        figs[4].add_subplot(111, aspect="equal"),
        m_file,
        scan,
        colour_scheme,
        figs[4],
    )

    # Plot density profiles
    ax9 = figs[5].add_subplot(231)
    ax9.set_position([0.075, 0.55, 0.25, 0.4])
    plot_n_profiles(ax9, demo_ranges, m_file, scan)

    # Plot temperature profiles
    ax10 = figs[5].add_subplot(232)
    ax10.set_position([0.375, 0.55, 0.25, 0.4])
    plot_t_profiles(ax10, demo_ranges, m_file, scan)

    # Plot impurity profiles
    ax11 = figs[5].add_subplot(233)
    ax11.set_position([0.7, 0.45, 0.25, 0.5])
    plot_radprofile(ax11, m_file, scan, imp, demo_ranges)

    # Plot current density profile
    ax12 = figs[5].add_subplot(4, 3, 10)
    ax12.set_position([0.075, 0.105, 0.25, 0.15])
    plot_jprofile(ax12, m_file, scan)

    # Plot q profile
    ax13 = figs[5].add_subplot(4, 3, 12)
    ax13.set_position([0.7, 0.125, 0.25, 0.15])
    plot_qprofile(ax13, demo_ranges, m_file, scan)

    plot_plasma_effective_charge_profile(figs[6].add_subplot(221), m_file, scan)
    plot_ion_charge_profile(figs[6].add_subplot(223), m_file, scan)

    if i_shape == 1:
        plot_rad_contour(figs[6].add_subplot(122), m_file, scan, imp)

    if i_shape != 1:
        msg = (
            "Radiation contour plots require a closed (Sauter) plasma boundary "
            "(i_plasma_shape == 1). "
            f"Current i_plasma_shape = {i_shape}. Contour plots are skipped; "
            "see the 1D radiation plots for available information."
        )
        # Add explanatory text to both figures reserved for contour outputs
        figs[6].text(0.75, 0.5, msg, ha="center", va="center", wrap=True, fontsize=12)

    plot_fusion_rate_profiles(figs[7].add_subplot(122), figs[7], m_file, scan)

    if m_file.get("i_plasma_shape", scan=scan) == 1:
        plot_fusion_rate_contours(figs[8], figs[9], m_file, scan)

    if i_shape != 1:
        msg = (
            "Fusion-rate contour plots require a closed (Sauter) plasma boundary "
            "(i_plasma_shape == 1). "
            f"Current i_plasma_shape = {i_shape}. Contour plots are skipped; "
            "see the 1D fusion rate/profile plots for available information."
        )
        # Add explanatory text to both figures reserved for contour outputs
        figs[8].text(0.5, 0.5, msg, ha="center", va="center", wrap=True, fontsize=12)
        figs[9].text(0.5, 0.5, msg, ha="center", va="center", wrap=True, fontsize=12)

    plot_plasma_pressure_profiles(figs[10].add_subplot(222), m_file, scan)
    plot_plasma_pressure_gradient_profiles(figs[10].add_subplot(224), m_file, scan)
    # Currently only works with Sauter geometry as plasma has a closed surface

    if i_shape == 1:
        plot_plasma_poloidal_pressure_contours(
            figs[10].add_subplot(121, aspect="equal"), m_file, scan
        )
    else:
        ax = figs[10].add_subplot(131, aspect="equal")
        msg = (
            "Plasma poloidal pressure contours require a closed (Sauter) plasma boundary "
            "(i_plasma_shape == 1). "
            f"Current i_plasma_shape = {i_shape}. Contour plots are skipped; "
            "see the 1D pressure/profile plots for available information."
        )
        ax.text(
            0.5,
            0.5,
            msg,
            ha="center",
            va="center",
            wrap=True,
            fontsize=10,
            transform=ax.transAxes,
        )
        ax.axis("off")

    plot_magnetic_fields_in_plasma(figs[11].add_subplot(122), m_file, scan)
    plot_beta_profiles(figs[11].add_subplot(221), m_file, scan)

    plot_ebw_ecrh_coupling_graph(figs[12].add_subplot(111), m_file, scan)

    plot_bootstrap_comparison(figs[13].add_subplot(221), m_file, scan)
    plot_h_threshold_comparison(figs[13].add_subplot(224), m_file, scan)
    plot_density_limit_comparison(figs[14].add_subplot(221), m_file, scan)
    plot_confinement_time_comparison(figs[14].add_subplot(224), m_file, scan)

    plot_debye_length_profile(figs[15].add_subplot(232), m_file, scan)
    plot_velocity_profile(figs[15].add_subplot(233), m_file, scan)

    ax_ion = figs[15].add_subplot(414)
    ax_electron = figs[15].add_subplot(413, sharex=ax_ion)

    plot_electron_frequency_profile(ax_electron, m_file, scan)

    plot_ion_frequency_profile(ax_ion, m_file, scan)

    plot_plasma_coloumb_logarithms(figs[15].add_subplot(231), m_file, scan)

    # Plot poloidal cross-section
    poloidal_cross_section(
        figs[16].add_subplot(121, aspect="equal"),
        m_file,
        scan,
        demo_ranges,
        radial_build,
        colour_scheme,
    )

    # Plot toroidal cross-section
    toroidal_cross_section(
        figs[16].add_subplot(122, aspect="equal"),
        m_file,
        scan,
        demo_ranges,
        colour_scheme,
    )

    # Plot color key
    ax17 = figs[16].add_subplot(222)
    ax17.set_position([0.5, 0.5, 0.5, 0.5])
    color_key(ax17, m_file, scan, colour_scheme)

    ax18 = figs[17].add_subplot(211)
    ax18.set_position([0.1, 0.33, 0.8, 0.6])
    plot_radial_build(ax18, m_file, colour_scheme)

    # Make each axes smaller vertically to leave room for the legend
    ax185 = figs[18].add_subplot(211)
    ax185.set_position([0.1, 0.61, 0.8, 0.32])

    ax18b = figs[18].add_subplot(212)
    ax18b.set_position([0.1, 0.13, 0.8, 0.32])
    plot_upper_vertical_build(ax185, m_file, colour_scheme)
    plot_lower_vertical_build(ax18b, m_file, colour_scheme)

    # Can only plot WP and turn structure if superconducting coil at the moment
    if m_file.get("i_tf_sup", scan=scan) == 1:
        # TF coil with WP
        ax19 = figs[19].add_subplot(221, aspect="equal")
        ax19.set_position([
            0.025,
            0.45,
            0.5,
            0.5,
        ])  # Half height, a bit wider, top left
        plot_superconducting_tf_wp(ax19, m_file, scan, figs[19])

        # TF coil turn structure
        ax20 = figs[20].add_subplot(325, aspect="equal")
        ax20.set_position([0.025, 0.5, 0.4, 0.4])
        plot_tf_cable_in_conduit_turn(ax20, figs[20], m_file, scan)
        plot_205 = figs[20].add_subplot(223, aspect="equal")
        plot_205.set_position([0.075, 0.1, 0.3, 0.3])
        plot_cable_in_conduit_cable(plot_205, figs[20], m_file, scan)
    else:
        ax19 = figs[19].add_subplot(211, aspect="equal")
        ax19.set_position([0.06, 0.55, 0.675, 0.4])
        plot_resistive_tf_wp(ax19, m_file, scan, figs[19])
        plot_resistive_tf_info(ax19, m_file, scan, figs[19])
    plot_tf_coil_structure(
        figs[21].add_subplot(111, aspect="equal"), m_file, scan, colour_scheme
    )

    plot_plasma_outboard_toroidal_ripple_map(figs[22], m_file, scan)

    plot_tf_stress(figs[23].subplots(nrows=3, ncols=1, sharex=True).flatten(), m_file)

    plot_current_profiles_over_time(figs[24].add_subplot(111), m_file, scan)

    plot_cs_coil_structure(
        figs[25].add_subplot(121, aspect="equal"), figs[25], m_file, scan
    )
    plot_cs_turn_structure(
        figs[25].add_subplot(224, aspect="equal"), figs[25], m_file, scan
    )

    plot_first_wall_top_down_cross_section(
        figs[26].add_subplot(221, aspect="equal"), m_file, scan
    )
    plot_first_wall_poloidal_cross_section(figs[26].add_subplot(122), m_file, scan)
    plot_fw_90_deg_pipe_bend(figs[26].add_subplot(337), m_file, scan)

    plot_blkt_pipe_bends(figs[27], m_file, scan)
    ax_blanket = figs[27].add_subplot(122, aspect="equal")
    plot_blanket(ax_blanket, m_file, scan, radial_build, colour_scheme)
    plot_firstwall(ax_blanket, m_file, scan, radial_build, colour_scheme)
    ax_blanket.set_xlabel("Radial position [m]")
    ax_blanket.set_ylabel("Vertical position [m]")
    ax_blanket.set_title("Blanket and First Wall Poloidal Cross-Section")
    ax_blanket.minorticks_on()
    ax_blanket.grid(which="minor", linestyle=":", linewidth=0.5, alpha=0.5)
    # Plot major radius line (vertical dashed line at rmajor)
    ax_blanket.axvline(
        m_file.get("rminor", scan=scan),
        color="black",
        linestyle="--",
        linewidth=1.5,
        label="Major Radius $R_0$",
    )
    # Plot a horizontal line at dz_blkt_half (blanket half height)
    dz_blkt_half = m_file.get("dz_blkt_half", scan=scan)
    ax_blanket.axhline(
        dz_blkt_half,
        color="purple",
        linestyle="--",
        linewidth=1.5,
        label="Blanket Half Height",
    )
    ax_blanket.axhline(
        -dz_blkt_half,
        color="purple",
        linestyle="--",
        linewidth=1.5,
        label="Blanket Half Height",
    )

    # Plot midplane line (horizontal dashed line at Z=0)
    ax_blanket.axhline(
        0.0,
        color="black",
        linestyle="--",
        linewidth=1.5,
        label="Midplane",
    )

    plot_main_power_flow(
        figs[28].add_subplot(111, aspect="equal"), m_file, scan, figs[28]
    )

    ax24 = figs[29].add_subplot(111)
    # set_position([left, bottom, width, height]) -> height ~ 0.66 => ~2/3 of page height
    ax24.set_position([0.08, 0.35, 0.84, 0.57])
    plot_system_power_profiles_over_time(ax24, m_file, scan, figs[29])

create_thickness_builds(m_file, scan)

Source code in process/core/io/plot_proc.py
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
def create_thickness_builds(m_file, scan: int):
    # Build the dictionaries of radial and vertical build values and cumulative values
    if int(m_file.get("i_single_null", scan=scan)) == 0:
        vertical_upper = [
            "z_plasma_xpoint_upper",
            "dz_fw_plasma_gap",
            "dz_divertor",
            "dz_shld_upper",
            "dz_vv_upper",
            "dz_shld_vv_gap",
            "dz_shld_thermal",
            "dr_tf_shld_gap",
            "dr_tf_inboard",
        ]
    else:
        vertical_upper = [
            "z_plasma_xpoint_upper",
            "dz_fw_plasma_gap",
            "dz_fw_upper",
            "dz_blkt_upper",
            "dr_shld_blkt_gap",
            "dz_shld_upper",
            "dz_vv_upper",
            "dz_shld_vv_gap",
            "dz_shld_thermal",
            "dr_tf_shld_gap",
            "dr_tf_inboard",
        ]

    radial = {}
    cumulative_radial = {}
    subtotal = 0
    for item in RADIAL_BUILD:
        if item == "rminori" or item == "rminoro":
            build = m_file.get("rminor", scan=scan)
        elif item == "vvblgapi" or item == "vvblgapo":
            build = m_file.get("dr_shld_blkt_gap", scan=scan)
        elif "dr_vv_inboard" in item:
            build = m_file.get("dr_vv_inboard", scan=scan)
        elif "dr_vv_outboard" in item:
            build = m_file.get("dr_vv_outboard", scan=scan)
        else:
            build = m_file.get(item, scan=scan)

    radial[item] = build
    subtotal += build
    cumulative_radial[item] = subtotal

    upper = {}
    cumulative_upper = {}
    subtotal = 0
    for item in vertical_upper:
        upper[item] = m_file.get(item, scan=scan)
        subtotal += upper[item]
        cumulative_upper[item] = subtotal

    lower = {}
    cumulative_lower = {}
    subtotal = 0
    for item in vertical_lower:
        lower[item] = m_file.get(item, scan=scan)
        subtotal -= lower[item]
        cumulative_lower[item] = subtotal

    return RadialBuild(
        upper, lower, radial, cumulative_upper, cumulative_lower, cumulative_radial
    )

main(args=None)

Source code in process/core/io/plot_proc.py
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
def main(args=None):
    args = parse_args(args)

    # create main plot
    # Increase range when adding new page
    pages = [plt.figure(figsize=(12, 9), dpi=80) for i in range(30)]

    # run main_plot
    main_plot(
        pages,
        mf.MFile(args.f) if args.f != "" else mf.MFile("MFILE.DAT"),
        scan=args.n or -1,
        demo_ranges=bool(args.DEMO_ranges),
        colour_scheme=int(args.colour),
    )

    if args.output_format == "pdf":
        with bpdf.PdfPages(args.f + "SUMMARY.pdf") as pdf:
            for p in pages:
                pdf.savefig(p)
    elif args.output_format == "png":
        folder = pathlib.Path(args.f.removesuffix(".DAT") + "_SUMMARY")
        folder.mkdir(parents=True, exist_ok=True)
        for no, page in enumerate(pages):
            page.savefig(pathlib.Path(folder, f"page{no}.png"), format="png")

    # show fig if option used
    if args.show:
        plt.show(block=True)

    plt.close("all")