Actual source code: ex48.c

  1: static char help[] = "Magnetohydrodynamics (MHD) with Poisson brackets and "
  2:                      "stream functions, solver testbed for M3D-C1. Used in https://arxiv.org/abs/2302.10242";

  4: /*F
  5: The strong form of a two field model for vorticity $\Omega$ and magnetic flux
  6: $\psi$, using auxiliary variables potential $\phi$ and (negative) current
  7: density $j_z$ \cite{Jardin04,Strauss98}.See http://arxiv.org/abs/  for more details
  8: F*/

 10: #include <assert.h>
 11: #include <petscdmplex.h>
 12: #include <petscds.h>
 13: #include <petscts.h>

 15: typedef enum _testidx {
 16:   TEST_TILT,
 17:   NUM_TEST_TYPES
 18: } TestType;
 19: const char *testTypes[NUM_TEST_TYPES + 1] = {"tilt", "unknown"};
 20: typedef enum _modelidx {
 21:   TWO_FILD,
 22:   ONE_FILD,
 23:   NUM_MODELS
 24: } ModelType;
 25: const char *modelTypes[NUM_MODELS + 1] = {"two-field", "one-field", "unknown"};
 26: typedef enum _fieldidx {
 27:   JZ,
 28:   PSI,
 29:   PHI,
 30:   OMEGA,
 31:   NUM_COMP
 32: } FieldIdx; // add more
 33: typedef enum _const_idx {
 34:   MU_CONST,
 35:   ETA_CONST,
 36:   TEST_CONST,
 37:   NUM_CONSTS
 38: } ConstIdx;

 40: typedef struct {
 41:   PetscInt  debug; /* The debugging level */
 42:   PetscReal plotDt;
 43:   PetscReal plotStartTime;
 44:   PetscInt  plotIdx;
 45:   PetscInt  plotStep;
 46:   PetscBool plotting;
 47:   PetscInt  dim;                          /* The topological mesh dimension */
 48:   char      filename[PETSC_MAX_PATH_LEN]; /* The optional ExodusII file */
 49:   PetscErrorCode (**initialFuncs)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, PetscCtx ctx);
 50:   PetscReal mu, eta;
 51:   PetscReal perturb;
 52:   TestType  testType;
 53:   ModelType modelType;
 54:   PetscInt  Nf;
 55:   PetscBool massConstant; /* treat the mass matrix as constant (assemble once) */
 56: } AppCtx;

 58: static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options)
 59: {
 60:   PetscInt ii;

 62:   PetscFunctionBeginUser;
 63:   options->debug         = 1;
 64:   options->filename[0]   = '\0';
 65:   options->testType      = TEST_TILT;
 66:   options->modelType     = TWO_FILD;
 67:   options->mu            = 0.005;
 68:   options->eta           = 0.001;
 69:   options->perturb       = 0;
 70:   options->plotDt        = 0.1;
 71:   options->plotStartTime = 0.0;
 72:   options->plotIdx       = 0;
 73:   options->plotStep      = PETSC_INT_MAX;
 74:   options->plotting      = PETSC_FALSE;
 75:   options->massConstant  = PETSC_TRUE;

 77:   PetscOptionsBegin(comm, "", "MHD Problem Options", "DMPLEX");
 78:   PetscCall(PetscOptionsInt("-debug", "The debugging level", "mhd.c", options->debug, &options->debug, NULL));
 79:   ii                = (PetscInt)options->testType;
 80:   options->testType = TEST_TILT;
 81:   ii                = options->testType;
 82:   PetscCall(PetscOptionsEList("-test_type", "The test type: 'tilt' Tilt instability", "mhd.c", testTypes, NUM_TEST_TYPES, testTypes[options->testType], &ii, NULL));
 83:   options->testType  = (TestType)ii;
 84:   ii                 = (PetscInt)options->modelType;
 85:   options->modelType = TWO_FILD;
 86:   ii                 = options->modelType;
 87:   PetscCall(PetscOptionsEList("-model_type", "The model type: 'two', 'one' field", "mhd.c", modelTypes, NUM_MODELS, modelTypes[options->modelType], &ii, NULL));
 88:   options->modelType = (ModelType)ii;
 89:   options->Nf        = options->modelType == TWO_FILD ? 4 : 2;

 91:   PetscCall(PetscOptionsReal("-mu", "Magnetic resistivity", "mhd.c", options->mu, &options->mu, NULL));
 92:   PetscCall(PetscOptionsReal("-eta", "Viscosity", "mhd.c", options->eta, &options->eta, NULL));
 93:   PetscCall(PetscOptionsReal("-plot_dt", "Plot frequency in time", "mhd.c", options->plotDt, &options->plotDt, NULL));
 94:   PetscCall(PetscOptionsReal("-plot_start_time", "Time to delay start of plotting", "mhd.c", options->plotStartTime, &options->plotStartTime, NULL));
 95:   PetscCall(PetscOptionsReal("-perturbation", "Random perturbation of initial psi scale", "mhd.c", options->perturb, &options->perturb, NULL));
 96:   PetscCall(PetscOptionsBool("-mass_constant", "Treat the mass matrix as constant (assemble once and reuse)", "mhd.c", options->massConstant, &options->massConstant, NULL));
 97:   PetscCall(PetscPrintf(comm, "Test Type = %s\n", testTypes[options->testType]));
 98:   PetscCall(PetscPrintf(comm, "Model Type = %s\n", modelTypes[options->modelType]));
 99:   PetscCall(PetscPrintf(comm, "eta = %g\n", (double)options->eta));
100:   PetscCall(PetscPrintf(comm, "mu = %g\n", (double)options->mu));
101:   PetscOptionsEnd();
102:   PetscFunctionReturn(PETSC_SUCCESS);
103: }

105: // | 0 1 | matrix to apply bracket
106: // |-1 0 |
107: static PetscReal s_K[2][2] = {
108:   {0,  1},
109:   {-1, 0}
110: };

112: /*
113:  dt - "g0" are mass terms
114: */
115: static void g0_dt(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
116: {
117:   g0[0] = u_tShift;
118: }

120: /*
121:  Identity, Mass
122: */
123: static void g0_1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
124: {
125:   g0[0] = 1;
126: }
127: /* 'right' Poisson bracket -<.,phi>, linearized variable is left (column), data
128:  * variable right */
129: static void g1_phi_right(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
130: {
131:   PetscInt           i, j;
132:   const PetscScalar *pphiDer = &u_x[uOff_x[PHI]]; // get derivative of the 'right' ("dg") and apply to
133:                                                   // live var "df"
134:   for (i = 0; i < dim; ++i)
135:     for (j = 0; j < dim; ++j)
136:       //  indexing with inner, j, index generates the left live variable [dy,-]
137:       //  by convention, put j index on right, with i destination: [ d/dy,
138:       //  -d/dx]'
139:       g1[i] += s_K[i][j] * pphiDer[j];
140: }
141: /* 'left' bracket -{jz,.}, "n" for negative, linearized variable right (column),
142:  * data variable left */
143: static void g1_njz_left(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
144: {
145:   PetscInt           i, j;
146:   const PetscScalar *jzDer = &u_x[uOff_x[JZ]]; // get derivative of the 'left' ("df") and apply to live
147:                                                // var "dg"
148:   for (i = 0; i < dim; ++i)
149:     for (j = 0; j < dim; ++j)
150:       // live right: Der[i] * K: Der[j] --> j: [d/dy, -d/dx]'
151:       g1[j] += -jzDer[i] * s_K[i][j];
152: }
153: /* 'left' Poisson bracket -< . , psi> */
154: static void g1_npsi_right(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
155: {
156:   PetscInt           i, j;
157:   const PetscScalar *psiDer = &u_x[uOff_x[PSI]];
158:   for (i = 0; i < dim; ++i)
159:     for (j = 0; j < dim; ++j) g1[i] += -s_K[i][j] * psiDer[j];
160: }

162: /* < Omega , . > */
163: static void g1_omega_left(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
164: {
165:   PetscInt           i;
166:   const PetscScalar *pOmegaDer = &u_x[uOff_x[OMEGA]];
167:   for (i = 0; i < dim; ++i)
168:     for (PetscInt j = 0; j < dim; ++j) g1[j] += pOmegaDer[i] * s_K[i][j];
169: }

171: /* < psi , . > */
172: static void g1_psi_left(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
173: {
174:   PetscInt           i;
175:   const PetscScalar *pPsiDer = &u_x[uOff_x[PSI]];
176:   for (i = 0; i < dim; ++i)
177:     for (PetscInt j = 0; j < dim; ++j) g1[j] += pPsiDer[i] * s_K[i][j];
178: }

180: // -Lapacians (resistivity), negative sign goes away from IBP
181: static void g3_nmu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[])
182: {
183:   PetscReal mu = PetscRealPart(constants[MU_CONST]);
184:   for (PetscInt d = 0; d < dim; ++d) g3[d * dim + d] = mu;
185: }

187: // Auxiliary variable = -del^2 x, negative sign goes away from IBP
188: static void g3_n1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[])
189: {
190:   for (PetscInt d = 0; d < dim; ++d) g3[d * dim + d] = 1;
191: }

193: /* residual point methods */
194: static PetscScalar poissonBracket(PetscInt dim, const PetscScalar df[], const PetscScalar dg[])
195: {
196:   PetscScalar ret = df[0] * dg[1] - df[1] * dg[0];
197:   if (dim == 3) {
198:     ret += df[1] * dg[2] - df[2] * dg[1];
199:     ret += df[2] * dg[0] - df[0] * dg[2];
200:   }
201:   return ret;
202: }
203: //
204: static void f0_Omega(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
205: {
206:   const PetscScalar *omegaDer = &u_x[uOff_x[OMEGA]];
207:   const PetscScalar *psiDer   = &u_x[uOff_x[PSI]];
208:   const PetscScalar *phiDer   = &u_x[uOff_x[PHI]];
209:   const PetscScalar *jzDer    = &u_x[uOff_x[JZ]];

211:   f0[0] += poissonBracket(dim, omegaDer, phiDer) - poissonBracket(dim, jzDer, psiDer);

213:   if (u_t) f0[0] += u_t[OMEGA];
214: }

216: static void f1_Omega(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
217: {
218:   const PetscScalar *omegaDer = &u_x[uOff_x[OMEGA]];
219:   PetscReal          mu       = PetscRealPart(constants[MU_CONST]);

221:   for (PetscInt d = 0; d < dim; ++d) f1[d] += mu * omegaDer[d];
222: }

224: // d/dt + {psi,phi} - eta j_z
225: static void f0_psi_4f(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
226: {
227:   const PetscScalar *psiDer = &u_x[uOff_x[PSI]];
228:   const PetscScalar *phiDer = &u_x[uOff_x[PHI]];
229:   PetscReal          eta    = PetscRealPart(constants[ETA_CONST]);

231:   f0[0] = -eta * u[uOff[JZ]];
232:   f0[0] += poissonBracket(dim, psiDer, phiDer);

234:   if (u_t) f0[0] += u_t[PSI];
235:   // printf("psiDer = %20.15e %20.15e psi = %20.15e
236: }

238: // d/dt - eta j_z
239: static void f0_psi_2f(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
240: {
241:   PetscReal eta = PetscRealPart(constants[ETA_CONST]);

243:   f0[0] = -eta * u[uOff[JZ]];

245:   if (u_t) f0[0] += u_t[PSI];
246:   // printf("psiDer = %20.15e %20.15e psi = %20.15e
247: }

249: static void f0_phi(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
250: {
251:   f0[0] += u[uOff[OMEGA]];
252: }

254: static void f1_phi(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
255: {
256:   const PetscScalar *phiDer = &u_x[uOff_x[PHI]];

258:   for (PetscInt d = 0; d < dim; ++d) f1[d] = phiDer[d];
259: }

261: /* - eta M */
262: static void g0_neta(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
263: {
264:   PetscReal eta = PetscRealPart(constants[ETA_CONST]);

266:   g0[0] = -eta;
267: }

269: static void f0_jz(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
270: {
271:   f0[0] = u[uOff[JZ]];
272: }

274: /* -del^2 psi = (grad v, grad psi) */
275: static void f1_jz(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
276: {
277:   const PetscScalar *psiDer = &u_x[uOff_x[PSI]];

279:   for (PetscInt d = 0; d < dim; ++d) f1[d] = psiDer[d];
280: }

282: static void f0_mhd_B_energy2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
283: {
284:   const PetscScalar *psiDer = &u_x[uOff_x[PSI]];
285:   PetscScalar        b2     = 0;
286:   for (int i = 0; i < dim; ++i) b2 += psiDer[i] * psiDer[i];
287:   f0[0] = b2;
288: }

290: static void f0_mhd_v_energy2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar *f0)
291: {
292:   const PetscScalar *phiDer = &u_x[uOff_x[PHI]];
293:   PetscScalar        v2     = 0;
294:   for (int i = 0; i < dim; ++i) v2 += phiDer[i] * phiDer[i];
295:   f0[0] = v2;
296: }

298: static PetscErrorCode Monitor(TS ts, PetscInt stepi, PetscReal time, Vec X, void *actx)
299: {
300:   AppCtx             *ctx = (AppCtx *)actx; /* user-defined application context */
301:   SNES                snes;
302:   SNESConvergedReason reason;
303:   TSConvergedReason   tsreason;

305:   PetscFunctionBegin;
306:   // PetscCall(TSGetApplicationContext(ts, &ctx));
307:   if (ctx->debug < 1) PetscFunctionReturn(PETSC_SUCCESS);
308:   PetscCall(TSGetSNES(ts, &snes));
309:   PetscCall(SNESGetConvergedReason(snes, &reason));
310:   if (reason < 0) {
311:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), "\t\t ***************** Monitor: SNES diverged with reason %d.\n", (int)reason));
312:     PetscFunctionReturn(PETSC_SUCCESS);
313:   }
314:   if (stepi > ctx->plotStep && ctx->plotting) {
315:     ctx->plotting = PETSC_FALSE; /* was doing diagnostics, now done */
316:     ctx->plotIdx++;
317:   }
318:   PetscCall(TSGetTime(ts, &time));
319:   PetscCall(TSGetConvergedReason(ts, &tsreason));
320:   if (((time - ctx->plotStartTime) / ctx->plotDt >= (PetscReal)ctx->plotIdx && time >= ctx->plotStartTime) || (tsreason == TS_CONVERGED_TIME || tsreason == TS_CONVERGED_ITS) || ctx->plotIdx == 0) {
321:     DM          dm, plex;
322:     Vec         X;
323:     PetscReal   val;
324:     PetscScalar tt[12]; // FE integral seems to need a large array
325:     PetscDS     prob;
326:     if (!ctx->plotting) { /* first step of possible backtracks */
327:       ctx->plotting = PETSC_TRUE;
328:     } else {
329:       PetscCall(PetscPrintf(PETSC_COMM_WORLD, "\t\t ?????? ------\n"));
330:       ctx->plotting = PETSC_TRUE;
331:     }
332:     ctx->plotStep = stepi;
333:     PetscCall(TSGetSolution(ts, &X));
334:     PetscCall(VecGetDM(X, &dm));
335:     PetscCall(DMGetOutputSequenceNumber(dm, NULL, &val));
336:     PetscCall(DMSetOutputSequenceNumber(dm, ctx->plotIdx, val));
337:     PetscCall(VecViewFromOptions(X, NULL, "-vec_view_mhd"));
338:     if (ctx->debug > 2) {
339:       Vec R;
340:       PetscCall(SNESGetFunction(snes, &R, NULL, NULL));
341:       PetscCall(VecViewFromOptions(R, NULL, "-vec_view_res"));
342:     }
343:     // compute energy
344:     PetscCall(DMGetDS(dm, &prob));
345:     PetscCall(DMConvert(dm, DMPLEX, &plex));
346:     PetscCall(PetscDSSetObjective(prob, 0, &f0_mhd_v_energy2));
347:     PetscCall(DMPlexComputeIntegralFEM(plex, X, &tt[0], ctx));
348:     val = PetscRealPart(tt[0]);
349:     PetscCall(PetscDSSetObjective(prob, 0, &f0_mhd_B_energy2));
350:     PetscCall(DMPlexComputeIntegralFEM(plex, X, &tt[0], ctx));
351:     val = PetscSqrtReal(val) * 0.5 + PetscSqrtReal(PetscRealPart(tt[0])) * 0.5;
352:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts), "MHD %4d) time = %9.5g, Eergy= %20.13e (plot ID %d)\n", (int)ctx->plotIdx, (double)time, (double)val, (int)ctx->plotIdx));
353:     /* clean up */
354:     PetscCall(DMDestroy(&plex));
355:   }
356:   PetscFunctionReturn(PETSC_SUCCESS);
357: }

359: static PetscErrorCode CreateBCLabel(DM dm, const char name[])
360: {
361:   DMLabel label;

363:   PetscFunctionBeginUser;
364:   PetscCall(DMCreateLabel(dm, name));
365:   PetscCall(DMGetLabel(dm, name, &label));
366:   PetscCall(DMPlexMarkBoundaryFaces(dm, PETSC_DETERMINE, label));
367:   PetscCall(DMPlexLabelComplete(dm, label));
368:   PetscFunctionReturn(PETSC_SUCCESS);
369: }
370: // Create mesh, dim is set here
371: static PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *ctx, DM *dm)
372: {
373:   const char *filename = ctx->filename;
374:   size_t      len;
375:   char        buff[256];
376:   PetscMPIInt size;
377:   PetscInt    nface = 1;

379:   PetscFunctionBeginUser;
380:   PetscCall(PetscStrlen(filename, &len));
381:   if (len) {
382:     PetscCall(DMPlexCreateFromFile(comm, filename, "", PETSC_TRUE, dm));
383:   } else {
384:     PetscCall(DMCreate(comm, dm));
385:     PetscCall(DMSetType(*dm, DMPLEX));
386:   }
387:   PetscCallMPI(MPI_Comm_size(comm, &size));
388:   while (nface * nface < size) nface *= 2; // 2D
389:   if (nface < 2) nface = 2;
390:   PetscCall(PetscSNPrintf(buff, sizeof(buff), "-dm_plex_box_faces %d,%d -petscpartitioner_type simple", (int)nface, (int)nface));
391:   PetscCall(PetscOptionsInsertString(NULL, buff));
392:   PetscCall(PetscOptionsInsertString(NULL, "-dm_plex_box_lower -2,-2 -dm_plex_box_upper 2,2"));
393:   PetscCall(DMSetFromOptions(*dm));
394:   PetscCall(DMPlexDistributeSetDefault(*dm, PETSC_FALSE));
395:   PetscCall(DMGetDimension(*dm, &ctx->dim));
396:   {
397:     char      convType[256];
398:     PetscBool flg;
399:     PetscOptionsBegin(comm, "", "Mesh conversion options", "DMPLEX");
400:     PetscCall(PetscOptionsFList("-dm_plex_convert_type", "Convert DMPlex to another format", "mhd", DMList, DMPLEX, convType, sizeof(convType), &flg));
401:     PetscOptionsEnd();
402:     if (flg) {
403:       DM dmConv;
404:       PetscCall(DMConvert(*dm, convType, &dmConv));
405:       if (dmConv) {
406:         PetscCall(DMDestroy(dm));
407:         *dm = dmConv;
408:       }
409:     }
410:   }
411:   PetscCall(DMLocalizeCoordinates(*dm)); /* needed for periodic */
412:   {
413:     PetscBool hasLabel;
414:     PetscCall(DMHasLabel(*dm, "marker", &hasLabel));
415:     if (!hasLabel) PetscCall(CreateBCLabel(*dm, "marker"));
416:   }
417:   PetscCall(PetscObjectSetName((PetscObject)*dm, "Mesh"));
418:   PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view_mhd"));
419:   PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view_res"));
420:   PetscFunctionReturn(PETSC_SUCCESS);
421: }

423: static PetscErrorCode initialSolution_Omega(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, PetscCtx ctx)
424: {
425:   u[0] = 0.0;
426:   return PETSC_SUCCESS;
427: }

429: static PetscErrorCode initialSolution_Psi(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *a_ctx)
430: {
431:   AppCtx   *ctx = (AppCtx *)a_ctx;
432:   PetscReal r   = 0, theta, cos_theta;
433:   // k = sp.jn_zeros(1, 1)[0]
434:   const PetscReal k = 3.8317059702075125;
435:   for (PetscInt i = 0; i < dim; i++) r += x[i] * x[i];
436:   r = PetscSqrtReal(r);
437:   // r = sqrt(dot(x,x))
438:   theta     = PetscAtan2Real(x[1], x[0]);
439:   cos_theta = PetscCosReal(theta);
440:   // f = conditional(gt(r, 1.0), outer_f, inner_f)
441:   if (r < 1.0) {
442:     // inner_f =
443:     // (2/(Constant(k)*bessel_J(0,Constant(k))))*bessel_J(1,Constant(k)*r)*cos_theta
444:     u[0] = 2.0 / (k * j0(k)) * j1(k * r) * cos_theta;
445:   } else {
446:     // outer_f =  (1/r - r)*cos_theta
447:     u[0] = (r - 1.0 / r) * cos_theta;
448:   }
449:   u[0] += ctx->perturb * ((double)rand() / (double)RAND_MAX - 0.5);
450:   return PETSC_SUCCESS;
451: }

453: static PetscErrorCode initialSolution_Phi(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, PetscCtx ctx)
454: {
455:   u[0] = 0.0;
456:   return PETSC_SUCCESS;
457: }

459: static PetscErrorCode initialSolution_Jz(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, PetscCtx ctx)
460: {
461:   u[0] = 0.0;
462:   return PETSC_SUCCESS;
463: }

465: static PetscErrorCode SetupProblem(PetscDS prob, DM dm, AppCtx *ctx)
466: {
467:   PetscInt f;

469:   PetscFunctionBeginUser;
470:   // for both 2 & 4 field (j_z is same)
471:   PetscCall(PetscDSSetJacobian(prob, JZ, JZ, g0_1, NULL, NULL, NULL));
472:   PetscCall(PetscDSSetJacobian(prob, JZ, PSI, NULL, NULL, NULL, g3_n1));
473:   PetscCall(PetscDSSetResidual(prob, JZ, f0_jz, f1_jz));

475:   PetscCall(PetscDSSetJacobian(prob, PSI, JZ, g0_neta, NULL, NULL, NULL));
476:   if (ctx->modelType == ONE_FILD) {
477:     PetscCall(PetscDSSetJacobian(prob, PSI, PSI, g0_dt, NULL, NULL,
478:                                  NULL)); // remove phi term

480:     PetscCall(PetscDSSetResidual(prob, PSI, f0_psi_2f, NULL));
481:   } else {
482:     PetscCall(PetscDSSetJacobian(prob, PSI, PSI, g0_dt, g1_phi_right, NULL, NULL));
483:     PetscCall(PetscDSSetJacobian(prob, PSI, PHI, NULL, g1_psi_left, NULL, NULL));
484:     PetscCall(PetscDSSetResidual(prob, PSI, f0_psi_4f, NULL));

486:     PetscCall(PetscDSSetJacobian(prob, PHI, PHI, NULL, NULL, NULL, g3_n1));
487:     PetscCall(PetscDSSetJacobian(prob, PHI, OMEGA, g0_1, NULL, NULL, NULL));
488:     PetscCall(PetscDSSetResidual(prob, PHI, f0_phi, f1_phi));

490:     PetscCall(PetscDSSetJacobian(prob, OMEGA, OMEGA, g0_dt, g1_phi_right, NULL, g3_nmu));
491:     PetscCall(PetscDSSetJacobian(prob, OMEGA, PSI, NULL, g1_njz_left, NULL, NULL));
492:     PetscCall(PetscDSSetJacobian(prob, OMEGA, PHI, NULL, g1_omega_left, NULL, NULL));
493:     PetscCall(PetscDSSetJacobian(prob, OMEGA, JZ, NULL, g1_npsi_right, NULL, NULL));
494:     PetscCall(PetscDSSetResidual(prob, OMEGA, f0_Omega, f1_Omega));
495:   }
496:   /* Setup constants - is this persistent? */
497:   {
498:     PetscScalar scales[NUM_CONSTS]; // +1 adding in testType for use in the f
499:                                     // and g functions
500:     /* These could be set from the command line */
501:     scales[MU_CONST]  = ctx->mu;
502:     scales[ETA_CONST] = ctx->eta;
503:     // scales[TEST_CONST] = (PetscReal)ctx->testType; -- how to make work with complex
504:     PetscCall(PetscDSSetConstants(prob, NUM_CONSTS, scales));
505:   }
506:   for (f = 0; f < ctx->Nf; ++f) {
507:     ctx->initialFuncs[f] = NULL;
508:     PetscCall(PetscDSSetImplicit(prob, f, PETSC_TRUE));
509:   }
510:   if (ctx->testType == TEST_TILT) {
511:     const PetscInt id = 1;
512:     DMLabel        label;
513:     PetscCall(DMGetLabel(dm, "marker", &label));

515:     ctx->initialFuncs[JZ]  = initialSolution_Jz;
516:     ctx->initialFuncs[PSI] = initialSolution_Psi;

518:     PetscCall(PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "Jz for tilt test", label, 1, &id, JZ, 0, NULL, (PetscVoidFn *)initialSolution_Jz, NULL, ctx, NULL));
519:     PetscCall(PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "Psi for tilt test", label, 1, &id, PSI, 0, NULL, (PetscVoidFn *)initialSolution_Psi, NULL, ctx, NULL));
520:     if (ctx->modelType == TWO_FILD) {
521:       ctx->initialFuncs[OMEGA] = initialSolution_Omega;
522:       ctx->initialFuncs[PHI]   = initialSolution_Phi;
523:       PetscCall(PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "Omega for tilt test", label, 1, &id, OMEGA, 0, NULL, (PetscVoidFn *)initialSolution_Omega, NULL, ctx, NULL));
524:       PetscCall(PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, "Phi for tilt test", label, 1, &id, PHI, 0, NULL, (PetscVoidFn *)initialSolution_Phi, NULL, ctx, NULL));
525:     }
526:   } else {
527:     PetscCheck(0, PetscObjectComm((PetscObject)prob), PETSC_ERR_ARG_WRONG, "Unsupported test type: %s (%d)", testTypes[PetscMin(ctx->testType, NUM_TEST_TYPES)], (int)ctx->testType);
528:   }
529:   PetscCall(PetscDSSetContext(prob, 0, ctx));
530:   PetscCall(PetscDSSetFromOptions(prob));
531:   PetscFunctionReturn(PETSC_SUCCESS);
532: }

534: // mass term for a single-component field: g0 = 1 (the FEM mass matrix entry \int phi_i phi_j)
535: static void g0_mass(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
536: {
537:   g0[0] = 1.0;
538: }

540: // Assemble the singular mass matrix, which is the FEM mass matrix on PSI and OMEGA and zero on JZ and PHI
541: static PetscErrorCode MassMatrix(TS ts, PetscReal t, Vec U, Mat M, void *actx)
542: {
543:   AppCtx       *ctx = (AppCtx *)actx;
544:   DM            dm, dmc;
545:   PetscDS       ds;
546:   PetscWeakForm wf;
547:   Vec           u;
548:   IS            cellIS;
549:   PetscFormKey  key;
550:   PetscInt      depth;

552:   PetscFunctionBeginUser;
553:   PetscCall(TSGetDM(ts, &dm));
554:   PetscCall(PetscObjectQuery((PetscObject)dm, "ex48_mass_dm", (PetscObject *)&dmc));
555:   if (!dmc) {
556:     PetscCall(DMClone(dm, &dmc));
557:     PetscCall(DMCopyDisc(dm, dmc));
558:     PetscCall(DMGetDS(dmc, &ds));
559:     PetscCall(PetscDSGetWeakForm(ds, &wf));
560:     PetscCall(PetscWeakFormClear(wf));
561:     PetscCall(PetscDSSetJacobian(ds, PSI, PSI, g0_mass, NULL, NULL, NULL));
562:     if (ctx->modelType == TWO_FILD) PetscCall(PetscDSSetJacobian(ds, OMEGA, OMEGA, g0_mass, NULL, NULL, NULL));
563:     PetscCall(PetscObjectCompose((PetscObject)dm, "ex48_mass_dm", (PetscObject)dmc));
564:     PetscCall(PetscObjectDereference((PetscObject)dmc)); // dm keeps dmc alive
565:   }
566:   PetscCall(MatZeroEntries(M));
567:   // g0_mass() ignores the state, but the integrator still reads u
568:   PetscCall(DMGetLocalVector(dmc, &u));
569:   PetscCall(VecZeroEntries(u));
570:   PetscCall(DMPlexGetDepth(dmc, &depth));
571:   PetscCall(DMGetStratumIS(dmc, "depth", depth, &cellIS));
572:   key.label = NULL;
573:   key.value = 0;
574:   key.field = 0;
575:   key.part  = 0;
576:   PetscCall(DMPlexComputeJacobianByKey(dmc, key, cellIS, 0.0, 0.0, u, NULL, M, M, ctx));
577:   PetscCall(ISDestroy(&cellIS));
578:   PetscCall(DMRestoreLocalVector(dmc, &u));
579:   PetscFunctionReturn(PETSC_SUCCESS);
580: }

582: static PetscErrorCode SetupDiscretization(DM dm, AppCtx *ctx)
583: {
584:   DM             cdm;
585:   const PetscInt dim = ctx->dim;
586:   PetscFE        fe[NUM_COMP];
587:   PetscDS        prob;
588:   PetscInt       Nf           = ctx->Nf, f;
589:   PetscBool      cell_simplex = PETSC_TRUE;
590:   MPI_Comm       comm         = PetscObjectComm((PetscObject)dm);

592:   PetscFunctionBeginUser;
593:   /* Create finite element */
594:   PetscCall(PetscFECreateDefault(comm, dim, 1, cell_simplex, NULL, -1, &fe[JZ]));
595:   PetscCall(PetscObjectSetName((PetscObject)fe[JZ], "j_z"));
596:   PetscCall(DMSetField(dm, JZ, NULL, (PetscObject)fe[JZ]));
597:   PetscCall(PetscFECreateDefault(comm, dim, 1, cell_simplex, NULL, -1, &fe[PSI]));
598:   PetscCall(PetscObjectSetName((PetscObject)fe[PSI], "psi"));
599:   PetscCall(DMSetField(dm, PSI, NULL, (PetscObject)fe[PSI]));
600:   if (ctx->modelType == TWO_FILD) {
601:     PetscCall(PetscFECreateDefault(comm, dim, 1, cell_simplex, NULL, -1, &fe[OMEGA]));
602:     PetscCall(PetscObjectSetName((PetscObject)fe[OMEGA], "Omega"));
603:     PetscCall(DMSetField(dm, OMEGA, NULL, (PetscObject)fe[OMEGA]));

605:     PetscCall(PetscFECreateDefault(comm, dim, 1, cell_simplex, NULL, -1, &fe[PHI]));
606:     PetscCall(PetscObjectSetName((PetscObject)fe[PHI], "phi"));
607:     PetscCall(DMSetField(dm, PHI, NULL, (PetscObject)fe[PHI]));
608:   }
609:   /* Set discretization and boundary conditions for each mesh */
610:   PetscCall(DMCreateDS(dm));
611:   PetscCall(DMGetDS(dm, &prob));
612:   for (f = 0; f < Nf; ++f) PetscCall(PetscDSSetDiscretization(prob, f, (PetscObject)fe[f]));
613:   PetscCall(SetupProblem(prob, dm, ctx));
614:   cdm = dm;
615:   while (cdm) {
616:     PetscCall(DMCopyDisc(dm, cdm));
617:     if (dm != cdm) PetscCall(PetscObjectSetName((PetscObject)cdm, "Coarse"));
618:     PetscCall(DMGetCoarseDM(cdm, &cdm));
619:   }
620:   for (f = 0; f < Nf; ++f) PetscCall(PetscFEDestroy(&fe[f]));
621:   PetscFunctionReturn(PETSC_SUCCESS);
622: }

624: int main(int argc, char **argv)
625: {
626:   DM          dm;
627:   TS          ts;
628:   Vec         u, r;
629:   AppCtx      ctx;
630:   PetscReal   t        = 0.0;
631:   AppCtx     *ctxarr[] = {&ctx, &ctx, &ctx, &ctx}; // each variable could have a different context
632:   PetscMPIInt rank;

634:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
635:   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
636:   PetscCall(ProcessOptions(PETSC_COMM_WORLD, &ctx)); // dim is not set
637:   /* create mesh and problem */
638:   PetscCall(CreateMesh(PETSC_COMM_WORLD, &ctx, &dm));
639:   PetscCall(DMView(dm, PETSC_VIEWER_STDOUT_WORLD));
640:   PetscCall(DMSetApplicationContext(dm, &ctx));
641:   PetscCall(PetscMalloc1(ctx.Nf, &ctx.initialFuncs));
642:   PetscCall(SetupDiscretization(dm, &ctx));
643:   PetscCall(DMCreateGlobalVector(dm, &u));
644:   PetscCall(PetscObjectSetName((PetscObject)u, "u"));
645:   PetscCall(VecDuplicate(u, &r));
646:   PetscCall(PetscObjectSetName((PetscObject)r, "r"));
647:   /* create TS */
648:   PetscCall(TSCreate(PETSC_COMM_WORLD, &ts));
649:   PetscCall(TSSetDM(ts, dm));
650:   PetscCall(TSSetApplicationContext(ts, &ctx));
651:   PetscCall(DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, &ctx));
652:   PetscCall(DMTSSetIFunctionLocal(dm, DMPlexTSComputeIFunctionFEM, &ctx));
653:   PetscCall(DMTSSetIJacobianLocal(dm, DMPlexTSComputeIJacobianFEM, &ctx));
654:   // The mass matrix is constant, so by default TSIRK assembles it once
655:   PetscCall(TSSetMassMatrix(ts, MassMatrix, &ctx));
656:   PetscCall(TSSetMassMatrixConstant(ts, ctx.massConstant));
657:   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER));
658:   PetscCall(TSSetMaxTime(ts, 15.0));
659:   PetscCall(TSSetFromOptions(ts));
660:   PetscCall(TSMonitorSet(ts, Monitor, &ctx, NULL));
661:   /* make solution */
662:   PetscCall(DMProjectFunction(dm, t, ctx.initialFuncs, (void **)ctxarr, INSERT_ALL_VALUES, u));
663:   ctx.perturb = 0.0;
664:   PetscCall(TSSetSolution(ts, u));
665:   // solve
666:   PetscCall(TSSolve(ts, u));
667:   // cleanup
668:   PetscCall(VecDestroy(&u));
669:   PetscCall(VecDestroy(&r));
670:   PetscCall(TSDestroy(&ts));
671:   PetscCall(DMDestroy(&dm));
672:   PetscCall(PetscFree(ctx.initialFuncs));
673:   PetscCall(PetscFinalize());
674:   return 0;
675: }

677: /*TEST

679:   test:
680:     suffix: 0
681:     requires: triangle !complex
682:     nsize: 4
683:     args: -dm_plex_box_lower -2,-2 -dm_plex_box_upper 2,2 -dm_plex_simplex 1 -dm_refine_hierarchy 2 \
684:       -eta 0.0001 -ksp_converged_reason -ksp_max_it 50 -ksp_rtol 1e-3 -ksp_type fgmres -mg_coarse_ksp_rtol 1e-1 \
685:       -mg_coarse_ksp_type fgmres -mg_coarse_mg_levels_ksp_type gmres -mg_coarse_pc_type gamg -mg_levels_ksp_max_it 4 \
686:       -mg_levels_ksp_type gmres -mg_levels_pc_type jacobi -mu 0.005 -pc_mg_type full -pc_type mg \
687:       -petscpartitioner_type simple -petscspace_degree 2 -snes_converged_reason -snes_max_it 10 -snes_monitor \
688:       -snes_rtol 1.e-9 -snes_stol 1.e-9 -ts_adapt_dt_max 0.01 -ts_adapt_monitor -ts_arkimex_type 1bee \
689:       -ts_time_step 0.001 -ts_max_step_rejections 10 -ts_max_snes_failures unlimited -ts_max_steps 1 -ts_max_time -ts_monitor -ts_type arkimex
690:     filter: grep -v DM_

692:   # TSIRK integrates this DAE with the mass matrix from TSSetMassMatrix() and PCPBJACOBI.
693:   # irk_nonconstant evaluates the mass matrix at every Jacobian and must match irk_constant.
694:   testset:
695:     suffix: irk
696:     requires: triangle !complex
697:     nsize: 4
698:     output_file: output/ex48_irk.out
699:     args: -dm_plex_box_lower -2,-2 -dm_plex_box_upper 2,2 -dm_plex_simplex 1 -dm_refine_hierarchy 2 \
700:       -eta 0.0001 -mu 0.005 -petscpartitioner_type simple -petscspace_degree 2 \
701:       -ts_type irk -ts_time_step 0.001 -ts_max_steps 2 -ts_monitor \
702:       -ksp_type fgmres -pc_type pbjacobi -ksp_rtol 1e-6 -ksp_max_it 200 -snes_rtol 1.e-9 -snes_converged_reason
703:     filter: grep -E "TS dt|Nonlinear solve"
704:     test:
705:       suffix: constant
706:     test:
707:       suffix: nonconstant
708:       args: -mass_constant 0

710: TEST*/