From 4cf738ee3b67d5e3b161da2ec2d428fb89e40911 Mon Sep 17 00:00:00 2001
From: "Ruth Sabariego (U0089683)" <Ruth.Sabariego@esat.kuleuven.be>
Date: Wed, 15 Jul 2020 15:01:50 +0200
Subject: [PATCH] Homogenisation of laminations in GetDP. Files used for
 generating results of ICS newsletter July 2020

---
 HomogenisationLaminations/lam_hyst/.DS_Store  | Bin 0 -> 6148 bytes
 HomogenisationLaminations/lam_hyst/BH.pro     | 158 ++++
 .../Macro_homogenisation_laminations.pro      | 656 ++++++++++++++
 .../lam_hyst/homog_laminations.pro            | 447 ++++++++++
 HomogenisationLaminations/lam_hyst/lam2d.geo  | 443 ++++++++++
 HomogenisationLaminations/lam_hyst/lam2d.pro  | 315 +++++++
 .../lam_hyst/lam2d_data.pro                   | 101 +++
 .../lam_hyst/matlab/.DS_Store                 | Bin 0 -> 8196 bytes
 .../lam_hyst/matlab/PQ.pro                    |  25 +
 .../lam_hyst/matlab/gausspoints_Ngp5.pro      |  40 +
 .../lam_hyst/matlab/get_b.m                   |  45 +
 .../lam_hyst/matlab/jiles_atherton.m          |  85 ++
 HomogenisationLaminations/lam_hyst/runHyst.sh |  68 ++
 HomogenisationLaminations/srm/.DS_Store       | Bin 0 -> 8196 bytes
 HomogenisationLaminations/srm/BH.pro          | 135 +++
 .../srm/Macro_homogenisation_laminations.pro  | 660 +++++++++++++++
 .../srm/MagStaDyn_SlidingSurface.pro          | 789 +++++++++++++++++
 HomogenisationLaminations/srm/generate_3d.geo |  83 ++
 .../srm/matlab/.DS_Store                      | Bin 0 -> 6148 bytes
 HomogenisationLaminations/srm/matlab/PQ.pro   |  25 +
 .../srm/matlab/bf_alpha.m                     | 191 +++++
 .../srm/matlab/bf_alpha_even.m                | 140 +++
 .../srm/matlab/build_PQmatrices.m             |  51 ++
 .../srm/matlab/gausspoints.m                  | 118 +++
 .../srm/matlab/gausspoints_Ngp5.pro           |  40 +
 HomogenisationLaminations/srm/matlab/lgwt.m   |  59 ++
 HomogenisationLaminations/srm/runF.sh         |  64 ++
 HomogenisationLaminations/srm/runT.sh         |  40 +
 HomogenisationLaminations/srm/srm.geo         | 250 ++++++
 HomogenisationLaminations/srm/srm.pro         | 801 ++++++++++++++++++
 HomogenisationLaminations/srm/srm_data.geo    | 193 +++++
 HomogenisationLaminations/srm/srm_rotor.geo   | 166 ++++
 HomogenisationLaminations/srm/srm_stator.geo  | 234 +++++
 33 files changed, 6422 insertions(+)
 create mode 100644 HomogenisationLaminations/lam_hyst/.DS_Store
 create mode 100644 HomogenisationLaminations/lam_hyst/BH.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/Macro_homogenisation_laminations.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/homog_laminations.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/lam2d.geo
 create mode 100644 HomogenisationLaminations/lam_hyst/lam2d.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/lam2d_data.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/matlab/.DS_Store
 create mode 100644 HomogenisationLaminations/lam_hyst/matlab/PQ.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/matlab/gausspoints_Ngp5.pro
 create mode 100644 HomogenisationLaminations/lam_hyst/matlab/get_b.m
 create mode 100644 HomogenisationLaminations/lam_hyst/matlab/jiles_atherton.m
 create mode 100755 HomogenisationLaminations/lam_hyst/runHyst.sh
 create mode 100644 HomogenisationLaminations/srm/.DS_Store
 create mode 100644 HomogenisationLaminations/srm/BH.pro
 create mode 100644 HomogenisationLaminations/srm/Macro_homogenisation_laminations.pro
 create mode 100644 HomogenisationLaminations/srm/MagStaDyn_SlidingSurface.pro
 create mode 100644 HomogenisationLaminations/srm/generate_3d.geo
 create mode 100644 HomogenisationLaminations/srm/matlab/.DS_Store
 create mode 100644 HomogenisationLaminations/srm/matlab/PQ.pro
 create mode 100644 HomogenisationLaminations/srm/matlab/bf_alpha.m
 create mode 100644 HomogenisationLaminations/srm/matlab/bf_alpha_even.m
 create mode 100644 HomogenisationLaminations/srm/matlab/build_PQmatrices.m
 create mode 100644 HomogenisationLaminations/srm/matlab/gausspoints.m
 create mode 100644 HomogenisationLaminations/srm/matlab/gausspoints_Ngp5.pro
 create mode 100644 HomogenisationLaminations/srm/matlab/lgwt.m
 create mode 100755 HomogenisationLaminations/srm/runF.sh
 create mode 100755 HomogenisationLaminations/srm/runT.sh
 create mode 100644 HomogenisationLaminations/srm/srm.geo
 create mode 100644 HomogenisationLaminations/srm/srm.pro
 create mode 100644 HomogenisationLaminations/srm/srm_data.geo
 create mode 100644 HomogenisationLaminations/srm/srm_rotor.geo
 create mode 100644 HomogenisationLaminations/srm/srm_stator.geo

diff --git a/HomogenisationLaminations/lam_hyst/.DS_Store b/HomogenisationLaminations/lam_hyst/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..9d6c8902230efbd1187b93ed04dc530c72db4102
GIT binary patch
literal 6148
zcmeHK%}T>S5T3QQMpVc}^tgB~(iUnFJcLleqtHSRRx~k%24Yj1lpbO<zL3x0Q}{g2
z>~6qf@F-$uVCS36&u;dE>}CK!xXYjoU;}`KgHVuBA>^(MZJFd6qEK^q;QOm&?nkj-
zG0|Ui(YrU`5j;pCLjCpq-~4$LCTXknA+~Du?Z%FUvOgY$vmjo%@p2X<H-l-s8ic{b
z_ZGLxPQ7%QxZXlVuDx`M5oHhKI6`}DvPWT%PVelaEbDffveRwnO_`mawVSfn>*e__
ziv4aKo}6A>4ZZ9se}2*Q31nKyfx!}9(OBC_kUT^_E=mP8Sil65(pA<lG6T#2Gr$aN
zA_L|ovGz7`^SozffEoCa0XiQf4noIZp-~+js8kDpSVy-Kw5gY%8fnlmSZKruiqNHq
zx>T4JL+En!OOxjqEHvtJ5T^MMX63SZ5o&duU#fHvjz-qZ05h=80QJ5oHr@Z1_{mf@
z`6`7KGr$b|R|Z7AKj^!-J9D>w+b7+%630Cb63Q#cKtX%$CjcMl9644&9hYQdo@21k
VNVAY%l_T<xfFgtyGw=%xd;*tNP00WN

literal 0
HcmV?d00001

diff --git a/HomogenisationLaminations/lam_hyst/BH.pro b/HomogenisationLaminations/lam_hyst/BH.pro
new file mode 100644
index 0000000..48675b4
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/BH.pro
@@ -0,0 +1,158 @@
+Function{
+
+  // analytical
+  // analytical Brauer law for nonlinear isotropic material:
+  // nu(b^2) = k1 + k2 * exp ( k3 * b^2 )
+  // nu = 100. + 10. * exp ( 1.8 * b * b )
+  k1 = 100.; k2 = 10.; k3 = 1.8;
+  nu_1a[] = k1 + k2 * Exp[k3*SquNorm[$1]] ;
+  dnudb2_1a[] =  k2 * k3 * Exp[k3*SquNorm[$1]] ;
+  h_1a[] = nu_1a[$1]*$1 ;
+  dhdb_1a[] = TensorDiag[1,1,1] * nu_1a[$1#1] + 2*dnudb2_1a[#1] * SquDyadicProduct[#1]  ;
+  dhdb_1a_NL[] = 2*dnudb2_1a[$1#1] * SquDyadicProduct[#1]  ;
+
+   // interpolated
+  Mat1_h = {
+    0.0000e+00, 5.5023e+00, 1.1018e+01, 1.6562e+01, 2.2149e+01, 2.7798e+01, 3.3528e+01,
+    3.9363e+01, 4.5335e+01, 5.1479e+01, 5.7842e+01, 6.4481e+01, 7.1470e+01, 7.8906e+01,
+    8.6910e+01, 9.5644e+01, 1.0532e+02, 1.1620e+02, 1.2868e+02, 1.4322e+02, 1.6050e+02,
+    1.8139e+02, 2.0711e+02, 2.3932e+02, 2.8028e+02, 3.3314e+02, 4.0231e+02, 4.9395e+02,
+    6.1678e+02, 7.8320e+02, 1.0110e+03, 1.3257e+03, 1.7645e+03, 2.3819e+03, 3.2578e+03,
+    4.5110e+03, 6.3187e+03, 8.9478e+03, 1.2802e+04, 1.8500e+04, 2.6989e+04, 3.9739e+04,
+    5.9047e+04, 8.8520e+04, 1.3388e+05, 2.0425e+05, 3.1434e+05, 4.8796e+05, 7.6403e+05
+  } ;
+  Mat1_b = {
+    0.0000e+00, 5.0000e-02, 1.0000e-01, 1.5000e-01, 2.0000e-01, 2.5000e-01, 3.0000e-01,
+    3.5000e-01, 4.0000e-01, 4.5000e-01, 5.0000e-01, 5.5000e-01, 6.0000e-01, 6.5000e-01,
+    7.0000e-01, 7.5000e-01, 8.0000e-01, 8.5000e-01, 9.0000e-01, 9.5000e-01, 1.0000e+00,
+    1.0500e+00, 1.1000e+00, 1.1500e+00, 1.2000e+00, 1.2500e+00, 1.3000e+00, 1.3500e+00,
+    1.4000e+00, 1.4500e+00, 1.5000e+00, 1.5500e+00, 1.6000e+00, 1.6500e+00, 1.7000e+00,
+    1.7500e+00, 1.8000e+00, 1.8500e+00, 1.9000e+00, 1.9500e+00, 2.0000e+00, 2.0500e+00,
+    2.1000e+00, 2.1500e+00, 2.2000e+00, 2.2500e+00, 2.3000e+00, 2.3500e+00, 2.4000e+00
+  } ;
+
+  Mat1_b2 = Mat1_b()^2;
+  Mat1_nu = Mat1_h()/Mat1_b();
+  Mat1_nu(0) = Mat1_nu(1);
+
+  Mat1_nu_b2  = ListAlt[Mat1_b2(), Mat1_nu()] ;
+  nu_1[] = InterpolationLinear[ SquNorm[$1] ]{Mat1_nu_b2()} ;
+  dnudb2_1[] = dInterpolationLinear[SquNorm[$1]]{Mat1_nu_b2()} ;
+  h_1[] = nu_1[$1] * $1 ;
+  dhdb_1[] = TensorDiag[1,1,1] * nu_1[$1#1] + 2*dnudb2_1[#1] * SquDyadicProduct[#1]  ;
+  dhdb_1_NL[] = 2*dnudb2_1[$1#1] * SquDyadicProduct[#1] ;
+
+
+  // nu = 123. + 0.0596 * exp ( 3.504 * b * b )
+  // analytical 3kW machine
+  nu_3kWa[] = 123. + 0.0596 * Exp[3.504*SquNorm[$1]] ;
+  dnudb2_3kWa[] = 0.0596*3.504 * Exp[3.504*SquNorm[$1]] ;
+  h_3kWa[] = nu_3kWa[$1]*$1 ;
+  dhdb_3kWa[] = TensorDiag[1,1,1] * nu_3kWa[$1#1] + 2*dnudb2_3kWa[#1] * SquDyadicProduct[#1]  ;
+  dhdb_3kWa_NL[] = 2*dnudb2_3kWa[$1#1] * SquDyadicProduct[#1]  ;
+
+  // interpolated
+  Mat3kW_h = {
+    0.0000e+00, 6.1465e+00, 1.2293e+01, 1.8440e+01, 2.4588e+01, 3.0736e+01, 3.6886e+01,
+    4.3037e+01, 4.9190e+01, 5.5346e+01, 6.1507e+01, 6.7673e+01, 7.3848e+01, 8.0036e+01,
+    8.6241e+01, 9.2473e+01, 9.8745e+01, 1.0508e+02, 1.1150e+02, 1.1806e+02, 1.2485e+02,
+    1.3199e+02, 1.3971e+02, 1.4836e+02, 1.5856e+02, 1.7137e+02, 1.8864e+02, 2.1363e+02,
+    2.5219e+02, 3.1498e+02, 4.2161e+02, 6.0888e+02, 9.4665e+02, 1.5697e+03, 2.7417e+03,
+    4.9870e+03, 9.3633e+03, 1.8037e+04, 3.5518e+04, 7.1329e+04, 1.4591e+05, 3.0380e+05,
+    6.4363e+05, 1.3872e+06, 3.0413e+06, 6.7826e+06, 1.5386e+07, 3.5504e+07, 8.3338e+07
+  } ;
+  Mat3kW_b = {
+    0.0000e+00, 5.0000e-02, 1.0000e-01, 1.5000e-01, 2.0000e-01, 2.5000e-01, 3.0000e-01,
+    3.5000e-01, 4.0000e-01, 4.5000e-01, 5.0000e-01, 5.5000e-01, 6.0000e-01, 6.5000e-01,
+    7.0000e-01, 7.5000e-01, 8.0000e-01, 8.5000e-01, 9.0000e-01, 9.5000e-01, 1.0000e+00,
+    1.0500e+00, 1.1000e+00, 1.1500e+00, 1.2000e+00, 1.2500e+00, 1.3000e+00, 1.3500e+00,
+    1.4000e+00, 1.4500e+00, 1.5000e+00, 1.5500e+00, 1.6000e+00, 1.6500e+00, 1.7000e+00,
+    1.7500e+00, 1.8000e+00, 1.8500e+00, 1.9000e+00, 1.9500e+00, 2.0000e+00, 2.0500e+00,
+    2.1000e+00, 2.1500e+00, 2.2000e+00, 2.2500e+00, 2.3000e+00, 2.3500e+00, 2.4000e+00
+  } ;
+
+  Mat3kW_b2 = Mat3kW_b()^2;
+  Mat3kW_nu = Mat3kW_h()/Mat3kW_b();
+  Mat3kW_nu(0) = Mat3kW_nu(1);
+
+  Mat3kW_nu_b2  = ListAlt[Mat3kW_b2(), Mat3kW_nu()] ;
+  nu_3kW[] = InterpolationLinear[SquNorm[$1]]{Mat3kW_nu_b2()} ;
+  dnudb2_3kW[] = dInterpolationLinear[SquNorm[$1]]{Mat3kW_nu_b2()} ;
+  h_3kW[] = nu_3kW[$1] * $1 ;
+  dhdb_3kW[] = TensorDiag[1,1,1]*nu_3kW[$1#1] + 2*dnudb2_3kW[#1] * SquDyadicProduct[#1] ;
+  dhdb_3kW_NL[] = 2*dnudb2_3kW[$1] * SquDyadicProduct[$1] ;
+
+  DefineFunction[nu_lin, nu_nonlin, dhdb_NL] ;
+  // linear case -- testing purposes
+  h_lin[] = nu_lin[] * $1 ;
+  dhdb_lin[] = nu_lin[] * TensorDiag[1.,1.,1.] ;
+  dhdb_lin_NL[] = TensorDiag[0.,0.,0.] ;
+
+
+  // Parameters for Jiles-Atherton hysteresis model
+  //Gyselink's paper: Incorporation of a Jiles-Atherton vector hysteresis model in 2D FE magnetic field computations
+  Msat = 1145220; aaa = 59.5; kkk = 99.2; ccc = 0.54; alpha = 1.3e-4 ;
+
+  // FeSi -- data for Jiles-Atherton model from Bastos paper
+  // Oxz is the lamination plane, Oy is perpendicular to the lamination
+  // Ox == transverse direction (Oy taken equal to Ox, as the field is negligible)
+  Msat_x = 1.31e6;
+  a_x = 233.78;
+  k_x = 374.975;
+  c_x = 0.736;
+  alpha_x = 562e-6 ;
+
+  // Oz == rolling direction
+  Msat_z = 1.33e6;
+  a_z = 172.856;
+  k_z = 232.652;
+  c_z = 0.652;
+  alpha_z = 417e-6;
+
+  // hyst_FeSi = { Msat_x, a_x, k_x, c_x, alpha_x}; // transverse direction
+  // hyst_FeSi = { Msat_z, a_z, k_z, c_z, alpha_z}; // rolling direction
+
+  hyst_FeSi = { Msat, aaa, kkk, ccc, alpha};
+
+
+
+
+  //Using anhysteretic curve from Jiles-Atherton model
+  anhys_b  = {
+    0.00000000, 0.32182278, 0.61073510, 0.79096285, 0.90997687,
+    0.99429048, 1.05693296, 1.10504060, 1.14290665, 1.17329715,
+    1.19808489, 1.21858522, 1.23574806, 1.25027452, 1.26269133,
+    1.27340002, 1.28271066, 1.29086537, 1.29805515, 1.30443212,
+    1.31011850, 1.31521331, 1.31979742, 1.32393739, 1.32768837,
+    1.33109640, 1.33420015, 1.33703230, 1.33962062, 1.34198886,
+    1.34415738, 1.34614376, 1.34796321, 1.34962896, 1.35115252,
+    1.35254394, 1.35381202, 1.35496447, 1.35600803, 1.35694862,
+    1.35779139, 1.35854083, 1.35920085, 1.35977480, 1.36026555,
+    1.36067549, 1.36100662, 1.36126050, 1.36143836, 1.36154102,
+    1.36156898 } ;
+
+  anhys_h  = {
+    0.00000000, 31.48945679, 62.94768133, 94.34347236, 125.64569053,
+    156.82328930, 187.84534575, 218.68109121, 249.29994180, 279.67152877,
+    309.76572863, 339.55269297, 369.00287816, 398.08707454, 426.77643550,
+    455.04250600, 482.85725087, 510.19308256, 537.02288850, 563.32005806,
+    589.05850886, 614.21271269, 638.75772080, 662.66918868, 685.92340017,
+    708.49729101, 730.36847168, 751.51524967, 771.91665092, 791.55244067,
+    810.40314351, 828.45006274, 845.67529883, 862.06176725, 877.59321537,
+    892.25423862, 906.03029572, 918.90772314, 930.87374864, 941.91650394,
+    952.02503648, 961.18932028, 969.40026594, 976.64972956, 982.93052091,
+    988.23641048, 992.56213574, 995.90340628, 998.25690814, 999.62030702,
+    999.99225068 } ;
+
+  anhys_b2  = anhys_b()^2 ;
+  anhys_nu  = anhys_h()/anhys_b() ;
+  anhys_nu(0) = anhys_nu(1) ;
+  anhys_nu_b2 = ListAlt[anhys_b2(), anhys_nu()] ;
+
+  nu_anhys[]     = InterpolationLinear[SquNorm[$1]]{anhys_nu_b2()} ;
+  dnudb2_anhys[] = dInterpolationLinear[SquNorm[$1]]{anhys_nu_b2()} ;
+  h_anhys[] = nu_anhys[$1#1] * #1 ;
+  dhdb_anhys[] = TensorDiag[1,1,1] * nu_anhys[$1#1] + 2*dnudb2_anhys[#1] * SquDyadicProduct[#1] ;
+  dhdb_anhys_NL[] = 2*dnudb2_anhys[$1#1] * SquDyadicProduct[#1] ;
+
+}
diff --git a/HomogenisationLaminations/lam_hyst/Macro_homogenisation_laminations.pro b/HomogenisationLaminations/lam_hyst/Macro_homogenisation_laminations.pro
new file mode 100644
index 0000000..f23e120
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/Macro_homogenisation_laminations.pro
@@ -0,0 +1,656 @@
+Group {
+  Domain_Lin = Region[{Domain_L}] ;
+  Domain_NonLin = Region[{Domain_NL}] ;
+}
+
+Include "matlab/PQ.pro" ;
+Include "matlab/gausspoints_Ngp5.pro";
+
+Function {
+
+  nuIron = nu_fe;
+  sigmaLam = sigma_fe;
+
+  //lambda = fillfactor ; //la = lambda ;
+  sigmaH[] = sigmaLam/fillfactor;
+
+
+  //Legendre Polynomials (used in post-processing)
+  yy[] = ((Fmod[$Y,e]-e/2)*2/dlam) ; //x = z/(dlam/2), e = dlam+de
+
+  alpha_0[] = 1 ; // zero order
+  alpha_2[] = 1/2*(-1+3*yy[]^2) ; //2nd order
+  alpha_4[] = 1/8*(35*yy[]^4-30*yy[]^2+3); //4th order
+  alpha_6[] = 1/16*(231*yy[]^6-315*yy[]^4+105*yy[]^2-5);
+  alpha_8[] = 1/128*(6435*yy[]^8-12012*yy[]^6+6930*yy[]^4-1260*yy[]^2+35);
+
+  dalpha_0[] = 0. ;
+  dalpha_2[] = 3*yy[]*2/dlam ;
+  dalpha_4[] = 1/2*(35*yy[]^3-15*yy[])*2/dlam; //4th order
+  dalpha_6[] = 1/8*(231*3*yy[]^5-315*2*yy[]^3+105*yy[])*2/dlam;
+  dalpha_8[] = 1/64*(6435*4*yy[]^7-12012*3*yy[]^5+6930*2*yy[]^3-1260*yy[])*2/dlam;
+
+  ialpha_0[] = yy[]*dlam/2 ;
+  ialpha_2[] = 1/2*(yy[]^3-yy[])*dlam/2 ;
+  ialpha_4[] = 1/8*(7*yy[]^5-10*yy[]^3+3*yy[])*dlam/2;
+  ialpha_6[] = 1/16*(33*yy[]^7-63*yy[]^5+35*yy[]^3-5*yy[])*dlam/2;
+  ialpha_8[] = 1/128*(6435*yy[]^9/9-12012*yy[]^7/7+6930*yy[]^5/5-1260*yy[]^3/3+35*yy[])*dlam/2;
+
+
+  If(Flag_ComplexReluctivity) // complex stuff
+    delta = Sqrt[2*nuIron/sigmaLam/Omega] ;
+    ds = dlam/delta ;
+    Printf("delta = %g mm",delta*1000) ;
+    Printf("ds = %g",ds) ;
+    Printf("Flag_ComplexReluctivity = %g ; ORDER = %g", Flag_ComplexReluctivity, ORDER);
+
+    //Definition of Sinh, Cosh and Tanh in terms of the real and imaginary parts of a complex argument
+    Sinh_[] = Complex[ Cos[Im[$1]]*Sinh[Re[$1]], Sin[Im[$1]]*Cosh[Re[$1]] ];
+    Cosh_[] = Complex[ Cos[Im[$1]]*Cosh[Re[$1]], Sin[Im[$1]]*Sinh[Re[$1]] ];
+    Tanh_[] = Sinh_[$1]/Cosh_[$1];
+
+    // G[] => Function used in L.Krahenbuhl's article IEEE Trans. Mag. vol.40, no. 2, pp. 912-915, 2004.
+    G[] = Tanh_[ds/2*Complex[1,1]]/(ds/2*Complex[1,1]);
+
+    // Gr = ds/2 * (Sinh[ds]+Sin[ds])/(Cosh[ds]-Cos[ds]) ;
+    // Gi = ds/2 * (Sinh[ds]-Sin[ds])/(Cosh[ds]-Cos[ds]) ;
+    // G[Iron] = Complex[Gr,Gi];
+
+    If(ORDER==0) //Analytical
+      nuCplx[] = nuIron/G[] ;
+    EndIf
+    If(ORDER==-1)   // Approx ORDER = 0
+      nuCplx[] = Complex[ nuIron, sigmaLam * dlam^2/12. * Omega ];
+    EndIf
+    If(ORDER==-2)   // Approx ORDER = 2
+      // nuIron_r2 = nuIron * (1+ 49*ds^4/(8820+20*ds^4) ) ;
+      // nuIron_i2 = nuIron * (ds^2/6-7*ds^6/(26460+60*ds^4) ) ;
+      // nu[#{DomainLam}] = Complex[nuIron_r2, nuIron_i2]*fillfactor ;
+      // From matlab: nu1s = (ds^6*i + 69*ds^4 + ds^2*(1470*i) + 8820)/(20*(ds^4 + 441))
+      nuCplx[] = nuIron * Complex[
+        (69*ds^4 + 8820)/(8820+20*ds^4), (ds^6 + ds^2*1470)/(8820+20*ds^4) ];
+    EndIf
+    If(ORDER==-3)   // Approx ORDER = 4
+      // From matlab:
+      // collect(nu2s) =
+      // (ds^10*1i + 300*ds^8 + ds^6*29520i + 1353240*ds^4 + ds^2*27442800i + 164656800)/(42*ds^8 + 438480*ds^4 + 164656800)
+      // collect(real(nu2s)) = (50*ds^8 + 225540*ds^4 + 27442800)/(7*ds^8 + 73080*ds^4 + 27442800)
+      // collect(imag(nu2s)) = (ds^10 + 29520*ds^6 + 27442800*ds^2)/(42*ds^8 + 438480*ds^4 + 164656800)
+      nuCplx[] = nuIron * Complex[
+        (50*ds^8 + 225540*ds^4 + 27442800)/(7*ds^8 + 73080*ds^4 + 27442800),
+        (ds^10 + 29520*ds^6 + 27442800*ds^2)/(42*ds^8 + 438480*ds^4 + 164656800)];
+    EndIf
+    muCplx[] = 1/nuCplx[];
+    nu[#{DomainLam}] = nuCplx[]/fillfactor ; //with homog block
+
+    nuOm[] = Complex[ Omega*Im[nuCplx[]], -Re[nuCplx[]] ];
+    muOm[] = Complex[-Omega*Im[muCplx[]], -Re[muCplx[]] ];
+
+    // from Patrick's files
+    Ytransf[] = Fmod[Y[]-de/2., dlam+de] -dlam/2. ;
+    FACJ[] =
+    (Ytransf[]>=-dlam/2. && Ytransf[]<=dlam/2.)?
+    sigmaLam*dlam*2*Pi*Freq*Complex[0,1] / 2 / Sinh_[Complex[1,1]/delta*dlam/2]*
+    Sinh_[Complex[1,1]/delta* Ytransf[] ] : 0. ;
+
+    FACB[] =
+    (Ytransf[]>=-dlam/2. && Ytransf[]<=dlam/2.)?
+    sigmaLam*dlam*2*Pi*Freq*Complex[0,1] / 2 / Sinh_[Complex[1,1]/delta*dlam/2]*
+    delta*Complex[1,-1]/2 /nuIron *
+    Cosh_[Complex[1,1]/delta* Ytransf[] ] : 0. ;
+
+  EndIf
+
+}
+
+FunctionSpace {
+
+
+  ORDERMAX=4; //1 (zero order); 2 (2nd order); 3 (4th order); 4 (6th order); homogenization approx
+  // Auxiliary BFs {d a_i}
+  For i In {2:ORDERMAX}
+    { Name Hcurl_a~{2*i-2} ; Type Form1 ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_Edge ;
+          Support DomainLam ; Entity EdgesOf[ All ] ; }
+      }
+      Constraint {
+        { NameOfCoef ae  ; EntityType EdgesOf ; NameOfConstraint MagneticVectorPotential ; }
+      }
+    }
+  EndFor
+  // Auxiliary BFs {b_i}
+  For i In {2:ORDERMAX}
+    { Name Hb~{2*i-2} ; Type Form2 ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_Facet ;
+          Support DomainLam ; Entity FacetsOf[ All ] ; }
+      }
+    }
+  EndFor
+
+
+  // Store hystory for every integration point along thickness
+  For i In {1:nbrQuadraturePnts}
+    { Name H_hysteresis~{i} ; Type Vector;
+      BasisFunction {
+        // { Name sex ; NameOfCoef aex ; Function BF_VolumeX ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+        // { Name sey ; NameOfCoef aey ; Function BF_VolumeY ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+        { Name sez ; NameOfCoef aez ; Function BF_VolumeZ ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+      }
+    }
+  EndFor
+
+}
+
+
+// -------------------------------------------------------
+// Terms in homogenized formulations for laminations
+// -------------------------------------------------------
+
+Macro Macro_Terms_DomainLamC_sigma
+
+  If(ORDER >= 1) //ORDER = 0
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_0 * Dof{d a}, {d a} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration II ; }
+  EndIf
+  If (ORDER > 1) //ORDER = 2
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_2 * Dof{b_2}, {d a} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration II ; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_2 * Dof{d a}, {b_2} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration II ; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_2 * Dof{b_2}, {b_2} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration II ; }
+  EndIf
+
+  If(ORDER > 2) //ORDER = 4
+    // 0 = nu*b_2/5 + sigma*d^2*(-dt(b0)/60   + dt(b_2)/210 - dt(b_4)/1260)
+    // 0 = nu*b_4/9 + sigma*d^2*(-dt(b_2)/1260 + dt(b_4)/1386)
+
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_4 *Dof{b_4},  {b_2} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_4 *Dof{b_2} , {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_4 *Dof{b_4} , {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+  EndIf
+
+  If(ORDER > 3) //ORDER = 6
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_6 * Dof{b_6}, {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_6 * Dof{b_4}, {b_6} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_6_6 * Dof{b_6}, {b_6} ];
+      In DomainLamC; Jacobian Vol ; Integration II; }
+  EndIf
+
+Return
+
+//---------------------------------------------------------------
+//---------------------------------------------------------------
+
+Macro Macro_Terms_DomainLam_nu
+
+If(!NbrRegions[Domain_NonLin]) // linear case
+  For k In {2:ORDER} // ORDER=2 => p_2;  ORDER=3 => p_4; ORDER=4 => p_6;
+    Galerkin { [ p~{2*k-2} * nu[] * Dof{b~{2*k-2}}, {b~{2*k-2}} ] ;
+      In DomainLam ; Jacobian Vol ; Integration II; }
+  EndFor
+  /*
+  Galerkin { [ p_2 * nu[] * Dof{b_2} , {b_2} ]; In DomainLam; Jacobian Vol ; Integration II; }
+  Galerkin { [ p_4 * nu[] * Dof{b_4} , {b_4} ]; In DomainLam; Jacobian Vol ; Integration II; }
+  Galerkin { [ p_6 * nu[] * Dof{b_6} , {b_6} ]; In DomainLam; Jacobian Vol ; Integration II; }
+  */
+
+Else // Directly using gauss points, nu[] and dhdb_NL[]
+
+  If (ORDER == 2)
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [  $nuprev * c_2~{i}   * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_02
+      Galerkin { [  $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_20
+      Galerkin { [  $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_22
+
+      Galerkin { JacNL[ SetVariable[1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi} * Dof{d a} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}   * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}   * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}^2 * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+    EndFor
+  EndIf
+
+  If( ORDER == 3 ) //ORDER = 4
+    //Galerkin { [nu[]/9 *Dof{b_4} , {b_4} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $nuprev * c_2~{i} * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_02
+      Galerkin { [ $nuprev * c_4~{i} * Dof{b_4} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_04
+
+      Galerkin { [ $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_20
+      Galerkin { [ $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_22
+      Galerkin { [ $nuprev * c_2~{i} * c_4~{i} * Dof{b_4} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_24
+
+      Galerkin { [ $nuprev * c_4~{i} * Dof{d a} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_40
+      Galerkin { [ $nuprev * c_4~{i} * c_2~{i} * Dof{b_2} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_42
+      Galerkin { [ $nuprev * c_4~{i}^2 * Dof{b_4} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_44
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+    EndFor
+  EndIf
+
+    If( ORDER == 4 ) //ORDER = 6
+    //Galerkin { [nu[]/13 *Dof{b_6} , {b_6} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $nuprev * c_2~{i} * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_02
+      Galerkin { [ $nuprev * c_4~{i} * Dof{b_4} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_04
+      Galerkin { [ $nuprev * c_6~{i} * Dof{b_6} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_06
+
+      Galerkin { [ $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_20
+      Galerkin { [ $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_22
+      Galerkin { [ $nuprev * c_2~{i} * c_4~{i} * Dof{b_4} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_24
+      Galerkin { [ $nuprev * c_2~{i} * c_6~{i} * Dof{b_6} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_26
+
+      Galerkin { [ $nuprev * c_4~{i} * Dof{d a} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_40
+      Galerkin { [ $nuprev * c_4~{i} * c_2~{i} * Dof{b_2} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_42
+      Galerkin { [ $nuprev * c_4~{i}^2 * Dof{b_4} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_44
+      Galerkin { [ $nuprev * c_4~{i} * c_6~{i} * Dof{b_6} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_46
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi *          c_6~{i} * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_06
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_6~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_26
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_40
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_42
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_6~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_46
+
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} *           Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_60
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_2~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_62
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_4~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_64
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_66
+    EndFor
+  EndIf
+
+EndIf
+
+Return
+
+//---------------------------------------------------------------
+//---------------------------------------------------------------
+
+Macro Macro_Terms_DomainLam_h
+
+If(!NbrRegions[Domain_NonLin]) // linear case
+
+  For k In {2:ORDER} // ORDER=2 => p_2;  ORDER=3 => p_4; ORDER=4 => p_6;
+    Galerkin { [ p~{2*k-2} * nu[] * Dof{b~{2*k-2}}, {b~{2*k-2}} ] ;
+      In DomainLam ; Jacobian Vol ; Integration II; }
+  EndFor
+
+Else // Directly using gauss points, h[] and dhdb[]
+
+  If (ORDER == 2) //ORDER = 2
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ // h_0
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_2
+
+      Galerkin { JacNL[ SetVariable[1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *           c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+    EndFor
+  EndIf
+
+  If( ORDER == 3 ) //ORDER = 4
+    //Galerkin { [nu[]/9 *Dof{b_4} , {b_4} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ; // h_0
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_2
+      Galerkin { [ $hprev * c_4~{i} * w~{i} , {b_4} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_4
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+    EndFor
+  EndIf
+
+    If( ORDER == 4 ) //ORDER = 6
+    //Galerkin { [nu[]/13 *Dof{b_6} , {b_6} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ; // h_0
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_2
+      Galerkin { [ $hprev * c_4~{i} * w~{i} , {b_4} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_4
+      Galerkin { [ $hprev * c_6~{i} * w~{i} , {b_6} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_6
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi *          c_6~{i} * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_06
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_6~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_26
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_40
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_42
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_6~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_46
+
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} *           Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_60
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_2~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_62
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_4~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_64
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_66
+    EndFor
+  EndIf
+
+EndIf
+
+Return
+
+//-----------------------------------------------------------------------------------
+
+Macro Macro_Terms_DomainLam_hysteresis
+
+If(NbrRegions[Domain_NL]) // nonlinear hysteretic case
+  If (ORDER == 2) //ORDER = 2
+    // for NR iterations
+    // History of h to be kept for every quadrature point along lamination thickness
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[
+            {h~{i}}[1],
+            ({d a}[1]+ c_2~{i}*{b_2}[1])/fillfactor,
+            ({d a}   + c_2~{i}*{b_2}   )/fillfactor]{List[hyst_FeSi]} , {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * w~{i}          , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_Jiles0
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_Jiles2
+    EndFor
+
+    For i In{1:nbrQuadraturePnts} //dhdb_Jiles00, dhdb_Jiles02, dhdb_Jiles22, dhdb_Jiles20
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor*
+            dhdb_Jiles[ {h~{i}}, ({d a}+c_2~{i}*{b_2})/fillfactor, {h~{i}}-{h~{i}}[1] ]{List[hyst_FeSi]}*w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}           * Dof{b_2} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+  EndIf
+
+  If (ORDER == 3) //ORDER = 4
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[{h~{i}}[1],
+            ({d a}[1]+c_2~{i}*{b_2}[1]+c_4~{i}*{b_4}[1])/fillfactor,
+            ({d a}+   c_2~{i}*{b_2}   +c_4~{i}*{b_4}   )/fillfactor]{List[hyst_FeSi]}, {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { [ Dof{h~{i}}           * w~{i}, {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_4~{i} * w~{i}, {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+    For i In{1:nbrQuadraturePnts}
+      //dhdb_Jiles 00, 02, 04, 22, 20, 24, 44, 40, 42
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor*dhdb_Jiles[
+              {h~{i}},
+              ({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor,
+              {h~{i}}-{h~{i}}[1] ]{List[hyst_FeSi]} * w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}          * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i}          * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_2~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_4~{i} * Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_4~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+  EndIf
+
+  If (ORDER == 4) //ORDER = 6
+    For i In {1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ;
+        In DomainLam  ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[
+            {h~{i}}[1],
+            ({d a}[1]+c_2~{i}*{b_2}[1]+c_4~{i}*{b_4}[1]+c_6~{i}*{b_6}[1])/fillfactor,
+            ({d a}+ c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{List[hyst_FeSi]}, {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { [ Dof{h~{i}}           * w~{i}, {d a} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_4~{i} * w~{i}, {b_4} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_6~{i} * w~{i}, {b_6} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+    For i In{1:nbrQuadraturePnts}
+      //dhdb_Jiles 00, 02, 04, 06, 22, 20, 24, 26, 44, 40, 42, 46, 66, 60, 62, 64
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor*dhdb_Jiles[
+              {h~{i}},
+              ({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor,
+              {h~{i}}-{h~{i}}[1]]{List[hyst_FeSi]}*w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}          * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i}          * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i}          * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_2~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_2~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_4~{i} * Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_4~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_4~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_6~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_6~{i} * Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_6~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+  EndIf
+
+
+
+EndIf
+
+
+Return
+
+
+
+//-----------------------------------------------------------------------------------
+// PostQuantities
+//-----------------------------------------------------------------------------------
+
+Macro PostQuantities_Homog
+
+  { Name b~{0} ; Value { Local { [ {d a}/fillfactor ] ; In DomainLam ; Jacobian Vol ; } } }
+  For k In{2:ORDER}
+    { Name b~{2*k-2}  ; Value { Term { [ alpha~{2*k-2}[]*{b~{2*k-2}}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+  { Name bz~{0} ; Value { Local { [ CompZ[{d a}] ] ; In DomainLam ; Jacobian Vol ; } } }
+  For k In{2:ORDER}
+    { Name bz~{2*k-2}  ; Value { Term { [ alpha~{2*k-2}[]*CompZ[{b~{2*k-2}}]/fillfactor ]  ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+  { Name btot  ; Value {
+      Term { [ {d a}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; }
+      For k In{2:ORDER}
+        Term { [ alpha~{2*k-2}[]*{b~{2*k-2}}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; }
+      EndFor
+    }
+  }
+
+  { Name j~{0} ;
+    Value { Term { [ sigmaH[]*ialpha~{0}[]*Dt[{d a}]/\Vector[0,-1,0] ] ; In DomainLam ; Jacobian Vol ; } } }
+  For k In{2:ORDER}
+    { Name j~{2*k-2} ;
+      Value { Term { [ sigmaH[]*ialpha~{2*k-2}[]*Dt[{b~{2*k-2}}]/\Vector[0,-1,0] ] ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+  For k In {0:ORDERMAX:2}
+    { Name  aa~{k} ; Value { Local { [  alpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+    { Name daa~{k} ; Value { Local { [ dalpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+    { Name iaa~{k} ; Value { Local { [ ialpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+
+  If(Flag_ComplexReluctivity) // Frequency domain
+    { Name j_beta  ; Value { Term { [ (Vector[0,1,0]*^{d a})*FACJ[] ] ; In DomainLam ; Jacobian Vol ;} } }
+    { Name b_alpha ; Value { Term { [ {d a}*FACB[] ] ; In DomainLam ; Jacobian Vol ; } } }
+
+    { Name ComplexPowerH ; Value { // real part -> eddy current losses; imag part-> magnetic energy
+        Integral { [ SymmetryFactor*AxialLength*{d a}*Conj[nuOm[]*{d a} ] ];
+          In DomainLam; Jacobian Vol ; Integration II ; }
+      }
+    }
+  EndIf
+
+  { Name JouleLossesH_local ;
+    Value {
+      If(Flag_ComplexReluctivity) // Frequency domain
+        Term { [ Re[ {d a}*Conj[ nuOm[]*{d a} ] ] ];
+          In DomainLamC ; Jacobian Vol ; }
+
+      Else // Time domain
+
+        Term { [ dlam^2*sigmaH[]*q_0_0*SquNorm[Dt[{d a}]] ] ;
+          In DomainLamC ; Jacobian Vol ; }
+        If (ORDER>1)
+          Term { [   dlam^2*sigmaH[]*q_2_2*SquNorm[Dt[{b_2}]] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_0_2*Dt[{d a}]*Dt[{b_2}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+        If (ORDER>2)
+          Term { [   dlam^2*sigmaH[]*q_4_4*SquNorm[Dt[{b_4}] ] ];
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_2_4*Dt[{b_2}]*Dt[{b_4}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+        If (ORDER>3)
+          Term { [   dlam^2*sigmaH[]*q_6_6*SquNorm[Dt[{b_6}] ] ];
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_4_6*Dt[{b_4}]*Dt[{b_6}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+
+      EndIf
+
+    } }
+
+  { Name JouleLossesH ;
+    Value {
+      If(Flag_ComplexReluctivity) // Frequency domain
+        Integral { [ SymmetryFactor*AxialLength*Re[ {d a}*Conj[ nuOm[]*{d a} ] ] ];
+          In DomainLamC ; Jacobian Vol ; Integration II;}
+      Else // Time domain
+        Integral { [ SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_0_0*SquNorm[Dt[{d a}]] ] ;
+          In DomainLamC ; Jacobian Vol ; Integration II; }
+        If (ORDER>1)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_2_2*SquNorm[Dt[{b_2}]] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_0_2*Dt[{d a}]*Dt[{b_2}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>2)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_4_4*SquNorm[Dt[{b_4}] ] ];
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_2_4*Dt[{b_2}]*Dt[{b_4}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>3)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_6_6*SquNorm[Dt[{b_6}] ] ];
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_4_6*Dt[{b_4}]*Dt[{b_6}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+      EndIf
+    } }
+
+  { Name MagEnergyH ; // this is only ok in the linear case
+    Value {
+      If(!NbrRegions[Domain_NL])
+        Integral { [ SymmetryFactor * AxialLength * nu[] * {d a} * Dt[{d a}] ] ;
+          In DomainLam ; Jacobian Vol ; Integration II; }
+        If (ORDER>1)
+          Integral { [ SymmetryFactor * AxialLength * p_2 * nu[] * {b_2} * Dt[Dt[{b_2}]] ] ;
+            In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>2)
+          Integral { [ SymmetryFactor * AxialLength * p_4 * nu[] * {b_4} * Dt[Dt[{b_4}]] ] ;
+            In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+      Else
+        // +++ What follows have to be checked... I think the crossed terms should appear, like in the formulation
+        // quid of the integration points in the thickness of the lamination ...
+        If(ORDER==0 || ORDER==1)
+          Integral { [ SymmetryFactor * AxialLength * nu[{d a}] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER == 2)
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2})/fillfactor] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2})/fillfactor] * {b_2} * Dt[Dt[{b_2}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER == 3)
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {b_2} * Dt[Dt[{b_2}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {b_4} * Dt[Dt[{b_4}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+
+      EndIf
+
+    }
+  }
+
+Return
diff --git a/HomogenisationLaminations/lam_hyst/homog_laminations.pro b/HomogenisationLaminations/lam_hyst/homog_laminations.pro
new file mode 100644
index 0000000..7c5edfd
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/homog_laminations.pro
@@ -0,0 +1,447 @@
+
+Include "BH.pro"; // nonlinear materials
+
+DefineConstant[
+  // Symmetry
+  AxialLength = 1,
+  SymmetryFactor = 1,
+  // Simulation parameters
+  visu = {1, Choices{0, 1}, AutoCheck 0,
+    Name StrCat[mfem,"Visu/Real-time maps"], Highlight "LawnGreen"}
+  Clean_Results = {0, Choices {0,1},
+    Name StrCat[mfem,"000Remove previous result files"],  Highlight "Red"},
+
+  // Nonlinear iterations
+  Nb_max_iter = {50, Name StrCat[mfem,"8Nonlinear solver/Max. num. iterations"], Visible Flag_NL, Highlight "AliceBlue", Closed}
+  relaxation_factor = {1., Name StrCat[mfem,"8Nonlinear solver/Relaxation factor"], Visible Flag_NL, Highlight "AliceBlue"}
+  stop_criterion = {1e-4, Name StrCat[mfem,"8Nonlinear solver/Stopping criterion"], Visible Flag_NL, Highlight "AliceBlue"}
+
+  // time loop, defaut values
+  time0      = {0, Name StrCat[mfem,"7Time solver/00initial instant"], Visible Flag_AnalysisType==1, Closed}
+  NbT        = {1, Name StrCat[mfem,"7Time solver/02nbr of periods"],  Visible Flag_AnalysisType==1, Highlight "AliceBlue"}
+  timemax    = {NbT*T, Name StrCat[mfem,"7Time solver/01final instant"], ReadOnly, Visible Flag_AnalysisType==1, Highlight "LightGrey"}
+  NbSteps    = {2*120, Name StrCat[mfem,"7Time solver/03steps per period"], Visible Flag_AnalysisType==1, Highlight "AliceBlue"}
+  delta_time = {T/NbSteps, Name StrCat[mfem,"7Time solver/04step or deltatime"], ReadOnly, Visible Flag_AnalysisType==1, Highlight "LightGrey"}
+
+  // ResDir = "resFloop/",
+  ResDir = "res_cost/",
+  ExtGmsh = ".pos",
+  ExtGnuplot = ".dat"
+
+  R_ = {"Analysis", Name "GetDP/1ResolutionChoices", Visible 1}
+  C_ = {"-solve -v 3 -v2", Name "GetDP/9ComputeCommand", Visible 1}
+  P_ = {"", Name "GetDP/2PostOperationChoices", Visible 1}
+];
+
+Group{
+  DefineGroup[DomainLam, DomainLamCC, DomainLamC];
+}
+
+
+Function {
+
+  mu0 = 4.e-7 * Pi ;
+  nu0 = 1./mu0;
+
+  mu_fe = mu0*mur_fe ;
+  nu_fe = nu0/mur_fe ;
+
+  nu[ #{Air,Ind} ]  = 1./mu0 ;
+  fillfactor = (Flag_HomogType==0) ? 1.:fillfactor;
+
+  Printf("===> Checking fillfactor %g", fillfactor);
+
+  sigma [ #{Ind} ]  = 5.9e7 ;
+  sigma [ #{Iron} ] = sigma_fe ;
+  rho[] = 1/sigma[] ;
+
+  nu_lin[] = nu_fe/fillfactor;
+
+  If(!NbrRegions[Domain_NL]) // Linear case
+    If(!Flag_ComplexReluctivity)
+      Printf("===> using LINEAR law");
+      nu[#{Iron}] = nu_lin[] ;
+      dhdb_NL[ #{Iron} ]   = dhdb_lin_NL[$1] ;
+    EndIf
+  Else
+    Printf("===> using NON LINEAR law");
+    If(!Flag_Hysteresis)
+      If(Flag_NonlinearLawType==0)
+        Printf("===> testing NON LINEAR case with LINEAR law");
+        nu[#{Iron}] = nu_lin[] ;
+        dhdb_NL[ #{Iron} ]   = dhdb_lin_NL[$1] ;
+      EndIf
+      If(Flag_NonlinearLawType==1)
+        Printf("===> 3kW machine NON LINEAR law");
+        nu[ #{Iron} ] = nu_3kW[$1] ;
+        h[ #{Iron} ] = h_3kW[$1] ;
+        dhdb_NL[ #{Iron} ]= dhdb_3kW_NL[$1] ;
+        dhdb[ #{Iron} ]   = dhdb_3kW[$1] ;
+      EndIf
+      If(Flag_NonlinearLawType==2)
+        Printf("===> anhysteretic NON LINEAR law corresponding to Jiles-Atherton params");
+        nu[ #{Iron} ] = nu_anhys[$1] ;
+        h[ #{Iron} ] = h_anhys[$1] ;
+        dhdb_NL[ #{Iron} ]= dhdb_anhys_NL[$1] ;
+        dhdb[ #{Iron} ]   = dhdb_anhys[$1] ;
+      EndIf
+    Else
+      Printf("===> Hysteretic NON LINEAR law => Jiles-Atherton model");
+    EndIf
+  EndIf
+
+  relaxation_function[] = ($Iteration<Nb_max_iter/2) ? relaxation_factor : 0.2 ;
+  relax_max = 1;
+  relax_min = 1/10;
+  relax_numtest=10;
+  test_all_factors=0;
+  relaxation_factors_lin() = LinSpace[relax_max,relax_min,relax_numtest];
+
+}
+
+
+Jacobian {
+  { Name Vol ; Case { { Region All ; Jacobian Vol ; } } }
+  { Name Sur ; Case { { Region All ; Jacobian Sur ; } } }
+  { Name Lin ; Case { { Region All ; Jacobian Lin ; } } }
+}
+
+Integration {
+  { Name II ; Case {
+      { Type Gauss ;
+        Case {
+          { GeoElement Line        ; NumberOfPoints  4 ; } // 1:20
+          { GeoElement Triangle    ; NumberOfPoints  6 ; } // 1, 3, 4, 6, 7, 12, 13, 16
+          { GeoElement Quadrangle  ; NumberOfPoints  7 ; } // 1, 3, 4, 7
+        }
+      }
+    }
+  }
+
+  { Name I1p ;
+    Case {
+      { Type Gauss ;
+        Case {
+          { GeoElement Triangle    ; NumberOfPoints  1 ; }
+          { GeoElement Quadrangle  ; NumberOfPoints  1 ; } // 1, 3, 4, 7
+        }
+      }
+    }
+  }
+}
+
+
+
+FunctionSpace {
+
+  { Name Hcurl_a; Type Form1;
+    BasisFunction {
+      { Name se ; NameOfCoef ae ; Function BF_Edge ;
+        Support Domain ; Entity EdgesOf[ All ] ; }
+    }
+    Constraint {
+      { NameOfCoef ae; EntityType EdgesOf ; NameOfConstraint MagneticVectorPotential; }
+      { NameOfCoef ae; EntityType EdgesOfTreeIn ; EntitySubType StartingOn ;
+        NameOfConstraint Gauge_av ; }
+    }
+  }
+
+  { Name Hgrad_u; Type Form0;
+    BasisFunction {
+      { Name su ; NameOfCoef un ; Function BF_Node ;
+        Support DomainC ; Entity NodesOf[ All ] ; }
+    }
+    Constraint {
+      { NameOfCoef un; EntityType NodesOf ; NameOfConstraint ElectricScalarPotential; }
+    }
+  }
+
+  // Current in stranded coil (3D)
+  { Name Hregion_i ; Type Scalar ;
+    BasisFunction {
+      { Name sr ; NameOfCoef ir ; Function BF_Region ;
+        Support DomainS0 ; Entity DomainS0 ; }
+    }
+    GlobalQuantity {
+      { Name Is ; Type AliasOf        ; NameOfCoef ir ; }
+      { Name Us ; Type AssociatedWith ; NameOfCoef ir ; }
+    }
+    Constraint {
+      { NameOfCoef Us ; EntityType Region ; NameOfConstraint Voltage ; }
+      { NameOfCoef Is ; EntityType Region ; NameOfConstraint Current ; }
+    }
+  }
+
+  // BFs for case with hysteresis
+  { Name H_hysteresis ; Type Vector;
+    BasisFunction {
+      { Name sex ; NameOfCoef aex ; Function BF_VolumeX ; Support Domain ; Entity VolumesOf[ All ] ; }
+      { Name sey ; NameOfCoef aey ; Function BF_VolumeY ; Support Domain ; Entity VolumesOf[ All ] ; }
+      { Name sez ; NameOfCoef aez ; Function BF_VolumeZ ; Support Domain ; Entity VolumesOf[ All ] ; }
+    }
+  }
+
+}
+
+
+If(Flag_HomogType)
+  Include "Macro_homogenisation_laminations.pro";
+EndIf
+
+
+Formulation {
+
+  { Name MagStaDyn_av ; Type FemEquation ;
+    Quantity {
+      { Name a ; Type Local  ; NameOfSpace Hcurl_a ; }
+
+      // Massive conductor (DomainC)
+      { Name v ; Type Local  ; NameOfSpace Hgrad_u ; }
+
+      // Source: Stranded conductor (DomainB)
+      { Name ir ; Type Local  ; NameOfSpace Hregion_i ; }
+      { Name Us ; Type Global ; NameOfSpace Hregion_i[Us] ; }
+      { Name Is ; Type Global ; NameOfSpace Hregion_i[Is] ; }
+
+      If(Flag_Hysteresis)
+        { Name h ; Type Local ; NameOfSpace H_hysteresis ; }
+      EndIf
+
+
+      If(Flag_HomogType>0)
+        // Homogenized laminations
+        For k In {2:ORDERMAX} // b_2, b_4, b_6
+          { Name b~{2*k-2}  ; Type Local ; NameOfSpace Hb~{2*k-2} ; }
+        EndFor
+        If(Flag_Hysteresis)
+          For i In {1:nbrQuadraturePnts}
+            { Name h~{i} ; Type Local ; NameOfSpace H_hysteresis~{i} ; }
+          EndFor
+        EndIf
+      EndIf
+    }
+
+    Equation {
+      Galerkin { [ nu[] * Dof{d a} , {d a} ]     ;
+        In Domain_L  ; Jacobian Vol ; Integration II ; }
+
+
+      If(NbrRegions[Domain_NL])
+        If( (Flag_HomogType==0) || (Flag_HomogType && ORDER==1))
+          If(!Flag_Hysteresis)
+            Galerkin { [ nu[{d a}/fillfactor] * Dof{d a} , {d a} ]     ;
+              In Domain_NL  ; Jacobian Vol ; Integration II ; }
+            Galerkin { JacNL [ 1/fillfactor*dhdb_NL[{d a}] * Dof{d a} , {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration II ; }
+          Else
+            Galerkin { [ SetVariable[
+                  h_Jiles[ {h}[1],
+                    {d a}[1]/fillfactor,
+                    {d a}/fillfactor ]{List[hyst_FeSi]},
+                  QuadraturePointIndex[] ]{$hjiles}, {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+            Galerkin { JacNL[ 1/fillfactor*dhdb_Jiles[
+                  {h},
+                  {d a}/fillfactor,
+                  {h}-{h}[1] ]{List[hyst_FeSi]} * Dof{d a} , {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+
+            // h_Jiles saved in local quantity {h}
+            // BF is constant per element => 1 integration point is enough
+            Galerkin { [ Dof{h}   , {h} ]  ; // saving h_Jiles in local quantity h
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+            Galerkin { [ -GetVariable[QuadraturePointIndex[]]{$hjiles} , {h} ]  ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+          EndIf
+        EndIf
+      EndIf
+
+      Galerkin { DtDof[ sigma[] * Dof{a} , {a} ] ;
+        In DomainC ; Jacobian Vol ; Integration II ; }
+      Galerkin { [ sigma[] * Dof{d v} , {a} ] ;
+        In DomainC ; Jacobian Vol ; Integration II ; }
+      Galerkin { DtDof[ sigma[] * Dof{a} , {d v} ] ;
+        In DomainC ; Jacobian Vol ; Integration II ; }
+      Galerkin { [ sigma[] * Dof{d v} , {d v} ] ;
+        In DomainC ; Jacobian Vol ; Integration II ; }
+
+      // Galerkin { [ -js[], {a} ] ;
+      //  In DomainS0 ; Jacobian Vol ; Integration II ; }
+      Galerkin { [ -Idir[] * Dof{ir}, {a} ] ;
+        In DomainS0 ; Jacobian Vol ; Integration II ; }
+
+      If(Flag_HomogType>0)
+        If(!Flag_ComplexReluctivity && Flag_AnalysisType>0)// Either additional terms or complex nu in DomainLam
+          Call Macro_Terms_DomainLamC_sigma;
+          If(!Flag_Hysteresis)
+            Call Macro_Terms_DomainLam_nu;
+          Else
+            Call Macro_Terms_DomainLam_hysteresis;
+          EndIf
+        EndIf
+      EndIf
+
+    }
+  }
+
+
+
+}
+
+//======================================================================
+
+Resolution {
+
+  { Name Analysis ;
+    System {
+      If( (Flag_AnalysisType<2) || NbrRegions[Domain_NL])
+        { Name Sys_Mag ; NameOfFormulation MagStaDyn_av ;}
+      Else
+        { Name Sys_Mag ; NameOfFormulation MagStaDyn_av ; Frequency Freq; }
+      EndIf
+    }
+    Operation {
+
+      If(Clean_Results)
+        // SystemCommand[StrCat["rm -rf ", ResDir]];
+        SystemCommand[StrCat["rm -rf ", ResDir, "*.pos"]];
+        SystemCommand[StrCat["rm -rf ", ResDir, "*.dat"]];
+      EndIf
+      CreateDir[ResDir];
+
+      If(Flag_AnalysisType!=1)
+        If(!NbrRegions[Domain_NL])
+          Generate[Sys_Mag] ; Solve[Sys_Mag] ;
+        Else
+          IterativeLoop[Nb_max_iter, stop_criterion, relaxation_factor]{
+            GenerateJac[Sys_Mag] ; SolveJac[Sys_Mag] ; }
+        EndIf
+        SaveSolution [Sys_Mag] ;
+
+        Test[ GetNumberRunTime[visu]{StrCat[mfem,"Visu/Real-time maps"]} ]{
+          PostOperation[Get_LocalFields];
+        }
+        PostOperation[Get_GlobalQuantities];
+      Else // time domain
+
+        InitSolution[Sys_Mag];
+        TimeLoopTheta[time0, timemax, delta_time , 1.]{
+          If(!NbrRegions[Domain_NL])
+            Generate[Sys_Mag] ; Solve[Sys_Mag] ;
+          Else
+          IterativeLoop[Nb_max_iter, stop_criterion, relaxation_function[]]{
+              GenerateJac[Sys_Mag] ;
+              //If(!Flag_Hysteresis)
+                SolveJac[Sys_Mag] ;
+                //Else
+                //SolveJac_AdaptRelax[Sys_Mag, relaxation_factors_lin(), test_all_factors ] ;
+                //EndIf
+            }
+          EndIf
+          SaveSolution [Sys_Mag] ;
+          Test[ GetNumberRunTime[visu]{StrCat[mfem,"Visu/Real-time maps"]} ]{
+            PostOperation[Get_LocalFields];
+          }
+          PostOperation[Get_GlobalQuantities];
+        }
+
+      EndIf
+
+
+    }
+  }
+
+}
+
+
+PostProcessing {
+
+  { Name MagStaDyn_av ; NameOfFormulation MagStaDyn_av ;
+    PostQuantity {
+      { Name a  ; Value { Local { [ {a} ]            ; In Domain ; Jacobian Vol ; } } }
+      { Name b  ; Value { Local { [ {d a} ]          ; In Domain ; Jacobian Vol ; } } }
+      { Name bz ; Value { Local { [ CompZ[{d a}] ]   ; In Domain ; Jacobian Vol ; } } }
+      { Name h  ; Value {
+          Local { [ nu[]*{d a} ] ; In Domain_L ; Jacobian Vol ; }
+          If(!Flag_Hysteresis)
+            Local { [ nu[{d a}]*{d a} ] ; In Domain_NL ; Jacobian Vol ; }
+          Else
+            Local { [ {h} ] ; In Domain_NL ; Jacobian Vol ; }
+          EndIf
+        }
+      }
+      If(Flag_Hysteresis)
+        { Name hdb  ; Value { // Useful for computing losses in hysteretic case, by integrating in one period (steady state)
+            Local { [ {h}*({d a}-{d a}[1]) ] ; In Domain_NL  ; Jacobian Vol ; }
+          }
+        }
+      EndIf
+
+      { Name v ; Value { Term { [ {v} ]              ; In DomainC ; Jacobian Vol ;} } }
+      { Name e ; Value { Term { [ -(Dt[{a}]+{d v}) ] ; In DomainC ; Jacobian Vol ;} } }
+
+      { Name j ; Value { Term { [ -sigma[]*(Dt[{a}]+{d v}) ] ; In DomainC ; Jacobian Vol ;} } }
+      { Name normj ; Value { Term { [ Norm[-sigma[]*(Dt[{a}]+{d v})] ] ; In DomainC ; Jacobian Vol ;} } }
+
+      { Name Jtot ; Value {
+          Integral { [ SymmetryFactor*AxialLength*(-sigma[]*(Dt[{a}]+{d v})) ] ;
+            In DomainC ; Jacobian Vol ; Integration II; } } }
+
+      { Name ir ; Value { Local { [ {ir} ]  ; In DomainS0 ; Jacobian Vol ; } } } // Source
+      { Name Isrc ; Value { Integral { [ SymmetryFactor*AxialLength*{ir} ]  ;
+            In DomainS0 ; Jacobian Vol ; Integration II ; } } } // Source
+      // { Name js ; Value { Local { [ js[] ]       ; In DomainS0 ; Jacobian Vol ; } } } // Source
+      { Name js ; Value { Local { [ Idir[] * {ir} ]  ; In DomainS0 ; Jacobian Vol ; } } } // Source
+
+      { Name Flux ; Value { Integral { [ SymmetryFactor*AxialLength * Idir[] * {a} ] ; // /Sc[] => to add => now in matlab files
+            In DomainS0 ; Jacobian Vol ; Integration II ; } } }
+
+      { Name ComplexPower ; Value { // real part -> eddy current losses; imag part-> magnetic energy
+          Integral { [ SymmetryFactor*AxialLength*Complex[ SquNorm[sigma[]*(Dt[{a}]+{d v}/SymmetryFactor)]/sigma[], nu[]*SquNorm[{d a}] ] ] ;
+            In Iron; Jacobian Vol ; Integration II ; }
+        }
+      }
+
+      { Name EddyCurrentLosses ;
+        Value {
+          Integral { [ SymmetryFactor*AxialLength*sigma[]*SquNorm[Dt[{a}]+{d v}/SymmetryFactor] ] ;
+            In Iron ; Jacobian Vol ; Integration II ; }
+        }
+      }
+
+      { Name MagneticEnergy ;
+        Value {
+          If(!Flag_Hysteresis)
+            Integral {
+              [ SymmetryFactor*AxialLength* nu[{d a}]*SquNorm[{d a}] ] ;
+              In Domain ; Jacobian Vol ; Integration II ; }
+          Else
+            Integral {
+              [ SymmetryFactor*AxialLength* nu[{d a}]*SquNorm[{d a}] ] ;
+              In Domain_L ; Jacobian Vol ; Integration II ; }
+            Integral {
+              [ SymmetryFactor*AxialLength* {h}*{d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration II ; }
+          EndIf
+        }
+      }
+
+      If(Flag_HomogType>0)
+        Call PostQuantities_Homog;
+      EndIf
+
+    }
+  }
+
+
+}
+
+
+
+PostOperation ViewTree UsingPost MagStaDyn_av {
+  // Print the tree for debugging purposes.
+  PrintGroup[ EdgesOfTreeIn[ { DomainGauge }, StartingOn { Surface_NoGauge_av } ],
+    In DomainGauge, File StrCat[ResDir,"Tree.pos"] ];
+    Echo[ Str["l=PostProcessing.NbViews-1;","View[l].ColorTable = { DarkRed };","View[l].LineWidth = 5;"] ,
+      File StrCat[ResDir,"tmp.geo"], LastTimeStepOnly] ;
+}
diff --git a/HomogenisationLaminations/lam_hyst/lam2d.geo b/HomogenisationLaminations/lam_hyst/lam2d.geo
new file mode 100644
index 0000000..784789b
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/lam2d.geo
@@ -0,0 +1,443 @@
+Include "lam2d_data.pro" ;
+
+ff = 1 ;
+
+Mesh.CharacteristicLengthFactor = 0.85/ff ;
+
+Mesh.Algorithm = 1; // 2D mesh algorithm (1=MeshAdapt, 2=Automatic, 5=Delaunay, 6=Frontal, 7=bamg, 8=delquad)
+Geometry.CopyMeshingMethod = 1; // Copy meshing method when duplicating geometrical entities?
+
+//Mesh.SurfaceFaces = 1; // Display faces of surface mesh?
+
+// Some common characteristic lengths
+//====================================
+
+pind = h/10 ;
+lca = pind; // lc for air
+
+Lay1 = ff*14; Pro1 = 0.8; // 14 horizontal divisions of the laminations
+Lay3 = (Flag_Fine>1) ? 2/2+1 : ff*11;
+Bwidth=1;  // vertical divisions of one lamination, no bump if Bwidth == 1
+Lay3_tot = 2/2*(nlam/2)+1 ;  // 22 vertical divisions of the stack ==> homogenised model
+
+Lay_isol_between_iron =(!Flag_HomogType) ? 4/2 : 2; //+++ only one division for isol
+
+plam = dlam/Lay3 ;
+
+Lay1_isol1 = ff*4 ; Bisolal1 = 1; // Isol with slight conductivity
+
+
+
+//=====================================
+// First lamination -- up to down
+//=====================================
+
+pl0[] += newp; Point(newp) = {xlam, ylam, 0, plam};
+pl0[] += newp; Point(newp) = {xlam, (Flag_Fine) ? ylam-dlam : 0, 0, plam};
+pl0[] += newp; Point(newp) = {0,    (Flag_Fine) ? ylam-dlam : 0, 0, plam};
+pl0[] += newp; Point(newp) = {0,    ylam, 0, plam};
+
+For k In {0:3}
+  ll0[] += newl; Line(newl) = {pl0[k], pl0[(k==3?0:k+1)]};
+EndFor
+
+Line Loop(newll) = {ll0[]};
+surfIron[] +=news; Plane Surface(news) = {newll-1};
+laxis_iron[] += ll0[2] ;
+lborder_iron[] +=ll0[0];
+
+// Iron
+Transfinite Line{-ll0[1],ll0[3]} = Lay1 Using Progression Pro1 ;
+Transfinite Line{ll0[{0,2}]} = (Flag_Fine?Lay3:Lay3_tot) Using Bump Bwidth;
+
+// pli[] += newp; Point(newp) = {xlam+w_sc, ylam, 0, plam};
+// pli[] += newp; Point(newp) = {xlam+w_sc, (Flag_Fine) ? ylam-dlam : 0, 0, plam};
+
+// lli[] += newl; Line(newl) = {pl0[0], pli[0]};
+// lli[] += newl; Line(newl) = {pli[0], pli[1]};
+// lli[] += newl; Line(newl) = {pli[1], pl0[1]};
+
+// Line Loop(newll) = {-ll0[0],lli[]};
+// surfIsol_side1[] +=news; Plane Surface(news) = {newll-1};
+
+//short circuit bar
+// Transfinite Line{lli[{0,2}]} = Lay1_isol1 Using Progression Bisolal1;
+// Transfinite Line{lli[{1}]} = (Flag_Fine?Lay3:Lay3_tot) Using Bump Bwidth;
+
+//=====================================
+// Inductor
+//=====================================
+phi = Pi/4;
+
+dla_ind = rla_ind * Cos[phi] ;
+
+xind1 = xlam + dla_ind ;
+xind2 = xlam + dla_ind + w_ind ;
+yind1 = ylam ;
+yind2 = ylam + dla_ind;
+
+pi[]+=newp ; Point(newp) = { xind1, 0,      0, pind};
+pi[]+=newp ; Point(newp) = { xind2, 0,      0, pind};
+pi[]+=newp ; Point(newp) = { xind2, yind1,  0, pind};
+pi[]+=newp ; Point(newp) = { xind1, yind1,  0, pind};
+
+li[]+=newl ; Line(newl) = {pi[0],pi[1]};
+li[]+=newl ; Line(newl) = {pi[1],pi[2]};
+li[]+=newl ; Line(newl) = {pi[2],pi[3]};
+li[]+=newl ; Line(newl) = {pi[3],pi[0]};
+Line Loop(newll) = {li[{0:3}]};
+surfind[] += news ; Plane Surface(news) = {newll-1};
+
+pi[]+=newp ; Point(newp) = { xlam, yind2,       0, pind};
+pi[]+=newp ; Point(newp) = { xlam, yind2+w_ind, 0, pind};
+pi[]+=newp ; Point(newp) = { 0, yind2+w_ind, 0, pind};
+pi[]+=newp ; Point(newp) = { 0, yind2,       0, pind};
+
+li[]+=newl ; Line(newl) = {pi[0+4],pi[1+4]};
+li[]+=newl ; Line(newl) = {pi[1+4],pi[2+4]};
+li[]+=newl ; Line(newl) = {pi[2+4],pi[3+4]};
+li[]+=newl ; Line(newl) = {pi[3+4],pi[0+4]};
+Line Loop(newll) = {li[{4:7}]};
+surfind[] += news ; Plane Surface(news) = {newll-1};
+
+ci[]+=newl ; Circle(newl) = {pi[3],pl0[0],pi[4]};
+ci[]+=newl ; Circle(newl) = {pi[2],pl0[0],pi[5]};
+
+Line Loop(newll) = {ci[0],li[4],-ci[1],li[2]};
+surfind[] += news ; Plane Surface(news) = {newll-1};
+
+// Inductor
+Transfinite Line{li[{0,2,4,6}]} = 2; // 3width inductor //Ceil[w_ind/pind] ;
+Transfinite Line{ci[]} = 7; // rounded part of inductor //Ceil[w_ind/pind]+1 ;
+Transfinite Line{li[{1,3}]} = nlam ;
+Transfinite Line{li[{5,7}]} = Lay1+3*2 ;
+
+Transfinite Surface "*" ;
+If(Flag_Recombine)
+  Recombine Surface "*" ;
+EndIf
+
+
+bndind[] += Abs(CombinedBoundary{Surface{surfind[]};});
+bndind_out[]+= {-bndind[3],bndind[7],-bndind[1]};
+bndind_in[]+= {bndind[5], -bndind[6], bndind[2]};
+
+cen0 = newp ; Point(cen0) = {0, 0, 0, pind};
+
+
+
+If(Flag_Fine)
+  //=====================================
+  // First isolation -- up to down
+  //=====================================
+  pe0[] += newp; Point(newp) = {xlam, ylam-e, 0, plam};
+  pe0[] += newp; Point(newp) = {0,    ylam-e, 0, plam};
+
+  le0[] += newl; Line(newl) = {pl0[1], pe0[0]};
+  le0[] += newl; Line(newl) = {pe0[0], pe0[1]};
+  le0[] += newl; Line(newl) = {pe0[1], pl0[2]};
+
+  laxis[] += le0[2];
+
+  Line Loop(newll) = {le0[], -ll0[1]};
+  surfIsol[] +=news; Plane Surface(news) = {newll-1};
+
+  // Isolation between iron
+  Transfinite Line{le0[{0,2}]} = Lay_isol_between_iron ;
+  Transfinite Line{-le0[1]} = Lay1 Using Progression Pro1 ;
+
+  If(nlam==2)
+    ldown[] = le0[1];
+    ledge[] = le0[0];
+  EndIf
+
+  For ii In {1:nlam/2-1}
+    surfIron[] += Translate {0, -ii*e,0} { Duplicata { Surface{surfIron[0]}; } };
+    aux[] = Boundary{Surface{surfIron[ii]};};
+    skinIron[]   += aux[] ;
+    laxis_iron[] += aux[2] ;
+
+    lborder_iron[] += aux[0];
+  EndFor
+  For ii In {1:nlam/2-1}
+    surfIsol[] += Translate {0, -ii*e,0} { Duplicata { Surface{surfIsol[0]}; } };
+    aux[] = Boundary{Surface{surfIsol[ii]};};
+    laxis[] += aux[2] ;
+    ldown[] += aux[1] ;
+    ledge[] += aux[0];
+  EndFor
+
+  nn=#ldown[];
+  pstomv[] = Boundary{Line{ldown[{nn-1}]};};
+
+  Translate {0, de/2,0} { Point{pstomv[]}; }
+
+
+  pntedge[] = Boundary{Line{ledge[#ledge[]-1]};};
+  lai[]+=newl; Line(newl) = {pntedge[1], pi[0]};
+  lai[]+=newl; Line(newl) = {pi[7], pl0[3]};
+
+
+  bndironisol[] = CombinedBoundary{
+    Surface{surfIron[],surfIsol[]};};
+
+  Transfinite Surface "*";
+  If(Flag_Recombine)
+    Recombine Surface "*" ;
+  EndIf
+
+  bndironisol[] -={laxis[], laxis_iron[],ldown[{#ldown[]-3:#ldown[]-1}]};
+  llairout = newll ; Line Loop(newll) = {bndironisol[], lai[], -bndind_in[]} ;
+
+  surfair[]   += news ; Plane Surface(news) = {llairout};
+
+  lines_sym[] += {ldown[{#ldown[]-1}],lai[0]};
+EndIf
+
+
+If(!Flag_Fine)
+  surfIsol[]={};
+  volisol[]={};
+  laxis[]={};
+  lai[]+= newl; Line(newl) = {pl0[1], pi[0]};
+  lai[]+= newl; Line(newl) = {pi[7],  pl0[3]};
+
+llairout   = newll ; Line Loop(newll) = {bndind_in[], -lai[{0}],-ll0[{3,0}],-lai[1]} ;
+  surfair[] += news ; Plane Surface(news) = {llairout};
+  lines_sym[] += {ll0[1],lai[0]};
+EndIf
+
+
+lines_symy0[] = {lines_sym[],li[0]}; // middle
+lines_symx0[] = {laxis[], laxis_iron[], lai[1], li[6]}; // axis
+lines_bnd[]   = {li[{1,5}],ci[1]}; // without air outside the coil
+
+
+// Symmetry with regard to y-axisO
+//====================================================
+surfIronD[] = {}; lborder_ironD[]={};
+
+If(!Flag_Symmetry || Flag_Symmetry==1)
+  // For convenience, symmetry of the lines where bnd conditions are imposed
+  lborder_iron[] += Symmetry {1,0,0,0} { Duplicata{Line{lborder_iron[]};} };
+
+  lines_symy0[] += Symmetry {1,0,0,0} { Duplicata{Line{lines_symy0[]};} };
+
+  lines_bnd[] += Symmetry {1,0,0,0} { Duplicata{Line{lines_bnd[]};} };
+
+  nnk = (Flag_Fine)?nlam/2:1;
+  For k In {0:nnk-1}
+    surfIron[] += Symmetry {1,0,0,0} { Duplicata{Surface{surfIron[k]};} };
+    If(Flag_Fine)
+      surfIsol[] += Symmetry {1,0,0,0} { Duplicata{Surface{surfIsol[k]};} };
+    EndIf
+  EndFor
+
+  surfind[]  += Symmetry {1,0,0,0} { Duplicata{Surface{surfind[]};} };
+  surfair[]  += Symmetry {1,0,0,0} { Duplicata{Surface{surfair[]};} };
+
+  // Complete model => Symmetry of the half model
+  // ==============
+
+  If(Flag_Symmetry==0)
+    lborder_ironD[] = Symmetry {0,1,0,0} { Duplicata{Line{lborder_iron[]};} };
+    lines_bnd[] += Symmetry {0,1,0,0} { Duplicata{Line{lines_bnd[]};} };
+
+    kk = #surfIron[];
+    For k In {0:kk-1}
+      surfIronD[]      += Symmetry {0,1,0,0} { Duplicata{Surface{surfIron[k]};} };
+
+      If(Flag_Fine)
+        surfIsol[] += Symmetry {0,1,0,0} { Duplicata{Surface{surfIsol[k]};} };
+       EndIf
+    EndFor
+
+    surfind[]  += Symmetry {0,1,0,0} { Duplicata{Surface{surfind[]};} };
+    surfair[]  += Symmetry {0,1,0,0} { Duplicata{Surface{surfair[]};} };
+  EndIf
+
+EndIf
+
+
+// Physical regions
+//====================================================
+
+Physical Surface("air",AIR) = {surfair[]} ;
+Physical Surface("inductor",IND) = {surfind[]} ;
+Physical Surface("insulation",ISOL) = {surfIsol[]} ;
+
+
+If(Flag_Fine)
+  nni = nlam/2;
+  For ii In {0:nni-1}
+    // 1/4 of geometry => common to all cases (Flag_Symmetry==2)
+    Physical Surface(Sprintf("iron %g", ii),IRON+ii)  = surfIron[{ii}];
+    Physical Line(Sprintf("skin iron (right side) %g",ii), SKINIRON_R+ii) = lborder_iron[{ii}];
+
+    If(Flag_Symmetry==2)
+      Physical Line(Sprintf("elec iron (middle) %g",ii), ELECIRON+ii) = laxis_iron[{ii}] ;
+    EndIf
+
+    If(Flag_Symmetry<2) // Complete ==0 or half geometry ==1
+      Physical Surface(Sprintf("iron %g", ii), IRON+ii) += surfIron[{ii+nni}]; // left side
+      Physical Line(Sprintf("skin iron (left side) %g",ii), SKINIRON_L+ii) = lborder_iron[{ii+nni}];
+
+      If(Flag_Symmetry==0)
+        Physical Surface(Sprintf("iron %g",nlam-ii-1),IRON+nlam-ii-1)  = surfIronD[{ii, ii+nni}];
+        Physical Line(Sprintf("skin iron (right side) %g",nlam-ii-1), SKINIRON_R+nlam-ii-1) = lborder_ironD[{ii}];
+        Physical Line(Sprintf("skin iron (left side) %g",nlam-ii-1), SKINIRON_L+nlam-ii-1) = lborder_ironD[{ii+nni}];
+      EndIf
+    EndIf
+
+    allSkinIron_i[] =  Abs( CombinedBoundary{ Physical Surface{IRON+ii}; } );
+    allSkinIron_i[] -= {laxis_iron[],lborder_iron[]};
+    Physical Line(Sprintf("skin iron %g", ii), SKINIRON+ii) = allSkinIron_i[] ;
+
+    If(Flag_Symmetry==0)
+      allSkinIron_iD[] =  Abs( CombinedBoundary{ Physical Surface{IRON+nlam-ii-1}; } );
+      allSkinIron_iD[] -= {laxis_iron[],lborder_iron[], lborder_ironD[]};
+      Physical Line(Sprintf("skin iron %g", nlam-ii-1), SKINIRON+nlam-ii-1) = allSkinIron_iD[] ;
+    EndIf
+  EndFor
+
+  allIronIsol[] =  Abs( CombinedBoundary{Surface{surfIron[],surfIronD[],surfIsol[]};} );
+  allIronIsol[] -= {lines_symy0[],lines_symx0[]};
+  Physical Line(Sprintf("skin iron + isol"), SKINMETAL) = allIronIsol[] ;
+EndIf
+
+If(!Flag_Fine)
+  Physical Surface("iron (homog)", IRON)  = {surfIron[],surfIronD[]};
+  allSkinIron[]  = Abs(CombinedBoundary{Surface{surfIron[],surfIronD[]};});
+
+  skinmetal[] = allSkinIron[];
+  skinmetal[] -= {lines_symy0[], lines_symx0[]};
+  Physical Line(Sprintf("skin metal"), SKINMETAL) = skinmetal[] ;
+
+  allSkinIron[] -= {laxis_iron[],lborder_iron[],lborder_ironD[]};
+
+  Physical Line("elec iron", ELECIRON) = laxis_iron[] ;
+
+  If(Flag_Symmetry==0) // Complete model model
+    Physical Line("skin iron (top, bottom)", SKINIRON) = allSkinIron[];
+    Physical Line("skin iron (right)", SKINIRON_R) = {lborder_iron[0], lborder_ironD[0]} ;
+    Physical Line("skin iron (left)" , SKINIRON_L) = {lborder_iron[1], lborder_ironD[1]} ;
+  EndIf
+  If(Flag_Symmetry==1) //1/2 of the model
+    Physical Line("skin iron (top)", SKINIRON) = allSkinIron[{1,3}];
+    Physical Line("skin iron (right)", SKINIRON_R) = lborder_iron[0] ;
+    Physical Line("skin iron (left)", SKINIRON_L) = lborder_iron[1] ;
+  EndIf
+  If(Flag_Symmetry==2) //1/4 of the model
+    Physical Line("skin iron (top)", SKINIRON) = allSkinIron[{1}];
+    Physical Line("skin iron (right)", SKINIRON_R) = lborder_iron[0] ;
+  EndIf
+
+EndIf
+
+
+//======================================================
+Physical Line("outer boundary", OUTERBND) = lines_bnd[];
+
+
+
+
+If(Flag_Symmetry!=0) // Flag_Symmetry==0 => Complete model: middle does not have to be define in case of complete geo
+  Physical Line("sym y=0", SYMMETRY_Y0)  = lines_symy0[]; // All but inductor and conductors
+EndIf
+
+If(Flag_Symmetry==2)
+  lines_symx0[] -= laxis_iron[]; // Avoiding repetition of elements in physicals...
+  Physical Line("symmetry at x=0, not iron", SYMMETRY_X0) = {lines_symx0[]};
+EndIf
+
+// Not used... just testing purposes (gauging)
+Physical Point(CORNER) = pi[1+1]; // 1 is at x-axis
+
+Color Red { Surface{ surfind[] };}
+Color Cyan { Surface{ surfair[] };}
+Color Cyan { Surface{ surfIsol[] };}
+Color SteelBlue { Surface{ surfIron[], surfIronD[] };}
+
+// Orchid, LightBlue, Gold, LightGreen
+
+// Inverting normals
+Reverse Surface{surfIron[],surfIsol[],surfind[2]};
+
+
+// Gauss integration points along the thickness of the lamination
+//===============================================================
+If(0)
+  Ngp = 5; // nbrQuadraturePoints (half lamination)
+  y_1 = 0.07443716949081559;
+  y_2 = 0.2166976970646236;
+  y_3 = 0.3397047841495122;
+  y_4 = 0.4325316833444923;
+  y_5 = 0.4869532642585858;
+
+  aaa = 0.5;
+
+  For ii In {0:nlam/2-1}
+    For kk In {1:Ngp}
+      pg[]+=newp ; Point(newp) = { aaa*xlam, h/2-d/2+y~{kk}*d-ii*e, 0};
+      pg[]+=newp ; Point(newp) = { aaa*xlam, h/2-d/2-y~{kk}*d-ii*e, 0};
+    EndFor
+  EndFor
+EndIf
+
+// Checking line for post-processing
+//==================================
+If(0)
+  dist_cen = 1e-3;
+  x0 = dist_cen; y0 = 0.;
+  x1 = w_lam/2;  y1 = h/2;
+
+  npts = 30 ;
+
+  For ll In {1:nlam-1:2}
+    For ii In {1:npts-1}
+      If(ll==3)
+      Printf("nlam %g x1=%g",nlam, e*ll/2-dlam/2+ii*dlam/npts);
+      EndIf
+      pl[]+=newp ; Point(newp) = { x0, e*ll/2-dlam/2+ii*dlam/npts ,0};
+    EndFor
+  EndFor
+EndIf
+
+
+// Improving the mesh of the air around the laminations
+//=============================================================
+
+ddl = 0.3*dla_ind;
+
+pmesh[]+=newp ; Point(newp) = {xlam/8,        ylam + ddl, 0., plam};
+pmesh[]+=newp ; Point(newp) = {xlam/4,        ylam + ddl, 0., plam};
+pmesh[]+=newp ; Point(newp) = {xlam/2-xlam/8, ylam + ddl, 0., plam};
+pmesh[]+=newp ; Point(newp) = {xlam/2,        ylam + ddl, 0., plam};
+pmesh[]+=newp ; Point(newp) = {xlam/2+xlam/8, ylam + ddl, 0., plam};
+Point{pmesh[]} In Surface {surfair[0]};
+
+Characteristic Length pl0[3] = (Flag_Fine==0 ? 4:1) * plam;
+
+
+If(!Flag_Symmetry || Flag_Symmetry==1)
+  pmesh_[]  += Symmetry {1,0,0,0} { Duplicata{Point{pmesh[]};} };
+  Point{pmesh_[]} In Surface {surfair[1] };
+
+  If(!Flag_Symmetry) // Just testing
+    pmeshD[]  += Symmetry {0,1,0,0} { Duplicata{Point{pmesh[]};} };
+    pmeshD_[] += Symmetry {0,1,0,0} { Duplicata{Point{pmesh_[]};} };
+
+    Point{pmeshD[]}  In Surface {surfair[2]};
+    Point{pmeshD_[]} In Surface {surfair[3]};
+  EndIf
+EndIf
+
+
+//-------------------------------------------------------------------------------
+// For nice visualization
+//-------------------------------------------------------------------------------
+
+// Hide { Point{ Point {:} }; Line{ Line {:} }; }
+// Hide { Point{ Point {:} }; Line{9,13};}
+
+// Show { Line{ linStator[], linRotor[] }; }
diff --git a/HomogenisationLaminations/lam_hyst/lam2d.pro b/HomogenisationLaminations/lam_hyst/lam2d.pro
new file mode 100644
index 0000000..9415db5
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/lam2d.pro
@@ -0,0 +1,315 @@
+Include "lam2d_data.pro" ;
+
+//--------------------------------------------------------------------------
+
+// gmsh lam2d.geo -2 -setnumber Flag_HomogType 0 -o fine.msh
+// gmsh lam2d.geo -2 -setnumber Flag_HomogType 1 -o block.msh (homogenized block)
+// gmsh lam2d.geo -2 -setnumber Flag_HomogType 2 -o hom2.msh  (homogenized lamination)
+
+//--------------------------------------------------------------------------
+//--------------------------------------------------------------------------
+
+DefineConstant[
+  Flag_AnalysisType = {1,
+    Choices{0="Static",  1="Time domain", 2="Frequency domain"},
+    ServerAction Str["Reset", StrCat[mfem, "00Approx. order"]],
+    Name StrCat[mfem, "100Type of analysis"], Highlight "Blue",
+    Help Str["- Use 'Static' to compute static fields",
+             "- Use 'Time domain' to compute the dynamic response (transient)",
+             "- Use 'Frequency domain' to compute the dynamic response (steady state)"]}
+
+  Freq = {100, Min 0.1, Max 500e3, Name StrCat[mfem,"101Frequency [Hz]"], Visible Flag_AnalysisType>0, Highlight "LightGreen"}
+  Omega  = 2*Pi*Freq
+  T = 1/Freq
+
+  Flag_NL = {!(Flag_AnalysisType==2), Choices{0,1},
+    Name StrCat[mfem,"20Nonlinear BH-curve?"], Highlight "LightPink", ReadOnly (Flag_AnalysisType==2)}
+  Flag_NonlinearLawType = {1,
+    Choices{
+      0="linear law (testing)",
+      1="3 kW machine law",
+      2="anhysteretic law",
+      3="Jiles-Atherton hysteretic law"},
+    Name StrCat[mfem,"21 Choose BH-curve?"], Highlight "Magenta", Visible Flag_NL,
+    ReadOnly (Flag_AnalysisType==2) }
+  Flag_Hysteresis = {(Flag_NonlinearLawType==3)?1:0, Choices{0,1},
+    Name StrCat[mfem,"22Jiles-Atherton hysteretic law?"],
+    Highlight "LightPink", ReadOnly, Visible Flag_NL}
+
+  ORDER = {(Flag_AnalysisType==0 || (Flag_Hysteresis==1))?1:(Flag_AnalysisType==2)?-2:2,
+    Choices {
+        0="exact",
+       -1="-1 (homog FD zero order)",
+       -2="-2 (homog FD 2nd order)",
+       -3="-3 (homog FD 4th order)",
+        1="1 (homog TD zero order)",
+        2="2 (homog TD 2nd order)",
+        3="3 (homog TD 4th order)",
+        4="4 (homog TD 6th order)" },
+      Name StrCat[mfem, "00Approx. order"],
+      Help Str["- With 'Time domain', use order>0",
+        "- With 'Frequency domain' all possibities hold"],
+      Highlight "Red", Visible Flag_HomogType, ReadOnly Flag_AnalysisType==0}
+
+    Flag_ComplexReluctivity  = Flag_HomogType && !(ORDER>0) // 0 3D fine reference model OR Homog real; 1 Homog with nu complex
+];
+
+
+Group{
+
+  NN = (Flag_HomogType==1)? 1 : nlam/(Flag_Symmetry==0 ? 1:2) ; // Testing complete geometry
+
+  For k In {0:NN-1}
+    Iron~{k}     = Region[{(IRON+k)}] ;
+    Iron        += Region[{(IRON+k)}] ;
+
+    ElecIron~{k} = Region[{(ELECIRON+k)}] ;
+    ElecIron    += Region[{ElecIron~{k}}] ;
+  EndFor
+
+  Ind     = Region[{IND}];
+  AirOut  = Region[{AIR}];
+  AirIn   = Region[{ISOL}]; // between laminations
+
+  SymX0 = Region[{}];
+  SurfaceElec = Region[{}]; // av-formulation
+
+  SymMiddle = Region[{SYMMETRY_Y0}];
+  If(1)
+    OuterBnd  = Region[{}];
+  Else
+    // Equivalent to no BC at outer boundary (with or without air outside ind)
+    // Using this condition or the previous gives exactly the same result
+    OuterBnd0 = #OUTERBND ;
+    PntOuterBnd = #CORNER;
+    OutLayerElements = ElementsOf[OuterBnd0, OnOneSideOf PntOuterBnd];
+    OuterBnd = Region[{OuterBnd0, -OutLayerElements}];
+  EndIf
+
+  If(Flag_Symmetry==2) // 1/4 of the model
+    SymX0 += Region[{SYMMETRY_X0}];
+    SymX0 += Region[{ElecIron}];
+    SurfaceElec += Region[{ElecIron}]; // av-formulation
+  EndIf
+
+  SurfaceGe0 = Region[{SymMiddle, SymX0}];
+  Surface_FixedMVP  = Region[{SurfaceGe0, OuterBnd}];
+
+  If (Flag_HomogType<2)
+    Air = Region[{AirOut, AirIn}];
+  Else
+    // laminated structure is there but min mesh
+    // for testing purposes
+    Air   = Region[{AirOut}];
+    Iron += Region[{AirIn}];
+  EndIf
+
+  DomainS0 = Region[{Ind}];
+  DomainCC = Region[{Air, Ind}];
+
+  If(Flag_HomogType==0) // Fine reference model
+    If(Flag_AnalysisType)
+      DomainC   = Region[{Iron}];
+    Else
+      DomainCC += Region[{Iron}];
+      DomainC   = Region[{}];
+    EndIf
+  Else
+    DomainLamC  = Region[{Iron}];
+    DomainLamCC = Region[{}];
+    DomainLam   = Region[{DomainLamC, DomainLamCC}];
+
+    DomainNoLamC  = Region[ {} ] ;
+    DomainC   = Region[ {DomainNoLamC} ] ;
+    // SkinDomainC = Region[{SkinMetal}]; //+++ for gauging => not needed when using av formulation
+  EndIf
+
+
+  If(!Flag_NL)
+    Domain_NL = Region[{}];
+    Domain_L = Region[{Air, Ind, Iron}];
+  Else
+    Domain_NL = Region[{Iron}];
+    Domain_L  = Region[{Air, Ind}];
+  EndIf
+  Domain = Region[{Domain_L, Domain_NL}];
+
+  DomainGauge = Region[{Domain}];
+  Surface_NoGauge_av = Region[{Surface_FixedMVP}];
+
+}
+
+
+Function {
+  DefineConstant[
+    mur_fe   = {2000, Name StrCat[mfem,"31relative mu (iron)"], Highlight "Ivory", Visible !Flag_NL}
+    sigma_fe = {2e6, Name StrCat[mfem,"32conductivity (iron)"], Highlight "Ivory"}
+    // sigma_sc = {sigma_fe/1e3, Name StrCat[mfem,"{23conductivity (sc)"], Highlight "Cyan"}
+  ];
+
+  //Fct_Src[] = F_Cos_wt_p[]{2*Pi*Freq, (Flag_AnalysisType==1) ? Pi/2 : 0};
+
+  // With hysteresis: Damped start necessary
+  Trelax = 1/Freq/8;
+  Frelax[] = 1;//($Time < Trelax) ? 0.5 * (1. - Cos [Pi*$Time/Trelax] ) : 1. ;
+
+  Fct_Src[] = (Flag_Hysteresis==1 ? Frelax[]:1) * ((Flag_AnalysisType==1) ? F_Sin_wt_p[]{2*Pi*Freq, 0} : F_Cos_wt_p[]{2*Pi*Freq, 0})  ;
+
+  xcen = xlam;
+  ycen = ylam;
+
+  phi0[] = Atan2[Y[]-(Y[]>0.?1.:-1.)*ycen, X[]-(X[]>0?1:-1)*xcen];
+  Idir[] = (Fabs[X[]]>=xcen && Fabs[Y[]]>=ycen) ?
+                              Vector[ -Sin[phi0[]#1], Cos[#1], 0. ] :
+          ((Fabs[X[]]<xcen) ? Vector[(Y[]>0?-1:1), 0., 0.] : Vector[0.,(X[]>0?1:-1)*1., 0.]);
+
+  Sc[] = SurfaceArea[]{IND};
+
+  val_current = 8e5; //anhysteretic law is saturated but converges well
+  //js[] = val_current * Idir[] * Fct_Src[] ; // --- 21/12/2018
+
+}
+
+
+// Constraints
+//============================================================
+Constraint {
+  { Name MagneticVectorPotential  ;
+    Case {
+      { Region SurfaceGe0 ; Value 0. ; }
+      { Region OuterBnd   ; Value 0. ; }
+    }
+  }
+  { Name Gauge_av; Type Assign;
+    Case {
+      { Region DomainGauge ; SubRegion Surface_NoGauge_av ; Value 0. ; }
+    }
+  }
+
+  { Name ElectricScalarPotential  ;
+    Case {
+      For k In {0:NN-1}
+        { Region ElecIron~{k} ; Value 0. ; }
+      EndFor
+    }
+  }
+
+  { Name Current ; Type Assign ;
+    Case {
+      { Region Ind ; Value val_current; TimeFunction Fct_Src[] ; }
+    }
+  }
+  { Name Voltage ; Type Assign ;
+    Case {
+    }
+  }
+
+}
+
+
+//======================================================================
+
+dist_cen = 1e-4;
+//dist_cen = w_lam/2-w_lam/2/8;
+
+x0 = dist_cen; y0 = 0.;
+x1 = w_lam/2;  y1 = h/2;
+
+NptsLam = 10*3 ;
+//Npts = NptsLam * nlam/2;
+
+newappend = Sprintf("_TD%g_nl%g_m%g", (Flag_AnalysisType==1),  Flag_NonlinearLawType, Flag_HomogType);
+If(Flag_HomogType==1)
+  newappend = Sprintf("_TD%g_nl%g_m%g_o%g", (Flag_AnalysisType==1),  Flag_NonlinearLawType, Flag_HomogType, ORDER);
+EndIf
+
+ExtGmsh = StrCat[ newappend, Sprintf("_de%g_f%g.pos", de/mm, Freq) ];
+ExtGplt = StrCat[ newappend, Sprintf("_de%g_f%g.dat", de/mm, Freq) ];
+ExtGpltGlobal = StrCat[ newappend, Sprintf("_de%g_f%g.dat", de/mm, Freq)];
+
+
+
+
+
+
+Include "homog_laminations.pro";
+
+ResId="";
+po_mag   = StrCat["{9Output - Magnetics/", ResId];
+
+//===========================================================================================
+
+PostOperation {
+
+  { Name Get_LocalFields ; NameOfPostProcessing MagStaDyn_av ; LastTimeStepOnly ;
+    Operation {
+      Print[ js, OnElementsOf Ind,    File StrCat[ ResDir, "js", ExtGmsh] ];
+      // Print[ a, OnElementsOf Domain,  File StrCat[ ResDir, "a", ExtGmsh] ];
+      If(NbrRegions[DomainC])
+        Print[ v, OnElementsOf DomainC, File StrCat[ ResDir, "v", ExtGmsh] ];
+        Print[ j, OnElementsOf DomainC, File StrCat[ ResDir, "j", ExtGmsh] ];
+        Echo[Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;",
+            "View[k].CenterGlyphs = 0;","View[k].GlyphLocation = 1;"], File "res/maps.opt"];
+      EndIf
+      // If(Flag_Hysteresis)
+      //   Print[ h, OnElementsOf Iron,  File StrCat[ ResDir, "h", ExtGmsh] ];
+      // EndIf
+      Print[ bz, OnElementsOf Iron,  File StrCat[ ResDir, "bz", ExtGmsh] ];
+      Echo[Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+
+      /*
+      If(Flag_HomogType>0)
+        If (ORDER>0) // Only time domain (or FD with b_k)
+          For k In {1:ORDER}
+            Print[ bz~{2*k-2}, OnElementsOf DomainLam, File StrCat[ResDir,Sprintf("bz%g",2*k-2),ExtGmsh] ] ;
+            Echo[ Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+            Print[ j~{2*k-2}, OnElementsOf DomainLam, File StrCat[ResDir,Sprintf("j%g",2*k-2),ExtGmsh] ] ;
+            Echo[ Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+          EndFor
+        EndIf
+      EndIf
+      */
+      If(Flag_AnalysisType==2) // a choice
+
+        If(Flag_HomogType==0)
+          For ll In {1:nlam-1:2}
+            y0~{ll} = e*ll/2-dlam/2;
+            y1~{ll} = y0~{ll} + dlam;
+            Print[ b, OnLine {{x0, y0~{ll}, 0.}{x0, y1~{ll}, 0.}}{NptsLam}, Format TimeTable, LastTimeStepOnly,
+              File >> StrCat[ ResDir, "bl", ExtGplt] ];
+            Print[ j, OnLine {{x0, y0~{ll}, 0.}{x0, y1~{ll}, 0.}}{NptsLam}, Format TimeTable, LastTimeStepOnly,
+              File >> StrCat[ ResDir, "jl", ExtGplt] ];
+          EndFor
+        EndIf
+
+        If(Flag_HomogType>0)
+          If (ORDER>0) // Only time domain (or FD with b_k)
+            For k In {1:ORDER}
+              For ll In {1:nlam-1:2}
+                y0~{ll} = e*ll/2-dlam/2;
+                y1~{ll} = y0~{ll} + dlam;
+                Print[ bz~{2*k-2}, OnLine {{x0, y0~{ll}, 0.}{x0, y1~{ll}, 0.}}{NptsLam}, Format TimeTable, LastTimeStepOnly,
+                  File >> StrCat[ ResDir, Sprintf("bl%g_o%g",2*k-2,ORDER), ExtGplt] ];
+                Print[ j~{2*k-2}, OnLine {{x0, y0~{ll}, 0.}{x0, y1~{ll}, 0.}}{NptsLam}, Format TimeTable, LastTimeStepOnly,
+                  File >> StrCat[ ResDir, Sprintf("jl%g_o%g",2*k-2,ORDER), ExtGplt] ];
+              EndFor
+            EndFor
+          EndIf
+        EndIf
+
+      EndIf
+    }
+  }
+
+  { Name Get_GlobalQuantities ; NameOfPostProcessing MagStaDyn_av ; Format TimeTable; LastTimeStepOnly ;
+    Operation {
+      Print[ Flux[DomainS0], OnGlobal, SendToServer StrCat[po_mag, "Flux linkage [Wb]"], Color "Ivory",
+        File > StrCat[ ResDir, "fl", ExtGpltGlobal] ];
+      Print[ EddyCurrentLosses[Iron], OnGlobal, SendToServer StrCat[po_mag, "Joule losses [W]"], Color "Ivory",
+        File > StrCat[ ResDir, "ecl", ExtGpltGlobal] ];
+      // Print[ MagneticEnergy[Iron], OnGlobal, SendToServer StrCat[po_mag, "Magnetic energy [J]"], Color "Ivory",
+      //  File > StrCat[ ResDir, "me", ExtGpltGlobal] ];
+    }
+  }
+
+}
diff --git a/HomogenisationLaminations/lam_hyst/lam2d_data.pro b/HomogenisationLaminations/lam_hyst/lam2d_data.pro
new file mode 100644
index 0000000..d09c060
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/lam2d_data.pro
@@ -0,0 +1,101 @@
+mgeo = "{0Geometrical parameters/";
+mgeo2 = "{0Geometrical parameters/dimensions/";
+
+mfem = "{1Analysis parameters/";
+
+DefineConstant[
+  Flag_HomogType = {0, Choices{
+      0="Fine reference model",
+      1="Homogenized block",
+      2="Homogenized lamination"}, Name StrCat[mgeo,"Model"] }
+  nlam = {2*10, Name StrCat[mgeo,"Number of laminations"]}
+
+  Flag_Symmetry = {2, Choices{
+      0="No symmetry",
+      1="1/2 of the model (at y=0)",
+      2="1/4 of the model (at y=0 & x=0)"},
+    Name StrCat[mgeo,"Symmetry at x=0"]}
+
+  Flag_Recombine = {1, Choices{0,1}, Name StrCat[mgeo, "Recombine"]}
+];
+
+// in geo file => Flag_Fine =0 homog. block,  =1 ref. fine, =2 homog. lamination,
+Flag_Fine = (Flag_HomogType==2) ? Flag_HomogType : !Flag_HomogType ;
+
+SymmetryFactor = (!Flag_Symmetry) ? 1:Flag_Symmetry*2 ;
+
+
+
+mm = 1e-3 ;
+
+DefineConstant[
+  dlam = { 0.50, Name StrCat[mgeo2,"0lamination thickness"], Units 'mm', Closed 1}
+  de   = { 0.05, Name StrCat[mgeo2,"1isolation thickness"], Units 'mm'} // 0.07
+  fillfactor = { dlam/(dlam+de), Name StrCat[mgeo2,"2fill factor"], Units '', ReadOnly 1}
+  w_lam = { 10, Name StrCat[mgeo2,"3lamination width"], Units 'mm'}
+];
+
+
+dlam = dlam*mm;
+de   = de  *mm;
+e    = dlam+de;
+
+h = nlam*dlam + (nlam-1)*(e-dlam); // height lamination stack
+
+w_lam = w_lam*mm;
+
+// inductor dimensions
+r1 = 8.4*mm;
+r2 = 9*mm;
+w_ind = r2-r1; //1*mm ;
+
+rla_ind = 2*e; // minimum distance between lamination and inductor (radius)
+
+//---------------------------------------------------------------------------
+
+xlam = w_lam/2 ; //h/2 ;
+ylam = h/2 ;
+
+x_air = 1.5*(h/2+rla_ind+w_ind);
+y_air = 1.5*(h/2+rla_ind+w_ind) ;
+
+area_ind = w_ind*w_lam/2 + w_ind*h/2 + Pi/4*((rla_ind+w_ind)^2-rla_ind^2);
+Printf("Area of 1/4 of the inductor %g", area_ind);
+
+
+// Some material characteristics
+// ==================================
+//sigmaLam  = 5e6 ;
+//sigmaCu   = 5.9e7  ; // conductivity of copper [S/m]
+//sigmaIsol = sigmaLam/1e6 ; // slightly conducting, as if we had a shortcircuit
+
+//murIron = 2500 ; // To use in linear case
+
+//============================
+// Physical numbers
+//============================
+IRON     = 1000 ; // all laminations or complete block (if homog); first lamination 10001 and so on.
+ELECIRON = 1500 ;
+
+SKINIRON   =1100 ; // skin of all lamination or of complete block (if homog); skin of first lamination 20001 and so on
+
+SKINIRON_R =1300; // right side
+SKINIRON_L =1400; // left side
+
+IND =       2000;
+SKININD =   2100;
+SKININDIN = 2101;
+
+AIR   = 6000;
+
+ISOL  = 3000; // Between laminations
+
+SYMMETRY_Y0 = 11111; // middle
+SYMMETRY_X0 = 22222; // axis
+
+OUTERBND  = 33333;
+
+CORNER = 4444;
+
+
+SKINMETAL = 5555; // Homog cases
diff --git a/HomogenisationLaminations/lam_hyst/matlab/.DS_Store b/HomogenisationLaminations/lam_hyst/matlab/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..6713a9d4fc62d7dcaa708fbf8e4cae7c4d62147d
GIT binary patch
literal 8196
zcmeHMT}&KB9RL6MX!k>8sI;Y!wnr&a+mjwGRw&RO95i6T5`jViIqq&3SY3AM?cM=J
z46%utXtYriqwyo!_+(9dF-997jn$|RN>Yt6KIn^&Mx%*O{%2>8QYeYOs7-g0ncwXH
zV`t{KzuV2s0RXmTv^sz?0FbD1WGXc`DBREMx{~Kx3JH<&Avx>JBuzU>*PpJ74h#VU
z0RsU80RsU80R#UB2I!m3i?qRaUwDHyU?5=NmSljxA3{_)Mtxio=)F3q@wNbj1!VRL
z^%?IFhJ1|rxFnD~R8XW6id6Ks7%0-o9`fU&J}wCq>45&`1O1WF-=Uy4I^93yg#$(f
z25rDVz`%M2_};w$CcuD6a8~c%lQX8_xRJ<J%*!t*+_YJesT9c%_D$KdeQv_dIBkja
z2*2u0xKl~L-*4OIN<Wc2ZRoRcRvNP{H(^+M+DkSxokB(j4NJ3U+w6>`Io^Hxgu@#s
z&dL@R4mXBFha!!O;m|@|{h@|%s3B6nxF}28tLs|2#;51cEj+UL=u2Wv=)V`Bc+DDL
zUcErgNtsESA`f0!wdrJI;?yGV#oVgDSy{EB-qv-W(j8}8vb2~}Gp=D<&S^dE5XM=t
zLj-iCY^yh|bAOzbq!MN-V<ud^)inEzbGkE_vdzr2<qWy{oXai4j-7U6o-xi?#?c?p
zDc;EH?UdyV8FV`y#z2<dF50%MswP}_q$%35e0wn~QIyiHgIU8dlBRwp;iPm+Gpxyh
zSwnNDhKWGSH6{!_Ez2eO&HYwlT3_B?wxdL?P<Q6CMC`R(iB(BMnWS+xW4QBT47GBP
zEV1`SHJVS4t?@f*o<~(H@06qwZjYsPYK2)*_aC5yM88AR_NRF;BFoI_f0&-KNLA|Z
zkz}R~n2Drr`liOCWI8#R6?FQ>W5*@A1j9oqdwQDI;|Q}FYnLQ;WsHyAop9V!GrC2?
zd#kHdJ0<B1_q1x7u2n_%2@!Y%$W_sZuL%iuKrMaB`e77wn1S=~G&}>(!UcE*-hy}F
zefS8j(9zXr@CAGY-@%XYGyDp_!SC<~0?MeMibYtCRk#<cu?~-76E@>9jA1wS;QiQ(
z12~3p9LFS1;aN<hgBe`J$MFe#5}(2s@Kt;bU&lA_UHkw)#LM_Geu-b>vY209PQyL^
ze0{+0sk2(H{vli5*bU{{aYE_*kL3Do5!dLJJ4&~1+r9U$+QSVktt*dl&68U#B2PC$
z7@lBqg7BW-^(v(2U0$K=R0l{``rI`Y3svVd&Ng!eNn9P}A$5<+xOBv2wOXUHJW{u~
z+^>cemQUK1z2JjNoyrPHrovmV98p*S=~#Fhl_r&KBE<@?tQ=SP?@Tz`)Eb4ML~{Gb
z>bnS+;4*vypOfmY!VmBh`~rWH;uK_9MtZBjUAP<f;eI@TcVjKyi;bkcW^BO|*oj?u
zlJqx#gE)l4ID#5Z;3OLOkf**Z&fz>hhUYyMUcl$@c~6IL;>9(p>sq6_ORH6v?Mqvx
zZB3Fbr_$@ggR7g4fqXIJGQR)s*!cYardwAq;edgFfxpiH7PR-Zw^95?Z+5=d4pAMa
x$_tNM66mE+<88+Yz3n*R${&W*4^b%3iTb!CkStXG^@D)m`yYJ&J>}in&0kEy-lzZo

literal 0
HcmV?d00001

diff --git a/HomogenisationLaminations/lam_hyst/matlab/PQ.pro b/HomogenisationLaminations/lam_hyst/matlab/PQ.pro
new file mode 100644
index 0000000..a66bde6
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/matlab/PQ.pro
@@ -0,0 +1,25 @@
+Function { 
+
+p_0 = 1 ; 
+p_2 = 1/5 ; 
+p_4 = 1/9 ; 
+p_6 = 1/13 ; 
+p_8 = 1/17 ; 
+
+q_0_0 = 1/12 ; 
+q_0_2 = -1/60 ; 
+q_0_4 = 0 ; 
+q_0_6 = 0 ; 
+q_0_8 = 0 ; 
+q_2_2 = 1/210 ; 
+q_2_4 = -1/1260 ; 
+q_2_6 = 0 ; 
+q_2_8 = 0 ; 
+q_4_4 = 1/1386 ; 
+q_4_6 = -1/5148 ; 
+q_4_8 = 0 ; 
+q_6_6 = 1/4290 ; 
+q_6_8 = -1/13260 ; 
+q_8_8 = 1/9690 ; 
+
+} 
diff --git a/HomogenisationLaminations/lam_hyst/matlab/gausspoints_Ngp5.pro b/HomogenisationLaminations/lam_hyst/matlab/gausspoints_Ngp5.pro
new file mode 100644
index 0000000..943d375
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/matlab/gausspoints_Ngp5.pro
@@ -0,0 +1,40 @@
+Function { 
+
+nbrQuadraturePnts = 5 ; 
+y_1 = 0.4869532642585859 ; 
+y_2 = 0.4325316833444923 ; 
+y_3 = 0.3397047841495122 ; 
+y_4 = 0.2166976970646236 ; 
+y_5 = 0.07443716949081558 ; 
+
+w_1 = 0.06667134430868803 ; 
+w_2 = 0.1494513491505806 ; 
+w_3 = 0.2190863625159821 ; 
+w_4 = 0.2692667193099962 ; 
+w_5 = 0.2955242247147529 ; 
+
+c_2_1 = 0.9227408894325529 ; 
+c_2_2 = 0.6225019425809211 ; 
+c_2_3 = 0.1923960422444001 ; 
+c_2_4 = -0.2182526485213317 ; 
+c_2_5 = -0.4667546467891736 ; 
+
+c_4_1 = 0.7540759623195408 ; 
+c_4_2 = 0.01876577623813898 ; 
+c_4_3 = -0.4237995624971215 ; 
+c_4_4 = -0.1750153257920291 ; 
+c_4_5 = 0.2940357210203751 ; 
+
+c_6_1 = 0.5198876842062001 ; 
+c_6_2 = -0.37631042528707 ; 
+c_6_3 = -0.05814566531984765 ; 
+c_6_4 = 0.3212307651150516 ; 
+c_6_5 = -0.1765653629252029 ; 
+
+c_8_1 = 0.2555659454712284 ; 
+c_8_2 = -0.3351473744834802 ; 
+c_8_3 = 0.31798282660715 ; 
+c_8_4 = -0.224720190317701 ; 
+c_8_5 = 0.08085046072097912 ; 
+
+} 
diff --git a/HomogenisationLaminations/lam_hyst/matlab/get_b.m b/HomogenisationLaminations/lam_hyst/matlab/get_b.m
new file mode 100644
index 0000000..1b18910
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/matlab/get_b.m
@@ -0,0 +1,45 @@
+function b = get_b(b1, h1, h2, n)
+% b1 - induction at previous step
+% h1 - magnetic field at previous step
+% h2 - magnetic field at current step
+% n  - number of integration points for computing b2 
+    
+    global mu0 Msat aa kk cc alpha
+    
+    b = b1 ;
+    dh = (h2-h1)/n ;
+    
+    for k = 0:n-1
+        h = (n-k)/n*h1 + k/n*h2 ;
+        m = b/mu0 - h ;     % magnetisation
+        he = h + alpha * m ; % effective field
+        
+        % anhysteretic magnetisation
+        if(abs(he)<0.01*aa)
+            man = Msat*he/(3*aa) ;
+        else
+            man = Msat*(cosh(he/aa)/sinh(he/aa)-aa/he) ;
+        end
+        
+        %Irreversible magnetisation
+        mi = (m-cc*man) / (1-cc) ;
+        
+        if (abs(he) < 0.01*aa) 
+            dmandhe=Msat/(3.*aa) ;
+        else 
+            dmandhe=Msat/aa*(1-(cosh(he/aa)/sinh(he/aa)).^2+(aa/he).^2) ;
+        end
+        
+        if (~abs(man-mi) || (man-mi)*dh < 0.)
+            dmidhe = 0 ;
+        else
+            dmidhe = abs(man-mi)/(kk) ;
+        end
+
+        % differential susceptibility
+        dmdh = (cc*dmandhe + (1-cc)*dmidhe) / ...
+               (1 - alpha*cc*dmandhe - alpha*(1-cc)*dmidhe) ;
+        
+        dbdh = mu0*(1+dmdh) ;
+        b = b + dbdh * dh ;
+    end
\ No newline at end of file
diff --git a/HomogenisationLaminations/lam_hyst/matlab/jiles_atherton.m b/HomogenisationLaminations/lam_hyst/matlab/jiles_atherton.m
new file mode 100644
index 0000000..4c553ab
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/matlab/jiles_atherton.m
@@ -0,0 +1,85 @@
+clear all; close all
+
+% Material parameters: e.g. hyst_FeSi = { Msat, a, k, c, alpha}
+global mu0 Msat aa kk cc alpha ;
+
+Msat = 1145220 ; 
+aa = 59.5 ; 
+kk = 99.2 ; 
+cc = 0.54 ; 
+alpha = 1.3e-4 ;
+
+mu0 = 4*pi*1e-7; 
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+ha = 1000 ;
+freq = 1 ;
+T = 1/freq ;
+t0 = 0 ;
+nbrT = 2 ;
+tmax = T*nbrT ;
+nbrsteps = 200 ;
+N = nbrsteps*nbrT ;
+
+time = linspace(t0,tmax,N) ;
+
+h = ha*sin(2*pi*freq*time) ;
+b = zeros(size(h)) ;
+nint = 10 ;
+
+for k=1:N-1
+    b(k+1) = get_b(b(k), h(k), h(k+1), nint) ;
+end
+
+figure(1), hold on, plot(time, h, 'b','LineWidth',2)
+xlabel('time(s)'), ylabel('h')
+
+figure(2), plot(h, b, 'r','LineWidth',2), grid on
+xlabel('h'), ylabel('b')
+
+
+
+
+% Save anhysteretic curve for first nonlinear computation
+
+
+
+%===============================================================================
+if(1) % one for creating file
+    N = nbrsteps*1/4 ; % anhysteretic curve ==> increasing h, till
+                       % max sin
+    figure(3), plot(h(1:N), b(1:N), 'm','LineWidth',2), grid on
+    xlabel('h'), ylabel('b')
+
+    filename = sprintf('BH_anhysteretic.pro');    
+    fid = fopen(filename, 'wt');
+    
+    fprintf(fid, 'Function { \n\n');
+    
+    fprintf(fid, 'anhys_b  = { \n' );
+    fprintf(fid, '%.8f, %.8f, %.8f, %.8f, %.8f,\n', b(1:N));
+    fprintf(fid, '%.8f } ; \n\n', b(N+1));
+    
+    fprintf(fid, 'anhys_h  = { \n' );
+    fprintf(fid, '%.8f, %.8f, %.8f, %.8f, %.8f, \n', h(1:N));
+    fprintf(fid, '%.8f } ; \n\n', h(N+1));
+    
+    fprintf(fid, 'anhys_b2  = List[anhys_b]^2 ;\n');
+    fprintf(fid, 'anhys_nu  = List[anhys_h]/List[anhys_b] ;\n');
+    fprintf(fid, 'anhys_nu(0)  = anhys_nu(1) ;\n');
+    fprintf(fid, 'anhys_nu_b   = ListAlt[anhys_b, anhys_nu] ;\n');
+    fprintf(fid, 'anhys_nu_b2  = ListAlt[anhys_b2, anhys_nu] ;\n');
+    fprintf(fid, '\n');
+    fprintf(fid, 'nu_anhys[]     = InterpolationLinear[SquNorm[$1]]{List[anhys_nu_b2]} ;\n');
+    fprintf(fid, 'dnudb2_anhys[] = dInterpolationLinear[SquNorm[$1]]{List[anhys_nu_b2]} ;\n');
+    fprintf(fid, 'h_anhys[] = nu_anhys[$1#1] * #1 ;\n');
+    fprintf(fid, ['dhdb_anhys[] = TensorDiag[1,1,1] * nu_anhys[$1#1] ' ...
+                  '+ 2*dnudb2_anhys[#1] * SquDyadicProduct[#1] ;\n']);
+    fprintf(fid, 'dhdb_anhys_NL[] = 2*dnudb2_anhys[$1#1] * SquDyadicProduct[#1] ;\n');
+    
+    fprintf(fid, '} \n');
+    %================================================================
+    fclose(fid);
+    
+end
\ No newline at end of file
diff --git a/HomogenisationLaminations/lam_hyst/runHyst.sh b/HomogenisationLaminations/lam_hyst/runHyst.sh
new file mode 100755
index 0000000..c83dc70
--- /dev/null
+++ b/HomogenisationLaminations/lam_hyst/runHyst.sh
@@ -0,0 +1,68 @@
+#!/bin/sh
+
+homog=1
+getmesh=0
+
+if [ $homog = 0 ]; then
+    mymesh="fine.msh"; nn=1; else
+    mymesh="homog.msh"; nn=3;
+fi
+if [ $getmesh  = 1 ]; then
+    gmsh lam2d.geo -nt 4 -v 4 -3 -setnumber Flag_HomogType $homog -setnumber Flag_Symmetry 2 -o $mymesh
+fi
+
+ff=5000
+ordermin=1 ordermax=$nn;
+law=3 # 0 linear; 1 3kw machine; 2 anhysteretic law; 3 hysteretic law
+nbt=20 # number of periods
+nbs=240 # number of steps per period
+
+runthis=1
+if [ $runthis = 1 ]; then
+for (( i=$ordermin ; i<=$ordermax ; i++ )) ; do
+    echo "====================== ORDER $i ==========================" ;
+    getdp -v 3 -cpu lam2d.pro -msh $mymesh \
+          -setnumber visu 0 \
+          -setnumber Flag_HomogType $homog \
+          -setnumber ORDER $i \
+          -setnumber Flag_Symmetry 2 \
+          -setnumber Flag_AnalysisType 1 \
+          -setnumber Flag_NL 1 \
+          -setnumber Flag_NonlinearLawType $law \
+          -setnumber Freq $ff \
+          -setnumber NbT $nbt \
+          -setnumber NbSteps $nbs \
+          -sol Analysis
+done
+fi
+
+
+# frequency loop for losses figure as function of frequency
+
+fmin=5
+fmax=5000
+nbf=20
+
+runthis=0
+if [ $runthis = 1 ]; then
+    for (( k=1 ; k<=$nbf ; k++ )) ; do
+        echo "e(l($fmin)+($k-1)*l($fmax/$fmin)/($nbf-1))" | bc -l
+        fk=`echo "e(l($fmin)+($k-1)*l($fmax/$fmin)/($nbf-1))" | bc -l`
+        echo "======================> $k freq $fk <==========================" ;
+        for (( i=$ordermin ; i<=$ordermax ; i++ )) ; do
+            echo "====================== ORDER $i ==========================" ;
+            getdp -v 3 -cpu lam2d.pro -msh $mymesh \
+                  -setnumber visu 0 \
+                  -setnumber Flag_HomogType $homog \
+                  -setnumber ORDER $i \
+                  -setnumber Flag_Symmetry 2 \
+                  -setnumber Flag_AnalysisType 1 \
+                  -setnumber Flag_NL 1 \
+                  -setnumber Flag_NonlinearLawType $law \
+                  -setnumber Freq $fk \
+                  -setnumber NbT $nbt \
+                  -setnumber NbSteps $nbs \
+                  -sol Analysis
+        done
+    done
+fi
diff --git a/HomogenisationLaminations/srm/.DS_Store b/HomogenisationLaminations/srm/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..73647d214b11fe0a0a352f307e8a4f578d5c9f6f
GIT binary patch
literal 8196
zcmeHMOKjXk82<mwqkc5R=`%?QSx6J5Z4&Y%2_&%DyqW@P#3s$7X;XXcBo>aHuD!cW
z)1Vas1QMbMH~@kJRGiwL5L_y5Ahi-)P$Z~8aN)p#3kWVf@sGzFnxx^t0jTPcX1<yK
zVb6U2)}!$P0LIgL3qUyl2viv=GBtN7%+KnU5(z9tgh=_IyGcuP9BWHtXb2ey83-8&
z83-8&8Th|2KzlYT!Z!Op_l9lAK*+#7$pCvlM5!{21(@ULzdES#j{t;)WcCa771kk)
z1{e!4$B{f#kf##zR1A(7$kWLl4dP+}<~Z_nz~JzK!JRQUp`d?vx_;CT2aItH+mL~f
zfvpU%vwI=TfeG{A-hO^BhDA`p1B+Ts%eqUN<!BUqLtC;;*K2P61|tQ9Ma4S=kxGep
zDzV^X6Q1g&-ME@M$ws59x1a_6G5Rd9-dD8~rjeah_Vhcpr<%5r@{>*7ppcmf)7G7A
z+)3NI>t83q9sZ4GmGYI9j`oIVYg^Z9Lv*F3?UB}oXlGaV>Z&O0uWjiaIkUKYe&xdI
zbMNrQV(`L%(oKthm&O|wX}OtxzR1XOev#j<FH(|s4h<ibW|dtTn)~r3&vb0}gpqOy
zXO&Wy);p4P?9r6L{Ig0~Qniw4OZALC%SxE%4R<2xSm{OEo%D=z9<xllPRi@|jguzj
zGTW@8q+R0~gA&b*F+l0A0-|uaWZ!}4!9z`LUA^(O`%0BEX}7d@B4fIyW*OsIQ}-68
zR5xkZx@pf(6JNGx&Y4C^EQ{O{$82@c@U!G{xl&MSgvqpKo=uzHGQU=pTrDb}2s1j}
z?rBG7nL3ZJl4}IvB(wLY3~ISqs*~$QMHR+enlZn`5vfsBTygAKdU!mwS!xv&T^zSm
z&9JzsL+TWiC&h^jr;QsQm3o9SY!D}t&f+4?+vVmb<UT>UE}UlfeoA${<4cD9*Q^Ew
zVTyVBbluQvV)gvl`U|azHS>{3TS^5q(bhEvGho0HEW@kt8eD|e;XU{WuENLg8C-`O
z@Fjc&U&D9sJ^TPa!q4z4{06_n9~eOycVY=v;6qr0wOEHoupK+F6T7e%hj182@EDHb
z6i(v|o<aj{bTEZ3UceXeC43oQ!ME`P{17kURs0mM;pcp6k-R96@o~PzFQ~U!l)*1A
za{7*<92^?{uS9vXgeh^??mc_=RUbUm*xK3CxBd_}J+}?gx?NAcgt$h0?c}w=HM_sO
zqVmA~k~~hTGR|$*d0zj@4yGSrjYUTvlx2kphYxG(WJy8Nw&;5g*O508_?jLjUjfOO
z``X$iSt%mL^31MoNm2?)(%jqoIC+anyxc3sC5ipC#DAc@OK=6Qk?z*uCaLWw_=WU#
z3jvE!!E&s`DtrK|u^ta&12$q4sjV9y!yaF8M}5U5a2zLal60q`j&nGV3wV}Pm&Occ
zF^A9N3%>p?;v4uTzJ>3T0xxe;-bh|^9P!F#<z*5n+j8uAvgg&hF(n+`<qQ<?`Iocv
z|KRrD|L^iuhSLuj2pRZ02C#4-F%YMS?cVe3tR1C#hAJy8F2~VNp@xMpyMG)fT>rz6
e`q97_3oyr#JXHSm4*}u+@ADq+|2_@(Z1X2af7G-9

literal 0
HcmV?d00001

diff --git a/HomogenisationLaminations/srm/BH.pro b/HomogenisationLaminations/srm/BH.pro
new file mode 100644
index 0000000..63056fc
--- /dev/null
+++ b/HomogenisationLaminations/srm/BH.pro
@@ -0,0 +1,135 @@
+Function{
+
+  // analytical
+  // analytical Brauer law for nonlinear isotropic material:
+  // nu(b^2) = k1 + k2 * exp ( k3 * b^2 )
+  // nu = 100. + 10. * exp ( 1.8 * b * b )
+  k1 = 100.; k2 = 10.; k3 = 1.8;
+  nu_1a[] = k1 + k2 * Exp[k3*SquNorm[$1]] ;
+  dnudb2_1a[] =  k2 * k3 * Exp[k3*SquNorm[$1]] ;
+  h_1a[] = nu_1a[$1]*$1 ;
+  dhdb_1a[] = TensorDiag[1,1,1] * nu_1a[$1#1] + 2*dnudb2_1a[#1] * SquDyadicProduct[#1]  ;
+  dhdb_1a_NL[] = 2*dnudb2_1a[$1#1] * SquDyadicProduct[#1]  ;
+
+   // interpolated
+  Mat1_h = {
+    0.0000e+00, 5.5023e+00, 1.1018e+01, 1.6562e+01, 2.2149e+01, 2.7798e+01, 3.3528e+01,
+    3.9363e+01, 4.5335e+01, 5.1479e+01, 5.7842e+01, 6.4481e+01, 7.1470e+01, 7.8906e+01,
+    8.6910e+01, 9.5644e+01, 1.0532e+02, 1.1620e+02, 1.2868e+02, 1.4322e+02, 1.6050e+02,
+    1.8139e+02, 2.0711e+02, 2.3932e+02, 2.8028e+02, 3.3314e+02, 4.0231e+02, 4.9395e+02,
+    6.1678e+02, 7.8320e+02, 1.0110e+03, 1.3257e+03, 1.7645e+03, 2.3819e+03, 3.2578e+03,
+    4.5110e+03, 6.3187e+03, 8.9478e+03, 1.2802e+04, 1.8500e+04, 2.6989e+04, 3.9739e+04,
+    5.9047e+04, 8.8520e+04, 1.3388e+05, 2.0425e+05, 3.1434e+05, 4.8796e+05, 7.6403e+05
+  } ;
+  Mat1_b = {
+    0.0000e+00, 5.0000e-02, 1.0000e-01, 1.5000e-01, 2.0000e-01, 2.5000e-01, 3.0000e-01,
+    3.5000e-01, 4.0000e-01, 4.5000e-01, 5.0000e-01, 5.5000e-01, 6.0000e-01, 6.5000e-01,
+    7.0000e-01, 7.5000e-01, 8.0000e-01, 8.5000e-01, 9.0000e-01, 9.5000e-01, 1.0000e+00,
+    1.0500e+00, 1.1000e+00, 1.1500e+00, 1.2000e+00, 1.2500e+00, 1.3000e+00, 1.3500e+00,
+    1.4000e+00, 1.4500e+00, 1.5000e+00, 1.5500e+00, 1.6000e+00, 1.6500e+00, 1.7000e+00,
+    1.7500e+00, 1.8000e+00, 1.8500e+00, 1.9000e+00, 1.9500e+00, 2.0000e+00, 2.0500e+00,
+    2.1000e+00, 2.1500e+00, 2.2000e+00, 2.2500e+00, 2.3000e+00, 2.3500e+00, 2.4000e+00
+  } ;
+
+  Mat1_b2 = Mat1_b()^2;
+  Mat1_nu = Mat1_h()/Mat1_b();
+  Mat1_nu(0) = Mat1_nu(1);
+
+  Mat1_nu_b2  = ListAlt[Mat1_b2(), Mat1_nu()] ;
+  nu_1[] = InterpolationLinear[ SquNorm[$1] ]{Mat1_nu_b2()} ;
+  dnudb2_1[] = dInterpolationLinear[SquNorm[$1]]{Mat1_nu_b2()} ;
+  h_1[] = nu_1[$1] * $1 ;
+  dhdb_1[] = TensorDiag[1,1,1] * nu_1[$1#1] + 2*dnudb2_1[#1] * SquDyadicProduct[#1]  ;
+  dhdb_1_NL[] = 2*dnudb2_1[$1#1] * SquDyadicProduct[#1] ;
+
+
+  // nu = 123. + 0.0596 * exp ( 3.504 * b * b )
+  // analytical 3kW machine
+  nu_3kWa[] = 123. + 0.0596 * Exp[3.504*SquNorm[$1]] ;
+  dnudb2_3kWa[] = 0.0596*3.504 * Exp[3.504*SquNorm[$1]] ;
+  h_3kWa[] = nu_3kWa[$1]*$1 ;
+  dhdb_3kWa[] = TensorDiag[1,1,1] * nu_3kWa[$1#1] + 2*dnudb2_3kWa[#1] * SquDyadicProduct[#1]  ;
+  dhdb_3kWa_NL[] = 2*dnudb2_3kWa[$1#1] * SquDyadicProduct[#1]  ;
+
+  // interpolated
+  Mat3kW_h = {
+    0.0000e+00, 6.1465e+00, 1.2293e+01, 1.8440e+01, 2.4588e+01, 3.0736e+01, 3.6886e+01,
+    4.3037e+01, 4.9190e+01, 5.5346e+01, 6.1507e+01, 6.7673e+01, 7.3848e+01, 8.0036e+01,
+    8.6241e+01, 9.2473e+01, 9.8745e+01, 1.0508e+02, 1.1150e+02, 1.1806e+02, 1.2485e+02,
+    1.3199e+02, 1.3971e+02, 1.4836e+02, 1.5856e+02, 1.7137e+02, 1.8864e+02, 2.1363e+02,
+    2.5219e+02, 3.1498e+02, 4.2161e+02, 6.0888e+02, 9.4665e+02, 1.5697e+03, 2.7417e+03,
+    4.9870e+03, 9.3633e+03, 1.8037e+04, 3.5518e+04, 7.1329e+04, 1.4591e+05, 3.0380e+05,
+    6.4363e+05, 1.3872e+06, 3.0413e+06, 6.7826e+06, 1.5386e+07, 3.5504e+07, 8.3338e+07
+  } ;
+  Mat3kW_b = {
+    0.0000e+00, 5.0000e-02, 1.0000e-01, 1.5000e-01, 2.0000e-01, 2.5000e-01, 3.0000e-01,
+    3.5000e-01, 4.0000e-01, 4.5000e-01, 5.0000e-01, 5.5000e-01, 6.0000e-01, 6.5000e-01,
+    7.0000e-01, 7.5000e-01, 8.0000e-01, 8.5000e-01, 9.0000e-01, 9.5000e-01, 1.0000e+00,
+    1.0500e+00, 1.1000e+00, 1.1500e+00, 1.2000e+00, 1.2500e+00, 1.3000e+00, 1.3500e+00,
+    1.4000e+00, 1.4500e+00, 1.5000e+00, 1.5500e+00, 1.6000e+00, 1.6500e+00, 1.7000e+00,
+    1.7500e+00, 1.8000e+00, 1.8500e+00, 1.9000e+00, 1.9500e+00, 2.0000e+00, 2.0500e+00,
+    2.1000e+00, 2.1500e+00, 2.2000e+00, 2.2500e+00, 2.3000e+00, 2.3500e+00, 2.4000e+00
+  } ;
+
+  Mat3kW_b2 = Mat3kW_b()^2;
+  Mat3kW_nu = Mat3kW_h()/Mat3kW_b();
+  Mat3kW_nu(0) = Mat3kW_nu(1);
+
+  Mat3kW_nu_b2  = ListAlt[Mat3kW_b2(), Mat3kW_nu()] ;
+  nu_3kW[] = InterpolationLinear[SquNorm[$1]]{Mat3kW_nu_b2()} ;
+  dnudb2_3kW[] = dInterpolationLinear[SquNorm[$1]]{Mat3kW_nu_b2()} ;
+  h_3kW[] = nu_3kW[$1] * $1 ;
+  dhdb_3kW[] = TensorDiag[1,1,1]*nu_3kW[$1#1] + 2*dnudb2_3kW[#1] * SquDyadicProduct[#1] ;
+  dhdb_3kW_NL[] = 2*dnudb2_3kW[$1] * SquDyadicProduct[$1] ;
+
+  DefineFunction[nu_lin, nu_nonlin, dhdb_NL] ;
+  // linear case -- testing purposes
+  h_lin[] = nu_lin[] * $1 ;
+  dhdb_lin[] = nu_lin[] * TensorDiag[1.,1.,1.] ;
+  dhdb_lin_NL[] = TensorDiag[0.,0.,0.] ;
+
+
+  // Parameters for Jiles-Atherton hysteresis model
+  //Gyselink's paper: Incorporation of a Jiles-Atherton vector hysteresis model in 2D FE magnetic field computations
+  Msat = 1145220; aaa = 59.5; kkk = 99.2; ccc = 0.54; alpha = 1.3e-4 ;
+  hyst_FeSi = { Msat, aaa, kkk, ccc, alpha};
+
+  //Using anhysteretic curve from Jiles-Atherton model
+  anhys_b  = {
+    0.00000000, 0.32182278, 0.61073510, 0.79096285, 0.90997687,
+    0.99429048, 1.05693296, 1.10504060, 1.14290665, 1.17329715,
+    1.19808489, 1.21858522, 1.23574806, 1.25027452, 1.26269133,
+    1.27340002, 1.28271066, 1.29086537, 1.29805515, 1.30443212,
+    1.31011850, 1.31521331, 1.31979742, 1.32393739, 1.32768837,
+    1.33109640, 1.33420015, 1.33703230, 1.33962062, 1.34198886,
+    1.34415738, 1.34614376, 1.34796321, 1.34962896, 1.35115252,
+    1.35254394, 1.35381202, 1.35496447, 1.35600803, 1.35694862,
+    1.35779139, 1.35854083, 1.35920085, 1.35977480, 1.36026555,
+    1.36067549, 1.36100662, 1.36126050, 1.36143836, 1.36154102,
+    1.36156898 } ;
+
+  anhys_h  = {
+    0.00000000, 31.48945679, 62.94768133, 94.34347236, 125.64569053,
+    156.82328930, 187.84534575, 218.68109121, 249.29994180, 279.67152877,
+    309.76572863, 339.55269297, 369.00287816, 398.08707454, 426.77643550,
+    455.04250600, 482.85725087, 510.19308256, 537.02288850, 563.32005806,
+    589.05850886, 614.21271269, 638.75772080, 662.66918868, 685.92340017,
+    708.49729101, 730.36847168, 751.51524967, 771.91665092, 791.55244067,
+    810.40314351, 828.45006274, 845.67529883, 862.06176725, 877.59321537,
+    892.25423862, 906.03029572, 918.90772314, 930.87374864, 941.91650394,
+    952.02503648, 961.18932028, 969.40026594, 976.64972956, 982.93052091,
+    988.23641048, 992.56213574, 995.90340628, 998.25690814, 999.62030702,
+    999.99225068 } ;
+
+  anhys_b2  = anhys_b()^2 ;
+  anhys_nu  = anhys_h()/anhys_b() ;
+  anhys_nu(0) = anhys_nu(1) ;
+  anhys_nu_b2 = ListAlt[anhys_b2(), anhys_nu()] ;
+
+  nu_anhys[]     = InterpolationLinear[SquNorm[$1]]{anhys_nu_b2()} ;
+  dnudb2_anhys[] = dInterpolationLinear[SquNorm[$1]]{anhys_nu_b2()} ;
+  h_anhys[] = nu_anhys[$1#1] * #1 ;
+  dhdb_anhys[] = TensorDiag[1,1,1] * nu_anhys[$1#1] + 2*dnudb2_anhys[#1] * SquDyadicProduct[#1] ;
+  dhdb_anhys_NL[] = 2*dnudb2_anhys[$1#1] * SquDyadicProduct[#1] ;
+
+}
diff --git a/HomogenisationLaminations/srm/Macro_homogenisation_laminations.pro b/HomogenisationLaminations/srm/Macro_homogenisation_laminations.pro
new file mode 100644
index 0000000..2f2735e
--- /dev/null
+++ b/HomogenisationLaminations/srm/Macro_homogenisation_laminations.pro
@@ -0,0 +1,660 @@
+Group {
+  Domain_Lin = Region[{Domain_L}] ;
+  Domain_NonLin = Region[{Domain_NL}] ;
+}
+
+Include "matlab/PQ.pro" ;
+Include "matlab/gausspoints_Ngp5.pro";
+
+nbrQuadraturePnts=Nqp;
+
+Function {
+
+  //lambda = fillfactor ; //la = lambda ;
+  sigmaH[] = sigmaLam/fillfactor;
+
+
+  //Legendre Polynomials (used in post-processing)
+  yy[] = ((Fmod[$Y,e]-e/2)*2/dlam) ; //x = z/(dlam/2), e = dlam+de
+
+  alpha_0[] = 1 ; // zero order
+  alpha_2[] = 1/2*(-1+3*yy[]^2) ; //2nd order
+  alpha_4[]=  1/8*(35*yy[]^4-30*yy[]^2+3); //4th order
+  alpha_6[] = 1/16*(231*yy[]^6-315*yy[]^4+105*yy[]^2-5);
+  alpha_8[] = 1/128*(6435*yy[]^8-12012*yy[]^6+6930*yy[]^4-1260*yy[]^2+35);
+
+  dalpha_0[] = 0. ;
+  dalpha_2[] = 3*yy[]*2/dlam ;
+  dalpha_4[] = 1/2*(35*yy[]^3-15*yy[])*2/dlam; //4th order
+  dalpha_6[] = 1/8*(231*3*yy[]^5-315*2*yy[]^3+105*yy[])*2/dlam;
+  dalpha_8[] = 1/64*(6435*4*yy[]^7-12012*3*yy[]^5+6930*2*yy[]^3-1260*yy[])*2/dlam;
+
+  ialpha_0[] = yy[]*dlam/2 ;
+  ialpha_2[] = 1/2*(yy[]^3-yy[])*dlam/2 ;
+  ialpha_4[] = 1/8*(7*yy[]^5-10*yy[]^3+3*yy[])*dlam/2;
+  ialpha_6[] = 1/16*(33*yy[]^7-63*yy[]^5+35*yy[]^3-5*yy[])*dlam/2;
+  ialpha_8[] = 1/128*(6435*yy[]^9/9-12012*yy[]^7/7+6930*yy[]^5/5-1260*yy[]^3/3+35*yy[])*dlam/2;
+
+
+  If(Flag_ComplexReluctivity) // complex stuff
+    delta = Sqrt[2*nuIron/sigmaLam/Omega] ;
+    ds = dlam/delta ;
+    Printf("delta = %g mm",delta*1000) ;
+    Printf("ds = %g",ds) ;
+    Printf("Flag_ComplexReluctivity = %g ; ORDER = %g", Flag_ComplexReluctivity, ORDER);
+
+    //Definition of Sinh, Cosh and Tanh in terms of the real and imaginary parts of a complex argument
+    Sinh_[] = Complex[ Cos[Im[$1]]*Sinh[Re[$1]], Sin[Im[$1]]*Cosh[Re[$1]] ];
+    Cosh_[] = Complex[ Cos[Im[$1]]*Cosh[Re[$1]], Sin[Im[$1]]*Sinh[Re[$1]] ];
+    Tanh_[] = Sinh_[$1]/Cosh_[$1];
+
+    // G[] => Function used in L.Krahenbuhl's article IEEE Trans. Mag. vol.40, no. 2, pp. 912-915, 2004.
+    G[] = Tanh_[ds/2*Complex[1,1]]/(ds/2*Complex[1,1]);
+
+    // Gr = ds/2 * (Sinh[ds]+Sin[ds])/(Cosh[ds]-Cos[ds]) ;
+    // Gi = ds/2 * (Sinh[ds]-Sin[ds])/(Cosh[ds]-Cos[ds]) ;
+    // G[Iron] = Complex[Gr,Gi];
+
+    If(ORDER==0) //Analytical
+      nuCplx[] = nuIron/G[] ;
+    EndIf
+    If(ORDER==-1)   // Approx ORDER = 0
+      nuCplx[] = Complex[ nuIron, sigmaLam * dlam^2/12. * Omega ];
+    EndIf
+    If(ORDER==-2)   // Approx ORDER = 2
+      // nuIron_r2 = nuIron * (1+ 49*ds^4/(8820+20*ds^4) ) ;
+      // nuIron_i2 = nuIron * (ds^2/6-7*ds^6/(26460+60*ds^4) ) ;
+      // nu[#{DomainLam}] = Complex[nuIron_r2, nuIron_i2]*fillfactor ;
+      // From matlab: nu1s = (ds^6*i + 69*ds^4 + ds^2*(1470*i) + 8820)/(20*(ds^4 + 441))
+      nuCplx[] = nuIron * Complex[
+        (69*ds^4 + 8820)/(8820+20*ds^4), (ds^6 + ds^2*1470)/(8820+20*ds^4) ];
+    EndIf
+    If(ORDER==-3)   // Approx ORDER = 4
+      // From matlab:
+      // collect(nu2s) =
+      // (ds^10*1i + 300*ds^8 + ds^6*29520i + 1353240*ds^4 + ds^2*27442800i + 164656800)/(42*ds^8 + 438480*ds^4 + 164656800)
+      // collect(real(nu2s)) = (50*ds^8 + 225540*ds^4 + 27442800)/(7*ds^8 + 73080*ds^4 + 27442800)
+      // collect(imag(nu2s)) = (ds^10 + 29520*ds^6 + 27442800*ds^2)/(42*ds^8 + 438480*ds^4 + 164656800)
+      nuCplx[] = nuIron * Complex[
+        (50*ds^8 + 225540*ds^4 + 27442800)/(7*ds^8 + 73080*ds^4 + 27442800),
+        (ds^10 + 29520*ds^6 + 27442800*ds^2)/(42*ds^8 + 438480*ds^4 + 164656800)];
+    EndIf
+    muCplx[] = 1/nuCplx[];
+    nu[#{DomainLam}] = nuCplx[]/fillfactor ; //with homog block
+
+    nuOm[] = Complex[ Omega*Im[nuCplx[]], -Re[nuCplx[]] ];
+    muOm[] = Complex[-Omega*Im[muCplx[]], -Re[muCplx[]] ];
+
+    // from Patrick's files
+    Ytransf[] = Fmod[Y[]-de/2., dlam+de] -dlam/2. ;
+    FACJ[] =
+    (Ytransf[]>=-dlam/2. && Ytransf[]<=dlam/2.)?
+    sigmaLam*dlam*2*Pi*Freq*Complex[0,1] / 2 / Sinh_[Complex[1,1]/delta*dlam/2]*
+    Sinh_[Complex[1,1]/delta* Ytransf[] ] : 0. ;
+
+    FACB[] =
+    (Ytransf[]>=-dlam/2. && Ytransf[]<=dlam/2.)?
+    sigmaLam*dlam*2*Pi*Freq*Complex[0,1] / 2 / Sinh_[Complex[1,1]/delta*dlam/2]*
+    delta*Complex[1,-1]/2 /nuIron *
+    Cosh_[Complex[1,1]/delta* Ytransf[] ] : 0. ;
+
+  EndIf
+
+}
+
+FunctionSpace {
+
+
+  ORDERMAX=4; //1 (zero order); 2 (2nd order); 3 (4th order); 4 (6th order); homogenization approx
+  // Auxiliary BFs {d a_i}
+  For i In {2:ORDERMAX}
+    { Name Hcurl_a~{2*i-2} ; Type Form1P ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_PerpendicularEdge ;
+          Support DomainLam ; Entity NodesOf[ All ] ; }
+      }
+      Constraint {
+        { NameOfCoef ae  ; EntityType NodesOf ; NameOfConstraint MVP ; }
+      }
+    }
+  EndFor
+  // Auxiliary BFs {b_i}
+  For i In {2:ORDERMAX}
+    { Name Hb~{2*i-2} ; Type Form2P ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_PerpendicularFacet ;
+          Support DomainLam ; Entity EdgesOf[ All ] ; }
+      }
+    }
+  EndFor
+
+
+  // Store history for every integration point along thickness
+  For i In {1:nbrQuadraturePnts}
+    { Name H_hysteresis~{i} ; Type Vector;
+      BasisFunction {
+        { Name sex ; NameOfCoef aex ; Function BF_VolumeX ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+        { Name sey ; NameOfCoef aey ; Function BF_VolumeY ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+        //{ Name sez ; NameOfCoef aez ; Function BF_VolumeZ ; Support DomainLam ; Entity VolumesOf[ DomainLam ] ; }
+      }
+    }
+  EndFor
+
+}
+
+
+// -------------------------------------------------------
+// Terms in homogenized formulations for laminations
+// -------------------------------------------------------
+
+Macro Macro_Terms_DomainLamC_sigma
+
+  If(ORDER >= 1) //ORDER = 0
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_0 * Dof{d a}, {d a} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration I1p ; }
+  EndIf
+  If (ORDER > 1) //ORDER = 2
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_2 * Dof{b_2}, {d a} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration I1p ; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_0_2 * Dof{d a}, {b_2} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration I1p ; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_2 * Dof{b_2}, {b_2} ] ;
+      In DomainLamC ; Jacobian Vol ; Integration I1p ; }
+  EndIf
+
+  If(ORDER > 2) //ORDER = 4
+    // 0 = nu*b_2/5 + sigma*d^2*(-dt(b0)/60   + dt(b_2)/210 - dt(b_4)/1260)
+    // 0 = nu*b_4/9 + sigma*d^2*(-dt(b_2)/1260 + dt(b_4)/1386)
+
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_4 *Dof{b_4},  {b_2} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_2_4 *Dof{b_2} , {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_4 *Dof{b_4} , {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+  EndIf
+
+  If(ORDER > 3) //ORDER = 6
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_6 * Dof{b_6}, {b_4} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_4_6 * Dof{b_4}, {b_6} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+    Galerkin { DtDof[ sigmaH[]*dlam^2 * q_6_6 * Dof{b_6}, {b_6} ];
+      In DomainLamC; Jacobian Vol ; Integration I1p; }
+  EndIf
+
+Return
+
+//---------------------------------------------------------------
+//---------------------------------------------------------------
+
+Macro Macro_Terms_DomainLam_nu
+
+If(!NbrRegions[Domain_NonLin]) // linear case
+  For k In {2:ORDER} // ORDER=2 => p_2;  ORDER=3 => p_4; ORDER=4 => p_6;
+    Galerkin { [ p~{2*k-2} * nu[] * Dof{b~{2*k-2}}, {b~{2*k-2}} ] ;
+      In DomainLam ; Jacobian Vol ; Integration II; }
+  EndFor
+  /*
+  If (ORDER > 1) //ORDER = 2
+    Galerkin { [ p_2 * nu[] * Dof{b_2}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+  EndIf
+  If(ORDER > 2) //ORDER = 4
+    Galerkin { [p_4 * nu[] *Dof{b_4} , {b_4} ]; In DomainLam; Jacobian Vol ; Integration I; }
+  EndIf
+  If(ORDER > 3) //ORDER = 6
+    Galerkin { [p_6 * nu[] *Dof{b_6} , {b_6} ]; In DomainLam; Jacobian Vol ; Integration I; }
+  EndIf
+  */
+
+Else // Directly using gauss points, nu[] and dhdb_NL[]
+
+  If (ORDER == 2) //ORDER = 2
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [  $nuprev * c_2~{i}   * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_02
+      Galerkin { [  $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_20
+      Galerkin { [  $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_22
+
+      Galerkin { JacNL[ SetVariable[1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi} * Dof{d a} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}   * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}   * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i}^2 * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+    EndFor
+  EndIf
+
+  If( ORDER == 3 ) //ORDER = 4
+    //Galerkin { [nu[]/9 *Dof{b_4} , {b_4} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $nuprev * c_2~{i} * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_02
+      Galerkin { [ $nuprev * c_4~{i} * Dof{b_4} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_04
+
+      Galerkin { [ $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_20
+      Galerkin { [ $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_22
+      Galerkin { [ $nuprev * c_2~{i} * c_4~{i} * Dof{b_4} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_24
+
+      Galerkin { [ $nuprev * c_4~{i} * Dof{d a} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_40
+      Galerkin { [ $nuprev * c_4~{i} * c_2~{i} * Dof{b_2} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_42
+      Galerkin { [ $nuprev * c_4~{i}^2 * Dof{b_4} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_44
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+    EndFor
+  EndIf
+
+    If( ORDER == 4 ) //ORDER = 6
+    //Galerkin { [nu[]/13 *Dof{b_6} , {b_6} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ nu[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{$bprev} ] ]{$nuprev} * Dof{d a} * w~{i} , {d a} ] ; // h_00
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $nuprev * c_2~{i} * Dof{b_2} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_02
+      Galerkin { [ $nuprev * c_4~{i} * Dof{b_4} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_04
+      Galerkin { [ $nuprev * c_6~{i} * Dof{b_6} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_06
+
+      Galerkin { [ $nuprev * c_2~{i}   * Dof{d a} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_20
+      Galerkin { [ $nuprev * c_2~{i}^2 * Dof{b_2} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_22
+      Galerkin { [ $nuprev * c_2~{i} * c_4~{i} * Dof{b_4} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_24
+      Galerkin { [ $nuprev * c_2~{i} * c_6~{i} * Dof{b_6} * w~{i} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_26
+
+      Galerkin { [ $nuprev * c_4~{i} * Dof{d a} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_40
+      Galerkin { [ $nuprev * c_4~{i} * c_2~{i} * Dof{b_2} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_42
+      Galerkin { [ $nuprev * c_4~{i}^2 * Dof{b_4} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_44
+      Galerkin { [ $nuprev * c_4~{i} * c_6~{i} * Dof{b_6} * w~{i} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_46
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb_NL[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi *          c_6~{i} * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_06
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_6~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_26
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_40
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_42
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_6~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_46
+
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} *           Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_60
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_2~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_62
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_4~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_64
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_66
+    EndFor
+  EndIf
+
+EndIf
+
+Return
+
+//---------------------------------------------------------------
+//---------------------------------------------------------------
+
+Macro Macro_Terms_DomainLam_h
+
+If(!NbrRegions[Domain_NonLin]) // linear case
+
+  If (ORDER > 1) //ORDER = 2
+    Galerkin { [ p_2 * nu[] * Dof{b_2}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+  EndIf
+  If(ORDER > 2) //ORDER = 4
+    // 0 = nu*b_2/5 + sigma*d^2*(-dt(b0)/60   + dt(b_2)/210-dt(b_4)/1260)
+    // 0 = nu*b_4/9 + sigma*d^2*(-dt(b_2)/1260 + dt(b_4)/1386)
+    Galerkin { [p_4 * nu[] *Dof{b_4} , {b_4} ]; In DomainLam; Jacobian Vol ; Integration I; }
+  EndIf
+
+Else // Directly using gauss points, h[] and dhdb[]
+
+  If (ORDER == 2) //ORDER = 2
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ // h_0
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_2
+
+      Galerkin { JacNL[ SetVariable[1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi} * Dof{d a} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *           c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+    EndFor
+  EndIf
+
+  If( ORDER == 3 ) //ORDER = 4
+    //Galerkin { [nu[]/9 *Dof{b_4} , {b_4} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ; // h_0
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_2
+      Galerkin { [ $hprev * c_4~{i} * w~{i} , {b_4} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_4
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+    EndFor
+  EndIf
+
+    If( ORDER == 4 ) //ORDER = 6
+    //Galerkin { [nu[]/13 *Dof{b_6} , {b_6} ]; In DomainLam ; Jacobian Vol ; Integration I; }
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [
+          SetVariable[ h[ SetVariable[({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{$bprev} ] ]{$hprev} * w~{i} , {d a} ] ; // h_0
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ $hprev * c_2~{i} * w~{i} , {b_2} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_2
+      Galerkin { [ $hprev * c_4~{i} * w~{i} , {b_4} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_4
+      Galerkin { [ $hprev * c_6~{i} * w~{i} , {b_6} ] ;  In DomainLam ; Jacobian Vol ; Integration I1p ; }// h_6
+
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor * dhdb[$bprev]* w~{i}]{$dhdb_wi}   * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_00
+      Galerkin { JacNL[ $dhdb_wi *          c_2~{i} * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_02
+      Galerkin { JacNL[ $dhdb_wi *          c_4~{i} * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_04
+      Galerkin { JacNL[ $dhdb_wi *          c_6~{i} * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_06
+
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} *           Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_20
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_22
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_4~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_24
+      Galerkin { JacNL[ $dhdb_wi * c_2~{i} * c_6~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_26
+
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} *           Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_40
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_2~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_42
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_44
+      Galerkin { JacNL[ $dhdb_wi * c_4~{i} * c_6~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_46
+
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} *           Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_60
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_2~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_62
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_4~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_64
+      Galerkin { JacNL[ $dhdb_wi * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } //dhdb_66
+    EndFor
+  EndIf
+
+EndIf
+
+Return
+
+//-----------------------------------------------------------------------------------
+
+
+Macro Macro_Terms_DomainLam_hysteresis
+
+If(NbrRegions[Domain_NL]) // nonlinear hysteretic case
+  If (ORDER == 2) //ORDER = 2
+    // for NR iterations
+    // History of h to be kept for every quadrature point along lamination thickness
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[ {h~{i}}[1],
+            ({d a}[1]+ c_2~{i}*{b_2}[1])/fillfactor,
+            ({d a}   + c_2~{i}*{b_2}   )/fillfactor ]{List[hyst_FeSi]} , {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * w~{i}          , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_Jiles0
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; } // h_Jiles2
+     EndFor
+
+     For i In{1:nbrQuadraturePnts} //dhdb_Jiles00, dhdb_Jiles02, dhdb_Jiles22, dhdb_Jiles20
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor *
+            dhdb_Jiles[ {h~{i}},
+              ({d a}+c_2~{i}*{b_2})/fillfactor,
+              {h~{i}}-{h~{i}}[1] ]{List[hyst_FeSi]}*w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}           * Dof{b_2} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+  EndIf
+
+  If (ORDER == 3) //ORDER = 4
+    For i In{1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[{h~{i}}[1],
+            ({d a}[1]+c_2~{i}*{b_2}[1]+c_4~{i}*{b_4}[1])/fillfactor,
+            ({d a}+   c_2~{i}*{b_2}   +c_4~{i}*{b_4}   )/fillfactor]{List[hyst_FeSi]}, {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { [ Dof{h~{i}}           * w~{i}, {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_4~{i} * w~{i}, {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+    For i In{1:nbrQuadraturePnts}
+      //dhdb_Jiles 00, 02, 04, 22, 20, 24, 44, 40, 42
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor *
+            dhdb_Jiles[ {h~{i}},
+                        ({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4})/fillfactor,
+                        {h~{i}}-{h~{i}}[1] ]{List[hyst_FeSi]} * w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}          * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i}          * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_2~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_4~{i} * Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_4~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+  EndIf
+
+  If (ORDER == 4) //ORDER = 6
+    For i In {1:nbrQuadraturePnts}
+      Galerkin { [ Dof{h~{i}} , {h~{i}} ] ;
+        In DomainLam  ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ -h_Jiles[ {h~{i}}[1],
+            ({d a}[1]+c_2~{i}*{b_2}[1]+c_4~{i}*{b_4}[1]+c_6~{i}*{b_6}[1])/fillfactor,
+            ({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor]{List[hyst_FeSi]}, {h~{i}} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { [ Dof{h~{i}}           * w~{i}, {d a} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_2~{i} * w~{i}, {b_2} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_4~{i} * w~{i}, {b_4} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { [ Dof{h~{i}} * c_6~{i} * w~{i}, {b_6} ]  ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+    For i In{1:nbrQuadraturePnts}
+      //dhdb_Jiles 00, 02, 04, 06, 22, 20, 24, 26, 44, 40, 42, 46, 66, 60, 62, 64
+      Galerkin { JacNL[ SetVariable[ 1/fillfactor *
+            dhdb_Jiles[ {h~{i}},
+              ({d a}+c_2~{i}*{b_2}+c_4~{i}*{b_4}+c_6~{i}*{b_6})/fillfactor,
+              {h~{i}}-{h~{i}}[1]]{List[hyst_FeSi]} * w~{i} ]{$dhdb_jiles} * Dof{d a} , {d a} ] ;
+        In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i}          * Dof{b_2} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i}          * Dof{b_4} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i}          * Dof{b_6} , {d a} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_2~{i} * Dof{b_2} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_2~{i} * Dof{d a} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_2~{i} * Dof{b_4} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_2~{i} * Dof{b_6} , {b_2} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_4~{i} * Dof{b_4} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_4~{i} * Dof{d a} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_4~{i} * Dof{b_2} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_4~{i} * Dof{b_6} , {b_4} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+
+      Galerkin { JacNL[ $dhdb_jiles * c_4~{i} * c_6~{i} * Dof{b_4} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles           * c_6~{i} * Dof{d a} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_2~{i} * c_6~{i} * Dof{b_2} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+      Galerkin { JacNL[ $dhdb_jiles * c_6~{i} * c_6~{i} * Dof{b_6} , {b_6} ] ; In DomainLam ; Jacobian Vol ; Integration I1p ; }
+    EndFor
+
+  EndIf
+
+
+
+EndIf
+
+
+Return
+
+
+
+
+//-----------------------------------------------------------------------------------
+// PostQuantities
+//-----------------------------------------------------------------------------------
+
+Macro PostQuantities_Homog
+
+  { Name b~{0} ; Value { Local { [ {d a}/fillfactor ] ; In DomainLam ; Jacobian Vol ; } } }
+  For k In{2:ORDER}
+    { Name b~{2*k-2}  ; Value { Term { [ alpha~{2*k-2}[]*{b~{2*k-2}}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; } } }
+    { Name baux~{2*k-2}  ; Value { Term { [ {b~{2*k-2}} ]  ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+  { Name btot  ; Value {
+      Term { [ {d a}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; }
+      For k In{2:ORDER}
+        Term { [ alpha~{2*k-2}[]*{b~{2*k-2}}/fillfactor ]  ; In DomainLam ; Jacobian Vol ; }
+      EndFor
+    }
+  }
+
+  { Name j~{0} ;
+    Value { Term { [ sigmaH[]*ialpha~{0}[]*Dt[{d a}]/\Vector[0,-1,0] ] ; In DomainLam ; Jacobian Vol ; } } }
+  For k In{2:ORDER}
+    { Name j~{2*k-2} ;
+      Value { Term { [ sigmaH[]*ialpha~{2*k-2}[]*Dt[{b~{2*k-2}}]/\Vector[0,-1,0] ] ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+
+  For k In {0:ORDERMAX:2}
+    { Name  aa~{k} ; Value { Local { [  alpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+    { Name daa~{k} ; Value { Local { [ dalpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+    { Name iaa~{k} ; Value { Local { [ ialpha~{k}[] ] ; In DomainLam ; Jacobian Vol ; } } }
+  EndFor
+
+  If(Flag_ComplexReluctivity) // Frequency domain
+    { Name j_beta  ; Value { Term { [ (Vector[0,1,0]*^{d a})*FACJ[] ] ; In DomainLam ; Jacobian Vol ;} } }
+    { Name b_alpha ; Value { Term { [ {d a}*FACB[] ] ; In DomainLam ; Jacobian Vol ; } } }
+
+    { Name ComplexPowerH ; Value { // real part -> eddy current losses; imag part-> magnetic energy
+        Integral { [ SymmetryFactor*AxialLength*{d a}*Conj[nuOm[]*{d a} ] ];
+          In DomainLam; Jacobian Vol ; Integration II ; }
+      }
+    }
+  EndIf
+
+  { Name JouleLossesH_local ;
+    Value {
+      If(Flag_ComplexReluctivity) // Frequency domain
+        Term { [ Re[ {d a}*Conj[ nuOm[]*{d a} ] ] ];
+          In DomainLamC ; Jacobian Vol ; }
+
+      Else // Time domain
+
+        Term { [ dlam^2*sigmaH[]*q_0_0*SquNorm[Dt[{d a}]] ] ;
+          In DomainLamC ; Jacobian Vol ; }
+        If (ORDER>1)
+          Term { [   dlam^2*sigmaH[]*q_2_2*SquNorm[Dt[{b_2}]] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_0_2*Dt[{d a}]*Dt[{b_2}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+        If (ORDER>2)
+          Term { [   dlam^2*sigmaH[]*q_4_4*SquNorm[Dt[{b_4}] ] ];
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_2_4*Dt[{b_2}]*Dt[{b_4}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+        If (ORDER>3)
+          Term { [   dlam^2*sigmaH[]*q_6_6*SquNorm[Dt[{b_6}] ] ];
+            In DomainLamC ; Jacobian Vol ; }
+          Term { [ 2*dlam^2*sigmaH[]*q_4_6*Dt[{b_4}]*Dt[{b_6}] ] ;
+            In DomainLamC ; Jacobian Vol ; }
+        EndIf
+
+      EndIf
+
+    } }
+
+  { Name JouleLossesH ;
+    Value {
+      If(Flag_ComplexReluctivity) // Frequency domain
+        Integral { [ SymmetryFactor*AxialLength*Re[ {d a}*Conj[ nuOm[]*{d a} ] ] ];
+          In DomainLamC ; Jacobian Vol ; Integration II;}
+      Else // Time domain
+        Integral { [ SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_0_0*SquNorm[Dt[{d a}]] ] ;
+          In DomainLamC ; Jacobian Vol ; Integration II; }
+        If (ORDER>1)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_2_2*SquNorm[Dt[{b_2}]] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_0_2*Dt[{d a}]*Dt[{b_2}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>2)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_4_4*SquNorm[Dt[{b_4}] ] ];
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_2_4*Dt[{b_2}]*Dt[{b_4}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>3)
+          Integral { [   SymmetryFactor*AxialLength* dlam^2*sigmaH[]*q_6_6*SquNorm[Dt[{b_6}] ] ];
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor*AxialLength* 2*dlam^2*sigmaH[]*q_4_6*Dt[{b_4}]*Dt[{b_6}] ] ;
+            In DomainLamC ; Jacobian Vol ; Integration II; }
+        EndIf
+      EndIf
+    } }
+
+  { Name MagEnergyH ; // this is only ok in the linear case
+    Value {
+      If(!NbrRegions[Domain_NL])
+        Integral { [ SymmetryFactor * AxialLength * nu[] * {d a} * Dt[{d a}] ] ;
+          In DomainLam ; Jacobian Vol ; Integration II; }
+        If (ORDER>1)
+          Integral { [ SymmetryFactor * AxialLength * p_2 * nu[] * {b_2} * Dt[Dt[{b_2}]] ] ;
+            In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER>2)
+          Integral { [ SymmetryFactor * AxialLength * p_4 * nu[] * {b_4} * Dt[Dt[{b_4}]] ] ;
+            In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+      Else
+        // +++ What follows have to be checked... I think the crossed terms should appear, like in the formulation
+        // quid of the integration points in the thickness of the lamination ...
+        If(ORDER == 1)
+          Integral { [ SymmetryFactor * AxialLength * nu[{d a}] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER == 2)
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2})/fillfactor] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2})/fillfactor] * {b_2} * Dt[Dt[{b_2}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+        If (ORDER == 3)
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {d a} * Dt[{d a}] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {b_2} * Dt[Dt[{b_2}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+          Integral { [ SymmetryFactor * AxialLength * nu[({d a}+{b_2}+{b_4})/fillfactor] * {b_4} * Dt[Dt[{b_4}]] ] ; In DomainLam ; Jacobian Vol ; Integration II; }
+        EndIf
+
+      EndIf
+
+    }
+  }
+
+Return
diff --git a/HomogenisationLaminations/srm/MagStaDyn_SlidingSurface.pro b/HomogenisationLaminations/srm/MagStaDyn_SlidingSurface.pro
new file mode 100644
index 0000000..acf4b77
--- /dev/null
+++ b/HomogenisationLaminations/srm/MagStaDyn_SlidingSurface.pro
@@ -0,0 +1,789 @@
+// --------------------------------------------------------------------------
+// Magnetodynamics - Magnetic vector potential (a) formulation
+// --------------------------------------------------------------------------
+
+
+DefineConstant[
+  Freq,
+  Val_Rint, Val_Rext,
+  SymmetryFactor     = (Flag_Symmetry?2:1), //*(Flag_HalfLam?2:1),
+  Nb_max_iter        = 100,
+  relaxation_factor  = 1,
+  stop_criterion     = 1e-4, // 1e-5
+  T = 1/Freq, // Fundamental period in s
+  // Mechanical equation
+  Inertia = 0
+  Flag_ImposedSpeed = 1,
+  // time loop, defaut values
+  time0      = 0,
+  NbT        = 1,
+  timemax    = NbT*T,
+  NbSteps    = 100,
+  delta_time = T/NbSteps
+] ;
+
+Group {
+  DefineGroup[
+    Domain, DomainCC, DomainC, DomainInf,
+    SkinDomainC,
+    DomainS, DomainB,
+    SurfaceElec, Surf_EC_bn0
+  ] ;
+}
+
+Function {
+  DefineFunction[
+    js0, mu, nu, sigma, rho,
+    h, dhdb, dhdb_NL,
+    Friction, Torque_mec
+  ] ;
+}
+
+
+Function {
+  // Sliding surface:
+  // a1 is the angular span of Region and RegionRef.
+  // a0 is the mesh step of the meshes of
+  // a2[] is the angular position (in radian) of the rotor
+  // relative to its reference position (as in the msh file)
+  // assumed to be aligned with the stator.
+  // a3[] is the shear angle of region AIRBM
+  // (smaller than half the discretization step of the sliding surface
+  // to adapt to a2[] values that are not multiple of this step).
+  // AlignWithMaster[] maps a point of coordinates {X[], Y[], Z[]} onto
+  // its image in the open set RegionRef-SubRegionRef by the symmetry mapping.
+  // Coef[] is evaluated on Master nodes
+  // fFloor[] is a safe version of Floor[] for real represented int variables
+  // fRem[a,b] substracts from a multiple of b so that the result is in [0,1[
+
+  Periodicity = (NbrPolesInModel%2)?-1:1 ;  // -1 for antiperiodicity, 1 for periodicity
+  RotatePZ[] = Rotate[ XYZ[], 0, 0, $1 ] ;
+  Tol = 1e-8 ; fFloor[] = Floor[ $1 + Tol ] ; fRem[] = $1 - fFloor[ $1 / $2 ] * $2;
+  a1 = 2.*Pi/(Flag_Symmetry?2:1) ; // total angular aperture MB [rad]
+  NbrDiv = (nDivBand /(Flag_Symmetry?2:1));
+  a0 = a1/NbrDiv ; // angular span of one moving band element
+  a2[] = $RotorPosition ;
+  a3[] = ( ( fRem[ a2[], a0 ]#2 <= 0.5*a0 ) ? #2 : #2-a0 ) ;
+
+  AlignWithMaster[] = RotatePZ[ - fFloor[ (Atan2[ Y[], X[] ] - a3[] )/a1 ] * a1 ] ;
+  RestoreRef[] = XYZ[] - Vector[ 0, 0, SlidingSurfaceShift ] ;
+  Coef[] = ( fFloor[ ((Atan2[ Y[], X[] ] - a2[] )/a1) ] % 2 ) ? Periodicity : 1. ;
+
+  // Maxwell stress tensor
+  T_max[] = ( SquDyadicProduct[$1] - SquNorm[$1] * TensorDiag[0.5, 0.5, 0.5] ) / mu0 ;
+  T_max_cplx[] = Re[0.5*(TensorV[CompX[$1]*Conj[$1], CompY[$1]*Conj[$1], CompZ[$1]*Conj[$1]]
+      - $1*Conj[$1] * TensorDiag[0.5, 0.5, 0.5] ) / mu0] ;
+  T_max_cplx_2f[] = 0.5*(TensorV[CompX[$1]*$1, CompY[$1]*$1, CompZ[$1]*$1] -
+    $1*$1 * TensorDiag[0.5, 0.5, 0.5] ) / mu0 ; // To check ????
+
+  AngularPosition[] = (Atan2[$Y,$X]#7 >= 0.)? #7 : #7+2*Pi ;
+
+  // Torque computed in postprocessing
+  Torque_mag[] = $Trotor ;
+  //Torque_mag[] = $Tstator ;
+
+
+  relaxation_function[] = ($Iteration<Nb_max_iter/2) ? relaxation_factor : 0.2 ;
+  relax_max = 1;
+  relax_min = 1/10;
+  relax_numtest=10;
+  test_all_factors=0;
+  relaxation_factors_lin() = LinSpace[relax_max,relax_min,relax_numtest];
+
+}
+
+
+Jacobian {
+  { Name Vol ;
+    Case {
+      { Region DomainInf ; Jacobian VolSphShell {Val_Rint, Val_Rext} ; }
+      { Region All ;       Jacobian Vol ; }
+    }
+  }
+  { Name Sur ;
+    Case {
+      { Region All ; Jacobian Sur ; }
+    }
+  }
+}
+
+Integration {
+  { Name II ;
+    Case {
+      { Type Gauss ;
+        Case {
+          { GeoElement Triangle    ; NumberOfPoints  4 ; }
+          { GeoElement Quadrangle  ; NumberOfPoints  4 ; }
+          { GeoElement Tetrahedron ; NumberOfPoints  4 ; }
+          { GeoElement Hexahedron  ; NumberOfPoints  6 ; }
+          { GeoElement Prism       ; NumberOfPoints  6 ; } // 21
+          { GeoElement Line        ; NumberOfPoints  4 ; }
+        }
+      }
+    }
+  }
+
+  { Name I1p ;
+    Case {
+      { Type Gauss ;
+        Case {
+          { GeoElement Triangle    ; NumberOfPoints  1 ; }
+        }
+      }
+    }
+  }
+
+  { Name IIvol ;
+    Case {
+      { Type Gauss ;
+        Case {
+          { GeoElement Hexahedron ; NumberOfPoints  14 ; } // Gauss points for Hexahedron: valid choices: 6, 14, 34, 77
+          { GeoElement Prism      ; NumberOfPoints  21 ; }  // Prism: valid choices: 6, 9, 21, 42
+
+        }
+      }
+    }
+  }
+
+}
+
+// --------------------------------------------------------------------------
+
+
+Constraint {
+
+  { Name MVP ;
+    Case {
+      { Type Assign; Region Sur_Dirichlet_bn  ; Value 0. ; }
+      If(Flag_Symmetry)
+        { Type Link ; Region Sur_StatorPerSlave ; RegionRef Sur_StatorPerMaster ;
+          ToleranceFactor 1e-8;	Coefficient Periodicity ; Function RotatePZ[ -a1 ] ; }
+
+        { Type Link ; Region Sur_RotorPerSlave ; RegionRef Sur_RotorPerMaster ;
+          ToleranceFactor 1e-8; Coefficient Periodicity ; Function RotatePZ[ -a1 ] ; }
+      EndIf
+
+      // Sliding surface
+      { Type Link ; Region Sur_SlidingSlave ; SubRegion Lin_SlidingSubslave ;
+        RegionRef Sur_SlidingMaster ; SubRegionRef Lin_SlidingSubmaster ;
+        ToleranceFactor 1e-8;
+        Coefficient Coef[] ; Function AlignWithMaster[] ; FunctionRef RestoreRef[] ; }
+    }
+  }
+
+  { Name u ;
+    Case {
+      { Type Assign ; Region Sur_Dirichlet_u ; Value 0. ; }
+    }
+  }
+
+
+  If(_3Dmodel)
+    // A correct spanning-tree is essential to the validity of the model.
+    // The spanning-tree must be autosimilar by rotation on the sliding surfaces
+    // (SubRegion2 clause, only the edges aligned with the Z axis are placed in
+    // the tree), and be also a spanning-tree and Dirichlet and Link surfaces and
+    // their boundaries (SubRegion clause).
+    { Name GaugeCondition_MVP ; Type Assign ;
+      Case {
+        If(Flag_GaugeType==TREE_COTREE_GAUGE)
+          { Region Vol_Tree ; Value 0. ;
+            SubRegion Region[ {Lin_Tree, Sur_Tree} ] ;
+            SubRegion2 Region[ Sur_Tree_Sliding, AlignedWith Z ] ;
+          }
+        EndIf
+      }
+    }
+  EndIf
+
+
+  //---------------------------------------------------------------------------------
+  { Name CurrentPosition ; // [m]
+    Case {
+      //{ Region DomainKin ; Type Init ; Value ($RotorPosition = RotorPosition) ; }
+      { Region DomainKin ; Type Init ; Value ($PreviousRotorPosition = 0) ; } // From machine_magstadyn
+    }
+  }
+
+  { Name CurrentVelocity ; // [rad/s]
+    Case {
+      { Region DomainKin ; Type Init ; Value 0. ; }
+    }
+  }
+
+}
+
+FunctionSpace {
+  If(_3Dmodel)
+    // Magnetic vector potential a (b = curl a)
+    { Name Hcurl_a ; Type Form1 ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_Edge ;
+          Support Dom_Hcurl_a ; Entity EdgesOf[ DomainCC ] ; }
+        { Name se2 ; NameOfCoef ae2 ; Function BF_Edge ;
+          Support Dom_Hcurl_a ; Entity EdgesOf[ DomainC, Not SkinDomainC ] ; }
+
+        // where fixing a=0 is too strong, rather fixing n x a = n x grad u !!!
+        { Name su ; NameOfCoef un ; Function BF_GradNode ;
+          Support DomainC ; Entity NodesOf[ SkinDomainC ] ; }
+      }
+      Constraint {
+        { NameOfCoef ae  ; EntityType EdgesOf ; NameOfConstraint MVP ; }
+        { NameOfCoef ae2 ; EntityType EdgesOf ; NameOfConstraint MVP ; }
+        { NameOfCoef ae  ; EntityType EdgesOfTreeIn ; EntitySubType StartingOn ;
+          NameOfConstraint GaugeCondition_MVP ; }
+        { NameOfCoef un;  EntityType NodesOf ; NameOfConstraint u; }
+      }
+    }
+
+    // Electric scalar potential
+    { Name Hregion_u ; Type Form0 ;
+      BasisFunction {
+        { Name sr ; NameOfCoef ur ; Function BF_GroupOfNodes ;
+          Support DomainC ; Entity GroupsOfNodesOf[ SurfaceElec ] ; }
+      }
+      GlobalQuantity {
+        { Name U ; Type AliasOf        ; NameOfCoef ur ; }
+        { Name I ; Type AssociatedWith ; NameOfCoef ur ; }
+      }
+      Constraint {
+        { NameOfCoef U ; EntityType GroupsOfNodesOf ; NameOfConstraint V_massive ; }
+        { NameOfCoef I ; EntityType GroupsOfNodesOf ; NameOfConstraint I_massive ; }
+      }
+    }
+  Else
+    // 2D model => with homogenization
+    { Name Hcurl_a ; Type Form1P ;
+      BasisFunction {
+        { Name se ; NameOfCoef ae ; Function BF_PerpendicularEdge ;
+          Support Domain ; Entity NodesOf[ All ] ; }
+      }
+      Constraint {
+        { NameOfCoef ae  ; EntityType NodesOf ; NameOfConstraint MVP ; }
+      }
+    }
+    { Name Hregion_u ; Type Vector ;
+      BasisFunction {
+        { Name sr ; NameOfCoef vr ; Function BF_RegionZ ;
+          Support DomainC ; Entity DomainC ; } }
+      GlobalQuantity {
+        { Name U ; Type AliasOf        ; NameOfCoef vr ; }
+        { Name I ; Type AssociatedWith ; NameOfCoef vr ; } }
+      Constraint {
+        { NameOfCoef U ; EntityType Region ; NameOfConstraint V_massive ; }
+        { NameOfCoef I ; EntityType Region ; NameOfConstraint I_massive ; }
+      }
+    }
+
+  EndIf
+
+  { Name Is1 ; Type Vector ;
+    BasisFunction {
+      { Name sr ; NameOfCoef ir ; Function BF_RegionZ ;
+        Support DomainB ; Entity DomainB ; }
+    }
+    GlobalQuantity {
+      { Name Ib ; Type AliasOf        ; NameOfCoef ir ; }
+      { Name Ub ; Type AssociatedWith ; NameOfCoef ir ; }
+    }
+    Constraint {
+      { NameOfCoef Ub ; EntityType Region ; NameOfConstraint V_stranded ; }
+      { NameOfCoef Ib ; EntityType Region ; NameOfConstraint I_stranded ; }
+    }
+  }
+
+  // Uz et Iz for circuit relations
+  { Name Hregion_Cir ; Type Scalar ;
+    BasisFunction {
+      { Name sr ; NameOfCoef ir ; Function BF_Region ;
+        Support DomainZtot_Cir ; Entity DomainZtot_Cir ; }
+    }
+    GlobalQuantity {
+      { Name Iz ; Type AliasOf        ; NameOfCoef ir ; }
+      { Name Uz ; Type AssociatedWith ; NameOfCoef ir ; }
+    }
+    Constraint {
+      //{ NameOfCoef Uz ; EntityType Region ; NameOfConstraint VInit_Cir ; }
+      { NameOfCoef Uz ; EntityType Region ; NameOfConstraint V_circuit ; }
+      { NameOfCoef Iz ; EntityType Region ; NameOfConstraint I_circuit ; }
+    }
+  }
+
+  // BFs for case with hysteresis
+  { Name H_hysteresis ; Type Vector;
+    BasisFunction {
+      { Name sex ; NameOfCoef aex ; Function BF_VolumeX ; Support Domain ; Entity VolumesOf[ All ] ; }
+      { Name sey ; NameOfCoef aey ; Function BF_VolumeY ; Support Domain ; Entity VolumesOf[ All ] ; }
+      { Name sez ; NameOfCoef aez ; Function BF_VolumeZ ; Support Domain ; Entity VolumesOf[ All ] ; }
+    }
+  }
+
+  // For the mechanical equation
+  { Name Position ; Type Scalar ;
+    BasisFunction {
+      { Name sr ; NameOfCoef pr ; Function BF_Region ;
+        Support DomainKin ; Entity DomainKin ; } }
+    GlobalQuantity {
+      { Name P ; Type AliasOf  ; NameOfCoef pr ; } }
+    Constraint {
+      { NameOfCoef P ; EntityType Region ; NameOfConstraint CurrentPosition ; } }
+  }
+
+  { Name Velocity ; Type Scalar ;
+    BasisFunction {
+      { Name sr ; NameOfCoef vr ; Function BF_Region ;
+        Support DomainKin ; Entity DomainKin ; } }
+    GlobalQuantity {
+      { Name V ; Type AliasOf ; NameOfCoef vr ; } }
+    Constraint {
+      { NameOfCoef V ; EntityType Region ; NameOfConstraint CurrentVelocity ; }
+    }
+  }
+
+
+}
+
+If(!_3Dmodel)
+  Include "Macro_homogenisation_laminations.pro";
+EndIf
+
+Formulation {
+
+  { Name MagStaDyn_a ; Type FemEquation ;
+    Quantity {
+      { Name a ; Type Local ; NameOfSpace Hcurl_a ; }
+
+      // Massive conductor (DomainC)
+      { Name v ; Type Local ; NameOfSpace Hregion_u ; }
+      { Name U ; Type Global ; NameOfSpace Hregion_u [U] ; }
+      { Name I ; Type Global ; NameOfSpace Hregion_u [I] ; }
+
+      // Source: Stranded conductor (DomainB)
+      { Name ir ; Type Local  ; NameOfSpace Is1 ; }
+      { Name Ub ; Type Global ; NameOfSpace Is1 [Ub] ; }
+      { Name Ib ; Type Global ; NameOfSpace Is1 [Ib] ; }
+
+      // Circuit quantities (DomainZtot_Cir)
+      { Name Uz ; Type Global ; NameOfSpace Hregion_Cir [Uz] ; }
+      { Name Iz ; Type Global ; NameOfSpace Hregion_Cir [Iz] ; }
+
+      If(Flag_Hysteresis)
+        { Name h ; Type Local ; NameOfSpace H_hysteresis ; }
+      EndIf
+
+      If(!_3Dmodel)
+        // Homog laminations 2D
+        For k In {2:ORDERMAX} // b_2, b_4, b_6
+          { Name b~{2*k-2}  ; Type Local ; NameOfSpace Hb~{2*k-2} ; }
+        EndFor
+        If(Flag_Hysteresis)
+          For i In {1:nbrQuadraturePnts}
+            { Name h~{i} ; Type Local ; NameOfSpace H_hysteresis~{i} ; }
+          EndFor
+        EndIf
+      EndIf
+
+    }
+    Equation {
+      Galerkin { [ nu[] * Dof{d a} , {d a} ]     ;
+        In Domain_L  ; Jacobian Vol ; Integration II ; }
+
+      If(NbrRegions[Domain_NL])
+        If( _3Dmodel || (_2Dmodel && ORDER==1))
+          If(!Flag_Hysteresis)
+            Galerkin { [ nu[{d a}/fillfactor] * Dof{d a} , {d a} ]     ;
+              In Domain_NL  ; Jacobian Vol ; Integration II ; }
+            Galerkin { JacNL [ 1/fillfactor*dhdb_NL[{d a}] * Dof{d a} , {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration II ; }
+          Else
+            Galerkin { [ SetVariable[
+                  h_Jiles[ {h}[1],
+                    {d a}[1]/fillfactor,
+                    {d a}/fillfactor ]{List[hyst_FeSi]},
+                  QuadraturePointIndex[] ]{$hjiles}, {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+            Galerkin { JacNL[ 1/fillfactor*dhdb_Jiles[
+                  {h},
+                  {d a}/fillfactor,
+                  {h}-{h}[1] ]{List[hyst_FeSi]} * Dof{d a} , {d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+
+            // h_Jiles saved in local quantity {h}
+            // BF is constant per element => 1 integration point is enough
+            Galerkin { [ Dof{h}   , {h} ]  ; // saving h_Jiles in local quantity h
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+            Galerkin { [ -GetVariable[QuadraturePointIndex[]]{$hjiles} , {h} ]  ;
+              In Domain_NL ; Jacobian Vol ; Integration I1p ; }
+          EndIf
+        EndIf
+      EndIf
+
+      // Source in stranded coil imposed via function
+      Galerkin { [ -js0[], {a} ] ; In DomainS ;
+        Jacobian Vol ; Integration II ; }
+
+      Galerkin { DtDof[ sigma[] * Dof{a} , {a} ] ;
+        In DomainC ; Jacobian Vol ; Integration II ; }
+
+      // voltage-current equation for massive conductors (DomainC)
+      If(_3Dmodel)
+        Galerkin { [ sigma[] * Dof{d v}, {a} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+
+        Galerkin { DtDof[ sigma[] * Dof{a} , {d v} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+        Galerkin { [ sigma[] * Dof{d v} , {d v} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+        GlobalTerm { [ Dof{I} , {U} ] ; In SurfaceElec ; }
+      Else
+        Galerkin {  [ -sigma[]/AxialLength * Dof{v} , {a} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+        Galerkin { DtDof [ sigma[] * Dof{a} , {v} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+        Galerkin { [ -sigma[]/AxialLength * Dof{v} , {v} ] ;
+          In DomainC ; Jacobian Vol ; Integration II ; }
+        GlobalTerm { [ Dof{I} , {U} ] ; In DomainC ; }
+
+        If(!Flag_ComplexReluctivity && !Flag_Statics)// Either additional terms or complex nu in DomainLam
+          Call Macro_Terms_DomainLamC_sigma;
+          If(!Flag_Hysteresis)
+            Call Macro_Terms_DomainLam_nu;
+          Else
+            Call Macro_Terms_DomainLam_hysteresis;
+          EndIf
+        EndIf
+      EndIf
+
+      Galerkin { [ -NbrWires_Area[] * Dof{ir}, {a} ] ;
+        In DomainB ; Jacobian Vol ; Integration II ; }
+      Galerkin { DtDof [ (_3Dmodel ? FactorLam : AxialLength) * NbrWires_Area[] * Dof{a}, {ir} ] ; // AxialLength
+        In DomainB ; Jacobian Vol ; Integration II ; }
+      GlobalTerm { [ Dof{Ub}/(SymmetryFactor*(Flag_HalfLam?2:1)), {Ib} ] ; In DomainB ; } //+++ constants added
+
+      If(Flag_Cir)
+        //Circuit related terms
+        GlobalTerm { NeverDt[ Dof{Uz}                , {Iz} ] ; In Resistance_Cir; }
+        GlobalTerm { NeverDt[ Resistance[{Uz}] * Dof{Iz}, {Iz} ] ; In Resistance_Cir; }
+
+        GlobalTerm { [ 0. * Dof{Iz} , {Iz} ] ; In DomainZtot_Cir ; }
+        GlobalTerm { [ 0. * Dof{Uz} , {Iz} ] ; In DomainZtot_Cir ; }
+
+        GlobalEquation {
+          Type Network ; NameOfConstraint ElectricalCircuit ;
+          If(_3Dmodel)
+            { Node {I};  Loop {U};  Equation {I};  In SurfaceElec ; }
+          Else
+            { Node {I};  Loop {U};  Equation {I};  In DomainC ; }
+          EndIf
+          { Node {Ib}; Loop {Ub}; Equation {Ub}; In DomainB ; }
+          { Node {Iz}; Loop {Uz}; Equation {Uz}; In DomainZtot_Cir ; }
+        }
+      EndIf
+
+    }
+  }
+
+  // Mechanics-------------------------------------------------------------------------------------------
+
+  { Name Mechanical ; Type FemEquation ;
+    Quantity {
+      { Name V ; Type Global ; NameOfSpace Velocity [V] ; } // velocity
+      { Name P ; Type Global ; NameOfSpace Position [P] ; } // position
+    }
+    Equation {
+      GlobalTerm { DtDof [ Inertia * Dof{V} , {V} ] ; In DomainKin ; }
+      GlobalTerm { [ Friction[] * Dof{V} , {V} ] ; In DomainKin ; }
+      GlobalTerm { [        Torque_mec[] , {V} ] ; In DomainKin ; }
+      GlobalTerm { [       -Torque_mag[] , {V} ] ; In DomainKin ; }
+
+      GlobalTerm { DtDof [ Dof{P} , {P} ] ; In DomainKin ; }
+      GlobalTerm {       [-Dof{V} , {P} ] ; In DomainKin ; }
+    }
+  }
+
+
+}
+
+
+Resolution {
+
+  { Name Analysis ;
+    System {
+      If( (Flag_AnalysisType<2) || NbrRegions[Domain_NL])
+        { Name Sys_Mag ; NameOfFormulation  MagStaDyn_a  ;}
+      Else
+        { Name Sys_Mag ; NameOfFormulation  MagStaDyn_a ; Frequency Freq; }
+      EndIf
+      If(Flag_AnalysisType==1 && !Flag_ImposedSpeed)
+        { Name Sys_Mec ; NameOfFormulation Mechanical ; }
+      EndIf
+    }
+    Operation {
+
+      If(Clean_Results)
+        // SystemCommand[StrCat["rm -rf ", ResDir]];
+        SystemCommand[StrCat["rm -rf ", ResDir, "*.pos"]];
+        // SystemCommand[StrCat["rm -rf ", ResDir, "*.dat"]];
+        SystemCommand[StrCat["rm -rf ", ResDir, "*m0*.dat"]]; // 2D
+        // SystemCommand[StrCat["rm -rf ", ResDir, "*m1*.dat"]]; // 3D
+      EndIf
+      CreateDir[ResDir];
+
+      If(_3Dmodel)
+        Evaluate[ $vol_airgap  = Vol_Rotor_Airgap[] ];
+        // Evaluate[ $vol_airgapS = Vol_Stator_Airgap[]];
+        // Print[ {$vol_airgap, $vol_airgapS}, Format "===> Check airgap volumes: VagR=%e VagS=%e "] ;
+      EndIf
+
+      If(Flag_AnalysisType!=1)
+        If(Flag_AnalysisType==2) // For convience, useful in postpro... not needed
+          SetTime[Freq];
+        EndIf
+
+        Evaluate[ $RotorPosition = RotorPosition ];
+        ChangeOfCoordinates[ NodesOf[ Vol_Moving ], RotatePZ[ a2[] ] ] ;
+        ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], RotatePZ[ a3[] ] ] ;
+        /*
+        // checking
+        Evaluate[ $a2 = a2[], $a3 = a3[] ];
+        Evaluate[ $aa = Fmod[ a2[], a0 ], $bb = fRem[ a2[], a0 ] ] ;
+        Print[ {$RotorPosition*rad2deg, $a2*rad2deg, $a3*rad2deg, $aa*rad2deg, $bb*rad2deg},
+        Format "wt=%e a2=%e a3=%e %e %e"] ;
+        */
+        UpdateConstraint[Sys_Mag];
+
+        ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], XYZ[] - Vector[ 0, 0, SlidingSurfaceShift ] ] ;
+
+        If(!NbrRegions[Domain_NL])
+          Generate[Sys_Mag] ; Solve[Sys_Mag] ;
+        Else
+          IterativeLoop[Nb_max_iter, stop_criterion, relaxation_factor]{
+            GenerateJac[Sys_Mag] ; SolveJac[Sys_Mag] ; }
+        EndIf
+        SaveSolution [Sys_Mag] ;
+
+        Test[ GetNumberRunTime[visu]{StrCat[main,"Visu/Real-time maps"]} ]{
+          PostOperation[Get_FieldMaps];
+        }
+        PostOperation[Get_GlobalQuantities];
+
+
+        ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], XYZ[] + Vector[ 0, 0, SlidingSurfaceShift ] ] ;
+
+      Else // time domain
+
+        Evaluate[ $RotorPosition = RotorPosition, $PreviousRotorPosition=0 ];
+        InitSolution[Sys_Mag]; SaveSolution[Sys_Mag];
+        If(!Flag_ImposedSpeed) // Full dynamics
+          InitSolution[Sys_Mec];
+          InitSolution[Sys_Mec]; // Twice for avoiding warning (a = d_t^2 x)
+          Evaluate[ $Tstator = 0., $Trotor = 0. ];
+        EndIf
+
+        TimeLoopTheta[time0, timemax, delta_time , 1.]{
+
+          If(Flag_ImposedSpeed)
+            Evaluate[ $RotorPosition = RotorPosition + wr*($TimeStep-1)*$DTime ];
+            // Print[ {$TimeStep, $Time, $RotorPosition*rad2deg}, Format "====> timestep=%e time=%e pos=%e"] ;
+          Else
+            Evaluate[ $RotorPosition = $RotorPosition + $PreviousRotorPosition ]; // This is not correct
+          EndIf
+
+          Test[ $TimeStep == 1 ]{
+            ChangeOfCoordinates[ NodesOf[ Vol_Moving ], RotatePZ[ a2[] ] ] ;
+          }
+          {
+            ChangeOfCoordinates[ NodesOf[ Vol_Moving ], RotatePZ[ delta_theta[] ] ] ; // either fixed or based on the mechanical computation
+          }
+
+          ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], RotatePZ[ a3[] ] ] ;
+
+          UpdateConstraint[Sys_Mag];
+
+          ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], XYZ[] - Vector[ 0, 0, SlidingSurfaceShift ] ] ;
+
+          If(!NbrRegions[Domain_NL])
+            Generate[Sys_Mag] ; Solve[Sys_Mag] ;
+          Else
+            IterativeLoop[Nb_max_iter, stop_criterion, relaxation_function[]]{
+              GenerateJac[Sys_Mag] ;
+              // If(!Flag_Hysteresis)
+              SolveJac[Sys_Mag] ;
+              // Else
+              //SolveJac_AdaptRelax[Sys_Mag, relaxation_factors_lin(), test_all_factors ] ;
+              //EndIf
+            }
+          EndIf
+          SaveSolution [Sys_Mag] ;
+
+          Test[ GetNumberRunTime[visu]{StrCat[main,"Visu/Real-time maps"]} ]{
+            PostOperation[Get_FieldMaps];
+          }
+          PostOperation[Get_GlobalQuantities];
+          //Test[ $TimeStep > 1 ]{ PostOperation[Get_GlobalQuantities] ; }
+
+          If(!Flag_ImposedSpeed)
+            Evaluate[ $PreviousRotorPosition = $RotorPosition ];
+
+            Generate [Sys_Mec] ; Solve [Sys_Mec] ; SaveSolution [Sys_Mec] ;
+            PostOperation[Get_MechanicalQs];
+            Print[ {$RotorPosition, $PreviousRotorPosition}, Format "====> Pos=%e PrevPos=%e"] ;
+          EndIf
+
+          ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], XYZ[] + Vector[ 0, 0, SlidingSurfaceShift ] ] ;
+          ChangeOfCoordinates[ NodesOf[ Sur_SlidingMaster ], RotatePZ[ -a3[] ] ] ;
+        }
+
+      EndIf
+
+
+    }
+  }
+
+}
+
+
+PostProcessing {
+
+  { Name MagStaDyn_a ; NameOfFormulation MagStaDyn_a;
+    PostQuantity {
+      { Name a  ; Value { Term { [ {a} ]         ; In Domain ; Jacobian Vol ; } } }
+      { Name az ; Value { Term { [ CompZ[{a}] ]  ; In Domain ; Jacobian Vol ; } } }
+      { Name b ; Value { Term { [ {d a} ]        ; In Domain ; Jacobian Vol ; } } }
+      { Name bsurf ; Value { Term { [ {d a} ]    ; In Sur_Link ; Jacobian Sur ; } } }
+      { Name h  ; Value {
+          Local { [ nu[]*{d a} ] ; In Domain_L ; Jacobian Vol ; }
+          If(!Flag_Hysteresis)
+            Local { [ nu[{d a}]*{d a} ] ; In Domain_NL ; Jacobian Vol ; }
+          Else
+            Local { [ {h} ] ; In Domain_NL ; Jacobian Vol ; }
+          EndIf
+        }
+      }
+      If(Flag_Hysteresis)
+        { Name hdb  ; Value { // Useful for computing losses in hysteretic case, by integrating in one period (steady state)
+            Local { [ {h}*({d a}-{d a}[1]) ] ; In Domain_NL  ; Jacobian Vol ; }
+          }
+        }
+      EndIf
+
+      { Name v ; Value { Term { [ {v} ] ; In DomainC ; Jacobian Vol ; } } }
+
+      { Name e ; Value { Term { [ -(Dt[{a}] + {d v}) ]         ; In DomainC ; Jacobian Vol ; } } }
+      { Name j ; Value { Term { [ -sigma[]*(Dt[{a}] + {d v}) ] ; In DomainC ; Jacobian Vol ; } } }
+
+      { Name js0 ; Value { Term { [ js0[] ] ; In DomainS ; Jacobian Vol ; } } }
+
+      { Name Flux ;
+        Value {
+          Integral {
+            [ SymmetryFactor*(Flag_HalfLam?2:1)*(_3Dmodel?FactorLam:AxialLength)/Sc[]*Idir[]* Vector[0,0,1] * {a} ] ;
+            In Region[{DomainS,DomainB}] ; Jacobian Vol ; Integration II ;
+          }
+        }
+      }
+
+      { Name rhoj2 ; // local losses
+        Value {
+          Term { [ sigma[]*SquNorm[ Dt[{a}]+{d v}] ] ; In DomainC ; Jacobian Vol ; }
+          Term { [ 1./sigma[]*SquNorm[ IA[]*{ir} ] ] ; In Phase1  ; Jacobian Vol ; }
+          Term { [ 1./sigma[]*SquNorm[ IB[]*{ir} ] ] ; In Phase2  ; Jacobian Vol ; }
+          Term { [ 1./sigma[]*SquNorm[ IC[]*{ir} ] ] ; In Phase3  ; Jacobian Vol ; }
+        }
+      }
+
+      { Name JouleLosses ; // global losses
+        Value {
+          Integral { [ SymmetryFactor * (Flag_HalfLam?2.:1.) * FactorLam * sigma[] * SquNorm[ -(Dt[{a}] + {d v}) ] ] ;
+            In DomainC ; Jacobian Vol ; Integration II ; }
+          Integral { [ 1./sigma[]*SquNorm[ IA[]*{ir} ] ] ; In Phase1 ; Jacobian Vol ; Integration II ; }
+          Integral { [ 1./sigma[]*SquNorm[ IB[]*{ir} ] ] ; In Phase2 ; Jacobian Vol ; Integration II ; }
+          Integral { [ 1./sigma[]*SquNorm[ IC[]*{ir} ] ] ; In Phase3 ; Jacobian Vol ; Integration II ; }
+        }
+      }
+
+      { Name MagneticEnergy ;
+        Value {
+          If(!Flag_Hysteresis)
+            Integral {
+              [ SymmetryFactor*(Flag_HalfLam?2:1)*(_3Dmodel?FactorLam:AxialLength)*nu[{d a}]*SquNorm[{d a}] ] ;
+              In Domain ; Jacobian Vol ; Integration II ; }
+          Else
+            Integral {
+              [ SymmetryFactor*(Flag_HalfLam?2:1)*(_3Dmodel?FactorLam:AxialLength)*nu[{d a}]*SquNorm[{d a}] ] ;
+              In Domain_L ; Jacobian Vol ; Integration II ; }
+            Integral {
+              [ SymmetryFactor*(Flag_HalfLam?2:1)*(_3Dmodel?FactorLam:AxialLength)*{h}*{d a} ] ;
+              In Domain_NL ; Jacobian Vol ; Integration II ; }
+          EndIf
+        }
+      }
+
+
+      { Name ComplexPower ; Value { // real part -> eddy current losses; imag part-> magnetic energy
+          Integral { [ SymmetryFactor * (Flag_HalfLam?2.:1.) * FactorLam *
+              Complex[ SquNorm[sigma[]*(Dt[{a}]+{d v}/SymmetryFactor)]/sigma[], nu[]*SquNorm[{d a}] ] ] ;
+            In DomainC; Jacobian Vol ; Integration II ; }
+        }
+      }
+
+      //{ Name U ; Value { Term { [ {U} ]   ; In SurfaceElec ; } } }
+      //{ Name I ; Value { Term { [ {I} ]   ; In SurfaceElec ; } } }
+
+      { Name U ; Value {
+          Term { [ {Ub} ]  ; In DomainB ; }
+          Term { [ {Uz} ]  ; In DomainZtot_Cir ; }
+        } }
+      { Name I ; Value {
+          Term { [ {Ib} ]  ; In DomainB ; }
+          Term { [ {Iz} ]  ; In DomainZtot_Cir ; }
+        } }
+
+      // volume stored in variable $vol_airgap (postprocessing or Evaluate)
+      { Name myVol ; Value { Integral { Type Global ; [ 1. ] ;
+            In Domain; Jacobian Vol ; Integration II ; } }
+      }
+      { Name myVol_agR ; Value { Term { Type Global; [ Vol_Rotor_Airgap[] ] ; In DomainDummy ; } } }
+      { Name myVol_agS ; Value { Term { Type Global; [ Vol_Stator_Airgap[] ] ; In DomainDummy ; } } }
+
+      { Name Torque_Maxwell ; // Torque computation via Maxwell stress tensor
+        Value {
+          Integral {
+            // \int_S (\vec{r} \times (T_max \vec{n}) ) / ep
+            // with ep = |S| / (2\pi r_avg)
+            [ CompZ [ XYZ[] /\ (T_max[{d a}] * XYZ[]) ] * 2*Pi*AxialLength/SurfaceArea[] ] ; // 2D case
+            In Domain ; Jacobian Vol  ; Integration II; } }
+      }
+
+      { Name Torque3D_Maxwell ; // Torque computation via Maxwell stress tensor (3D)
+        Value {
+          Integral {
+            [ CompZ [ XYZ[] /\ (T_max[{d a}] * XYZ[] ) ] * 2 * Pi * nblam*dlam/$vol_airgap ] ;
+            In Domain; Jacobian Vol ; Integration II ; } }
+      }
+
+      If(!_3Dmodel)
+        Call PostQuantities_Homog;
+      EndIf
+
+    }
+  }
+
+  { Name Mechanical ; NameOfFormulation Mechanical ;
+    PostQuantity {
+      { Name P    ; Value { Term { [ {P} ]  ; In DomainKin ; } } } // Position [rad]
+      { Name Pdeg ; Value { Term { [ {P}*180/Pi ]  ; In DomainKin ; } } } // Position [deg]
+      { Name V    ; Value { Term { [ {V} ]  ; In DomainKin ; } } } // Velocity [rad/s]
+      { Name Vrpm ; Value { Term { [ {V}*30/Pi ]  ; In DomainKin ; } } } // Velocity [rpm]
+    }
+  }
+
+}
+
+// --------------------------------------------------------------------------
+
+DefineConstant[
+  R_ = {"Analysis", Name "GetDP/1ResolutionChoices", Visible 1}
+  C_ = {"-solve -v 3 -v2 -cpu", Name "GetDP/9ComputeCommand", Visible 1}
+  P_ = {"", Name "GetDP/2PostOperationChoices", Visible 1}
+];
diff --git a/HomogenisationLaminations/srm/generate_3d.geo b/HomogenisationLaminations/srm/generate_3d.geo
new file mode 100644
index 0000000..f5907b3
--- /dev/null
+++ b/HomogenisationLaminations/srm/generate_3d.geo
@@ -0,0 +1,83 @@
+DefineConstant[
+  NumSlices = (Flag_AirLayer)?2:1,
+  SlicePhysOffset = _Offset,
+  SlicePhysOffset_aux = _Offset_top
+];
+
+AxialLength~{1} = dlam/(Flag_HalfLam?2:1); // width of 1 lamination (or axial length)
+one~{1}[]       = one[];
+layer_top~{1}[] = layer_top[];
+
+If(Flag_AirLayer)
+  AxialLength~{2} = zair; // adding air on top
+  one~{2}[]       = 1;
+  layer_top~{2}[] = 1;
+EndIf
+
+Geometry.AutoCoherence = 0;
+
+ps~{0}[] = Physical Surface {:};
+pl~{0}[] = Physical Line {:};
+pp~{0}[] = Physical Point {:};
+
+
+
+For slice In{1:NumSlices}
+  For s In {0:#ps~{0}[]-1}
+    pv~{slice}[] += ps~{slice-1}[s] + SlicePhysOffset * slice;
+    ps~{slice}[] += ps~{slice-1}[s] + SlicePhysOffset_aux * slice;
+    ele[] = Physical Surface{ps~{slice-1}[s]};
+    name = StrCat( Physical Surface{ps~{0}[s]}, Sprintf(" (slice %g)", slice) );
+    Physical Volume(pv~{slice}[s]) = {};
+    Physical Surface(ps~{slice}[s]) = {};
+    For e In {0:#ele[]-1}
+      p[] = Extrude{0,0, AxialLength~{slice}}{
+        Surface{ ele[e] }; Recombine; Layers{one~{slice}[],layer_top~{slice}[]};
+      };
+      Physical Volume(Str(name), pv~{slice}[s]) += p[1];
+      Physical Surface(Str(name), ps~{slice}[s]) += p[0];
+    EndFor
+  EndFor
+  For l In {0:#pl~{0}[]-1}
+    psl~{slice}[] += pl~{slice-1}[l] + SlicePhysOffset * slice;
+    pl~{slice}[] += pl~{slice-1}[l] + SlicePhysOffset_aux * slice;
+    ele[] = Physical Line{pl~{slice-1}[l]};
+    name = StrCat( Physical Line{pl~{0}[l]}, Sprintf(" (slice %g)", slice) );
+    Physical Surface(psl~{slice}[l]) = {};
+    Physical Line(pl~{slice}[l]) = {};
+    For e In {0:#ele[]-1}
+      p[] = Extrude{0,0,AxialLength~{slice}}{
+        Line{ ele[e] }; Recombine; Layers{one~{slice}[], layer_top~{slice}[]};
+      };
+      Physical Surface(Str(name), psl~{slice}[l]) += p[1];
+      Physical Line(Str(name), pl~{slice}[l]) += p[0];
+    EndFor
+  EndFor
+
+    // Extruding points
+  For k In {0:#pp~{0}[]-1}
+    plp~{slice}[] += pp~{slice-1}[k] + SlicePhysOffset * slice; // lines from physical points
+    pp~{slice}[]  += pp~{slice-1}[k] + SlicePhysOffset_aux * slice; // pnts -> aux for next layer
+
+    ele[] = Physical Point{pp~{slice-1}[k]};
+    name = StrCat( Physical Point{pp~{0}[k]}, Sprintf(" (slice %g)", slice) );
+
+    Physical Line(plp~{slice}[k]) = {};
+    Physical Point(pp~{slice}[k]) = {};
+    For e In {0:#ele[]-1}
+      p[] = Extrude{0,0,AxialLength~{slice}}{
+        Point{ ele[e] }; Recombine; Layers{one~{slice}[], layer_top~{slice}[]};
+      };
+      Physical Line(Str(name), plp~{slice}[k]) += p[1];
+      Physical Point(Str(name), pp~{slice}[k]) += p[0];
+    EndFor
+  EndFor
+
+EndFor
+
+
+
+
+
+Geometry.AutoCoherence = 1;
+Coherence;
diff --git a/HomogenisationLaminations/srm/matlab/.DS_Store b/HomogenisationLaminations/srm/matlab/.DS_Store
new file mode 100644
index 0000000000000000000000000000000000000000..33cced7ea9d80a98d9b0c074430d2323362558e4
GIT binary patch
literal 6148
zcmeHKyH3ME5S)b+mS|E^-Y@V6rzm^@9{>W=AzXy?uJ|rKjoF8yL^cu)4Vsm9=WcK3
zEKlL}0<hh2yaToX2D&3YJuJ=7-4}LM86(np#}Nm-VjK@IZ;R^ngmVYHW5Nd>&-u^O
z^xHeuZ&p?cNC7Dz1*Cu!SX01zFKxI<RFnczKnk1`@b5#TJNCjkF+Lp(F#-@bOowqD
zvjnkug4he^L}qA~RAN%CMhr_j^R4Q7;hdOsSPdUmPqvy+ES}E$Ta?3kqM{U#0+$M0
z=XUG;|DOKC{C`Q(P6|kYf2DwJ_7D3VU#WWQ;^n;8Hu@9YYrg1iTnB|A+A%TOF*n|h
eZ=)#dny-1@3+Ke3Gaq!Keg<3@nH2bI1-=1tgcYCw

literal 0
HcmV?d00001

diff --git a/HomogenisationLaminations/srm/matlab/PQ.pro b/HomogenisationLaminations/srm/matlab/PQ.pro
new file mode 100644
index 0000000..a66bde6
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/PQ.pro
@@ -0,0 +1,25 @@
+Function { 
+
+p_0 = 1 ; 
+p_2 = 1/5 ; 
+p_4 = 1/9 ; 
+p_6 = 1/13 ; 
+p_8 = 1/17 ; 
+
+q_0_0 = 1/12 ; 
+q_0_2 = -1/60 ; 
+q_0_4 = 0 ; 
+q_0_6 = 0 ; 
+q_0_8 = 0 ; 
+q_2_2 = 1/210 ; 
+q_2_4 = -1/1260 ; 
+q_2_6 = 0 ; 
+q_2_8 = 0 ; 
+q_4_4 = 1/1386 ; 
+q_4_6 = -1/5148 ; 
+q_4_8 = 0 ; 
+q_6_6 = 1/4290 ; 
+q_6_8 = -1/13260 ; 
+q_8_8 = 1/9690 ; 
+
+} 
diff --git a/HomogenisationLaminations/srm/matlab/bf_alpha.m b/HomogenisationLaminations/srm/matlab/bf_alpha.m
new file mode 100644
index 0000000..a48bac1
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/bf_alpha.m
@@ -0,0 +1,191 @@
+clear all
+close all
+
+syms z
+
+alpha0 = z^0 ;
+alpha1 = 2*z ;
+alpha2 = 1/2*(-1+12*z^2) ;
+alpha3 = 1/2*(5*(2*z)^3-3*(2*z)) ;
+alpha4 = 1/8*(3-120*z^2+560*z^4) ;
+alpha5 = 1/8*(63*(2*z)^5-70*(2*z)^3+15*(2*z));
+alpha6 = 1/16*(-5+105*(2*z)^2-315*(2*z)^4+231*(2*z)^6);
+
+beta2 = -int(int(alpha0,z),z) + subs(int(int(alpha0,z),z),1/2);
+beta3 = -int(int(alpha1,z),z) + 2*z*subs(int(int(alpha1,z),z),1/2);
+beta4 = -int(int(alpha2)) + subs(int(int(alpha2)),1/2);
+beta5 = -int(int(alpha3)) + 2*z*subs(int(int(alpha3)),1/2);
+beta6 = -int(int(alpha4)) + subs(int(int(alpha4)),1/2);
+beta7 = -int(int(alpha5)) + 2*z*subs(int(int(alpha5)),1/2);
+beta8 = -int(int(alpha6)) + subs(int(int(alpha6)),1/2);
+
+%beta2 = 1/8*(1-4*z^2);
+%beta4 = 1/32*(-1+8*z^2-16*z^4);
+%beta6 = 1/192*(1-4*9*z^2+16*15*z^4-64*7*z^6);
+
+d = [-1/2:0.02:1/2];
+
+a0 = subs(alpha0,z,d);
+a1 = subs(alpha1,z,d);
+a2 = subs(alpha2,z,d);
+a3 = subs(alpha3,z,d);
+a4 = subs(alpha4,z,d);
+a5 = subs(alpha5,z,d);
+
+%A = [d' a1' a2' a3' a4' a5']; 
+%save legendre.dat -ascii -double A
+
+cc=hsv(6) ;
+figure(1),
+plot(d, a0, 'color', cc(1,:), 'LineWidth',3,'DisplayName','a_0'), hold on
+plot(d, a1, 'color', cc(2,:), 'LineWidth',3,'DisplayName','a_1'), 
+plot(d, a2, 'color', cc(3,:), 'LineWidth',3,'DisplayName','a_2'),
+plot(d, a3, 'color', cc(4,:), 'LineWidth',3,'DisplayName','a_3'),
+plot(d, a4, 'color', cc(5,:), 'LineWidth',3,'DisplayName','a_4'),
+plot(d, a5, 'color', cc(6,:), 'LineWidth',3,'DisplayName','a_5'),
+
+h=legend('-DynamicLegend','Location','Best'); legend boxoff
+set(h,'FontName','Symbol','FontSize',18),
+axis([-0.5 0.5 -1 1.05])
+set(gca,'FontName','Helvetica','FontSize',18),
+set(gca,'XTick',[-0.5:0.5:0.5])
+set(gca,'YTick',[-1:.5:1])
+set(gca,'XTickLabel',{'-d/2','0','d/2'})
+saveas(figure(1), 'alpha.eps', 'epsc')
+eps2pdf('alpha.eps', 'alpha.pdf')
+
+b2 = subs(beta2,z,d);
+b3 = subs(beta3,z,d);
+b4 = subs(beta4,z,d);
+b5 = subs(beta5,z,d);
+b6 = subs(beta6,z,d);
+b7 = subs(beta7,z,d);
+
+figure(2),
+plot(d, b2, 'color', cc(1,:), 'LineWidth',3,'DisplayName','b_2'), hold on
+plot(d, b3, 'color', cc(2,:), 'LineWidth',3,'DisplayName','b_3'), 
+plot(d, b4, 'color', cc(3,:), 'LineWidth',3,'DisplayName','b_4'),
+plot(d, b5, 'color', cc(4,:), 'LineWidth',3,'DisplayName','b_5'),
+plot(d, b6, 'color', cc(5,:), 'LineWidth',3,'DisplayName','b_6'),
+plot(d, b7, 'color', cc(6,:), 'LineWidth',3,'DisplayName','b_7'),
+
+h=legend('-DynamicLegend','Location','Best'); legend boxoff
+set(h,'FontName','Symbol','FontSize',18),
+%axis([-0.5 0.5 -1 1.05])
+set(gca,'FontName','Helvetica','FontSize',18),
+set(gca,'XTick',[-0.5:0.5:0.5])
+%set(gca,'YTick',[-1:.5:1])
+set(gca,'XTickLabel',{'-d/2','0','d/2'})
+saveas(figure(2), 'beta.eps', 'epsc')
+eps2pdf('beta.eps', 'beta.pdf')
+
+
+% curl h = j
+gamma1 = diff(beta2,z);
+gamma2 = diff(beta3,z);
+gamma3 = diff(beta4,z);
+gamma4 = diff(beta5,z);
+gamma5 = diff(beta6,z);
+gamma6 = diff(beta7,z);
+
+g1 = subs(gamma1,z,d);
+g2 = subs(gamma2,z,d);
+g3 = subs(gamma3,z,d);
+g4 = subs(gamma4,z,d);
+g5 = subs(gamma5,z,d);
+g6 = subs(gamma6,z,d);
+
+figure(3),
+plot(d, g1, 'color', cc(1,:), 'LineWidth',3,'DisplayName','g_1'), hold on
+plot(d, g2, 'color', cc(2,:), 'LineWidth',3,'DisplayName','g_2'), 
+plot(d, g3, 'color', cc(3,:), 'LineWidth',3,'DisplayName','g_3'),
+plot(d, g4, 'color', cc(4,:), 'LineWidth',3,'DisplayName','g_4'),
+plot(d, g5, 'color', cc(5,:), 'LineWidth',3,'DisplayName','g_5'),
+plot(d, g6, 'color', cc(6,:), 'LineWidth',3,'DisplayName','g_6'),
+
+h=legend('-DynamicLegend','Location','Best'); legend boxoff
+set(h,'FontName','Symbol','FontSize',18),
+%axis([-0.5 0.5 -1 1.05])
+set(gca,'FontName','Helvetica','FontSize',18),
+set(gca,'XTick',[-0.5:0.5:0.5])
+%set(gca,'YTick',[-1:.5:1])
+set(gca,'XTickLabel',{'-d/2','0','d/2'})
+saveas(figure(3), 'gamma.eps', 'epsc')
+eps2pdf('gamma.eps', 'gamma.pdf')
+
+
+%figure,plot(d,b2,d,b3,d,b4,d,b5,d,b6,'LineWidth',2); legend('b2','b3','b4','b5','b6');
+%B = [d' b2' b3' b4' b5' b6'];
+%save beta.dat -ascii -double B   
+
+a = -1/2 ;
+b = 1/2 ;
+
+alpha = [alpha0 alpha1 alpha2 alpha3 alpha4] ;
+beta = [beta2 beta3 beta4 beta5 beta6] ;
+
+P = int(alpha.'*alpha,a,b)
+Q = int(beta.'*alpha,a,b)
+
+P0 = int(alpha(1:2).'*alpha(1:2),a,b);
+Q0 = int(alpha(1:2).'*beta(1:2),a,b);
+
+P2 = int(alpha(1:3).'*alpha(1:3),a,b);
+Q2 = int(alpha(1:3).'*beta(1:3),a,b);
+
+
+n = size(alpha,2);
+P_e = int(alpha(1:2:n)'*alpha(1:2:n),a,b);
+Q_e = int(alpha(1:2:n)'*beta(1:2:n),a,b);
+
+
+%===============================================================================
+%{
+N = 6;
+
+fid = fopen('PQ.pro', 'wt');
+fprintf(fid, 'Function { \n\n');
+
+for i = 1:N
+    %fprintf(fid, 'p_%d = %.16g ; \n', i-1, double(P(i,i)) );
+    fprintf(fid, 'p_%d = %s ; \n', i-1, char(P(i,i)) );
+end
+
+fprintf(fid, '\n');
+
+for i = 1:N
+    for j = i:N
+        %fprintf(fid, 'q_%d_%d = %.16g ; \n', i-1, j-1, double(Q(i,j)));
+        fprintf(fid, 'q_%d_%d = %s ; \n', i-1, j-1, char(Q(i,j)));
+    end
+end
+fprintf(fid, '\n');
+
+fprintf(fid, '} \n');
+fclose(fid)
+%}
+
+
+
+
+%figure,plot(d,g1,d,g2,d,g3,d,g4,d,g5,'LineWidth',2); 
+%legend('g1','g2','g3','g4','g5');
+
+
+% curl e = -d_t b
+gamma1_ = int(alpha0,z);
+gamma2_ = int(alpha1,z);
+gamma3_ = int(alpha2,z);
+gamma4_ = int(alpha3,z);
+gamma5_ = int(alpha4,z);
+gamma6_ = int(alpha5,z);
+g1_ = subs(gamma1_,z,d);
+g2_ = subs(gamma2_,z,d);
+g3_ = subs(gamma3_,z,d);
+g4_ = subs(gamma4_,z,d);
+g5_ = subs(gamma5_,z,d);
+g6_ = subs(gamma6_,z,d);
+
+%figure,plot(d,g1_,d,g2_,d,g3_,d,g4_,d,g5_,'LineWidth',2); 
+%legend('g1_','g2_','g3_','g4_','g5_');
+
diff --git a/HomogenisationLaminations/srm/matlab/bf_alpha_even.m b/HomogenisationLaminations/srm/matlab/bf_alpha_even.m
new file mode 100644
index 0000000..48e06e6
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/bf_alpha_even.m
@@ -0,0 +1,140 @@
+clear
+close all
+
+myfontsize=16;
+myfontsizelegend=16;
+
+set(0,'DefaultAxesFontName', 'Helvetica')
+set(0,'DefaultAxesFontSize', 18)
+
+syms z
+
+alpha0 = z^0 ;
+alpha2 = 1/2*(-1+12*z^2) ;
+alpha4 = 1/8*(3-120*z^2+560*z^4) ;
+alpha6 = 1/16*(-5+105*(2*z)^2-315*(2*z)^4+231*(2*z)^6);
+alpha8 = 1/128*(6435*(2*z)^8-12012*(2*z)^6+6930*(2*z)^4-1260*(2*z)^2+35);
+
+
+% Define Legendre polynomials ------------------------------------------
+% Legendre polynomial basis functions (Matlab provides three different versions)
+% P is symbolic; default=row vectors
+n = 9;
+syms x Pl;
+x = 2*z;
+Pl(1)=1;    % Start with P0(x)=1
+Pl(2)=x;    % Start with P1(x)=x
+for i=3:n  % Apply generation formula: P(i,x)=(2*i-1)/i*x*P(i-1,x)-(i-1)/i*P(i-2,x) for i=3,4,...
+    Pl(i)=(2*i-3)/(i-1)*x*Pl(i-1)-(i-2)/(i-1)*Pl(i-2) ; % for lower index starting from 1
+end
+Pl = simplify(Pl);
+even_alphas = Pl(1:2:end);
+even_betas = -int(int(even_alphas,z),z) + subs(int(int(even_alphas,z),z),1/2);
+
+beta2 = -int(int(alpha0,z),z) + subs(int(int(alpha0,z),z),1/2);
+beta4 = -int(int(alpha2)) + subs(int(int(alpha2)),1/2);
+beta6 = -int(int(alpha4)) + subs(int(int(alpha4)),1/2);
+beta8 = -int(int(alpha6)) + subs(int(int(alpha6)),1/2);
+beta10 = -int(int(alpha8)) + subs(int(int(alpha8)),1/2);
+
+d = (-1/2:0.01:1/2);
+
+a0 = subs(alpha0,z,d);
+a2 = subs(alpha2,z,d);
+a4 = subs(alpha4,z,d);
+a6 = subs(alpha6,z,d);
+a8 = subs(alpha8,z,d);
+
+b2 = subs(beta2,z,d);
+b4 = subs(beta4,z,d);
+b6 = subs(beta6,z,d);
+b8 = subs(beta8,z,d);
+b10 = subs(beta10,z,d);
+
+%A = [d'a0' a2' a4' a6' a8']; 
+%B = [d' b2' b4' b6' b8'];
+%save legendre.dat -ascii -double A
+%save beta.dat -ascii -double B 
+
+A = [a0' a2' a4' a6' a8']; 
+B = [b2' b4' b6' b8' b10'];
+
+nn = 4; % number of polynomials to plot < size(A,2)
+
+cc=hsv(nn) ;
+%set(0,'defaulttextinterpreter','latex');
+figure, hold on 
+%axis square, axis([-41 41 -2.1 2.1]) 
+%title('With Jiles-Atherton model','FontName','Times New Roman','FontSize',myfontsize), hold on
+for k=1:nn
+    plot(d', A(:,k),'color',cc(k,:),...
+         'LineWidth',2,'DisplayName',['\alpha',sprintf('%g',2*(k-1))]),
+    xlabel('normalized lamination width','FontName','Times New Roman','FontSize',myfontsize), 
+    %ylabel('$\alpha$','FontName','Symbol','FontSize',myfontsize), 
+    h=legend('-DynamicLegend','Location','NorthWest'); legend boxoff
+    set(h,'FontName','Helvetica','FontSize',myfontsizelegend), 
+end
+
+figure, hold on 
+%axis square, axis([-41 41 -2.1 2.1]) 
+%title('With Jiles-Atherton model','FontName','Times New Roman','FontSize',myfontsize), hold on
+for k=1:nn
+    plot(d', B(:,k),'color',cc(k,:),...
+         'LineWidth',2,'DisplayName',['\beta',sprintf('%g',2*(k+1))])
+    xlabel('normalized lamination width','FontName','Times New Roman','FontSize',myfontsize), 
+    %ylabel('$\beta$','FontName','Times New Roman','FontSize',myfontsize), 
+    h=legend('-DynamicLegend','Location','NorthWest'); legend boxoff
+    set(h,'FontName','Helvetica','FontSize',myfontsizelegend), 
+end
+saveas(figure(1), 'alphas.eps', 'eps2c')
+saveas(figure(2), 'betas.eps', 'eps2c')
+
+  
+
+%figure,plot(d,a0,d,a2,d,a4,d,a6,d,a8,'LineWidth',2);legend('a0','a2','a4','a6','a8');
+%figure,plot(d,a0,d,a2,d,a4,d,a6,d,a8,'LineWidth',2);legend('a0','a1','a2','a3','a4'); %new notation
+%figure,plot(d,b2,d,b4,d,b6,d,b8,d,b10,'LineWidth',2); legend('b2','b4','b6','b8','b10');
+%figure,plot(d,b2,d,b4,d,b6,d,b8,d,b10,'LineWidth',2); legend('b0','b1','b2','b3','b4'); %new notation
+
+
+
+a = -1/2 ;
+b = 1/2 ;
+
+alpha = [alpha0 alpha2 alpha4 alpha6 alpha8] ;
+beta =  [beta2 beta4 beta6 beta8 beta10] ;
+
+P = int(alpha.'*alpha,a,b)
+Q = int(beta.'*alpha,a,b)
+
+
+%===============================================================================
+
+N = 8;
+
+fid = fopen('PQ.pro', 'wt');
+fprintf(fid, 'Function { \n\n');
+
+for i = 1:2:N+1
+    ii = ceil(i/2);
+    %fprintf(fid, 'p_%d = %.16g ; \n', i-1, double(P(i,i)) );
+    fprintf(fid, 'p_%d = %s ; \n', i-1, char(P(ii,ii)) );
+end
+
+fprintf(fid, '\n');
+
+for i = 1:2:N+1
+    ii = ceil(i/2); 
+    for j = i:2:N+1
+        jj = ceil(j/2);
+        %fprintf(fid, 'q_%d_%d = %.16g ; \n', i-1, j-1, double(Q(i,j)));
+        fprintf(fid, 'q_%d_%d = %s ; \n', i-1, j-1, char(Q(ii,jj)));
+    end
+end
+fprintf(fid, '\n');
+
+fprintf(fid, '} \n');
+fclose(fid);
+
+
+
diff --git a/HomogenisationLaminations/srm/matlab/build_PQmatrices.m b/HomogenisationLaminations/srm/matlab/build_PQmatrices.m
new file mode 100644
index 0000000..1ac1923
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/build_PQmatrices.m
@@ -0,0 +1,51 @@
+function [P, Q] = build_PQmatrices(k, flag_all)
+% n is the maximum number of terms considered in the expansion of b or h
+% flag_all => if 1, we keep even and odd polynomials
+% This functions generates the Legendre polynomials and its derivates
+
+if nargin < 2
+    flag_all = 0;
+    k = 2*k;
+end
+
+% Define Legendre polynomials ------------------------------------------
+% Legendre polynomial basis functions (Matlab provides three different versions)
+% P is symbolic; default=row vectors
+
+syms x z Pl
+
+x = 2*z;
+Pl(1)=1;    % Start with P0(x)=1
+Pl(2)=x;    % Start with P1(x)=x
+for ii=3:k  % Apply generation formula: P(i,x)=(2*i-1)/i*x*P(i-1,x)-(i-1)/i*P(i-2,x) for i=3,4,...
+    Pl(ii)=(2*ii-3)/(ii-1)*x*Pl(ii-1)-(ii-2)/(ii-1)*Pl(ii-2) ; % for lower index starting from 1
+end
+
+Pl = simplify(Pl) ; % alphas
+Pb = -int(int(Pl,z),z) + subs(int(int(Pl,z),z),1/2) ; % betas
+
+if flag_all==0 
+    step = 2 ;
+end
+
+if flag_all==1 % all polynomials 
+    step = 1;
+end
+
+alpha = Pl(1:step:k) ; 
+beta  = Pb(1:step:k) ; 
+
+% alpha0 = z^0 ;
+% alpha2 = 1/2*(-1+12*z^2) ;
+% alpha4 = 1/8*(3-120*z^2+560*z^4) ;
+% alpha6 = 1/16*(-5+105*(2*z)^2-315*(2*z)^4+231*(2*z)^6);
+% alpha8 = 1/128*(6435*(2*z)^8-12012*(2*z)^6+6930*(2*z)^4-1260*(2*z)^2+35);
+
+d = (-1/2:0.01:1/2);
+
+% Constructing matrices P and Q
+a = -1/2 ;
+b = 1/2 ;
+
+P = int(alpha.'*alpha,a,b);
+Q = int(beta.'*alpha,a,b);
diff --git a/HomogenisationLaminations/srm/matlab/gausspoints.m b/HomogenisationLaminations/srm/matlab/gausspoints.m
new file mode 100644
index 0000000..3893c26
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/gausspoints.m
@@ -0,0 +1,118 @@
+clear
+close all
+format long
+
+syms x z 
+x = 2*z ;
+
+%Even legendre polynomials defined between [-1/2,1/2]
+alpha0 = x^0 ;
+alpha2 = 1/2*(3*x^2-1) ;
+alpha4 = 1/8*(35*x^4-30*x^2+3);
+alpha6 = 1/16*(231*x^6-315*x^4+105*x^2-5);
+alpha8 = 1/128*(6435*x^8-12012*x^6+6930*x^4-1260*x^2+35);
+alpha10 = 1/256*(46189*x^10-109395*x^8+90090*x^6-30030*x^4+3465*x^2-63);
+
+N = 10 ; % Watch out! It must be even, as we are integrating on
+         % half the width of the lamination, i.e. taking half the
+         % number of gauss points
+
+% Using Legendre-Gauss quadrature: N points in [-1,1]
+[lx,lp] = lgwt(N,-1,1) ; 
+
+% Shell defined in [-1/2,1/2] ==> Divide by 2 the Gauss pnts
+% lx_ = lx/2; lp_ = lp/2;
+
+% for taking advantage of symmetry: only half of the
+% gauss points... ==> watch out N must be pair 
+lx_ = lx(lx>=0)/2 ;
+lp_ = 2*lp(lx>=0)/2 ;
+
+use_myalpha=1;
+if(use_myalpha)
+    a2_ = double(subs(alpha2,z,lx_));
+    a4_ = double(subs(alpha4,z,lx_));
+    a6_ = double(subs(alpha6,z,lx_));
+    a8_ = double(subs(alpha8,z,lx_));
+    a10_ = double(subs(alpha10,z,lx_));
+else
+    % using the legendre function from Matlab
+    a2_  = legendreP(2,2*lx_) ;
+    a4_  = legendreP(4,2*lx_) ;
+    a6_  = legendreP(6,2*lx_) ;
+    a8_  = legendreP(8,2*lx_) ;
+    a10_ = legendreP(10,2*lx_) ;
+end
+
+%zth = [-1/2:0.01:1/2];
+zth = (0:0.005:1/2);
+
+a2 = legendreP(2,2*zth) ;
+a4 = legendreP(4,2*zth) ;
+a6 = legendreP(6,2*zth) ;
+a8 = legendreP(8,2*zth) ;
+a10 = legendreP(10,2*zth) ;
+
+aa = [a2 ; a4 ; a6 ; a8 ; a10] ;
+aa_ = [a2_  a4_  a6_  a8_  a10_] ;
+
+order_max=10;
+cc=hsv(order_max/2) ;
+markers = {'+','o','*','.','x','s','d','^','v','>','<','p','h'};
+
+figure, hold on
+legend('-DynamicLegend', 'Location','Best')
+for k=1:order_max/2 
+    plot(zth,aa(k,:),'color',cc(k,:),'LineWidth',2,'DisplayName', ...
+         sprintf('alpha%g',2*k)), 
+    plot(lx_,aa_(:,k),markers{mod(k,numel(markers))},'color',cc(k,:),...
+         'DisplayName',sprintf('alpha%g',2*k),'LineWidth',2, 'MarkerSize',8);
+end
+
+
+
+A = aa_.*aa_.*(lp_*ones(1,size(aa_,2)));
+Pnum = sum(A);
+
+orders = (2:2:order_max);
+P = 1./(2*orders+1);
+%P = [1/5 1/9 1/13 1/17 1/21]
+
+RelativeError = (Pnum-P)./P;
+
+
+%===============================================================================
+if(0) % one for creating file
+
+N = ceil(N/2); % if symmetry taken into account    
+filename = sprintf('gausspoints_Ngp%g.pro',N);    
+fid = fopen(filename, 'wt');
+
+fprintf(fid, 'Function { \n\n');
+
+fprintf(fid, 'Nqp = %.16g ; // nbrQuadraturePoints \n', N );
+
+fprintf(fid, 'y_%d = %.16g ; \n', [1:N; lx_']);% gauss point lamination                                                  
+fprintf(fid, '\n');
+
+fprintf(fid, 'w_%d = %.16g ; \n', [1:N; lp_']);
+fprintf(fid, '\n');
+
+fprintf(fid, 'a_2_%d = %.16g ; \n', [1:N; a2_']);
+fprintf(fid, '\n');
+
+fprintf(fid, 'a_4_%d = %.16g ; \n', [1:N; a4_']);
+fprintf(fid, '\n');
+
+fprintf(fid, 'a_6_%d = %.16g ; \n', [1:N; a6_']);
+fprintf(fid, '\n');
+
+fprintf(fid, 'a_8_%d = %.16g ; \n', [1:N; a8_']);
+fprintf(fid, '\n');
+
+fprintf(fid, '} \n');
+%================================================================
+fclose(fid)
+
+end
+%===============================================================================
diff --git a/HomogenisationLaminations/srm/matlab/gausspoints_Ngp5.pro b/HomogenisationLaminations/srm/matlab/gausspoints_Ngp5.pro
new file mode 100644
index 0000000..95fd3cd
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/gausspoints_Ngp5.pro
@@ -0,0 +1,40 @@
+Function {
+
+Nqp = 5 ; // nbrQuadraturePoints
+y_1 = 0.4869532642585859 ;
+y_2 = 0.4325316833444923 ;
+y_3 = 0.3397047841495122 ;
+y_4 = 0.2166976970646236 ;
+y_5 = 0.07443716949081558 ;
+
+w_1 = 0.06667134430868803 ;
+w_2 = 0.1494513491505806 ;
+w_3 = 0.2190863625159821 ;
+w_4 = 0.2692667193099962 ;
+w_5 = 0.2955242247147529 ;
+
+c_2_1 = 0.9227408894325531 ;
+c_2_2 = 0.6225019425809211 ;
+c_2_3 = 0.1923960422444001 ;
+c_2_4 = -0.2182526485213317 ;
+c_2_5 = -0.4667546467891736 ;
+
+c_4_1 = 0.7540759623195411 ;
+c_4_2 = 0.01876577623813908 ;
+c_4_3 = -0.4237995624971215 ;
+c_4_4 = -0.1750153257920291 ;
+c_4_5 = 0.2940357210203751 ;
+
+c_6_1 = 0.5198876842062005 ;
+c_6_2 = -0.3763104252870703 ;
+c_6_3 = -0.05814566531984777 ;
+c_6_4 = 0.3212307651150516 ;
+c_6_5 = -0.1765653629252029 ;
+
+c_8_1 = 0.2555659454712238 ;
+c_8_2 = -0.3351473744834834 ;
+c_8_3 = 0.3179828266071496 ;
+c_8_4 = -0.2247201903177009 ;
+c_8_5 = 0.08085046072097907 ;
+
+}
diff --git a/HomogenisationLaminations/srm/matlab/lgwt.m b/HomogenisationLaminations/srm/matlab/lgwt.m
new file mode 100644
index 0000000..29256ff
--- /dev/null
+++ b/HomogenisationLaminations/srm/matlab/lgwt.m
@@ -0,0 +1,59 @@
+function [x,w]=lgwt(N,a,b)
+
+% lgwt.m
+%
+% This script is for computing definite integrals using Legendre-Gauss 
+% Quadrature. Computes the Legendre-Gauss nodes and weights  on an interval
+% [a,b] with truncation order N
+%
+% Suppose you have a continuous function f(x) which is defined on [a,b]
+% which you can evaluate at any x in [a,b]. Simply evaluate it at all of
+% the values contained in the x vector to obtain a vector f. Then compute
+% the definite integral using sum(f.*w);
+%
+% Written by Greg von Winckel - 02/25/2004
+N=N-1;
+N1=N+1; N2=N+2;
+
+xu=linspace(-1,1,N1)';
+
+% Initial guess
+y=cos((2*(0:N)'+1)*pi/(2*N+2))+(0.27/N1)*sin(pi*xu*N/N2);
+
+% Legendre-Gauss Vandermonde Matrix
+L=zeros(N1,N2);
+
+% Derivative of LGVM
+Lp=zeros(N1,N2);
+
+% Compute the zeros of the N+1 Legendre Polynomial
+% using the recursion relation and the Newton-Raphson method
+
+y0=2;
+
+% Iterate until new points are uniformly within epsilon of old points
+while max(abs(y-y0))>eps
+    
+    
+    L(:,1)=1;
+    Lp(:,1)=0;
+    
+    L(:,2)=y;
+    Lp(:,2)=1;
+    
+    for k=2:N1
+        L(:,k+1)=( (2*k-1)*y.*L(:,k)-(k-1)*L(:,k-1) )/k;
+    end
+ 
+    Lp=(N2)*( L(:,N1)-y.*L(:,N2) )./(1-y.^2);   
+    
+    y0=y;
+    y=y0-L(:,N2)./Lp;
+    
+end
+
+% Linear map from[-1,1] to [a,b]
+x=(a*(1-y)+b*(1+y))/2;      
+
+% Compute the weights
+w=(b-a)./((1-y.^2).*Lp.^2)*(N2/N1)^2;
\ No newline at end of file
diff --git a/HomogenisationLaminations/srm/runF.sh b/HomogenisationLaminations/srm/runF.sh
new file mode 100755
index 0000000..5340a70
--- /dev/null
+++ b/HomogenisationLaminations/srm/runF.sh
@@ -0,0 +1,64 @@
+#!/bin/sh
+
+m3d=1
+
+if [ $m3d = 1 ]; then
+    mymesh="srm3d.msh"
+else
+    mymesh="srm2d.msh"
+fi
+echo $mymesh
+
+getmesh=0
+if [ $getmesh  = 1 ]; then
+    gmsh srm.geo -nt 4 -v 4 -3 -setnumber _3Dmodel $m3d -setnumber Flag_Symmetry 1 -setnumber Flag_HalfLam $m3d -o $mymesh
+fi
+
+nn=40; 
+fmin=1;
+fmax=10000;
+
+# th=-15 #rotor and stator teeth aligned 
+# th=-30 #rotor and stator teeth misaligned (half tooth)
+th=15 #rotor and stator teeth fully misaligned
+
+if [ $m3d = 1 ]; then
+    for (( i=1 ; i<=$nn ; i++ )) ; do
+        echo "====================== FE $i ==========================" ;
+        echo "e(l($fmin)+($i-1)*l($fmax/$fmin)/($nn-1))" | bc -l
+        ff=`echo "e(l($fmin)+($i-1)*l($fmax/$fmin)/($nn-1))" | bc -l`
+        getdp -v 3 -cpu srm.pro -msh $mymesh \
+              -setnumber visu 0 \
+              -setnumber _3Dmodel $m3d \
+              -setnumber Flag_Symmetry 1 \
+              -setnumber Flag_AnalysisType 2 \
+              -setnumber Type_Supply 1 \
+              -setnumber Freq $ff \
+              -setnumber _thetaInit0 $th \
+              -sol Analysis
+    done
+else
+    for (( i=1 ; i<=$nn ; i++ )) ; do
+        #echo "e(l($fmin)+($i-1)*l($fmax/$fmin)/($nn-1))" | bc -l
+        ff=`echo "e(l($fmin)+($i-1)*l($fmax/$fmin)/($nn-1))" | bc -l`
+        for (( o=0 ; o<=3 ; o++ )) ; do
+            if [ $o = 0 ]; then
+                order=$o
+            else
+                order=`echo "(-1*$o)" | bc -l`
+            fi
+            echo "====================== FE $i ORDER $order ==========================" ;           
+            getdp -v 3 -cpu srm.pro -msh $mymesh \
+                  -setnumber visu 0 \
+                  -setnumber _3Dmodel $m3d \
+                  -setnumber Flag_Symmetry 1 \
+                  -setnumber Flag_AnalysisType 2 \
+                  -setnumber Type_Supply 1 \
+                  -setnumber Freq $ff \
+                  -setnumber ORDER $order \
+                  -setnumber _thetaInit0 $th \
+                  -sol Analysis
+        done
+    done
+fi
+
diff --git a/HomogenisationLaminations/srm/runT.sh b/HomogenisationLaminations/srm/runT.sh
new file mode 100755
index 0000000..c0bd9ec
--- /dev/null
+++ b/HomogenisationLaminations/srm/runT.sh
@@ -0,0 +1,40 @@
+#!/bin/sh
+
+m3d=0
+if [ $m3d = 1 ]; then
+    mymesh="srm3d.msh"
+    i0=1
+    nn=1 # ORDER is not used
+else
+    mymesh="srm2d.msh"
+    i0=3
+    nn=3 #order: 1,2,3
+fi
+
+getmesh=0
+if [ $getmesh  = 1 ]; then
+    gmsh srm.geo -nt 4 -v 4 -3 -setnumber _3Dmodel $m3d -setnumber Flag_Symmetry 1 -setnumber Flag_HalfLam $m3d -o $mymesh
+fi
+
+ff=2000
+rpm=20000
+nbs=360 #default is 180 => 1 degree per step
+
+runthis=1
+if [ $runthis = 1 ]; then
+for (( i=$i0 ; i<=$nn ; i++ )) ; do
+    echo "====================== ORDER $i ==========================" ;
+    getdp -v 3 -cpu srm.pro -msh $mymesh \
+          -setnumber visu 0 \
+          -setnumber _3Dmodel $m3d \
+          -setnumber ORDER $i \
+          -setnumber Flag_Symmetry 1 \
+          -setnumber Flag_AnalysisType 1 \
+          -setnumber Type_Supply 5 \
+          -setnumber Freq $ff \
+          -setnumber myrpm $rpm \
+          -setnumber NbSteps $nbs \
+          -sol Analysis
+done
+fi
+
diff --git a/HomogenisationLaminations/srm/srm.geo b/HomogenisationLaminations/srm/srm.geo
new file mode 100644
index 0000000..ccda324
--- /dev/null
+++ b/HomogenisationLaminations/srm/srm.geo
@@ -0,0 +1,250 @@
+// Switched Reluctance Motor Gmsh geometry file (2D)
+
+Include "srm_data.geo" ;
+
+Solver.AutoShowLastStep = 1;
+Mesh.Algorithm = 1 ;
+// 2D mesh algorithm (1: MeshAdapt, 2: Automatic, 5: Delaunay, 6: Frontal-Delaunay, 7: BAMG, 8: Frontal-Delaunay for Quads, 9: Packing of Parallelograms)
+Geometry.CopyMeshingMethod = 1;
+
+
+//------------------------------------------------------------
+//------------------------------------------------------------
+// Create origin
+pAxe = newp ; Point(pAxe) = { 0. , 0. , 0., 3*Lc} ;
+pAxeShift = newp; Point(newp) = {0,0,SlidingSurfaceShift, 3*Lc};
+
+
+Include "srm_stator.geo";
+Include "srm_rotor.geo";
+
+//-------------------------------------------------------------------------------
+// For nice visualization
+//-------------------------------------------------------------------------------
+/*
+Hide { Point{ Point {:} }; Line{ Line {:} }; }
+Show { Line{ linStator[], linRotor[] }; }
+*/
+
+//Physical Line(NICEPOS) = {linStator[],linRotor[] } ;
+
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+
+Coherence;
+
+
+If(_3Dmodel)
+  // Common to stator, rotor and mb...
+  //====================================
+
+  layer_top()={}; aux()={};
+
+  If (alpha==1)
+    a_top = 1/nllam;
+  Else
+    a_top = (alpha-1)/(alpha^nllam - 1); // nllam == number of divitions per half lamination
+  EndIf
+
+  one(0) = 1;
+  layer_top(0) = a_top ;
+  For k In {1:nllam-1}
+    one(k) = 1;
+    layer_top(k) = layer_top(k-1) + a_top * alpha^k;
+  EndFor
+
+  // complete lamination
+  If(!Flag_HalfLam)
+    one() ={one(),one()};
+    If(nllam==1)
+      layer_top() ={0.5,1};
+    EndIf
+    If(nllam > 1)
+      For k In {0:nllam-1}
+        aux(k) = layer_top(k)/2;
+      EndFor
+      For k In {0:nllam-1}
+        If(k==0)
+          layer_top(k) = aux(nllam-k-1)-aux(nllam-k-2);
+          layer_top(nllam+k) = 0.5 + aux(k) ;
+          Else
+          If(k<nllam-1)
+            layer_top(k) = layer_top(k-1) + aux(nllam-k-1)-aux(nllam-k-2);
+            Else
+            layer_top(k) = layer_top(k-1) + aux(nllam-k-1);
+          EndIf
+          layer_top(nllam+k) = layer_top(nllam+k-1) + aux(k)-aux(k-1);
+        EndIf
+      EndFor
+    EndIf
+  EndIf
+
+
+  Include "generate_3d.geo";
+
+  _indexVol     = _3Dmodel*_Offset;
+  _indexVol_air = _3Dmodel*(_Offset*2+_Offset_top);
+
+  If(!Flag_HalfLam && Flag_AirLayer)
+    // There is a problem with the SlidingSurfaceShift => link not correct
+    // probably the symmetry for some of the stator parts have to take that into account
+
+    bbb() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Surface{BND_AIRLAYER+_indexVol_air};} };
+    Physical Surface(BND_AIRLAYER + _indexVol) += bbb();
+
+    If(Flag_Symmetry)
+      // Lin_SlidingSubslave and Lin_SlidingSubmaster
+      bbb() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Line{REF_PNT_MB_ROTOR+_indexVol_air};} };
+      Physical Line(REF_PNT_MB_ROTOR  + _indexVol) += bbb();
+      bbb() = Symmetry {0,0,1,-dlam/2-SlidingSurfaceShift} { Duplicata{Physical Line{REF_PNT_MB_STATOR+_indexVol_air};} };
+      Physical Line(REF_PNT_MB_STATOR  + _indexVol)+= bbb();
+
+       // Sur_StatorPerMaster, Sur_StatorPerSlave
+      bbb() = Symmetry {0,0,1,-dlam/2-SlidingSurfaceShift} { Duplicata{Physical Surface{BND_A0_STATOR+_indexVol_air};} };
+      Physical Surface(BND_A0_STATOR + _indexVol)+= bbb();
+      bbb() = Symmetry {0,0,1,-dlam/2-SlidingSurfaceShift} { Duplicata{Physical Surface{BND_A1_STATOR+_indexVol_air};} };
+      Physical Surface(BND_A1_STATOR + _indexVol)+= bbb();
+
+      // Sur_RotorPerMaster, Sur_RotorPerSlave
+      bbb() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Surface{BND_A0_ROTOR+_indexVol_air};} };
+      Physical Surface(BND_A0_ROTOR + _indexVol)+= bbb();
+      bbb() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Surface{BND_A1_ROTOR+_indexVol_air};} };
+      Physical Surface(BND_A1_ROTOR + _indexVol)+= bbb();
+    EndIf
+
+    bbb() = Symmetry {0,0,1,-dlam/2-SlidingSurfaceShift} { Duplicata{Physical Surface{MB_STATOR+_indexVol_air};} };
+    Physical Surface(MB_STATOR+_indexVol) += bbb();
+    bbb() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Surface{MB_ROTOR+_indexVol_air};} };
+    Physical Surface(MB_ROTOR+_indexVol) += bbb();
+
+
+    NN = (!Flag_Symmetry)?Ns-1:(Ns/2-1);
+    For i In {0:NN}
+      vvv() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Volume{COILN+i+_indexVol_air};} };
+      Physical Volume(COILN+i+_indexVol) += vvv() ;
+      vvv() = Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Volume{COILP+i+_indexVol_air};} };
+      Physical Volume(COILP+i+_indexVol) += vvv() ;
+      pv~{2}() -= {COILN+i+_indexVol_air, COILP+i+_indexVol_air};
+    EndFor
+
+    // Copying top layer to the bottom (all air minus coils)
+    For k In {0:#pv~{2}()-1}
+      aaa() += Symmetry {0,0,1,-dlam/2} { Duplicata{Physical Volume{pv~{2}(k)};} };
+    EndFor
+    Physical Volume(AIRLAYER + _indexVol) += aaa();
+    cut_xy_bottom() = Surface In BoundingBox {-Rsout*1.25,-Rsout*1.25,-1.01*zair, 2*(Rsout*1.25), 2*(Rsout+1.25), -0.5*zair};
+    Physical Surface(BND_AIRLAYER + _indexVol) += cut_xy_bottom();
+  EndIf
+
+  // Additional surfaces for 3D
+  skinStatorIron_()  = Abs(CombinedBoundary{Physical Volume{(STATOR + _3Dmodel*_Offset)};});
+  skinRotorIron_()   = Abs(CombinedBoundary{Physical Volume{(ROTOR + _3Dmodel*_Offset)};});
+  If(Flag_HalfLam)
+    skinStatorIron_() -= Physical Surface{(STATOR)}; // bottom
+    skinRotorIron_() -= Physical Surface{(ROTOR)}; // bottom
+  EndIf
+  If(Flag_Symmetry)
+    skinStatorIron_() -= Physical Surface{(BND_A0_STATOR + _3Dmodel*_Offset)};
+    skinStatorIron_() -= Physical Surface{(BND_A1_STATOR + _3Dmodel*_Offset)};
+    skinRotorIron_() -= Physical Surface{(BND_A0_ROTOR + _3Dmodel*_Offset)};
+    skinRotorIron_() -= Physical Surface{(BND_A1_ROTOR + _3Dmodel*_Offset)};
+  EndIf
+  Physical Surface ("skin stator iron", SKIN_STATOR) = {skinStatorIron_()};
+  Physical Surface ("skin rotor iron", SKIN_ROTOR) = {skinRotorIron_()};
+
+  NN = (!Flag_Symmetry)?Ns-1:(Ns/2-1);
+  For i In {0:NN}
+    volCoilN() += Physical Volume{ (COILN+i+_3Dmodel*_Offset) } ;
+    volCoilP() += Physical Volume{ (COILP+i+_3Dmodel*_Offset) } ;
+  EndFor
+
+  // Merging some Physicals when two slices... => needed for correct constraints
+  If(Flag_AirLayer)
+    // Sur_SlidingSlave and Sur_SlidingMaster
+    Physical Surface(MB_STATOR+_indexVol) += Physical Surface{MB_STATOR+_indexVol_air};
+    Physical Surface(MB_ROTOR +_indexVol) += Physical Surface{MB_ROTOR+_indexVol_air};
+    If(Flag_Symmetry)
+      // Sur_StatorPerMaster, Sur_StatorPerSlave
+      Physical Surface(BND_A0_STATOR + _indexVol)+= Physical Surface{BND_A0_STATOR+_indexVol_air};
+      Physical Surface(BND_A1_STATOR + _indexVol)+= Physical Surface{BND_A1_STATOR+_indexVol_air};
+
+      // Sur_RotorPerMaster, Sur_RotorPerSlave
+      Physical Surface(BND_A0_ROTOR + _indexVol)+= Physical Surface{BND_A0_ROTOR+_indexVol_air};
+      Physical Surface(BND_A1_ROTOR + _indexVol)+= Physical Surface{BND_A1_ROTOR+_indexVol_air};
+
+      // Lin_SlidingSubslave and Lin_SlidingSubmaster
+      Physical Line(REF_PNT_MB_ROTOR  + _indexVol) += Physical Line{REF_PNT_MB_ROTOR  + _indexVol_air};
+      Physical Line(REF_PNT_MB_STATOR  + _indexVol)+= Physical Line{REF_PNT_MB_STATOR  + _indexVol_air};
+    EndIf
+
+    // Outer boundary
+    Physical Surface(BND_AIRLAYER + _3Dmodel*_Offset) += Physical Surface{BND_AIRLAYER+_indexVol_air};
+
+    // Delete (not necessary but useful for checking)
+    // ====================================
+    Physical Surface("line MB stator (slice 2)") -= Physical Surface{MB_STATOR+_indexVol_air};
+    Physical Surface("line MB rotor (slice 2)") -= Physical Surface{MB_ROTOR+_indexVol_air};
+    If(Flag_Symmetry)
+      Physical Surface("bnd stator A0 (slice 2)") -= Physical Surface{BND_A0_STATOR+_indexVol_air};
+      Physical Surface("bnd stator A1 (slice 2)") -= Physical Surface{BND_A1_STATOR+_indexVol_air};
+      Physical Surface("bnd rotor A0 (slice 2)")  -= Physical Surface{BND_A0_ROTOR+_indexVol_air};
+      Physical Surface("bnd rotor A1 (slice 2)")  -= Physical Surface{BND_A1_ROTOR+_indexVol_air};
+      Physical Line("reference point MB rotor (slice 2)")  -= Physical Line{REF_PNT_MB_ROTOR+_indexVol_air};
+      Physical Line("reference point MB stator (slice 2)")  -= Physical Line{REF_PNT_MB_STATOR+_indexVol_air};
+    EndIf
+    Physical Surface("bnd airlayer (slice 2)") -= Physical Surface{BND_AIRLAYER+_indexVol_air};
+
+  EndIf
+
+
+  treelines() = {};
+  If(!Flag_AirLayer)
+    treelines() = CombinedBoundary{ Physical Surface{(BND_STATOR + _3Dmodel*_Offset)};};
+  Else
+    treelines() = CombinedBoundary{ Physical Surface{(BND_AIRLAYER + _3Dmodel*_Offset)};};
+  EndIf
+
+  If(Flag_Symmetry)
+    treelines() += CombinedBoundary{ Physical Surface{(BND_A0_STATOR + _3Dmodel*_Offset)};};
+    treelines() += CombinedBoundary{ Physical Surface{(BND_A1_STATOR + _3Dmodel*_Offset)};};
+    treelines() += CombinedBoundary{ Physical Surface{(BND_A0_ROTOR + _3Dmodel*_Offset)};};
+    treelines() += CombinedBoundary{ Physical Surface{(BND_A1_ROTOR + _3Dmodel*_Offset)};};
+  EndIf
+  treelines() += CombinedBoundary{ Physical Surface {
+        MB_STATOR, MB_STATOR  + _3Dmodel*_Offset,
+        MB_ROTOR, MB_ROTOR  + _3Dmodel*_Offset
+      };};
+  treelines() = Unique(Abs(treelines())); // removing duplicata
+  Physical Line("TreeLines", TREELINES) = { treelines()};
+
+
+  // Some colors for aesthetics...
+  //=================================
+  //Recursive
+  Color SteelBlue { Physical Volume {(STATOR + _3Dmodel*_Offset)}; }
+  //Recursive
+  Color SteelBlue { Physical Volume {(ROTOR + _3Dmodel*_Offset)}; }
+  //Recursive
+  Color SkyBlue {Physical Volume {(AIR_STATOR + _3Dmodel*_Offset)};}
+  //Recursive
+  Color SkyBlue {Physical Volume {(AIRGAP_STATOR + _3Dmodel*_Offset)};} // Structured for sliding surface
+  //Recursive
+  Color SkyBlue {Physical Volume {(AIR_ROTOR + _3Dmodel*_Offset)};}
+  //Recursive
+  Color SkyBlue {Physical Volume {(AIRGAP_ROTOR + _3Dmodel*_Offset)};}// Structured for sliding surface
+
+  //Recursive
+  Color Red        {Volume{ volCoilP({0:NN:Ns/2}) };} // A+
+  //Recursive
+  Color SpringGreen{Volume{ volCoilN({2:NN:Ns/2}) };} // C-
+  //Recursive
+  Color Gold       {Volume{ volCoilP({1:NN:Ns/2}) };} // B+
+  //Recursive
+  Color Red         {Volume{ volCoilN({0:NN:Ns/2}) };} // A- Pink
+  //Recursive
+  Color SpringGreen  {Volume{ volCoilP({2:NN:Ns/2}) };} // C+ ForestGreen
+  //Recursive
+  Color Gold {Volume{ volCoilN({1:NN:Ns/2}) };} // B- PaleGoldenrod
+
+
+EndIf
diff --git a/HomogenisationLaminations/srm/srm.pro b/HomogenisationLaminations/srm/srm.pro
new file mode 100644
index 0000000..8b7270e
--- /dev/null
+++ b/HomogenisationLaminations/srm/srm.pro
@@ -0,0 +1,801 @@
+Include "srm_data.geo";
+Include "BH.pro";
+
+_2Dmodel = !_3Dmodel;
+TREE_COTREE_GAUGE=1;
+
+DefineConstant[
+  Flag_AnalysisType = {1,
+    Choices{0="Static",  1="Time domain", 2="Frequency domain"},
+    ServerAction Str["Reset", StrCat[main,"110Type of supply"], ',' ,StrCat[main, "00Approx. order"]],
+    Name StrCat[main, "100Type of analysis"], Highlight "Red",
+    Help Str["- Use 'Static' to compute static fields created in the machine",
+             "- Use 'Time domain' to compute the dynamic response (transient) of the machine",
+             "- Use 'Frequency domain' to compute the dynamic response (steady state) of the machine"]}
+
+  Flag_NL      = {!(Flag_AnalysisType==2), Choices{0,1}, Name StrCat[main,"13Nonlinear material?"],
+    Highlight "LightPink", ReadOnly (Flag_AnalysisType==2)}
+
+  Flag_NonlinearLawType = {1,
+    Choices{
+      0="linear law (testing)",
+      1="analytica BH-law",
+      2="anhysteretic law",
+      3="Jiles-Atherton hysteretic law"},
+    ServerAction Str["Reset", StrCat[main, "43Nbr of time steps"]],
+    Name StrCat[main,"21 Choose BH-curve?"], Highlight "Magenta", Visible Flag_NL,
+    ReadOnly (Flag_AnalysisType==2) }
+  Flag_Hysteresis = {(Flag_NonlinearLawType==3)?1:0, Choices{0,1},
+    Name StrCat[main,"22Jiles-Atherton hysteretic law?"],
+    Highlight "LightPink", ReadOnly, Visible Flag_NL}
+
+  Flag_Statics = (Flag_AnalysisType==0) //|| (Flag_Hysteresis==1)
+
+  Flag_GaugeType = { 1, Choices{0="No gauge", 1="Tree-cotree gauge"},
+    Name StrCat[main,"05Type of gauge"], Highlight "Blue", Visible _3Dmodel}
+
+  Type_Supply = { (Flag_AnalysisType!=1)?1:5, Choices{ // 1
+      0="Constant current in phase 1",
+      1="Sinusoidal current in phase 1",
+      2="Pulse applied to phase 1",
+      3="current imposed in phases acoording to rotor position (without circuits)",
+      4="current imposed in phases acoording to rotor position (with circuits)",
+      5="voltage +- Vdc according to rotor position (with diodes)"},
+    Name StrCat[main,"110Type of supply"], Highlight "Blue", ReadOnly (Flag_AnalysisType==2)}
+  Flag_Cir = (Type_Supply>3)
+
+  Freq = {5e3, Name StrCat[main,"111Frequency [Hz]"], Highlight "AliceBlue"}
+  Omega = 2*Pi*Freq
+
+  mu0 = 4.e-7 * Pi
+  SkinDepth = { 1e3*Sqrt[1/(Pi*Freq*mu0*murIron*sigmaLam)], Highlight Str[colorro],
+    Visible !Flag_Statics && !Flag_NL, ReadOnly 1, Name StrCat[main,"112Skin depth in lamination [mm]"] }
+
+  visu = {1, Choices{0, 1}, AutoCheck 0,
+    Name StrCat[main,"Visu/Real-time maps"], Highlight "LawnGreen"}
+  Clean_Results = {0, Choices {0,1},
+    Name StrCat[main,'000Remove previous result files'], Highlight "Red"}
+
+  ORDER = {(Flag_AnalysisType==0 || (Flag_Hysteresis==1))?1:2,
+    Choices {
+        0="exact",
+       -1="-1 (homog FD zero order)",
+       -2="-2 (homog FD 2nd order)",
+       -3="-3 (homog FD 4th order)",
+        1="1 (homog TD zero order)",
+        2="2 (homog TD 2nd order)",
+        3="3 (homog TD 4th order)",
+        4="4 (homog TD 6th order)" },
+      Name StrCat[main, "00Approx. order"],
+      Help Str["- With 'Time domain', use order>0",
+        "- With 'Frequency domain' all possibities hold"],
+      Highlight "Red", Visible !_3Dmodel, ReadOnly Flag_Statics}
+
+  Flag_ComplexReluctivity  = (!_3Dmodel) && !(ORDER>0) // 0 3D fine reference model OR Homog real; 1 Homog with nu complex
+
+  Flag_ImposedSpeed = { (Flag_AnalysisType==1), Choices{0="None", 1="Choose speed"},
+    ServerAction Str["Reset", StrCat[main, "43Nbr of time steps"], ',' , StrCat[main,"21Initial rotor pos. (pro) [deg]"]],
+    Name StrCat[main,"30Imposed rotor speed [rpm]"], Highlight "Red", Visible (Flag_AnalysisType==1)},
+  myrpm = { 5000, Name StrCat[main,"31Speed [rpm]"],
+    Highlight "AliceBlue", Visible (Flag_AnalysisType==1 && Flag_ImposedSpeed==1)},
+
+  Tmec = { 0, Name StrCat[main,"33Mechanical torque [Nm]"],
+    Highlight "AliceBlue", Visible 0*(!Flag_ImposedSpeed && Flag_AnalysisType==1) },
+  Frict = { 0, Name StrCat[main,"34Friction torque [Nm]"],
+    Highlight "AliceBlue", Visible 0*(!Flag_ImposedSpeed && Flag_AnalysisType==1) }
+
+  _thetaInit0 = (Flag_ImposedSpeed?-30:-15),  // if -40 => matching data from cmag2011
+  _thetaSpan  = 180
+
+];
+
+
+
+thetaInit = deg2rad * DefineNumber[_thetaInit0, Name StrCat[main,"41Initial rotor pos. (pro) [deg]"],
+  Visible 1, Highlight "Green", ReadOnly 0];
+thetaMax  = deg2rad * DefineNumber[_thetaInit0+_thetaSpan,
+  ServerAction Str["Reset", StrCat[main, "43Nbr of time steps"]],
+  Name StrCat[main,"42End rotor pos. (pro) [deg]"],
+  Visible (Flag_AnalysisType==1) && Flag_ImposedSpeed, Highlight "Red"];
+
+// delta_theta = deg2rad * DefineNumber[ 1., Name StrCat[main,"23Angular step [deg]"], Visible (Flag_AnalysisType==1)];
+
+DefineConstant[
+  NbSteps = { (Flag_ImposedSpeed==1) ? (Flag_Hysteresis?2:1)*(thetaMax-thetaInit)/deg2rad : 1000,
+    Min (thetaMax-thetaInit)/deg2rad, // by default a degree
+    Name StrCat[main, "43Nbr of time steps"],
+    Help Str["- If imposed speed, it is the number of angular divisions",
+      "- If calculated speed, it is just a limit to stop the time loop"] ,
+    Highlight "AliceBlue", Visible (Flag_AnalysisType==1), ReadOnly 0 }
+];
+
+
+
+ResDir = "res/";
+ExtGmsh = ".pos";
+ExtGplt = ".dat";
+
+addtofile="_cost";
+
+If(Flag_AnalysisType==1)
+  ExtGplt = StrCat[addtofile,Sprintf("_f%g_rpm%g.dat", Freq, myrpm)];
+  If(_2Dmodel)
+    ExtGmsh = StrCat[addtofile,Sprintf("_f%g_rpm%g_n%g.pos", Freq, myrpm, ORDER)];
+    ExtGplt = StrCat[addtofile,Sprintf("_f%g_rpm%g_n%g.dat", Freq, myrpm, ORDER)];
+  EndIf
+Else
+  ExtGplt = StrCat[addtofile,Sprintf("_FD_th%g.dat", thetaInit/deg2rad)];
+  If(_2Dmodel)
+    ExtGmsh = StrCat[addtofile,Sprintf("_FD_th%g_n%g.pos", thetaInit/deg2rad, ORDER)];
+    ExtGplt = StrCat[addtofile,Sprintf("_FD_th%g_n%g.dat", thetaInit/deg2rad, ORDER)];
+  EndIf
+EndIf
+
+
+NbrPolesInModel = NbrStatorPoles ;
+NbrPolesTot = NbrStatorPolesTot ;
+
+_indexVol     = _3Dmodel*_Offset;
+_indexVol_air = _3Dmodel*(_Offset*2+_Offset_top);
+
+Group {
+  Stator = Region[{(STATOR + _indexVol)}] ;
+  Rotor  = Region[{(ROTOR  + _indexVol)}] ;
+  Iron   = Region[{Rotor, Stator}];
+
+  SkinStator = Region[{(SKIN_STATOR)}] ;
+  SkinRotor  = Region[{(SKIN_ROTOR)}] ;
+
+  Air = Region[{
+      (AIR_STATOR + _indexVol), (AIRGAP_STATOR + _indexVol),
+      (AIR_ROTOR  + _indexVol), (AIRGAP_ROTOR  + _indexVol)} ] ;
+
+  // For torque computation
+  Rotor_Airgap = Region[{(AIRGAP_ROTOR  + _indexVol)} ] ;
+  Stator_Airgap =Region[{(AIRGAP_STATOR + _indexVol)} ] ;
+
+
+  If(_3Dmodel && Flag_AirLayer)
+    Air += Region[{
+        (STATOR+_indexVol_air),
+        (ROTOR +_indexVol_air),
+        (AIR_STATOR + _indexVol_air), (AIRGAP_STATOR +_indexVol_air),
+        (AIR_ROTOR  + _indexVol_air), (AIRGAP_ROTOR  +_indexVol_air)
+      }];
+    Air += Region[{// Air layer around stator
+        (AIRLAYER + _indexVol),
+        (AIRLAYER + _indexVol_air)
+      }];
+  EndIf
+
+  For i In {1:Ns/SymmetryFactor}
+    IndS~{i} = Region[{(COILP+i-1+_indexVol)}] ;
+    CutIndS~{i} = Region[ {(COILP+i-1)} ] ;
+
+    IndS~{Ns+i} = Region[{(COILN+i-1+_indexVol)}] ;
+    CutIndS~{Ns+i} = Region[{(COILN+i-1)}] ;
+
+    If(_3Dmodel && Flag_AirLayer)
+      IndS~{i}    += Region[{(COILP+i-1+_indexVol_air)}] ;
+      IndS~{Ns+i} += Region[{(COILN+i-1+_indexVol_air)}] ;
+    EndIf
+
+    IndsS += Region[{IndS~{i}, IndS~{Ns+i}}] ;
+  EndFor
+  If(!Flag_Symmetry)
+    Phase1 = Region[ {IndS~{1}, IndS~{(Ns+1)}, IndS~{4}, IndS~{(Ns+4)}} ];
+    Phase2 = Region[ {IndS~{2}, IndS~{(Ns+2)}, IndS~{5}, IndS~{(Ns+5)}} ];
+    Phase3 = Region[ {IndS~{3}, IndS~{(Ns+3)}, IndS~{6}, IndS~{(Ns+6)}} ];
+  Else
+    Phase1 = Region[ {IndS~{1}, IndS~{(Ns+1)}} ];
+    Phase2 = Region[ {IndS~{2}, IndS~{(Ns+2)}} ];
+    Phase3 = Region[ {IndS~{3}, IndS~{(Ns+3)}} ];
+  EndIf
+
+  If(!Flag_AirLayer)
+    Sur_Outer  = Region[{ (BND_STATOR + _indexVol) }] ;// In 3D, you need to add top (and bottom)
+  Else
+    Sur_Outer  = Region[{ (BND_AIRLAYER + _indexVol) }] ; // side airlayer (lam + air  level)
+  EndIf
+
+  _slice_lam = _3Dmodel*_Offset_top;
+  _slice_air = _3Dmodel*(_Offset_top+_Offset_top*2);
+
+  If(_3Dmodel)
+    If(Flag_HalfLam)
+      Bot_air = Region[{AIR_STATOR, AIRGAP_STATOR, AIR_ROTOR, AIRGAP_ROTOR}];
+      If(Flag_AirLayer)
+        Bot_air += Region[{AIRLAYER}];
+      EndIf
+      For i In {1:Ns}
+        Bot_coils += Region[{ (COILP+i-1), (COILN+i-1) }] ;
+      EndFor
+    Else
+      Bot_air  = Region[{}];
+      Bot_coils = Region[{}];
+    EndIf
+
+    If(!Flag_AirLayer)
+      Top_air = Region[{
+          (AIR_STATOR+_slice_lam), (AIRGAP_STATOR+_slice_lam),
+          (AIR_ROTOR +_slice_lam), (AIRGAP_ROTOR +_slice_lam) }];
+      For i In {1:Ns}
+        Top_coils += Region[{ (COILP+i-1+_slice_lam), (COILN+i-1+_slice_lam) }] ;
+      EndFor
+    Else
+      Top_air = Region[{
+          (AIR_STATOR+_slice_air), (AIRGAP_STATOR+_slice_air),
+          (AIR_ROTOR +_slice_air), (AIRGAP_ROTOR +_slice_air)}];
+      Top_air += Region[{(AIRLAYER+_slice_air)}];
+
+      For i In {1:Ns}
+        Top_coils += Region[{ (COILP+i-1+_slice_air), (COILN+i-1+_slice_air) }] ;
+      EndFor
+    EndIf
+
+    Sur_Bottom = Region[ {Bot_air, Bot_coils} ];
+    Sur_Top    = Region[ {Top_air, Top_coils} ];
+  EndIf
+
+  Bnd_A0_Stator = Region[{(BND_A0_STATOR + _indexVol)}] ;
+  Bnd_A1_Stator = Region[{(BND_A1_STATOR + _indexVol)}] ;
+  Bnd_A0_Rotor  = Region[{(BND_A0_ROTOR  + _indexVol)}] ;
+  Bnd_A1_Rotor  = Region[{(BND_A1_ROTOR  + _indexVol)}] ;
+
+  Sur_StatorPerMaster = Region[{Bnd_A0_Stator}];
+  Sur_StatorPerSlave  = Region[{Bnd_A1_Stator}];
+  Sur_RotorPerMaster = Region[{Bnd_A0_Rotor}];
+  Sur_RotorPerSlave  = Region[{Bnd_A1_Rotor}];
+
+
+  DefineGroup[DomainLamC, DomainLamCC, DomainLam];
+  If(Flag_Statics)
+    DomainCC = Region[ {Air, IndsS, Rotor, Stator} ] ;
+    DomainC  = Region[ {} ] ;
+    SkinDomainC = Region[{}];
+    DomainLam  = Region[{Rotor, Stator}];
+  Else
+    DomainCC = Region[ {Air, IndsS} ] ;
+    If(_3Dmodel)
+      DomainC  = Region[ {Rotor, Stator} ] ;
+      SkinDomainC = Region[{SkinRotor, SkinStator}];
+    Else
+      // Homogenization domains (used in 2D)
+      DomainLamC = Region[ {Rotor, Stator} ] ; // Treated with homogenization
+      DomainLamCC = Region[{}];
+      DomainLam   = Region[{DomainLamC, DomainLamCC}];
+
+      DomainNoLamC  = Region[ {} ] ;
+      SkinDomainNoLamC  = Region[ {} ] ;
+      DomainC = Region[ {DomainNoLamC} ] ;
+      SkinDomainC = Region[{SkinDomainNoLamC}];
+    EndIf
+  EndIf
+
+  If(_3Dmodel)
+    Sur_Bottom += Region[ {STATOR, ROTOR} ];
+    If(!Flag_AirLayer)
+      Sur_Top += Region[ {(STATOR+_slice_lam),(ROTOR+_slice_lam)} ];
+    Else
+      Sur_Top += Region[ {(STATOR+_slice_air),(ROTOR+_slice_air)} ];
+    EndIf
+  EndIf
+
+  If(!Flag_NL)
+    Domain_NL = #{};
+    Domain_L = Region[ {DomainCC, DomainC, DomainLamC} ] ;
+    Domain   = Region[ {Domain_L} ] ;
+  Else
+    Domain_L  = Region[ {Air, IndsS} ] ;
+    Domain_NL = Region[ {Stator, Rotor} ] ;
+    Domain    = Region[ {Domain_L, Domain_NL} ] ;
+  EndIf
+
+  If(!Flag_Cir)
+    DomainS = Region[ {IndsS} ] ;
+    DomainB = Region[ {} ] ;
+  Else
+    DomainS = Region[ {} ] ;
+    DomainB = Region[ {IndsS} ] ;
+  EndIf
+
+  DomainMap = Region[{Rotor, Stator, Air, IndsS}];
+
+
+  // Dummy numbers for circuit definition
+  R1 = #551 ;
+  R2 = #552 ;
+  R3 = #553 ;
+
+  E1 = #771 ;
+  E2 = #772 ;
+  E3 = #773 ;
+
+  If(Flag_Cir)
+    DomainZtot_Cir = #{R1,R2,R3, E1,E2,E3} ;
+    Resistance_Cir = #{R1,R2,R3} ;
+  Else
+    DomainZtot_Cir = #{} ;
+    Resistance_Cir = #{} ;
+  EndIf
+
+
+  If(_3Dmodel)
+    Sur_Dirichlet_bn = Region[{Sur_Outer, Sur_Top, Sur_Bottom}];
+  Else
+    Sur_Dirichlet_bn = Region[{Sur_Outer}];
+  EndIf
+
+  Sur_Dirichlet_u  = Region[{}];
+  If(_3Dmodel && Flag_HalfLam)
+    Sur_Dirichlet_u += Region[{Sur_Bottom}];
+  EndIf
+
+  // For the moving band:
+  Sur_SlidingSlave  = Region[{(MB_ROTOR  + _indexVol)}] ;
+  Sur_SlidingMaster = Region[{(MB_STATOR + _indexVol)}] ;
+
+  Lin_SlidingSubslave = #{}; Lin_SlidingSubmaster = #{};
+  If(Flag_Symmetry)
+    If(_3Dmodel)
+      Lin_SlidingSubslave  = Region[{(REF_PNT_MB_ROTOR  + _indexVol)}] ;
+      Lin_SlidingSubmaster = Region[{(REF_PNT_MB_STATOR + _indexVol)}] ;
+    Else
+      Lin_SlidingSubslave  = Region[{(REF_PNT_MB_ROTOR )}] ;
+      Lin_SlidingSubmaster = Region[{(REF_PNT_MB_STATOR)}] ;
+    EndIf
+  EndIf
+
+
+  // Moving region
+  Vol_Moving = Region[ {Rotor, (AIR_ROTOR+_3Dmodel*_Offset), (AIRGAP_ROTOR+_indexVol)} ] ;
+  If(Flag_AirLayer)
+    Vol_Moving += Region[ {
+        (ROTOR +_indexVol_air),
+        (AIR_ROTOR   +_indexVol_air),
+        (AIRGAP_ROTOR+_indexVol_air) } ] ;
+  EndIf
+
+  Sur_Link = Region[ {Sur_SlidingMaster, Sur_SlidingSlave,
+      Sur_StatorPerMaster, Sur_StatorPerSlave,
+      Sur_RotorPerMaster, Sur_RotorPerSlave} ] ;
+
+  Lin_TreeLines        = Region[{TREELINES}];
+  Sur_Tree_Sliding = Region[ { Sur_SlidingMaster, Sur_SlidingSlave } ];
+
+  Vol_Tree = Region[{Domain}];
+  Sur_Tree  = Region [ {Sur_Link, Sur_Dirichlet_bn} ] ;
+  Lin_Tree = Region[ Lin_TreeLines ] ;
+
+  Dom_Hcurl_a = Region[ {Domain, Sur_Dirichlet_bn, Sur_Link} ] ;
+
+
+  DomainKin = Region[1234] ;    // Dummy region number for mechanical equation
+  DomainDummy = Region[12345] ; // Dummy region number for postpro with functions
+
+}
+
+Function {
+
+  rpm = (Flag_ImposedSpeed==0) ? 0.: myrpm ; // speed [rpm]
+  wr = rpm/60*2*Pi ;   // angular rotor speed in rad_mec/s
+
+  RotorPosition = thetaInit; // [rad] initial rotor position
+  // time step
+  If(Flag_ImposedSpeed)
+    // Imposed movement with fixed wr + time domain
+    delta_time = (thetaMax-thetaInit)/NbSteps/wr;
+  Else
+    delta_time = 1/Freq/100; // .5e-3 It should be linked to Freq
+  EndIf
+
+  delta_theta[] = (Flag_ImposedSpeed) ? wr*$DTime : ($RotorPosition-$PreviousRotorPosition) ; // angle step (in rad)
+  time0 = 0.;                       // initial time [s]
+  timemax = NbSteps * delta_time ;  // final   time [s]
+
+}
+
+// --------------------------------------------------------------------------
+
+Function {
+
+  mu [ #{Air, IndsS} ]  = mu0 ;
+  nu [ #{Air, IndsS} ]  = 1. / mu0 ;
+
+  sigma [ #{IndsS} ] = 5.9e7 ;
+  sigma [ #{Rotor, Stator} ] = sigmaLam ;
+  rho[] = 1/sigma[] ;
+
+  // Linear case or 'Frequency domain' computation
+  muIron = murIron * mu0 ;
+  nuIron = 1./(mu0*murIron) ;
+  nu_lin[] = nuIron ;
+
+  If(!NbrRegions[Domain_NL]) // Linear case
+    If(!Flag_ComplexReluctivity)
+      Printf("===> using LINEAR law");
+      nu[#{Iron}] = nu_lin[] ;
+      dhdb_NL[ #{Iron} ]   = dhdb_lin_NL[$1] ;
+    EndIf
+  Else
+        Printf("===> using NON LINEAR law");
+    If(!Flag_Hysteresis)
+      If(Flag_NonlinearLawType==0)
+        Printf("===> testing NON LINEAR case with LINEAR law");
+        nu[#{Iron}] = nu_lin[] ;
+        dhdb_NL[ #{Iron} ]   = dhdb_lin_NL[$1] ;
+      EndIf
+      If(Flag_NonlinearLawType==1)
+        Printf("===> analytical NON LINEAR law");
+        nu[#{Iron}]     = nu_1a[$1];
+        dhdb_NL[#{Iron}] = dhdb_1a_NL[$1];
+
+        h [#{Iron}]    = h_1a[$1];
+        dhdb [#{Iron}] = dhdb_1a[$1];
+      EndIf
+      If(Flag_NonlinearLawType==2)
+        Printf("===> anhysteretic NON LINEAR law corresponding to Jiles-Atherton params");
+        nu[ #{Iron} ] = nu_anhys[$1] ;
+        h[ #{Iron} ] = h_anhys[$1] ;
+        dhdb_NL[ #{Iron} ]= dhdb_anhys_NL[$1] ;
+        dhdb[ #{Iron} ]   = dhdb_anhys[$1] ;
+      EndIf
+    Else
+      Printf("===> Hysteretic NON LINEAR law => Jiles-Atherton model");
+    EndIf
+  EndIf
+
+  FactorLam = nblam ; // One (half) lamination in 3D model... AxialLength set to 1 in 3D, FactorLam = AxialLength/dlam=nblam
+  Imax = 1./2 ; Umax = 1. ;
+  Nw=226.;
+  Sc[] = SurfaceArea[]{COILN} ;
+  NbrWires_Area[] = Nw/Sc[] ;
+
+  If(!Flag_Symmetry)
+    Idir[#{ IndS~{1},IndS~{(Ns+4)},IndS~{2},IndS~{(Ns+5)},IndS~{3},IndS~{(Ns+6)} }] =  Nw ;
+    Idir[#{ IndS~{4},IndS~{(Ns+1)},IndS~{5},IndS~{(Ns+2)},IndS~{6},IndS~{(Ns+3)} }] = -Nw ;
+  Else
+    Idir[#{ IndS~{1},     IndS~{2},     IndS~{3} }] =  Nw ;
+    Idir[#{ IndS~{(Ns+1)},IndS~{(Ns+2)},IndS~{(Ns+3)} }] = -Nw ;
+  EndIf
+
+  Vol_Rotor_Airgap[] = SurfaceArea[]{AIRGAP_ROTOR}*dlam/(Flag_HalfLam?2:1);
+  Vol_Stator_Airgap[] = SurfaceArea[]{AIRGAP_STATOR}*dlam/(Flag_HalfLam?2:1);
+
+  Vdc = 300 ;
+  Resistance[#DomainB]  = 1 ;
+  Resistance[#{551,552,553}] = (Type_Supply==5)? (($1 <= 0.) ?  1.2 : 1e5) : 1e-5;
+
+  T = 1/Freq ;
+  wPulse = T/2 ;
+  F_Pulse[] = (F_Period[$Time]{T} <  wPulse )?  1 : -1 ;
+
+  If(Type_Supply == 0)
+    UI[] = 1;
+    UI1[Phase1] = UI[] ;
+    UI3[Phase3] = 0. ;
+    UI2[Phase2] = 0. ;
+  EndIf
+  If(Type_Supply == 1)
+    UI[] = F_Cos_wt_p[]{2*Pi*Freq, 0 };
+    UI1[Phase1] = UI[] ;
+    UI3[Phase3] = 0. ;
+    UI2[Phase2] = 0. ;
+  EndIf
+  If(Type_Supply == 2)
+    UI[] = F_Pulse[];
+    UI1[Phase1] = UI[] ;
+    UI3[Phase3] = 0. ;
+    UI2[Phase2] = 0. ;
+  EndIf
+
+  shift = Pi/6; // with regard to previous implementation
+  TH[] = $RotorPosition + shift; // Originally TH[] = (TH0+Om*$Time) ;
+  TH_phase[] = TH[] + $1 ;
+  F_PulseTH[] = (F_Period[TH_phase[$1]]{Pi/2} < Pi/6) ?  1 : 0 ; // Pi/12 +++
+
+  If(Type_Supply == 3)
+    Imax = 1 ;
+    UI1[Phase1] = F_PulseTH[ Pi/6] ;
+    UI3[Phase3] = F_PulseTH[ 0.  ] ;
+    UI2[Phase2] = F_PulseTH[-Pi/6] ;
+  EndIf
+
+  If(!Flag_Cir)
+    // Imposed current + Flag_Cir = 0: Type_Supply = 0, 1, 2
+    Iphase[Phase1] = Imax * Idir[] * UI1[] ;
+    Iphase[Phase2] = Imax * Idir[] * UI2[] ;
+    Iphase[Phase3] = Imax * Idir[] * UI3[] ;
+    js0[] = Iphase[] * Vector[0,0,1] / Sc[] ; // Used without circuit
+  EndIf
+
+  If(Type_Supply == 4) //Circuit with imposed current
+    UI1[] = F_PulseTH[ Pi/6] ;
+    UI3[] = F_PulseTH[ 0.  ] ;
+    UI2[] = F_PulseTH[-Pi/6] ;
+  EndIf
+
+  If(Type_Supply == 5) // Circuit with imposed voltage
+    Ext_Angle = Pi/3; // = 60
+    a_on  = Pi/6;
+    a_off = a_on + Ext_Angle;
+    UI1[] = (F_Period[TH[]+a_on]{Pi/2} < a_on) ? 1. : ( (F_Period[TH[]+a_on]{Pi/2} <= a_off )? -1. : 0.) ;
+    UI3[] = (F_Period[TH[]     ]{Pi/2} < a_on) ? 1. : ( (F_Period[TH[]     ]{Pi/2} <= a_off )? -1. : 0.) ;
+    UI2[] = (F_Period[TH[]-a_on]{Pi/2} < a_on) ? 1. : ( (F_Period[TH[]-a_on]{Pi/2} <= a_off )? -1. : 0.) ;
+  EndIf
+
+  DefineFunction[IA, IB, IC];// Post-processing in Phase1, Phase2 and Phase3 with imposed current
+  If(Type_Supply<5)
+    IA[] = UI1[];
+    IB[] = UI2[];
+    IC[] = UI3[];
+  EndIf
+
+  Friction[] = Frict ;
+  Torque_mec[] = Tmec ;
+  Inertia = inertia_fe ;
+
+}
+
+
+
+// --------------------------------------------------------------------------
+
+Constraint {
+
+  { Name ElectricalCircuit ; Type Network ;
+
+    If(!Flag_Symmetry)
+      Case Circuit1 {
+        { Region E1 ;             Branch {100,101} ; }
+        { Region R1 ;             Branch {101,102} ; }
+        { Region IndS~{1} ;       Branch {102,103} ; }
+        { Region IndS~{4} ;       Branch {104,103} ; }
+        { Region IndS~{(Ns+1)} ;  Branch {105,104} ; }
+        { Region IndS~{(Ns+4)} ;  Branch {105,100} ; }
+      }
+      Case Circuit2 {
+        { Region E2 ;             Branch {200,201} ; }
+        { Region R2 ;             Branch {201,202} ; }
+        { Region IndS~{2} ;       Branch {202,203} ; }
+        { Region IndS~{5} ;       Branch {204,203} ; }
+        { Region IndS~{(Ns+2)} ;  Branch {205,204} ; }
+        { Region IndS~{(Ns+5)} ;  Branch {205,200} ; }
+      }
+      Case Circuit3 {
+        { Region E3 ;             Branch {300,301} ; }
+        { Region R3 ;             Branch {301,302} ; }
+        { Region IndS~{3} ;       Branch {302,303} ; }
+        { Region IndS~{6} ;       Branch {304,303} ; }
+        { Region IndS~{(Ns+3)} ;  Branch {305,304} ; }
+        { Region IndS~{(Ns+6)} ;  Branch {305,300} ; }
+      }
+      Else
+        Case Circuit1 {
+          { Region E1 ;             Branch {100,101} ; }
+          { Region R1 ;             Branch {101,102} ; }
+          { Region IndS~{1} ;       Branch {102,103} ; }
+          { Region IndS~{(Ns+1)} ;  Branch {100,103} ; }
+        }
+        Case Circuit2 {
+          { Region E2 ;             Branch {200,201} ; }
+          { Region R2 ;             Branch {201,202} ; }
+          { Region IndS~{2} ;       Branch {202,203} ; }
+          { Region IndS~{(Ns+2)} ;  Branch {200,203} ; }
+        }
+        Case Circuit3 {
+          { Region E3 ;             Branch {300,301} ; }
+          { Region R3 ;             Branch {301,302} ; }
+          { Region IndS~{3} ;       Branch {302,303} ; }
+          { Region IndS~{(Ns+3)} ;  Branch {300,303} ; }
+      }
+      EndIf
+
+  }
+
+  { Name V_circuit ;
+    Case {
+      If(Flag_Cir && Type_Supply==5) // ??? /(Flag_HalfLam?2:1)
+        { Region E1 ; Value Vdc ; TimeFunction  UI1[] ;}
+        { Region E2 ; Value Vdc ; TimeFunction  UI2[] ;}
+        { Region E3 ; Value Vdc ; TimeFunction  UI3[] ;}
+      EndIf
+    }
+  }
+
+  { Name I_circuit ;
+    Case {
+      If(Flag_Cir && Type_Supply==4)
+        { Region E1 ; Value Imax ; TimeFunction  UI1[] ;}
+        { Region E2 ; Value Imax ; TimeFunction  UI2[] ;}
+        { Region E3 ; Value Imax ; TimeFunction  UI3[] ;}
+      EndIf
+    }
+  }
+
+  { Name I_stranded ; // Not necessary if circuit
+    Case {
+      If(!Flag_Cir)
+        { Region Phase1 ; Value Imax*Idir[]/Nw; TimeFunction F_Cos_wt_p[]{2*Pi*Freq, 0 } ; }
+        { Region Phase2 ; Value Imax*Idir[]/Nw; TimeFunction 0. ; }
+        { Region Phase3 ; Value Imax*Idir[]/Nw; TimeFunction 0. ; }
+      EndIf
+    }
+  }
+  { Name V_stranded ;
+    Case {
+    }
+  }
+
+  { Name I_massive ;
+    Case {
+      If(!Flag_Statics)
+        { Region Rotor  ; Value 0. ; }
+        { Region Stator ; Value 0. ; }
+      EndIf
+    }
+  }
+  { Name V_massive ;
+    Case {
+    }
+  }
+
+
+}
+// --------------------------------------------------------------------------
+// --------------------------------------------------------------------------
+
+Include "MagStaDyn_SlidingSurface.pro"
+
+ResId = "" ;
+po_mec  = StrCat["{9Output - Mechanics/", ResId];
+po_mecT = StrCat[po_mec,"0Torque [Nm]/"];
+po_mecP = StrCat[po_mec,"1Position [rad]/"];
+po_mecV = StrCat[po_mec,"2Speed [rpm]/"];
+
+po_mag   = StrCat["{9Output - Magnetics/", ResId];
+po_magF  = StrCat[po_mag, "1Flux [Wb]/"];
+po_magS  = StrCat[po_mag, "0I [A] and V [V]/"];
+po_magJL = StrCat[po_mag, "2Joule losses [W]/"];
+
+
+PostOperation Get_FieldMaps UsingPost MagStaDyn_a {
+  If(NbrRegions[DomainC])
+    Print[ j, OnElementsOf DomainC, LastTimeStepOnly, File StrCat[ResDir,"j",ExtGmsh] ] ;
+    Echo[Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+  EndIf
+  Print[ b, OnElementsOf DomainMap, LastTimeStepOnly, File StrCat[ResDir,"b",ExtGmsh] ] ;
+  Echo[Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+
+  If(_3Dmodel)
+    // Print[ rhoj2, OnElementsOf DomainC, LastTimeStepOnly, File StrCat[ResDir,"jl3d",ExtGmsh] ] ;
+    // Echo[ Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3; View[k].ScaleType = 2;"], File "res/maps.opt"];
+  EndIf
+  If(_2Dmodel)
+    For k In{2:ORDER}
+      Print[ b~{2*k-2}, OnElementsOf DomainLam, LastTimeStepOnly, File StrCat[ResDir,Sprintf("b%g",2*k-2),ExtGmsh] ] ;
+      Echo[ Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3;"], File "res/maps.opt"];
+    EndFor
+    If(!Flag_Statics)
+      Print[ JouleLossesH_local, OnElementsOf DomainLamC, LastTimeStepOnly, File StrCat[ResDir,"jll",ExtGmsh] ] ;
+      Echo[ Str["k=PostProcessing.NbViews-1;","View[k].RangeType = 3; View[k].ScaleType = 2;"], File "res/maps.opt"];
+      // Value scale type (1: linear, 2: logarithmic, 3: double logarithmic)
+    EndIf
+    Print[ az, OnElementsOf DomainMap, LastTimeStepOnly, File StrCat[ResDir,"a",ExtGmsh] ] ;
+    Echo[Str["k=PostProcessing.NbViews-1;", "View[k].RangeType = 3;",// per timestep
+        "View[k].IntervalsType = 3;","View[k].NbIso = 25; View[k].LineWidth = 2; View[k].ScaleType = 1;"], File "res/maps.opt"];
+  EndIf
+}
+
+PostOperation Get_GlobalQuantities UsingPost MagStaDyn_a {
+  Print[ Flux[Phase1], OnGlobal , Format TimeTable , SendToServer StrCat[po_magF, "Ph 1"]{0}, Color "Ivory",
+    LastTimeStepOnly, File  > StrCat[ResDir,Sprintf("Fl1_m%g",_3Dmodel),ExtGplt]] ;
+  Print[ Flux[Phase2], OnGlobal , Format TimeTable , SendToServer StrCat[po_magF, "Ph 2"]{0}, Color "Pink",
+    LastTimeStepOnly, File  > StrCat[ResDir,Sprintf("Fl2_m%g",_3Dmodel),ExtGplt]] ;
+  Print[ Flux[Phase3], OnGlobal , Format TimeTable , SendToServer StrCat[po_magF, "Ph 3"]{0}, Color "LightGreen",
+    LastTimeStepOnly, File  > StrCat[ResDir,Sprintf("Fl3_m%g",_3Dmodel),ExtGplt]] ;
+
+  If(Flag_Cir) // Table does not write down # xxx on 771 772 773 => better for matlab
+    Print[ U, OnRegion Region[{E1,E2,E3}], Format Table, LastTimeStepOnly,
+      File > StrCat[ResDir,Sprintf("U_m%g",_3Dmodel), ExtGplt] ];
+    Print[ I, OnRegion Region[{E1,E2,E3}], Format Table, LastTimeStepOnly,
+      File > StrCat[ResDir,Sprintf("I_m%g",_3Dmodel), ExtGplt] ];
+
+    Print[ U, OnRegion E1, Format Table, SendToServer StrCat[po_magS, "U Ph 1"]{0}, Color "Ivory",
+      LastTimeStepOnly, File > StrCat[ResDir,"Uaux",ExtGplt]] ;
+    Print[ I, OnRegion E1, Format Table, SendToServer StrCat[po_magS, "I Ph 1"]{0}, Color "Ivory",
+      LastTimeStepOnly, File > StrCat[ResDir,"Iaux",ExtGplt]] ;
+    Print[ U, OnRegion E2, Format Table, SendToServer StrCat[po_magS, "U Ph 2"]{0}, Color "Pink",
+      LastTimeStepOnly, File > StrCat[ResDir,"Uaux",ExtGplt]] ;
+    Print[ I, OnRegion E2, Format Table, SendToServer StrCat[po_magS, "I Ph 2"]{0}, Color "Pink",
+      LastTimeStepOnly, File > StrCat[ResDir,"Iaux",ExtGplt]] ;
+    Print[ U, OnRegion E3, Format Table, SendToServer StrCat[po_magS, "U Ph 3"]{0}, Color "LightGreen",
+      LastTimeStepOnly, File > StrCat[ResDir,"Uaux",ExtGplt]] ;
+    Print[ I, OnRegion E3, Format Table, SendToServer StrCat[po_magS, "I Ph 3"]{0}, Color "LightGreen",
+      LastTimeStepOnly, File > StrCat[ResDir,"Iaux",ExtGplt]] ;
+  EndIf
+  If(!Flag_Statics)
+    If(_3Dmodel)
+      Print[ JouleLosses[Stator], OnGlobal , Format TimeTable , SendToServer StrCat[po_mag, "9Losses stator"]{0}, Color "Ivory",
+        LastTimeStepOnly, File > StrCat[ResDir, Sprintf("JLstator_m%g", _3Dmodel),ExtGplt]] ;
+      Print[ JouleLosses[Rotor], OnGlobal , Format TimeTable , SendToServer StrCat[po_mag, "9Losses rotor"]{0}, Color "Ivory",
+        LastTimeStepOnly, File > StrCat[ResDir, Sprintf("JLrotor_m%g", _3Dmodel),ExtGplt]] ;
+
+      If(Flag_AnalysisType==2)
+        Print[ ComplexPower[Stator], OnGlobal , Format Table ,
+          LastTimeStepOnly, File > StrCat[ResDir, Sprintf("Sstator_m%g", _3Dmodel),ExtGplt]] ;
+        Print[ ComplexPower[Rotor], OnGlobal , Format Table ,
+          LastTimeStepOnly, File > StrCat[ResDir, Sprintf("Srotor_m%g", _3Dmodel),ExtGplt]] ;
+      EndIf
+    Else
+      // Homog case
+      Print[ JouleLossesH[Stator], OnGlobal , Format TimeTable , SendToServer StrCat[po_mag, "9Losses stator H"]{0}, Color "Ivory",
+        LastTimeStepOnly, File > StrCat[ResDir, Sprintf("JLstator_m%g", _3Dmodel),ExtGplt]] ;
+      Print[ JouleLossesH[Rotor], OnGlobal , Format TimeTable , SendToServer StrCat[po_mag, "9Losses rotor H"]{0}, Color "Ivory",
+        LastTimeStepOnly, File > StrCat[ResDir, Sprintf("JLrotor_m%g", _3Dmodel),ExtGplt]] ;
+
+      If(Flag_AnalysisType==2 && Flag_ComplexReluctivity)
+        Print[ ComplexPowerH[Stator], OnGlobal , Format Table ,
+          LastTimeStepOnly, File > StrCat[ResDir, Sprintf("Sstator_m%g", _3Dmodel),ExtGplt]] ;
+        Print[ ComplexPowerH[Rotor], OnGlobal , Format Table ,
+          LastTimeStepOnly, File > StrCat[ResDir, Sprintf("Srotor_m%g", _3Dmodel),ExtGplt]] ;
+      EndIf
+
+    EndIf
+  EndIf
+
+  If(Flag_AnalysisType<2) // FD requires another expression
+    If(_3Dmodel)
+      // Print[ myVol[Rotor_Airgap], OnGlobal,   Format Table, LastTimeStepOnly, StoreInVariable $vol_airgap, File >StrCat[ResDir,"Vaux", ExtGplt] ] ;
+      // Print[ myVol_agR, OnRegion DomainDummy, Format Table, LastTimeStepOnly, StoreInVariable $vol_airgap, File >StrCat[ResDir,"Vaux", ExtGplt] ] ;
+      Print[ Torque3D_Maxwell[Rotor_Airgap], OnGlobal, Format TimeTable, LastTimeStepOnly, StoreInVariable $Trotor,
+        File > StrCat[ResDir,"Tr",ExtGplt], SendToServer StrCat[po_mecT, "rotor"]{0}, Color "Ivory" ];
+      /*
+      // Print[ myVol_agS, OnRegion DomainDummy, Format Table, LastTimeStepOnly, StoreInVariable $vol_airgap, File >StrCat[ResDir,"Vaux", ExtGplt] ] ;
+      Print[ Torque3D_Maxwell[Stator_Airgap], OnGlobal, Format TimeTable, LastTimeStepOnly, StoreInVariable $Tstator,
+      File > StrCat[ResDir,"Ts",ExtGplt], SendToServer StrCat[po_mecT, "stator"]{0}, Color "Ivory" ];
+      */
+    Else
+      Print[ Torque_Maxwell[Rotor_Airgap], OnGlobal, Format TimeTable, LastTimeStepOnly, StoreInVariable $Trotor,
+        File > StrCat[ResDir,Sprintf("Tr_2d"),ExtGplt], SendToServer StrCat[po_mecT, "rotor"]{0}, Color "Ivory" ];
+      // Print[ Torque_Maxwell[Stator_Airgap], OnGlobal, Format TimeTable, LastTimeStepOnly, StoreInVariable $Tstator,
+      //  File > StrCat[ResDir,Sprintf("Ts_2d"),ExtGplt], SendToServer StrCat[po_mecT, "stator"]{0}, Color "Ivory" ];
+    EndIf
+  EndIf
+}
+
+PostOperation Get_MechanicalQs UsingPost Mechanical {
+  Print[ P, OnRegion DomainKin, Format Table,
+    File > StrCat[ResDir,"P", ExtGplt], LastTimeStepOnly, StoreInVariable $RotorPosition,
+    SendToServer StrCat[po_mec,"11Position [rad]"]{0}, Color "Ivory"] ;
+  Print[ Pdeg, OnRegion DomainKin, Format Table, File > StrCat[ResDir,"P_deg", ExtGplt], LastTimeStepOnly,
+    SendToServer StrCat[po_mec,"10Position [deg]"]{0}, Color "Ivory"] ;
+  // Print[ V, OnRegion DomainKin, Format Table, File > StrCat[ResDir,"V", ExtGnplt], LastTimeStepOnly,
+  // SendToServer StrCat[po_mec,"21Velocity [rad\s]"]{0}, Color "Ivory"] ;//MediumPurple1
+  Print[ Vrpm, OnRegion DomainKin, Format Table, File > StrCat[ResDir,"Vrpm", ExtGplt], LastTimeStepOnly,
+    SendToServer StrCat[po_mec,"20Velocity [rpm]"]{0}, Color "Ivory"] ;//MediumPurple1
+}
+
+
+
+PostOperation ViewTree UsingPost MagStaDyn_a {
+ If(Flag_GaugeType == TREE_COTREE_GAUGE)
+    // Print the tree for debugging purposes.
+    PrintGroup[ EdgesOfTreeIn[ { Vol_Tree }, StartingOn { Sur_Tree, Lin_Tree } ],
+      In Vol_Tree, File StrCat[ResDir,"Tree.pos"] ];
+    Echo[ Str["l=PostProcessing.NbViews-1;","View[l].ColorTable = { DarkRed };","View[l].LineWidth = 5;"] ,
+      File StrCat[ResDir,"tmp.geo"], LastTimeStepOnly] ;
+  EndIf
+
+  Print[ bsurf, OnElementsOf Region[ Sur_Link ],
+  	 LastTimeStepOnly, File "bsl.pos"] ;
+  Echo[ Str["l=PostProcessing.NbViews-1;",
+  	    "View[l].ArrowSizeMax = 100;",
+  	    "View[l].CenterGlyphs = 0;",
+  	    "View[l].GlyphLocation = 1;",
+  	    "View[l].ScaleType = 1;",
+  	    "View[l].LineWidth = 3;",
+  	    "View[l].VectorType = 4;" ] ,
+          File StrCat[ResDir,"tmp.geo"], LastTimeStepOnly] ;
+
+}
diff --git a/HomogenisationLaminations/srm/srm_data.geo b/HomogenisationLaminations/srm/srm_data.geo
new file mode 100644
index 0000000..306cbfc
--- /dev/null
+++ b/HomogenisationLaminations/srm/srm_data.geo
@@ -0,0 +1,193 @@
+// Switched Reluctance Motor Parameter File (2D)
+// All dimensions in meters and rads
+// Ruth V. Sabariego (August, 2013)
+
+mm = 1e-3 ;
+deg2rad = Pi/180 ;
+rad2deg = 1/deg2rad;
+
+pp   = "{0Geo. & mesh parameters/";
+main = "{1Sim. parameters/";
+
+close_menu = 1;
+colorro  = "LightGrey";
+colorpp = "Ivory";
+
+StatorDim = "1Stator dimensions/" ;
+RotorDim = "2Rotor dimensions/" ;
+
+DefineConstant[
+  _3Dmodel = {0, Choices {0, 1}, ServerAction Str["Reset", StrCat[main,"02Half lamination width?"]],
+    Name StrCat[main,"00 3D model?"], Highlight "Blue"}
+  Flag_Symmetry = {1, Choices {0="Full geo", 1="Half geo"},
+    Name StrCat[main,"01Type of FE model"], Highlight "Blue"}
+  Flag_AirLayer = {0, Choices{0,1},
+    Name StrCat[main,"02Adding air layer?"], Highlight "Yellow", Visible _3Dmodel*0} // Not used
+
+  Flag_HalfLam = {_3Dmodel, Choices{0,1},
+    Name StrCat[main,"02Half lamination width?"],
+    Highlight "Yellow", Visible _3Dmodel, ReadOnly Flag_AirLayer} //if Lam complete, model not ready with airlayer
+
+  NbrStatorPoles = { Flag_Symmetry ? 3:6, Choices {3="3", 6="6"},
+    Name StrCat[main,"03Number of stator poles"], ReadOnly 1, Highlight "Black", Visible 1}
+  NbrRotorPoles = { Flag_Symmetry ? 2:4, Choices {2="2", 4="4"},
+    Name StrCat[main,"04Number of rotor poles"], ReadOnly 1, Highlight "Black"}
+
+  //--------------------------------------------------------------------------------
+
+  ag     = {1*0.29, Name StrCat[pp, "0Air gap width"], Units 'mm', Highlight Str[colorpp], Closed close_menu},
+
+  Rsout  = {60, Name StrCat[pp, StatorDim, "11Outer radius"], Units 'mm', Highlight Str[colorpp]},
+  Rsin   = {30, Name StrCat[pp,  StatorDim, "12Inner radius"], Units 'mm', Highlight Str[colorpp]},
+  YWs    = {12, Name StrCat[pp,  StatorDim, "13Yoke width"], Units 'mm', Highlight Str[colorpp]},
+  Betas_deg = {32, Name StrCat[pp,  StatorDim, "14Pole arc"], Units 'deg', Highlight Str[colorpp]},
+
+  Rrout  = {Rsin-ag, Name StrCat[pp,  RotorDim, "11Outer radius"], Units 'mm',ReadOnly 1, Highlight Str[colorro]},
+  Rrin  = {20, Name StrCat[pp,  RotorDim, "12Outer yoke radius"], Units 'mm',Highlight Str[colorpp]},
+  Rshaft  = {6, Name StrCat[pp,  RotorDim, "13Shaft radius"], Units 'mm',Highlight Str[colorpp]},
+  Betar_deg = {32, Name StrCat[pp,  RotorDim, "14Pole arc"], Units 'deg', Highlight Str[colorpp]}
+
+  clFactor = {1, Name StrCat[pp,"03mesh density factor"], Highlight "Ivory"}
+  dlam   = { 0.5, Name StrCat[pp,"02lamination width"], Units 'mm', Highlight "Ivory" }
+  de     = { 0*0.05, Name StrCat[pp,"03isolation thickness"], Units 'mm'}
+  fillfactor = { _3Dmodel ? 1. : dlam/(dlam+de), Name StrCat[pp,"03fill factor"], Units '', ReadOnly 1}
+  nllam  = { 5, Name StrCat[pp,"03nb layers in half lamination"], Highlight "Yellow"}
+  _adapt_dlam_mesh = {1, Choices {0, 1}, Name StrCat[pp,"04 non uniform distribution of layers in lamination thickness"], Highlight "Red"}
+  alpha = { (_adapt_dlam_mesh) ? 0.5:1.,
+    Name StrCat[pp,"05ratio for progression in lamination"], Highlight "Yellow", Visible _adapt_dlam_mesh, ReadOnly !_adapt_dlam_mesh}
+  // 1 for uniform distribution of layers, < 1 for thinner close to boundary, > 1 for thinner in the middle
+
+  // AxialLength = {60, Name StrCat[pp, "0Axial length"], Units 'mm', Highlight Str[colorpp]} // to correct for 1 lamination cases, different in 2D and 3D
+
+  nblam = {60/dlam, Name StrCat[pp, "04Number of laminations"],Highlight Str[colorpp]}
+  AxialLength = {!_3Dmodel?(nblam*dlam):1/mm, Name StrCat[pp, "05Axial length"],
+    Units 'mm', Highlight Str[colorro], ReadOnly}
+];
+
+ag=ag*mm;
+AxialLength = AxialLength*mm;
+dlam = dlam*mm;
+de = de*mm;
+e  = dlam+de;
+
+Rsout = Rsout*mm;
+Rsin=Rsin*mm;
+YWs =YWs*mm;
+
+Rrout =Rrout*mm;
+Rrin =Rrin*mm;
+Rshaft = Rshaft*mm;
+
+Betas = Betas_deg * deg2rad ;
+Betar = Betar_deg * deg2rad ;
+
+zair = 1/8*dlam;
+Rair = Rsout+zair;
+
+Lc = 7.5e-4/2*clFactor ; // base characteristic length
+
+SlidingSurfaceShift = 1e-5;
+
+//------------------------------------------------------------------------------
+// moving band
+// transfine meshing in moving band
+// some layers in airgap
+frac_ag = 1/4;
+Rag1 = Rsin-frac_ag*ag; // Outer layer from stator
+Rag2 = Rsin-2*frac_ag*ag;
+
+Ragr1 = Rrout+frac_ag*ag;
+Ragr2 = Rrout+2*frac_ag*ag; // Outer layer from rotor
+
+Rair2= Rag2;
+Rair3= Ragr2;
+
+Rag_rotor  = Rair3;
+Rag_stator = Rair2;
+
+// Printf("Rag_rotor %g %g", Ragr1, Ragr2);
+// Printf("Rag_stator %g %g", Rag1, Rag2);
+
+// Vol_agR = 0.5*Pi*(Ragr2^2-Ragr1^2)*dlam/(Flag_HalfLam?2.:1.);
+// Vol_agS = 0.5*Pi*(Rag1^2-Rag2^2)*dlam/(Flag_HalfLam?2.:1.);
+// Printf("Vol airgap Rotor %g Vol airgap Stator= %g", Vol_agR, Vol_agS);
+
+
+// ndiv_mb  = Ceil[2*Pi*Rag2/2/(Lc)/3] + 1 ; // number of divisions = ndiv_mb-1 ;
+// nDivBand = 4 * (ndiv_mb-1) ;
+ndiv_mb  = 90 + 1; // 90 => 1 degree
+nDivBand = 4 * (ndiv_mb-1) ;
+// Printf("====> ndiv_mb %g, nDivBand = %g", nDivBand/4, nDivBand);
+
+//------------------------------------------------------------------------------
+//------------------------------------------------------------------------------
+// Stator:
+NbrStatorPolesTot = 6 ;
+SymmetryFactor = NbrStatorPolesTot/NbrStatorPoles ;
+Ns = NbrStatorPolesTot;
+th0ss = Pi/Ns;    // +++ 0 Angular pos. stator
+dths = 2.*Pi/Ns;  // Ang. shift between 2 stator poles
+
+aperture0 = 2*Pi/nDivBand ; // angular aperture of one single mesh element
+
+// Rotor
+NbrRotorPolesTot = 4 ;  // Num. of Rotor Poles
+Nr = NbrRotorPolesTot;
+th0rs = Pi/Nr; // horizontal InitialRotorAngle; // Angular pos. rotor
+dthr   = 2.*Pi/Nr ;	// Ang. shift between 2 rotor poles
+
+DefineConstant[
+  murIron  = {1000, Name StrCat[pp, "Relative permeability for linear case"]}
+  sigmaLam = {5e6,  Name StrCat[pp, "iron conductivity"]}
+];
+
+VA = 220 ; // rms values
+IA = 1/Sqrt[2] ;
+inertia_fe = 8.3e-3 ;
+
+
+//------------------------------------------------------------
+// Physical regions
+//------------------------------------------------------------
+
+STATOR = 1000 ; SKIN_STATOR = 10000 ;
+ROTOR  = 2000 ; SKIN_ROTOR  = 20000 ;
+SHAFT  = 2100 ;
+
+COILN  = 1100 ; SKIN_COILN  = 11000 ; CUT_COILN  = 11100 ;
+COILP  = 1200 ; SKIN_COILP  = 12000 ; CUT_COILP  = 12100 ;
+
+BND_STATOR = 5555 ;
+BND_A0_STATOR = 5600;
+BND_A1_STATOR = 5601;
+
+TOP_STATOR = 5560 ; BOT_STATOR = 5561 ;
+TOP_ROTOR  = 5570 ; BOT_ROTOR  = 5571 ;
+TOP_AIR    = 5580 ; BOT_AIR = 5581;
+TOP_COILS  = 5590 ; BOT_COILS = 5591;
+
+AIRGAP_STATOR = 3000 ;
+AIR_STATOR  = 3001 ;
+AIRGAP_ROTOR  = 3100 ;
+AIR_ROTOR  = 3101 ;
+
+AIRLAYER = 4000; BND_AIRLAYER = 4444;
+
+BND_A0_ROTOR = 6600;
+BND_A1_ROTOR = 6601;
+
+MB_STATOR  = 1111 ; MB_ROTOR   = 2222 ;
+
+MB_STATOR_SURF = 3330 ;
+MB_ROTOR_SURF  = 3340 ;
+
+REF_PNT_ROTOR     = 8800;
+REF_PNT_MB_ROTOR  = 8801;
+REF_PNT_MB_STATOR = 8802;
+
+NICEPOS = 111111 ;
+
+_Offset=1e6;
+_Offset_top=1e7;
+
+TREELINES= 22;
diff --git a/HomogenisationLaminations/srm/srm_rotor.geo b/HomogenisationLaminations/srm/srm_rotor.geo
new file mode 100644
index 0000000..447a08f
--- /dev/null
+++ b/HomogenisationLaminations/srm/srm_rotor.geo
@@ -0,0 +1,166 @@
+//--------------------------------------------------------------------------------
+// SRM rotor
+//--------------------------------------------------------------------------------
+
+// Create all rotor points
+For N In {0:Nr/2-1}
+  th0r = N*dthr+th0rs;
+  p1rox=Rrin*Cos(-dthr/2.+th0r);   p1roy=Rrin*Sin(-dthr/2.+th0r);
+  p6rox=Rrout*Cos(-dthr/2.+th0r);  p6roy=Rrout*Sin(-dthr/2.+th0r);
+
+  th2r=Asin(Rrout/Rrin*Sin(Betar/2.));
+  p2rox=Rrin*Cos(-th2r+th0r);      p2roy=Rrin*Sin(-th2r+th0r);
+  p3rox=Rrout*Cos(-Betar/2.+th0r); p3roy=Rrout*Sin(-Betar/2.+th0r);
+  p4rox=Rrout*Cos(Betar/2.+th0r);  p4roy=Rrout*Sin(Betar/2.+th0r);
+  p5rox=Rrin*Cos(th2r+th0r);       p5roy=Rrin*Sin(th2r+th0r);
+  p1rix=Rshaft*Cos(-dthr/2.+th0r); p1riy=Rshaft*Sin(-dthr/2.+th0r);
+
+  p1ro[N]=newp; Point(p1ro[N])={p1rox,p1roy,0.,4*Lc};
+  p2ro[N]=newp; Point(p2ro[N])={p2rox,p2roy,0.,6*Lc};
+  p3ro[N]=newp; Point(p3ro[N])={p3rox,p3roy,0.,2*Lc/2};
+  p4ro[N]=newp; Point(p4ro[N])={p4rox,p4roy,0.,2*Lc/2};
+  p5ro[N]=newp; Point(p5ro[N])={p5rox,p5roy,0.,6*Lc};
+  p6ro[N]=newp; Point(p6ro[N])={p6rox,p6roy,0.,6*Lc};
+  p1ri[N]=newp; Point(p1ri[N])={p1rix,p1riy,0.,6*Lc};
+EndFor
+
+N = Nr/2 ;
+th0r = N*dthr+th0rs;
+p1rox=Rrin*Cos(-dthr/2.+th0r);   p1roy=Rrin*Sin(-dthr/2.+th0r);
+p1rix=Rshaft*Cos(-dthr/2.+th0r); p1riy=Rshaft*Sin(-dthr/2.+th0r);
+p6rox=Rrout*Cos(-dthr/2.+th0r);  p6roy=Rrout*Sin(-dthr/2.+th0r);
+p1ro[N]=newp; Point(p1ro[N])={p1rox,p1roy,0.,4*Lc};
+p1ri[N]=newp; Point(p1ri[N])={p1rix,p1riy,0.,6*Lc};
+p6ro[N]=newp; Point(p6ro[N])={p6rox,p6roy,0.,6*Lc};
+
+// Create Rotor Lines, arcs and regions
+For N In {0:Nr/2-1}
+  arcri[N]=newl; Circle(arcri[N])={p1ri[N],pAxe,p1ri[(N+1)%Nr]};
+EndFor
+cutshaft[0] = newl; Line(newl)={p1ri[2],pAxe};
+cutshaft[1] = newl; Line(newl)={pAxe,p1ri[0]};
+
+For N In {0:Nr/2-1}
+  clro1[N]=newl; Circle(clro1[N])={p1ro[N],pAxe,p2ro[N]};
+  clro2[N]=newl; Line(clro2[N])={p2ro[N],p3ro[N]};
+  clro3[N]=newl; Circle(clro3[N])={p3ro[N],pAxe,p4ro[N]};
+  clro4[N]=newl; Line(clro4[N])={p4ro[N],p5ro[N]};
+  clro5[N]=newl; Circle(clro5[N])={p5ro[N],pAxe,p1ro[(N+1)%Nr]};
+EndFor
+
+rr1=newl; Line(newl)={p1ri[0],p1ro[0]};
+rr2=newl; Line(newl)={p1ri[Nr/2],p1ro[Nr/2]};
+llshaft = newll ; Line Loop (llshaft) = {arcri[],cutshaft[]};
+Shaft[] += news ; Plane Surface(Shaft[0]) = {llshaft} ;
+
+rotorout[]= clro1[0]:clro5[Nr/2-1] ;
+llrotor = newll ; Line Loop (llrotor) = {rotorout[],-rr2, -arcri[{1:0}],rr1};
+Rotor[] += news ; Plane Surface(Rotor[0]) = {llrotor} ;
+rr1_=newl; Line(newl)={p1ro[0],p6ro[0]};
+rr2_=newl; Line(newl)={p1ro[2],p6ro[2]};
+
+For N In {0:Nr/2-1}
+  clrr2[N]=newl; Circle(clrr2[N])={p6ro[N],pAxe,p3ro[N]};
+  clrr3[N]=newl; Circle(clrr3[N])={p4ro[N],pAxe,p6ro[(N+1)%Ns]};
+EndFor
+
+Line Loop(newll) = {rotorout[{0,1}],-clrr2[0], -rr1_};
+AirgapRotorIn[]+=news; Plane Surface(news) = {newll-1};
+Line Loop(newll) = {rotorout[{3:6}], -clrr2[1],-clrr3[0]};
+AirgapRotorIn[]+=news; Plane Surface(news) = {newll-1};
+Line Loop(newll) = {rotorout[{8,9}], rr2_, -clrr3[1]};
+AirgapRotorIn[]+=news; Plane Surface(news) = {newll-1};
+
+
+//============================================================
+// moving band - from Rotor
+Rairr1=Ragr1;
+Rairr2=Ragr2; // closing the airgap
+For N In {0:Ns/2-1}
+  th0r=N*Pi/2+th0rs;
+  p1airrcox = Rairr1*Cos(-dthr/2.+th0r);
+  p1airrcoy = Rairr1*Sin(-dthr/2.+th0r);
+  p1airrcox_= Rairr2*Cos(-dthr/2.+th0r);
+  p1airrcoy_= Rairr2*Sin(-dthr/2.+th0r);
+  p1airrco[N] = newp; Point(p1airrco[N]) ={p1airrcox,p1airrcoy,0.,Lc/2} ;
+  p1airrco_[N]= newp; Point(p1airrco_[N])={p1airrcox_,p1airrcoy_,0.,Lc/2} ;
+EndFor
+
+For N In {0:1}
+  airG1r[N]=newl; Circle(airG1r[N]) = {p1airrco[N], pAxe, p1airrco[N+1]};
+  airG2r[N]=newl; Circle(airG2r[N]) = {p1airrco_[N],pAxe, p1airrco_[N+1]};
+
+  airG12r[N] = newl ; Line(airG12r[N]) = {p1airrco[N], p1airrco_[N]} ;
+EndFor
+airG12r[2] = newl ; Line(airG12r[2]) = {p1airrco[2], p1airrco_[2]} ;
+
+lmbr[]+=newl; Line(newl)={p1airrco[0],p6ro[0]};
+lmbr[]+=newl; Line(newl)={p6ro[2],p1airrco[2]};
+
+bndmbrotor[] = {clrr3[1],rotorout[7],clrr2[1],clrr3[0],rotorout[2],clrr2[0]};
+ll_inmbr=newll; Line Loop(ll_inmbr)={-lmbr[0],airG1r[{0,1}],-lmbr[1], -bndmbrotor[]};
+surairgapR[]+=news ; Plane Surface(surairgapR[0]) = {ll_inmbr};
+
+For N In {0:1}
+  surmbrotor[N]=news ; Line Loop (surmbrotor[N]) = {-airG2r[N],-airG12r[N],airG1r[N],airG12r[N+1]};
+  Plane Surface(surmbrotor[N])= surmbrotor[N];
+EndFor
+
+Transfinite Line {airG1r[], airG2r[]} = ndiv_mb ;
+Transfinite Line {airG12r[]} = 1 ;
+Transfinite Surface {surmbrotor[]}; Recombine Surface {surmbrotor[]};
+
+// Periodic Line ???
+
+//============================================================
+//============================================================
+If(Flag_Symmetry==0) // FULL MODEL
+
+  Rotor[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{Rotor[0]};} };
+  Shaft[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{Shaft[0]};} };
+
+  airG2r[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Line{airG2r[{0,1}]};} };
+
+  surairgapR[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{surairgapR[{0}]};} };
+  surmbrotor[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{surmbrotor[{0,1}]};} };
+
+  NN = #AirgapRotorIn[]-1 ;
+  For N In {0:NN}
+    AirgapRotorIn[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{AirgapRotorIn[N]};} };
+  EndFor
+EndIf
+
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+// Physical regions
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+
+Reverse Surface {AirgapRotorIn[], surmbrotor[]};
+
+Physical Surface("rotor iron", ROTOR)  = {Rotor[]} ;
+Physical Surface("rotor air", AIR_ROTOR)= {AirgapRotorIn[], surairgapR[], Shaft[]};
+Physical Surface("rotor air (touching MB)", AIRGAP_ROTOR) = {surmbrotor[]};
+
+Physical Line("line MB rotor", MB_ROTOR)  = airG2r[] ;
+If(Flag_Symmetry)
+  Physical Point("reference point", REF_PNT_ROTOR) = {pAxe} ;
+  Physical Point("reference point MB rotor", REF_PNT_MB_ROTOR) = {p1airrco_[2]} ;
+
+  //Lines for symmetry link
+  Physical Line("bnd rotor A0", BND_A0_ROTOR) = {rr1,rr1_,cutshaft[1],lmbr[0], airG12r[0]} ;
+  Physical Line("bnd rotor A1", BND_A1_ROTOR) = {rr2,rr2_,cutshaft[0],lmbr[1], airG12r[2]};
+EndIf
+
+//-------------------------------------------------------------------------------
+// For nice visualization
+//-------------------------------------------------------------------------------
+linRotor[]  = Abs(CombinedBoundary{ Surface{Rotor[]}; });
+
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+Color SteelBlue {Physical Surface{ROTOR};}
+Color SkyBlue {Physical Surface{AIR_ROTOR};}
+Color Cyan {Physical Surface{AIRGAP_ROTOR};}
+
+Geometry.AutoCoherence = 0;
diff --git a/HomogenisationLaminations/srm/srm_stator.geo b/HomogenisationLaminations/srm/srm_stator.geo
new file mode 100644
index 0000000..bda8089
--- /dev/null
+++ b/HomogenisationLaminations/srm/srm_stator.geo
@@ -0,0 +1,234 @@
+//--------------------------------------------------------------------------------
+// SRM stator
+//--------------------------------------------------------------------------------
+
+// Create all stator points
+Rsmid = Rsout-YWs ;
+For N In {0:Ns/2-1}
+  th0s=N*dths+th0ss;
+  p1sox=Rsout*Cos(-dths/2.+th0s); p1soy=Rsout*Sin(-dths/2.+th0s);
+  p1six=Rsmid*Cos(-dths/2.+th0s); p1siy=Rsmid*Sin(-dths/2.+th0s);
+
+  th4s=Asin(Rsin/Rsmid*Sin(Betas/2.));
+  p2six=Rsmid*Cos(-th4s+th0s);    p2siy=Rsmid*Sin(-th4s+th0s);
+  p3six=Rsin*Cos(-Betas/2.+th0s); p3siy=Rsin*Sin(-Betas/2.+th0s);
+  p4six=Rsin*Cos( Betas/2.+th0s); p4siy=Rsin*Sin( Betas/2.+th0s);
+  p5six=Rsmid*Cos(th4s+th0s);     p5siy=Rsmid*Sin(th4s+th0s);
+
+  p1so[N]=newp; Point(p1so[N])={p1sox,p1soy,0.,8*Lc} ;
+  p1si[N]=newp; Point(p1si[N])={p1six,p1siy,0.,8*Lc} ;
+  p2si[N]=newp; Point(p2si[N])={p2six,p2siy,0.,8*Lc} ;
+  p3si[N]=newp; Point(p3si[N])={p3six,p3siy,0.,1*Lc} ;
+  p4si[N]=newp; Point(p4si[N])={p4six,p4siy,0.,1*Lc} ;
+  p5si[N]=newp; Point(p5si[N])={p5six,p5siy,0.,8*Lc} ;
+EndFor
+
+N = Ns/2 ;
+th0s=N*dths+th0ss;
+p1sox=Rsout*Cos(-dths/2.+th0s);  p1soy=Rsout*Sin(-dths/2.+th0s);
+p1six=Rsmid*Cos(-dths/2.+th0s);  p1siy=Rsmid*Sin(-dths/2.+th0s);
+p1so[]+=newp; Point(newp)={p1sox,p1soy,0.,8*Lc} ;
+p1si[]+=newp; Point(newp)={p1six,p1siy,0.,8*Lc} ;
+
+// Create Stator Lines, arcs and regions
+// outer stator surface
+For N In {0:Ns/2-1}
+ arcso[]+=newl; Circle(newl)={p1so[N],pAxe,p1so[(N+1)%Ns]};
+EndFor
+
+// outer surface of N-th stator tooth
+For N In {0:Ns/2-1}
+ clsi1[N]=newl; Circle(clsi1[N])={p1si[N],pAxe,p2si[N]};
+ clsi2[N]=newl; Line(clsi2[N])={p2si[N],p3si[N]};
+ clsi3[N]=newl; Circle(clsi3[N])={p3si[N],pAxe,p4si[N]};
+ clsi4[N]=newl; Line(clsi4[N])={p4si[N],p5si[N]};
+ clsi5[N]=newl; Circle(clsi5[N])={p5si[N],pAxe,p1si[(N+1)%Ns]};
+EndFor
+
+ss1=newl; Line(newl)={p1si[0], p1so[0]};
+ss2=newl; Line(newl)={p1si[Ns/2], p1so[Ns/2]};
+llStator=newll;
+statorin[] = {clsi1[0]:clsi5[Ns/2-1]} ;
+
+llstator = newll ; Line Loop (llstator)={-ss1,clsi1[0]:clsi5[Ns/2-1],ss2,-arcso[{2:0:-1}]};
+Stator[] += news ; Plane Surface(Stator[0]) = {llstator} ;
+
+// Create Coil regions
+For N In {0:Ns/2}
+ th0s=N*dths+th0ss;
+ p1cx=Rsin*Cos(-dths/2.+th0s);
+ p1cy=Rsin*Sin(-dths/2.+th0s);
+ p1c[N]=newp; Point(p1c[N])={p1cx,p1cy,0.,2*Lc} ;
+EndFor
+For N In {0:Ns/2}
+ clci1[N]=newl; Line(clci1[N])={p1si[N],p1c[N]};
+EndFor
+For N In {0:Ns/2-1}
+  clci2[N]=newl; Circle(clci2[N])={p1c[N],pAxe,p3si[N]};
+  clci3[N]=newl; Circle(clci3[N])={p4si[N],pAxe,p1c[(N+1)%Ns]};
+EndFor
+
+For N In {0:Ns/2-1}
+ Coillln[N]=newll; Line Loop (Coillln[N])={clci1[N],clci2[N],-clsi2[N],-clsi1[N]};
+ Coiln[N]=news ;   Plane Surface(Coiln[N])= {Coillln[N]};
+ Coilllp[N]=newll; Line Loop (Coilllp[N])={-clsi4[N],clci3[N],-clci1[(N+1)%Ns],-clsi5[N]};
+ Coilp[N]=news ;   Plane Surface(Coilp[N])= {Coilllp[N]};
+EndFor
+
+// Lines limiting the stator and coils (outer airgap)
+For N In {0:Ns/2-1}
+  airgco[3*N]  =clci2[N] ;
+  airgco[3*N+1]=clsi3[N] ;
+  airgco[3*N+2]=clci3[N] ;
+EndFor
+
+// Create Airgap Region
+Rair1=Rag1 ;
+Rair2=Rag2 ; // closing the airgap
+For N In {0:Ns/2-1}
+  th0s=N*Pi/2+th0ss;
+  p1aircox = Rair1*Cos(-dths/2.+th0s);
+  p1aircoy = Rair1*Sin(-dths/2.+th0s);
+  p1aircox_= Rair2*Cos(-dths/2.+th0s);
+  p1aircoy_= Rair2*Sin(-dths/2.+th0s);
+  p1airco[N] = newp; Point(p1airco[N]) ={p1aircox,p1aircoy,0.,  Lc/2} ;
+  p1airco_[N]= newp; Point(p1airco_[N])={p1aircox_,p1aircoy_, SlidingSurfaceShift,Lc/2} ;
+EndFor
+
+// Moving band
+For N In {0:1}
+  airG1[N]=newl; Circle(airG1[N]) = {p1airco[N], pAxe, p1airco[N+1]};
+  airG2[N]=newl; Circle(airG2[N]) = {p1airco_[N],pAxeShift, p1airco_[N+1]};
+
+  airG12[N] = newl ; Line(airG12[N]) = {p1airco[N], p1airco_[N]} ;
+EndFor
+airG12[2] = newl ; Line(airG12[2]) = {p1airco[2], p1airco_[2]} ;
+
+lmbs[]+=newl; Line(newl)={p1airco[0],p1c[0]};
+lmbs[]+=newl; Line(newl)={p1c[Ns/2],p1airco[2]};
+
+ll_inmbs=newll; Line Loop(ll_inmbs)={lmbs[0], airgco[], lmbs[1],-airG1[{1,0}]};
+surairgapS[0]=news ; Plane Surface(surairgapS[0]) = {ll_inmbs};
+
+For N In {0:1}
+  surmbstator[N]=news ; Line Loop (surmbstator[N]) = {-airG2[N],-airG12[N],airG1[N],airG12[N+1]};
+  Plane Surface(surmbstator[N])= surmbstator[N];
+EndFor
+
+Transfinite Line {airG1[], airG2[]} = ndiv_mb ;
+Transfinite Line {airG12[]} = 1 ;
+Transfinite Surface {surmbstator[]}; Recombine Surface {surmbstator[]};
+
+
+If(Flag_AirLayer)
+  For N In {0:Ns/2}
+    th0s=N*dths+th0ss;
+    pax=Rair*Cos(-dths/2.+th0s); pay=Rair*Sin(-dths/2.+th0s);
+    pa[N]=newp; Point(pa[N])={pax,pay,0.,8*Lc} ;
+  EndFor
+
+  For N In {0:Ns/2-1}
+    arca[]+=newl; Circle(newl)={pa[N],pAxe,pa[(N+1)%Ns]};
+  EndFor
+
+  lair0=newl; Line(newl)={3, pa[0]};
+  lair1=newl; Line(newl)={21, pa[3]};
+
+  Curve Loop(newll) = {58, 59, 60, -62, -3, -2, -1, 61};
+  surf_airlayer_out(0)=news; Plane Surface(surf_airlayer_out(0)) = {newll-1};
+EndIf
+
+
+
+//============================================================
+//============================================================
+If(Flag_Symmetry==0)
+  // FULL MODEL
+  // Rotation of Pi + duplication of all surfaces
+  NN = #arcso[]-1 ;
+  For N In {0:NN} // For simplicity (those lines would appear naturally when rotating Stator[0])
+    arcso[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Line{arcso[N]};} };
+  EndFor
+
+  Stator[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{Stator[0]};} };
+
+  For N In {0:Ns/2-1}
+    Coiln[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{Coiln[N]};} };
+    Coilp[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{Coilp[N]};} };
+  EndFor
+
+
+  airG2[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Line{airG2[{0,1}]};} };
+
+  surairgapS[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{surairgapS[{0}]};} };
+  surmbstator[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{surmbstator[{0,1}]};} };
+
+  If(Flag_AirLayer)
+    arca[]+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Line{arca[{0,1,2}]};} };
+    surf_airlayer_out()+= Rotate {{0, 0, 1}, {0, 0, 0}, Pi} { Duplicata{ Surface{surf_airlayer_out(0)};} };
+  EndIf
+
+EndIf
+
+
+
+
+
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+// Physical regions
+//-------------------------------------------------------------------------------
+//-------------------------------------------------------------------------------
+
+allsurfaces[]= Surface {:};
+allsurfaces[] -= {surairgapS[],surmbstator[]};
+Reverse Surface {allsurfaces[]};
+
+Physical Surface("stator iron", STATOR) = {Stator[]} ;
+Physical Surface("stator air", AIR_STATOR) = {surairgapS[]}; // part of airgap which is not regular
+Physical Surface("stator air (touching MB)", AIRGAP_STATOR) = {surmbstator[]}; // regular airgap
+
+NN = (!Flag_Symmetry)?Ns-1:(Ns/2-1);
+For N In {0:NN}
+ Physical Surface(Sprintf('coil N %g', N), COILN+N) = {Coiln[N]} ;
+ Physical Surface(Sprintf('coil P %g', N), COILP+N) = {Coilp[N]} ;
+EndFor
+
+Physical Line("skin stator (outer side)", BND_STATOR) = arcso[] ;
+Physical Line("line MB stator", MB_STATOR) = airG2[] ; // lines to connect
+
+If(Flag_Symmetry)
+  Physical Point("reference point MB stator", REF_PNT_MB_STATOR) = {p1airco_[2]} ;
+  //Lines for symmetry link
+  If(!Flag_AirLayer)
+    Physical Line("bnd stator A0", BND_A0_STATOR) = {ss1, clci1[0], airG12[0],lmbs[0]} ;
+    Physical Line("bnd stator A1", BND_A1_STATOR) = {ss2, clci1[#clci1[]-1], airG12[2],lmbs[1]} ;
+  Else
+    Physical Line("bnd stator A0", BND_A0_STATOR) = {ss1, clci1[0], airG12[0],lmbs[0], lair0} ;
+    Physical Line("bnd stator A1", BND_A1_STATOR) = {ss2, clci1[#clci1[]-1], airG12[2],lmbs[1],lair1} ;
+  EndIf
+EndIf
+
+If(Flag_AirLayer)
+  Physical Surface("air layer", AIRLAYER) = {surf_airlayer_out()} ;
+  Physical Line("bnd airlayer", BND_AIRLAYER) = arca[] ;
+EndIf
+
+
+
+//-------------------------------------------------------------------------------
+// For nice visualization
+//-------------------------------------------------------------------------------
+linStator[] = Abs(CombinedBoundary{ Surface{Stator[]};});
+linStator[] += Abs(Boundary{Surface{Coiln[], Coilp[]};});
+
+Color SteelBlue {Surface{Stator[]};}
+Color SkyBlue {Surface{surairgapS[]};}
+Color Cyan {Surface{surmbstator[]};}
+
+Color Red        {Surface{ Coilp[{0:NN:Ns/2}] };} // A+
+Color SpringGreen{Surface{ Coiln[{2:NN:Ns/2}] };} // C-
+Color Gold       {Surface{ Coilp[{1:NN:Ns/2}] };} // B+
+Color Red         {Surface{ Coiln[{0:NN:Ns/2}] };} // A-  Pink
+Color SpringGreen  {Surface{ Coilp[{2:NN:Ns/2}] };} // C+ ForestGreen
+Color Gold {Surface{ Coiln[{1:NN:Ns/2}] };} // B- PaleGoldenrod
-- 
GitLab