Actual source code: taotermsum.c

  1: #include <petsc/private/taoimpl.h>
  2: #include <../src/tao/term/impls/sum/taotermsum.h>
  3: #include <ctype.h>

  5: static const char *const TaoTermMasks[] = {"none", "objective", "gradient", "hessian", "TaoTermMask", "TAOTERM_MASK_", NULL};

  7: typedef struct _n_TaoTerm_Sum TaoTerm_Sum;

  9: typedef struct _n_TaoTermSumHessCache {
 10:   PetscObjectId    x_id;
 11:   PetscObjectId    p_id;
 12:   PetscObjectState x_state;
 13:   PetscObjectState p_state;
 14:   PetscInt         n_terms;
 15:   Mat             *hessians;
 16:   Vec             *Axs;
 17: } TaoTermSumHessCache;

 19: struct _n_TaoTerm_Sum {
 20:   PetscInt            n_terms;
 21:   TaoTermMapping     *terms;
 22:   PetscReal          *subterm_values;
 23:   TaoTermSumHessCache hessian_cache;
 24: };

 26: PETSC_INTERN PetscErrorCode TaoTermSumVecNestGetSubVecsRead(Vec params, PetscInt *n, Vec **subparams, PetscBool **is_dummy)
 27: {
 28:   PetscContainer is_dummy_container = NULL;

 30:   PetscFunctionBegin;
 31:   *is_dummy = NULL;
 32:   PetscCall(VecNestGetSubVecsRead(params, n, subparams));
 33:   PetscCall(PetscObjectQuery((PetscObject)params, "__TaoTermSumParametersPack", (PetscObject *)&is_dummy_container));
 34:   if (is_dummy_container) PetscCall(PetscContainerGetPointer(is_dummy_container, (void **)is_dummy));
 35:   PetscFunctionReturn(PETSC_SUCCESS);
 36: }

 38: PETSC_INTERN PetscErrorCode TaoTermSumVecNestRestoreSubVecsRead(Vec params, PetscInt *n, Vec **subparams, PetscBool **is_dummy)
 39: {
 40:   PetscFunctionBegin;
 41:   PetscCall(VecNestRestoreSubVecsRead(params, n, subparams));
 42:   PetscFunctionReturn(PETSC_SUCCESS);
 43: }

 45: static PetscErrorCode TaoTermSumHessCacheReset(TaoTermSumHessCache *cache)
 46: {
 47:   PetscFunctionBegin;
 48:   PetscCall(MatDestroyMatrices(cache->n_terms, &cache->hessians));
 49:   for (PetscInt i = 0; i < cache->n_terms; i++) PetscCall(VecDestroy(&cache->Axs[i]));
 50:   PetscCall(PetscFree(cache->Axs));
 51:   cache->n_terms = 0;
 52:   cache->x_id    = 0;
 53:   cache->p_id    = 0;
 54:   cache->x_state = 0;
 55:   cache->p_state = 0;
 56:   PetscFunctionReturn(PETSC_SUCCESS);
 57: }

 59: static PetscErrorCode TaoTermSumIsDummyDestroy(PetscCtxRt ctx)
 60: {
 61:   PetscFunctionBegin;
 62:   PetscCall(PetscFree(*(void **)ctx));
 63:   PetscFunctionReturn(PETSC_SUCCESS);
 64: }

 66: /*@
 67:   TaoTermSumParametersPack - Concatenate the parameters for terms into a `VECNEST` parameter vector for a `TAOTERMSUM`

 69:   Collective

 71:   Input Parameters:
 72: + term  - a `TaoTerm` of type `TAOTERMSUM`
 73: - p_arr - an array of parameters `Vec`s, one for each term in the sum.  An entry can be `NULL` for a term that doesn't take parameters.

 75:   Output Parameter:
 76: . params - a `Vec` of type `VECNEST` that concatenates all of the parameters

 78:   Level: developer

 80:   Note:
 81:   This is a wrapper around `VecCreateNest()`, but that function does not allow `NULL` for any of the `Vec`s in the array.  A 0-length
 82:   vector will be created for each `NULL` `Vec` that will be internally ignored by `TAOTERMSUM`.

 84: .seealso: [](sec_tao_term),
 85:           `TaoTerm`,
 86:           `TAOTERMSUM`,
 87:           `TaoTermSumParametersUnpack()`,
 88:           `VECNEST`,
 89:           `VecNestGetTaoTermSumParameters()`,
 90:           `VecCreateNest()`
 91: @*/
 92: PetscErrorCode TaoTermSumParametersPack(TaoTerm term, Vec p_arr[], Vec *params)
 93: {
 94:   PetscInt       n_terms;
 95:   Vec           *p;
 96:   PetscBool     *is_dummy;
 97:   PetscContainer is_dummy_container;

 99:   PetscFunctionBegin;
101:   PetscAssertPointer(p_arr, 2);
102:   PetscAssertPointer(params, 3);
103:   PetscCall(TaoTermSumGetNumberTerms(term, &n_terms));
104:   PetscCall(PetscMalloc1(n_terms, &p));
105:   PetscCall(PetscMalloc1(n_terms, &is_dummy));
106:   for (PetscInt i = 0; i < n_terms; i++) {
107:     if (p_arr[i]) {
109:       p[i]        = p_arr[i];
110:       is_dummy[i] = PETSC_FALSE;
111:     } else {
112:       TaoTerm               subterm;
113:       Vec                   dummy_vec;
114:       TaoTermParametersMode mode;
115:       VecType               vec_type = VECSTANDARD;
116:       PetscLayout           layout   = NULL;

118:       PetscCall(TaoTermSumGetTerm(term, i, NULL, NULL, &subterm, NULL));
119:       PetscCall(TaoTermGetParametersMode(subterm, &mode));
120:       if (mode != TAOTERM_PARAMETERS_NONE) {
121:         PetscCall(TaoTermGetParametersVecType(subterm, &vec_type));
122:         PetscCall(TaoTermGetParametersLayout(subterm, &layout));
123:         layout->refcnt++;
124:       } else {
125:         PetscCall(PetscLayoutCreate(PetscObjectComm((PetscObject)term), &layout));
126:         PetscCall(PetscLayoutSetLocalSize(layout, 0));
127:         PetscCall(PetscLayoutSetSize(layout, 0));
128:       }
129:       PetscCall(VecCreate(PetscObjectComm((PetscObject)term), &dummy_vec));
130:       PetscCall(VecSetLayout(dummy_vec, layout));
131:       PetscCall(PetscLayoutDestroy(&layout));
132:       PetscCall(VecSetType(dummy_vec, vec_type));
133:       is_dummy[i] = PETSC_TRUE;
134:       p[i]        = dummy_vec;
135:     }
136:   }
137:   PetscCall(VecCreateNest(PetscObjectComm((PetscObject)term), n_terms, NULL, p, params));
138:   for (PetscInt i = 0; i < n_terms; i++) {
139:     if (!p_arr[i]) PetscCall(VecDestroy(&p[i]));
140:   }
141:   PetscCall(PetscFree(p));
142:   PetscCall(PetscContainerCreate(PetscObjectComm((PetscObject)term), &is_dummy_container));
143:   PetscCall(PetscContainerSetPointer(is_dummy_container, (void *)is_dummy));
144:   PetscCall(PetscContainerSetCtxDestroy(is_dummy_container, TaoTermSumIsDummyDestroy));
145:   PetscCall(PetscObjectCompose((PetscObject)*params, "__TaoTermSumParametersPack", (PetscObject)is_dummy_container));
146:   PetscCall(PetscContainerDestroy(&is_dummy_container));
147:   PetscFunctionReturn(PETSC_SUCCESS);
148: }

150: /*@
151:   TaoTermSumParametersUnpack - Unpack the concatenated parameters created by `TaoTermSumParametersPack()` and destroy the `VECNEST`

153:   Collective

155:   Input Parameters:
156: + term   - a `TaoTerm` of type `TAOTERMSUM`
157: - params - a `Vec` created by `TaoTermSumParametersPack()`

159:   Output Parameter:
160: . p_arr - an array of parameters `Vec`s, one for each term in the sum.  An entry will be `NULL` if `NULL` was passed in the same position of `TaoTermSumParametersPack()`

162:   Level: intermediate

164: .seealso: [](sec_tao_term),
165:           `TaoTerm`,
166:           `TAOTERMSUM`,
167:           `TaoTermSumParametersPack()`,
168:           `VecNestGetTaoTermSumParameters()`
169: @*/
170: PetscErrorCode TaoTermSumParametersUnpack(TaoTerm term, Vec *params, Vec p_arr[])
171: {
172:   PetscInt       n_terms;
173:   PetscBool     *is_dummy           = NULL;
174:   PetscContainer is_dummy_container = NULL;

176:   PetscFunctionBegin;
179:   PetscAssertPointer(p_arr, 3);
180:   PetscCall(TaoTermSumGetNumberTerms(term, &n_terms));
181:   PetscCall(PetscObjectQuery((PetscObject)*params, "__TaoTermSumParametersPack", (PetscObject *)&is_dummy_container));
182:   if (is_dummy_container) PetscCall(PetscContainerGetPointer(is_dummy_container, (void **)&is_dummy));
183:   for (PetscInt i = 0; i < n_terms; i++) {
184:     Vec subparam;

186:     PetscCall(VecNestGetSubVec(*params, i, &subparam));
187:     if (is_dummy && is_dummy[i]) {
188:       p_arr[i] = NULL;
189:     } else {
190:       PetscCall(PetscObjectReference((PetscObject)subparam));
191:       p_arr[i] = subparam;
192:     }
193:   }
194:   PetscCall(VecDestroy(params));
195:   PetscFunctionReturn(PETSC_SUCCESS);
196: }

198: /*@
199:   VecNestGetTaoTermSumParameters - A wrapper around `VecNestGetSubVec()` for `TAOTERMSUM`.

201:   Not collective

203:   Input Parameters:
204: + params - a `VECNEST` that has one nested vector for each term of a `TAOTERMSUM`
205: - index  - the index of a term

207:   Output Parameter:
208: . subparams - the parameters of the internal terms of `TAOTERMSUM`. (may be `NULL`)

210:   Level: intermediate

212:   Note:
213:   `VecNestGetSubVec()` cannot return `NULL` for the subvec.  If `params` was
214:   created by `TaoTermSumParametersPack()`, then any `NULL` subvecs that were passed
215:   to that function will be returned `NULL` by this function.

217: .seealso: [](sec_tao_term),
218:           `TaoTerm`,
219:           `TAOTERMSUM`,
220:           `TaoTermSumParametersPack()`,
221:           `TaoTermSumParametersUnpack()`,
222:           `VECNEST`,
223:           `VecNestGetSubVec()`
224: @*/
225: PetscErrorCode VecNestGetTaoTermSumParameters(Vec params, PetscInt index, Vec *subparams)
226: {
227:   PetscBool     *is_dummy           = NULL;
228:   PetscContainer is_dummy_container = NULL;

230:   PetscFunctionBegin;
232:   PetscAssertPointer(subparams, 3);
233:   PetscCall(PetscObjectQuery((PetscObject)params, "__TaoTermSumParametersPack", (PetscObject *)&is_dummy_container));
234:   if (is_dummy_container) PetscCall(PetscContainerGetPointer(is_dummy_container, (void **)&is_dummy));
235:   if (is_dummy && is_dummy[index]) {
236:     *subparams = NULL;
237:   } else {
238:     PetscCall(VecNestGetSubVec(params, index, subparams));
239:   }
240:   PetscFunctionReturn(PETSC_SUCCESS);
241: }

243: static PetscErrorCode TaoTermDestroy_Sum(TaoTerm term)
244: {
245:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;

247:   PetscFunctionBegin;
248:   for (PetscInt i = 0; i < sum->n_terms; i++) PetscCall(TaoTermMappingReset(&sum->terms[i]));
249:   PetscCall(TaoTermSumHessCacheReset(&sum->hessian_cache));
250:   PetscCall(PetscFree(sum->terms));
251:   PetscCall(PetscFree(sum->subterm_values));
252:   PetscCall(PetscFree(sum));
253:   term->data = NULL;
254:   PetscCall(PetscObjectReference((PetscObject)term->parameters_factory_orig));
255:   PetscCall(MatDestroy(&term->parameters_factory));
256:   term->parameters_factory = term->parameters_factory_orig;
257:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetNumberTerms_C", NULL));
258:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetNumberTerms_C", NULL));
259:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTerm_C", NULL));
260:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTerm_C", NULL));
261:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumAddTerm_C", NULL));
262:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTermHessianMatrices_C", NULL));
263:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTermHessianMatrices_C", NULL));
264:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTermMask_C", NULL));
265:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTermMask_C", NULL));
266:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetLastTermObjectives_C", NULL));
267:   PetscFunctionReturn(PETSC_SUCCESS);
268: }

270: static PetscErrorCode TaoTermView_Sum_NameHasSpaces(const char name[], PetscBool *has_spaces)
271: {
272:   size_t n;

274:   PetscFunctionBegin;
275:   PetscCall(PetscStrlen(name, &n));
276:   for (size_t i = 0; i < n; i++) {
277:     if (isspace((unsigned char)name[i])) {
278:       *has_spaces = PETSC_TRUE;
279:       PetscFunctionReturn(PETSC_SUCCESS);
280:     }
281:   }
282:   *has_spaces = PETSC_FALSE;
283:   PetscFunctionReturn(PETSC_SUCCESS);
284: }

286: static PetscErrorCode TaoTermViewSumPrintSubtermName(PetscViewer viewer, TaoTerm subterm, PetscInt i, const char f[], PetscBool colon_newline)
287: {
288:   const char *subterm_prefix;
289:   const char *subterm_name = NULL;

291:   PetscFunctionBegin;
292:   if (((PetscObject)subterm)->name) PetscCall(PetscObjectGetName((PetscObject)subterm, &subterm_name));
293:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)subterm, &subterm_prefix));
294:   if (subterm_name) {
295:     PetscBool same;

297:     PetscCall(PetscStrncmp(subterm_name, "TaoTerm_", 8, &same));
298:     if (same == PETSC_FALSE) {
299:       PetscBool has_spaces;

301:       PetscCall(TaoTermView_Sum_NameHasSpaces(subterm_name, &has_spaces));
302:       if (has_spaces) PetscCall(PetscViewerASCIIPrintf(viewer, "%s_{%s}%s", f, subterm_name, colon_newline ? ":\n" : ""));
303:       else PetscCall(PetscViewerASCIIPrintf(viewer, "%s%s", subterm_name, colon_newline ? ":\n" : ""));
304:       PetscFunctionReturn(PETSC_SUCCESS);
305:     }
306:   }
307:   if (subterm_prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "%s_{%s}%s", f, subterm_prefix, colon_newline ? ":\n" : ""));
308:   else PetscCall(PetscViewerASCIIPrintf(viewer, "%s_%" PetscInt_FMT "%s", f, i, colon_newline ? ":\n" : ""));
309:   PetscFunctionReturn(PETSC_SUCCESS);
310: }

312: PETSC_INTERN PetscErrorCode TaoTermViewSumPrintMapName(PetscViewer viewer, Mat map, PetscInt i, const char A[], PetscBool colon_newline)
313: {
314:   const char *map_prefix;
315:   const char *map_name = NULL;

317:   PetscFunctionBegin;
318:   if (((PetscObject)map)->name) PetscCall(PetscObjectGetName((PetscObject)map, &map_name));
319:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)map, &map_prefix));
320:   if (map_name) {
321:     PetscBool same;

323:     PetscCall(PetscStrncmp(map_name, "Mat_", 4, &same));
324:     if (same == PETSC_FALSE) {
325:       PetscBool has_spaces;

327:       PetscCall(TaoTermView_Sum_NameHasSpaces(map_name, &has_spaces));
328:       if (has_spaces) PetscCall(PetscViewerASCIIPrintf(viewer, "%s_{%s}%s", A, map_name, colon_newline ? ":\n" : ""));
329:       else PetscCall(PetscViewerASCIIPrintf(viewer, "%s%s", map_name, colon_newline ? ":\n" : ""));
330:       PetscFunctionReturn(PETSC_SUCCESS);
331:     }
332:   }
333:   if (map_prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "%s_{%s}%s", A, map_prefix, colon_newline ? ":\n" : ""));
334:   else PetscCall(PetscViewerASCIIPrintf(viewer, "%s_%" PetscInt_FMT "%s", A, i, colon_newline ? ":\n" : ""));
335:   PetscFunctionReturn(PETSC_SUCCESS);
336: }

338: PETSC_INTERN PetscErrorCode TaoTermViewSumPrintSubterm(TaoTerm term, PetscViewer viewer, Vec params, PetscInt i, PetscBool initial, PetscBool print_map, const char f[], const char A[], const char x[], const char p[])
339: {
340:   PetscReal             scale;
341:   TaoTerm               subterm;
342:   Mat                   map;
343:   TaoTermParametersMode pmode;

345:   PetscFunctionBegin;
346:   PetscCall(TaoTermSumGetTerm(term, i, NULL, &scale, &subterm, &map));
347:   if (scale == 1.0) PetscCall(PetscViewerASCIIPrintf(viewer, "%s", initial ? "" : " + "));
348:   else if (initial) PetscCall(PetscViewerASCIIPrintf(viewer, "%g ", (double)scale));
349:   else PetscCall(PetscViewerASCIIPrintf(viewer, " %s %g ", scale >= 0.0 ? "+" : "-", (double)PetscAbsReal(scale)));
350:   PetscCall(TaoTermViewSumPrintSubtermName(viewer, subterm, i, f, PETSC_FALSE));
351:   PetscCall(PetscViewerASCIIPrintf(viewer, "("));
352:   if (print_map && map) {
353:     PetscCall(TaoTermViewSumPrintMapName(viewer, map, i, A, PETSC_FALSE));
354:     PetscCall(PetscViewerASCIIPrintf(viewer, " "));
355:   }
356:   PetscCall(PetscViewerASCIIPrintf(viewer, "%s", x));
357:   PetscCall(TaoTermGetParametersMode(subterm, &pmode));
358:   switch (pmode) {
359:   case TAOTERM_PARAMETERS_NONE:
360:     break;
361:   case TAOTERM_PARAMETERS_OPTIONAL:
362:     PetscCall(PetscViewerASCIIPrintf(viewer, "; [p_%" PetscInt_FMT "]", i));
363:     break;
364:   case TAOTERM_PARAMETERS_REQUIRED:
365:     PetscCall(PetscViewerASCIIPrintf(viewer, "; p_%" PetscInt_FMT, i));
366:     break;
367:   }
368:   PetscCall(PetscViewerASCIIPrintf(viewer, ")"));
369:   PetscFunctionReturn(PETSC_SUCCESS);
370: }

372: static PetscErrorCode TaoTermView_Sum_ASCII_INFO(TaoTerm term, PetscViewer viewer)
373: {
374:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;

376:   PetscFunctionBegin;
377:   PetscCall(PetscViewerASCIIPrintf(viewer, "Sum of %" PetscInt_FMT " terms:%s", sum->n_terms, sum->n_terms > 0 ? " " : ""));
378:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
379:   for (PetscInt i = 0; i < sum->n_terms; i++) PetscCall(TaoTermViewSumPrintSubterm(term, viewer, NULL, i, (i == 0) ? PETSC_TRUE : PETSC_FALSE, PETSC_TRUE, "f", "A", "x", "p"));
380:   PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
381:   PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
382:   for (PetscInt i = 0; i < sum->n_terms; i++) {
383:     Mat     map;
384:     TaoTerm subterm;

386:     PetscCall(TaoTermSumGetTerm(term, i, NULL, NULL, &subterm, &map));
387:     PetscCall(TaoTermViewSumPrintSubtermName(viewer, subterm, i, "f", PETSC_TRUE));
388:     PetscCall(PetscViewerASCIIPushTab(viewer));
389:     PetscCall(TaoTermView(subterm, viewer));
390:     PetscCall(PetscViewerASCIIPopTab(viewer));
391:     if (map == NULL) continue;
392:     PetscCall(TaoTermViewSumPrintMapName(viewer, map, i, "A", PETSC_TRUE));
393:     PetscCall(PetscViewerASCIIPushTab(viewer));
394:     PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
395:     PetscCall(MatView(map, viewer));
396:     PetscCall(PetscViewerPopFormat(viewer));
397:     PetscCall(PetscViewerASCIIPopTab(viewer));
398:   }
399:   PetscFunctionReturn(PETSC_SUCCESS);
400: }

402: static PetscErrorCode TaoTermView_Sum(TaoTerm term, PetscViewer viewer)
403: {
404:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;
405:   PetscBool    iascii;

407:   PetscFunctionBegin;
408:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
409:   if (iascii) {
410:     PetscViewerFormat format;

412:     PetscCall(PetscViewerGetFormat(viewer, &format));
413:     if (sum->n_terms <= 3 && format != PETSC_VIEWER_ASCII_INFO_DETAIL) {
414:       PetscCall(TaoTermView_Sum_ASCII_INFO(term, viewer));
415:       PetscFunctionReturn(PETSC_SUCCESS);
416:     }
417:     PetscCall(PetscViewerASCIIPrintf(viewer, "Sum of %" PetscInt_FMT " terms:\n", sum->n_terms));
418:     PetscCall(PetscViewerASCIIPushTab(viewer));
419:     for (PetscInt i = 0; i < sum->n_terms; i++) {
420:       PetscReal   scale;
421:       const char *subprefix;
422:       TaoTerm     subterm;
423:       Mat         map;
424:       TaoTermMask mask;

426:       PetscCall(TaoTermSumGetTerm(term, i, &subprefix, &scale, &subterm, &map));

428:       PetscCall(PetscViewerASCIIPrintf(viewer, "Summand %" PetscInt_FMT ":\n", i));
429:       PetscCall(PetscViewerASCIIPushTab(viewer));

431:       if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerASCIIPrintf(viewer, "Scale (tao_term_sum_%sscale): %g\n", subprefix, (double)scale));
432:       else PetscCall(PetscViewerASCIIPrintf(viewer, "Scale: %g\n", (double)scale));
433:       PetscCall(PetscViewerASCIIPrintf(viewer, "Term:\n"));
434:       PetscCall(PetscViewerASCIIPushTab(viewer));
435:       PetscCall(TaoTermView(subterm, viewer));
436:       PetscCall(PetscViewerASCIIPopTab(viewer));
437:       if (format == PETSC_VIEWER_ASCII_INFO_DETAIL && map == NULL) PetscCall(PetscViewerASCIIPrintf(viewer, "Map: unmapped\n"));
438:       else if (map != NULL) {
439:         PetscCall(PetscViewerASCIIPrintf(viewer, "Map:\n"));
440:         PetscCall(PetscViewerASCIIPushTab(viewer));
441:         PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
442:         PetscCall(MatView(map, viewer));
443:         PetscCall(PetscViewerPopFormat(viewer));
444:         PetscCall(PetscViewerASCIIPopTab(viewer));
445:       }
446:       PetscCall(TaoTermSumGetTermMask(term, i, &mask));
447:       if (format == PETSC_VIEWER_ASCII_INFO_DETAIL && mask != TAOTERM_MASK_NONE) {
448:         PetscBool preceding = PETSC_FALSE;

450:         PetscCall(PetscViewerASCIIPrintf(viewer, "Mask (tao_term_sum_%smask): ", subprefix));
451:         PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
452:         if (TaoTermObjectiveMasked(mask)) {
453:           PetscCall(PetscViewerASCIIPrintf(viewer, "objective"));
454:           preceding = PETSC_TRUE;
455:         }
456:         if (TaoTermGradientMasked(mask)) {
457:           PetscCall(PetscViewerASCIIPrintf(viewer, "%sgradient", preceding ? ", " : ""));
458:           preceding = PETSC_TRUE;
459:         }
460:         if (TaoTermHessianMasked(mask)) PetscCall(PetscViewerASCIIPrintf(viewer, "%shessian", preceding ? ", " : ""));
461:         PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
462:         PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
463:       }

465:       PetscCall(PetscViewerASCIIPopTab(viewer));
466:     }
467:     PetscCall(PetscViewerASCIIPopTab(viewer));
468:   }
469:   PetscFunctionReturn(PETSC_SUCCESS);
470: }

472: /*@
473:   TaoTermSumSetNumberTerms - Set the number of terms in the sum

475:   Collective

477:   Input Parameters:
478: + term    - a `TaoTerm` of type `TAOTERMSUM`
479: - n_terms - the number of terms that will be in the sum

481:   Level: developer

483:   Note:
484:   If `n_terms` is smaller than the current number of terms, the trailing terms will be dropped.

486: .seealso: [](sec_tao_term),
487:           `TaoTerm`,
488:           `TAOTERMSUM`,
489:           `TaoTermSumGetNumberTerms()`
490: @*/
491: PetscErrorCode TaoTermSumSetNumberTerms(TaoTerm term, PetscInt n_terms)
492: {
493:   PetscFunctionBegin;
496:   PetscTryMethod(term, "TaoTermSumSetNumberTerms_C", (TaoTerm, PetscInt), (term, n_terms));
497:   PetscFunctionReturn(PETSC_SUCCESS);
498: }

500: static PetscErrorCode TaoTermSumSetNumberTerms_Sum(TaoTerm term, PetscInt n_terms)
501: {
502:   TaoTerm_Sum    *sum         = (TaoTerm_Sum *)term->data;
503:   PetscInt        n_terms_old = sum->n_terms;
504:   PetscReal      *new_values;
505:   TaoTermMapping *new_summands;

507:   PetscFunctionBegin;
508:   if (n_terms == n_terms_old) PetscFunctionReturn(PETSC_SUCCESS);
509:   for (PetscInt i = n_terms; i < n_terms_old; i++) PetscCall(TaoTermMappingReset(&sum->terms[i]));
510:   PetscCall(PetscMalloc1(n_terms, &new_summands));
511:   PetscCall(PetscCalloc1(n_terms, &new_values));
512:   PetscCall(PetscArraycpy(new_summands, sum->terms, PetscMin(n_terms, n_terms_old)));
513:   PetscCall(PetscArrayzero(&new_summands[n_terms_old], PetscMax(0, n_terms - n_terms_old)));
514:   PetscCall(PetscFree(sum->terms));
515:   PetscCall(PetscFree(sum->subterm_values));
516:   sum->terms          = new_summands;
517:   sum->subterm_values = new_values;
518:   sum->n_terms        = n_terms;
519:   for (PetscInt i = n_terms_old; i < n_terms; i++) PetscCall(TaoTermSumSetTerm(term, i, NULL, 1.0, NULL, NULL));
520:   PetscFunctionReturn(PETSC_SUCCESS);
521: }

523: /*@
524:   TaoTermSumGetNumberTerms - Get the number of terms in the sum

526:   Not collective

528:   Input Parameter:
529: . term - a `TaoTerm` of type `TAOTERMSUM`

531:   Output Parameter:
532: . n_terms - the number of terms that will be in the sum

534:   Level: developer

536: .seealso: [](sec_tao_term),
537:           `TaoTerm`,
538:           `TAOTERMSUM`,
539:           `TaoTermSumSetNumberTerms()`
540: @*/
541: PetscErrorCode TaoTermSumGetNumberTerms(TaoTerm term, PetscInt *n_terms)
542: {
543:   PetscFunctionBegin;
545:   PetscAssertPointer(n_terms, 2);
546:   PetscUseMethod(term, "TaoTermSumGetNumberTerms_C", (TaoTerm, PetscInt *), (term, n_terms));
547:   PetscFunctionReturn(PETSC_SUCCESS);
548: }

550: static PetscErrorCode TaoTermSumGetNumberTerms_Sum(TaoTerm term, PetscInt *n_terms)
551: {
552:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;

554:   PetscFunctionBegin;
555:   *n_terms = sum->n_terms;
556:   PetscFunctionReturn(PETSC_SUCCESS);
557: }

559: /*@
560:   TaoTermSumGetTerm - Get the data for a term in a `TAOTERMSUM`

562:   Not collective

564:   Input Parameters:
565: + sumterm - a `TaoTerm` of type `TAOTERMSUM`
566: - index   - a number $0 \leq i < n$, where $n$ is the number of terms in `TaoTermSumGetNumberTerms()`

568:   Output Parameters:
569: + prefix - (optional) the prefix used for configuring the term
570: . scale  - (optional) the coefficient scaling the term in the sum
571: . term   - the `TaoTerm` at given index of `TAOTERMSUM`
572: - map    - (optional) a map from the `TAOTERMSUM` solution space to the `term` solution space; if `NULL` the map is assumed to be the identity

574:   Level: developer

576: .seealso: [](sec_tao_term),
577:           `TaoTerm`,
578:           `TAOTERMSUM`,
579:           `TaoTermSumSetTerm()`,
580:           `TaoTermSumAddTerm()`
581: @*/
582: PetscErrorCode TaoTermSumGetTerm(TaoTerm sumterm, PetscInt index, const char *prefix[], PetscReal *scale, TaoTerm *term, Mat *map)
583: {
584:   PetscFunctionBegin;
587:   if (prefix) PetscAssertPointer(prefix, 3);
588:   if (term) PetscAssertPointer(term, 5);
589:   if (scale) PetscAssertPointer(scale, 4);
590:   if (map) PetscAssertPointer(map, 6);
591:   PetscUseMethod(sumterm, "TaoTermSumGetTerm_C", (TaoTerm, PetscInt, const char **, PetscReal *, TaoTerm *, Mat *), (sumterm, index, prefix, scale, term, map));
592:   PetscFunctionReturn(PETSC_SUCCESS);
593: }

595: static PetscErrorCode TaoTermSumGetTerm_Sum(TaoTerm term, PetscInt index, const char **prefix, PetscReal *scale, TaoTerm *subterm, Mat *map)
596: {
597:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
598:   TaoTermMapping *summand;

600:   PetscFunctionBegin;
601:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
602:   summand = &sum->terms[index];
603:   PetscCall(TaoTermMappingGetData(summand, prefix, scale, subterm, map));
604:   PetscFunctionReturn(PETSC_SUCCESS);
605: }

607: /*@
608:   TaoTermSumSetTerm - Set a term in a sum of terms

610:   Collective

612:   Input Parameters:
613: + sumterm - a `TaoTerm` of type `TAOTERMSUM`
614: . index   - a number $0 \leq i < n$, where $n$ is the number of terms in `TaoTermSumSetNumberTerms()`
615: . prefix  - (optional) the prefix used for configuring the term (if `NULL`, `term_x_` will be the prefix, e.g. "term_0_", "term_1_", etc.)
616: . scale   - the coefficient scaling the term in the sum
617: . term    - the `TaoTerm` to be set in `TAOTERMSUM`
618: - map     - (optional) a map from the `TAOTERMSUM` solution space to the `term` solution space; if `NULL` the map is assumed to be the identity

620:   Level: developer

622: .seealso: [](sec_tao_term),
623:           `TaoTerm`,
624:           `TAOTERMSUM`,
625:           `TaoTermSumGetTerm()`,
626:           `TaoTermSumAddTerm()`
627: @*/
628: PetscErrorCode TaoTermSumSetTerm(TaoTerm sumterm, PetscInt index, const char prefix[], PetscReal scale, TaoTerm term, Mat map)
629: {
630:   PetscFunctionBegin;
633:   if (prefix) PetscAssertPointer(prefix, 3);
637:   PetscTryMethod(sumterm, "TaoTermSumSetTerm_C", (TaoTerm, PetscInt, const char[], PetscReal, TaoTerm, Mat), (sumterm, index, prefix, scale, term, map));
638:   PetscFunctionReturn(PETSC_SUCCESS);
639: }

641: static PetscErrorCode TaoTermSumSetTerm_Sum(TaoTerm term, PetscInt index, const char prefix[], PetscReal scale, TaoTerm subterm, Mat map)
642: {
643:   char            subterm_x_[256];
644:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
645:   TaoTermMapping *summand;

647:   PetscFunctionBegin;
648:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
649:   summand = &sum->terms[index];
650:   if (prefix == NULL) {
651:     PetscCall(PetscSNPrintf(subterm_x_, 256, "term_%" PetscInt_FMT "_", index));
652:     prefix = subterm_x_;
653:   }
654:   PetscCall(TaoTermMappingSetData(summand, prefix, scale, subterm, map));
655:   PetscFunctionReturn(PETSC_SUCCESS);
656: }

658: /*@
659:   TaoTermSumSetTermHessianMatrices - Set Hessian matrices that can be used internally by a `TAOTERMSUM`

661:   Logically collective

663:   Input Parameters:
664: + term          - a `TaoTerm` of type `TAOTERMSUM`
665: . index         - the index for the term from `TaoTermSumSetTerm()` or `TaoTermSumAddTerm()`
666: . unmapped_H    - (optional) unmapped Hessian matrix
667: . unmapped_Hpre - (optional) unmapped matrix for constructing the preconditioner of `unmapped_H`
668: . mapped_H      - (optional) Hessian matrix
669: - mapped_Hpre   - (optional) matrix for constructing the preconditioner of `mapped_H`

671:   Level: developer

673:   Notes:
674:   If the inner term has the form $g(x) = \alpha f(Ax; p)$, the "mapped" Hessians should be able to hold the Hessian
675:   $\nabla^2 g$ and the unmapped Hessians should be able to hold the Hessian $\nabla_x^2 f$.  If the term is not mapped,
676:   just pass the unmapped Hessians (e.g. `TaoTermSumSetTermHessianMatrices(term, 0, H, Hpre, NULL, NULL)`).

678: .seealso: [](sec_tao_term),
679:           `TaoTerm`,
680:           `TAOTERMSUM`,
681:           `TaoTermComputeHessian()`,
682:           `TaoTermSumGetTermHessianMatrices()`
683: @*/
684: PetscErrorCode TaoTermSumSetTermHessianMatrices(TaoTerm term, PetscInt index, Mat unmapped_H, Mat unmapped_Hpre, Mat mapped_H, Mat mapped_Hpre)
685: {
686:   PetscFunctionBegin;
693:   PetscTryMethod(term, "TaoTermSumSetTermHessianMatrices_C", (TaoTerm, PetscInt, Mat, Mat, Mat, Mat), (term, index, unmapped_H, unmapped_Hpre, mapped_H, mapped_Hpre));
694:   PetscFunctionReturn(PETSC_SUCCESS);
695: }

697: static PetscErrorCode TaoTermSumSetTermHessianMatrices_Sum(TaoTerm term, PetscInt index, Mat unmapped_H, Mat unmapped_Hpre, Mat mapped_H, Mat mapped_Hpre)
698: {
699:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
700:   TaoTermMapping *summand;
701:   PetscBool       is_callback;

703:   PetscFunctionBegin;
704:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
705:   summand = &sum->terms[index];

707:   PetscCall(PetscObjectTypeCompare((PetscObject)summand->term, TAOTERMCALLBACKS, &is_callback));
708:   if (is_callback) {
709:     MatType   H_type, Hpre_type;
710:     PetscBool Hpre_is_H;

712:     Hpre_is_H = (mapped_H == mapped_Hpre) ? PETSC_TRUE : PETSC_FALSE;

714:     if (mapped_H) PetscCall(MatGetType(mapped_H, &H_type));
715:     else H_type = NULL;
716:     if (mapped_Hpre) PetscCall(MatGetType(mapped_Hpre, &Hpre_type));
717:     else Hpre_type = NULL;
718:     PetscCall(TaoTermSetCreateHessianMode(summand->term, Hpre_is_H, H_type, Hpre_type));
719:   }

721:   PetscCall(PetscObjectReference((PetscObject)unmapped_H));
722:   PetscCall(MatDestroy(&summand->_unmapped_H));
723:   summand->_unmapped_H = unmapped_H;

725:   PetscCall(PetscObjectReference((PetscObject)unmapped_Hpre));
726:   PetscCall(MatDestroy(&summand->_unmapped_Hpre));
727:   summand->_unmapped_Hpre = unmapped_Hpre;

729:   PetscCall(PetscObjectReference((PetscObject)mapped_H));
730:   PetscCall(MatDestroy(&summand->_mapped_H));
731:   summand->_mapped_H = mapped_H;

733:   PetscCall(PetscObjectReference((PetscObject)mapped_Hpre));
734:   PetscCall(MatDestroy(&summand->_mapped_Hpre));
735:   summand->_mapped_Hpre = mapped_Hpre;
736:   PetscFunctionReturn(PETSC_SUCCESS);
737: }

739: /*@
740:   TaoTermSumGetTermHessianMatrices - Get Hessian matrices set with `TaoTermSumSetTermHessianMatrices()`.

742:   Not collective

744:   Input Parameters:
745: + term  - a `TaoTerm` of type `TAOTERMSUM`
746: - index - the index for the term from `TaoTermSumSetTerm()` or `TaoTermSumAddTerm()`

748:   Output Parameters:
749: + unmapped_H    - (optional) unmapped Hessian matrix
750: . unmapped_Hpre - (optional) unmapped matrix for constructing the preconditioner for `unmapped_H`
751: . mapped_H      - (optional) Hessian matrix
752: - mapped_Hpre   - (optional) matrix for constructing the preconditioner for `mapped_H`

754:   Level: developer

756: .seealso: [](sec_tao_term),
757:           `TaoTerm`,
758:           `TAOTERMSUM`,
759:           `TaoTermComputeHessian()`,
760:           `TaoTermSumSetTermHessianMatrices()`
761: @*/
762: PetscErrorCode TaoTermSumGetTermHessianMatrices(TaoTerm term, PetscInt index, Mat *unmapped_H, Mat *unmapped_Hpre, Mat *mapped_H, Mat *mapped_Hpre)
763: {
764:   PetscFunctionBegin;
766:   if (unmapped_H) PetscAssertPointer(unmapped_H, 3);
767:   if (unmapped_Hpre) PetscAssertPointer(unmapped_Hpre, 4);
768:   if (mapped_H) PetscAssertPointer(mapped_H, 5);
769:   if (mapped_Hpre) PetscAssertPointer(mapped_Hpre, 6);
770:   PetscTryMethod(term, "TaoTermSumGetTermHessianMatrices_C", (TaoTerm, PetscInt, Mat *, Mat *, Mat *, Mat *), (term, index, unmapped_H, unmapped_Hpre, mapped_H, mapped_Hpre));
771:   PetscFunctionReturn(PETSC_SUCCESS);
772: }

774: static PetscErrorCode TaoTermSumGetTermHessianMatrices_Sum(TaoTerm term, PetscInt index, Mat *unmapped_H, Mat *unmapped_Hpre, Mat *mapped_H, Mat *mapped_Hpre)
775: {
776:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
777:   TaoTermMapping *summand;

779:   PetscFunctionBegin;
780:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
781:   summand = &sum->terms[index];

783:   if (unmapped_H) *unmapped_H = summand->_unmapped_H;
784:   if (unmapped_Hpre) *unmapped_Hpre = summand->_unmapped_Hpre;
785:   if (mapped_H) *mapped_H = summand->_mapped_H;
786:   if (mapped_Hpre) *mapped_Hpre = summand->_mapped_Hpre;
787:   PetscFunctionReturn(PETSC_SUCCESS);
788: }

790: /*@
791:   TaoTermSumGetTermMask - Get the `TaoTermMask` of a term in the sum

793:   Not collective

795:   Input Parameters:
796: + term  - a `TaoTerm` of type `TAOTERMSUM`
797: - index - the index for the term from `TaoTermSumSetTerm()` or `TaoTermSumAddTerm()`

799:   Output Parameter:
800: . mask - a bitmask of `TaoTermMask` evaluation methods to mask (e.g. just `TAOTERM_MASK_OBJECTIVE` or a bitwise-or like `TAOTERM_MASK_OBJECTIVE | TAOTERM_MASK_GRADIENT`)

802:   Level: developer

804: .seealso: [](sec_tao_term),
805:           `TaoTerm`,
806:           `TAOTERMSUM`,
807:           `TaoTermSumSetTermMask()`
808: @*/
809: PetscErrorCode TaoTermSumGetTermMask(TaoTerm term, PetscInt index, TaoTermMask *mask)
810: {
811:   PetscFunctionBegin;
813:   PetscAssertPointer(mask, 3);
814:   PetscUseMethod(term, "TaoTermSumGetTermMask_C", (TaoTerm, PetscInt, TaoTermMask *), (term, index, mask));
815:   PetscFunctionReturn(PETSC_SUCCESS);
816: }

818: static PetscErrorCode TaoTermSumGetTermMask_Sum(TaoTerm term, PetscInt index, TaoTermMask *mask)
819: {
820:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
821:   TaoTermMapping *summand;

823:   PetscFunctionBegin;
824:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
825:   summand = &sum->terms[index];
826:   *mask   = summand->mask;
827:   PetscFunctionReturn(PETSC_SUCCESS);
828: }

830: /*@
831:   TaoTermSumSetTermMask - Set a `TaoTermMask` on a term in the sum

833:   Logically collective

835:   Input Parameters:
836: + term  - a `TaoTerm` of type `TAOTERMSUM`
837: . index - the index for the term from `TaoTermSumSetTerm()` or `TaoTermSumAddTerm()`
838: - mask  - a bitmask of `TaoTermMask` evaluation methods to mask (e.g. just `TAOTERM_MASK_OBJECTIVE` or a bitwise-or like `TAOTERM_MASK_OBJECTIVE | TAOTERM_MASK_GRADIENT`)

840:   Options Database Keys:
841: . -tao_term_sum_<prefix_>mask - a list containing any of `none`, `objective`, `gradient`, and `hessian` to indicate which evaluations to mask for a term with a given prefix (see `TaoTermSumSetTerm()`)

843:   Level: developer

845:   Note:
846:   Some optimization methods may add a damping term to the Hessian of an
847:   objective function without affecting the objective or gradient.  If, e.g.,
848:   the regularizer has index `1`, then this can be accomplished with
849:   `TaoTermSumSetTermMask(term, 1, TAOTERM_MASK_OBJECTIVE | TAOTERM_MASK_GRADIENT)`.

851: .seealso: [](sec_tao_term),
852:           `TaoTerm`,
853:           `TAOTERMSUM`,
854:           `TaoTermSumGetTermMask()`
855: @*/
856: PetscErrorCode TaoTermSumSetTermMask(TaoTerm term, PetscInt index, TaoTermMask mask)
857: {
858:   PetscFunctionBegin;
861:   PetscTryMethod(term, "TaoTermSumSetTermMask_C", (TaoTerm, PetscInt, TaoTermMask), (term, index, mask));
862:   PetscFunctionReturn(PETSC_SUCCESS);
863: }

865: static PetscErrorCode TaoTermSumSetTermMask_Sum(TaoTerm term, PetscInt index, TaoTermMask mask)
866: {
867:   TaoTerm_Sum    *sum = (TaoTerm_Sum *)term->data;
868:   TaoTermMapping *summand;

870:   PetscFunctionBegin;
871:   PetscCheck(index >= 0 && index < sum->n_terms, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Index %" PetscInt_FMT " is not in [0, %" PetscInt_FMT ")", index, sum->n_terms);
872:   summand       = &sum->terms[index];
873:   summand->mask = mask;
874:   PetscFunctionReturn(PETSC_SUCCESS);
875: }

877: /*@
878:   TaoTermSumAddTerm - Append a term to the terms being summed

880:   Collective

882:   Input Parameters:
883: + sumterm - a `TaoTerm` of type `TAOTERMSUM`
884: . prefix  - (optional) the prefix used for configuring the term (if `NULL`, the index of the term will be used as a prefix, e.g. `term_0_`, `term_1_`, etc.)
885: . scale   - the coefficient scaling the term in the sum
886: . term    - the `TaoTerm` to add
887: - map     - (optional) a map from the `TAOTERMSUM` solution space to the `term` solution space; if `NULL` the map is assumed to be the identity

889:   Output Parameter:
890: . index - (optional) the index of the newly added term

892:   Level: developer

894: .seealso: [](sec_tao_term), `TaoTerm`, `TAOTERMSUM`
895: @*/
896: PetscErrorCode TaoTermSumAddTerm(TaoTerm sumterm, const char prefix[], PetscReal scale, TaoTerm term, Mat map, PetscInt *index)
897: {
898:   PetscFunctionBegin;
900:   if (prefix) PetscAssertPointer(prefix, 2);
904:   if (index) PetscAssertPointer(index, 6);
905:   PetscTryMethod(sumterm, "TaoTermSumAddTerm_C", (TaoTerm, const char[], PetscReal, TaoTerm, Mat, PetscInt *), (sumterm, prefix, scale, term, map, index));
906:   PetscFunctionReturn(PETSC_SUCCESS);
907: }

909: static PetscErrorCode TaoTermSumAddTerm_Sum(TaoTerm term, const char prefix[], PetscReal scale, TaoTerm subterm, Mat map, PetscInt *index)
910: {
911:   PetscInt n_terms_old;

913:   PetscFunctionBegin;
914:   PetscCall(TaoTermSumGetNumberTerms(term, &n_terms_old));
915:   PetscCall(TaoTermSumSetNumberTerms(term, n_terms_old + 1));
916:   PetscCall(TaoTermSumSetTerm(term, n_terms_old, prefix, scale, subterm, map));
917:   if (index) *index = n_terms_old;
918:   PetscFunctionReturn(PETSC_SUCCESS);
919: }

921: static PetscErrorCode TaoTermSetFromOptions_Sum(TaoTerm term, PetscOptionItems PetscOptionsObject)
922: {
923:   PetscInt    n_terms;
924:   const char *prefix;

926:   PetscFunctionBegin;
927:   PetscCall(TaoTermSumGetNumberTerms(term, &n_terms));
928:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)term, &prefix));
929:   PetscOptionsHeadBegin(PetscOptionsObject, "TaoTerm sum options");
930:   PetscCall(PetscOptionsBoundedInt("-tao_term_sum_number_terms", "The number of terms in the sum", "TaoTermSumSetNumberTerms", n_terms, &n_terms, NULL, 0));
931:   PetscCall(TaoTermSumSetNumberTerms(term, n_terms));
932:   for (PetscInt i = 0; i < n_terms; i++) {
933:     const char *subprefix;
934:     Mat         map;
935:     PetscReal   scale;
936:     TaoTerm     subterm;
937:     char        arg[256];
938:     PetscBool   flg;
939:     PetscEnum   masks[4] = {ENUM_DUMMY, ENUM_DUMMY, ENUM_DUMMY, ENUM_DUMMY};
940:     PetscInt    n_masks  = PETSC_STATIC_ARRAY_LENGTH(masks);

942:     PetscCall(TaoTermSumGetTerm(term, i, &subprefix, &scale, &subterm, &map));
943:     if (subterm == NULL) {
944:       PetscCall(TaoTermDuplicate(term, TAOTERM_DUPLICATE_SIZEONLY, &subterm));
945:       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)subterm, prefix));
946:       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)subterm, subprefix));
947:     } else PetscCall(PetscObjectReference((PetscObject)subterm));
948:     PetscCall(TaoTermSetFromOptions(subterm));

950:     PetscCall(PetscSNPrintf(arg, 256, "-tao_term_sum_%sscale", subprefix));
951:     PetscCall(PetscOptionsReal(arg, "The scale of the term in the TaoTermSum", "TaoTermSumSetTerm", scale, &scale, NULL));

953:     PetscCall(PetscSNPrintf(arg, 256, "-tao_term_sum_%smask", subprefix));
954:     PetscCall(PetscOptionsEnumArray(arg, "The mask of the term in the TaoTermSum", "TaoTermSumSetTermMask", TaoTermMasks, masks, &n_masks, &flg));
955:     if (flg) {
956:       PetscEnum mask = (PetscEnum)TAOTERM_MASK_NONE;

958:       for (PetscInt j = 0; j < n_masks; j++) {
959:         PetscEnum this_mask = masks[j] ? (PetscEnum)(1 << (masks[j] - 1)) : (PetscEnum)TAOTERM_MASK_NONE;

961:         mask = (PetscEnum)(mask | this_mask);
962:       }

964:       PetscCall(TaoTermSumSetTermMask(term, i, (TaoTermMask)mask));
965:     }

967:     if (map) PetscCall(MatSetFromOptions(map));
968:     PetscCall(TaoTermSumSetTerm(term, i, subprefix, scale, subterm, map));
969:     PetscCall(TaoTermDestroy(&subterm));
970:   }
971:   PetscOptionsHeadEnd();
972:   PetscFunctionReturn(PETSC_SUCCESS);
973: }

975: /*@
976:   TaoTermSumGetLastTermObjectives - Get the contributions from each term to the
977:   last evaluation of `TaoTermComputeObjective()` or `TaoTermComputeObjectiveAndGradient()`

979:   Not collective

981:   Input Parameter:
982: . term - a `TaoTerm` of type `TAOTERMSUM`

984:   Output Parameter:
985: . values - an array of the contributions to the last computed objective value

987:   Level: developer

989: .seealso: [](sec_tao_term),
990:           `TaoTerm`,
991:           `TAOTERMSUM`
992: @*/
993: PetscErrorCode TaoTermSumGetLastTermObjectives(TaoTerm term, const PetscReal *values[])
994: {
995:   PetscFunctionBegin;
997:   PetscAssertPointer(values, 2);
998:   PetscUseMethod(term, "TaoTermSumGetLastTermObjectives_C", (TaoTerm, const PetscReal *[]), (term, values));
999:   PetscFunctionReturn(PETSC_SUCCESS);
1000: }

1002: static PetscErrorCode TaoTermSumGetLastTermObjectives_Sum(TaoTerm term, const PetscReal *values[])
1003: {
1004:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;

1006:   PetscFunctionBegin;
1007:   *values = sum->subterm_values;
1008:   PetscFunctionReturn(PETSC_SUCCESS);
1009: }

1011: static PetscErrorCode TaoTermComputeObjective_Sum(TaoTerm term, Vec x, Vec params, PetscReal *value)
1012: {
1013:   TaoTerm_Sum *sum        = (TaoTerm_Sum *)term->data;
1014:   Vec         *sub_params = NULL;
1015:   PetscBool   *is_dummy   = NULL;
1016:   PetscReal    value_;
1017:   PetscReal   *values = sum->subterm_values;

1019:   PetscFunctionBegin;
1020:   if (params) PetscCall(TaoTermSumVecNestGetSubVecsRead(params, NULL, &sub_params, &is_dummy));
1021:   value_ = 0.0;
1022:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1023:     TaoTermMapping *summand   = &sum->terms[i];
1024:     Vec             sub_param = TaoTermSumGetSubVec(params, sub_params, is_dummy, i);

1026:     PetscCall(TaoTermMappingComputeObjective(summand, x, sub_param, INSERT_VALUES, &values[i]));
1027:     value_ += values[i];
1028:   }
1029:   if (params) PetscCall(TaoTermSumVecNestRestoreSubVecsRead(params, NULL, &sub_params, &is_dummy));
1030:   *value = value_;
1031:   PetscFunctionReturn(PETSC_SUCCESS);
1032: }

1034: static PetscErrorCode TaoTermComputeGradient_Sum(TaoTerm term, Vec x, Vec params, Vec g)
1035: {
1036:   TaoTerm_Sum *sum        = (TaoTerm_Sum *)term->data;
1037:   Vec         *sub_params = NULL;
1038:   PetscBool   *is_dummy   = NULL;

1040:   PetscFunctionBegin;
1041:   if (params) PetscCall(TaoTermSumVecNestGetSubVecsRead(params, NULL, &sub_params, &is_dummy));
1042:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1043:     TaoTermMapping *summand   = &sum->terms[i];
1044:     Vec             sub_param = TaoTermSumGetSubVec(params, sub_params, is_dummy, i);

1046:     PetscCall(TaoTermMappingComputeGradient(summand, x, sub_param, i == 0 ? INSERT_VALUES : ADD_VALUES, g));
1047:   }
1048:   if (params) PetscCall(TaoTermSumVecNestRestoreSubVecsRead(params, NULL, &sub_params, &is_dummy));
1049:   PetscFunctionReturn(PETSC_SUCCESS);
1050: }

1052: static PetscErrorCode TaoTermComputeObjectiveAndGradient_Sum(TaoTerm term, Vec x, Vec params, PetscReal *value, Vec g)
1053: {
1054:   TaoTerm_Sum *sum        = (TaoTerm_Sum *)term->data;
1055:   Vec         *sub_params = NULL;
1056:   PetscBool   *is_dummy   = NULL;
1057:   PetscReal   *values     = sum->subterm_values;
1058:   PetscReal    value_;

1060:   PetscFunctionBegin;
1061:   if (params) PetscCall(TaoTermSumVecNestGetSubVecsRead(params, NULL, &sub_params, &is_dummy));
1062:   value_ = 0.0;
1063:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1064:     TaoTermMapping *summand   = &sum->terms[i];
1065:     Vec             sub_param = TaoTermSumGetSubVec(params, sub_params, is_dummy, i);

1067:     values[i] = 0.0;
1068:     PetscCall(TaoTermMappingComputeObjectiveAndGradient(summand, x, sub_param, i == 0 ? INSERT_VALUES : ADD_VALUES, &values[i], g));
1069:     value_ += values[i];
1070:   }
1071:   if (params) PetscCall(TaoTermSumVecNestRestoreSubVecsRead(params, NULL, &sub_params, &is_dummy));
1072:   *value = value_;
1073:   PetscFunctionReturn(PETSC_SUCCESS);
1074: }

1076: static PetscErrorCode TaoTermComputeHessian_Sum(TaoTerm term, Vec x, Vec params, Mat H, Mat Hpre)
1077: {
1078:   TaoTerm_Sum *sum        = (TaoTerm_Sum *)term->data;
1079:   Vec         *sub_params = NULL;
1080:   PetscBool   *is_dummy   = NULL;

1082:   PetscFunctionBegin;
1083:   if (H == NULL && Hpre == NULL) PetscFunctionReturn(PETSC_SUCCESS);
1084:   if (params) PetscCall(TaoTermSumVecNestGetSubVecsRead(params, NULL, &sub_params, &is_dummy));
1085:   // If mattype dense, then after zero entries, H->assembled = true.
1086:   // But for aij, H->assembled is still false.
1087:   if (H) {
1088:     PetscCall(MatZeroEntries(H));
1089:     PetscCall(MatAssemblyBegin(H, MAT_FINAL_ASSEMBLY));
1090:     PetscCall(MatAssemblyEnd(H, MAT_FINAL_ASSEMBLY));
1091:   }
1092:   if (Hpre && (Hpre != H)) {
1093:     PetscCall(MatZeroEntries(Hpre));
1094:     PetscCall(MatAssemblyBegin(Hpre, MAT_FINAL_ASSEMBLY));
1095:     PetscCall(MatAssemblyEnd(Hpre, MAT_FINAL_ASSEMBLY));
1096:   }
1097:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1098:     TaoTermMapping *summand   = &sum->terms[i];
1099:     Vec             sub_param = TaoTermSumGetSubVec(params, sub_params, is_dummy, i);

1101:     PetscCall(TaoTermMappingComputeHessian(summand, x, sub_param, ADD_VALUES, H, Hpre == H ? NULL : Hpre));
1102:   }
1103:   if (params) PetscCall(TaoTermSumVecNestRestoreSubVecsRead(params, NULL, &sub_params, &is_dummy));
1104:   PetscFunctionReturn(PETSC_SUCCESS);
1105: }

1107: static PetscErrorCode TaoTermSetUp_Sum(TaoTerm term)
1108: {
1109:   TaoTerm_Sum *sum          = (TaoTerm_Sum *)term->data;
1110:   PetscBool    all_none     = PETSC_TRUE;
1111:   PetscBool    any_required = PETSC_FALSE;
1112:   PetscInt     k = 0, K = 0;
1113:   Mat         *mats, new_parameters_factory;
1114:   PetscLayout  layout = NULL, clayout;

1116:   PetscFunctionBegin;
1117:   PetscCall(PetscCalloc1(sum->n_terms, &mats));
1118:   PetscCall(MatGetLayouts(term->solution_factory, &layout, &clayout));
1119:   if (layout->setupcalled == PETSC_FALSE) layout = NULL;
1120:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1121:     TaoTermMapping       *summand = &sum->terms[i];
1122:     TaoTermParametersMode submode;
1123:     PetscLayout           sub_layout;
1124:     PetscBool             congruent;

1126:     PetscCall(TaoTermSetUp(summand->term));
1127:     if (summand->map) {
1128:       PetscCall(MatSetUp(summand->map));
1129:       PetscCall(MatGetLayouts(summand->map, NULL, &sub_layout));
1130:     } else PetscCall(TaoTermGetSolutionLayout(summand->term, &sub_layout));
1131:     if (i == 0 && layout == NULL) layout = sub_layout;
1132:     PetscCall(PetscLayoutCompare(layout, sub_layout, &congruent));
1133:     if (congruent == PETSC_FALSE) {
1134:       PetscInt N, sub_N;
1135:       MPI_Comm comm = PetscObjectComm((PetscObject)term);

1137:       PetscCall(PetscLayoutGetSize(layout, &N));
1138:       PetscCall(PetscLayoutGetSize(sub_layout, &sub_N));

1140:       SETERRQ(comm, PETSC_ERR_ARG_SIZ, "%sterm %" PetscInt_FMT " has solution layout (input size %" PetscInt_FMT ") that is incompatible with %s solution layout (size %" PetscInt_FMT ")", summand->map ? "mapped " : "", i, sub_N, i == 0 ? "the sum's" : "previous terms'", N);
1141:     }
1142:     PetscCall(TaoTermGetParametersMode(summand->term, &submode));
1143:     if (submode == TAOTERM_PARAMETERS_REQUIRED) any_required = PETSC_TRUE;
1144:     if (submode != TAOTERM_PARAMETERS_NONE) {
1145:       PetscInt subk, subK;

1147:       all_none = PETSC_FALSE;
1148:       PetscCall(TaoTermGetParametersSizes(summand->term, &subk, &subK, NULL));
1149:       k += subk;
1150:       K += subK;
1151:     }
1152:     if (summand->term->parameters_mode != TAOTERM_PARAMETERS_NONE) {
1153:       PetscCall(PetscObjectReference((PetscObject)summand->term->parameters_factory));
1154:       mats[i] = summand->term->parameters_factory;
1155:     } else {
1156:       PetscCall(MatCreate(PetscObjectComm((PetscObject)term), &mats[i]));
1157:       PetscCall(MatSetType(mats[i], MATDUMMY));
1158:       PetscCall(MatSetSizes(mats[i], 0, 0, 0, 0));
1159:       PetscCall(MatSetUp(mats[i]));
1160:     }
1161:   }
1162:   PetscCall(MatSetLayouts(term->solution_factory, layout, clayout));
1163:   if (all_none) {
1164:     term->parameters_mode = TAOTERM_PARAMETERS_NONE;
1165:   } else if (any_required) {
1166:     term->parameters_mode = TAOTERM_PARAMETERS_REQUIRED;
1167:   } else {
1168:     term->parameters_mode = TAOTERM_PARAMETERS_OPTIONAL;
1169:   }
1170:   PetscCall(TaoTermSetParametersSizes(term, k, K, 1));
1171:   PetscCall(MatCreateNest(PetscObjectComm((PetscObject)term), sum->n_terms, NULL, 1, NULL, mats, &new_parameters_factory));
1172:   PetscCall(MatSetVecType(new_parameters_factory, VECNEST));
1173:   PetscCall(MatDestroy(&term->parameters_factory));
1174:   term->parameters_factory = new_parameters_factory;
1175:   PetscCall(MatDestroyMatrices(sum->n_terms, &mats));
1176:   PetscFunctionReturn(PETSC_SUCCESS);
1177: }

1179: static PetscErrorCode TaoTermCreateSolutionVec_Sum(TaoTerm term, Vec *solution_vec)
1180: {
1181:   PetscFunctionBegin;
1182:   if (solution_vec) PetscCall(MatCreateVecs(term->solution_factory, NULL, solution_vec));
1183:   PetscFunctionReturn(PETSC_SUCCESS);
1184: }

1186: static PetscErrorCode TaoTermCreateParametersVec_Sum(TaoTerm term, Vec *parameters_vec)
1187: {
1188:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;

1190:   PetscFunctionBegin;
1191:   if (parameters_vec) {
1192:     Vec *vecs;

1194:     PetscCall(PetscCalloc1(sum->n_terms, &vecs));
1195:     for (PetscInt i = 0; i < sum->n_terms; i++) {
1196:       TaoTermMapping       *summand = &sum->terms[i];
1197:       TaoTermParametersMode submode;

1199:       PetscCall(TaoTermGetParametersMode(summand->term, &submode));
1200:       if (submode != TAOTERM_PARAMETERS_NONE) PetscCall(TaoTermCreateParametersVec(summand->term, &vecs[i]));
1201:     }
1202:     PetscCall(TaoTermSumParametersPack(term, vecs, parameters_vec));
1203:     for (PetscInt i = 0; i < sum->n_terms; i++) PetscCall(VecDestroy(&vecs[i]));
1204:     PetscCall(PetscFree(vecs));
1205:   }
1206:   PetscFunctionReturn(PETSC_SUCCESS);
1207: }

1209: static PetscErrorCode TaoTermCreateHessianMatrices_Sum(TaoTerm term, Mat *H, Mat *Hpre)
1210: {
1211:   TaoTerm_Sum *sum = (TaoTerm_Sum *)term->data;
1212:   PetscBool    Hpre_is_H, sub_Hpre_is_H;

1214:   PetscFunctionBegin;
1215:   Hpre_is_H = term->Hpre_is_H;
1216:   // Need to create subterms' mapped Hessians and PtAP routines, if needed
1217:   for (PetscInt i = 0; i < sum->n_terms; i++) {
1218:     TaoTermMapping *summand = &sum->terms[i];
1219:     PetscBool       is_callback;

1221:     PetscCall(PetscObjectTypeCompare((PetscObject)summand->term, TAOTERMCALLBACKS, &is_callback));
1222:     if (is_callback) {
1223:       Mat c_H;

1225:       PetscCall(TaoTermSumGetTermHessianMatrices(term, i, NULL, NULL, &c_H, NULL));
1226:       PetscCheck(c_H, PetscObjectComm((PetscObject)summand->term), PETSC_ERR_USER, "TAOTERMCALLBACKS does not have Hessian routines set. Call TaoSetHessian()");
1227:     }
1228:     PetscCall(TaoTermMappingCreateHessianMatrices(summand, &summand->_mapped_H, &summand->_mapped_Hpre));

1230:     sub_Hpre_is_H = (summand->_mapped_H == summand->_mapped_Hpre) ? PETSC_TRUE : PETSC_FALSE;
1231:     Hpre_is_H     = (Hpre_is_H && sub_Hpre_is_H) ? PETSC_TRUE : PETSC_FALSE;
1232:   }

1234:   term->Hpre_is_H = Hpre_is_H;
1235:   PetscCall(TaoTermCreateHessianMatricesDefault(term, H, Hpre));
1236:   PetscFunctionReturn(PETSC_SUCCESS);
1237: }

1239: /*MC
1240:   TAOTERMSUM - A `TaoTerm` that is a sum of multiple `TaoTerms`.

1242:   Level: developer

1244:   Note:
1245:   The default Hessian creation mode (see `TaoTermGetCreateHessianMode()`) is `H == Hpre` and `TaoTermCreateHessianMatrices()`
1246:   will create a `MATAIJ`.

1248: .seealso: [](sec_tao_term),
1249:           `TaoTerm`,
1250:           `TaoTermType`,
1251:           `TaoTermSumGetNumberTerms()`,
1252:           `TaoTermSumSetNumberTerms()`,
1253:           `TaoTermSumGetTerm()`,
1254:           `TaoTermSumSetTerm()`,
1255:           `TaoTermSumAddTerm()`,
1256:           `TaoTermSumGetTermHessianMatrices()`,
1257:           `TaoTermSumSetTermHessianMatrices()`,
1258:           `TaoTermSumGetTermMask()`,
1259:           `TaoTermSumSetTermMask()`
1260: M*/
1261: PETSC_INTERN PetscErrorCode TaoTermCreate_Sum(TaoTerm term)
1262: {
1263:   TaoTerm_Sum *sum;

1265:   PetscFunctionBegin;
1266:   PetscCall(PetscNew(&sum));
1267:   term->data            = (void *)sum;
1268:   term->parameters_mode = TAOTERM_PARAMETERS_OPTIONAL;

1270:   PetscCall(PetscFree(term->H_mattype));
1271:   PetscCall(PetscFree(term->Hpre_mattype));

1273:   PetscCall(PetscStrallocpy(MATAIJ, (char **)&term->H_mattype));
1274:   PetscCall(PetscStrallocpy(MATAIJ, (char **)&term->Hpre_mattype));
1275:   term->Hpre_is_H = PETSC_TRUE;

1277:   term->ops->destroy               = TaoTermDestroy_Sum;
1278:   term->ops->view                  = TaoTermView_Sum;
1279:   term->ops->setfromoptions        = TaoTermSetFromOptions_Sum;
1280:   term->ops->objective             = TaoTermComputeObjective_Sum;
1281:   term->ops->gradient              = TaoTermComputeGradient_Sum;
1282:   term->ops->objectiveandgradient  = TaoTermComputeObjectiveAndGradient_Sum;
1283:   term->ops->hessian               = TaoTermComputeHessian_Sum;
1284:   term->ops->setup                 = TaoTermSetUp_Sum;
1285:   term->ops->createsolutionvec     = TaoTermCreateSolutionVec_Sum;
1286:   term->ops->createparametersvec   = TaoTermCreateParametersVec_Sum;
1287:   term->ops->createhessianmatrices = TaoTermCreateHessianMatrices_Sum;
1288:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetNumberTerms_C", TaoTermSumGetNumberTerms_Sum));
1289:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetNumberTerms_C", TaoTermSumSetNumberTerms_Sum));
1290:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTerm_C", TaoTermSumGetTerm_Sum));
1291:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTerm_C", TaoTermSumSetTerm_Sum));
1292:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumAddTerm_C", TaoTermSumAddTerm_Sum));
1293:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTermHessianMatrices_C", TaoTermSumGetTermHessianMatrices_Sum));
1294:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTermHessianMatrices_C", TaoTermSumSetTermHessianMatrices_Sum));
1295:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetTermMask_C", TaoTermSumGetTermMask_Sum));
1296:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumSetTermMask_C", TaoTermSumSetTermMask_Sum));
1297:   PetscCall(PetscObjectComposeFunction((PetscObject)term, "TaoTermSumGetLastTermObjectives_C", TaoTermSumGetLastTermObjectives_Sum));
1298:   PetscFunctionReturn(PETSC_SUCCESS);
1299: }