Skip to content

Mesh Pancake3D

Implements mesh generation class and methods for the Pancake3D magnets.

Mesh

Bases: Base

Main mesh class for Pancake3D.

Parameters:

Name Type Description Default
fdm

FiQuS data model

required
geom_folder str

folder where the geometry files are saved

required
mesh_folder str

folder where the mesh files are saved

required
solution_folder str

folder where the solution files are saved

required
Source code in fiqus/mesh_generators/MeshPancake3D.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
2387
2388
2389
2390
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
class Mesh(Base):
    """
    Main mesh class for Pancake3D.

    :param fdm: FiQuS data model
    :param geom_folder: folder where the geometry files are saved
    :type geom_folder: str
    :param mesh_folder: folder where the mesh files are saved
    :type mesh_folder: str
    :param solution_folder: folder where the solution files are saved
    :type solution_folder: str
    """

    def __init__(
        self,
        fdm,
        geom_folder,
        mesh_folder,
        solution_folder,
    ) -> None:
        super().__init__(fdm, geom_folder, mesh_folder, solution_folder)

        # Read volume information file:
        with open(self.vi_file, "r") as f:
            self.dimTags = json.load(f)

        for key, value in self.dimTags.items():
            self.dimTags[key] = [tuple(dimTag) for dimTag in value]

        # Start GMSH:
        self.gu = GmshUtils(self.mesh_folder)
        self.gu.initialize()

        self.contactLayerAndWindingRadialLines = []  # Store for strucured terminals

    def generate_mesh(self):
        """
        Sets the mesh settings and generates the mesh.


        """
        logger.info("Generating Pancake3D mesh has been started.")

        start_time = timeit.default_timer()

        # =============================================================================
        # MESHING WINDING AND CONTACT LAYER STARTS =======================================
        # =============================================================================
        allWindingAndCLSurfaceTags = []
        allWindingAndCLLineTags = []
        for i in range(self.geo.N):
            # Get the volume tags:
            windingVolumeDimTags = self.dimTags[self.geo.wi.name + str(i + 1)]
            windingVolumeTags = [dimTag[1] for dimTag in windingVolumeDimTags]

            contactLayerVolumeDimTags = self.dimTags[self.geo.ii.name + str(i + 1)]
            contactLayerVolumeTags = [dimTag[1] for dimTag in contactLayerVolumeDimTags]

            # Get the surface and line tags:
            windingSurfaceTags, windingLineTags = self.get_boundaries(
                windingVolumeDimTags, returnTags=True
            )
            allWindingAndCLSurfaceTags.extend(windingSurfaceTags)
            allWindingAndCLLineTags.extend(windingLineTags)
            contactLayerSurfaceTags, contactLayerLineTags = self.get_boundaries(
                contactLayerVolumeDimTags, returnTags=True
            )
            allWindingAndCLSurfaceTags.extend(contactLayerSurfaceTags)
            allWindingAndCLLineTags.extend(contactLayerLineTags)

            self.structure_mesh(
                windingVolumeTags,
                windingSurfaceTags,
                windingLineTags,
                contactLayerVolumeTags,
                contactLayerSurfaceTags,
                contactLayerLineTags,
                meshSettingIndex=i,
            )

        notchVolumesDimTags = (
            self.dimTags["innerTransitionNotch"] + self.dimTags["outerTransitionNotch"]
        )
        notchVolumeTags = [dimTag[1] for dimTag in notchVolumesDimTags]

        notchSurfaceTags, notchLineTags = self.get_boundaries(
            notchVolumesDimTags, returnTags=True
        )

        for lineTag in notchLineTags:
            if lineTag not in allWindingAndCLLineTags:
                gmsh.model.mesh.setTransfiniteCurve(lineTag, 1)

        recombine = self.mesh.wi.elementType[0] in ["hexahedron", "prism"]
        for surfaceTag in notchSurfaceTags:
            if surfaceTag not in allWindingAndCLSurfaceTags:
                gmsh.model.mesh.setTransfiniteSurface(surfaceTag)
                if recombine:
                    normal = gmsh.model.getNormal(surfaceTag, [0.5, 0.5])
                    if abs(normal[2]) > 1e-4:
                        pass
                    else:
                        gmsh.model.mesh.setRecombine(2, surfaceTag)


        for volumeTag in notchVolumeTags:
            gmsh.model.mesh.setTransfiniteVolume(volumeTag)

        # =============================================================================
        # MESHING WINDING AND CONTACT LAYER ENDS =========================================
        # =============================================================================

        # =============================================================================
        # MESHING AIR STARTS ==========================================================
        # =============================================================================
        # Winding and contact layer extrusions of the air:
        # Get the volume tags:
        airTopWindingExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-TopPancakeWindingExtursion"
        ]

        airTopContactLayerExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-TopPancakeContactLayerExtursion"
        ]

        airTopTerminalsExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-TopTerminalsExtrusion"
        ]

        airBottomWindingExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-BottomPancakeWindingExtursion"
        ]

        airBottomContactLayerExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-BottomPancakeContactLayerExtursion"
        ]

        airBottomTerminalsExtrusionVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-BottomTerminalsExtrusion"
        ]

        removedAirVolumeDimTags = []
        newAirVolumeDimTags = []
        if self.mesh.ai.structured:
            # Then it means air type is cuboid!
            airTopWindingExtrusionVolumeTags = [
                dimTag[1] for dimTag in airTopWindingExtrusionVolumeDimTags
            ]
            airTopContactLayerExtrusionVolumeTags = [
                dimTag[1] for dimTag in airTopContactLayerExtrusionVolumeDimTags
            ]
            airBottomWindingExtrusionVolumeTags = [
                dimTag[1] for dimTag in airBottomWindingExtrusionVolumeDimTags
            ]
            airBottomContactLayerExtrusionVolumeTags = [
                dimTag[1] for dimTag in airBottomContactLayerExtrusionVolumeDimTags
            ]

            # Calcualte axial number of elements for air:
            axialElementsPerLengthForWinding = min(self.mesh.wi.axne) / self.geo.wi.h
            axneForAir = round(
                axialElementsPerLengthForWinding * self.geo.ai.margin + 1e-6
            )

            # Get the surface and line tags:
            (
                airTopWindingExtrusionSurfaceTags,
                airTopWindingExtrusionLineTags,
            ) = self.get_boundaries(
                airTopWindingExtrusionVolumeDimTags, returnTags=True
            )
            (
                airTopContactLayerExtrusionSurfaceTags,
                airTopContactLayerExtrusionLineTags,
            ) = self.get_boundaries(
                airTopContactLayerExtrusionVolumeDimTags, returnTags=True
            )

            self.structure_mesh(
                airTopWindingExtrusionVolumeTags,
                airTopWindingExtrusionSurfaceTags,
                airTopWindingExtrusionLineTags,
                airTopContactLayerExtrusionVolumeTags,
                airTopContactLayerExtrusionSurfaceTags,
                airTopContactLayerExtrusionLineTags,
                meshSettingIndex=self.geo.N - 1,  # The last pancake coil
                axialNumberOfElements=axneForAir,
                bumpCoefficient=1,
            )

            # Get the surface and line tags:
            (
                airBottomWindingExtrusionSurfaceTags,
                airBottomWindingExtrusionLineTags,
            ) = self.get_boundaries(
                airBottomWindingExtrusionVolumeDimTags, returnTags=True
            )
            (
                airBottomContactLayerExtrusionSurfaceTags,
                airBottomContactLayerExtrusionLineTags,
            ) = self.get_boundaries(
                airBottomContactLayerExtrusionVolumeDimTags, returnTags=True
            )

            self.structure_mesh(
                airBottomWindingExtrusionVolumeTags,
                airBottomWindingExtrusionSurfaceTags,
                airBottomWindingExtrusionLineTags,
                airBottomContactLayerExtrusionVolumeTags,
                airBottomContactLayerExtrusionSurfaceTags,
                airBottomContactLayerExtrusionLineTags,
                meshSettingIndex=0,  # The first pancake coil
                axialNumberOfElements=axneForAir,
                bumpCoefficient=1,
            )

            # Structure tubes of the air:
            airOuterTubeVolumeDimTags = self.dimTags[self.geo.ai.name + "-OuterTube"]
            airOuterTubeVolumeTags = [dimTag[1] for dimTag in airOuterTubeVolumeDimTags]

            airTopTubeTerminalsVolumeDimTags = self.dimTags[
                self.geo.ai.name + "-TopTubeTerminalsExtrusion"
            ]
            airTopTubeTerminalsVolumeTags = [
                dimTag[1] for dimTag in airTopTubeTerminalsVolumeDimTags
            ]

            airBottomTubeTerminalsVolumeDimTags = self.dimTags[
                self.geo.ai.name + "-BottomTubeTerminalsExtrusion"
            ]
            airBottomTubeTerminalsVolumeTags = [
                dimTag[1] for dimTag in airBottomTubeTerminalsVolumeDimTags
            ]

            # Structure inner cylinder of the air:
            airInnerCylinderVolumeDimTags = self.dimTags[
                self.geo.ai.name + "-InnerCylinder"
            ]
            airInnerCylinderVolumeTags = [
                dimTag[1] for dimTag in airInnerCylinderVolumeDimTags
            ]

            airTubesAndCylinders = airOuterTubeVolumeTags + airInnerCylinderVolumeTags

            if self.geo.ai.shellTransformation:
                shellVolumes = self.dimTags[self.geo.ai.shellVolumeName]
                shellVolumeTags = [dimTag[1] for dimTag in shellVolumes]
                airTubesAndCylinders.extend(shellVolumeTags)

            airRadialElementMultiplier = 1 / self.mesh.ai.radialElementSize
            self.structure_tubes_and_cylinders(
                airTubesAndCylinders,
                radialElementMultiplier=airRadialElementMultiplier,
            )

            if self.mesh.ti.structured:
                terminalsRadialElementMultiplier = 1 / self.mesh.ti.radialElementSize

                self.structure_tubes_and_cylinders(
                    airTopTubeTerminalsVolumeTags + airBottomTubeTerminalsVolumeTags,
                    radialElementMultiplier=terminalsRadialElementMultiplier,
                )

                airTopTouchingTerminalsVolumeDimTags = list(
                    set(airTopTerminalsExtrusionVolumeDimTags)
                    - set(airTopTubeTerminalsVolumeDimTags)
                )
                airTopTouchingTerminalsVolumeTags = [
                    dimTag[1] for dimTag in airTopTouchingTerminalsVolumeDimTags
                ]

                airBottomTouchingTerminalsVolumeDimTags = list(
                    set(airBottomTerminalsExtrusionVolumeDimTags)
                    - set(airBottomTubeTerminalsVolumeDimTags)
                )
                airBottomTouchingTerminalsVolumeTags = [
                    dimTag[1] for dimTag in airBottomTouchingTerminalsVolumeDimTags
                ]

                self.structure_tubes_and_cylinders(
                    airTopTouchingTerminalsVolumeTags
                    + airBottomTouchingTerminalsVolumeTags,
                    terminalNonTubeParts=True,
                    radialElementMultiplier=terminalsRadialElementMultiplier,
                )

        else:
            # Fuse top volumes:
            airTopVolumeDimTags = (
                airTopWindingExtrusionVolumeDimTags
                + airTopContactLayerExtrusionVolumeDimTags
                + airTopTerminalsExtrusionVolumeDimTags
            )
            airTopVolumeDimTag = Mesh.fuse_volumes(
                airTopVolumeDimTags,
                fuseSurfaces=True,
                fusedSurfacesArePlane=True,
            )
            newAirVolumeDimTags.append(airTopVolumeDimTag)
            removedAirVolumeDimTags.extend(airTopVolumeDimTags)

            # Fuse bottom volumes:
            airBottomVolumeDimTags = (
                airBottomWindingExtrusionVolumeDimTags
                + airBottomContactLayerExtrusionVolumeDimTags
                + airBottomTerminalsExtrusionVolumeDimTags
            )
            airBottomVolumeDimTag = Mesh.fuse_volumes(
                airBottomVolumeDimTags,
                fuseSurfaces=True,
                fusedSurfacesArePlane=True,
            )
            newAirVolumeDimTags.append(airBottomVolumeDimTag)
            removedAirVolumeDimTags.extend(airBottomVolumeDimTags)

            # Fuse inner cylinder and outer tube part of air:
            airInnerCylinderVolumeDimTags = self.dimTags[
                self.geo.ai.name + "-InnerCylinder"
            ]
            if self.geo.N > 1:
                # Fuse the first two and the last two volumes separately (due to cuts):
                firstTwoVolumes = airInnerCylinderVolumeDimTags[0:2]
                lastTwoVolumes = airInnerCylinderVolumeDimTags[-2:]
                airInnerCylinderVolumeDimTags = airInnerCylinderVolumeDimTags[2:-2]
                airInnerCylinderVolumeDimTag = Mesh.fuse_volumes(
                    airInnerCylinderVolumeDimTags, fuseSurfaces=False
                )
                airInnerCylinderVolumeDimTagFirst = Mesh.fuse_volumes(
                    firstTwoVolumes,
                    fuseSurfaces=False,
                )
                airInnerCylinderVolumeDimTagLast = Mesh.fuse_volumes(
                    lastTwoVolumes,
                    fuseSurfaces=False,
                )
                newAirVolumeDimTags.append(airInnerCylinderVolumeDimTag)
                newAirVolumeDimTags.append(airInnerCylinderVolumeDimTagFirst)
                newAirVolumeDimTags.append(airInnerCylinderVolumeDimTagLast)
                removedAirVolumeDimTags.extend(
                    airInnerCylinderVolumeDimTags + firstTwoVolumes + lastTwoVolumes
                )
                self.dimTags[self.geo.ai.name + "-InnerCylinder"] = [
                    airInnerCylinderVolumeDimTag,
                    airInnerCylinderVolumeDimTagFirst,
                    airInnerCylinderVolumeDimTagLast,
                ]
            else:
                pass
                # self.dimTags[self.geo.ai.name + "-InnerCylinder"] = [
                #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][1],
                #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][0],
                #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][2],
                # ]

            airOuterTubeVolumeDimTags = self.dimTags[self.geo.ai.name + "-OuterTube"]
            airOuterTubeVolumeDimTag = Mesh.fuse_volumes(
                airOuterTubeVolumeDimTags,
                fuseSurfaces=True,
                fusedSurfacesArePlane=False,
            )
            newAirOuterTubeVolumeDimTag = airOuterTubeVolumeDimTag
            removedAirVolumeDimTags.extend(airOuterTubeVolumeDimTags)
            self.dimTags[self.geo.ai.name + "-OuterTube"] = [newAirOuterTubeVolumeDimTag]

            if self.geo.ai.shellTransformation:
                # Fuse air shell volumes:
                if self.geo.ai.type == "cylinder":
                    removedShellVolumeDimTags = []
                    shellVolumeDimTags = self.dimTags[self.geo.ai.shellVolumeName]
                    shellVolumeDimTag = Mesh.fuse_volumes(
                        shellVolumeDimTags,
                        fuseSurfaces=True,
                        fusedSurfacesArePlane=False,
                    )
                    removedShellVolumeDimTags.extend(shellVolumeDimTags)
                    newShellVolumeDimTags = [shellVolumeDimTag]
                    for removedDimTag in removedShellVolumeDimTags:
                        self.dimTags[self.geo.ai.shellVolumeName].remove(removedDimTag)
                elif self.geo.ai.type == "cuboid":
                    # Unfortunately, surfaces cannot be combined for the cuboid type of air.
                    # However, it doesn't affect the mesh quality that much.
                    newShellVolumeDimTags = []

                    shellPart1VolumeDimTag = Mesh.fuse_volumes(
                        self.dimTags[self.geo.ai.shellVolumeName + "-Part1"],
                        fuseSurfaces=False,
                    )
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part1"] = [
                        shellPart1VolumeDimTag
                    ]

                    shellPart2VolumeDimTag = Mesh.fuse_volumes(
                        self.dimTags[self.geo.ai.shellVolumeName + "-Part2"],
                        fuseSurfaces=False,
                    )
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part2"] = [
                        shellPart2VolumeDimTag
                    ]

                    shellPart3VolumeDimTag = Mesh.fuse_volumes(
                        self.dimTags[self.geo.ai.shellVolumeName + "-Part3"],
                        fuseSurfaces=False,
                    )
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part3"] = [
                        shellPart3VolumeDimTag
                    ]

                    shellPart4VolumeDimTag = Mesh.fuse_volumes(
                        self.dimTags[self.geo.ai.shellVolumeName + "-Part4"],
                        fuseSurfaces=False,
                    )
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part4"] = [
                        shellPart4VolumeDimTag
                    ]

                # The problem is, shell volume and outer air tube volume has a common
                # surface and that surface should be combined as well for high quality mesh.
                # However, it can be only done for cylinder type of air for now.
                # Get the combined boundary surfaces:
                if self.geo.ai.type == "cylinder":
                    (
                        newAirOuterTubeVolumeDimTag,
                        newShellVolumeDimTag,
                    ) = Mesh.fuse_common_surfaces_of_two_volumes(
                        [airOuterTubeVolumeDimTag],
                        newShellVolumeDimTags,
                        fuseOtherSurfaces=False,
                        surfacesArePlane=False,
                    )
                    self.dimTags[self.geo.ai.name + "-OuterTube"] = [newAirOuterTubeVolumeDimTag]
                    airOuterTubeVolumeDimTag = newAirOuterTubeVolumeDimTag
                    self.dimTags[self.geo.ai.shellVolumeName].append(
                        newShellVolumeDimTag
                    )

            newAirVolumeDimTags.append(newAirOuterTubeVolumeDimTag)

            # Update volume tags dictionary of air:
            self.dimTags[self.geo.ai.name] = list(
                (
                    set(self.dimTags[self.geo.ai.name]) - set(removedAirVolumeDimTags)
                ).union(set(newAirVolumeDimTags))
            )

        # ==============================================================================
        # MESHING AIR ENDS =============================================================
        # ==============================================================================

        # ==============================================================================
        # MESHING TERMINALS STARTS =====================================================
        # ==============================================================================
        if self.mesh.ti.structured:
            # Structure tubes of the terminals:
            terminalOuterTubeVolumeDimTags = self.dimTags[self.geo.ti.o.name + "-Tube"]
            terminalOuterTubeVolumeTags = [
                dimTag[1] for dimTag in terminalOuterTubeVolumeDimTags
            ]
            terminalInnerTubeVolumeDimTags = self.dimTags[self.geo.ti.i.name + "-Tube"]
            terminalInnerTubeVolumeTags = [
                dimTag[1] for dimTag in terminalInnerTubeVolumeDimTags
            ]

            terminalsRadialElementMultiplier = 1 / self.mesh.ti.radialElementSize
            self.structure_tubes_and_cylinders(
                terminalOuterTubeVolumeTags + terminalInnerTubeVolumeTags,
                radialElementMultiplier=terminalsRadialElementMultiplier,
            )

            # Structure nontube parts of the terminals:
            terminalOuterNonTubeVolumeDimTags = self.dimTags[
                self.geo.ti.o.name + "-Touching"
            ]
            terminalOuterNonTubeVolumeTags = [
                dimTag[1] for dimTag in terminalOuterNonTubeVolumeDimTags
            ]
            terminalInnerNonTubeVolumeDimTags = self.dimTags[
                self.geo.ti.i.name + "-Touching"
            ]
            terminalInnerNonTubeVolumeTags = [
                dimTag[1] for dimTag in terminalInnerNonTubeVolumeDimTags
            ]

            self.structure_tubes_and_cylinders(
                terminalInnerNonTubeVolumeTags + terminalOuterNonTubeVolumeTags,
                terminalNonTubeParts=True,
                radialElementMultiplier=terminalsRadialElementMultiplier,
            )
        # ==============================================================================
        # MESHING TERMINALS ENDS =======================================================
        # ==============================================================================

        # ==============================================================================
        # FIELD SETTINGS STARTS ========================================================
        # ==============================================================================

        # Mesh fields for the air:
        # Meshes will grow as they get further from the field surfaces:
        fieldSurfacesDimTags = gmsh.model.getBoundary(
            self.dimTags[self.geo.wi.name], oriented=False, combined=True
        )
        fieldSurfacesTags = [dimTag[1] for dimTag in fieldSurfacesDimTags]

        distanceField = gmsh.model.mesh.field.add("Distance")

        gmsh.model.mesh.field.setNumbers(
            distanceField,
            "SurfacesList",
            fieldSurfacesTags,
        )

        thresholdField = gmsh.model.mesh.field.add("Threshold")
        gmsh.model.mesh.field.setNumber(thresholdField, "InField", distanceField)
        gmsh.model.mesh.field.setNumber(thresholdField, "SizeMin", self.mesh.sizeMin)
        gmsh.model.mesh.field.setNumber(thresholdField, "SizeMax", self.mesh.sizeMax)
        gmsh.model.mesh.field.setNumber(
            thresholdField, "DistMin", self.mesh.startGrowingDistance
        )

        gmsh.model.mesh.field.setNumber(
            thresholdField, "DistMax", self.mesh.stopGrowingDistance
        )

        gmsh.model.mesh.field.setAsBackgroundMesh(thresholdField)

        # ==============================================================================
        # FIELD SETTINGS ENDS ==========================================================
        # ==============================================================================

        gmsh.option.setNumber("Mesh.MeshSizeExtendFromBoundary", 0)
        gmsh.option.setNumber("Mesh.MeshSizeFromPoints", 0)
        gmsh.option.setNumber("Mesh.MeshSizeFromCurvature", 0)

        try:
            # Only print warnings and errors:
            # Don't print on terminal, because we will use logger:
            gmsh.option.setNumber("General.Terminal", 0)
            # Start logger:
            gmsh.logger.start()

            # Mesh:
            gmsh.model.mesh.generate()
            gmsh.model.mesh.optimize()

            # Print the log:
            log = gmsh.logger.get()
            for line in log:
                if line.startswith("Info"):
                    logger.info(re.sub(r"Info:\s+", "", line))
                elif line.startswith("Warning"):
                    logger.warning(re.sub(r"Warning:\s+", "", line))

            gmsh.logger.stop()
        except:
            # Print the log:
            log = gmsh.logger.get()
            for line in log:
                if line.startswith("Info"):
                    logger.info(re.sub(r"Info:\s+", "", line))
                elif line.startswith("Warning"):
                    logger.warning(re.sub(r"Warning:\s+", "", line))
                elif line.startswith("Error"):
                    logger.error(re.sub(r"Error:\s+", "", line))

            gmsh.logger.stop()

            self.generate_regions()

            logger.error(
                "Meshing Pancake3D magnet has failed. Try to change"
                " minimumElementSize and maximumElementSize parameters."
            )
            raise

        # SICN not implemented in 1D!
        allElementsDim2 = list(gmsh.model.mesh.getElements(dim=2)[1][0])
        allElementsDim3 = list(gmsh.model.mesh.getElements(dim=3)[1][0])
        allElements = allElementsDim2 + allElementsDim3
        elementQualities = gmsh.model.mesh.getElementQualities(allElements)
        lowestQuality = min(elementQualities)
        averageQuality = sum(elementQualities) / len(elementQualities)
        NofLowQualityElements = len(
            [quality for quality in elementQualities if quality < 0.01]
        )
        NofIllElemets = len(
            [quality for quality in elementQualities if quality < 0.001]
        )

        logger.info(
            f"The lowest quality among the elements is {lowestQuality:.4f} (SICN). The"
            " number of elements with quality lower than 0.01 is"
            f" {NofLowQualityElements}."
        )

        if NofIllElemets > 0:
            logger.warning(
                f"There are {NofIllElemets} elements with quality lower than 0.001. Try"
                " to change minimumElementSize and maximumElementSize parameters."
            )

        # Create cuts:
        # This is required to make the air a simply connected domain. This is required
        # for the solution part. You can read more about Homology in GMSH documentation.
        airTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ai.name]]

        if self.geo.ai.shellTransformation:
            shellTags = [
                dimTag[1] for dimTag in self.dimTags[self.geo.ai.shellVolumeName]
            ]
            airTags.extend(shellTags)

        dummyAirRegion = gmsh.model.addPhysicalGroup(dim=3, tags=airTags)
        dummyAirRegionDimTag = (3, dummyAirRegion)

        innerCylinderTags = [self.dimTags[self.geo.ai.name + "-InnerCylinder"][0][1]]
        gapTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ai.name + "-Gap"]]
        # Only remove every second gap:
        gapTags = gapTags[1::2]

        dummyAirRegionWithoutInnerCylinder = gmsh.model.addPhysicalGroup(
            dim=3, tags=list(set(airTags) - set(innerCylinderTags) - set(gapTags))
        )
        dummyAirRegionWithoutInnerCylinderDimTag = (
            3,
            dummyAirRegionWithoutInnerCylinder,
        )

        windingTags = [dimTag[1] for dimTag in self.dimTags[self.geo.wi.name]]
        dummyWindingRegion = gmsh.model.addPhysicalGroup(dim=3, tags=windingTags)
        dummyWindingRegionDimTag = (3, dummyWindingRegion)

        if self.geo.ii.tsa:
            # Find all the contact layer surfaces:
            allWindingDimTags = []
            for i in range(self.geo.N):
                windingDimTags = self.dimTags[self.geo.wi.name + str(i + 1)]
                allWindingDimTags.extend(windingDimTags)

            windingBoundarySurfaces = gmsh.model.getBoundary(
                allWindingDimTags, combined=True, oriented=False
            )
            allWindingSurfaces = gmsh.model.getBoundary(
                allWindingDimTags, combined=False, oriented=False
            )

            contactLayerSurfacesDimTags = list(
                set(allWindingSurfaces) - set(windingBoundarySurfaces)
            )
            contactLayerTags = [dimTag[1] for dimTag in contactLayerSurfacesDimTags]

            # Get rid of non-contactLayer surfaces:
            realContactLayerTags = []
            for contactLayerTag in contactLayerTags:
                surfaceNormal = list(gmsh.model.getNormal(contactLayerTag, [0.5, 0.5]))
                centerOfMass = gmsh.model.occ.getCenterOfMass(2, contactLayerTag)

                if (
                    abs(
                        surfaceNormal[0] * centerOfMass[0]
                        + surfaceNormal[1] * centerOfMass[1]
                    )
                    > 1e-6
                ):
                    realContactLayerTags.append(contactLayerTag)

            # Get rid of surfaces that touch terminals:
            terminalSurfaces = gmsh.model.getBoundary(
                self.dimTags[self.geo.ti.o.name] + self.dimTags[self.geo.ti.i.name],
                combined=False,
                oriented=False,
            )
            terminalSurfaces = [dimTag[1] for dimTag in terminalSurfaces]
            finalContactLayerTags = [
                tag for tag in realContactLayerTags if tag not in terminalSurfaces
            ]

            dummyContactLayerRegion = gmsh.model.addPhysicalGroup(
                dim=2, tags=finalContactLayerTags
            )
            dummyContactLayerRegionDimTag = (2, dummyContactLayerRegion)

        else:
            contactLayerTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ii.name]]

            # get rid of volumes that touch terminals:
            terminalSurfaces = gmsh.model.getBoundary(
                self.dimTags[self.geo.ti.o.name] + self.dimTags[self.geo.ti.i.name],
                combined=False,
                oriented=False,
            )
            finalContactLayerTags = []
            for contactLayerTag in contactLayerTags:
                insulatorSurfaces = gmsh.model.getBoundary(
                    [(3, contactLayerTag)], combined=False, oriented=False
                )
                itTouchesTerminals = False
                for insulatorSurface in insulatorSurfaces:
                    if insulatorSurface in terminalSurfaces:
                        itTouchesTerminals = True
                        break

                if not itTouchesTerminals:
                    finalContactLayerTags.append(contactLayerTag)

            dummyContactLayerRegion = gmsh.model.addPhysicalGroup(
                dim=3, tags=finalContactLayerTags
            )
            dummyContactLayerRegionDimTag = (3, dummyContactLayerRegion)

        # First cohomology request (normal cut for NI coils):
        gmsh.model.mesh.addHomologyRequest(
            "Cohomology",
            domainTags=[dummyAirRegion],
            subdomainTags=[],
            dims=[1],
        )

        # Second cohomology request (insulated cut for insulated coils):
        if self.geo.N > 1:
            gmsh.model.mesh.addHomologyRequest(
                "Cohomology",
                domainTags=[
                    dummyAirRegionWithoutInnerCylinder,
                    dummyContactLayerRegion,
                ],
                subdomainTags=[],
                dims=[1],
            )
        else:
            gmsh.model.mesh.addHomologyRequest(
                "Cohomology",
                domainTags=[
                    dummyAirRegion,
                    dummyContactLayerRegion,
                ],
                subdomainTags=[],
                dims=[1],
            )

        # Third cohomology request (for cuts between pancake coils):
        gmsh.model.mesh.addHomologyRequest(
            "Cohomology",
            domainTags=[
                dummyAirRegion,
                dummyContactLayerRegion,
                dummyWindingRegion,
            ],
            subdomainTags=[],
            dims=[1],
        )

        # Start logger:
        gmsh.logger.start()

        cuts = gmsh.model.mesh.computeHomology()

        # Print the log:
        log = gmsh.logger.get()
        for line in log:
            if line.startswith("Info"):
                logger.info(re.sub(r"Info:\s+", "", line))
            elif line.startswith("Warning"):
                logger.warning(re.sub(r"Warning:\s+", "", line))
        gmsh.logger.stop()

        if self.geo.N > 1:
            cutsDictionary = {
                "H^1{1}": self.geo.ai.cutName,
                "H^1{1,4,3}": "CutsBetweenPancakes",
                "H^1{2,4}": "CutsForPerfectInsulation",
            }
        else:
            cutsDictionary = {
                "H^1{1}": self.geo.ai.cutName,
                "H^1{1,4,3}": "CutsBetweenPancakes",
                "H^1{1,4}": "CutsForPerfectInsulation",
            }
        cutTags = [dimTag[1] for dimTag in cuts]
        cutEntities = []
        for tag in cutTags:
            name = gmsh.model.getPhysicalName(1, tag)
            cutEntities = list(gmsh.model.getEntitiesForPhysicalGroup(1, tag))
            cutEntitiesDimTags = [(1, cutEntity) for cutEntity in cutEntities]
            for key in cutsDictionary:
                if key in name:
                    if cutsDictionary[key] in self.dimTags:
                        self.dimTags[cutsDictionary[key]].extend(cutEntitiesDimTags)
                    else:
                        self.dimTags[cutsDictionary[key]] = cutEntitiesDimTags

        # Remove newly created physical groups because they will be created again in
        # generate_regions method.
        gmsh.model.removePhysicalGroups(
            [dummyContactLayerRegionDimTag]
            + [dummyAirRegionDimTag]
            + [dummyAirRegionWithoutInnerCylinderDimTag]
            + [dummyWindingRegionDimTag]
            + cuts
        )

        logger.info(
            "Generating Pancake3D mesh has been finished in"
            f" {timeit.default_timer() - start_time:.2f} s."
        )

    def structure_mesh(
        self,
        windingVolumeTags,
        windingSurfaceTags,
        windingLineTags,
        contactLayerVolumeTags,
        contactLayerSurfaceTags,
        contactLayerLineTags,
        meshSettingIndex,
        axialNumberOfElements=None,
        bumpCoefficient=None,
    ):
        """
        Structures the winding and contact layer meshed depending on the user inputs. If
        the bottom and top part of the air is to be structured, the same method is used.

        :param windingVolumeTags: tags of the winding volumes
        :type windingVolumeTags: list[int]
        :param windingSurfaceTags: tags of the winding surfaces
        :type windingSurfaceTags: list[int]
        :param windingLineTags: tags of the winding lines
        :type windingLineTags: list[int]
        :param contactLayerVolumeTags: tags of the contact layer volumes
        :type contactLayerVolumeTags: list[int]
        :param contactLayerSurfaceTags: tags of the contact layer surfaces
        :type contactLayerSurfaceTags: list[int]
        :param contactLayerLineTags: tags of the contact layer lines
        :type contactLayerLineTags: list[int]
        :param meshSettingIndex: index of the mesh setting
        :type meshSettingIndex: int
        :param axialNumberOfElements: number of axial elements
        :type axialNumberOfElements: int, optional
        :param bumpCoefficient: bump coefficient for axial meshing
        :type bumpCoefficient: float, optional

        """
        # Transfinite settings:
        # Arc lenght of the innermost one turn of spiral:
        if self.geo.ii.tsa:
            oneTurnSpiralLength = curve.calculateSpiralArcLength(
                self.geo.wi.r_i,
                self.geo.wi.r_i
                + self.geo.wi.t
                + self.geo.ii.t * (self.geo.N - 1) / self.geo.N,
                0,
                2 * math.pi,
            )
        else:
            oneTurnSpiralLength = curve.calculateSpiralArcLength(
                self.geo.wi.r_i,
                self.geo.wi.r_i + self.geo.wi.t,
                0,
                2 * math.pi,
            )

        # Arc length of one element:
        arcElementLength = oneTurnSpiralLength / self.mesh.wi.ane[meshSettingIndex]

        # Number of azimuthal elements per turn:
        arcNumElementsPerTurn = round(oneTurnSpiralLength / arcElementLength)

        # Make all the lines transfinite:
        for j, lineTags in enumerate([windingLineTags, contactLayerLineTags]):
            for lineTag in lineTags:
                lineObject = curve(lineTag, self.geo)

                if lineObject.type is curveType.horizontal:
                    # The curve is horizontal, so radialNumberOfElementsPerTurn entry is
                    # used.
                    if self.geo.ii.tsa:
                        numNodes = self.mesh.wi.rne[meshSettingIndex] + 1

                    else:
                        if j == 0:
                            # This line is the winding's horizontal line:
                            numNodes = self.mesh.wi.rne[meshSettingIndex] + 1

                        else:
                            # This line is the contact layer's horizontal line:
                            numNodes = self.mesh.ii.rne[meshSettingIndex] + 1

                    # Set transfinite curve:
                    self.contactLayerAndWindingRadialLines.append(lineTag)
                    gmsh.model.mesh.setTransfiniteCurve(lineTag, numNodes)

                elif lineObject.type is curveType.axial:
                    # The curve is axial, so axialNumberOfElements entry is used.
                    if axialNumberOfElements is None:
                        numNodes = self.mesh.wi.axne[meshSettingIndex] + 1
                    else:
                        numNodes = axialNumberOfElements + 1

                    if bumpCoefficient is None:
                        bumpCoefficient = self.mesh.wi.axbc[meshSettingIndex]
                    gmsh.model.mesh.setTransfiniteCurve(
                        lineTag, numNodes, meshType="Bump", coef=bumpCoefficient
                    )

                else:
                    # The line is an arc, so the previously calculated arcNumElementsPerTurn
                    # is used. All the number of elements per turn must be the same
                    # independent of radial position. Otherwise, transfinite meshing cannot
                    # be performed. However, to support the float number of turns, number
                    # of nodes are being calculated depending on the start and end turns of
                    # the arc.d
                    lengthInTurns = abs(lineObject.n2 - lineObject.n1)
                    if lengthInTurns > 0.5:
                        # The arc can never be longer than half a turn.
                        lengthInTurns = 1 - lengthInTurns

                    lengthInTurns = (
                        round(lengthInTurns / self.geo.wi.turnTol) * self.geo.wi.turnTol
                    )

                    arcNumEl = round(arcNumElementsPerTurn * lengthInTurns)

                    arcNumNodes = int(arcNumEl + 1)

                    # Set transfinite curve:
                    gmsh.model.mesh.setTransfiniteCurve(lineTag, arcNumNodes)

        for j, surfTags in enumerate([windingSurfaceTags, contactLayerSurfaceTags]):
            for surfTag in surfTags:
                # Make all the surfaces transfinite:
                gmsh.model.mesh.setTransfiniteSurface(surfTag)

                if self.mesh.wi.elementType[meshSettingIndex] == "hexahedron":
                    # If the element type is hexahedron, recombine all the surfaces:
                    gmsh.model.mesh.setRecombine(2, surfTag)
                elif self.mesh.wi.elementType[meshSettingIndex] == "prism":
                    # If the element type is prism, recombine only the side surfaces:
                    surfaceNormal = list(gmsh.model.getNormal(surfTag, [0.5, 0.5]))
                    if abs(surfaceNormal[2]) < 1e-6:
                        gmsh.model.mesh.setRecombine(2, surfTag)

                # If the element type is tetrahedron, do not recombine any surface.

        for volTag in windingVolumeTags + contactLayerVolumeTags:
            # Make all the volumes transfinite:
            gmsh.model.mesh.setTransfiniteVolume(volTag)

    def structure_tubes_and_cylinders(
        self, volumeTags, terminalNonTubeParts=False, radialElementMultiplier=1
    ):
        # Number of azimuthal elements per quarter:
        arcNumElementsPerQuarter = int(self.mesh.wi.ane[0] / 4)
        radialNumberOfElementsPerLength = (
            self.mesh.wi.rne[0] / self.geo.wi.t * radialElementMultiplier
        )

        surfacesDimTags = gmsh.model.getBoundary(
            [(3, tag) for tag in volumeTags], combined=False, oriented=False
        )
        surfacesTags = [dimTag[1] for dimTag in surfacesDimTags]
        surfacesTags = list(set(surfacesTags))

        curvesDimTags = gmsh.model.getBoundary(
            surfacesDimTags, combined=False, oriented=False
        )
        curvesTags = [dimTag[1] for dimTag in curvesDimTags]

        # Make all the lines transfinite:
        for curveTag in curvesTags:
            curveObject = curve(curveTag, self.geo)

            if curveObject.type is curveType.horizontal:
                # The curve is horizontal, so radialNumberOfElementsPerTurn entry is
                # used.

                # But, the curve might be a part of the transitionNotch.
                isTransitionNotch = False
                point2 = curveObject.points[1]
                point1 = curveObject.points[0]
                if (
                    abs(point2[0] - point1[0]) > 1e-5
                    and abs(point2[1] - point1[1]) > 1e-5
                ):
                    isTransitionNotch = True

                if isTransitionNotch:
                    gmsh.model.mesh.setTransfiniteCurve(curveTag, 2)
                else:
                    if terminalNonTubeParts:
                        if curveTag not in self.contactLayerAndWindingRadialLines:
                            numNodes = (
                                round(radialNumberOfElementsPerLength * self.geo.ti.i.t)
                                + 1
                            )
                            # Set transfinite curve:
                            gmsh.model.mesh.setTransfiniteCurve(curveTag, numNodes)
                    else:
                        numNodes = (
                            round(radialNumberOfElementsPerLength * curveObject.length)
                            + 1
                        )
                        # Set transfinite curve:
                        gmsh.model.mesh.setTransfiniteCurve(curveTag, numNodes)

            elif curveObject.type is curveType.axial:
                # The curve is axial, so axialNumberOfElements entry is used.
                if math.isclose(curveObject.length, self.geo.wi.h, rel_tol=1e-7):
                    numNodes = min(self.mesh.wi.axne) + 1
                else:
                    axialElementsPerLength = min(self.mesh.wi.axne) / self.geo.wi.h
                    numNodes = (
                        round(axialElementsPerLength * curveObject.length + 1e-6) + 1
                    )

                gmsh.model.mesh.setTransfiniteCurve(curveTag, numNodes)

            else:
                # The line is an arc
                lengthInTurns = abs(curveObject.n2 - curveObject.n1)
                if lengthInTurns > 0.5:
                    # The arc can never be longer than half a turn.
                    lengthInTurns = 1 - lengthInTurns

                lengthInTurns = (
                    round(lengthInTurns / self.geo.wi.turnTol) * self.geo.wi.turnTol
                )

                arcNumEl = round(arcNumElementsPerQuarter * 4 * lengthInTurns)

                arcNumNodes = int(arcNumEl + 1)

                # Set transfinite curve:

                gmsh.model.mesh.setTransfiniteCurve(curveTag, arcNumNodes)

        for surfaceTag in surfacesTags:
            # Make all the surfaces transfinite:

            if self.mesh.wi.elementType[0] == "hexahedron":
                # If the element type is hexahedron, recombine all the surfaces:
                gmsh.model.mesh.setRecombine(2, surfaceTag)
            elif self.mesh.wi.elementType[0] == "prism":
                # If the element type is prism, recombine only the side surfaces:
                surfaceNormal = list(gmsh.model.getNormal(surfaceTag, [0.5, 0.5]))
                if abs(surfaceNormal[2]) < 1e-5:
                    gmsh.model.mesh.setRecombine(2, surfaceTag)

            curves = gmsh.model.getBoundary(
                [(2, surfaceTag)], combined=False, oriented=False
            )
            numberOfCurves = len(curves)
            if terminalNonTubeParts:
                if numberOfCurves == 4:
                    numberOfHorizontalCurves = 0
                    for curveTag in curves:
                        curveObject = curve(curveTag[1], self.geo)
                        if curveObject.type is curveType.horizontal:
                            numberOfHorizontalCurves += 1

                    if numberOfHorizontalCurves == 3:
                        pass
                    else:
                        gmsh.model.mesh.setTransfiniteSurface(surfaceTag)

                elif numberOfCurves == 3:
                    pass
                else:
                    curves = gmsh.model.getBoundary(
                        [(2, surfaceTag)], combined=False, oriented=False
                    )
                    curveObjects = [curve(line[1], self.geo) for line in curves]

                    divisionCurves = []
                    for curveObject in curveObjects:
                        if curveObject.type is curveType.horizontal:
                            point1 = curveObject.points[0]
                            point2 = curveObject.points[1]
                            if not (
                                abs(point2[0] - point1[0]) > 1e-5
                                and abs(point2[1] - point1[1]) > 1e-5
                            ):
                                divisionCurves.append(curveObject)

                    cornerPoints = (
                        divisionCurves[0].pointTags + divisionCurves[1].pointTags
                    )

                    if surfaceTag not in alreadyMeshedSurfaceTags:
                        alreadyMeshedSurfaceTags.append(surfaceTag)
                        gmsh.model.mesh.setTransfiniteSurface(
                            surfaceTag, cornerTags=cornerPoints
                        )
            else:
                if numberOfCurves == 3:
                    # Then it is a pie, corner points should be adjusted:
                    originPointTag = None
                    curveObject1 = curve(curves[0][1], self.geo)
                    for point, tag in zip(curveObject1.points, curveObject1.pointTags):
                        if math.sqrt(point[0] ** 2 + point[1] ** 2) < 1e-6:
                            originPointTag = tag

                    if originPointTag is None:
                        curveObject2 = curve(curves[1][1], self.geo)
                        for point, tag in zip(
                            curveObject2.points, curveObject2.pointTags
                        ):
                            if math.sqrt(point[0] ** 2 + point[1] ** 2) < 1e-6:
                                originPointTag = tag

                    otherPointDimTags = gmsh.model.getBoundary(
                        [(2, surfaceTag)],
                        combined=False,
                        oriented=False,
                        recursive=True,
                    )
                    otherPointTags = [dimTag[1] for dimTag in otherPointDimTags]
                    otherPointTags.remove(originPointTag)
                    cornerTags = [originPointTag] + otherPointTags
                    gmsh.model.mesh.setTransfiniteSurface(
                        surfaceTag, cornerTags=cornerTags
                    )
                else:
                    gmsh.model.mesh.setTransfiniteSurface(surfaceTag)

        for volumeTag in volumeTags:
            if terminalNonTubeParts:
                surfaces = gmsh.model.getBoundary(
                    [(3, volumeTag)], combined=False, oriented=False
                )
                curves = gmsh.model.getBoundary(
                    surfaces, combined=False, oriented=False
                )
                curves = list(set(curves))

                if len(curves) == 12:
                    numberOfArcs = 0
                    for curveTag in curves:
                        curveObject = curve(curveTag[1], self.geo)
                        if curveObject.type is curveType.spiralArc:
                            numberOfArcs += 1
                    if numberOfArcs == 2:
                        pass
                    else:
                        gmsh.model.mesh.setTransfiniteVolume(volumeTag)
                # elif len(curves) == 15:
                #     divisionCurves = []
                #     for curveTag in curves:
                #         curveObject = curve(curveTag[1], self.geo)
                #         if curveObject.type is curveType.horizontal:
                #             point1 = curveObject.points[0]
                #             point2 = curveObject.points[1]
                #             if not (
                #                 abs(point2[0] - point1[0]) > 1e-5
                #                 and abs(point2[1] - point1[1]) > 1e-5
                #             ):
                #                 divisionCurves.append(curveObject)

                #     cornerPoints = (
                #         divisionCurves[0].pointTags
                #         + divisionCurves[1].pointTags
                #         + divisionCurves[2].pointTags
                #         + divisionCurves[3].pointTags
                #     )
                #     gmsh.model.mesh.setTransfiniteVolume(
                #         volumeTag, cornerTags=cornerPoints
                #     )
            else:
                # Make all the volumes transfinite:
                gmsh.model.mesh.setTransfiniteVolume(volumeTag)

    @staticmethod
    def get_boundaries(volumeDimTags, returnTags=False):
        """
        Returns all the surface and line dimTags or tags of a given list of volume
        dimTags.

        :param volumeDimTags: dimTags of the volumes
        :type volumeDimTags: list[tuple[int, int]]
        :param returnTags: if True, returns tags instead of dimTags
        :type returnTags: bool, optional
        :return: surface and line dimTags or tags
        :rtype: tuple[list[tuple[int, int]], list[tuple[int, int]]] or
            tuple[list[int], list[int]]
        """
        # Get the surface tags:
        surfaceDimTags = list(
            set(
                gmsh.model.getBoundary(
                    volumeDimTags,
                    combined=False,
                    oriented=False,
                    recursive=False,
                )
            )
        )

        # Get the line tags:
        lineDimTags = list(
            set(
                gmsh.model.getBoundary(
                    surfaceDimTags,
                    combined=False,
                    oriented=False,
                    recursive=False,
                )
            )
        )

        if returnTags:
            surfaceTags = [dimTag[1] for dimTag in surfaceDimTags]
            lineTags = [dimTag[1] for dimTag in lineDimTags]
            return surfaceTags, lineTags
        else:
            return surfaceDimTags, lineDimTags

    @staticmethod
    def fuse_volumes(volumeDimTags, fuseSurfaces=True, fusedSurfacesArePlane=False):
        """
        Fuses all the volumes in a given list of volume dimTags, removes old volumes,
        and returns the new volume dimTag. Also, if compundSurfacces is True, it fuses
        the surfaces that only belong to the volume. fusedSurfacesArePlane can be
        used to change the behavior of the fuse_surfaces method.

        :param volumeDimTags: dimTags of the volumes
        :type volumeDimTags: list[tuple[int, int]]
        :param fuseSurfaces: if True, fuses the surfaces that only belong to the
            volume
        :type fuseSurfaces: bool, optional
        :param fusedSurfacesArePlane: if True, fused surfaces are assumed to be
            plane, and fusion is performed accordingly
        :return: new volume's dimTag
        :rtype: tuple[int, int]
        """

        # Get the combined boundary surfaces:
        boundarySurfacesDimTags = gmsh.model.getBoundary(
            volumeDimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )
        boundarSurfacesTags = [dimTag[1] for dimTag in boundarySurfacesDimTags]

        # Get all the boundary surfaces:
        allBoundarySurfacesDimTags = gmsh.model.getBoundary(
            volumeDimTags,
            combined=False,
            oriented=False,
            recursive=False,
        )

        # Find internal (common) surfaces:
        internalSurfacesDimTags = list(
            set(allBoundarySurfacesDimTags) - set(boundarySurfacesDimTags)
        )

        # Get the combined boundary lines:
        boundaryLinesDimTags = gmsh.model.getBoundary(
            allBoundarySurfacesDimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )
        boundarLinesTags = [dimTag[1] for dimTag in boundaryLinesDimTags]

        # Get all the boundary lines:
        allBoundaryLinesDimTags = gmsh.model.getBoundary(
            allBoundarySurfacesDimTags,
            combined=False,
            oriented=False,
            recursive=False,
        )

        # Find internal (common) lines:
        internalLinesDimTags = list(
            set(allBoundaryLinesDimTags) - set(boundarLinesTags)
        )

        # Remove the old volumes:
        removedVolumeDimTags = volumeDimTags
        gmsh.model.occ.remove(removedVolumeDimTags, recursive=False)

        # Remove the internal surfaces:
        gmsh.model.occ.remove(internalSurfacesDimTags, recursive=False)

        # Remove the internal lines:
        gmsh.model.occ.remove(internalLinesDimTags, recursive=False)

        # Create a new single volume (even thought we don't use the new volume tag
        # directly, it is required for finding the surfaces that only belong to the
        # volume):
        surfaceLoop = gmsh.model.occ.addSurfaceLoop(boundarSurfacesTags, sewing=True)
        newVolumeTag = gmsh.model.occ.addVolume([surfaceLoop])
        newVolumeDimTag = (3, newVolumeTag)
        gmsh.model.occ.synchronize()

        if fuseSurfaces:
            newVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
                (3, newVolumeTag), surfacesArePlane=fusedSurfacesArePlane
            )

        return newVolumeDimTag

    @staticmethod
    def fuse_common_surfaces_of_two_volumes(
        volume1DimTags, volume2DimTags, fuseOtherSurfaces=False, surfacesArePlane=False
    ):
        """
        Fuses common surfaces of two volumes. Volumes are given as a list of dimTags,
        but they are assumed to form a single volume, and this function fuses those
        multiple volumes into a single volume as well. If fuseOtherSurfaces is set to
        True, it tries to fuse surfaces that only belong to one volume too; however,
        that feature is not used in Pancake3D currently.

        :param volume1DimTags: dimTags of the first volume
        :type volume1DimTags: list[tuple[int, int]]
        :param volume2DimTags: dimTags of the second volume
        :type volume2DimTags: list[tuple[int, int]]
        :param fuseOtherSurfaces: if True, fuses the surfaces that only belong to one
            volume
        :type fuseOtherSurfaces: bool, optional
        :param surfacesArePlane: if True, fused surfaces are assumed to be plane, and
            fusion is performed accordingly
        :type surfacesArePlane: bool, optional
        :return: new volumes dimTags
        :rtype: tuple[tuple[int, int], tuple[int, int]]
        """
        vol1BoundarySurfacesDimTags = gmsh.model.getBoundary(
            volume1DimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )

        vol2BoundarySurfacesDimTags = gmsh.model.getBoundary(
            volume2DimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )

        # Remove the old volumes:
        gmsh.model.occ.remove(volume1DimTags + volume2DimTags, recursive=False)

        # Find common surfaces:
        commonSurfacesDimTags = list(
            set(vol2BoundarySurfacesDimTags).intersection(
                set(vol1BoundarySurfacesDimTags)
            )
        )

        # Fuse common surfaces:
        fusedCommonSurfaceDimTags = Mesh.fuse_surfaces(
            commonSurfacesDimTags, surfacesArePlane=surfacesArePlane
        )

        # Create the new volumes:
        for commonSurfaceDimTag in commonSurfacesDimTags:
            vol1BoundarySurfacesDimTags.remove(commonSurfaceDimTag)
            vol2BoundarySurfacesDimTags.remove(commonSurfaceDimTag)

        vol1BoundarySurfacesDimTags.extend(fusedCommonSurfaceDimTags)
        vol1BoundarySurfaceTags = [dimTag[1] for dimTag in vol1BoundarySurfacesDimTags]
        vol2BoundarySurfacesDimTags.extend(fusedCommonSurfaceDimTags)
        vol2BoundarySurfaceTags = [dimTag[1] for dimTag in vol2BoundarySurfacesDimTags]

        vol1SurfaceLoop = gmsh.model.occ.addSurfaceLoop(
            vol1BoundarySurfaceTags, sewing=True
        )
        vol1NewVolumeDimTag = (3, gmsh.model.occ.addVolume([vol1SurfaceLoop]))

        vol2SurfaceLoop = gmsh.model.occ.addSurfaceLoop(
            vol2BoundarySurfaceTags, sewing=True
        )
        vol2NewVolumeDimTag = (
            3,
            gmsh.model.occ.addVolume([vol2SurfaceLoop]),
        )

        gmsh.model.occ.synchronize()

        if fuseOtherSurfaces:
            vol1NewVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
                vol1NewVolumeDimTag, surfacesArePlane=surfacesArePlane
            )
            vol2NewVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
                vol2NewVolumeDimTag, surfacesArePlane=surfacesArePlane
            )

        return vol1NewVolumeDimTag, vol2NewVolumeDimTag

    @staticmethod
    def fuse_possible_surfaces_of_a_volume(volumeDimTag, surfacesArePlane=False):
        """
        Fuses surfaces that only belong to the volumeDimTag.

        :param volumeDimTag: dimTag of the volume
        :type volumeDimTag: tuple[int, int]
        :param surfacesArePlane: if True, fused surfaces are assumed to be plane, and
            fusion is performed accordingly
        :type surfacesArePlane: bool, optional
        :return: new volume dimTag
        :rtype: tuple[int, int]
        """
        boundarySurfacesDimTags = gmsh.model.getBoundary(
            [volumeDimTag],
            combined=True,
            oriented=False,
            recursive=False,
        )
        boundarSurfacesTags = [dimTag[1] for dimTag in boundarySurfacesDimTags]

        # Combine surfaces that only belong to the volume:
        toBeFusedSurfacesDimTags = []
        surfacesNormals = []
        for surfaceDimTag in boundarySurfacesDimTags:
            upward, _ = gmsh.model.getAdjacencies(surfaceDimTag[0], surfaceDimTag[1])

            if len(list(upward)) == 1:
                toBeFusedSurfacesDimTags.append(surfaceDimTag)
                # Get the normal of the surface:
                surfacesNormals.append(
                    list(gmsh.model.getNormal(surfaceDimTag[1], [0.5, 0.5]))
                )

        # Remove the old volume (it is not required anymore):
        gmsh.model.occ.remove([volumeDimTag], recursive=False)
        gmsh.model.occ.synchronize()

        # Categorize surfaces based on their normals so that they can be combined
        # correctly. Without these, perpendicular surfaces will cause problems.

        # Define a threshold to determine if two surface normals are similar or not
        threshold = 1e-6

        # Initialize an empty list to store the sets of surfaces
        setsOfSurfaces = []

        # Calculate the Euclidean distance between each pair of objects
        for i in range(len(toBeFusedSurfacesDimTags)):
            surfaceDimTag = toBeFusedSurfacesDimTags[i]
            surfaceTouchingVolumeTags, _ = list(
                gmsh.model.getAdjacencies(surfaceDimTag[0], surfaceDimTag[1])
            )
            surfaceNormal = surfacesNormals[i]
            assignedToASet = False

            for surfaceSet in setsOfSurfaces:
                representativeSurfaceDimTag = surfaceSet[0]
                representativeSurfaceTouchingVolumeTags, _ = list(
                    gmsh.model.getAdjacencies(
                        representativeSurfaceDimTag[0],
                        representativeSurfaceDimTag[1],
                    )
                )
                representativeNormal = list(
                    gmsh.model.getNormal(representativeSurfaceDimTag[1], [0.5, 0.5])
                )

                # Calculate the difference between surfaceNormal and
                # representativeNormal:
                difference = math.sqrt(
                    sum(
                        (x - y) ** 2
                        for x, y in zip(surfaceNormal, representativeNormal)
                    )
                )

                # Check if the distance is below the threshold
                if difference < threshold and set(surfaceTouchingVolumeTags) == set(
                    representativeSurfaceTouchingVolumeTags
                ):
                    # Add the object to an existing category
                    surfaceSet.append(surfaceDimTag)
                    assignedToASet = True
                    break

            if not assignedToASet:
                # Create a new category with the current object if none of the
                # existing sets match
                setsOfSurfaces.append([surfaceDimTag])

        for surfaceSet in setsOfSurfaces:
            if len(surfaceSet) > 1:
                oldSurfaceDimTags = surfaceSet
                newSurfaceDimTags = Mesh.fuse_surfaces(
                    oldSurfaceDimTags, surfacesArePlane=surfacesArePlane
                )
                newSurfaceTags = [dimTag[1] for dimTag in newSurfaceDimTags]

                oldSurfaceTags = [dimTag[1] for dimTag in oldSurfaceDimTags]
                boundarSurfacesTags = [
                    tag for tag in boundarSurfacesTags if tag not in oldSurfaceTags
                ]
                boundarSurfacesTags.extend(newSurfaceTags)

        # Create a new single volume:
        surfaceLoop = gmsh.model.occ.addSurfaceLoop(boundarSurfacesTags, sewing=True)
        newVolumeTag = gmsh.model.occ.addVolume([surfaceLoop])
        gmsh.model.occ.synchronize()

        return (3, newVolumeTag)

    @staticmethod
    def fuse_surfaces(surfaceDimTags, surfacesArePlane=False, categorizeSurfaces=False):
        """
        Fuses all the surfaces in a given list of surface dimTags, removes the old
        surfaces, and returns the new dimTags. If surfacesArePlane is True, the surfaces
        are assumed to be plane, and fusing will be done without gmsh.model.occ.fuse
        method, which is faster.

        :param surfaceDimTags: dimTags of the surfaces
        :type surfaceDimTags: list[tuple[int, int]]
        :param surfacesArePlane: if True, surfaces are assumed to be plane
        :type surfacesArePlane: bool, optional
        :return: newly created surface dimTags
        :rtype: list[tuple[int, int]]
        """
        oldSurfaceDimTags = surfaceDimTags

        if surfacesArePlane:
            # Get the combined boundary curves:
            boundaryCurvesDimTags = gmsh.model.getBoundary(
                oldSurfaceDimTags,
                combined=True,
                oriented=False,
                recursive=False,
            )

            # Get all the boundary curves:
            allCurvesDimTags = gmsh.model.getBoundary(
                oldSurfaceDimTags,
                combined=False,
                oriented=False,
                recursive=False,
            )

            # Find internal (common) curves:
            internalCurvesDimTags = list(
                set(allCurvesDimTags) - set(boundaryCurvesDimTags)
            )

            # Remove the old surfaces:
            gmsh.model.occ.remove(oldSurfaceDimTags, recursive=False)

            # Remove the internal curves:
            gmsh.model.occ.remove(internalCurvesDimTags, recursive=True)

            # Create a new single surface:
            def findOuterOnes(dimTags, findInnerOnes=False):
                """
                Finds the outermost surface/curve/point in a list of dimTags. The outermost means
                the furthest from the origin.
                """
                dim = dimTags[0][0]

                if dim == 2:
                    distances = []
                    for dimTag in dimTags:
                        _, curves = gmsh.model.occ.getCurveLoops(dimTag[1])
                        for curve in curves:
                            curve = list(curve)
                            gmsh.model.occ.synchronize()
                            pointTags = gmsh.model.getBoundary(
                                [(1, curveTag) for curveTag in curve],
                                oriented=False,
                                combined=False,
                            )
                            # Get the positions of the points:
                            points = []
                            for dimTag in pointTags:
                                boundingbox1 = gmsh.model.occ.getBoundingBox(
                                    0, dimTag[1]
                                )[:3]
                                boundingbox2 = gmsh.model.occ.getBoundingBox(
                                    0, dimTag[1]
                                )[3:]
                                boundingbox = list(
                                    map(operator.add, boundingbox1, boundingbox2)
                                )
                                points.append(
                                    list(map(operator.truediv, boundingbox, (2, 2, 2)))
                                )

                            distances.append(
                                max([point[0] ** 2 + point[1] ** 2 for point in points])
                            )
                elif dim == 1:
                    distances = []
                    for dimTag in dimTags:
                        gmsh.model.occ.synchronize()
                        pointTags = gmsh.model.getBoundary(
                            [dimTag],
                            oriented=False,
                            combined=False,
                        )
                        # Get the positions of the points:
                        points = []
                        for dimTag in pointTags:
                            boundingbox1 = gmsh.model.occ.getBoundingBox(0, dimTag[1])[
                                :3
                            ]
                            boundingbox2 = gmsh.model.occ.getBoundingBox(0, dimTag[1])[
                                3:
                            ]
                            boundingbox = list(
                                map(operator.add, boundingbox1, boundingbox2)
                            )
                            points.append(
                                list(map(operator.truediv, boundingbox, (2, 2, 2)))
                            )

                        distances.append(
                            max([point[0] ** 2 + point[1] ** 2 for point in points])
                        )

                if findInnerOnes:
                    goalDistance = min(distances)
                else:
                    goalDistance = max(distances)

                result = []
                for distance, dimTag in zip(distances, dimTags):
                    # Return all the dimTags with the hoal distance:
                    if math.isclose(distance, goalDistance, abs_tol=1e-6):
                        result.append(dimTag)

                return result

            outerCurvesDimTags = findOuterOnes(boundaryCurvesDimTags)
            outerCurvesTags = [dimTag[1] for dimTag in outerCurvesDimTags]
            curveLoopOuter = gmsh.model.occ.addCurveLoop(outerCurvesTags)

            innerCurvesDimTags = findOuterOnes(
                boundaryCurvesDimTags, findInnerOnes=True
            )
            innerCurvesTags = [dimTag[1] for dimTag in innerCurvesDimTags]
            curveLoopInner = gmsh.model.occ.addCurveLoop(innerCurvesTags)

            newSurfaceTag = gmsh.model.occ.addPlaneSurface(
                [curveLoopOuter, curveLoopInner]
            )

            gmsh.model.occ.synchronize()

            return [(2, newSurfaceTag)]
        else:
            # Create a new single surface:
            try:
                fuseResults = gmsh.model.occ.fuse(
                    [oldSurfaceDimTags[-1]],
                    oldSurfaceDimTags[0:-1],
                    removeObject=False,
                    removeTool=False,
                )
                newSurfaceDimTags = fuseResults[0]
            except:
                return oldSurfaceDimTags

            # Get the combined boundary curves:
            gmsh.model.occ.synchronize()
            boundaryCurvesDimTags = gmsh.model.getBoundary(
                newSurfaceDimTags,
                combined=True,
                oriented=False,
                recursive=False,
            )

            # Get all the boundary curves:
            allCurvesDimTags = gmsh.model.getBoundary(
                oldSurfaceDimTags,
                combined=False,
                oriented=False,
                recursive=False,
            )

            # Find internal (common) curves:
            internalCurvesDimTags = list(
                set(allCurvesDimTags) - set(boundaryCurvesDimTags)
            )

            # Remove the old surfaces:
            gmsh.model.occ.remove(oldSurfaceDimTags, recursive=False)

            # Remove the internal curves:
            gmsh.model.occ.remove(internalCurvesDimTags, recursive=False)

            gmsh.model.occ.synchronize()

            return newSurfaceDimTags

    def generate_regions(self):
        """
        Generates physical groups and the regions file. Physical groups are generated in
        GMSH, and their tags and names are saved in the regions file. FiQuS use the
        regions file to create the corresponding .pro file.

        .vi file sends the information about geometry from geometry class to mesh class.
        .regions file sends the information about the physical groups formed out of
        elementary entities from the mesh class to the solution class.

        The file extension for the regions file is custom because users should not edit
        or even see this file.

        Regions are generated in the meshing part because BREP files cannot store
        regions.
        """
        logger.info("Generating physical groups and regions file has been started.")
        start_time = timeit.default_timer()

        # Create regions instance to both generate regions file and physical groups:
        self.regions = regions()

        # ==============================================================================
        # WINDING AND CONTACT LAYER REGIONS START =========================================
        # ==============================================================================
        if not self.geo.ii.tsa:
            windingTags = [dimTag[1] for dimTag in self.dimTags[self.geo.wi.name]]
            self.regions.addEntities(
                self.geo.wi.name, windingTags, regionType.powered, entityType.vol
            )

            insulatorTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ii.name]]

            terminalDimTags = (
                self.dimTags[self.geo.ti.i.name] + self.dimTags[self.geo.ti.o.name]
            )
            terminalAndNotchSurfaces = gmsh.model.getBoundary(
                terminalDimTags, combined=False, oriented=False
            )
            transitionNotchSurfaces = gmsh.model.getBoundary(
                self.dimTags["innerTransitionNotch"]
                + self.dimTags["outerTransitionNotch"],
                combined=False,
                oriented=False,
            )

            contactLayer = []
            contactLayerBetweenTerminalsAndWinding = []
            for insulatorTag in insulatorTags:
                insulatorSurfaces = gmsh.model.getBoundary(
                    [(3, insulatorTag)], combined=False, oriented=False
                )
                itTouchesTerminals = False
                for insulatorSurface in insulatorSurfaces:
                    if (
                        insulatorSurface
                        in terminalAndNotchSurfaces + transitionNotchSurfaces
                    ):
                        contactLayerBetweenTerminalsAndWinding.append(insulatorTag)
                        itTouchesTerminals = True
                        break

                if not itTouchesTerminals:
                    contactLayer.append(insulatorTag)

            self.regions.addEntities(
                self.geo.ii.name, contactLayer, regionType.insulator, entityType.vol
            )

            self.regions.addEntities(
                "WindingAndTerminalContactLayer",
                contactLayerBetweenTerminalsAndWinding,
                regionType.insulator,
                entityType.vol,
            )
        else:
            # Calculate the number of stacks for each individual winding. Number of
            # stacks is the number of volumes per turn. It affects how the regions
            # are created because of the TSA's pro file formulation.

            # find the smallest prime number that divides NofVolumes:
            windingDimTags = self.dimTags[self.geo.wi.name + "1"]
            windingTags = [dimTag[1] for dimTag in windingDimTags]
            NofVolumes = self.geo.wi.NofVolPerTurn
            smallest_prime_divisor = 2
            while NofVolumes % smallest_prime_divisor != 0:
                smallest_prime_divisor += 1

            # the number of stacks is the region divison per turn:
            NofStacks = smallest_prime_divisor

            # the number of sets are the total number of regions for all windings and
            # contact layers:
            NofSets = 2 * NofStacks

            allInnerTerminalSurfaces = gmsh.model.getBoundary(
                self.dimTags[self.geo.ti.i.name] + self.dimTags["innerTransitionNotch"],
                combined=False,
                oriented=False,
            )
            allInnerTerminalContactLayerSurfaces = []
            for innerTerminalSurface in allInnerTerminalSurfaces:
                normal = gmsh.model.getNormal(innerTerminalSurface[1], [0.5, 0.5])
                if abs(normal[2]) < 1e-5:
                    curves = gmsh.model.getBoundary(
                        [innerTerminalSurface], combined=False, oriented=False
                    )
                    curveTags = [dimTag[1] for dimTag in curves]
                    for curveTag in curveTags:
                        curveObject = curve(curveTag, self.geo)
                        if curveObject.type is curveType.spiralArc:
                            allInnerTerminalContactLayerSurfaces.append(
                                innerTerminalSurface[1]
                            )

            finalWindingSets = []
            finalContactLayerSets = []
            for i in range(NofSets):
                finalWindingSets.append([])
                finalContactLayerSets.append([])

            for i in range(self.geo.N):
                windingDimTags = self.dimTags[self.geo.wi.name + str(i + 1)]
                windingTags = [dimTag[1] for dimTag in windingDimTags]

                NofVolumes = len(windingDimTags)

                windings = []
                for windingTag in windingTags:
                    surfaces = gmsh.model.getBoundary(
                        [(3, windingTag)], combined=False, oriented=False
                    )
                    curves = gmsh.model.getBoundary(
                        surfaces, combined=False, oriented=False
                    )
                    curveTags = list(set([dimTag[1] for dimTag in curves]))
                    for curveTag in curveTags:
                        curveObject = curve(curveTag, self.geo)
                        if curveObject.type is curveType.spiralArc:
                            windingVolumeLengthInTurns = abs(
                                curveObject.n2 - curveObject.n1
                            )
                            if windingVolumeLengthInTurns > 0.5:
                                # The arc can never be longer than half a turn.
                                windingVolumeLengthInTurns = (
                                    1 - windingVolumeLengthInTurns
                                )

                    windings.append((windingTag, windingVolumeLengthInTurns))

                windingStacks = []
                while len(windings) > 0:
                    stack = []
                    stackLength = 0
                    for windingTag, windingVolumeLengthInTurns in windings:
                        if stackLength < 1 / NofStacks - 1e-6:
                            stack.append(windingTag)
                            stackLength += windingVolumeLengthInTurns
                        else:
                            break
                    # remove all the windings that are already added to the stack:
                    windings = [
                        (windingTag, windingVolumeLengthInTurns)
                        for windingTag, windingVolumeLengthInTurns in windings
                        if windingTag not in stack
                    ]

                    # find spiral surfaces of the stack:
                    stackDimTags = [(3, windingTag) for windingTag in stack]
                    stackSurfacesDimTags = gmsh.model.getBoundary(
                        stackDimTags, combined=True, oriented=False
                    )
                    stackCurvesDimTags = gmsh.model.getBoundary(
                        stackSurfacesDimTags, combined=False, oriented=False
                    )
                    # find the curve furthest from the origin:
                    curveObjects = []
                    for curveDimTag in stackCurvesDimTags:
                        curveObject = curve(curveDimTag[1], self.geo)
                        if curveObject.type is curveType.spiralArc:
                            curveObjectDistanceFromOrigin = math.sqrt(
                                curveObject.points[0][0] ** 2
                                + curveObject.points[0][1] ** 2
                            )
                            curveObjects.append(
                                (curveObject, curveObjectDistanceFromOrigin)
                            )

                    # sort the curves based on their distance from the origin (furthest first)
                    curveObjects.sort(key=lambda x: x[1], reverse=True)

                    curveTags = [curveObject[0].tag for curveObject in curveObjects]

                    # only keep half of the curveTags:
                    furthestCurveTags = curveTags[: len(curveTags) // 2]

                    stackSpiralSurfaces = []
                    for surfaceDimTag in stackSurfacesDimTags:
                        normal = gmsh.model.getNormal(surfaceDimTag[1], [0.5, 0.5])
                        if abs(normal[2]) < 1e-5:
                            curves = gmsh.model.getBoundary(
                                [surfaceDimTag], combined=False, oriented=False
                            )
                            curveTags = [dimTag[1] for dimTag in curves]
                            for curveTag in curveTags:
                                if curveTag in furthestCurveTags:
                                    stackSpiralSurfaces.append(surfaceDimTag[1])
                                    break

                    # add inner terminal surfaces too:
                    if len(windingStacks) >= NofStacks:
                        correspondingWindingStack = windingStacks[
                            len(windingStacks) - NofStacks
                        ]
                        correspondingWindings = correspondingWindingStack[0]
                        correspondingSurfaces = gmsh.model.getBoundary(
                            [(3, windingTag) for windingTag in correspondingWindings],
                            combined=True,
                            oriented=False,
                        )
                        correspondingSurfaceTags = [
                            dimTag[1] for dimTag in correspondingSurfaces
                        ]
                        for surface in allInnerTerminalContactLayerSurfaces:
                            if surface in correspondingSurfaceTags:
                                stackSpiralSurfaces.append(surface)

                    windingStacks.append((stack, stackSpiralSurfaces))

                windingSets = []
                contactLayerSets = []
                for j in range(NofSets):
                    windingTags = [
                        windingTags for windingTags, _ in windingStacks[j::NofSets]
                    ]
                    windingTags = list(itertools.chain.from_iterable(windingTags))

                    surfaceTags = [
                        surfaceTags for _, surfaceTags in windingStacks[j::NofSets]
                    ]
                    surfaceTags = list(itertools.chain.from_iterable(surfaceTags))

                    windingSets.append(windingTags)
                    contactLayerSets.append(surfaceTags)

                # windingSets is a list with a length of NofSets.
                # finalWindingSets is also a list with a length of NofSets.
                for j, (windingSet, contactLayerSet) in enumerate(
                    zip(windingSets, contactLayerSets)
                ):
                    finalWindingSets[j].extend(windingSet)
                    finalContactLayerSets[j].extend(contactLayerSet)

            # Seperate transition layer:
            terminalAndNotchSurfaces = gmsh.model.getBoundary(
                self.dimTags[self.geo.ti.i.name]
                + self.dimTags[self.geo.ti.o.name]
                + self.dimTags["innerTransitionNotch"]
                + self.dimTags["outerTransitionNotch"],
                combined=False,
                oriented=False,
            )
            terminalAndNotchSurfaceTags = set(
                [dimTag[1] for dimTag in terminalAndNotchSurfaces]
            )

            contactLayerSets = []
            terminalWindingContactLayerSets = []
            for j in range(NofSets):
                contactLayerSets.append([])
                terminalWindingContactLayerSets.append([])

            for j in range(NofSets):
                allContactLayersInTheSet = finalContactLayerSets[j]

                insulatorList = []
                windingTerminalInsulatorList = []
                for contactLayer in allContactLayersInTheSet:
                    if contactLayer in terminalAndNotchSurfaceTags:
                        windingTerminalInsulatorList.append(contactLayer)
                    else:
                        insulatorList.append(contactLayer)

                contactLayerSets[j].extend(set(insulatorList))
                terminalWindingContactLayerSets[j].extend(set(windingTerminalInsulatorList))

            allContactLayerSurfacesForAllPancakes = []
            for j in range(NofSets):
                # Add winding volumes:
                self.regions.addEntities(
                    self.geo.wi.name + "-" + str(j + 1),
                    finalWindingSets[j],
                    regionType.powered,
                    entityType.vol,
                )

                # Add insulator surfaces:
                self.regions.addEntities(
                    self.geo.ii.name + "-" + str(j + 1),
                    contactLayerSets[j],
                    regionType.insulator,
                    entityType.surf,
                )
                allContactLayerSurfacesForAllPancakes.extend(contactLayerSets[j])

                # Add terminal and winding contact layer:
                self.regions.addEntities(
                    "WindingAndTerminalContactLayer" + "-" + str(j + 1),
                    terminalWindingContactLayerSets[j],
                    regionType.insulator,
                    entityType.surf,
                )
                allContactLayerSurfacesForAllPancakes.extend(
                    terminalWindingContactLayerSets[j]
                )

            allContactLayerSurfacesForAllPancakes = list(
                set(allContactLayerSurfacesForAllPancakes)
            )
            # Get insulator's boundary line that touches the air (required for the
            # pro file formulation):
            allContactLayerSurfacesForAllPancakesDimTags = [
                (2, surfaceTag) for surfaceTag in allContactLayerSurfacesForAllPancakes
            ]
            insulatorBoundary = gmsh.model.getBoundary(
                allContactLayerSurfacesForAllPancakesDimTags,
                combined=True,
                oriented=False,
            )
            insulatorBoundaryTags = [dimTag[1] for dimTag in insulatorBoundary]

            # Add insulator boundary lines:
            # Vertical lines should be removed from the insulator boundary because
            # they touch the terminals, not the air:
            verticalInsulatorBoundaryTags = []
            insulatorBoundaryTagsCopy = insulatorBoundaryTags.copy()
            for lineTag in insulatorBoundaryTagsCopy:
                lineObject = curve(lineTag, self.geo)
                if lineObject.type is curveType.axial:
                    verticalInsulatorBoundaryTags.append(lineTag)
                    insulatorBoundaryTags.remove(lineTag)

            # Create regions:
            self.regions.addEntities(
                self.geo.contactLayerBoundaryName,
                insulatorBoundaryTags,
                regionType.insulator,
                entityType.curve,
            )
            self.regions.addEntities(
                self.geo.contactLayerBoundaryName + "-TouchingTerminal",
                verticalInsulatorBoundaryTags,
                regionType.insulator,
                entityType.curve,
            )

        innerTransitionNotchTags = [
            dimTag[1] for dimTag in self.dimTags["innerTransitionNotch"]
        ]
        outerTransitionNotchTags = [
            dimTag[1] for dimTag in self.dimTags["outerTransitionNotch"]
        ]
        self.regions.addEntities(
            "innerTransitionNotch",
            innerTransitionNotchTags,
            regionType.powered,
            entityType.vol,
        )
        self.regions.addEntities(
            "outerTransitionNotch",
            outerTransitionNotchTags,
            regionType.powered,
            entityType.vol,
        )
        # ==============================================================================
        # WINDING AND CONTACT LAYER REGIONS ENDS =======================================
        # ==============================================================================

        # ==============================================================================
        # TERMINAL REGIONS START =======================================================
        # ==============================================================================

        innerTerminalTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ti.i.name]]
        self.regions.addEntities(
            self.geo.ti.i.name, innerTerminalTags, regionType.powered, entityType.vol_in
        )
        outerTerminalTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ti.o.name]]
        self.regions.addEntities(
            self.geo.ti.o.name,
            outerTerminalTags,
            regionType.powered,
            entityType.vol_out,
        )

        # Top and bottom terminal surfaces:
        firstTerminalDimTags = self.dimTags[self.geo.ti.firstName]
        lastTerminalDimTags = self.dimTags[self.geo.ti.lastName]

        if self.mesh.ti.structured:
            topSurfaceDimTags = []
            for i in [1, 2, 3, 4]:
                lastTerminalSurfaces = gmsh.model.getBoundary(
                    [lastTerminalDimTags[-i]], combined=False, oriented=False
                )
                topSurfaceDimTags.append(lastTerminalSurfaces[-1])
        else:
            lastTerminalSurfaces = gmsh.model.getBoundary(
                [lastTerminalDimTags[-1]], combined=False, oriented=False
            )
            topSurfaceDimTags = [lastTerminalSurfaces[-1]]
        topSurfaceTags = [dimTag[1] for dimTag in topSurfaceDimTags]

        if self.mesh.ti.structured:
            bottomSurfaceDimTags = []
            for i in [1, 2, 3, 4]:
                firstTerminalSurfaces = gmsh.model.getBoundary(
                    [firstTerminalDimTags[-i]], combined=False, oriented=False
                )
                bottomSurfaceDimTags.append(firstTerminalSurfaces[-1])
        else:
            firstTerminalSurfaces = gmsh.model.getBoundary(
                [firstTerminalDimTags[-1]], combined=False, oriented=False
            )
            bottomSurfaceDimTags = [firstTerminalSurfaces[-1]]
        bottomSurfaceTags = [dimTag[1] for dimTag in bottomSurfaceDimTags]

        self.regions.addEntities(
            "TopSurface",
            topSurfaceTags,
            regionType.powered,
            entityType.surf_out,
        )
        self.regions.addEntities(
            "BottomSurface",
            bottomSurfaceTags,
            regionType.powered,
            entityType.surf_in,
        )

        # if self.geo.ii.tsa:
        #     outerTerminalSurfaces = gmsh.model.getBoundary(
        #         self.dimTags[self.geo.ti.o.name], combined=True, oriented=False
        #     )
        #     outerTerminalSurfaces = [dimTag[1] for dimTag in outerTerminalSurfaces]
        #     innerTerminalSurfaces = gmsh.model.getBoundary(
        #         self.dimTags[self.geo.ti.i.name], combined=True, oriented=False
        #     )
        #     innerTerminalSurfaces = [dimTag[1] for dimTag in innerTerminalSurfaces]
        #     windingSurfaces = gmsh.model.getBoundary(
        #         self.dimTags[self.geo.wi.name] + self.dimTags[self.geo.ii.name],
        #         combined=True,
        #         oriented=False,
        #     )
        #     windingSurfaces = [dimTag[1] for dimTag in windingSurfaces]

        #     windingAndOuterTerminalCommonSurfaces = list(
        #         set(windingSurfaces).intersection(set(outerTerminalSurfaces))
        #     )
        #     windingAndInnerTerminalCommonSurfaces = list(
        #         set(windingSurfaces).intersection(set(innerTerminalSurfaces))
        #     )

        #     self.regions.addEntities(
        #         "WindingAndTerminalContactLayer",
        #         windingAndOuterTerminalCommonSurfaces
        #         + windingAndInnerTerminalCommonSurfaces,
        #         regionType.insulator,
        #         entityType.surf,
        #     )

        # ==============================================================================
        # TERMINAL REGIONS ENDS ========================================================
        # ==============================================================================

        # ==============================================================================
        # AIR AND AIR SHELL REGIONS STARTS =============================================
        # ==============================================================================
        airTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ai.name]]
        self.regions.addEntities(
            self.geo.ai.name, airTags, regionType.air, entityType.vol
        )

        # Create a region with two points on air to be used in the pro file formulation:
        # To those points, Phi=0 boundary condition will be applied to set the gauge.
        outerAirSurfaces = gmsh.model.getBoundary(
            self.dimTags[self.geo.ai.name + "-OuterTube"], combined=True, oriented=False
        )
        outerAirSurface = outerAirSurfaces[-1]
        outerAirCurves = gmsh.model.getBoundary(
            [outerAirSurface], combined=True, oriented=False
        )
        outerAirCurve = outerAirCurves[-1]
        outerAirPoint = gmsh.model.getBoundary(
            [outerAirCurve], combined=False, oriented=False
        )
        outerAirPointTag = outerAirPoint[0][1]
        self.regions.addEntities(
            "OuterAirPoint",
            [outerAirPointTag],
            regionType.air,
            entityType.point,
        )

        innerAirSurfaces = gmsh.model.getBoundary(
            self.dimTags[self.geo.ai.name + "-InnerCylinder"],
            combined=True,
            oriented=False,
        )
        innerAirSurface = innerAirSurfaces[0]
        innerAirCurves = gmsh.model.getBoundary(
            [innerAirSurface], combined=True, oriented=False
        )
        innerAirCurve = innerAirCurves[-1]
        innerAirPoint = gmsh.model.getBoundary(
            [innerAirCurve], combined=False, oriented=False
        )
        innerAirPointTag = innerAirPoint[0][1]
        self.regions.addEntities(
            "InnerAirPoint",
            [innerAirPointTag],
            regionType.air,
            entityType.point,
        )

        if self.geo.ai.shellTransformation:
            if self.geo.ai.type == "cylinder":
                airShellTags = [
                    dimTag[1] for dimTag in self.dimTags[self.geo.ai.shellVolumeName]
                ]
                self.regions.addEntities(
                    self.geo.ai.shellVolumeName,
                    airShellTags,
                    regionType.air_far_field,
                    entityType.vol,
                )
            elif self.geo.ai.type == "cuboid":
                airShell1Tags = [
                    dimTag[1]
                    for dimTag in self.dimTags[self.geo.ai.shellVolumeName + "-Part1"]
                    + self.dimTags[self.geo.ai.shellVolumeName + "-Part3"]
                ]
                airShell2Tags = [
                    dimTag[1]
                    for dimTag in self.dimTags[self.geo.ai.shellVolumeName + "-Part2"]
                    + self.dimTags[self.geo.ai.shellVolumeName + "-Part4"]
                ]
                self.regions.addEntities(
                    self.geo.ai.shellVolumeName + "-PartX",
                    airShell1Tags,
                    regionType.air_far_field,
                    entityType.vol,
                )
                self.regions.addEntities(
                    self.geo.ai.shellVolumeName + "-PartY",
                    airShell2Tags,
                    regionType.air_far_field,
                    entityType.vol,
                )
        # ==============================================================================
        # AIR AND AIR SHELL REGIONS ENDS ===============================================
        # ==============================================================================

        # ==============================================================================
        # CUTS STARTS ==================================================================
        # ==============================================================================
        if self.geo.ai.cutName in self.dimTags:
            cutTags = [dimTag[1] for dimTag in self.dimTags[self.geo.ai.cutName]]
            self.regions.addEntities(
                self.geo.ai.cutName, cutTags, regionType.air, entityType.cochain
            )

        if "CutsForPerfectInsulation" in self.dimTags:
            cutTags = [dimTag[1] for dimTag in self.dimTags["CutsForPerfectInsulation"]]
            self.regions.addEntities(
                "CutsForPerfectInsulation", cutTags, regionType.air, entityType.cochain
            )

        if "CutsBetweenPancakes" in self.dimTags:
            cutTags = [dimTag[1] for dimTag in self.dimTags["CutsBetweenPancakes"]]
            self.regions.addEntities(
                "CutsBetweenPancakes", cutTags, regionType.air, entityType.cochain
            )
        # ==============================================================================
        # CUTS ENDS ====================================================================
        # ==============================================================================

        # ==============================================================================
        # PANCAKE BOUNDARY SURFACE STARTS ==============================================
        # ==============================================================================
        # Pancake3D Boundary Surface:
        allPancakeVolumes = (
            self.dimTags[self.geo.wi.name]
            + self.dimTags[self.geo.ti.i.name]
            + self.dimTags[self.geo.ti.o.name]
            + self.dimTags[self.geo.ii.name]
            + self.dimTags["innerTransitionNotch"]
            + self.dimTags["outerTransitionNotch"]
        )
        Pancake3DAllBoundary = gmsh.model.getBoundary(
            allPancakeVolumes, combined=True, oriented=False
        )
        Pancake3DBoundaryDimTags = list(
            set(Pancake3DAllBoundary)
            - set(topSurfaceDimTags)
            - set(bottomSurfaceDimTags)
        )
        pancake3DBoundaryTags = [dimTag[1] for dimTag in Pancake3DBoundaryDimTags]
        self.regions.addEntities(
            self.geo.pancakeBoundaryName,
            pancake3DBoundaryTags,
            regionType.powered,
            entityType.surf,
        )

        if not self.geo.ii.tsa:
            # Pancake3D Boundary Surface with only winding and terminals:
            allPancakeVolumes = (
                self.dimTags[self.geo.wi.name]
                + self.dimTags[self.geo.ti.i.name]
                + self.dimTags[self.geo.ti.o.name]
                + self.dimTags["innerTransitionNotch"]
                + self.dimTags["outerTransitionNotch"]
                + [(3, tag) for tag in contactLayerBetweenTerminalsAndWinding]
            )
            Pancake3DAllBoundary = gmsh.model.getBoundary(
                allPancakeVolumes, combined=True, oriented=False
            )
            Pancake3DBoundaryDimTags = list(
                set(Pancake3DAllBoundary)
                - set(topSurfaceDimTags)
                - set(bottomSurfaceDimTags)
            )
            pancake3DBoundaryTags = [dimTag[1] for dimTag in Pancake3DBoundaryDimTags]
            self.regions.addEntities(
                self.geo.pancakeBoundaryName + "-OnlyWindingAndTerminals",
                pancake3DBoundaryTags,
                regionType.powered,
                entityType.surf,
            )

        # ==============================================================================
        # PANCAKE BOUNDARY SURFACE ENDS ================================================
        # ==============================================================================

        # Generate regions file:
        self.regions.generateRegionsFile(self.regions_file)
        self.rm = FilesAndFolders.read_data_from_yaml(self.regions_file, RegionsModel)

        logger.info(
            "Generating physical groups and regions file has been finished in"
            f" {timeit.default_timer() - start_time:.2f} s."
        )

    def generate_mesh_file(self):
        """
        Saves mesh file to disk.


        """
        logger.info(
            f"Generating Pancake3D mesh file ({self.mesh_file}) has been started."
        )
        start_time = timeit.default_timer()

        gmsh.write(self.mesh_file)

        logger.info(
            f"Generating Pancake3D mesh file ({self.mesh_file}) has been finished"
            f" in {timeit.default_timer() - start_time:.2f} s."
        )

        if self.mesh_gui:
            gmsh.option.setNumber("Geometry.Volumes", 0)
            gmsh.option.setNumber("Geometry.Surfaces", 0)
            gmsh.option.setNumber("Geometry.Curves", 0)
            gmsh.option.setNumber("Geometry.Points", 0)
            self.gu.launch_interactive_GUI()
        else:
            gmsh.clear()
            gmsh.finalize()

    def load_mesh(self):
        """
        Loads mesh from .msh file.


        """
        logger.info("Loading Pancake3D mesh has been started.")
        start_time = timeit.default_timer()

        previousGeo = FilesAndFolders.read_data_from_yaml(
            self.geometry_data_file, Pancake3DGeometry
        )
        previousMesh = FilesAndFolders.read_data_from_yaml(
            self.mesh_data_file, Pancake3DMesh
        )

        if previousGeo.dict() != self.geo.dict():
            raise ValueError(
                "Geometry data has been changed. Please regenerate the geometry or load"
                " the previous geometry data."
            )
        elif previousMesh.dict() != self.mesh.dict():
            raise ValueError(
                "Mesh data has been changed. Please regenerate the mesh or load the"
                " previous mesh data."
            )

        gmsh.clear()
        gmsh.open(self.mesh_file)

        logger.info(
            "Loading Pancake3D mesh has been finished in"
            f" {timeit.default_timer() - start_time:.2f} s."
        )

fuse_common_surfaces_of_two_volumes(volume1DimTags, volume2DimTags, fuseOtherSurfaces=False, surfacesArePlane=False) staticmethod

Fuses common surfaces of two volumes. Volumes are given as a list of dimTags, but they are assumed to form a single volume, and this function fuses those multiple volumes into a single volume as well. If fuseOtherSurfaces is set to True, it tries to fuse surfaces that only belong to one volume too; however, that feature is not used in Pancake3D currently.

Parameters:

Name Type Description Default
volume1DimTags list[tuple[int, int]]

dimTags of the first volume

required
volume2DimTags list[tuple[int, int]]

dimTags of the second volume

required
fuseOtherSurfaces bool, optional

if True, fuses the surfaces that only belong to one volume

False
surfacesArePlane bool, optional

if True, fused surfaces are assumed to be plane, and fusion is performed accordingly

False

Returns:

Type Description
tuple[tuple[int, int], tuple[int, int]]

new volumes dimTags

Source code in fiqus/mesh_generators/MeshPancake3D.py
@staticmethod
def fuse_common_surfaces_of_two_volumes(
    volume1DimTags, volume2DimTags, fuseOtherSurfaces=False, surfacesArePlane=False
):
    """
    Fuses common surfaces of two volumes. Volumes are given as a list of dimTags,
    but they are assumed to form a single volume, and this function fuses those
    multiple volumes into a single volume as well. If fuseOtherSurfaces is set to
    True, it tries to fuse surfaces that only belong to one volume too; however,
    that feature is not used in Pancake3D currently.

    :param volume1DimTags: dimTags of the first volume
    :type volume1DimTags: list[tuple[int, int]]
    :param volume2DimTags: dimTags of the second volume
    :type volume2DimTags: list[tuple[int, int]]
    :param fuseOtherSurfaces: if True, fuses the surfaces that only belong to one
        volume
    :type fuseOtherSurfaces: bool, optional
    :param surfacesArePlane: if True, fused surfaces are assumed to be plane, and
        fusion is performed accordingly
    :type surfacesArePlane: bool, optional
    :return: new volumes dimTags
    :rtype: tuple[tuple[int, int], tuple[int, int]]
    """
    vol1BoundarySurfacesDimTags = gmsh.model.getBoundary(
        volume1DimTags,
        combined=True,
        oriented=False,
        recursive=False,
    )

    vol2BoundarySurfacesDimTags = gmsh.model.getBoundary(
        volume2DimTags,
        combined=True,
        oriented=False,
        recursive=False,
    )

    # Remove the old volumes:
    gmsh.model.occ.remove(volume1DimTags + volume2DimTags, recursive=False)

    # Find common surfaces:
    commonSurfacesDimTags = list(
        set(vol2BoundarySurfacesDimTags).intersection(
            set(vol1BoundarySurfacesDimTags)
        )
    )

    # Fuse common surfaces:
    fusedCommonSurfaceDimTags = Mesh.fuse_surfaces(
        commonSurfacesDimTags, surfacesArePlane=surfacesArePlane
    )

    # Create the new volumes:
    for commonSurfaceDimTag in commonSurfacesDimTags:
        vol1BoundarySurfacesDimTags.remove(commonSurfaceDimTag)
        vol2BoundarySurfacesDimTags.remove(commonSurfaceDimTag)

    vol1BoundarySurfacesDimTags.extend(fusedCommonSurfaceDimTags)
    vol1BoundarySurfaceTags = [dimTag[1] for dimTag in vol1BoundarySurfacesDimTags]
    vol2BoundarySurfacesDimTags.extend(fusedCommonSurfaceDimTags)
    vol2BoundarySurfaceTags = [dimTag[1] for dimTag in vol2BoundarySurfacesDimTags]

    vol1SurfaceLoop = gmsh.model.occ.addSurfaceLoop(
        vol1BoundarySurfaceTags, sewing=True
    )
    vol1NewVolumeDimTag = (3, gmsh.model.occ.addVolume([vol1SurfaceLoop]))

    vol2SurfaceLoop = gmsh.model.occ.addSurfaceLoop(
        vol2BoundarySurfaceTags, sewing=True
    )
    vol2NewVolumeDimTag = (
        3,
        gmsh.model.occ.addVolume([vol2SurfaceLoop]),
    )

    gmsh.model.occ.synchronize()

    if fuseOtherSurfaces:
        vol1NewVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
            vol1NewVolumeDimTag, surfacesArePlane=surfacesArePlane
        )
        vol2NewVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
            vol2NewVolumeDimTag, surfacesArePlane=surfacesArePlane
        )

    return vol1NewVolumeDimTag, vol2NewVolumeDimTag

fuse_possible_surfaces_of_a_volume(volumeDimTag, surfacesArePlane=False) staticmethod

Fuses surfaces that only belong to the volumeDimTag.

Parameters:

Name Type Description Default
volumeDimTag tuple[int, int]

dimTag of the volume

required
surfacesArePlane bool, optional

if True, fused surfaces are assumed to be plane, and fusion is performed accordingly

False

Returns:

Type Description
tuple[int, int]

new volume dimTag

Source code in fiqus/mesh_generators/MeshPancake3D.py
@staticmethod
def fuse_possible_surfaces_of_a_volume(volumeDimTag, surfacesArePlane=False):
    """
    Fuses surfaces that only belong to the volumeDimTag.

    :param volumeDimTag: dimTag of the volume
    :type volumeDimTag: tuple[int, int]
    :param surfacesArePlane: if True, fused surfaces are assumed to be plane, and
        fusion is performed accordingly
    :type surfacesArePlane: bool, optional
    :return: new volume dimTag
    :rtype: tuple[int, int]
    """
    boundarySurfacesDimTags = gmsh.model.getBoundary(
        [volumeDimTag],
        combined=True,
        oriented=False,
        recursive=False,
    )
    boundarSurfacesTags = [dimTag[1] for dimTag in boundarySurfacesDimTags]

    # Combine surfaces that only belong to the volume:
    toBeFusedSurfacesDimTags = []
    surfacesNormals = []
    for surfaceDimTag in boundarySurfacesDimTags:
        upward, _ = gmsh.model.getAdjacencies(surfaceDimTag[0], surfaceDimTag[1])

        if len(list(upward)) == 1:
            toBeFusedSurfacesDimTags.append(surfaceDimTag)
            # Get the normal of the surface:
            surfacesNormals.append(
                list(gmsh.model.getNormal(surfaceDimTag[1], [0.5, 0.5]))
            )

    # Remove the old volume (it is not required anymore):
    gmsh.model.occ.remove([volumeDimTag], recursive=False)
    gmsh.model.occ.synchronize()

    # Categorize surfaces based on their normals so that they can be combined
    # correctly. Without these, perpendicular surfaces will cause problems.

    # Define a threshold to determine if two surface normals are similar or not
    threshold = 1e-6

    # Initialize an empty list to store the sets of surfaces
    setsOfSurfaces = []

    # Calculate the Euclidean distance between each pair of objects
    for i in range(len(toBeFusedSurfacesDimTags)):
        surfaceDimTag = toBeFusedSurfacesDimTags[i]
        surfaceTouchingVolumeTags, _ = list(
            gmsh.model.getAdjacencies(surfaceDimTag[0], surfaceDimTag[1])
        )
        surfaceNormal = surfacesNormals[i]
        assignedToASet = False

        for surfaceSet in setsOfSurfaces:
            representativeSurfaceDimTag = surfaceSet[0]
            representativeSurfaceTouchingVolumeTags, _ = list(
                gmsh.model.getAdjacencies(
                    representativeSurfaceDimTag[0],
                    representativeSurfaceDimTag[1],
                )
            )
            representativeNormal = list(
                gmsh.model.getNormal(representativeSurfaceDimTag[1], [0.5, 0.5])
            )

            # Calculate the difference between surfaceNormal and
            # representativeNormal:
            difference = math.sqrt(
                sum(
                    (x - y) ** 2
                    for x, y in zip(surfaceNormal, representativeNormal)
                )
            )

            # Check if the distance is below the threshold
            if difference < threshold and set(surfaceTouchingVolumeTags) == set(
                representativeSurfaceTouchingVolumeTags
            ):
                # Add the object to an existing category
                surfaceSet.append(surfaceDimTag)
                assignedToASet = True
                break

        if not assignedToASet:
            # Create a new category with the current object if none of the
            # existing sets match
            setsOfSurfaces.append([surfaceDimTag])

    for surfaceSet in setsOfSurfaces:
        if len(surfaceSet) > 1:
            oldSurfaceDimTags = surfaceSet
            newSurfaceDimTags = Mesh.fuse_surfaces(
                oldSurfaceDimTags, surfacesArePlane=surfacesArePlane
            )
            newSurfaceTags = [dimTag[1] for dimTag in newSurfaceDimTags]

            oldSurfaceTags = [dimTag[1] for dimTag in oldSurfaceDimTags]
            boundarSurfacesTags = [
                tag for tag in boundarSurfacesTags if tag not in oldSurfaceTags
            ]
            boundarSurfacesTags.extend(newSurfaceTags)

    # Create a new single volume:
    surfaceLoop = gmsh.model.occ.addSurfaceLoop(boundarSurfacesTags, sewing=True)
    newVolumeTag = gmsh.model.occ.addVolume([surfaceLoop])
    gmsh.model.occ.synchronize()

    return (3, newVolumeTag)

fuse_surfaces(surfaceDimTags, surfacesArePlane=False, categorizeSurfaces=False) staticmethod

Fuses all the surfaces in a given list of surface dimTags, removes the old surfaces, and returns the new dimTags. If surfacesArePlane is True, the surfaces are assumed to be plane, and fusing will be done without gmsh.model.occ.fuse method, which is faster.

Parameters:

Name Type Description Default
surfaceDimTags list[tuple[int, int]]

dimTags of the surfaces

required
surfacesArePlane bool, optional

if True, surfaces are assumed to be plane

False

Returns:

Type Description
list[tuple[int, int]]

newly created surface dimTags

Source code in fiqus/mesh_generators/MeshPancake3D.py
@staticmethod
def fuse_surfaces(surfaceDimTags, surfacesArePlane=False, categorizeSurfaces=False):
    """
    Fuses all the surfaces in a given list of surface dimTags, removes the old
    surfaces, and returns the new dimTags. If surfacesArePlane is True, the surfaces
    are assumed to be plane, and fusing will be done without gmsh.model.occ.fuse
    method, which is faster.

    :param surfaceDimTags: dimTags of the surfaces
    :type surfaceDimTags: list[tuple[int, int]]
    :param surfacesArePlane: if True, surfaces are assumed to be plane
    :type surfacesArePlane: bool, optional
    :return: newly created surface dimTags
    :rtype: list[tuple[int, int]]
    """
    oldSurfaceDimTags = surfaceDimTags

    if surfacesArePlane:
        # Get the combined boundary curves:
        boundaryCurvesDimTags = gmsh.model.getBoundary(
            oldSurfaceDimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )

        # Get all the boundary curves:
        allCurvesDimTags = gmsh.model.getBoundary(
            oldSurfaceDimTags,
            combined=False,
            oriented=False,
            recursive=False,
        )

        # Find internal (common) curves:
        internalCurvesDimTags = list(
            set(allCurvesDimTags) - set(boundaryCurvesDimTags)
        )

        # Remove the old surfaces:
        gmsh.model.occ.remove(oldSurfaceDimTags, recursive=False)

        # Remove the internal curves:
        gmsh.model.occ.remove(internalCurvesDimTags, recursive=True)

        # Create a new single surface:
        def findOuterOnes(dimTags, findInnerOnes=False):
            """
            Finds the outermost surface/curve/point in a list of dimTags. The outermost means
            the furthest from the origin.
            """
            dim = dimTags[0][0]

            if dim == 2:
                distances = []
                for dimTag in dimTags:
                    _, curves = gmsh.model.occ.getCurveLoops(dimTag[1])
                    for curve in curves:
                        curve = list(curve)
                        gmsh.model.occ.synchronize()
                        pointTags = gmsh.model.getBoundary(
                            [(1, curveTag) for curveTag in curve],
                            oriented=False,
                            combined=False,
                        )
                        # Get the positions of the points:
                        points = []
                        for dimTag in pointTags:
                            boundingbox1 = gmsh.model.occ.getBoundingBox(
                                0, dimTag[1]
                            )[:3]
                            boundingbox2 = gmsh.model.occ.getBoundingBox(
                                0, dimTag[1]
                            )[3:]
                            boundingbox = list(
                                map(operator.add, boundingbox1, boundingbox2)
                            )
                            points.append(
                                list(map(operator.truediv, boundingbox, (2, 2, 2)))
                            )

                        distances.append(
                            max([point[0] ** 2 + point[1] ** 2 for point in points])
                        )
            elif dim == 1:
                distances = []
                for dimTag in dimTags:
                    gmsh.model.occ.synchronize()
                    pointTags = gmsh.model.getBoundary(
                        [dimTag],
                        oriented=False,
                        combined=False,
                    )
                    # Get the positions of the points:
                    points = []
                    for dimTag in pointTags:
                        boundingbox1 = gmsh.model.occ.getBoundingBox(0, dimTag[1])[
                            :3
                        ]
                        boundingbox2 = gmsh.model.occ.getBoundingBox(0, dimTag[1])[
                            3:
                        ]
                        boundingbox = list(
                            map(operator.add, boundingbox1, boundingbox2)
                        )
                        points.append(
                            list(map(operator.truediv, boundingbox, (2, 2, 2)))
                        )

                    distances.append(
                        max([point[0] ** 2 + point[1] ** 2 for point in points])
                    )

            if findInnerOnes:
                goalDistance = min(distances)
            else:
                goalDistance = max(distances)

            result = []
            for distance, dimTag in zip(distances, dimTags):
                # Return all the dimTags with the hoal distance:
                if math.isclose(distance, goalDistance, abs_tol=1e-6):
                    result.append(dimTag)

            return result

        outerCurvesDimTags = findOuterOnes(boundaryCurvesDimTags)
        outerCurvesTags = [dimTag[1] for dimTag in outerCurvesDimTags]
        curveLoopOuter = gmsh.model.occ.addCurveLoop(outerCurvesTags)

        innerCurvesDimTags = findOuterOnes(
            boundaryCurvesDimTags, findInnerOnes=True
        )
        innerCurvesTags = [dimTag[1] for dimTag in innerCurvesDimTags]
        curveLoopInner = gmsh.model.occ.addCurveLoop(innerCurvesTags)

        newSurfaceTag = gmsh.model.occ.addPlaneSurface(
            [curveLoopOuter, curveLoopInner]
        )

        gmsh.model.occ.synchronize()

        return [(2, newSurfaceTag)]
    else:
        # Create a new single surface:
        try:
            fuseResults = gmsh.model.occ.fuse(
                [oldSurfaceDimTags[-1]],
                oldSurfaceDimTags[0:-1],
                removeObject=False,
                removeTool=False,
            )
            newSurfaceDimTags = fuseResults[0]
        except:
            return oldSurfaceDimTags

        # Get the combined boundary curves:
        gmsh.model.occ.synchronize()
        boundaryCurvesDimTags = gmsh.model.getBoundary(
            newSurfaceDimTags,
            combined=True,
            oriented=False,
            recursive=False,
        )

        # Get all the boundary curves:
        allCurvesDimTags = gmsh.model.getBoundary(
            oldSurfaceDimTags,
            combined=False,
            oriented=False,
            recursive=False,
        )

        # Find internal (common) curves:
        internalCurvesDimTags = list(
            set(allCurvesDimTags) - set(boundaryCurvesDimTags)
        )

        # Remove the old surfaces:
        gmsh.model.occ.remove(oldSurfaceDimTags, recursive=False)

        # Remove the internal curves:
        gmsh.model.occ.remove(internalCurvesDimTags, recursive=False)

        gmsh.model.occ.synchronize()

        return newSurfaceDimTags

fuse_volumes(volumeDimTags, fuseSurfaces=True, fusedSurfacesArePlane=False) staticmethod

Fuses all the volumes in a given list of volume dimTags, removes old volumes, and returns the new volume dimTag. Also, if compundSurfacces is True, it fuses the surfaces that only belong to the volume. fusedSurfacesArePlane can be used to change the behavior of the fuse_surfaces method.

Parameters:

Name Type Description Default
volumeDimTags list[tuple[int, int]]

dimTags of the volumes

required
fuseSurfaces bool, optional

if True, fuses the surfaces that only belong to the volume

True
fusedSurfacesArePlane

if True, fused surfaces are assumed to be plane, and fusion is performed accordingly

False

Returns:

Type Description
tuple[int, int]

new volume's dimTag

Source code in fiqus/mesh_generators/MeshPancake3D.py
@staticmethod
def fuse_volumes(volumeDimTags, fuseSurfaces=True, fusedSurfacesArePlane=False):
    """
    Fuses all the volumes in a given list of volume dimTags, removes old volumes,
    and returns the new volume dimTag. Also, if compundSurfacces is True, it fuses
    the surfaces that only belong to the volume. fusedSurfacesArePlane can be
    used to change the behavior of the fuse_surfaces method.

    :param volumeDimTags: dimTags of the volumes
    :type volumeDimTags: list[tuple[int, int]]
    :param fuseSurfaces: if True, fuses the surfaces that only belong to the
        volume
    :type fuseSurfaces: bool, optional
    :param fusedSurfacesArePlane: if True, fused surfaces are assumed to be
        plane, and fusion is performed accordingly
    :return: new volume's dimTag
    :rtype: tuple[int, int]
    """

    # Get the combined boundary surfaces:
    boundarySurfacesDimTags = gmsh.model.getBoundary(
        volumeDimTags,
        combined=True,
        oriented=False,
        recursive=False,
    )
    boundarSurfacesTags = [dimTag[1] for dimTag in boundarySurfacesDimTags]

    # Get all the boundary surfaces:
    allBoundarySurfacesDimTags = gmsh.model.getBoundary(
        volumeDimTags,
        combined=False,
        oriented=False,
        recursive=False,
    )

    # Find internal (common) surfaces:
    internalSurfacesDimTags = list(
        set(allBoundarySurfacesDimTags) - set(boundarySurfacesDimTags)
    )

    # Get the combined boundary lines:
    boundaryLinesDimTags = gmsh.model.getBoundary(
        allBoundarySurfacesDimTags,
        combined=True,
        oriented=False,
        recursive=False,
    )
    boundarLinesTags = [dimTag[1] for dimTag in boundaryLinesDimTags]

    # Get all the boundary lines:
    allBoundaryLinesDimTags = gmsh.model.getBoundary(
        allBoundarySurfacesDimTags,
        combined=False,
        oriented=False,
        recursive=False,
    )

    # Find internal (common) lines:
    internalLinesDimTags = list(
        set(allBoundaryLinesDimTags) - set(boundarLinesTags)
    )

    # Remove the old volumes:
    removedVolumeDimTags = volumeDimTags
    gmsh.model.occ.remove(removedVolumeDimTags, recursive=False)

    # Remove the internal surfaces:
    gmsh.model.occ.remove(internalSurfacesDimTags, recursive=False)

    # Remove the internal lines:
    gmsh.model.occ.remove(internalLinesDimTags, recursive=False)

    # Create a new single volume (even thought we don't use the new volume tag
    # directly, it is required for finding the surfaces that only belong to the
    # volume):
    surfaceLoop = gmsh.model.occ.addSurfaceLoop(boundarSurfacesTags, sewing=True)
    newVolumeTag = gmsh.model.occ.addVolume([surfaceLoop])
    newVolumeDimTag = (3, newVolumeTag)
    gmsh.model.occ.synchronize()

    if fuseSurfaces:
        newVolumeDimTag = Mesh.fuse_possible_surfaces_of_a_volume(
            (3, newVolumeTag), surfacesArePlane=fusedSurfacesArePlane
        )

    return newVolumeDimTag

generate_mesh()

Sets the mesh settings and generates the mesh.

Source code in fiqus/mesh_generators/MeshPancake3D.py
 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
def generate_mesh(self):
    """
    Sets the mesh settings and generates the mesh.


    """
    logger.info("Generating Pancake3D mesh has been started.")

    start_time = timeit.default_timer()

    # =============================================================================
    # MESHING WINDING AND CONTACT LAYER STARTS =======================================
    # =============================================================================
    allWindingAndCLSurfaceTags = []
    allWindingAndCLLineTags = []
    for i in range(self.geo.N):
        # Get the volume tags:
        windingVolumeDimTags = self.dimTags[self.geo.wi.name + str(i + 1)]
        windingVolumeTags = [dimTag[1] for dimTag in windingVolumeDimTags]

        contactLayerVolumeDimTags = self.dimTags[self.geo.ii.name + str(i + 1)]
        contactLayerVolumeTags = [dimTag[1] for dimTag in contactLayerVolumeDimTags]

        # Get the surface and line tags:
        windingSurfaceTags, windingLineTags = self.get_boundaries(
            windingVolumeDimTags, returnTags=True
        )
        allWindingAndCLSurfaceTags.extend(windingSurfaceTags)
        allWindingAndCLLineTags.extend(windingLineTags)
        contactLayerSurfaceTags, contactLayerLineTags = self.get_boundaries(
            contactLayerVolumeDimTags, returnTags=True
        )
        allWindingAndCLSurfaceTags.extend(contactLayerSurfaceTags)
        allWindingAndCLLineTags.extend(contactLayerLineTags)

        self.structure_mesh(
            windingVolumeTags,
            windingSurfaceTags,
            windingLineTags,
            contactLayerVolumeTags,
            contactLayerSurfaceTags,
            contactLayerLineTags,
            meshSettingIndex=i,
        )

    notchVolumesDimTags = (
        self.dimTags["innerTransitionNotch"] + self.dimTags["outerTransitionNotch"]
    )
    notchVolumeTags = [dimTag[1] for dimTag in notchVolumesDimTags]

    notchSurfaceTags, notchLineTags = self.get_boundaries(
        notchVolumesDimTags, returnTags=True
    )

    for lineTag in notchLineTags:
        if lineTag not in allWindingAndCLLineTags:
            gmsh.model.mesh.setTransfiniteCurve(lineTag, 1)

    recombine = self.mesh.wi.elementType[0] in ["hexahedron", "prism"]
    for surfaceTag in notchSurfaceTags:
        if surfaceTag not in allWindingAndCLSurfaceTags:
            gmsh.model.mesh.setTransfiniteSurface(surfaceTag)
            if recombine:
                normal = gmsh.model.getNormal(surfaceTag, [0.5, 0.5])
                if abs(normal[2]) > 1e-4:
                    pass
                else:
                    gmsh.model.mesh.setRecombine(2, surfaceTag)


    for volumeTag in notchVolumeTags:
        gmsh.model.mesh.setTransfiniteVolume(volumeTag)

    # =============================================================================
    # MESHING WINDING AND CONTACT LAYER ENDS =========================================
    # =============================================================================

    # =============================================================================
    # MESHING AIR STARTS ==========================================================
    # =============================================================================
    # Winding and contact layer extrusions of the air:
    # Get the volume tags:
    airTopWindingExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-TopPancakeWindingExtursion"
    ]

    airTopContactLayerExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-TopPancakeContactLayerExtursion"
    ]

    airTopTerminalsExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-TopTerminalsExtrusion"
    ]

    airBottomWindingExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-BottomPancakeWindingExtursion"
    ]

    airBottomContactLayerExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-BottomPancakeContactLayerExtursion"
    ]

    airBottomTerminalsExtrusionVolumeDimTags = self.dimTags[
        self.geo.ai.name + "-BottomTerminalsExtrusion"
    ]

    removedAirVolumeDimTags = []
    newAirVolumeDimTags = []
    if self.mesh.ai.structured:
        # Then it means air type is cuboid!
        airTopWindingExtrusionVolumeTags = [
            dimTag[1] for dimTag in airTopWindingExtrusionVolumeDimTags
        ]
        airTopContactLayerExtrusionVolumeTags = [
            dimTag[1] for dimTag in airTopContactLayerExtrusionVolumeDimTags
        ]
        airBottomWindingExtrusionVolumeTags = [
            dimTag[1] for dimTag in airBottomWindingExtrusionVolumeDimTags
        ]
        airBottomContactLayerExtrusionVolumeTags = [
            dimTag[1] for dimTag in airBottomContactLayerExtrusionVolumeDimTags
        ]

        # Calcualte axial number of elements for air:
        axialElementsPerLengthForWinding = min(self.mesh.wi.axne) / self.geo.wi.h
        axneForAir = round(
            axialElementsPerLengthForWinding * self.geo.ai.margin + 1e-6
        )

        # Get the surface and line tags:
        (
            airTopWindingExtrusionSurfaceTags,
            airTopWindingExtrusionLineTags,
        ) = self.get_boundaries(
            airTopWindingExtrusionVolumeDimTags, returnTags=True
        )
        (
            airTopContactLayerExtrusionSurfaceTags,
            airTopContactLayerExtrusionLineTags,
        ) = self.get_boundaries(
            airTopContactLayerExtrusionVolumeDimTags, returnTags=True
        )

        self.structure_mesh(
            airTopWindingExtrusionVolumeTags,
            airTopWindingExtrusionSurfaceTags,
            airTopWindingExtrusionLineTags,
            airTopContactLayerExtrusionVolumeTags,
            airTopContactLayerExtrusionSurfaceTags,
            airTopContactLayerExtrusionLineTags,
            meshSettingIndex=self.geo.N - 1,  # The last pancake coil
            axialNumberOfElements=axneForAir,
            bumpCoefficient=1,
        )

        # Get the surface and line tags:
        (
            airBottomWindingExtrusionSurfaceTags,
            airBottomWindingExtrusionLineTags,
        ) = self.get_boundaries(
            airBottomWindingExtrusionVolumeDimTags, returnTags=True
        )
        (
            airBottomContactLayerExtrusionSurfaceTags,
            airBottomContactLayerExtrusionLineTags,
        ) = self.get_boundaries(
            airBottomContactLayerExtrusionVolumeDimTags, returnTags=True
        )

        self.structure_mesh(
            airBottomWindingExtrusionVolumeTags,
            airBottomWindingExtrusionSurfaceTags,
            airBottomWindingExtrusionLineTags,
            airBottomContactLayerExtrusionVolumeTags,
            airBottomContactLayerExtrusionSurfaceTags,
            airBottomContactLayerExtrusionLineTags,
            meshSettingIndex=0,  # The first pancake coil
            axialNumberOfElements=axneForAir,
            bumpCoefficient=1,
        )

        # Structure tubes of the air:
        airOuterTubeVolumeDimTags = self.dimTags[self.geo.ai.name + "-OuterTube"]
        airOuterTubeVolumeTags = [dimTag[1] for dimTag in airOuterTubeVolumeDimTags]

        airTopTubeTerminalsVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-TopTubeTerminalsExtrusion"
        ]
        airTopTubeTerminalsVolumeTags = [
            dimTag[1] for dimTag in airTopTubeTerminalsVolumeDimTags
        ]

        airBottomTubeTerminalsVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-BottomTubeTerminalsExtrusion"
        ]
        airBottomTubeTerminalsVolumeTags = [
            dimTag[1] for dimTag in airBottomTubeTerminalsVolumeDimTags
        ]

        # Structure inner cylinder of the air:
        airInnerCylinderVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-InnerCylinder"
        ]
        airInnerCylinderVolumeTags = [
            dimTag[1] for dimTag in airInnerCylinderVolumeDimTags
        ]

        airTubesAndCylinders = airOuterTubeVolumeTags + airInnerCylinderVolumeTags

        if self.geo.ai.shellTransformation:
            shellVolumes = self.dimTags[self.geo.ai.shellVolumeName]
            shellVolumeTags = [dimTag[1] for dimTag in shellVolumes]
            airTubesAndCylinders.extend(shellVolumeTags)

        airRadialElementMultiplier = 1 / self.mesh.ai.radialElementSize
        self.structure_tubes_and_cylinders(
            airTubesAndCylinders,
            radialElementMultiplier=airRadialElementMultiplier,
        )

        if self.mesh.ti.structured:
            terminalsRadialElementMultiplier = 1 / self.mesh.ti.radialElementSize

            self.structure_tubes_and_cylinders(
                airTopTubeTerminalsVolumeTags + airBottomTubeTerminalsVolumeTags,
                radialElementMultiplier=terminalsRadialElementMultiplier,
            )

            airTopTouchingTerminalsVolumeDimTags = list(
                set(airTopTerminalsExtrusionVolumeDimTags)
                - set(airTopTubeTerminalsVolumeDimTags)
            )
            airTopTouchingTerminalsVolumeTags = [
                dimTag[1] for dimTag in airTopTouchingTerminalsVolumeDimTags
            ]

            airBottomTouchingTerminalsVolumeDimTags = list(
                set(airBottomTerminalsExtrusionVolumeDimTags)
                - set(airBottomTubeTerminalsVolumeDimTags)
            )
            airBottomTouchingTerminalsVolumeTags = [
                dimTag[1] for dimTag in airBottomTouchingTerminalsVolumeDimTags
            ]

            self.structure_tubes_and_cylinders(
                airTopTouchingTerminalsVolumeTags
                + airBottomTouchingTerminalsVolumeTags,
                terminalNonTubeParts=True,
                radialElementMultiplier=terminalsRadialElementMultiplier,
            )

    else:
        # Fuse top volumes:
        airTopVolumeDimTags = (
            airTopWindingExtrusionVolumeDimTags
            + airTopContactLayerExtrusionVolumeDimTags
            + airTopTerminalsExtrusionVolumeDimTags
        )
        airTopVolumeDimTag = Mesh.fuse_volumes(
            airTopVolumeDimTags,
            fuseSurfaces=True,
            fusedSurfacesArePlane=True,
        )
        newAirVolumeDimTags.append(airTopVolumeDimTag)
        removedAirVolumeDimTags.extend(airTopVolumeDimTags)

        # Fuse bottom volumes:
        airBottomVolumeDimTags = (
            airBottomWindingExtrusionVolumeDimTags
            + airBottomContactLayerExtrusionVolumeDimTags
            + airBottomTerminalsExtrusionVolumeDimTags
        )
        airBottomVolumeDimTag = Mesh.fuse_volumes(
            airBottomVolumeDimTags,
            fuseSurfaces=True,
            fusedSurfacesArePlane=True,
        )
        newAirVolumeDimTags.append(airBottomVolumeDimTag)
        removedAirVolumeDimTags.extend(airBottomVolumeDimTags)

        # Fuse inner cylinder and outer tube part of air:
        airInnerCylinderVolumeDimTags = self.dimTags[
            self.geo.ai.name + "-InnerCylinder"
        ]
        if self.geo.N > 1:
            # Fuse the first two and the last two volumes separately (due to cuts):
            firstTwoVolumes = airInnerCylinderVolumeDimTags[0:2]
            lastTwoVolumes = airInnerCylinderVolumeDimTags[-2:]
            airInnerCylinderVolumeDimTags = airInnerCylinderVolumeDimTags[2:-2]
            airInnerCylinderVolumeDimTag = Mesh.fuse_volumes(
                airInnerCylinderVolumeDimTags, fuseSurfaces=False
            )
            airInnerCylinderVolumeDimTagFirst = Mesh.fuse_volumes(
                firstTwoVolumes,
                fuseSurfaces=False,
            )
            airInnerCylinderVolumeDimTagLast = Mesh.fuse_volumes(
                lastTwoVolumes,
                fuseSurfaces=False,
            )
            newAirVolumeDimTags.append(airInnerCylinderVolumeDimTag)
            newAirVolumeDimTags.append(airInnerCylinderVolumeDimTagFirst)
            newAirVolumeDimTags.append(airInnerCylinderVolumeDimTagLast)
            removedAirVolumeDimTags.extend(
                airInnerCylinderVolumeDimTags + firstTwoVolumes + lastTwoVolumes
            )
            self.dimTags[self.geo.ai.name + "-InnerCylinder"] = [
                airInnerCylinderVolumeDimTag,
                airInnerCylinderVolumeDimTagFirst,
                airInnerCylinderVolumeDimTagLast,
            ]
        else:
            pass
            # self.dimTags[self.geo.ai.name + "-InnerCylinder"] = [
            #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][1],
            #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][0],
            #     self.dimTags[self.geo.ai.name + "-InnerCylinder"][2],
            # ]

        airOuterTubeVolumeDimTags = self.dimTags[self.geo.ai.name + "-OuterTube"]
        airOuterTubeVolumeDimTag = Mesh.fuse_volumes(
            airOuterTubeVolumeDimTags,
            fuseSurfaces=True,
            fusedSurfacesArePlane=False,
        )
        newAirOuterTubeVolumeDimTag = airOuterTubeVolumeDimTag
        removedAirVolumeDimTags.extend(airOuterTubeVolumeDimTags)
        self.dimTags[self.geo.ai.name + "-OuterTube"] = [newAirOuterTubeVolumeDimTag]

        if self.geo.ai.shellTransformation:
            # Fuse air shell volumes:
            if self.geo.ai.type == "cylinder":
                removedShellVolumeDimTags = []
                shellVolumeDimTags = self.dimTags[self.geo.ai.shellVolumeName]
                shellVolumeDimTag = Mesh.fuse_volumes(
                    shellVolumeDimTags,
                    fuseSurfaces=True,
                    fusedSurfacesArePlane=False,
                )
                removedShellVolumeDimTags.extend(shellVolumeDimTags)
                newShellVolumeDimTags = [shellVolumeDimTag]
                for removedDimTag in removedShellVolumeDimTags:
                    self.dimTags[self.geo.ai.shellVolumeName].remove(removedDimTag)
            elif self.geo.ai.type == "cuboid":
                # Unfortunately, surfaces cannot be combined for the cuboid type of air.
                # However, it doesn't affect the mesh quality that much.
                newShellVolumeDimTags = []

                shellPart1VolumeDimTag = Mesh.fuse_volumes(
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part1"],
                    fuseSurfaces=False,
                )
                self.dimTags[self.geo.ai.shellVolumeName + "-Part1"] = [
                    shellPart1VolumeDimTag
                ]

                shellPart2VolumeDimTag = Mesh.fuse_volumes(
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part2"],
                    fuseSurfaces=False,
                )
                self.dimTags[self.geo.ai.shellVolumeName + "-Part2"] = [
                    shellPart2VolumeDimTag
                ]

                shellPart3VolumeDimTag = Mesh.fuse_volumes(
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part3"],
                    fuseSurfaces=False,
                )
                self.dimTags[self.geo.ai.shellVolumeName + "-Part3"] = [
                    shellPart3VolumeDimTag
                ]

                shellPart4VolumeDimTag = Mesh.fuse_volumes(
                    self.dimTags[self.geo.ai.shellVolumeName + "-Part4"],
                    fuseSurfaces=False,
                )
                self.dimTags[self.geo.ai.shellVolumeName + "-Part4"] = [
                    shellPart4VolumeDimTag
                ]

            # The problem is, shell volume and outer air tube volume has a common
            # surface and that surface should be combined as well for high quality mesh.
            # However, it can be only done for cylinder type of air for now.
            # Get the combined boundary surfaces:
            if self.geo.ai.type == "cylinder":
                (
                    newAirOuterTubeVolumeDimTag,
                    newShellVolumeDimTag,
                ) = Mesh.fuse_common_surfaces_of_two_volumes(
                    [airOuterTubeVolumeDimTag],
                    newShellVolumeDimTags,
                    fuseOtherSurfaces=False,
                    surfacesArePlane=False,
                )
                self.dimTags[self.geo.ai.name + "-OuterTube"] = [newAirOuterTubeVolumeDimTag]