xref: /petsc/src/snes/impls/composite/snescomposite.c (revision 98d129c30f3ee9fdddc40fdbc5a989b7be64f888)
1 /*
2       Defines a SNES that can consist of a collection of SNESes
3 */
4 #include <petsc/private/snesimpl.h> /*I "petscsnes.h" I*/
5 #include <petscblaslapack.h>
6 
7 const char *const SNESCompositeTypes[] = {"ADDITIVE", "MULTIPLICATIVE", "ADDITIVEOPTIMAL", "SNESCompositeType", "SNES_COMPOSITE", NULL};
8 
9 typedef struct _SNES_CompositeLink *SNES_CompositeLink;
10 struct _SNES_CompositeLink {
11   SNES               snes;
12   PetscReal          dmp;
13   Vec                X;
14   SNES_CompositeLink next;
15   SNES_CompositeLink previous;
16 };
17 
18 typedef struct {
19   SNES_CompositeLink head;
20   PetscInt           nsnes;
21   SNESCompositeType  type;
22   Vec                Xorig;
23   PetscInt           innerFailures; /* the number of inner failures we've seen */
24 
25   /* context for ADDITIVEOPTIMAL */
26   Vec         *Xes, *Fes; /* solution and residual vectors for the subsolvers */
27   PetscReal   *fnorms;    /* norms of the solutions */
28   PetscScalar *h;         /* the matrix formed as q_ij = (rdot_i, rdot_j) */
29   PetscScalar *g;         /* the dotproducts of the previous function with the candidate functions */
30   PetscBLASInt n;         /* matrix dimension -- nsnes */
31   PetscBLASInt nrhs;      /* the number of right-hand sides */
32   PetscBLASInt lda;       /* the padded matrix dimension */
33   PetscBLASInt ldb;       /* the padded vector dimension */
34   PetscReal   *s;         /* the singular values */
35   PetscScalar *beta;      /* the RHS and combination */
36   PetscReal    rcond;     /* the exit condition */
37   PetscBLASInt rank;      /* the effective rank */
38   PetscScalar *work;      /* the work vector */
39   PetscReal   *rwork;     /* the real work vector used for complex */
40   PetscBLASInt lwork;     /* the size of the work vector */
41   PetscBLASInt info;      /* the output condition */
42 
43   PetscReal rtol; /* restart tolerance for accepting the combination */
44   PetscReal stol; /* restart tolerance for the combination */
45 } SNES_Composite;
46 
47 static PetscErrorCode SNESCompositeApply_Multiplicative(SNES snes, Vec X, Vec B, Vec F, PetscReal *fnorm)
48 {
49   SNES_Composite     *jac  = (SNES_Composite *)snes->data;
50   SNES_CompositeLink  next = jac->head;
51   Vec                 FSub;
52   SNESConvergedReason reason;
53 
54   PetscFunctionBegin;
55   PetscCheck(next, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "No composite SNESes supplied via SNESCompositeAddSNES() or -snes_composite_sneses");
56   if (snes->normschedule == SNES_NORM_ALWAYS) PetscCall(SNESSetInitialFunction(next->snes, F));
57   PetscCall(SNESSolve(next->snes, B, X));
58   PetscCall(SNESGetConvergedReason(next->snes, &reason));
59   if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
60     jac->innerFailures++;
61     if (jac->innerFailures >= snes->maxFailures) {
62       snes->reason = SNES_DIVERGED_INNER;
63       PetscFunctionReturn(PETSC_SUCCESS);
64     }
65   }
66 
67   while (next->next) {
68     /* only copy the function over in the case where the functions correspond */
69     if (next->snes->npcside == PC_RIGHT && next->snes->normschedule != SNES_NORM_NONE) {
70       PetscCall(SNESGetFunction(next->snes, &FSub, NULL, NULL));
71       next = next->next;
72       PetscCall(SNESSetInitialFunction(next->snes, FSub));
73     } else {
74       next = next->next;
75     }
76     PetscCall(SNESSolve(next->snes, B, X));
77     PetscCall(SNESGetConvergedReason(next->snes, &reason));
78     if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
79       jac->innerFailures++;
80       if (jac->innerFailures >= snes->maxFailures) {
81         snes->reason = SNES_DIVERGED_INNER;
82         PetscFunctionReturn(PETSC_SUCCESS);
83       }
84     }
85   }
86   if (next->snes->npcside == PC_RIGHT) {
87     PetscCall(SNESGetFunction(next->snes, &FSub, NULL, NULL));
88     PetscCall(VecCopy(FSub, F));
89     if (fnorm) {
90       if (snes->xl && snes->xu) {
91         PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, fnorm));
92       } else {
93         PetscCall(VecNorm(F, NORM_2, fnorm));
94       }
95       SNESCheckFunctionNorm(snes, *fnorm);
96     }
97   } else if (snes->normschedule == SNES_NORM_ALWAYS) {
98     PetscCall(SNESComputeFunction(snes, X, F));
99     if (fnorm) {
100       if (snes->xl && snes->xu) {
101         PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, fnorm));
102       } else {
103         PetscCall(VecNorm(F, NORM_2, fnorm));
104       }
105       SNESCheckFunctionNorm(snes, *fnorm);
106     }
107   }
108   PetscFunctionReturn(PETSC_SUCCESS);
109 }
110 
111 static PetscErrorCode SNESCompositeApply_Additive(SNES snes, Vec X, Vec B, Vec F, PetscReal *fnorm)
112 {
113   SNES_Composite     *jac  = (SNES_Composite *)snes->data;
114   SNES_CompositeLink  next = jac->head;
115   Vec                 Y, Xorig;
116   SNESConvergedReason reason;
117 
118   PetscFunctionBegin;
119   Y = snes->vec_sol_update;
120   if (!jac->Xorig) PetscCall(VecDuplicate(X, &jac->Xorig));
121   Xorig = jac->Xorig;
122   PetscCall(VecCopy(X, Xorig));
123   PetscCheck(next, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "No composite SNESes supplied via SNESCompositeAddSNES() or -snes_composite_sneses");
124   if (snes->normschedule == SNES_NORM_ALWAYS) {
125     PetscCall(SNESSetInitialFunction(next->snes, F));
126     while (next->next) {
127       next = next->next;
128       PetscCall(SNESSetInitialFunction(next->snes, F));
129     }
130   }
131   next = jac->head;
132   PetscCall(VecCopy(Xorig, Y));
133   PetscCall(SNESSolve(next->snes, B, Y));
134   PetscCall(SNESGetConvergedReason(next->snes, &reason));
135   if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
136     jac->innerFailures++;
137     if (jac->innerFailures >= snes->maxFailures) {
138       snes->reason = SNES_DIVERGED_INNER;
139       PetscFunctionReturn(PETSC_SUCCESS);
140     }
141   }
142   PetscCall(VecAXPY(Y, -1.0, Xorig));
143   PetscCall(VecAXPY(X, next->dmp, Y));
144   while (next->next) {
145     next = next->next;
146     PetscCall(VecCopy(Xorig, Y));
147     PetscCall(SNESSolve(next->snes, B, Y));
148     PetscCall(SNESGetConvergedReason(next->snes, &reason));
149     if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
150       jac->innerFailures++;
151       if (jac->innerFailures >= snes->maxFailures) {
152         snes->reason = SNES_DIVERGED_INNER;
153         PetscFunctionReturn(PETSC_SUCCESS);
154       }
155     }
156     PetscCall(VecAXPY(Y, -1.0, Xorig));
157     PetscCall(VecAXPY(X, next->dmp, Y));
158   }
159   if (snes->normschedule == SNES_NORM_ALWAYS) {
160     PetscCall(SNESComputeFunction(snes, X, F));
161     if (fnorm) {
162       if (snes->xl && snes->xu) {
163         PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, fnorm));
164       } else {
165         PetscCall(VecNorm(F, NORM_2, fnorm));
166       }
167       SNESCheckFunctionNorm(snes, *fnorm);
168     }
169   }
170   PetscFunctionReturn(PETSC_SUCCESS);
171 }
172 
173 /* approximately solve the overdetermined system:
174 
175  2*F(x_i)\cdot F(\x_j)\alpha_i = 0
176  \alpha_i                      = 1
177 
178  Which minimizes the L2 norm of the linearization of:
179  ||F(\sum_i \alpha_i*x_i)||^2
180 
181  With the constraint that \sum_i\alpha_i = 1
182  Where x_i is the solution from the ith subsolver.
183  */
184 static PetscErrorCode SNESCompositeApply_AdditiveOptimal(SNES snes, Vec X, Vec B, Vec F, PetscReal *fnorm)
185 {
186   SNES_Composite     *jac  = (SNES_Composite *)snes->data;
187   SNES_CompositeLink  next = jac->head;
188   Vec                *Xes = jac->Xes, *Fes = jac->Fes;
189   PetscInt            i, j;
190   PetscScalar         tot, total, ftf;
191   PetscReal           min_fnorm;
192   PetscInt            min_i;
193   SNESConvergedReason reason;
194 
195   PetscFunctionBegin;
196   PetscCheck(next, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "No composite SNESes supplied via SNESCompositeAddSNES() or -snes_composite_sneses");
197 
198   if (snes->normschedule == SNES_NORM_ALWAYS) {
199     next = jac->head;
200     PetscCall(SNESSetInitialFunction(next->snes, F));
201     while (next->next) {
202       next = next->next;
203       PetscCall(SNESSetInitialFunction(next->snes, F));
204     }
205   }
206 
207   next = jac->head;
208   i    = 0;
209   PetscCall(VecCopy(X, Xes[i]));
210   PetscCall(SNESSolve(next->snes, B, Xes[i]));
211   PetscCall(SNESGetConvergedReason(next->snes, &reason));
212   if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
213     jac->innerFailures++;
214     if (jac->innerFailures >= snes->maxFailures) {
215       snes->reason = SNES_DIVERGED_INNER;
216       PetscFunctionReturn(PETSC_SUCCESS);
217     }
218   }
219   while (next->next) {
220     i++;
221     next = next->next;
222     PetscCall(VecCopy(X, Xes[i]));
223     PetscCall(SNESSolve(next->snes, B, Xes[i]));
224     PetscCall(SNESGetConvergedReason(next->snes, &reason));
225     if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
226       jac->innerFailures++;
227       if (jac->innerFailures >= snes->maxFailures) {
228         snes->reason = SNES_DIVERGED_INNER;
229         PetscFunctionReturn(PETSC_SUCCESS);
230       }
231     }
232   }
233 
234   /* all the solutions are collected; combine optimally */
235   for (i = 0; i < jac->n; i++) {
236     for (j = 0; j < i + 1; j++) PetscCall(VecDotBegin(Fes[i], Fes[j], &jac->h[i + j * jac->n]));
237     PetscCall(VecDotBegin(Fes[i], F, &jac->g[i]));
238   }
239 
240   for (i = 0; i < jac->n; i++) {
241     for (j = 0; j < i + 1; j++) {
242       PetscCall(VecDotEnd(Fes[i], Fes[j], &jac->h[i + j * jac->n]));
243       if (i == j) jac->fnorms[i] = PetscSqrtReal(PetscRealPart(jac->h[i + j * jac->n]));
244     }
245     PetscCall(VecDotEnd(Fes[i], F, &jac->g[i]));
246   }
247 
248   ftf = (*fnorm) * (*fnorm);
249 
250   for (i = 0; i < jac->n; i++) {
251     for (j = i + 1; j < jac->n; j++) jac->h[i + j * jac->n] = jac->h[j + i * jac->n];
252   }
253 
254   for (i = 0; i < jac->n; i++) {
255     for (j = 0; j < jac->n; j++) jac->h[i + j * jac->n] = jac->h[i + j * jac->n] - jac->g[j] - jac->g[i] + ftf;
256     jac->beta[i] = ftf - jac->g[i];
257   }
258 
259   jac->info  = 0;
260   jac->rcond = -1.;
261   PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
262 #if defined(PETSC_USE_COMPLEX)
263   PetscCallBLAS("LAPACKgelss", LAPACKgelss_(&jac->n, &jac->n, &jac->nrhs, jac->h, &jac->lda, jac->beta, &jac->lda, jac->s, &jac->rcond, &jac->rank, jac->work, &jac->lwork, jac->rwork, &jac->info));
264 #else
265   PetscCallBLAS("LAPACKgelss", LAPACKgelss_(&jac->n, &jac->n, &jac->nrhs, jac->h, &jac->lda, jac->beta, &jac->lda, jac->s, &jac->rcond, &jac->rank, jac->work, &jac->lwork, &jac->info));
266 #endif
267   PetscCall(PetscFPTrapPop());
268   PetscCheck(jac->info >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_LIB, "Bad argument to GELSS");
269   PetscCheck(jac->info <= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_LIB, "SVD failed to converge");
270   tot   = 0.;
271   total = 0.;
272   for (i = 0; i < jac->n; i++) {
273     PetscCheck(!snes->errorifnotconverged || !PetscIsInfOrNanScalar(jac->beta[i]), PetscObjectComm((PetscObject)snes), PETSC_ERR_LIB, "SVD generated inconsistent output");
274     PetscCall(PetscInfo(snes, "%" PetscInt_FMT ": %g\n", i, (double)PetscRealPart(jac->beta[i])));
275     tot += jac->beta[i];
276     total += PetscAbsScalar(jac->beta[i]);
277   }
278   PetscCall(VecScale(X, (1. - tot)));
279   PetscCall(VecMAXPY(X, jac->n, jac->beta, Xes));
280   PetscCall(SNESComputeFunction(snes, X, F));
281 
282   if (snes->xl && snes->xu) {
283     PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, fnorm));
284   } else {
285     PetscCall(VecNorm(F, NORM_2, fnorm));
286   }
287 
288   /* take the minimum-normed candidate if it beats the combination by a factor of rtol or the combination has stagnated */
289   min_fnorm = jac->fnorms[0];
290   min_i     = 0;
291   for (i = 0; i < jac->n; i++) {
292     if (jac->fnorms[i] < min_fnorm) {
293       min_fnorm = jac->fnorms[i];
294       min_i     = i;
295     }
296   }
297 
298   /* stagnation or divergence restart to the solution of the solver that failed the least */
299   if (PetscRealPart(total) < jac->stol || min_fnorm * jac->rtol < *fnorm) {
300     PetscCall(VecCopy(jac->Xes[min_i], X));
301     PetscCall(VecCopy(jac->Fes[min_i], F));
302     *fnorm = min_fnorm;
303   }
304   PetscFunctionReturn(PETSC_SUCCESS);
305 }
306 
307 static PetscErrorCode SNESSetUp_Composite(SNES snes)
308 {
309   DM                 dm;
310   SNES_Composite    *jac  = (SNES_Composite *)snes->data;
311   SNES_CompositeLink next = jac->head;
312   PetscInt           n    = 0, i;
313   Vec                F;
314 
315   PetscFunctionBegin;
316   PetscCall(SNESGetDM(snes, &dm));
317 
318   if (snes->ops->computevariablebounds) {
319     /* SNESVI only ever calls computevariablebounds once, so calling it once here is justified */
320     if (!snes->xl) PetscCall(VecDuplicate(snes->vec_sol, &snes->xl));
321     if (!snes->xu) PetscCall(VecDuplicate(snes->vec_sol, &snes->xu));
322     PetscUseTypeMethod(snes, computevariablebounds, snes->xl, snes->xu);
323   }
324 
325   while (next) {
326     n++;
327     PetscCall(SNESSetDM(next->snes, dm));
328     PetscCall(SNESSetApplicationContext(next->snes, snes->user));
329     if (snes->xl && snes->xu) {
330       if (snes->ops->computevariablebounds) {
331         PetscCall(SNESVISetComputeVariableBounds(next->snes, snes->ops->computevariablebounds));
332       } else {
333         PetscCall(SNESVISetVariableBounds(next->snes, snes->xl, snes->xu));
334       }
335     }
336 
337     next = next->next;
338   }
339   jac->nsnes = n;
340   PetscCall(SNESGetFunction(snes, &F, NULL, NULL));
341   if (jac->type == SNES_COMPOSITE_ADDITIVEOPTIMAL) {
342     PetscCall(VecDuplicateVecs(F, jac->nsnes, &jac->Xes));
343     PetscCall(PetscMalloc1(n, &jac->Fes));
344     PetscCall(PetscMalloc1(n, &jac->fnorms));
345     next = jac->head;
346     i    = 0;
347     while (next) {
348       PetscCall(SNESGetFunction(next->snes, &F, NULL, NULL));
349       jac->Fes[i] = F;
350       PetscCall(PetscObjectReference((PetscObject)F));
351       next = next->next;
352       i++;
353     }
354     /* allocate the subspace direct solve area */
355     jac->nrhs = 1;
356     jac->lda  = jac->nsnes;
357     jac->ldb  = jac->nsnes;
358     jac->n    = jac->nsnes;
359 
360     PetscCall(PetscMalloc1(jac->n * jac->n, &jac->h));
361     PetscCall(PetscMalloc1(jac->n, &jac->beta));
362     PetscCall(PetscMalloc1(jac->n, &jac->s));
363     PetscCall(PetscMalloc1(jac->n, &jac->g));
364     jac->lwork = 12 * jac->n;
365 #if defined(PETSC_USE_COMPLEX)
366     PetscCall(PetscMalloc1(jac->lwork, &jac->rwork));
367 #endif
368     PetscCall(PetscMalloc1(jac->lwork, &jac->work));
369   }
370   PetscFunctionReturn(PETSC_SUCCESS);
371 }
372 
373 static PetscErrorCode SNESReset_Composite(SNES snes)
374 {
375   SNES_Composite    *jac  = (SNES_Composite *)snes->data;
376   SNES_CompositeLink next = jac->head;
377 
378   PetscFunctionBegin;
379   while (next) {
380     PetscCall(SNESReset(next->snes));
381     next = next->next;
382   }
383   PetscCall(VecDestroy(&jac->Xorig));
384   if (jac->Xes) PetscCall(VecDestroyVecs(jac->nsnes, &jac->Xes));
385   if (jac->Fes) PetscCall(VecDestroyVecs(jac->nsnes, &jac->Fes));
386   PetscCall(PetscFree(jac->fnorms));
387   PetscCall(PetscFree(jac->h));
388   PetscCall(PetscFree(jac->s));
389   PetscCall(PetscFree(jac->g));
390   PetscCall(PetscFree(jac->beta));
391   PetscCall(PetscFree(jac->work));
392   PetscCall(PetscFree(jac->rwork));
393   PetscFunctionReturn(PETSC_SUCCESS);
394 }
395 
396 static PetscErrorCode SNESDestroy_Composite(SNES snes)
397 {
398   SNES_Composite    *jac  = (SNES_Composite *)snes->data;
399   SNES_CompositeLink next = jac->head, next_tmp;
400 
401   PetscFunctionBegin;
402   PetscCall(SNESReset_Composite(snes));
403   while (next) {
404     PetscCall(SNESDestroy(&next->snes));
405     next_tmp = next;
406     next     = next->next;
407     PetscCall(PetscFree(next_tmp));
408   }
409   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeSetType_C", NULL));
410   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeAddSNES_C", NULL));
411   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeGetSNES_C", NULL));
412   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeSetDamping_C", NULL));
413   PetscCall(PetscFree(snes->data));
414   PetscFunctionReturn(PETSC_SUCCESS);
415 }
416 
417 static PetscErrorCode SNESSetFromOptions_Composite(SNES snes, PetscOptionItems *PetscOptionsObject)
418 {
419   SNES_Composite    *jac  = (SNES_Composite *)snes->data;
420   PetscInt           nmax = 8, i;
421   SNES_CompositeLink next;
422   char              *sneses[8];
423   PetscReal          dmps[8];
424   PetscBool          flg;
425 
426   PetscFunctionBegin;
427   PetscOptionsHeadBegin(PetscOptionsObject, "Composite preconditioner options");
428   PetscCall(PetscOptionsEnum("-snes_composite_type", "Type of composition", "SNESCompositeSetType", SNESCompositeTypes, (PetscEnum)jac->type, (PetscEnum *)&jac->type, &flg));
429   if (flg) PetscCall(SNESCompositeSetType(snes, jac->type));
430   PetscCall(PetscOptionsStringArray("-snes_composite_sneses", "List of composite solvers", "SNESCompositeAddSNES", sneses, &nmax, &flg));
431   if (flg) {
432     for (i = 0; i < nmax; i++) {
433       PetscCall(SNESCompositeAddSNES(snes, sneses[i]));
434       PetscCall(PetscFree(sneses[i])); /* deallocate string sneses[i], which is allocated in PetscOptionsStringArray() */
435     }
436   }
437   PetscCall(PetscOptionsRealArray("-snes_composite_damping", "Damping of the additive composite solvers", "SNESCompositeSetDamping", dmps, &nmax, &flg));
438   if (flg) {
439     for (i = 0; i < nmax; i++) PetscCall(SNESCompositeSetDamping(snes, i, dmps[i]));
440   }
441   PetscCall(PetscOptionsReal("-snes_composite_stol", "Step tolerance for restart on the additive composite solvers", "", jac->stol, &jac->stol, NULL));
442   PetscCall(PetscOptionsReal("-snes_composite_rtol", "Residual tolerance for the additive composite solvers", "", jac->rtol, &jac->rtol, NULL));
443   PetscOptionsHeadEnd();
444 
445   next = jac->head;
446   while (next) {
447     PetscCall(SNESSetFromOptions(next->snes));
448     next = next->next;
449   }
450   PetscFunctionReturn(PETSC_SUCCESS);
451 }
452 
453 static PetscErrorCode SNESView_Composite(SNES snes, PetscViewer viewer)
454 {
455   SNES_Composite    *jac  = (SNES_Composite *)snes->data;
456   SNES_CompositeLink next = jac->head;
457   PetscBool          iascii;
458 
459   PetscFunctionBegin;
460   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
461   if (iascii) {
462     PetscCall(PetscViewerASCIIPrintf(viewer, "  type - %s\n", SNESCompositeTypes[jac->type]));
463     PetscCall(PetscViewerASCIIPrintf(viewer, "  SNESes on composite preconditioner follow\n"));
464     PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------------------------------\n"));
465   }
466   if (iascii) PetscCall(PetscViewerASCIIPushTab(viewer));
467   while (next) {
468     PetscCall(SNESView(next->snes, viewer));
469     next = next->next;
470   }
471   if (iascii) {
472     PetscCall(PetscViewerASCIIPopTab(viewer));
473     PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------------------------------\n"));
474   }
475   PetscFunctionReturn(PETSC_SUCCESS);
476 }
477 
478 static PetscErrorCode SNESCompositeSetType_Composite(SNES snes, SNESCompositeType type)
479 {
480   SNES_Composite *jac = (SNES_Composite *)snes->data;
481 
482   PetscFunctionBegin;
483   jac->type = type;
484   PetscFunctionReturn(PETSC_SUCCESS);
485 }
486 
487 static PetscErrorCode SNESCompositeAddSNES_Composite(SNES snes, SNESType type)
488 {
489   SNES_Composite    *jac;
490   SNES_CompositeLink next, ilink;
491   PetscInt           cnt = 0;
492   const char        *prefix;
493   char               newprefix[20];
494   DM                 dm;
495 
496   PetscFunctionBegin;
497   PetscCall(PetscNew(&ilink));
498   ilink->next = NULL;
499   PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &ilink->snes));
500   PetscCall(SNESGetDM(snes, &dm));
501   PetscCall(SNESSetDM(ilink->snes, dm));
502   PetscCall(SNESSetTolerances(ilink->snes, snes->abstol, snes->rtol, snes->stol, 1, snes->max_funcs));
503   PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes, (PetscObject)ilink->snes));
504   jac  = (SNES_Composite *)snes->data;
505   next = jac->head;
506   if (!next) {
507     jac->head       = ilink;
508     ilink->previous = NULL;
509   } else {
510     cnt++;
511     while (next->next) {
512       next = next->next;
513       cnt++;
514     }
515     next->next      = ilink;
516     ilink->previous = next;
517   }
518   PetscCall(SNESGetOptionsPrefix(snes, &prefix));
519   PetscCall(SNESSetOptionsPrefix(ilink->snes, prefix));
520   PetscCall(PetscSNPrintf(newprefix, sizeof(newprefix), "sub_%d_", (int)cnt));
521   PetscCall(SNESAppendOptionsPrefix(ilink->snes, newprefix));
522   PetscCall(PetscObjectIncrementTabLevel((PetscObject)ilink->snes, (PetscObject)snes, 1));
523   PetscCall(SNESSetType(ilink->snes, type));
524   PetscCall(SNESSetNormSchedule(ilink->snes, SNES_NORM_FINAL_ONLY));
525 
526   ilink->dmp = 1.0;
527   jac->nsnes++;
528   PetscFunctionReturn(PETSC_SUCCESS);
529 }
530 
531 static PetscErrorCode SNESCompositeGetSNES_Composite(SNES snes, PetscInt n, SNES *subsnes)
532 {
533   SNES_Composite    *jac;
534   SNES_CompositeLink next;
535   PetscInt           i;
536 
537   PetscFunctionBegin;
538   jac  = (SNES_Composite *)snes->data;
539   next = jac->head;
540   for (i = 0; i < n; i++) {
541     PetscCheck(next->next, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "Not enough SNESes in composite preconditioner");
542     next = next->next;
543   }
544   *subsnes = next->snes;
545   PetscFunctionReturn(PETSC_SUCCESS);
546 }
547 
548 /*@C
549   SNESCompositeSetType - Sets the type of composite preconditioner.
550 
551   Logically Collective
552 
553   Input Parameters:
554 + snes - the preconditioner context
555 - type - `SNES_COMPOSITE_ADDITIVE` (default), `SNES_COMPOSITE_MULTIPLICATIVE`, or `SNES_COMPOSITE_ADDITIVEOPTIMAL`
556 
557   Options Database Key:
558 . -snes_composite_type <type: one of multiplicative, additive, additiveoptimal> - Sets composite preconditioner type
559 
560   Level: developer
561 
562 .seealso: [](ch_snes), `SNES_COMPOSITE_ADDITIVE`, `SNES_COMPOSITE_MULTIPLICATIVE`, `SNESCompositeType`, `SNESCOMPOSITE`, `SNES_COMPOSITE_ADDITIVEOPTIMAL`,
563           `PCCompositeType`
564 @*/
565 PetscErrorCode SNESCompositeSetType(SNES snes, SNESCompositeType type)
566 {
567   PetscFunctionBegin;
568   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
569   PetscValidLogicalCollectiveEnum(snes, type, 2);
570   PetscTryMethod(snes, "SNESCompositeSetType_C", (SNES, SNESCompositeType), (snes, type));
571   PetscFunctionReturn(PETSC_SUCCESS);
572 }
573 
574 /*@C
575   SNESCompositeAddSNES - Adds another `SNES` to the `SNESCOMPOSITE`
576 
577   Collective
578 
579   Input Parameters:
580 + snes - the `SNES` context of type `SNESCOMPOSITE`
581 - type - the `SNESType` of the new solver
582 
583   Level: developer
584 
585 .seealso: [](ch_snes), `SNES`, `SNESCOMPOSITE`, `SNESCompositeGetSNES()`
586 @*/
587 PetscErrorCode SNESCompositeAddSNES(SNES snes, SNESType type)
588 {
589   PetscFunctionBegin;
590   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
591   PetscTryMethod(snes, "SNESCompositeAddSNES_C", (SNES, SNESType), (snes, type));
592   PetscFunctionReturn(PETSC_SUCCESS);
593 }
594 
595 /*@
596   SNESCompositeGetSNES - Gets one of the `SNES` objects in the `SNES` of `SNESType` `SNESCOMPOSITE`
597 
598   Not Collective
599 
600   Input Parameters:
601 + snes - the `SNES` context
602 - n    - the number of the composed `SNES` requested
603 
604   Output Parameter:
605 . subsnes - the `SNES` requested
606 
607   Level: developer
608 
609 .seealso: [](ch_snes), `SNES`, `SNESCOMPOSITE`, `SNESCompositeAddSNES()`, `SNESCompositeGetNumber()`
610 @*/
611 PetscErrorCode SNESCompositeGetSNES(SNES snes, PetscInt n, SNES *subsnes)
612 {
613   PetscFunctionBegin;
614   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
615   PetscAssertPointer(subsnes, 3);
616   PetscUseMethod(snes, "SNESCompositeGetSNES_C", (SNES, PetscInt, SNES *), (snes, n, subsnes));
617   PetscFunctionReturn(PETSC_SUCCESS);
618 }
619 
620 /*@
621   SNESCompositeGetNumber - Get the number of subsolvers in the `SNESCOMPOSITE`
622 
623   Logically Collective
624 
625   Input Parameter:
626 . snes - the `SNES` context
627 
628   Output Parameter:
629 . n - the number of subsolvers
630 
631   Level: developer
632 
633 .seealso: [](ch_snes), `SNES`, `SNESCOMPOSITE`, `SNESCompositeAddSNES()`, `SNESCompositeGetSNES()`
634 @*/
635 PetscErrorCode SNESCompositeGetNumber(SNES snes, PetscInt *n)
636 {
637   SNES_Composite    *jac;
638   SNES_CompositeLink next;
639 
640   PetscFunctionBegin;
641   jac  = (SNES_Composite *)snes->data;
642   next = jac->head;
643 
644   *n = 0;
645   while (next) {
646     *n   = *n + 1;
647     next = next->next;
648   }
649   PetscFunctionReturn(PETSC_SUCCESS);
650 }
651 
652 static PetscErrorCode SNESCompositeSetDamping_Composite(SNES snes, PetscInt n, PetscReal dmp)
653 {
654   SNES_Composite    *jac;
655   SNES_CompositeLink next;
656   PetscInt           i;
657 
658   PetscFunctionBegin;
659   jac  = (SNES_Composite *)snes->data;
660   next = jac->head;
661   for (i = 0; i < n; i++) {
662     PetscCheck(next->next, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "Not enough SNESes in composite preconditioner");
663     next = next->next;
664   }
665   next->dmp = dmp;
666   PetscFunctionReturn(PETSC_SUCCESS);
667 }
668 
669 /*@
670   SNESCompositeSetDamping - Sets the damping of a subsolver when using `SNES_COMPOSITE_ADDITIVE` with a `SNES` of `SNESType` `SNESCOMPOSITE`
671 
672   Not Collective
673 
674   Input Parameters:
675 + snes - the `SNES` context
676 . n    - the number of the sub-`SNES` object requested
677 - dmp  - the damping
678 
679   Level: intermediate
680 
681 .seealso: [](ch_snes), `SNES`, `SNESCOMPOSITE`, `SNESCompositeAddSNES()`, `SNESCompositeGetSNES()`,
682           `SNES_COMPOSITE_ADDITIVE`, `SNES_COMPOSITE_MULTIPLICATIVE`, `SNESCompositeType`, `SNESCompositeSetType()`
683 @*/
684 PetscErrorCode SNESCompositeSetDamping(SNES snes, PetscInt n, PetscReal dmp)
685 {
686   PetscFunctionBegin;
687   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
688   PetscUseMethod(snes, "SNESCompositeSetDamping_C", (SNES, PetscInt, PetscReal), (snes, n, dmp));
689   PetscFunctionReturn(PETSC_SUCCESS);
690 }
691 
692 static PetscErrorCode SNESSolve_Composite(SNES snes)
693 {
694   Vec              F, X, B, Y;
695   PetscInt         i;
696   PetscReal        fnorm = 0.0, xnorm = 0.0, snorm = 0.0;
697   SNESNormSchedule normtype;
698   SNES_Composite  *comp = (SNES_Composite *)snes->data;
699 
700   PetscFunctionBegin;
701   X = snes->vec_sol;
702   F = snes->vec_func;
703   B = snes->vec_rhs;
704   Y = snes->vec_sol_update;
705 
706   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
707   snes->iter          = 0;
708   snes->norm          = 0.;
709   comp->innerFailures = 0;
710   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
711   snes->reason = SNES_CONVERGED_ITERATING;
712   PetscCall(SNESGetNormSchedule(snes, &normtype));
713   if (normtype == SNES_NORM_ALWAYS || normtype == SNES_NORM_INITIAL_ONLY || normtype == SNES_NORM_INITIAL_FINAL_ONLY) {
714     if (!snes->vec_func_init_set) {
715       PetscCall(SNESComputeFunction(snes, X, F));
716     } else snes->vec_func_init_set = PETSC_FALSE;
717 
718     if (snes->xl && snes->xu) {
719       PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, &fnorm));
720     } else {
721       PetscCall(VecNorm(F, NORM_2, &fnorm)); /* fnorm <- ||F||  */
722     }
723     SNESCheckFunctionNorm(snes, fnorm);
724     PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
725     snes->iter = 0;
726     snes->norm = fnorm;
727     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
728     PetscCall(SNESLogConvergenceHistory(snes, snes->norm, 0));
729 
730     /* test convergence */
731     PetscCall(SNESConverged(snes, 0, 0.0, 0.0, fnorm));
732     PetscCall(SNESMonitor(snes, 0, snes->norm));
733     if (snes->reason) PetscFunctionReturn(PETSC_SUCCESS);
734   } else {
735     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
736     PetscCall(SNESLogConvergenceHistory(snes, snes->norm, 0));
737     PetscCall(SNESMonitor(snes, 0, snes->norm));
738   }
739 
740   for (i = 0; i < snes->max_its; i++) {
741     /* Call general purpose update function */
742     PetscTryTypeMethod(snes, update, snes->iter);
743 
744     /* Copy the state before modification by application of the composite solver;
745        we will subtract the new state after application */
746     PetscCall(VecCopy(X, Y));
747 
748     if (comp->type == SNES_COMPOSITE_ADDITIVE) {
749       PetscCall(SNESCompositeApply_Additive(snes, X, B, F, &fnorm));
750     } else if (comp->type == SNES_COMPOSITE_MULTIPLICATIVE) {
751       PetscCall(SNESCompositeApply_Multiplicative(snes, X, B, F, &fnorm));
752     } else if (comp->type == SNES_COMPOSITE_ADDITIVEOPTIMAL) {
753       PetscCall(SNESCompositeApply_AdditiveOptimal(snes, X, B, F, &fnorm));
754     } else SETERRQ(PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "Unsupported SNESComposite type");
755     if (snes->reason < 0) break;
756 
757     /* Compute the solution update for convergence testing */
758     PetscCall(VecAYPX(Y, -1.0, X));
759 
760     if ((i == snes->max_its - 1) && (normtype == SNES_NORM_INITIAL_FINAL_ONLY || normtype == SNES_NORM_FINAL_ONLY)) {
761       PetscCall(SNESComputeFunction(snes, X, F));
762 
763       if (snes->xl && snes->xu) {
764         PetscCall(VecNormBegin(X, NORM_2, &xnorm));
765         PetscCall(VecNormBegin(Y, NORM_2, &snorm));
766         PetscCall(SNESVIComputeInactiveSetFnorm(snes, F, X, &fnorm));
767         PetscCall(VecNormEnd(X, NORM_2, &xnorm));
768         PetscCall(VecNormEnd(Y, NORM_2, &snorm));
769       } else {
770         PetscCall(VecNormBegin(F, NORM_2, &fnorm));
771         PetscCall(VecNormBegin(X, NORM_2, &xnorm));
772         PetscCall(VecNormBegin(Y, NORM_2, &snorm));
773 
774         PetscCall(VecNormEnd(F, NORM_2, &fnorm));
775         PetscCall(VecNormEnd(X, NORM_2, &xnorm));
776         PetscCall(VecNormEnd(Y, NORM_2, &snorm));
777       }
778       SNESCheckFunctionNorm(snes, fnorm);
779     } else if (normtype == SNES_NORM_ALWAYS) {
780       PetscCall(VecNormBegin(X, NORM_2, &xnorm));
781       PetscCall(VecNormBegin(Y, NORM_2, &snorm));
782       PetscCall(VecNormEnd(X, NORM_2, &xnorm));
783       PetscCall(VecNormEnd(Y, NORM_2, &snorm));
784     }
785     /* Monitor convergence */
786     PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
787     snes->iter  = i + 1;
788     snes->norm  = fnorm;
789     snes->xnorm = xnorm;
790     snes->ynorm = snorm;
791     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
792     PetscCall(SNESLogConvergenceHistory(snes, snes->norm, 0));
793     /* Test for convergence */
794     PetscCall(SNESConverged(snes, snes->iter, xnorm, snorm, fnorm));
795     PetscCall(SNESMonitor(snes, snes->iter, snes->norm));
796     if (snes->reason) break;
797   }
798   PetscFunctionReturn(PETSC_SUCCESS);
799 }
800 
801 /*MC
802      SNESCOMPOSITE - Builds a nonlinear solver/preconditioner by composing together several `SNES` nonlinear solvers {cite}`bruneknepleysmithtu15`
803 
804    Options Database Keys:
805 +  -snes_composite_type <type: one of multiplicative, additive, additiveoptimal> - Sets composite preconditioner type
806 -  -snes_composite_sneses - <snes0,snes1,...> list of `SNES` to compose
807 
808    Level: intermediate
809 
810 .seealso: [](ch_snes), `SNES`, `SNESCOMPOSITE`, `SNESCompositeAddSNES()`, `SNESCompositeGetSNES()`,
811           `SNES_COMPOSITE_ADDITIVE`, `SNES_COMPOSITE_ADDITIVEOPTIMAL`, `SNES_COMPOSITE_MULTIPLICATIVE`, `SNESCompositeType`,
812           `SNESCompositeSetType()`, `SNESCompositeSetDamping()`, `SNESCompositeGetNumber()`, `PCCompositeType`
813 M*/
814 
815 PETSC_EXTERN PetscErrorCode SNESCreate_Composite(SNES snes)
816 {
817   SNES_Composite *jac;
818 
819   PetscFunctionBegin;
820   PetscCall(PetscNew(&jac));
821 
822   snes->ops->solve          = SNESSolve_Composite;
823   snes->ops->setup          = SNESSetUp_Composite;
824   snes->ops->reset          = SNESReset_Composite;
825   snes->ops->destroy        = SNESDestroy_Composite;
826   snes->ops->setfromoptions = SNESSetFromOptions_Composite;
827   snes->ops->view           = SNESView_Composite;
828 
829   snes->usesksp = PETSC_FALSE;
830 
831   snes->alwayscomputesfinalresidual = PETSC_FALSE;
832 
833   snes->data  = (void *)jac;
834   jac->type   = SNES_COMPOSITE_ADDITIVEOPTIMAL;
835   jac->Fes    = NULL;
836   jac->Xes    = NULL;
837   jac->fnorms = NULL;
838   jac->nsnes  = 0;
839   jac->head   = NULL;
840   jac->stol   = 0.1;
841   jac->rtol   = 1.1;
842 
843   jac->h     = NULL;
844   jac->s     = NULL;
845   jac->beta  = NULL;
846   jac->work  = NULL;
847   jac->rwork = NULL;
848 
849   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeSetType_C", SNESCompositeSetType_Composite));
850   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeAddSNES_C", SNESCompositeAddSNES_Composite));
851   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeGetSNES_C", SNESCompositeGetSNES_Composite));
852   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESCompositeSetDamping_C", SNESCompositeSetDamping_Composite));
853   PetscFunctionReturn(PETSC_SUCCESS);
854 }
855