Actual source code: ex9bus.c

  1: static char help[] = "Power grid stability analysis of WECC 9 bus system.\n\
  2: This example is based on the 9-bus (node) example given in the book Power\n\
  3: Systems Dynamics and Stability (Chapter 7) by P. Sauer and M. A. Pai.\n\
  4: The power grid in this example consists of 9 buses (nodes), 3 generators,\n\
  5: 3 loads, and 9 transmission lines. The network equations are written\n\
  6: in current balance form using rectangular coordinates.\n\n";

  8: /*
  9:    The equations for the stability analysis are described by the DAE

 11:    \dot{x} = f(x,y,t)
 12:      0     = g(x,y,t)

 14:    where the generators are described by differential equations, while the algebraic
 15:    constraints define the network equations.

 17:    The generators are modeled with a 4th order differential equation describing the electrical
 18:    and mechanical dynamics. Each generator also has an exciter system modeled by 3rd order
 19:    diff. eqns. describing the exciter, voltage regulator, and the feedback stabilizer
 20:    mechanism.

 22:    The network equations are described by nodal current balance equations.
 23:     I(x,y) - Y*V = 0

 25:    where:
 26:     I(x,y) is the current injected from generators and loads.
 27:       Y    is the admittance matrix, and
 28:       V    is the voltage vector
 29: */

 31: /*
 32:    Include "petscts.h" so that we can use the TS ODE integrators.  Note that this
 33:    file automatically includes:
 34:      petscsys.h - base PETSc routines
 35:      petscis.h  - index sets
 36:      petscvec.h - vectors
 37:      petscmat.h - matrices
 38:      petscpc.h  - preconditioners
 39:      petscksp.h - linear solvers
 40: */

 42: #include <petscts.h>
 43: #include <petscdm.h>
 44: #include <petscdmda.h>
 45: #include <petscdmcomposite.h>

 47: #define freq 60
 48: #define w_s  (2 * PETSC_PI * freq)

 50: /* Sizes and indices */
 51: const PetscInt nbus    = 9;         /* Number of network buses */
 52: const PetscInt ngen    = 3;         /* Number of generators */
 53: const PetscInt nload   = 3;         /* Number of loads */
 54: const PetscInt gbus[3] = {0, 1, 2}; /* Buses at which generators are incident */
 55: const PetscInt lbus[3] = {4, 5, 7}; /* Buses at which loads are incident */

 57: /* Generator real and reactive powers (found via loadflow) */
 58: const PetscScalar PG[3] = {0.716786142395021, 1.630000000000000, 0.850000000000000};
 59: const PetscScalar QG[3] = {0.270702180178785, 0.066120127797275, -0.108402221791588};
 60: /* Generator constants */
 61: const PetscScalar H[3]    = {23.64, 6.4, 3.01};       /* Inertia constant */
 62: const PetscScalar Rs[3]   = {0.0, 0.0, 0.0};          /* Stator Resistance */
 63: const PetscScalar Xd[3]   = {0.146, 0.8958, 1.3125};  /* d-axis reactance */
 64: const PetscScalar Xdp[3]  = {0.0608, 0.1198, 0.1813}; /* d-axis transient reactance */
 65: const PetscScalar Xq[3]   = {0.4360, 0.8645, 1.2578}; /* q-axis reactance Xq(1) set to 0.4360, value given in text 0.0969 */
 66: const PetscScalar Xqp[3]  = {0.0969, 0.1969, 0.25};   /* q-axis transient reactance */
 67: const PetscScalar Td0p[3] = {8.96, 6.0, 5.89};        /* d-axis open circuit time constant */
 68: const PetscScalar Tq0p[3] = {0.31, 0.535, 0.6};       /* q-axis open circuit time constant */
 69: PetscScalar       M[3];                               /* M = 2*H/w_s */
 70: PetscScalar       D[3];                               /* D = 0.1*M */

 72: PetscScalar TM[3]; /* Mechanical Torque */
 73: /* Exciter system constants */
 74: const PetscScalar KA[3]    = {20.0, 20.0, 20.0};    /* Voltage regulartor gain constant */
 75: const PetscScalar TA[3]    = {0.2, 0.2, 0.2};       /* Voltage regulator time constant */
 76: const PetscScalar KE[3]    = {1.0, 1.0, 1.0};       /* Exciter gain constant */
 77: const PetscScalar TE[3]    = {0.314, 0.314, 0.314}; /* Exciter time constant */
 78: const PetscScalar KF[3]    = {0.063, 0.063, 0.063}; /* Feedback stabilizer gain constant */
 79: const PetscScalar TF[3]    = {0.35, 0.35, 0.35};    /* Feedback stabilizer time constant */
 80: const PetscScalar k1[3]    = {0.0039, 0.0039, 0.0039};
 81: const PetscScalar k2[3]    = {1.555, 1.555, 1.555}; /* k1 and k2 for calculating the saturation function SE = k1*exp(k2*Efd) */
 82: const PetscScalar VRMIN[3] = {-4.0, -4.0, -4.0};
 83: const PetscScalar VRMAX[3] = {7.0, 7.0, 7.0};
 84: PetscInt          VRatmin[3];
 85: PetscInt          VRatmax[3];

 87: PetscScalar Vref[3];
 88: /* Load constants
 89:   We use a composite load model that describes the load and reactive powers at each time instant as follows
 90:   P(t) = \sum\limits_{i=0}^ld_nsegsp \ld_alphap_i*P_D0(\frac{V_m(t)}{V_m0})^\ld_betap_i
 91:   Q(t) = \sum\limits_{i=0}^ld_nsegsq \ld_alphaq_i*Q_D0(\frac{V_m(t)}{V_m0})^\ld_betaq_i
 92:   where
 93:     ld_nsegsp,ld_nsegsq - Number of individual load models for real and reactive power loads
 94:     ld_alphap,ld_alphap - Percentage contribution (weights) or loads
 95:     P_D0                - Real power load
 96:     Q_D0                - Reactive power load
 97:     V_m(t)              - Voltage magnitude at time t
 98:     V_m0                - Voltage magnitude at t = 0
 99:     ld_betap, ld_betaq  - exponents describing the load model for real and reactive part

101:     Note: All loads have the same characteristic currently.
102: */
103: const PetscScalar PD0[3]       = {1.25, 0.9, 1.0};
104: const PetscScalar QD0[3]       = {0.5, 0.3, 0.35};
105: const PetscInt    ld_nsegsp[3] = {3, 3, 3};
106: const PetscScalar ld_alphap[3] = {1.0, 0.0, 0.0};
107: const PetscScalar ld_betap[3]  = {2.0, 1.0, 0.0};
108: const PetscInt    ld_nsegsq[3] = {3, 3, 3};
109: const PetscScalar ld_alphaq[3] = {1.0, 0.0, 0.0};
110: const PetscScalar ld_betaq[3]  = {2.0, 1.0, 0.0};

112: typedef struct {
113:   DM          dmgen, dmnet;        /* DMs to manage generator and network subsystem */
114:   DM          dmpgrid;             /* Composite DM to manage the entire power grid */
115:   Mat         Ybus;                /* Network admittance matrix */
116:   Vec         V0;                  /* Initial voltage vector (Power flow solution) */
117:   PetscReal   tfaulton, tfaultoff; /* Fault on and off times */
118:   PetscInt    faultbus;            /* Fault bus */
119:   PetscScalar Rfault;
120:   PetscReal   t0, tmax;
121:   PetscInt    neqs_gen, neqs_net, neqs_pgrid;
122:   Mat         Sol; /* Matrix to save solution at each time step */
123:   PetscInt    stepnum;
124:   PetscReal   t;
125:   SNES        snes_alg;
126:   IS          is_diff;      /* indices for differential equations */
127:   IS          is_alg;       /* indices for algebraic equations */
128:   PetscBool   setisdiff;    /* TS computes truncation error based only on the differential variables */
129:   PetscBool   semiexplicit; /* If the flag is set then a semi-explicit method is used using TSRK */
130: } Userctx;

132: /*
133:   The first two events are for fault on and off, respectively. The following events are
134:   to check the min/max limits on the state variable VR. A non windup limiter is used for
135:   the VR limits.
136: */
137: PetscErrorCode EventFunction(TS ts, PetscReal t, Vec X, PetscReal *fvalue, PetscCtx ctx)
138: {
139:   Userctx           *user = (Userctx *)ctx;
140:   Vec                Xgen, Xnet;
141:   PetscInt           i, idx = 0;
142:   const PetscScalar *xgen, *xnet;
143:   PetscScalar        Efd, RF, VR, Vr, Vi, Vm;

145:   PetscFunctionBegin;
146:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Xgen, &Xnet));
147:   PetscCall(DMCompositeScatter(user->dmpgrid, X, Xgen, Xnet));

149:   PetscCall(VecGetArrayRead(Xgen, &xgen));
150:   PetscCall(VecGetArrayRead(Xnet, &xnet));

152:   /* Event for fault-on time */
153:   fvalue[0] = t - user->tfaulton;
154:   /* Event for fault-off time */
155:   fvalue[1] = t - user->tfaultoff;

157:   for (i = 0; i < ngen; i++) {
158:     Efd = xgen[idx + 6];
159:     RF  = xgen[idx + 7];
160:     VR  = xgen[idx + 8];

162:     Vr = xnet[2 * gbus[i]];     /* Real part of generator terminal voltage */
163:     Vi = xnet[2 * gbus[i] + 1]; /* Imaginary part of the generator terminal voltage */
164:     Vm = PetscSqrtScalar(Vr * Vr + Vi * Vi);

166:     if (!VRatmax[i]) {
167:       fvalue[2 + 2 * i] = PetscRealPart(VRMAX[i] - VR);
168:     } else {
169:       fvalue[2 + 2 * i] = PetscRealPart((VR - KA[i] * RF + KA[i] * KF[i] * Efd / TF[i] - KA[i] * (Vref[i] - Vm)) / TA[i]);
170:     }
171:     if (!VRatmin[i]) {
172:       fvalue[2 + 2 * i + 1] = PetscRealPart(VRMIN[i] - VR);
173:     } else {
174:       fvalue[2 + 2 * i + 1] = PetscRealPart((VR - KA[i] * RF + KA[i] * KF[i] * Efd / TF[i] - KA[i] * (Vref[i] - Vm)) / TA[i]);
175:     }
176:     idx = idx + 9;
177:   }
178:   PetscCall(VecRestoreArrayRead(Xgen, &xgen));
179:   PetscCall(VecRestoreArrayRead(Xnet, &xnet));

181:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Xgen, &Xnet));
182:   PetscFunctionReturn(PETSC_SUCCESS);
183: }

185: PetscErrorCode PostEventFunction(TS ts, PetscInt nevents, PetscInt event_list[], PetscReal t, Vec X, PetscBool forwardsolve, PetscCtx ctx)
186: {
187:   Userctx     *user = (Userctx *)ctx;
188:   Vec          Xgen, Xnet;
189:   PetscScalar *xgen, *xnet;
190:   PetscInt     row_loc, col_loc;
191:   PetscScalar  val;
192:   PetscInt     i, idx = 0, event_num;
193:   PetscScalar  fvalue;
194:   PetscScalar  Efd, RF, VR;
195:   PetscScalar  Vr, Vi, Vm;

197:   PetscFunctionBegin;
198:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Xgen, &Xnet));
199:   PetscCall(DMCompositeScatter(user->dmpgrid, X, Xgen, Xnet));

201:   PetscCall(VecGetArray(Xgen, &xgen));
202:   PetscCall(VecGetArray(Xnet, &xnet));

204:   for (i = 0; i < nevents; i++) {
205:     if (event_list[i] == 0) {
206:       /* Apply disturbance - resistive fault at user->faultbus */
207:       /* This is done by adding shunt conductance to the diagonal location
208:          in the Ybus matrix */
209:       row_loc = 2 * user->faultbus;
210:       col_loc = 2 * user->faultbus + 1; /* Location for G */
211:       val     = 1 / user->Rfault;
212:       PetscCall(MatSetValues(user->Ybus, 1, &row_loc, 1, &col_loc, &val, ADD_VALUES));
213:       row_loc = 2 * user->faultbus + 1;
214:       col_loc = 2 * user->faultbus; /* Location for G */
215:       val     = 1 / user->Rfault;
216:       PetscCall(MatSetValues(user->Ybus, 1, &row_loc, 1, &col_loc, &val, ADD_VALUES));

218:       PetscCall(MatAssemblyBegin(user->Ybus, MAT_FINAL_ASSEMBLY));
219:       PetscCall(MatAssemblyEnd(user->Ybus, MAT_FINAL_ASSEMBLY));

221:       /* Solve the algebraic equations */
222:       PetscCall(SNESSolve(user->snes_alg, NULL, X));
223:     } else if (event_list[i] == 1) {
224:       /* Remove the fault */
225:       row_loc = 2 * user->faultbus;
226:       col_loc = 2 * user->faultbus + 1;
227:       val     = -1 / user->Rfault;
228:       PetscCall(MatSetValues(user->Ybus, 1, &row_loc, 1, &col_loc, &val, ADD_VALUES));
229:       row_loc = 2 * user->faultbus + 1;
230:       col_loc = 2 * user->faultbus;
231:       val     = -1 / user->Rfault;
232:       PetscCall(MatSetValues(user->Ybus, 1, &row_loc, 1, &col_loc, &val, ADD_VALUES));

234:       PetscCall(MatAssemblyBegin(user->Ybus, MAT_FINAL_ASSEMBLY));
235:       PetscCall(MatAssemblyEnd(user->Ybus, MAT_FINAL_ASSEMBLY));

237:       /* Solve the algebraic equations */
238:       PetscCall(SNESSolve(user->snes_alg, NULL, X));

240:       /* Check the VR derivatives and reset flags if needed */
241:       for (i = 0; i < ngen; i++) {
242:         Efd = xgen[idx + 6];
243:         RF  = xgen[idx + 7];
244:         VR  = xgen[idx + 8];

246:         Vr = xnet[2 * gbus[i]];     /* Real part of generator terminal voltage */
247:         Vi = xnet[2 * gbus[i] + 1]; /* Imaginary part of the generator terminal voltage */
248:         Vm = PetscSqrtScalar(Vr * Vr + Vi * Vi);

250:         if (VRatmax[i]) {
251:           fvalue = (VR - KA[i] * RF + KA[i] * KF[i] * Efd / TF[i] - KA[i] * (Vref[i] - Vm)) / TA[i];
252:           if (fvalue < 0) {
253:             VRatmax[i] = 0;
254:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: dVR_dt went negative on fault clearing at time %g\n", i, (double)t));
255:           }
256:         }
257:         if (VRatmin[i]) {
258:           fvalue = (VR - KA[i] * RF + KA[i] * KF[i] * Efd / TF[i] - KA[i] * (Vref[i] - Vm)) / TA[i];

260:           if (fvalue > 0) {
261:             VRatmin[i] = 0;
262:             PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: dVR_dt went positive on fault clearing at time %g\n", i, (double)t));
263:           }
264:         }
265:         idx = idx + 9;
266:       }
267:     } else {
268:       idx       = (event_list[i] - 2) / 2;
269:       event_num = (event_list[i] - 2) % 2;
270:       if (event_num == 0) { /* Max VR */
271:         if (!VRatmax[idx]) {
272:           VRatmax[idx] = 1;
273:           PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: hit upper limit at time %g\n", idx, (double)t));
274:         } else {
275:           VRatmax[idx] = 0;
276:           PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: freeing variable as dVR_dt is negative at time %g\n", idx, (double)t));
277:         }
278:       } else {
279:         if (!VRatmin[idx]) {
280:           VRatmin[idx] = 1;
281:           PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: hit lower limit at time %g\n", idx, (double)t));
282:         } else {
283:           VRatmin[idx] = 0;
284:           PetscCall(PetscPrintf(PETSC_COMM_SELF, "VR[%" PetscInt_FMT "]: freeing variable as dVR_dt is positive at time %g\n", idx, (double)t));
285:         }
286:       }
287:     }
288:   }

290:   PetscCall(VecRestoreArray(Xgen, &xgen));
291:   PetscCall(VecRestoreArray(Xnet, &xnet));

293:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Xgen, &Xnet));
294:   PetscFunctionReturn(PETSC_SUCCESS);
295: }

297: /* Converts from machine frame (dq) to network (phase a real,imag) reference frame */
298: PetscErrorCode dq2ri(PetscScalar Fd, PetscScalar Fq, PetscScalar delta, PetscScalar *Fr, PetscScalar *Fi)
299: {
300:   PetscFunctionBegin;
301:   *Fr = Fd * PetscSinScalar(delta) + Fq * PetscCosScalar(delta);
302:   *Fi = -Fd * PetscCosScalar(delta) + Fq * PetscSinScalar(delta);
303:   PetscFunctionReturn(PETSC_SUCCESS);
304: }

306: /* Converts from network frame ([phase a real,imag) to machine (dq) reference frame */
307: PetscErrorCode ri2dq(PetscScalar Fr, PetscScalar Fi, PetscScalar delta, PetscScalar *Fd, PetscScalar *Fq)
308: {
309:   PetscFunctionBegin;
310:   *Fd = Fr * PetscSinScalar(delta) - Fi * PetscCosScalar(delta);
311:   *Fq = Fr * PetscCosScalar(delta) + Fi * PetscSinScalar(delta);
312:   PetscFunctionReturn(PETSC_SUCCESS);
313: }

315: /* Saves the solution at each time to a matrix */
316: PetscErrorCode SaveSolution(TS ts)
317: {
318:   Userctx           *user;
319:   Vec                X;
320:   const PetscScalar *x;
321:   PetscScalar       *mat;
322:   PetscInt           idx;
323:   PetscReal          t;

325:   PetscFunctionBegin;
326:   PetscCall(TSGetApplicationContext(ts, &user));
327:   PetscCall(TSGetTime(ts, &t));
328:   PetscCall(TSGetSolution(ts, &X));
329:   idx = user->stepnum * (user->neqs_pgrid + 1);
330:   PetscCall(MatDenseGetArray(user->Sol, &mat));
331:   PetscCall(VecGetArrayRead(X, &x));
332:   mat[idx] = t;
333:   PetscCall(PetscArraycpy(mat + idx + 1, x, user->neqs_pgrid));
334:   PetscCall(MatDenseRestoreArray(user->Sol, &mat));
335:   PetscCall(VecRestoreArrayRead(X, &x));
336:   user->stepnum++;
337:   PetscFunctionReturn(PETSC_SUCCESS);
338: }

340: PetscErrorCode SetInitialGuess(Vec X, Userctx *user)
341: {
342:   Vec                Xgen, Xnet;
343:   PetscScalar       *xgen;
344:   const PetscScalar *xnet;
345:   PetscInt           i, idx = 0;
346:   PetscScalar        Vr, Vi, IGr, IGi, Vm, Vm2;
347:   PetscScalar        Eqp, Edp, delta;
348:   PetscScalar        Efd, RF, VR; /* Exciter variables */
349:   PetscScalar        Id, Iq;      /* Generator dq axis currents */
350:   PetscScalar        theta, Vd, Vq, SE;

352:   PetscFunctionBegin;
353:   M[0] = 2 * H[0] / w_s;
354:   M[1] = 2 * H[1] / w_s;
355:   M[2] = 2 * H[2] / w_s;
356:   D[0] = 0.1 * M[0];
357:   D[1] = 0.1 * M[1];
358:   D[2] = 0.1 * M[2];

360:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Xgen, &Xnet));

362:   /* Network subsystem initialization */
363:   PetscCall(VecCopy(user->V0, Xnet));

365:   /* Generator subsystem initialization */
366:   PetscCall(VecGetArrayWrite(Xgen, &xgen));
367:   PetscCall(VecGetArrayRead(Xnet, &xnet));

369:   for (i = 0; i < ngen; i++) {
370:     Vr  = xnet[2 * gbus[i]];     /* Real part of generator terminal voltage */
371:     Vi  = xnet[2 * gbus[i] + 1]; /* Imaginary part of the generator terminal voltage */
372:     Vm  = PetscSqrtScalar(Vr * Vr + Vi * Vi);
373:     Vm2 = Vm * Vm;
374:     IGr = (Vr * PG[i] + Vi * QG[i]) / Vm2;
375:     IGi = (Vi * PG[i] - Vr * QG[i]) / Vm2;

377:     delta = PetscAtan2Real(Vi + Xq[i] * IGr, Vr - Xq[i] * IGi); /* Machine angle */

379:     theta = PETSC_PI / 2.0 - delta;

381:     Id = IGr * PetscCosScalar(theta) - IGi * PetscSinScalar(theta); /* d-axis stator current */
382:     Iq = IGr * PetscSinScalar(theta) + IGi * PetscCosScalar(theta); /* q-axis stator current */

384:     Vd = Vr * PetscCosScalar(theta) - Vi * PetscSinScalar(theta);
385:     Vq = Vr * PetscSinScalar(theta) + Vi * PetscCosScalar(theta);

387:     Edp = Vd + Rs[i] * Id - Xqp[i] * Iq; /* d-axis transient EMF */
388:     Eqp = Vq + Rs[i] * Iq + Xdp[i] * Id; /* q-axis transient EMF */

390:     TM[i] = PG[i];

392:     /* The generator variables are ordered as [Eqp,Edp,delta,w,Id,Iq] */
393:     xgen[idx]     = Eqp;
394:     xgen[idx + 1] = Edp;
395:     xgen[idx + 2] = delta;
396:     xgen[idx + 3] = w_s;

398:     idx = idx + 4;

400:     xgen[idx]     = Id;
401:     xgen[idx + 1] = Iq;

403:     idx = idx + 2;

405:     /* Exciter */
406:     Efd = Eqp + (Xd[i] - Xdp[i]) * Id;
407:     SE  = k1[i] * PetscExpScalar(k2[i] * Efd);
408:     VR  = KE[i] * Efd + SE;
409:     RF  = KF[i] * Efd / TF[i];

411:     xgen[idx]     = Efd;
412:     xgen[idx + 1] = RF;
413:     xgen[idx + 2] = VR;

415:     Vref[i] = Vm + (VR / KA[i]);

417:     VRatmin[i] = VRatmax[i] = 0;

419:     idx = idx + 3;
420:   }
421:   PetscCall(VecRestoreArrayWrite(Xgen, &xgen));
422:   PetscCall(VecRestoreArrayRead(Xnet, &xnet));

424:   /* PetscCall(VecView(Xgen,0)); */
425:   PetscCall(DMCompositeGather(user->dmpgrid, INSERT_VALUES, X, Xgen, Xnet));
426:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Xgen, &Xnet));
427:   PetscFunctionReturn(PETSC_SUCCESS);
428: }

430: /* Computes F = [f(x,y);g(x,y)] */
431: PetscErrorCode ResidualFunction(Vec X, Vec F, Userctx *user)
432: {
433:   Vec                Xgen, Xnet, Fgen, Fnet;
434:   const PetscScalar *xgen, *xnet;
435:   PetscScalar       *fgen, *fnet;
436:   PetscInt           i, idx = 0;
437:   PetscScalar        Vr, Vi, Vm, Vm2;
438:   PetscScalar        Eqp, Edp, delta, w; /* Generator variables */
439:   PetscScalar        Efd, RF, VR;        /* Exciter variables */
440:   PetscScalar        Id, Iq;             /* Generator dq axis currents */
441:   PetscScalar        Vd, Vq, SE;
442:   PetscScalar        IGr, IGi, IDr, IDi;
443:   PetscScalar        Zdq_inv[4], det;
444:   PetscScalar        PD, QD, Vm0, *v0;

446:   PetscFunctionBegin;
447:   PetscCall(VecZeroEntries(F));
448:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Xgen, &Xnet));
449:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Fgen, &Fnet));
450:   PetscCall(DMCompositeScatter(user->dmpgrid, X, Xgen, Xnet));
451:   PetscCall(DMCompositeScatter(user->dmpgrid, F, Fgen, Fnet));

453:   /* Network current balance residual IG + Y*V + IL = 0. Only YV is added here.
454:      The generator current injection, IG, and load current injection, ID are added later
455:   */
456:   /* Note that the values in Ybus are stored assuming the imaginary current balance
457:      equation is ordered first followed by real current balance equation for each bus.
458:      Thus imaginary current contribution goes in location 2*i, and
459:      real current contribution in 2*i+1
460:   */
461:   PetscCall(MatMult(user->Ybus, Xnet, Fnet));

463:   PetscCall(VecGetArrayRead(Xgen, &xgen));
464:   PetscCall(VecGetArrayRead(Xnet, &xnet));
465:   PetscCall(VecGetArrayWrite(Fgen, &fgen));
466:   PetscCall(VecGetArrayWrite(Fnet, &fnet));

468:   /* Generator subsystem */
469:   for (i = 0; i < ngen; i++) {
470:     Eqp   = xgen[idx];
471:     Edp   = xgen[idx + 1];
472:     delta = xgen[idx + 2];
473:     w     = xgen[idx + 3];
474:     Id    = xgen[idx + 4];
475:     Iq    = xgen[idx + 5];
476:     Efd   = xgen[idx + 6];
477:     RF    = xgen[idx + 7];
478:     VR    = xgen[idx + 8];

480:     /* Generator differential equations */
481:     fgen[idx]     = (-Eqp - (Xd[i] - Xdp[i]) * Id + Efd) / Td0p[i];
482:     fgen[idx + 1] = (-Edp + (Xq[i] - Xqp[i]) * Iq) / Tq0p[i];
483:     fgen[idx + 2] = w - w_s;
484:     fgen[idx + 3] = (TM[i] - Edp * Id - Eqp * Iq - (Xqp[i] - Xdp[i]) * Id * Iq - D[i] * (w - w_s)) / M[i];

486:     Vr = xnet[2 * gbus[i]];     /* Real part of generator terminal voltage */
487:     Vi = xnet[2 * gbus[i] + 1]; /* Imaginary part of the generator terminal voltage */

489:     PetscCall(ri2dq(Vr, Vi, delta, &Vd, &Vq));
490:     /* Algebraic equations for stator currents */
491:     det = Rs[i] * Rs[i] + Xdp[i] * Xqp[i];

493:     Zdq_inv[0] = Rs[i] / det;
494:     Zdq_inv[1] = Xqp[i] / det;
495:     Zdq_inv[2] = -Xdp[i] / det;
496:     Zdq_inv[3] = Rs[i] / det;

498:     fgen[idx + 4] = Zdq_inv[0] * (-Edp + Vd) + Zdq_inv[1] * (-Eqp + Vq) + Id;
499:     fgen[idx + 5] = Zdq_inv[2] * (-Edp + Vd) + Zdq_inv[3] * (-Eqp + Vq) + Iq;

501:     /* Add generator current injection to network */
502:     PetscCall(dq2ri(Id, Iq, delta, &IGr, &IGi));

504:     fnet[2 * gbus[i]] -= IGi;
505:     fnet[2 * gbus[i] + 1] -= IGr;

507:     Vm = PetscSqrtScalar(Vd * Vd + Vq * Vq);

509:     SE = k1[i] * PetscExpScalar(k2[i] * Efd);

511:     /* Exciter differential equations */
512:     fgen[idx + 6] = (-KE[i] * Efd - SE + VR) / TE[i];
513:     fgen[idx + 7] = (-RF + KF[i] * Efd / TF[i]) / TF[i];
514:     if (VRatmax[i]) fgen[idx + 8] = VR - VRMAX[i];
515:     else if (VRatmin[i]) fgen[idx + 8] = VRMIN[i] - VR;
516:     else fgen[idx + 8] = (-VR + KA[i] * RF - KA[i] * KF[i] * Efd / TF[i] + KA[i] * (Vref[i] - Vm)) / TA[i];

518:     idx = idx + 9;
519:   }

521:   PetscCall(VecGetArray(user->V0, &v0));
522:   for (i = 0; i < nload; i++) {
523:     Vr  = xnet[2 * lbus[i]];     /* Real part of load bus voltage */
524:     Vi  = xnet[2 * lbus[i] + 1]; /* Imaginary part of the load bus voltage */
525:     Vm  = PetscSqrtScalar(Vr * Vr + Vi * Vi);
526:     Vm2 = Vm * Vm;
527:     Vm0 = PetscSqrtScalar(v0[2 * lbus[i]] * v0[2 * lbus[i]] + v0[2 * lbus[i] + 1] * v0[2 * lbus[i] + 1]);
528:     PD = QD = 0.0;
529:     for (PetscInt k = 0; k < ld_nsegsp[i]; k++) PD += ld_alphap[k] * PD0[i] * PetscPowScalar(Vm / Vm0, ld_betap[k]);
530:     for (PetscInt k = 0; k < ld_nsegsq[i]; k++) QD += ld_alphaq[k] * QD0[i] * PetscPowScalar(Vm / Vm0, ld_betaq[k]);

532:     /* Load currents */
533:     IDr = (PD * Vr + QD * Vi) / Vm2;
534:     IDi = (-QD * Vr + PD * Vi) / Vm2;

536:     fnet[2 * lbus[i]] += IDi;
537:     fnet[2 * lbus[i] + 1] += IDr;
538:   }
539:   PetscCall(VecRestoreArray(user->V0, &v0));

541:   PetscCall(VecRestoreArrayRead(Xgen, &xgen));
542:   PetscCall(VecRestoreArrayRead(Xnet, &xnet));
543:   PetscCall(VecRestoreArrayWrite(Fgen, &fgen));
544:   PetscCall(VecRestoreArrayWrite(Fnet, &fnet));

546:   PetscCall(DMCompositeGather(user->dmpgrid, INSERT_VALUES, F, Fgen, Fnet));
547:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Xgen, &Xnet));
548:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Fgen, &Fnet));
549:   PetscFunctionReturn(PETSC_SUCCESS);
550: }

552: /*   f(x,y)
553:      g(x,y)
554:  */
555: PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec X, Vec F, PetscCtx ctx)
556: {
557:   Userctx *user = (Userctx *)ctx;

559:   PetscFunctionBegin;
560:   user->t = t;
561:   PetscCall(ResidualFunction(X, F, user));
562:   PetscFunctionReturn(PETSC_SUCCESS);
563: }

565: /* f(x,y) - \dot{x}
566:      g(x,y) = 0
567:  */
568: PetscErrorCode IFunction(TS ts, PetscReal t, Vec X, Vec Xdot, Vec F, PetscCtx ctx)
569: {
570:   PetscScalar       *f;
571:   const PetscScalar *xdot;
572:   PetscInt           i;

574:   PetscFunctionBegin;
575:   PetscCall(RHSFunction(ts, t, X, F, ctx));
576:   PetscCall(VecScale(F, -1.0));
577:   PetscCall(VecGetArray(F, &f));
578:   PetscCall(VecGetArrayRead(Xdot, &xdot));
579:   for (i = 0; i < ngen; i++) {
580:     f[9 * i] += xdot[9 * i];
581:     f[9 * i + 1] += xdot[9 * i + 1];
582:     f[9 * i + 2] += xdot[9 * i + 2];
583:     f[9 * i + 3] += xdot[9 * i + 3];
584:     f[9 * i + 6] += xdot[9 * i + 6];
585:     f[9 * i + 7] += xdot[9 * i + 7];
586:     f[9 * i + 8] += xdot[9 * i + 8];
587:   }
588:   PetscCall(VecRestoreArray(F, &f));
589:   PetscCall(VecRestoreArrayRead(Xdot, &xdot));
590:   PetscFunctionReturn(PETSC_SUCCESS);
591: }

593: /* This function is used for solving the algebraic system only during fault on and
594:    off times. It computes the entire F and then zeros out the part corresponding to
595:    differential equations
596:  F = [0;g(y)];
597: */
598: PetscErrorCode AlgFunction(SNES snes, Vec X, Vec F, PetscCtx ctx)
599: {
600:   Userctx     *user = (Userctx *)ctx;
601:   PetscScalar *f;
602:   PetscInt     i;

604:   PetscFunctionBegin;
605:   PetscCall(ResidualFunction(X, F, user));
606:   PetscCall(VecGetArray(F, &f));
607:   for (i = 0; i < ngen; i++) {
608:     f[9 * i]     = 0;
609:     f[9 * i + 1] = 0;
610:     f[9 * i + 2] = 0;
611:     f[9 * i + 3] = 0;
612:     f[9 * i + 6] = 0;
613:     f[9 * i + 7] = 0;
614:     f[9 * i + 8] = 0;
615:   }
616:   PetscCall(VecRestoreArray(F, &f));
617:   PetscFunctionReturn(PETSC_SUCCESS);
618: }

620: PetscErrorCode PostStage(TS ts, PetscReal t, PetscInt i, Vec *X)
621: {
622:   Userctx *user;

624:   PetscFunctionBegin;
625:   PetscCall(TSGetApplicationContext(ts, &user));
626:   PetscCall(SNESSolve(user->snes_alg, NULL, X[i]));
627:   PetscFunctionReturn(PETSC_SUCCESS);
628: }

630: PetscErrorCode PostEvaluate(TS ts)
631: {
632:   Userctx *user;
633:   Vec      X;

635:   PetscFunctionBegin;
636:   PetscCall(TSGetApplicationContext(ts, &user));
637:   PetscCall(TSGetSolution(ts, &X));
638:   PetscCall(SNESSolve(user->snes_alg, NULL, X));
639:   PetscFunctionReturn(PETSC_SUCCESS);
640: }

642: PetscErrorCode PreallocateJacobian(Mat J, Userctx *user)
643: {
644:   PetscInt *d_nnz;
645:   PetscInt  i, idx = 0, start = 0;
646:   PetscInt  ncols;

648:   PetscFunctionBegin;
649:   PetscCall(PetscMalloc1(user->neqs_pgrid, &d_nnz));
650:   for (i = 0; i < user->neqs_pgrid; i++) d_nnz[i] = 0;
651:   /* Generator subsystem */
652:   for (i = 0; i < ngen; i++) {
653:     d_nnz[idx] += 3;
654:     d_nnz[idx + 1] += 2;
655:     d_nnz[idx + 2] += 2;
656:     d_nnz[idx + 3] += 5;
657:     d_nnz[idx + 4] += 6;
658:     d_nnz[idx + 5] += 6;

660:     d_nnz[user->neqs_gen + 2 * gbus[i]] += 3;
661:     d_nnz[user->neqs_gen + 2 * gbus[i] + 1] += 3;

663:     d_nnz[idx + 6] += 2;
664:     d_nnz[idx + 7] += 2;
665:     d_nnz[idx + 8] += 5;

667:     idx = idx + 9;
668:   }
669:   start = user->neqs_gen;

671:   for (i = 0; i < nbus; i++) {
672:     PetscCall(MatGetRow(user->Ybus, 2 * i, &ncols, NULL, NULL));
673:     d_nnz[start + 2 * i] += ncols;
674:     d_nnz[start + 2 * i + 1] += ncols;
675:     PetscCall(MatRestoreRow(user->Ybus, 2 * i, &ncols, NULL, NULL));
676:   }
677:   PetscCall(MatSeqAIJSetPreallocation(J, 0, d_nnz));
678:   PetscCall(PetscFree(d_nnz));
679:   PetscFunctionReturn(PETSC_SUCCESS);
680: }

682: /*
683:    J = [df_dx, df_dy
684:         dg_dx, dg_dy]
685: */
686: PetscErrorCode ResidualJacobian(Vec X, Mat J, Mat B, PetscCtx ctx)
687: {
688:   Userctx           *user = (Userctx *)ctx;
689:   Vec                Xgen, Xnet;
690:   const PetscScalar *xgen, *xnet;
691:   PetscInt           i, idx = 0;
692:   PetscScalar        Vr, Vi, Vm, Vm2;
693:   PetscScalar        Eqp, Edp, delta; /* Generator variables */
694:   PetscScalar        Efd;
695:   PetscScalar        Id, Iq; /* Generator dq axis currents */
696:   PetscScalar        Vd, Vq;
697:   PetscScalar        val[10];
698:   PetscInt           row[2], col[10];
699:   PetscInt           net_start = user->neqs_gen;
700:   PetscScalar        Zdq_inv[4], det;
701:   PetscScalar        dVd_dVr, dVd_dVi, dVq_dVr, dVq_dVi, dVd_ddelta, dVq_ddelta;
702:   PetscScalar        dIGr_ddelta, dIGi_ddelta, dIGr_dId, dIGr_dIq, dIGi_dId, dIGi_dIq;
703:   PetscScalar        dSE_dEfd;
704:   PetscScalar        dVm_dVd, dVm_dVq, dVm_dVr, dVm_dVi;
705:   PetscInt           ncols;
706:   const PetscInt    *cols;
707:   const PetscScalar *yvals;
708:   PetscScalar        PD, QD, Vm0, Vm4;
709:   const PetscScalar *v0;
710:   PetscScalar        dPD_dVr, dPD_dVi, dQD_dVr, dQD_dVi;
711:   PetscScalar        dIDr_dVr, dIDr_dVi, dIDi_dVr, dIDi_dVi;

713:   PetscFunctionBegin;
714:   PetscCall(MatZeroEntries(B));
715:   PetscCall(DMCompositeGetLocalVectors(user->dmpgrid, &Xgen, &Xnet));
716:   PetscCall(DMCompositeScatter(user->dmpgrid, X, Xgen, Xnet));

718:   PetscCall(VecGetArrayRead(Xgen, &xgen));
719:   PetscCall(VecGetArrayRead(Xnet, &xnet));

721:   /* Generator subsystem */
722:   for (i = 0; i < ngen; i++) {
723:     Eqp   = xgen[idx];
724:     Edp   = xgen[idx + 1];
725:     delta = xgen[idx + 2];
726:     Id    = xgen[idx + 4];
727:     Iq    = xgen[idx + 5];
728:     Efd   = xgen[idx + 6];

730:     /*    fgen[idx]   = (-Eqp - (Xd[i] - Xdp[i])*Id + Efd)/Td0p[i]; */
731:     row[0] = idx;
732:     col[0] = idx;
733:     col[1] = idx + 4;
734:     col[2] = idx + 6;
735:     val[0] = -1 / Td0p[i];
736:     val[1] = -(Xd[i] - Xdp[i]) / Td0p[i];
737:     val[2] = 1 / Td0p[i];

739:     PetscCall(MatSetValues(J, 1, row, 3, col, val, INSERT_VALUES));

741:     /*    fgen[idx+1] = (-Edp + (Xq[i] - Xqp[i])*Iq)/Tq0p[i]; */
742:     row[0] = idx + 1;
743:     col[0] = idx + 1;
744:     col[1] = idx + 5;
745:     val[0] = -1 / Tq0p[i];
746:     val[1] = (Xq[i] - Xqp[i]) / Tq0p[i];
747:     PetscCall(MatSetValues(J, 1, row, 2, col, val, INSERT_VALUES));

749:     /*    fgen[idx+2] = w - w_s; */
750:     row[0] = idx + 2;
751:     col[0] = idx + 2;
752:     col[1] = idx + 3;
753:     val[0] = 0;
754:     val[1] = 1;
755:     PetscCall(MatSetValues(J, 1, row, 2, col, val, INSERT_VALUES));

757:     /*    fgen[idx+3] = (TM[i] - Edp*Id - Eqp*Iq - (Xqp[i] - Xdp[i])*Id*Iq - D[i]*(w - w_s))/M[i]; */
758:     row[0] = idx + 3;
759:     col[0] = idx;
760:     col[1] = idx + 1;
761:     col[2] = idx + 3;
762:     col[3] = idx + 4;
763:     col[4] = idx + 5;
764:     val[0] = -Iq / M[i];
765:     val[1] = -Id / M[i];
766:     val[2] = -D[i] / M[i];
767:     val[3] = (-Edp - (Xqp[i] - Xdp[i]) * Iq) / M[i];
768:     val[4] = (-Eqp - (Xqp[i] - Xdp[i]) * Id) / M[i];
769:     PetscCall(MatSetValues(J, 1, row, 5, col, val, INSERT_VALUES));

771:     Vr = xnet[2 * gbus[i]];     /* Real part of generator terminal voltage */
772:     Vi = xnet[2 * gbus[i] + 1]; /* Imaginary part of the generator terminal voltage */
773:     PetscCall(ri2dq(Vr, Vi, delta, &Vd, &Vq));

775:     det = Rs[i] * Rs[i] + Xdp[i] * Xqp[i];

777:     Zdq_inv[0] = Rs[i] / det;
778:     Zdq_inv[1] = Xqp[i] / det;
779:     Zdq_inv[2] = -Xdp[i] / det;
780:     Zdq_inv[3] = Rs[i] / det;

782:     dVd_dVr    = PetscSinScalar(delta);
783:     dVd_dVi    = -PetscCosScalar(delta);
784:     dVq_dVr    = PetscCosScalar(delta);
785:     dVq_dVi    = PetscSinScalar(delta);
786:     dVd_ddelta = Vr * PetscCosScalar(delta) + Vi * PetscSinScalar(delta);
787:     dVq_ddelta = -Vr * PetscSinScalar(delta) + Vi * PetscCosScalar(delta);

789:     /*    fgen[idx+4] = Zdq_inv[0]*(-Edp + Vd) + Zdq_inv[1]*(-Eqp + Vq) + Id; */
790:     row[0] = idx + 4;
791:     col[0] = idx;
792:     col[1] = idx + 1;
793:     col[2] = idx + 2;
794:     val[0] = -Zdq_inv[1];
795:     val[1] = -Zdq_inv[0];
796:     val[2] = Zdq_inv[0] * dVd_ddelta + Zdq_inv[1] * dVq_ddelta;
797:     col[3] = idx + 4;
798:     col[4] = net_start + 2 * gbus[i];
799:     col[5] = net_start + 2 * gbus[i] + 1;
800:     val[3] = 1;
801:     val[4] = Zdq_inv[0] * dVd_dVr + Zdq_inv[1] * dVq_dVr;
802:     val[5] = Zdq_inv[0] * dVd_dVi + Zdq_inv[1] * dVq_dVi;
803:     PetscCall(MatSetValues(J, 1, row, 6, col, val, INSERT_VALUES));

805:     /*  fgen[idx+5] = Zdq_inv[2]*(-Edp + Vd) + Zdq_inv[3]*(-Eqp + Vq) + Iq; */
806:     row[0] = idx + 5;
807:     col[0] = idx;
808:     col[1] = idx + 1;
809:     col[2] = idx + 2;
810:     val[0] = -Zdq_inv[3];
811:     val[1] = -Zdq_inv[2];
812:     val[2] = Zdq_inv[2] * dVd_ddelta + Zdq_inv[3] * dVq_ddelta;
813:     col[3] = idx + 5;
814:     col[4] = net_start + 2 * gbus[i];
815:     col[5] = net_start + 2 * gbus[i] + 1;
816:     val[3] = 1;
817:     val[4] = Zdq_inv[2] * dVd_dVr + Zdq_inv[3] * dVq_dVr;
818:     val[5] = Zdq_inv[2] * dVd_dVi + Zdq_inv[3] * dVq_dVi;
819:     PetscCall(MatSetValues(J, 1, row, 6, col, val, INSERT_VALUES));

821:     dIGr_ddelta = Id * PetscCosScalar(delta) - Iq * PetscSinScalar(delta);
822:     dIGi_ddelta = Id * PetscSinScalar(delta) + Iq * PetscCosScalar(delta);
823:     dIGr_dId    = PetscSinScalar(delta);
824:     dIGr_dIq    = PetscCosScalar(delta);
825:     dIGi_dId    = -PetscCosScalar(delta);
826:     dIGi_dIq    = PetscSinScalar(delta);

828:     /* fnet[2*gbus[i]]   -= IGi; */
829:     row[0] = net_start + 2 * gbus[i];
830:     col[0] = idx + 2;
831:     col[1] = idx + 4;
832:     col[2] = idx + 5;
833:     val[0] = -dIGi_ddelta;
834:     val[1] = -dIGi_dId;
835:     val[2] = -dIGi_dIq;
836:     PetscCall(MatSetValues(J, 1, row, 3, col, val, INSERT_VALUES));

838:     /* fnet[2*gbus[i]+1]   -= IGr; */
839:     row[0] = net_start + 2 * gbus[i] + 1;
840:     col[0] = idx + 2;
841:     col[1] = idx + 4;
842:     col[2] = idx + 5;
843:     val[0] = -dIGr_ddelta;
844:     val[1] = -dIGr_dId;
845:     val[2] = -dIGr_dIq;
846:     PetscCall(MatSetValues(J, 1, row, 3, col, val, INSERT_VALUES));

848:     Vm = PetscSqrtScalar(Vd * Vd + Vq * Vq);

850:     /*    fgen[idx+6] = (-KE[i]*Efd - SE + VR)/TE[i]; */
851:     /*    SE  = k1[i]*PetscExpScalar(k2[i]*Efd); */

853:     dSE_dEfd = k1[i] * k2[i] * PetscExpScalar(k2[i] * Efd);

855:     row[0] = idx + 6;
856:     col[0] = idx + 6;
857:     col[1] = idx + 8;
858:     val[0] = (-KE[i] - dSE_dEfd) / TE[i];
859:     val[1] = 1 / TE[i];
860:     PetscCall(MatSetValues(J, 1, row, 2, col, val, INSERT_VALUES));

862:     /* Exciter differential equations */

864:     /*    fgen[idx+7] = (-RF + KF[i]*Efd/TF[i])/TF[i]; */
865:     row[0] = idx + 7;
866:     col[0] = idx + 6;
867:     col[1] = idx + 7;
868:     val[0] = (KF[i] / TF[i]) / TF[i];
869:     val[1] = -1 / TF[i];
870:     PetscCall(MatSetValues(J, 1, row, 2, col, val, INSERT_VALUES));

872:     /*    fgen[idx+8] = (-VR + KA[i]*RF - KA[i]*KF[i]*Efd/TF[i] + KA[i]*(Vref[i] - Vm))/TA[i]; */
873:     /* Vm = (Vd^2 + Vq^2)^0.5; */

875:     row[0] = idx + 8;
876:     if (VRatmax[i]) {
877:       col[0] = idx + 8;
878:       val[0] = 1.0;
879:       PetscCall(MatSetValues(J, 1, row, 1, col, val, INSERT_VALUES));
880:     } else if (VRatmin[i]) {
881:       col[0] = idx + 8;
882:       val[0] = -1.0;
883:       PetscCall(MatSetValues(J, 1, row, 1, col, val, INSERT_VALUES));
884:     } else {
885:       dVm_dVd = Vd / Vm;
886:       dVm_dVq = Vq / Vm;
887:       dVm_dVr = dVm_dVd * dVd_dVr + dVm_dVq * dVq_dVr;
888:       dVm_dVi = dVm_dVd * dVd_dVi + dVm_dVq * dVq_dVi;
889:       row[0]  = idx + 8;
890:       col[0]  = idx + 6;
891:       col[1]  = idx + 7;
892:       col[2]  = idx + 8;
893:       val[0]  = -(KA[i] * KF[i] / TF[i]) / TA[i];
894:       val[1]  = KA[i] / TA[i];
895:       val[2]  = -1 / TA[i];
896:       col[3]  = net_start + 2 * gbus[i];
897:       col[4]  = net_start + 2 * gbus[i] + 1;
898:       val[3]  = -KA[i] * dVm_dVr / TA[i];
899:       val[4]  = -KA[i] * dVm_dVi / TA[i];
900:       PetscCall(MatSetValues(J, 1, row, 5, col, val, INSERT_VALUES));
901:     }
902:     idx = idx + 9;
903:   }

905:   for (i = 0; i < nbus; i++) {
906:     PetscCall(MatGetRow(user->Ybus, 2 * i, &ncols, &cols, &yvals));
907:     row[0] = net_start + 2 * i;
908:     for (PetscInt k = 0; k < ncols; k++) {
909:       col[k] = net_start + cols[k];
910:       val[k] = yvals[k];
911:     }
912:     PetscCall(MatSetValues(J, 1, row, ncols, col, val, INSERT_VALUES));
913:     PetscCall(MatRestoreRow(user->Ybus, 2 * i, &ncols, &cols, &yvals));

915:     PetscCall(MatGetRow(user->Ybus, 2 * i + 1, &ncols, &cols, &yvals));
916:     row[0] = net_start + 2 * i + 1;
917:     for (PetscInt k = 0; k < ncols; k++) {
918:       col[k] = net_start + cols[k];
919:       val[k] = yvals[k];
920:     }
921:     PetscCall(MatSetValues(J, 1, row, ncols, col, val, INSERT_VALUES));
922:     PetscCall(MatRestoreRow(user->Ybus, 2 * i + 1, &ncols, &cols, &yvals));
923:   }

925:   PetscCall(MatAssemblyBegin(J, MAT_FLUSH_ASSEMBLY));
926:   PetscCall(MatAssemblyEnd(J, MAT_FLUSH_ASSEMBLY));

928:   PetscCall(VecGetArrayRead(user->V0, &v0));
929:   for (i = 0; i < nload; i++) {
930:     Vr  = xnet[2 * lbus[i]];     /* Real part of load bus voltage */
931:     Vi  = xnet[2 * lbus[i] + 1]; /* Imaginary part of the load bus voltage */
932:     Vm  = PetscSqrtScalar(Vr * Vr + Vi * Vi);
933:     Vm2 = Vm * Vm;
934:     Vm4 = Vm2 * Vm2;
935:     Vm0 = PetscSqrtScalar(v0[2 * lbus[i]] * v0[2 * lbus[i]] + v0[2 * lbus[i] + 1] * v0[2 * lbus[i] + 1]);
936:     PD = QD = 0.0;
937:     dPD_dVr = dPD_dVi = dQD_dVr = dQD_dVi = 0.0;
938:     for (PetscInt k = 0; k < ld_nsegsp[i]; k++) {
939:       PD += ld_alphap[k] * PD0[i] * PetscPowScalar(Vm / Vm0, ld_betap[k]);
940:       dPD_dVr += ld_alphap[k] * ld_betap[k] * PD0[i] * PetscPowScalar(1 / Vm0, ld_betap[k]) * Vr * PetscPowScalar(Vm, ld_betap[k] - 2);
941:       dPD_dVi += ld_alphap[k] * ld_betap[k] * PD0[i] * PetscPowScalar(1 / Vm0, ld_betap[k]) * Vi * PetscPowScalar(Vm, ld_betap[k] - 2);
942:     }
943:     for (PetscInt k = 0; k < ld_nsegsq[i]; k++) {
944:       QD += ld_alphaq[k] * QD0[i] * PetscPowScalar(Vm / Vm0, ld_betaq[k]);
945:       dQD_dVr += ld_alphaq[k] * ld_betaq[k] * QD0[i] * PetscPowScalar(1 / Vm0, ld_betaq[k]) * Vr * PetscPowScalar(Vm, ld_betaq[k] - 2);
946:       dQD_dVi += ld_alphaq[k] * ld_betaq[k] * QD0[i] * PetscPowScalar(1 / Vm0, ld_betaq[k]) * Vi * PetscPowScalar(Vm, ld_betaq[k] - 2);
947:     }

949:     /*    IDr = (PD*Vr + QD*Vi)/Vm2; */
950:     /*    IDi = (-QD*Vr + PD*Vi)/Vm2; */

952:     dIDr_dVr = (dPD_dVr * Vr + dQD_dVr * Vi + PD) / Vm2 - ((PD * Vr + QD * Vi) * 2 * Vr) / Vm4;
953:     dIDr_dVi = (dPD_dVi * Vr + dQD_dVi * Vi + QD) / Vm2 - ((PD * Vr + QD * Vi) * 2 * Vi) / Vm4;

955:     dIDi_dVr = (-dQD_dVr * Vr + dPD_dVr * Vi - QD) / Vm2 - ((-QD * Vr + PD * Vi) * 2 * Vr) / Vm4;
956:     dIDi_dVi = (-dQD_dVi * Vr + dPD_dVi * Vi + PD) / Vm2 - ((-QD * Vr + PD * Vi) * 2 * Vi) / Vm4;

958:     /*    fnet[2*lbus[i]]   += IDi; */
959:     row[0] = net_start + 2 * lbus[i];
960:     col[0] = net_start + 2 * lbus[i];
961:     col[1] = net_start + 2 * lbus[i] + 1;
962:     val[0] = dIDi_dVr;
963:     val[1] = dIDi_dVi;
964:     PetscCall(MatSetValues(J, 1, row, 2, col, val, ADD_VALUES));
965:     /*    fnet[2*lbus[i]+1] += IDr; */
966:     row[0] = net_start + 2 * lbus[i] + 1;
967:     col[0] = net_start + 2 * lbus[i];
968:     col[1] = net_start + 2 * lbus[i] + 1;
969:     val[0] = dIDr_dVr;
970:     val[1] = dIDr_dVi;
971:     PetscCall(MatSetValues(J, 1, row, 2, col, val, ADD_VALUES));
972:   }
973:   PetscCall(VecRestoreArrayRead(user->V0, &v0));

975:   PetscCall(VecRestoreArrayRead(Xgen, &xgen));
976:   PetscCall(VecRestoreArrayRead(Xnet, &xnet));

978:   PetscCall(DMCompositeRestoreLocalVectors(user->dmpgrid, &Xgen, &Xnet));

980:   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
981:   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
982:   PetscFunctionReturn(PETSC_SUCCESS);
983: }

985: /*
986:    J = [I, 0
987:         dg_dx, dg_dy]
988: */
989: PetscErrorCode AlgJacobian(SNES snes, Vec X, Mat A, Mat B, PetscCtx ctx)
990: {
991:   Userctx *user = (Userctx *)ctx;

993:   PetscFunctionBegin;
994:   PetscCall(ResidualJacobian(X, A, B, ctx));
995:   PetscCall(MatSetOption(A, MAT_KEEP_NONZERO_PATTERN, PETSC_TRUE));
996:   PetscCall(MatZeroRowsIS(A, user->is_diff, 1.0, NULL, NULL));
997:   PetscFunctionReturn(PETSC_SUCCESS);
998: }

1000: /*
1001:    J = [-df_dx, -df_dy
1002:         dg_dx, dg_dy]
1003: */

1005: PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec X, Mat A, Mat B, PetscCtx ctx)
1006: {
1007:   Userctx *user = (Userctx *)ctx;

1009:   PetscFunctionBegin;
1010:   user->t = t;

1012:   PetscCall(ResidualJacobian(X, A, B, user));
1013:   PetscFunctionReturn(PETSC_SUCCESS);
1014: }

1016: /*
1017:    J = [df_dx-aI, df_dy
1018:         dg_dx, dg_dy]
1019: */

1021: PetscErrorCode IJacobian(TS ts, PetscReal t, Vec X, Vec Xdot, PetscReal a, Mat A, Mat B, Userctx *user)
1022: {
1023:   PetscScalar atmp = (PetscScalar)a;
1024:   PetscInt    i, row;

1026:   PetscFunctionBegin;
1027:   user->t = t;

1029:   PetscCall(RHSJacobian(ts, t, X, A, B, user));
1030:   PetscCall(MatScale(B, -1.0));
1031:   for (i = 0; i < ngen; i++) {
1032:     row = 9 * i;
1033:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1034:     row = 9 * i + 1;
1035:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1036:     row = 9 * i + 2;
1037:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1038:     row = 9 * i + 3;
1039:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1040:     row = 9 * i + 6;
1041:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1042:     row = 9 * i + 7;
1043:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1044:     row = 9 * i + 8;
1045:     PetscCall(MatSetValues(A, 1, &row, 1, &row, &atmp, ADD_VALUES));
1046:   }
1047:   PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1048:   PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1049:   PetscFunctionReturn(PETSC_SUCCESS);
1050: }

1052: int main(int argc, char **argv)
1053: {
1054:   TS                 ts;
1055:   SNES               snes_alg;
1056:   PetscMPIInt        size;
1057:   Userctx            user;
1058:   PetscViewer        Xview, Ybusview, viewer;
1059:   Vec                X, F_alg;
1060:   Mat                J, A;
1061:   PetscInt           i, idx, *idx2;
1062:   Vec                Xdot;
1063:   PetscScalar       *x, *mat, *amat;
1064:   const PetscScalar *rmat;
1065:   Vec                vatol;
1066:   PetscInt          *direction;
1067:   PetscBool         *terminate;
1068:   const PetscInt    *idx3;
1069:   PetscScalar       *vatoli;

1071:   PetscFunctionBeginUser;
1072:   PetscCall(PetscInitialize(&argc, &argv, "petscoptions", help));
1073:   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
1074:   PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "Only for sequential runs");

1076:   user.neqs_gen   = 9 * ngen; /* # eqs. for generator subsystem */
1077:   user.neqs_net   = 2 * nbus; /* # eqs. for network subsystem   */
1078:   user.neqs_pgrid = user.neqs_gen + user.neqs_net;

1080:   /* Create indices for differential and algebraic equations */

1082:   PetscCall(PetscMalloc1(7 * ngen, &idx2));
1083:   for (i = 0; i < ngen; i++) {
1084:     idx2[7 * i]     = 9 * i;
1085:     idx2[7 * i + 1] = 9 * i + 1;
1086:     idx2[7 * i + 2] = 9 * i + 2;
1087:     idx2[7 * i + 3] = 9 * i + 3;
1088:     idx2[7 * i + 4] = 9 * i + 6;
1089:     idx2[7 * i + 5] = 9 * i + 7;
1090:     idx2[7 * i + 6] = 9 * i + 8;
1091:   }
1092:   PetscCall(ISCreateGeneral(PETSC_COMM_WORLD, 7 * ngen, idx2, PETSC_COPY_VALUES, &user.is_diff));
1093:   PetscCall(ISComplement(user.is_diff, 0, user.neqs_pgrid, &user.is_alg));
1094:   PetscCall(PetscFree(idx2));

1096:   /* Read initial voltage vector and Ybus */
1097:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "X.bin", FILE_MODE_READ, &Xview));
1098:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, "Ybus.bin", FILE_MODE_READ, &Ybusview));

1100:   PetscCall(VecCreate(PETSC_COMM_WORLD, &user.V0));
1101:   PetscCall(VecSetSizes(user.V0, PETSC_DECIDE, user.neqs_net));
1102:   PetscCall(VecLoad(user.V0, Xview));

1104:   PetscCall(MatCreate(PETSC_COMM_WORLD, &user.Ybus));
1105:   PetscCall(MatSetSizes(user.Ybus, PETSC_DECIDE, PETSC_DECIDE, user.neqs_net, user.neqs_net));
1106:   PetscCall(MatSetType(user.Ybus, MATBAIJ));
1107:   /*  PetscCall(MatSetBlockSize(user.Ybus,2)); */
1108:   PetscCall(MatLoad(user.Ybus, Ybusview));

1110:   /* Set run time options */
1111:   PetscOptionsBegin(PETSC_COMM_WORLD, NULL, "Transient stability fault options", "");
1112:   {
1113:     user.tfaulton     = 1.0;
1114:     user.tfaultoff    = 1.2;
1115:     user.Rfault       = 0.0001;
1116:     user.setisdiff    = PETSC_FALSE;
1117:     user.semiexplicit = PETSC_FALSE;
1118:     user.faultbus     = 8;
1119:     PetscCall(PetscOptionsReal("-tfaulton", "", "", user.tfaulton, &user.tfaulton, NULL));
1120:     PetscCall(PetscOptionsReal("-tfaultoff", "", "", user.tfaultoff, &user.tfaultoff, NULL));
1121:     PetscCall(PetscOptionsInt("-faultbus", "", "", user.faultbus, &user.faultbus, NULL));
1122:     user.t0   = 0.0;
1123:     user.tmax = 5.0;
1124:     PetscCall(PetscOptionsReal("-t0", "", "", user.t0, &user.t0, NULL));
1125:     PetscCall(PetscOptionsReal("-tmax", "", "", user.tmax, &user.tmax, NULL));
1126:     PetscCall(PetscOptionsBool("-setisdiff", "", "", user.setisdiff, &user.setisdiff, NULL));
1127:     PetscCall(PetscOptionsBool("-dae_semiexplicit", "", "", user.semiexplicit, &user.semiexplicit, NULL));
1128:   }
1129:   PetscOptionsEnd();

1131:   PetscCall(PetscViewerDestroy(&Xview));
1132:   PetscCall(PetscViewerDestroy(&Ybusview));

1134:   /* Create DMs for generator and network subsystems */
1135:   PetscCall(DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, user.neqs_gen, 1, 1, NULL, &user.dmgen));
1136:   PetscCall(DMSetOptionsPrefix(user.dmgen, "dmgen_"));
1137:   PetscCall(DMSetFromOptions(user.dmgen));
1138:   PetscCall(DMSetUp(user.dmgen));
1139:   PetscCall(DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, user.neqs_net, 1, 1, NULL, &user.dmnet));
1140:   PetscCall(DMSetOptionsPrefix(user.dmnet, "dmnet_"));
1141:   PetscCall(DMSetFromOptions(user.dmnet));
1142:   PetscCall(DMSetUp(user.dmnet));
1143:   /* Create a composite DM packer and add the two DMs */
1144:   PetscCall(DMCompositeCreate(PETSC_COMM_WORLD, &user.dmpgrid));
1145:   PetscCall(DMSetOptionsPrefix(user.dmpgrid, "pgrid_"));
1146:   PetscCall(DMCompositeAddDM(user.dmpgrid, user.dmgen));
1147:   PetscCall(DMCompositeAddDM(user.dmpgrid, user.dmnet));

1149:   PetscCall(DMCreateGlobalVector(user.dmpgrid, &X));

1151:   PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
1152:   PetscCall(MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, user.neqs_pgrid, user.neqs_pgrid));
1153:   PetscCall(MatSetFromOptions(J));
1154:   PetscCall(PreallocateJacobian(J, &user));

1156:   /* Create matrix to save solutions at each time step */
1157:   user.stepnum = 0;

1159:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, user.neqs_pgrid + 1, 1002, NULL, &user.Sol));
1160:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1161:      Create timestepping solver context
1162:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1163:   PetscCall(TSCreate(PETSC_COMM_WORLD, &ts));
1164:   PetscCall(TSSetProblemType(ts, TS_NONLINEAR));
1165:   if (user.semiexplicit) {
1166:     PetscCall(TSSetType(ts, TSRK));
1167:     PetscCall(TSSetRHSFunction(ts, NULL, RHSFunction, &user));
1168:     PetscCall(TSSetRHSJacobian(ts, J, J, RHSJacobian, &user));
1169:   } else {
1170:     PetscCall(TSSetType(ts, TSCN));
1171:     PetscCall(TSSetEquationType(ts, TS_EQ_DAE_IMPLICIT_INDEX1));
1172:     PetscCall(TSSetIFunction(ts, NULL, (TSIFunctionFn *)IFunction, &user));
1173:     PetscCall(TSSetIJacobian(ts, J, J, (TSIJacobianFn *)IJacobian, &user));
1174:   }
1175:   PetscCall(TSSetApplicationContext(ts, &user));

1177:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1178:      Set initial conditions
1179:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
1180:   PetscCall(SetInitialGuess(X, &user));
1181:   /* Just to set up the Jacobian structure */

1183:   PetscCall(VecDuplicate(X, &Xdot));
1184:   PetscCall(IJacobian(ts, 0.0, X, Xdot, 0.0, J, J, &user));
1185:   PetscCall(VecDestroy(&Xdot));

1187:   /* Save initial solution */

1189:   idx = user.stepnum * (user.neqs_pgrid + 1);
1190:   PetscCall(MatDenseGetArray(user.Sol, &mat));
1191:   PetscCall(VecGetArray(X, &x));

1193:   mat[idx] = 0.0;

1195:   PetscCall(PetscArraycpy(mat + idx + 1, x, user.neqs_pgrid));
1196:   PetscCall(MatDenseRestoreArray(user.Sol, &mat));
1197:   PetscCall(VecRestoreArray(X, &x));
1198:   user.stepnum++;

1200:   PetscCall(TSSetMaxTime(ts, user.tmax));
1201:   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP));
1202:   PetscCall(TSSetTimeStep(ts, 0.01));
1203:   PetscCall(TSSetFromOptions(ts));
1204:   PetscCall(TSSetPostStep(ts, SaveSolution));
1205:   PetscCall(TSSetSolution(ts, X));

1207:   PetscCall(PetscMalloc1(2 * ngen + 2, &direction));
1208:   PetscCall(PetscMalloc1(2 * ngen + 2, &terminate));
1209:   direction[0] = direction[1] = 1;
1210:   terminate[0] = terminate[1] = PETSC_FALSE;
1211:   for (i = 0; i < ngen; i++) {
1212:     direction[2 + 2 * i]     = -1;
1213:     direction[2 + 2 * i + 1] = 1;
1214:     terminate[2 + 2 * i] = terminate[2 + 2 * i + 1] = PETSC_FALSE;
1215:   }

1217:   PetscCall(TSSetEventHandler(ts, 2 * ngen + 2, direction, terminate, EventFunction, PostEventFunction, (void *)&user));

1219:   if (user.semiexplicit) {
1220:     /* Use a semi-explicit approach with the time-stepping done by an explicit method and the
1221:        algrebraic part solved via PostStage and PostEvaluate callbacks
1222:     */
1223:     PetscCall(TSSetType(ts, TSRK));
1224:     PetscCall(TSSetPostStage(ts, PostStage));
1225:     PetscCall(TSSetPostEvaluate(ts, PostEvaluate));
1226:   }

1228:   if (user.setisdiff) {
1229:     /* Create vector of absolute tolerances and set the algebraic part to infinity */
1230:     PetscCall(VecDuplicate(X, &vatol));
1231:     PetscCall(VecSet(vatol, 100000.0));
1232:     PetscCall(VecGetArray(vatol, &vatoli));
1233:     PetscCall(ISGetIndices(user.is_diff, &idx3));
1234:     for (PetscInt k = 0; k < 7 * ngen; k++) vatoli[idx3[k]] = 1e-2;
1235:     PetscCall(VecRestoreArray(vatol, &vatoli));
1236:   }

1238:   /* Create the nonlinear solver for solving the algebraic system */
1239:   /* Note that although the algebraic system needs to be solved only for
1240:      Idq and V, we reuse the entire system including xgen. The xgen
1241:      variables are held constant by setting their residuals to 0 and
1242:      putting a 1 on the Jacobian diagonal for xgen rows
1243:   */

1245:   PetscCall(VecDuplicate(X, &F_alg));
1246:   PetscCall(SNESCreate(PETSC_COMM_WORLD, &snes_alg));
1247:   PetscCall(SNESSetFunction(snes_alg, F_alg, AlgFunction, &user));
1248:   PetscCall(SNESSetJacobian(snes_alg, J, J, AlgJacobian, &user));
1249:   PetscCall(SNESSetFromOptions(snes_alg));

1251:   user.snes_alg = snes_alg;

1253:   /* Solve */
1254:   PetscCall(TSSolve(ts, X));

1256:   PetscCall(MatAssemblyBegin(user.Sol, MAT_FINAL_ASSEMBLY));
1257:   PetscCall(MatAssemblyEnd(user.Sol, MAT_FINAL_ASSEMBLY));

1259:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, user.neqs_pgrid + 1, user.stepnum, NULL, &A));
1260:   PetscCall(MatDenseGetArrayRead(user.Sol, &rmat));
1261:   PetscCall(MatDenseGetArray(A, &amat));
1262:   PetscCall(PetscArraycpy(amat, rmat, user.stepnum * (user.neqs_pgrid + 1)));
1263:   PetscCall(MatDenseRestoreArray(A, &amat));
1264:   PetscCall(MatDenseRestoreArrayRead(user.Sol, &rmat));
1265:   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_SELF, "out.bin", FILE_MODE_WRITE, &viewer));
1266:   PetscCall(MatView(A, viewer));
1267:   PetscCall(PetscViewerDestroy(&viewer));
1268:   PetscCall(MatDestroy(&A));

1270:   PetscCall(PetscFree(direction));
1271:   PetscCall(PetscFree(terminate));
1272:   PetscCall(SNESDestroy(&snes_alg));
1273:   PetscCall(VecDestroy(&F_alg));
1274:   PetscCall(MatDestroy(&J));
1275:   PetscCall(MatDestroy(&user.Ybus));
1276:   PetscCall(MatDestroy(&user.Sol));
1277:   PetscCall(VecDestroy(&X));
1278:   PetscCall(VecDestroy(&user.V0));
1279:   PetscCall(DMDestroy(&user.dmgen));
1280:   PetscCall(DMDestroy(&user.dmnet));
1281:   PetscCall(DMDestroy(&user.dmpgrid));
1282:   PetscCall(ISDestroy(&user.is_diff));
1283:   PetscCall(ISDestroy(&user.is_alg));
1284:   PetscCall(TSDestroy(&ts));
1285:   if (user.setisdiff) PetscCall(VecDestroy(&vatol));
1286:   PetscCall(PetscFinalize());
1287:   return 0;
1288: }

1290: /*TEST

1292:    build:
1293:       requires: double !complex !defined(PETSC_USE_64BIT_INDICES)

1295:    test:
1296:       suffix: implicit
1297:       args: -ts_monitor -snes_monitor
1298:       localrunfiles: petscoptions X.bin Ybus.bin

1300:    test:
1301:       suffix: semiexplicit
1302:       args: -ts_monitor -dae_semiexplicit -snes_error_if_not_converged -ts_rk_type 2a
1303:       localrunfiles: petscoptions X.bin Ybus.bin

1305:    test:
1306:       suffix: steprestart
1307:       # needs ARKIMEX methods with all implicit stages since the mass matrix is not the identity
1308:       args: -ts_monitor -snes_monitor -ts_type arkimex -ts_arkimex_type prssp2
1309:       localrunfiles: petscoptions X.bin Ybus.bin

1311: TEST*/