Actual source code: virs.c

  1: #include <../src/snes/impls/vi/rs/virsimpl.h>
  2: #include <petsc/private/dmimpl.h>
  3: #include <petsc/private/vecimpl.h>

  5: /*@
  6:   SNESVIGetInactiveSet - Gets the global indices for the inactive set variables (these correspond to the degrees of freedom the linear
  7:   system is solved on)

  9:   Input Parameter:
 10: . snes - the `SNES` context

 12:   Output Parameter:
 13: . inact - inactive set index set

 15:   Level: advanced

 17:   Note:
 18:   See `SNESVINEWTONRSLS` for a concise description of the active and inactive sets

 20: .seealso: [](ch_snes), `SNES`, `SNESVINEWTONRSLS`
 21: @*/
 22: PetscErrorCode SNESVIGetInactiveSet(SNES snes, IS *inact)
 23: {
 24:   SNES_VINEWTONRSLS *vi = (SNES_VINEWTONRSLS *)snes->data;

 26:   PetscFunctionBegin;
 27:   *inact = vi->IS_inact;
 28:   PetscFunctionReturn(PETSC_SUCCESS);
 29: }

 31: /*
 32:     Provides a wrapper to a DM to allow it to be used to generated the interpolation/restriction from the DM for the smaller matrices and vectors
 33:   defined by the reduced space method.

 35:     Simple calls the regular DM interpolation and restricts it to operation on the variables not associated with active constraints.
 36: */
 37: typedef struct {
 38:   PetscInt n; /* size of vectors in the reduced DM space */
 39:   IS       inactive;

 41:   PetscErrorCode (*createinterpolation)(DM, DM, Mat *, Vec *); /* DM's original routines */
 42:   PetscErrorCode (*coarsen)(DM, MPI_Comm, DM *);
 43:   PetscErrorCode (*createglobalvector)(DM, Vec *);
 44:   PetscErrorCode (*createinjection)(DM, DM, Mat *);
 45:   PetscErrorCode (*hascreateinjection)(DM, PetscBool *);

 47:   DM dm; /* when destroying this object we need to reset the above function into the base DM */
 48: } DM_SNESVI;

 50: /*
 51:      DMCreateGlobalVector_SNESVI - Creates global vector of the size of the reduced space
 52: */
 53: static PetscErrorCode DMCreateGlobalVector_SNESVI(DM dm, Vec *vec)
 54: {
 55:   PetscContainer isnes;
 56:   DM_SNESVI     *dmsnesvi;

 58:   PetscFunctionBegin;
 59:   PetscCall(PetscObjectQuery((PetscObject)dm, "VI", (PetscObject *)&isnes));
 60:   PetscCheck(isnes, PetscObjectComm((PetscObject)dm), PETSC_ERR_PLIB, "Composed SNES is missing");
 61:   PetscCall(PetscContainerGetPointer(isnes, &dmsnesvi));
 62:   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)dm), dmsnesvi->n, PETSC_DETERMINE, vec));
 63:   PetscCall(VecSetDM(*vec, dm));
 64:   PetscFunctionReturn(PETSC_SUCCESS);
 65: }

 67: /*
 68:      DMCreateInterpolation_SNESVI - Modifieds the interpolation obtained from the DM by removing all rows and columns associated with active constraints.
 69: */
 70: static PetscErrorCode DMCreateInterpolation_SNESVI(DM dm1, DM dm2, Mat *mat, Vec *vec)
 71: {
 72:   PetscContainer isnes;
 73:   DM_SNESVI     *dmsnesvi1, *dmsnesvi2;
 74:   Mat            interp;

 76:   PetscFunctionBegin;
 77:   PetscCall(PetscObjectQuery((PetscObject)dm1, "VI", (PetscObject *)&isnes));
 78:   PetscCheck(isnes, PetscObjectComm((PetscObject)dm1), PETSC_ERR_PLIB, "Composed VI data structure is missing");
 79:   PetscCall(PetscContainerGetPointer(isnes, &dmsnesvi1));
 80:   PetscCall(PetscObjectQuery((PetscObject)dm2, "VI", (PetscObject *)&isnes));
 81:   PetscCheck(isnes, PetscObjectComm((PetscObject)dm2), PETSC_ERR_PLIB, "Composed VI data structure is missing");
 82:   PetscCall(PetscContainerGetPointer(isnes, &dmsnesvi2));

 84:   PetscCall((*dmsnesvi1->createinterpolation)(dm1, dm2, &interp, NULL));
 85:   PetscCall(MatCreateSubMatrix(interp, dmsnesvi2->inactive, dmsnesvi1->inactive, MAT_INITIAL_MATRIX, mat));
 86:   PetscCall(MatDestroy(&interp));
 87:   *vec = NULL;
 88:   PetscFunctionReturn(PETSC_SUCCESS);
 89: }

 91: /*
 92:      DMCoarsen_SNESVI - Computes the regular coarsened DM then computes additional information about its inactive set
 93: */
 94: static PetscErrorCode DMCoarsen_SNESVI(DM dm1, MPI_Comm comm, DM *dm2)
 95: {
 96:   PetscContainer  isnes;
 97:   DM_SNESVI      *dmsnesvi1;
 98:   Vec             finemarked, coarsemarked;
 99:   IS              inactive;
100:   Mat             inject;
101:   const PetscInt *index;
102:   PetscInt        n, k, cnt = 0, rstart, *coarseindex;
103:   PetscScalar    *marked;

105:   PetscFunctionBegin;
106:   PetscCall(PetscObjectQuery((PetscObject)dm1, "VI", (PetscObject *)&isnes));
107:   PetscCheck(isnes, PetscObjectComm((PetscObject)dm1), PETSC_ERR_PLIB, "Composed VI data structure is missing");
108:   PetscCall(PetscContainerGetPointer(isnes, &dmsnesvi1));

110:   /* get the original coarsen */
111:   PetscCall((*dmsnesvi1->coarsen)(dm1, comm, dm2));

113:   /* not sure why this extra reference is needed, but without the dm2 disappears too early */
114:   /* Updating the KSPCreateVecs() to avoid using DMGetGlobalVector() when matrix is available removes the need for this reference? */
115:   /*  PetscCall(PetscObjectReference((PetscObject)*dm2));*/

117:   /* need to set back global vectors in order to use the original injection */
118:   PetscCall(DMClearGlobalVectors(dm1));

120:   dm1->ops->createglobalvector = dmsnesvi1->createglobalvector;

122:   PetscCall(DMCreateGlobalVector(dm1, &finemarked));
123:   PetscCall(DMCreateGlobalVector(*dm2, &coarsemarked));

125:   /*
126:      fill finemarked with locations of inactive points
127:   */
128:   PetscCall(ISGetIndices(dmsnesvi1->inactive, &index));
129:   PetscCall(ISGetLocalSize(dmsnesvi1->inactive, &n));
130:   PetscCall(VecSet(finemarked, 0.0));
131:   for (k = 0; k < n; k++) PetscCall(VecSetValue(finemarked, index[k], 1.0, INSERT_VALUES));
132:   PetscCall(VecAssemblyBegin(finemarked));
133:   PetscCall(VecAssemblyEnd(finemarked));

135:   PetscCall(DMCreateInjection(*dm2, dm1, &inject));
136:   PetscCall(MatRestrict(inject, finemarked, coarsemarked));
137:   PetscCall(MatDestroy(&inject));

139:   /*
140:      create index set list of coarse inactive points from coarsemarked
141:   */
142:   PetscCall(VecGetLocalSize(coarsemarked, &n));
143:   PetscCall(VecGetOwnershipRange(coarsemarked, &rstart, NULL));
144:   PetscCall(VecGetArray(coarsemarked, &marked));
145:   for (k = 0; k < n; k++) {
146:     if (marked[k] != 0.0) cnt++;
147:   }
148:   PetscCall(PetscMalloc1(cnt, &coarseindex));
149:   cnt = 0;
150:   for (k = 0; k < n; k++) {
151:     if (marked[k] != 0.0) coarseindex[cnt++] = k + rstart;
152:   }
153:   PetscCall(VecRestoreArray(coarsemarked, &marked));
154:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)coarsemarked), cnt, coarseindex, PETSC_OWN_POINTER, &inactive));

156:   PetscCall(DMClearGlobalVectors(dm1));

158:   dm1->ops->createglobalvector = DMCreateGlobalVector_SNESVI;

160:   PetscCall(DMSetVI(*dm2, inactive));

162:   PetscCall(VecDestroy(&finemarked));
163:   PetscCall(VecDestroy(&coarsemarked));
164:   PetscCall(ISDestroy(&inactive));
165:   PetscFunctionReturn(PETSC_SUCCESS);
166: }

168: static PetscErrorCode DMDestroy_SNESVI(PetscCtxRt ctx)
169: {
170:   DM_SNESVI *dmsnesvi = *(DM_SNESVI **)ctx;

172:   PetscFunctionBegin;
173:   /* reset the base methods in the DM object that were changed when the DM_SNESVI was reset */
174:   dmsnesvi->dm->ops->createinterpolation = dmsnesvi->createinterpolation;
175:   dmsnesvi->dm->ops->coarsen             = dmsnesvi->coarsen;
176:   dmsnesvi->dm->ops->createglobalvector  = dmsnesvi->createglobalvector;
177:   dmsnesvi->dm->ops->createinjection     = dmsnesvi->createinjection;
178:   dmsnesvi->dm->ops->hascreateinjection  = dmsnesvi->hascreateinjection;
179:   /* need to clear out this vectors because some of them may not have a reference to the DM
180:     but they are counted as having references to the DM in DMDestroy() */
181:   PetscCall(DMClearGlobalVectors(dmsnesvi->dm));

183:   PetscCall(ISDestroy(&dmsnesvi->inactive));
184:   PetscCall(PetscFree(dmsnesvi));
185:   PetscFunctionReturn(PETSC_SUCCESS);
186: }

188: /*@
189:   DMSetVI - Marks a `DM` as associated with a VI problem. This causes the interpolation/restriction operators to
190:   be restricted to only those variables NOT associated with active constraints.

192:   Logically Collective

194:   Input Parameters:
195: + dm       - the `DM` object
196: - inactive - an `IS` indicating which points are currently not active

198:   Level: intermediate

200: .seealso: [](ch_snes), `SNES`, `SNESVINEWTONRSLS`, `SNESVIGetInactiveSet()`
201: @*/
202: PetscErrorCode DMSetVI(DM dm, IS inactive)
203: {
204:   PetscContainer isnes;
205:   DM_SNESVI     *dmsnesvi;

207:   PetscFunctionBegin;
208:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);

210:   PetscCall(PetscObjectReference((PetscObject)inactive));

212:   PetscCall(PetscObjectQuery((PetscObject)dm, "VI", (PetscObject *)&isnes));
213:   if (!isnes) {
214:     PetscCall(PetscNew(&dmsnesvi));
215:     PetscCall(PetscObjectContainerCompose((PetscObject)dm, "VI", dmsnesvi, DMDestroy_SNESVI));

217:     dmsnesvi->createinterpolation = dm->ops->createinterpolation;
218:     dm->ops->createinterpolation  = DMCreateInterpolation_SNESVI;
219:     dmsnesvi->coarsen             = dm->ops->coarsen;
220:     dm->ops->coarsen              = DMCoarsen_SNESVI;
221:     dmsnesvi->createglobalvector  = dm->ops->createglobalvector;
222:     dm->ops->createglobalvector   = DMCreateGlobalVector_SNESVI;
223:     dmsnesvi->createinjection     = dm->ops->createinjection;
224:     dm->ops->createinjection      = NULL;
225:     dmsnesvi->hascreateinjection  = dm->ops->hascreateinjection;
226:     dm->ops->hascreateinjection   = NULL;
227:   } else {
228:     PetscCall(PetscContainerGetPointer(isnes, &dmsnesvi));
229:     PetscCall(ISDestroy(&dmsnesvi->inactive));
230:   }
231:   PetscCall(DMClearGlobalVectors(dm));
232:   PetscCall(ISGetLocalSize(inactive, &dmsnesvi->n));

234:   dmsnesvi->inactive = inactive;
235:   dmsnesvi->dm       = dm;
236:   PetscFunctionReturn(PETSC_SUCCESS);
237: }

239: /*@
240:   DMDestroyVI - Frees the `DM_SNESVI` object contained in the `DM` and resets any function pointers the reduced-space `SNESVI` code composed onto it

242:   Not Collective

244:   Input Parameter:
245: . dm - the `DM` from which the VI context should be removed (may be `NULL`)

247:   Level: developer

249: .seealso: `DM`, `SNESVINEWTONRSLS`, `SNESVISetVariableBounds()`, `PetscObjectCompose()`
250: @*/
251: PetscErrorCode DMDestroyVI(DM dm)
252: {
253:   PetscFunctionBegin;
254:   if (!dm) PetscFunctionReturn(PETSC_SUCCESS);
255:   PetscCall(PetscObjectCompose((PetscObject)dm, "VI", (PetscObject)NULL));
256:   PetscFunctionReturn(PETSC_SUCCESS);
257: }

259: /* Create active and inactive set vectors. The local size of this vector is set and PETSc computes the global size */
260: static PetscErrorCode SNESCreateSubVectors_VINEWTONRSLS(SNES snes, PetscInt n, Vec *newv)
261: {
262:   Vec v;

264:   PetscFunctionBegin;
265:   PetscCall(VecCreate(PetscObjectComm((PetscObject)snes), &v));
266:   PetscCall(VecSetSizes(v, n, PETSC_DECIDE));
267:   PetscCall(VecSetType(v, VECSTANDARD));
268:   *newv = v;
269:   PetscFunctionReturn(PETSC_SUCCESS);
270: }

272: /* Resets the snes PC and KSP when the active set sizes change */
273: static PetscErrorCode SNESVIResetPCandKSP(SNES snes, Mat Amat, Mat Pmat)
274: {
275:   KSP snesksp;

277:   PetscFunctionBegin;
278:   PetscCall(SNESGetKSP(snes, &snesksp));
279:   PetscCall(KSPReset(snesksp));
280:   PetscCall(KSPResetFromOptions(snesksp));

282:   /*
283:   KSP                    kspnew;
284:   PC                     pcnew;
285:   MatSolverType          stype;

287:   PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes),&kspnew));
288:   kspnew->pc_side = snesksp->pc_side;
289:   kspnew->rtol    = snesksp->rtol;
290:   kspnew->abstol    = snesksp->abstol;
291:   kspnew->max_it  = snesksp->max_it;
292:   PetscCall(KSPSetType(kspnew,((PetscObject)snesksp)->type_name));
293:   PetscCall(KSPGetPC(kspnew,&pcnew));
294:   PetscCall(PCSetType(kspnew->pc,((PetscObject)snesksp->pc)->type_name));
295:   PetscCall(PCSetOperators(kspnew->pc,Amat,Pmat));
296:   PetscCall(PCFactorGetMatSolverType(snesksp->pc,&stype));
297:   PetscCall(PCFactorSetMatSolverType(kspnew->pc,stype));
298:   PetscCall(KSPDestroy(&snesksp));
299:   snes->ksp = kspnew;
300:    PetscCall(KSPSetFromOptions(kspnew));*/
301:   PetscFunctionReturn(PETSC_SUCCESS);
302: }

304: /* Variational Inequality solver using reduce space method. No semismooth algorithm is
305:    implemented in this algorithm. It basically identifies the active constraints and does
306:    a linear solve on the other variables (those not associated with the active constraints). */
307: static PetscErrorCode SNESSolve_VINEWTONRSLS(SNES snes)
308: {
309:   SNES_VINEWTONRSLS   *vi = (SNES_VINEWTONRSLS *)snes->data;
310:   PetscInt             maxits, i, lits;
311:   SNESLineSearchReason lsreason;
312:   PetscReal            fnorm, gnorm, xnorm = 0, ynorm;
313:   Vec                  Y, X, F;
314:   KSPConvergedReason   kspreason;
315:   KSP                  ksp;
316:   PC                   pc;

318:   PetscFunctionBegin;
319:   /* Multigrid must use Galerkin for coarse grids with active set/reduced space methods; cannot rediscretize on coarser grids*/
320:   PetscCall(SNESGetKSP(snes, &ksp));
321:   PetscCall(KSPGetPC(ksp, &pc));
322:   PetscCall(PCMGSetGalerkin(pc, PC_MG_GALERKIN_BOTH));

324:   snes->numFailures            = 0;
325:   snes->numLinearSolveFailures = 0;
326:   snes->reason                 = SNES_CONVERGED_ITERATING;

328:   maxits = snes->max_its;  /* maximum number of iterations */
329:   X      = snes->vec_sol;  /* solution vector */
330:   F      = snes->vec_func; /* residual vector */
331:   Y      = snes->work[0];  /* work vectors */

333:   PetscCall(SNESLineSearchSetVIFunctions(snes->linesearch, SNESVIProjectOntoBounds, SNESVIComputeInactiveSetFnorm, SNESVIComputeInactiveSetFtY));
334:   PetscCall(SNESLineSearchSetVecs(snes->linesearch, X, NULL, NULL, NULL, NULL));
335:   PetscCall(SNESLineSearchSetUp(snes->linesearch));

337:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
338:   snes->iter = 0;
339:   snes->norm = 0.0;
340:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));

342:   PetscCall(SNESVIProjectOntoBounds(snes, X));
343:   PetscCall(SNESComputeFunction(snes, X, F));
344:   PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, &fnorm));
345:   PetscCall(VecNorm(X, NORM_2, &xnorm)); /* xnorm <- ||x||  */
346:   SNESCheckFunctionDomainError(snes, fnorm);
347:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
348:   snes->norm = fnorm;
349:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
350:   PetscCall(SNESLogConvergenceHistory(snes, fnorm, 0));

352:   /* test convergence */
353:   PetscCall(SNESConverged(snes, 0, 0.0, 0.0, fnorm));
354:   PetscCall(SNESMonitor(snes, 0, fnorm));
355:   if (snes->reason) PetscFunctionReturn(PETSC_SUCCESS);

357:   for (i = 0; i < maxits; i++) {
358:     IS         IS_act;    /* _act -> active set _inact -> inactive set */
359:     IS         IS_redact; /* redundant active set */
360:     VecScatter scat_act, scat_inact;
361:     PetscInt   nis_act, nis_inact;
362:     Vec        Y_act, Y_inact, F_inact;
363:     Mat        jac_inact_inact, prejac_inact_inact;
364:     PetscBool  isequal;

366:     /* Call general purpose update function */
367:     PetscTryTypeMethod(snes, update, snes->iter);
368:     PetscCall(SNESComputeJacobian(snes, X, snes->jacobian, snes->jacobian_pre));
369:     SNESCheckJacobianDomainError(snes);

371:     /* Create active and inactive index sets */

373:     /*original
374:     PetscCall(SNESVICreateIndexSets_RS(snes,X,F,&IS_act,&vi->IS_inact));
375:      */
376:     PetscCall(SNESVIGetActiveSetIS(snes, X, F, &IS_act));

378:     if (vi->checkredundancy) {
379:       PetscCall((*vi->checkredundancy)(snes, IS_act, &IS_redact, vi->ctxP));
380:       if (IS_redact) {
381:         PetscCall(ISSort(IS_redact));
382:         PetscCall(ISComplement(IS_redact, X->map->rstart, X->map->rend, &vi->IS_inact));
383:         PetscCall(ISDestroy(&IS_redact));
384:       } else {
385:         PetscCall(ISComplement(IS_act, X->map->rstart, X->map->rend, &vi->IS_inact));
386:       }
387:     } else {
388:       PetscCall(ISComplement(IS_act, X->map->rstart, X->map->rend, &vi->IS_inact));
389:     }

391:     /* Create inactive set submatrix */
392:     PetscCall(MatCreateSubMatrix(snes->jacobian, vi->IS_inact, vi->IS_inact, MAT_INITIAL_MATRIX, &jac_inact_inact));

394:     if (0) { /* Dead code (temporary developer hack) */
395:       IS keptrows;
396:       PetscCall(MatFindNonzeroRows(jac_inact_inact, &keptrows));
397:       if (keptrows) {
398:         PetscInt        cnt, *nrows, k;
399:         const PetscInt *krows, *inact;
400:         PetscInt        rstart;

402:         PetscCall(MatGetOwnershipRange(jac_inact_inact, &rstart, NULL));
403:         PetscCall(MatDestroy(&jac_inact_inact));
404:         PetscCall(ISDestroy(&IS_act));

406:         PetscCall(ISGetLocalSize(keptrows, &cnt));
407:         PetscCall(ISGetIndices(keptrows, &krows));
408:         PetscCall(ISGetIndices(vi->IS_inact, &inact));
409:         PetscCall(PetscMalloc1(cnt, &nrows));
410:         for (k = 0; k < cnt; k++) nrows[k] = inact[krows[k] - rstart];
411:         PetscCall(ISRestoreIndices(keptrows, &krows));
412:         PetscCall(ISRestoreIndices(vi->IS_inact, &inact));
413:         PetscCall(ISDestroy(&keptrows));
414:         PetscCall(ISDestroy(&vi->IS_inact));

416:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)snes), cnt, nrows, PETSC_OWN_POINTER, &vi->IS_inact));
417:         PetscCall(ISComplement(vi->IS_inact, F->map->rstart, F->map->rend, &IS_act));
418:         PetscCall(MatCreateSubMatrix(snes->jacobian, vi->IS_inact, vi->IS_inact, MAT_INITIAL_MATRIX, &jac_inact_inact));
419:       }
420:     }
421:     PetscCall(DMSetVI(snes->dm, vi->IS_inact));
422:     /* remove later */

424:     /*
425:     PetscCall(VecView(vi->xu,PETSC_VIEWER_BINARY_(((PetscObject)vi->xu)->comm)));
426:     PetscCall(VecView(vi->xl,PETSC_VIEWER_BINARY_(((PetscObject)vi->xl)->comm)));
427:     PetscCall(VecView(X,PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)X))));
428:     PetscCall(VecView(F,PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)F))));
429:     PetscCall(ISView(vi->IS_inact,PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)vi->IS_inact))));
430:      */

432:     /* Get sizes of active and inactive sets */
433:     PetscCall(ISGetLocalSize(IS_act, &nis_act));
434:     PetscCall(ISGetLocalSize(vi->IS_inact, &nis_inact));

436:     /* Create active and inactive set vectors */
437:     PetscCall(SNESCreateSubVectors_VINEWTONRSLS(snes, nis_inact, &F_inact));
438:     PetscCall(SNESCreateSubVectors_VINEWTONRSLS(snes, nis_act, &Y_act));
439:     PetscCall(SNESCreateSubVectors_VINEWTONRSLS(snes, nis_inact, &Y_inact));

441:     /* Create scatter contexts */
442:     PetscCall(VecScatterCreate(Y, IS_act, Y_act, NULL, &scat_act));
443:     PetscCall(VecScatterCreate(Y, vi->IS_inact, Y_inact, NULL, &scat_inact));

445:     /* Do a vec scatter to active and inactive set vectors */
446:     PetscCall(VecScatterBegin(scat_inact, F, F_inact, INSERT_VALUES, SCATTER_FORWARD));
447:     PetscCall(VecScatterEnd(scat_inact, F, F_inact, INSERT_VALUES, SCATTER_FORWARD));

449:     PetscCall(VecScatterBegin(scat_act, Y, Y_act, INSERT_VALUES, SCATTER_FORWARD));
450:     PetscCall(VecScatterEnd(scat_act, Y, Y_act, INSERT_VALUES, SCATTER_FORWARD));

452:     PetscCall(VecScatterBegin(scat_inact, Y, Y_inact, INSERT_VALUES, SCATTER_FORWARD));
453:     PetscCall(VecScatterEnd(scat_inact, Y, Y_inact, INSERT_VALUES, SCATTER_FORWARD));

455:     /* Active set direction = 0 */
456:     PetscCall(VecSet(Y_act, 0));
457:     if (snes->jacobian != snes->jacobian_pre) PetscCall(MatCreateSubMatrix(snes->jacobian_pre, vi->IS_inact, vi->IS_inact, MAT_INITIAL_MATRIX, &prejac_inact_inact));
458:     else prejac_inact_inact = jac_inact_inact;

460:     PetscCall(ISEqual(vi->IS_inact_prev, vi->IS_inact, &isequal));
461:     if (!isequal) {
462:       PetscCall(SNESVIResetPCandKSP(snes, jac_inact_inact, prejac_inact_inact));
463:       PetscCall(PCFieldSplitRestrictIS(pc, vi->IS_inact));
464:     }

466:     /*      PetscCall(ISView(vi->IS_inact,0)); */
467:     /*      PetscCall(ISView(IS_act,0));*/
468:     /*      ierr = MatView(snes->jacobian_pre,0); */

470:     PetscCall(KSPSetOperators(snes->ksp, jac_inact_inact, prejac_inact_inact));
471:     PetscCall(KSPSetUp(snes->ksp));
472:     {
473:       PC        pc;
474:       PetscBool flg;
475:       PetscCall(KSPGetPC(snes->ksp, &pc));
476:       PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCFIELDSPLIT, &flg));
477:       if (flg) {
478:         KSP *subksps;
479:         PetscCall(PCFieldSplitGetSubKSP(pc, NULL, &subksps));
480:         PetscCall(KSPGetPC(subksps[0], &pc));
481:         PetscCall(PetscFree(subksps));
482:         PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCBJACOBI, &flg));
483:         if (flg) {
484:           PetscInt        n, N = 101 * 101, j, cnts[3] = {0, 0, 0};
485:           const PetscInt *ii;

487:           PetscCall(ISGetSize(vi->IS_inact, &n));
488:           PetscCall(ISGetIndices(vi->IS_inact, &ii));
489:           for (j = 0; j < n; j++) {
490:             if (ii[j] < N) cnts[0]++;
491:             else if (ii[j] < 2 * N) cnts[1]++;
492:             else if (ii[j] < 3 * N) cnts[2]++;
493:           }
494:           PetscCall(ISRestoreIndices(vi->IS_inact, &ii));

496:           PetscCall(PCBJacobiSetTotalBlocks(pc, 3, cnts));
497:         }
498:       }
499:     }

501:     PetscCall(KSPSolve(snes->ksp, F_inact, Y_inact));
502:     PetscCall(VecScatterBegin(scat_act, Y_act, Y, INSERT_VALUES, SCATTER_REVERSE));
503:     PetscCall(VecScatterEnd(scat_act, Y_act, Y, INSERT_VALUES, SCATTER_REVERSE));
504:     PetscCall(VecScatterBegin(scat_inact, Y_inact, Y, INSERT_VALUES, SCATTER_REVERSE));
505:     PetscCall(VecScatterEnd(scat_inact, Y_inact, Y, INSERT_VALUES, SCATTER_REVERSE));

507:     PetscCall(VecDestroy(&F_inact));
508:     PetscCall(VecDestroy(&Y_act));
509:     PetscCall(VecDestroy(&Y_inact));
510:     PetscCall(VecScatterDestroy(&scat_act));
511:     PetscCall(VecScatterDestroy(&scat_inact));
512:     PetscCall(ISDestroy(&IS_act));
513:     if (!isequal) {
514:       PetscCall(ISDestroy(&vi->IS_inact_prev));
515:       PetscCall(ISDuplicate(vi->IS_inact, &vi->IS_inact_prev));
516:     }
517:     PetscCall(ISDestroy(&vi->IS_inact));
518:     PetscCall(MatDestroy(&jac_inact_inact));
519:     if (snes->jacobian != snes->jacobian_pre) PetscCall(MatDestroy(&prejac_inact_inact));

521:     PetscCall(KSPGetConvergedReason(snes->ksp, &kspreason));
522:     if (kspreason < 0) {
523:       if (++snes->numLinearSolveFailures >= snes->maxLinearSolveFailures) {
524:         PetscCall(PetscInfo(snes, "iter=%" PetscInt_FMT ", number linear solve failures %" PetscInt_FMT " greater than current SNES allowed, stopping solve\n", snes->iter, snes->numLinearSolveFailures));
525:         snes->reason = SNES_DIVERGED_LINEAR_SOLVE;
526:         break;
527:       }
528:     }

530:     PetscCall(KSPGetIterationNumber(snes->ksp, &lits));
531:     snes->linear_its += lits;
532:     PetscCall(PetscInfo(snes, "iter=%" PetscInt_FMT ", linear solve iterations=%" PetscInt_FMT "\n", snes->iter, lits));
533:     /*
534:     if (snes->ops->precheck) {
535:       PetscBool changed_y = PETSC_FALSE;
536:       PetscUseTypeMethod(snes,precheck ,X,Y,snes->precheck,&changed_y);
537:     }

539:     if (PetscLogPrintInfo) PetscCall(SNESVICheckResidual_Private(snes,snes->jacobian,F,Y,G,W));
540:     */
541:     /* Compute a (scaled) negative update in the line search routine:
542:          Y <- X - lambda*Y
543:        and evaluate G = function(Y) (depends on the line search).
544:     */
545:     PetscCall(VecCopy(Y, snes->vec_sol_update));
546:     ynorm = 1;
547:     gnorm = fnorm;
548:     PetscCall(SNESLineSearchApply(snes->linesearch, X, F, &gnorm, Y));
549:     PetscCall(DMDestroyVI(snes->dm));
550:     if (snes->reason) break;
551:     PetscCall(SNESLineSearchGetReason(snes->linesearch, &lsreason));
552:     if (lsreason) {
553:       if (snes->stol * xnorm > ynorm) {
554:         snes->reason = SNES_CONVERGED_SNORM_RELATIVE;
555:         break;
556:       } else if (lsreason == SNES_LINESEARCH_FAILED_FUNCTION_DOMAIN) {
557:         snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN;
558:         break;
559:       } else if (lsreason == SNES_LINESEARCH_FAILED_NANORINF) {
560:         snes->reason = SNES_DIVERGED_FUNCTION_NANORINF;
561:         break;
562:       } else if (lsreason == SNES_LINESEARCH_FAILED_OBJECTIVE_DOMAIN) {
563:         snes->reason = SNES_DIVERGED_OBJECTIVE_DOMAIN;
564:         break;
565:       } else if (lsreason == SNES_LINESEARCH_FAILED_JACOBIAN_DOMAIN) {
566:         snes->reason = SNES_DIVERGED_JACOBIAN_DOMAIN;
567:         break;
568:       } else if (++snes->numFailures >= snes->maxFailures) {
569:         PetscBool ismin;

571:         snes->reason = SNES_DIVERGED_LINE_SEARCH;
572:         PetscCall(SNESVICheckLocalMin_Private(snes, snes->jacobian, F, X, gnorm, &ismin));
573:         if (ismin) snes->reason = SNES_DIVERGED_LOCAL_MIN;
574:         break;
575:       }
576:     }
577:     PetscCall(SNESLineSearchGetNorms(snes->linesearch, &xnorm, &gnorm, &ynorm));
578:     PetscCall(PetscInfo(snes, "fnorm=%18.16e, gnorm=%18.16e, ynorm=%18.16e, lssucceed=%d\n", (double)fnorm, (double)gnorm, (double)ynorm, (int)lsreason));
579:     /* Update function and solution vectors */
580:     fnorm = gnorm;
581:     /* Monitor convergence */
582:     PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
583:     snes->iter  = i + 1;
584:     snes->norm  = fnorm;
585:     snes->xnorm = xnorm;
586:     snes->ynorm = ynorm;
587:     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
588:     PetscCall(SNESLogConvergenceHistory(snes, snes->norm, lits));
589:     /* Test for convergence, xnorm = || X || */
590:     if (snes->ops->converged != SNESConvergedSkip) PetscCall(VecNorm(X, NORM_2, &xnorm));
591:     PetscCall(SNESConverged(snes, snes->iter, xnorm, ynorm, fnorm));
592:     PetscCall(SNESMonitor(snes, snes->iter, snes->norm));
593:     if (snes->reason) break;
594:   }
595:   /* make sure that the VI information attached to the DM is removed if the for loop above was broken early due to some exceptional conditional */
596:   PetscCall(DMDestroyVI(snes->dm));
597:   PetscFunctionReturn(PETSC_SUCCESS);
598: }

600: /*@C
601:   SNESVISetRedundancyCheck - Provide a function to check for any redundancy in the VI active set

603:   Logically Collective

605:   Input Parameters:
606: + snes - the `SNESVINEWTONRSLS` context
607: . func - the function to check of redundancies
608: - ctx  - optional context used by the function

610:   Calling sequence of func:
611: + snes      - the `SNES` context
612: . is_act    - the set of points in the active sets
613: . is_redact - output, the set of points in the non-redundant active set
614: - ctx       - optional context

616:   Level: advanced

618:   Note:
619:   Sometimes the inactive set will result in a singular sub-Jacobian problem that needs to be solved, this allows the user,
620:   when they know more about their specific problem to provide a function that removes the redundancy that results in the singular linear system

622:   See `SNESVINEWTONRSLS` for a concise description of the active and inactive sets

624: .seealso: [](ch_snes), `SNES`, `SNESVINEWTONRSLS`, `SNESVIGetInactiveSet()`, `DMSetVI()`
625:  @*/
626: PetscErrorCode SNESVISetRedundancyCheck(SNES snes, PetscErrorCode (*func)(SNES snes, IS is_act, IS *is_redact, PetscCtx ctx), PetscCtx ctx)
627: {
628:   SNES_VINEWTONRSLS *vi = (SNES_VINEWTONRSLS *)snes->data;

630:   PetscFunctionBegin;
632:   vi->checkredundancy = func;
633:   vi->ctxP            = ctx;
634:   PetscFunctionReturn(PETSC_SUCCESS);
635: }

637: #if defined(PETSC_HAVE_MATLAB)
638:   #include <engine.h>
639:   #include <mex.h>
640: typedef struct {
641:   char    *funcname;
642:   mxArray *ctx;
643: } SNESMatlabContext;

645: PetscErrorCode SNESVIRedundancyCheck_Matlab(SNES snes, IS is_act, IS *is_redact, PetscCtx ctx)
646: {
647:   SNESMatlabContext *sctx = (SNESMatlabContext *)ctx;
648:   int                nlhs = 1, nrhs = 5;
649:   mxArray           *plhs[1], *prhs[5];
650:   long long int      l1 = 0, l2 = 0, ls = 0;
651:   PetscInt          *indices = NULL;

653:   PetscFunctionBegin;
656:   PetscAssertPointer(is_redact, 3);
657:   PetscCheckSameComm(snes, 1, is_act, 2);

659:   /* Create IS for reduced active set of size 0, its size and indices will
660:    bet set by the MATLAB function */
661:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)snes), 0, indices, PETSC_OWN_POINTER, is_redact));
662:   /* call MATLAB function in ctx */
663:   PetscCall(PetscArraycpy(&ls, &snes, 1));
664:   PetscCall(PetscArraycpy(&l1, &is_act, 1));
665:   PetscCall(PetscArraycpy(&l2, is_redact, 1));
666:   prhs[0] = mxCreateDoubleScalar((double)ls);
667:   prhs[1] = mxCreateDoubleScalar((double)l1);
668:   prhs[2] = mxCreateDoubleScalar((double)l2);
669:   prhs[3] = mxCreateString(sctx->funcname);
670:   prhs[4] = sctx->ctx;
671:   PetscCall(mexCallMATLAB(nlhs, plhs, nrhs, prhs, "PetscSNESVIRedundancyCheckInternal"));
672:   PetscCall(mxGetScalar(plhs[0]));
673:   mxDestroyArray(prhs[0]);
674:   mxDestroyArray(prhs[1]);
675:   mxDestroyArray(prhs[2]);
676:   mxDestroyArray(prhs[3]);
677:   mxDestroyArray(plhs[0]);
678:   PetscFunctionReturn(PETSC_SUCCESS);
679: }

681: PetscErrorCode SNESVISetRedundancyCheckMatlab(SNES snes, const char *func, mxArray *ctx)
682: {
683:   SNESMatlabContext *sctx;

685:   PetscFunctionBegin;
686:   /* currently sctx is memory bleed */
687:   PetscCall(PetscNew(&sctx));
688:   PetscCall(PetscStrallocpy(func, &sctx->funcname));
689:   sctx->ctx = mxDuplicateArray(ctx);
690:   PetscCall(SNESVISetRedundancyCheck(snes, SNESVIRedundancyCheck_Matlab, sctx));
691:   PetscFunctionReturn(PETSC_SUCCESS);
692: }

694: #endif

696: static PetscErrorCode SNESSetUp_VINEWTONRSLS(SNES snes)
697: {
698:   SNES_VINEWTONRSLS *vi = (SNES_VINEWTONRSLS *)snes->data;
699:   PetscInt          *indices;
700:   PetscInt           i, n, rstart, rend;
701:   SNESLineSearch     linesearch;

703:   PetscFunctionBegin;
704:   PetscCall(SNESSetUp_VI(snes));

706:   /* Set up previous active index set for the first snes solve
707:    vi->IS_inact_prev = 0,1,2,....N */

709:   PetscCall(VecGetOwnershipRange(snes->work[0], &rstart, &rend));
710:   PetscCall(VecGetLocalSize(snes->work[0], &n));
711:   PetscCall(PetscMalloc1(n, &indices));
712:   for (i = 0; i < n; i++) indices[i] = rstart + i;
713:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)snes), n, indices, PETSC_OWN_POINTER, &vi->IS_inact_prev));

715:   /* set the line search functions */
716:   if (!snes->linesearch) {
717:     PetscCall(SNESGetLineSearch(snes, &linesearch));
718:     PetscCall(SNESLineSearchSetType(linesearch, SNESLINESEARCHBT));
719:   }
720:   PetscFunctionReturn(PETSC_SUCCESS);
721: }

723: static PetscErrorCode SNESReset_VINEWTONRSLS(SNES snes)
724: {
725:   SNES_VINEWTONRSLS *vi = (SNES_VINEWTONRSLS *)snes->data;

727:   PetscFunctionBegin;
728:   PetscCall(SNESReset_VI(snes));
729:   PetscCall(ISDestroy(&vi->IS_inact_prev));
730:   PetscFunctionReturn(PETSC_SUCCESS);
731: }

733: /*MC
734:    SNESVINEWTONRSLS - Reduced space active set solvers for variational inequalities based on Newton's method

736:    Options Database Keys:
737: +  -snes_type (vinewtonssls|vinewtonrsls) - A semi-smooth solver or a reduced space active set method
738: .  -snes_vi_zero_tolerance                - Tolerance for considering $u_i$ value to be on a bound.
739: .  -snes_vi_monitor                       - Prints the number of active constraints (inactive set points) at each iteration.
740: .  -snes_vi_monitor_residual              - View the residual vector at each iteration, using zero for active constraints (i.e. the inactive variables).
741: -  -snes_vi_monitor_active                - View the active set by outputting a one for vector components in the active set and zero for the inactive.

743:    Level: beginner

745:    Note:
746:    Reduced-space (active set methods) work as follows at each iteration\:
747:    - The algorithm produces an inactive set of variables, that is a list of variables whose values will not be changed in the current iteration, i.e. they
748:      are to be constrained to their current values. These are all the variables that are on the lower bound, that is $u_i = L_i$ with also $[F(u)]_i \ge 0$ or
749:      the upper bound $u_i = U_i$ with also $[F(u)]_i \le 0.$
750:    - A step direction is obtained by solving the linear system arising from the Jacobian used in Newton's method but with the inactive variables removed
751:      from both the rows and columns.
752:    - A line search is then used to update the active variables (the inactive set of variables are not changed).

754:    The inactive set is chosen based on the sign of $[F(u)]_i$ because this gives exactly the set of points that would be moved outside of the domain given
755:    an infinitesimal Newton (or even Richardson) step and our goal is to remain within the bounds, that is, to continue to satisfy the inequality constraints.

757:    See {cite}`benson2006flexible`

759: .seealso: [](ch_snes), `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()`, `SNESCreate()`, `SNES`, `SNESSetType()`, `SNESVINEWTONSSLS`, `SNESNEWTONTR`, `SNESLineSearchSetType()`, `SNESLineSearchSetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESVIGetInactiveSet()`, `DMSetVI()`, `SNESVISetRedundancyCheck()`
760: M*/
761: PETSC_EXTERN PetscErrorCode SNESCreate_VINEWTONRSLS(SNES snes)
762: {
763:   SNES_VINEWTONRSLS *vi;
764:   SNESLineSearch     linesearch;

766:   PetscFunctionBegin;
767:   snes->ops->reset          = SNESReset_VINEWTONRSLS;
768:   snes->ops->setup          = SNESSetUp_VINEWTONRSLS;
769:   snes->ops->solve          = SNESSolve_VINEWTONRSLS;
770:   snes->ops->destroy        = SNESDestroy_VI;
771:   snes->ops->setfromoptions = SNESSetFromOptions_VI;
772:   snes->ops->view           = NULL;
773:   snes->ops->converged      = SNESConvergedDefault_VI;

775:   snes->usesksp = PETSC_TRUE;
776:   snes->usesnpc = PETSC_FALSE;

778:   PetscCall(SNESGetLineSearch(snes, &linesearch));
779:   if (!((PetscObject)linesearch)->type_name) PetscCall(SNESLineSearchSetType(linesearch, SNESLINESEARCHBT));
780:   PetscCall(SNESLineSearchBTSetAlpha(linesearch, 0.0));

782:   snes->alwayscomputesfinalresidual = PETSC_TRUE;

784:   PetscCall(SNESParametersInitialize(snes));

786:   PetscCall(PetscNew(&vi));
787:   snes->data          = (void *)vi;
788:   vi->checkredundancy = NULL;

790:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESVISetVariableBounds_C", SNESVISetVariableBounds_VI));
791:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESVISetComputeVariableBounds_C", SNESVISetComputeVariableBounds_VI));
792:   PetscFunctionReturn(PETSC_SUCCESS);
793: }