xref: /petsc/src/tao/bound/impls/bnk/bnk.c (revision 5fedec97950c19de564efaecd0f125b1a6cb2b20)
1 #include <petsctaolinesearch.h>
2 #include <../src/tao/bound/impls/bnk/bnk.h>
3 #include <petscksp.h>
4 
5 static const char *BNK_INIT[64] = {"constant", "direction", "interpolation"};
6 static const char *BNK_UPDATE[64] = {"step", "reduction", "interpolation"};
7 static const char *BNK_AS[64] = {"none", "bertsekas"};
8 
9 /*------------------------------------------------------------*/
10 
11 /* Routine for initializing the KSP solver, the BFGS preconditioner, and the initial trust radius estimation */
12 
13 PetscErrorCode TaoBNKInitialize(Tao tao, PetscInt initType, PetscBool *needH)
14 {
15   PetscErrorCode               ierr;
16   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
17   PC                           pc;
18 
19   PetscReal                    f_min, ftrial, prered, actred, kappa, sigma, resnorm;
20   PetscReal                    tau, tau_1, tau_2, tau_max, tau_min, max_radius;
21   PetscBool                    is_bfgs, is_jacobi, is_symmetric, sym_set;
22   PetscInt                     n, N, nDiff;
23   PetscInt                     i_max = 5;
24   PetscInt                     j_max = 1;
25   PetscInt                     i, j;
26 
27   PetscFunctionBegin;
28   /* Project the current point onto the feasible set */
29   ierr = TaoComputeVariableBounds(tao);CHKERRQ(ierr);
30   ierr = TaoSetVariableBounds(bnk->bncg, tao->XL, tao->XU);CHKERRQ(ierr);
31   if (tao->bounded) {
32     ierr = TaoLineSearchSetVariableBounds(tao->linesearch,tao->XL,tao->XU);CHKERRQ(ierr);
33   }
34 
35   /* Project the initial point onto the feasible region */
36   ierr = TaoBoundSolution(tao->solution, tao->XL,tao->XU, 0.0, &nDiff, tao->solution);CHKERRQ(ierr);
37 
38   /* Check convergence criteria */
39   ierr = TaoComputeObjectiveAndGradient(tao, tao->solution, &bnk->f, bnk->unprojected_gradient);CHKERRQ(ierr);
40   ierr = TaoBNKEstimateActiveSet(tao, bnk->as_type);CHKERRQ(ierr);
41   ierr = VecCopy(bnk->unprojected_gradient, tao->gradient);CHKERRQ(ierr);
42   ierr = VecISSet(tao->gradient, bnk->active_idx, 0.0);CHKERRQ(ierr);
43   ierr = TaoGradientNorm(tao, tao->gradient, NORM_2, &bnk->gnorm);CHKERRQ(ierr);
44 
45   /* Test the initial point for convergence */
46   ierr = VecFischer(tao->solution, bnk->unprojected_gradient, tao->XL, tao->XU, bnk->W);CHKERRQ(ierr);
47   ierr = VecNorm(bnk->W, NORM_2, &resnorm);CHKERRQ(ierr);
48   if (PetscIsInfOrNanReal(bnk->f) || PetscIsInfOrNanReal(resnorm)) SETERRQ(PetscObjectComm((PetscObject)tao),PETSC_ERR_USER, "User provided compute function generated Inf or NaN");
49   ierr = TaoLogConvergenceHistory(tao,bnk->f,resnorm,0.0,tao->ksp_its);CHKERRQ(ierr);
50   ierr = TaoMonitor(tao,tao->niter,bnk->f,resnorm,0.0,1.0);CHKERRQ(ierr);
51   ierr = (*tao->ops->convergencetest)(tao,tao->cnvP);CHKERRQ(ierr);
52   if (tao->reason != TAO_CONTINUE_ITERATING) PetscFunctionReturn(0);
53 
54   /* Reset KSP stopping reason counters */
55   bnk->ksp_atol = 0;
56   bnk->ksp_rtol = 0;
57   bnk->ksp_dtol = 0;
58   bnk->ksp_ctol = 0;
59   bnk->ksp_negc = 0;
60   bnk->ksp_iter = 0;
61   bnk->ksp_othr = 0;
62 
63   /* Reset accepted step type counters */
64   bnk->tot_cg_its = 0;
65   bnk->newt = 0;
66   bnk->bfgs = 0;
67   bnk->sgrad = 0;
68   bnk->grad = 0;
69 
70   /* Initialize the Hessian perturbation */
71   bnk->pert = bnk->sval;
72 
73   /* Reset initial steplength to zero (this helps BNCG reset its direction internally) */
74   ierr = VecSet(tao->stepdirection, 0.0);CHKERRQ(ierr);
75 
76   /* Allocate the vectors needed for the BFGS approximation */
77   ierr = KSPGetPC(tao->ksp, &pc);CHKERRQ(ierr);
78   ierr = PetscObjectTypeCompare((PetscObject)pc, PCLMVM, &is_bfgs);CHKERRQ(ierr);
79   ierr = PetscObjectTypeCompare((PetscObject)pc, PCJACOBI, &is_jacobi);CHKERRQ(ierr);
80   if (is_bfgs) {
81     bnk->bfgs_pre = pc;
82     ierr = PCLMVMGetMatLMVM(bnk->bfgs_pre, &bnk->M);CHKERRQ(ierr);
83     ierr = VecGetLocalSize(tao->solution, &n);CHKERRQ(ierr);
84     ierr = VecGetSize(tao->solution, &N);CHKERRQ(ierr);
85     ierr = MatSetSizes(bnk->M, n, n, N, N);CHKERRQ(ierr);
86     ierr = MatLMVMAllocate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
87     ierr = MatIsSymmetricKnown(bnk->M, &sym_set, &is_symmetric);CHKERRQ(ierr);
88     if (!sym_set || !is_symmetric) SETERRQ(PetscObjectComm((PetscObject)tao), PETSC_ERR_ARG_INCOMP, "LMVM matrix in the LMVM preconditioner must be symmetric.");
89   } else if (is_jacobi) {
90     ierr = PCJacobiSetUseAbs(pc,PETSC_TRUE);CHKERRQ(ierr);
91   }
92 
93   /* Prepare the min/max vectors for safeguarding diagonal scales */
94   ierr = VecSet(bnk->Diag_min, bnk->dmin);CHKERRQ(ierr);
95   ierr = VecSet(bnk->Diag_max, bnk->dmax);CHKERRQ(ierr);
96 
97   /* Initialize trust-region radius.  The initialization is only performed
98      when we are using Nash, Steihaug-Toint or the Generalized Lanczos method. */
99   *needH = PETSC_TRUE;
100   if (bnk->is_nash || bnk->is_stcg || bnk->is_gltr) {
101     switch(initType) {
102     case BNK_INIT_CONSTANT:
103       /* Use the initial radius specified */
104       tao->trust = tao->trust0;
105       break;
106 
107     case BNK_INIT_INTERPOLATION:
108       /* Use interpolation based on the initial Hessian */
109       max_radius = 0.0;
110       tao->trust = tao->trust0;
111       for (j = 0; j < j_max; ++j) {
112         f_min = bnk->f;
113         sigma = 0.0;
114 
115         if (*needH) {
116           /* Compute the Hessian at the new step, and extract the inactive subsystem */
117           ierr = (*bnk->computehessian)(tao);CHKERRQ(ierr);
118           ierr = TaoBNKEstimateActiveSet(tao, BNK_AS_NONE);CHKERRQ(ierr);
119           ierr = MatDestroy(&bnk->H_inactive);CHKERRQ(ierr);
120           if (bnk->active_idx) {
121             ierr = MatCreateSubMatrix(tao->hessian, bnk->inactive_idx, bnk->inactive_idx, MAT_INITIAL_MATRIX, &bnk->H_inactive);CHKERRQ(ierr);
122           } else {
123             ierr = PetscObjectReference((PetscObject)tao->hessian);CHKERRQ(ierr);
124             bnk->H_inactive = tao->hessian;
125           }
126           *needH = PETSC_FALSE;
127         }
128 
129         for (i = 0; i < i_max; ++i) {
130           /* Take a steepest descent step and snap it to bounds */
131           ierr = VecCopy(tao->solution, bnk->Xold);CHKERRQ(ierr);
132           ierr = VecAXPY(tao->solution, -tao->trust/bnk->gnorm, tao->gradient);CHKERRQ(ierr);
133           ierr = TaoBoundSolution(tao->solution, tao->XL,tao->XU, 0.0, &nDiff, tao->solution);CHKERRQ(ierr);
134           /* Compute the step we actually accepted */
135           ierr = VecCopy(tao->solution, bnk->W);CHKERRQ(ierr);
136           ierr = VecAXPY(bnk->W, -1.0, bnk->Xold);CHKERRQ(ierr);
137           /* Compute the objective at the trial */
138           ierr = TaoComputeObjective(tao, tao->solution, &ftrial);CHKERRQ(ierr);
139           if (PetscIsInfOrNanReal(bnk->f)) SETERRQ(PetscObjectComm((PetscObject)tao),PETSC_ERR_USER, "User provided compute function generated Inf or NaN");
140           ierr = VecCopy(bnk->Xold, tao->solution);CHKERRQ(ierr);
141           if (PetscIsInfOrNanReal(ftrial)) {
142             tau = bnk->gamma1_i;
143           } else {
144             if (ftrial < f_min) {
145               f_min = ftrial;
146               sigma = -tao->trust / bnk->gnorm;
147             }
148 
149             /* Compute the predicted and actual reduction */
150             if (bnk->active_idx) {
151               ierr = VecGetSubVector(bnk->W, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
152               ierr = VecGetSubVector(bnk->Xwork, bnk->inactive_idx, &bnk->inactive_work);CHKERRQ(ierr);
153             } else {
154               bnk->X_inactive = bnk->W;
155               bnk->inactive_work = bnk->Xwork;
156             }
157             ierr = MatMult(bnk->H_inactive, bnk->X_inactive, bnk->inactive_work);CHKERRQ(ierr);
158             ierr = VecDot(bnk->X_inactive, bnk->inactive_work, &prered);CHKERRQ(ierr);
159             if (bnk->active_idx) {
160               ierr = VecRestoreSubVector(bnk->W, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
161               ierr = VecRestoreSubVector(bnk->Xwork, bnk->inactive_idx, &bnk->inactive_work);CHKERRQ(ierr);
162             }
163             prered = tao->trust * (bnk->gnorm - 0.5 * tao->trust * prered / (bnk->gnorm * bnk->gnorm));
164             actred = bnk->f - ftrial;
165             if ((PetscAbsScalar(actred) <= bnk->epsilon) && (PetscAbsScalar(prered) <= bnk->epsilon)) {
166               kappa = 1.0;
167             } else {
168               kappa = actred / prered;
169             }
170 
171             tau_1 = bnk->theta_i * bnk->gnorm * tao->trust / (bnk->theta_i * bnk->gnorm * tao->trust + (1.0 - bnk->theta_i) * prered - actred);
172             tau_2 = bnk->theta_i * bnk->gnorm * tao->trust / (bnk->theta_i * bnk->gnorm * tao->trust - (1.0 + bnk->theta_i) * prered + actred);
173             tau_min = PetscMin(tau_1, tau_2);
174             tau_max = PetscMax(tau_1, tau_2);
175 
176             if (PetscAbsScalar(kappa - (PetscReal)1.0) <= bnk->mu1_i) {
177               /*  Great agreement */
178               max_radius = PetscMax(max_radius, tao->trust);
179 
180               if (tau_max < 1.0) {
181                 tau = bnk->gamma3_i;
182               } else if (tau_max > bnk->gamma4_i) {
183                 tau = bnk->gamma4_i;
184               } else {
185                 tau = tau_max;
186               }
187             } else if (PetscAbsScalar(kappa - (PetscReal)1.0) <= bnk->mu2_i) {
188               /*  Good agreement */
189               max_radius = PetscMax(max_radius, tao->trust);
190 
191               if (tau_max < bnk->gamma2_i) {
192                 tau = bnk->gamma2_i;
193               } else if (tau_max > bnk->gamma3_i) {
194                 tau = bnk->gamma3_i;
195               } else {
196                 tau = tau_max;
197               }
198             } else {
199               /*  Not good agreement */
200               if (tau_min > 1.0) {
201                 tau = bnk->gamma2_i;
202               } else if (tau_max < bnk->gamma1_i) {
203                 tau = bnk->gamma1_i;
204               } else if ((tau_min < bnk->gamma1_i) && (tau_max >= 1.0)) {
205                 tau = bnk->gamma1_i;
206               } else if ((tau_1 >= bnk->gamma1_i) && (tau_1 < 1.0) && ((tau_2 < bnk->gamma1_i) || (tau_2 >= 1.0))) {
207                 tau = tau_1;
208               } else if ((tau_2 >= bnk->gamma1_i) && (tau_2 < 1.0) && ((tau_1 < bnk->gamma1_i) || (tau_2 >= 1.0))) {
209                 tau = tau_2;
210               } else {
211                 tau = tau_max;
212               }
213             }
214           }
215           tao->trust = tau * tao->trust;
216         }
217 
218         if (f_min < bnk->f) {
219           /* We accidentally found a solution better than the initial, so accept it */
220           bnk->f = f_min;
221           ierr = VecCopy(tao->solution, bnk->Xold);CHKERRQ(ierr);
222           ierr = VecAXPY(tao->solution,sigma,tao->gradient);CHKERRQ(ierr);
223           ierr = TaoBoundSolution(tao->solution, tao->XL,tao->XU, 0.0, &nDiff, tao->solution);CHKERRQ(ierr);
224           ierr = VecCopy(tao->solution, tao->stepdirection);CHKERRQ(ierr);
225           ierr = VecAXPY(tao->stepdirection, -1.0, bnk->Xold);CHKERRQ(ierr);
226           ierr = TaoComputeGradient(tao,tao->solution,bnk->unprojected_gradient);CHKERRQ(ierr);
227           ierr = TaoBNKEstimateActiveSet(tao, bnk->as_type);CHKERRQ(ierr);
228           ierr = VecCopy(bnk->unprojected_gradient, tao->gradient);CHKERRQ(ierr);
229           ierr = VecISSet(tao->gradient, bnk->active_idx, 0.0);CHKERRQ(ierr);
230           /* Compute gradient at the new iterate and flip switch to compute the Hessian later */
231           ierr = TaoGradientNorm(tao, tao->gradient, NORM_2, &bnk->gnorm);CHKERRQ(ierr);
232           *needH = PETSC_TRUE;
233           /* Test the new step for convergence */
234           ierr = VecFischer(tao->solution, bnk->unprojected_gradient, tao->XL, tao->XU, bnk->W);CHKERRQ(ierr);
235           ierr = VecNorm(bnk->W, NORM_2, &resnorm);CHKERRQ(ierr);
236           if (PetscIsInfOrNanReal(resnorm)) SETERRQ(PetscObjectComm((PetscObject)tao),PETSC_ERR_USER, "User provided compute function generated Inf or NaN");
237           ierr = TaoLogConvergenceHistory(tao,bnk->f,resnorm,0.0,tao->ksp_its);CHKERRQ(ierr);
238           ierr = TaoMonitor(tao,tao->niter,bnk->f,resnorm,0.0,1.0);CHKERRQ(ierr);
239           ierr = (*tao->ops->convergencetest)(tao,tao->cnvP);CHKERRQ(ierr);
240           if (tao->reason != TAO_CONTINUE_ITERATING) PetscFunctionReturn(0);
241           /* active BNCG recycling early because we have a stepdirection computed */
242           ierr = TaoSetRecycleHistory(bnk->bncg, PETSC_TRUE);CHKERRQ(ierr);
243         }
244       }
245       tao->trust = PetscMax(tao->trust, max_radius);
246 
247       /* Ensure that the trust radius is within the limits */
248       tao->trust = PetscMax(tao->trust, bnk->min_radius);
249       tao->trust = PetscMin(tao->trust, bnk->max_radius);
250       break;
251 
252     default:
253       /* Norm of the first direction will initialize radius */
254       tao->trust = 0.0;
255       break;
256     }
257   }
258   PetscFunctionReturn(0);
259 }
260 
261 /*------------------------------------------------------------*/
262 
263 /* Routine for computing the exact Hessian and preparing the preconditioner at the new iterate */
264 
265 PetscErrorCode TaoBNKComputeHessian(Tao tao)
266 {
267   PetscErrorCode ierr;
268   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
269 
270   PetscFunctionBegin;
271   /* Compute the Hessian */
272   ierr = TaoComputeHessian(tao,tao->solution,tao->hessian,tao->hessian_pre);CHKERRQ(ierr);
273   /* Add a correction to the BFGS preconditioner */
274   if (bnk->M) {
275     ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
276   }
277   /* Prepare the reduced sub-matrices for the inactive set */
278   ierr = MatDestroy(&bnk->Hpre_inactive);CHKERRQ(ierr);
279   ierr = MatDestroy(&bnk->H_inactive);CHKERRQ(ierr);
280   if (bnk->active_idx) {
281     ierr = MatCreateSubMatrix(tao->hessian, bnk->inactive_idx, bnk->inactive_idx, MAT_INITIAL_MATRIX, &bnk->H_inactive);CHKERRQ(ierr);
282     if (tao->hessian == tao->hessian_pre) {
283       ierr = PetscObjectReference((PetscObject)bnk->H_inactive);CHKERRQ(ierr);
284       bnk->Hpre_inactive = bnk->H_inactive;
285     } else {
286       ierr = MatCreateSubMatrix(tao->hessian_pre, bnk->inactive_idx, bnk->inactive_idx, MAT_INITIAL_MATRIX, &bnk->Hpre_inactive);CHKERRQ(ierr);
287     }
288     if (bnk->bfgs_pre) {
289       ierr = PCLMVMSetIS(bnk->bfgs_pre, bnk->inactive_idx);CHKERRQ(ierr);
290     }
291   } else {
292     ierr = PetscObjectReference((PetscObject)tao->hessian);CHKERRQ(ierr);
293     bnk->H_inactive = tao->hessian;
294     if (tao->hessian == tao->hessian_pre) {
295       ierr = PetscObjectReference((PetscObject)bnk->H_inactive);CHKERRQ(ierr);
296       bnk->Hpre_inactive = bnk->H_inactive;
297     } else {
298       ierr = PetscObjectReference((PetscObject)tao->hessian_pre);
299       bnk->Hpre_inactive = tao->hessian_pre;
300     }
301     if (bnk->bfgs_pre) {
302       ierr = PCLMVMClearIS(bnk->bfgs_pre);CHKERRQ(ierr);
303     }
304   }
305   PetscFunctionReturn(0);
306 }
307 
308 /*------------------------------------------------------------*/
309 
310 /* Routine for estimating the active set */
311 
312 PetscErrorCode TaoBNKEstimateActiveSet(Tao tao, PetscInt asType)
313 {
314   PetscErrorCode ierr;
315   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
316   PetscBool      hessComputed, diagExists;
317 
318   PetscFunctionBegin;
319   switch (asType) {
320   case BNK_AS_NONE:
321     ierr = ISDestroy(&bnk->inactive_idx);CHKERRQ(ierr);
322     ierr = VecWhichInactive(tao->XL, tao->solution, bnk->unprojected_gradient, tao->XU, PETSC_TRUE, &bnk->inactive_idx);CHKERRQ(ierr);
323     ierr = ISDestroy(&bnk->active_idx);CHKERRQ(ierr);
324     ierr = ISComplementVec(bnk->inactive_idx, tao->solution, &bnk->active_idx);CHKERRQ(ierr);
325     break;
326 
327   case BNK_AS_BERTSEKAS:
328     /* Compute the trial step vector with which we will estimate the active set at the next iteration */
329     if (bnk->M) {
330       /* If the BFGS preconditioner matrix is available, we will construct a trial step with it */
331       ierr = MatSolve(bnk->M, bnk->unprojected_gradient, bnk->W);CHKERRQ(ierr);
332     } else {
333       hessComputed = diagExists = PETSC_FALSE;
334       if (tao->hessian) {
335         ierr = MatAssembled(tao->hessian, &hessComputed);CHKERRQ(ierr);
336       }
337       if (hessComputed) {
338         ierr = MatHasOperation(tao->hessian, MATOP_GET_DIAGONAL, &diagExists);CHKERRQ(ierr);
339       }
340       if (diagExists) {
341         /* BFGS preconditioner doesn't exist so let's invert the absolute diagonal of the Hessian instead onto the gradient */
342         ierr = MatGetDiagonal(tao->hessian, bnk->Xwork);CHKERRQ(ierr);
343         ierr = VecAbs(bnk->Xwork);CHKERRQ(ierr);
344         ierr = VecMedian(bnk->Diag_min, bnk->Xwork, bnk->Diag_max, bnk->Xwork);CHKERRQ(ierr);
345         ierr = VecReciprocal(bnk->Xwork);CHKERRQ(ierr);
346         ierr = VecPointwiseMult(bnk->W, bnk->Xwork, bnk->unprojected_gradient);CHKERRQ(ierr);
347       } else {
348         /* If the Hessian or its diagonal does not exist, we will simply use gradient step */
349         ierr = VecCopy(bnk->unprojected_gradient, bnk->W);CHKERRQ(ierr);
350       }
351     }
352     ierr = VecScale(bnk->W, -1.0);CHKERRQ(ierr);
353     ierr = TaoEstimateActiveBounds(tao->solution, tao->XL, tao->XU, bnk->unprojected_gradient, bnk->W, bnk->Xwork, bnk->as_step, &bnk->as_tol,
354                                    &bnk->active_lower, &bnk->active_upper, &bnk->active_fixed, &bnk->active_idx, &bnk->inactive_idx);CHKERRQ(ierr);
355     break;
356 
357   default:
358     break;
359   }
360   PetscFunctionReturn(0);
361 }
362 
363 /*------------------------------------------------------------*/
364 
365 /* Routine for bounding the step direction */
366 
367 PetscErrorCode TaoBNKBoundStep(Tao tao, PetscInt asType, Vec step)
368 {
369   PetscErrorCode               ierr;
370   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
371 
372   PetscFunctionBegin;
373   switch (asType) {
374   case BNK_AS_NONE:
375     ierr = VecISSet(step, bnk->active_idx, 0.0);CHKERRQ(ierr);
376     break;
377 
378   case BNK_AS_BERTSEKAS:
379     ierr = TaoBoundStep(tao->solution, tao->XL, tao->XU, bnk->active_lower, bnk->active_upper, bnk->active_fixed, 1.0, step);CHKERRQ(ierr);
380     break;
381 
382   default:
383     break;
384   }
385   PetscFunctionReturn(0);
386 }
387 
388 /*------------------------------------------------------------*/
389 
390 /* Routine for taking a finite number of BNCG iterations to
391    accelerate Newton convergence.
392 
393    In practice, this approach simply trades off Hessian evaluations
394    for more gradient evaluations.
395 */
396 
397 PetscErrorCode TaoBNKTakeCGSteps(Tao tao, PetscBool *terminate)
398 {
399   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
400   PetscErrorCode               ierr;
401 
402   PetscFunctionBegin;
403   *terminate = PETSC_FALSE;
404   if (bnk->max_cg_its > 0) {
405     /* Copy the current function value (important vectors are already shared) */
406     bnk->bncg_ctx->f = bnk->f;
407     /* Take some small finite number of BNCG iterations */
408     ierr = TaoSolve(bnk->bncg);CHKERRQ(ierr);
409     /* Add the number of gradient and function evaluations to the total */
410     tao->nfuncs += bnk->bncg->nfuncs;
411     tao->nfuncgrads += bnk->bncg->nfuncgrads;
412     tao->ngrads += bnk->bncg->ngrads;
413     tao->nhess += bnk->bncg->nhess;
414     bnk->tot_cg_its += bnk->bncg->niter;
415     /* Extract the BNCG function value out and save it into BNK */
416     bnk->f = bnk->bncg_ctx->f;
417     if (bnk->bncg->reason == TAO_CONVERGED_GATOL || bnk->bncg->reason == TAO_CONVERGED_GRTOL || bnk->bncg->reason == TAO_CONVERGED_GTTOL || bnk->bncg->reason == TAO_CONVERGED_MINF) {
418       *terminate = PETSC_TRUE;
419     } else {
420       ierr = TaoBNKEstimateActiveSet(tao, bnk->as_type);CHKERRQ(ierr);
421     }
422   }
423   PetscFunctionReturn(0);
424 }
425 
426 /*------------------------------------------------------------*/
427 
428 /* Routine for computing the Newton step. */
429 
430 PetscErrorCode TaoBNKComputeStep(Tao tao, PetscBool shift, KSPConvergedReason *ksp_reason, PetscInt *step_type)
431 {
432   PetscErrorCode               ierr;
433   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
434   PetscInt                     bfgsUpdates = 0;
435   PetscInt                     kspits;
436   PetscBool                    is_lmvm;
437 
438   PetscFunctionBegin;
439   /* If there are no inactive variables left, save some computation and return an adjusted zero step
440      that has (l-x) and (u-x) for lower and upper bounded variables. */
441   if (!bnk->inactive_idx) {
442     ierr = VecSet(tao->stepdirection, 0.0);CHKERRQ(ierr);
443     ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
444     PetscFunctionReturn(0);
445   }
446 
447   /* Shift the reduced Hessian matrix */
448   if (shift && bnk->pert > 0) {
449     ierr = PetscObjectTypeCompare((PetscObject)tao->hessian, MATLMVM, &is_lmvm);CHKERRQ(ierr);
450     if (is_lmvm) {
451       ierr = MatShift(tao->hessian, bnk->pert);CHKERRQ(ierr);
452     } else {
453       ierr = MatShift(bnk->H_inactive, bnk->pert);CHKERRQ(ierr);
454       if (bnk->H_inactive != bnk->Hpre_inactive) {
455         ierr = MatShift(bnk->Hpre_inactive, bnk->pert);CHKERRQ(ierr);
456       }
457     }
458   }
459 
460   /* Solve the Newton system of equations */
461   tao->ksp_its = 0;
462   ierr = VecSet(tao->stepdirection, 0.0);CHKERRQ(ierr);
463   ierr = KSPReset(tao->ksp);CHKERRQ(ierr);
464   ierr = KSPResetFromOptions(tao->ksp);CHKERRQ(ierr);
465   ierr = KSPSetOperators(tao->ksp,bnk->H_inactive,bnk->Hpre_inactive);CHKERRQ(ierr);
466   ierr = VecCopy(bnk->unprojected_gradient, bnk->Gwork);CHKERRQ(ierr);
467   if (bnk->active_idx) {
468     ierr = VecGetSubVector(bnk->Gwork, bnk->inactive_idx, &bnk->G_inactive);CHKERRQ(ierr);
469     ierr = VecGetSubVector(tao->stepdirection, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
470   } else {
471     bnk->G_inactive = bnk->unprojected_gradient;
472     bnk->X_inactive = tao->stepdirection;
473   }
474   if (bnk->is_nash || bnk->is_stcg || bnk->is_gltr) {
475     ierr = KSPCGSetRadius(tao->ksp,tao->trust);CHKERRQ(ierr);
476     ierr = KSPSolve(tao->ksp, bnk->G_inactive, bnk->X_inactive);CHKERRQ(ierr);
477     ierr = KSPGetIterationNumber(tao->ksp,&kspits);CHKERRQ(ierr);
478     tao->ksp_its+=kspits;
479     tao->ksp_tot_its+=kspits;
480     ierr = KSPCGGetNormD(tao->ksp,&bnk->dnorm);CHKERRQ(ierr);
481 
482     if (0.0 == tao->trust) {
483       /* Radius was uninitialized; use the norm of the direction */
484       if (bnk->dnorm > 0.0) {
485         tao->trust = bnk->dnorm;
486 
487         /* Modify the radius if it is too large or small */
488         tao->trust = PetscMax(tao->trust, bnk->min_radius);
489         tao->trust = PetscMin(tao->trust, bnk->max_radius);
490       } else {
491         /* The direction was bad; set radius to default value and re-solve
492            the trust-region subproblem to get a direction */
493         tao->trust = tao->trust0;
494 
495         /* Modify the radius if it is too large or small */
496         tao->trust = PetscMax(tao->trust, bnk->min_radius);
497         tao->trust = PetscMin(tao->trust, bnk->max_radius);
498 
499         ierr = KSPCGSetRadius(tao->ksp,tao->trust);CHKERRQ(ierr);
500         ierr = KSPSolve(tao->ksp, bnk->G_inactive, bnk->X_inactive);CHKERRQ(ierr);
501         ierr = KSPGetIterationNumber(tao->ksp,&kspits);CHKERRQ(ierr);
502         tao->ksp_its+=kspits;
503         tao->ksp_tot_its+=kspits;
504         ierr = KSPCGGetNormD(tao->ksp,&bnk->dnorm);CHKERRQ(ierr);
505 
506         if (bnk->dnorm == 0.0) SETERRQ(PetscObjectComm((PetscObject)tao),PETSC_ERR_PLIB, "Initial direction zero");
507       }
508     }
509   } else {
510     ierr = KSPSolve(tao->ksp, bnk->G_inactive, bnk->X_inactive);CHKERRQ(ierr);
511     ierr = KSPGetIterationNumber(tao->ksp, &kspits);CHKERRQ(ierr);
512     tao->ksp_its += kspits;
513     tao->ksp_tot_its+=kspits;
514   }
515   /* Restore sub vectors back */
516   if (bnk->active_idx) {
517     ierr = VecRestoreSubVector(bnk->Gwork, bnk->inactive_idx, &bnk->G_inactive);CHKERRQ(ierr);
518     ierr = VecRestoreSubVector(tao->stepdirection, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
519   }
520   /* Make sure the safeguarded fall-back step is zero for actively bounded variables */
521   ierr = VecScale(tao->stepdirection, -1.0);CHKERRQ(ierr);
522   ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
523 
524   /* Record convergence reasons */
525   ierr = KSPGetConvergedReason(tao->ksp, ksp_reason);CHKERRQ(ierr);
526   if (KSP_CONVERGED_ATOL == *ksp_reason) {
527     ++bnk->ksp_atol;
528   } else if (KSP_CONVERGED_RTOL == *ksp_reason) {
529     ++bnk->ksp_rtol;
530   } else if (KSP_CONVERGED_CG_CONSTRAINED == *ksp_reason) {
531     ++bnk->ksp_ctol;
532   } else if (KSP_CONVERGED_CG_NEG_CURVE == *ksp_reason) {
533     ++bnk->ksp_negc;
534   } else if (KSP_DIVERGED_DTOL == *ksp_reason) {
535     ++bnk->ksp_dtol;
536   } else if (KSP_DIVERGED_ITS == *ksp_reason) {
537     ++bnk->ksp_iter;
538   } else {
539     ++bnk->ksp_othr;
540   }
541 
542   /* Make sure the BFGS preconditioner is healthy */
543   if (bnk->M) {
544     ierr = MatLMVMGetUpdateCount(bnk->M, &bfgsUpdates);CHKERRQ(ierr);
545     if ((KSP_DIVERGED_INDEFINITE_PC == *ksp_reason) && (bfgsUpdates > 0)) {
546       /* Preconditioner is numerically indefinite; reset the approximation. */
547       ierr = MatLMVMReset(bnk->M, PETSC_FALSE);CHKERRQ(ierr);
548       ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
549     }
550   }
551   *step_type = BNK_NEWTON;
552   PetscFunctionReturn(0);
553 }
554 
555 /*------------------------------------------------------------*/
556 
557 /* Routine for recomputing the predicted reduction for a given step vector */
558 
559 PetscErrorCode TaoBNKRecomputePred(Tao tao, Vec S, PetscReal *prered)
560 {
561   PetscErrorCode               ierr;
562   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
563 
564   PetscFunctionBegin;
565   /* Extract subvectors associated with the inactive set */
566   if (bnk->active_idx) {
567     ierr = VecGetSubVector(tao->stepdirection, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
568     ierr = VecGetSubVector(bnk->Xwork, bnk->inactive_idx, &bnk->inactive_work);CHKERRQ(ierr);
569     ierr = VecGetSubVector(bnk->Gwork, bnk->inactive_idx, &bnk->G_inactive);CHKERRQ(ierr);
570   } else {
571     bnk->X_inactive = tao->stepdirection;
572     bnk->inactive_work = bnk->Xwork;
573     bnk->G_inactive = bnk->Gwork;
574   }
575   /* Recompute the predicted decrease based on the quadratic model */
576   ierr = MatMult(bnk->H_inactive, bnk->X_inactive, bnk->inactive_work);CHKERRQ(ierr);
577   ierr = VecAYPX(bnk->inactive_work, -0.5, bnk->G_inactive);CHKERRQ(ierr);
578   ierr = VecDot(bnk->inactive_work, bnk->X_inactive, prered);CHKERRQ(ierr);
579   /* Restore the sub vectors */
580   if (bnk->active_idx) {
581     ierr = VecRestoreSubVector(tao->stepdirection, bnk->inactive_idx, &bnk->X_inactive);CHKERRQ(ierr);
582     ierr = VecRestoreSubVector(bnk->Xwork, bnk->inactive_idx, &bnk->inactive_work);CHKERRQ(ierr);
583     ierr = VecRestoreSubVector(bnk->Gwork, bnk->inactive_idx, &bnk->G_inactive);CHKERRQ(ierr);
584   }
585   PetscFunctionReturn(0);
586 }
587 
588 /*------------------------------------------------------------*/
589 
590 /* Routine for ensuring that the Newton step is a descent direction.
591 
592    The step direction falls back onto BFGS, scaled gradient and gradient steps
593    in the event that the Newton step fails the test.
594 */
595 
596 PetscErrorCode TaoBNKSafeguardStep(Tao tao, KSPConvergedReason ksp_reason, PetscInt *stepType)
597 {
598   PetscErrorCode               ierr;
599   TAO_BNK                      *bnk = (TAO_BNK *)tao->data;
600 
601   PetscReal                    gdx, e_min;
602   PetscInt                     bfgsUpdates;
603 
604   PetscFunctionBegin;
605   switch (*stepType) {
606   case BNK_NEWTON:
607     ierr = VecDot(tao->stepdirection, tao->gradient, &gdx);CHKERRQ(ierr);
608     if ((gdx >= 0.0) || PetscIsInfOrNanReal(gdx)) {
609       /* Newton step is not descent or direction produced Inf or NaN
610         Update the perturbation for next time */
611       if (bnk->pert <= 0.0) {
612         /* Initialize the perturbation */
613         bnk->pert = PetscMin(bnk->imax, PetscMax(bnk->imin, bnk->imfac * bnk->gnorm));
614         if (bnk->is_gltr) {
615           ierr = KSPGLTRGetMinEig(tao->ksp,&e_min);CHKERRQ(ierr);
616           bnk->pert = PetscMax(bnk->pert, -e_min);
617         }
618       } else {
619         /* Increase the perturbation */
620         bnk->pert = PetscMin(bnk->pmax, PetscMax(bnk->pgfac * bnk->pert, bnk->pmgfac * bnk->gnorm));
621       }
622 
623       if (!bnk->M) {
624         /* We don't have the bfgs matrix around and updated
625           Must use gradient direction in this case */
626         ierr = VecCopy(tao->gradient, tao->stepdirection);CHKERRQ(ierr);
627         *stepType = BNK_GRADIENT;
628       } else {
629         /* Attempt to use the BFGS direction */
630         ierr = MatSolve(bnk->M, bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
631 
632         /* Check for success (descent direction)
633           NOTE: Negative gdx here means not a descent direction because
634           the fall-back step is missing a negative sign. */
635         ierr = VecDot(tao->gradient, tao->stepdirection, &gdx);CHKERRQ(ierr);
636         if ((gdx <= 0.0) || PetscIsInfOrNanReal(gdx)) {
637           /* BFGS direction is not descent or direction produced not a number
638             We can assert bfgsUpdates > 1 in this case because
639             the first solve produces the scaled gradient direction,
640             which is guaranteed to be descent */
641 
642           /* Use steepest descent direction (scaled) */
643           ierr = MatLMVMReset(bnk->M, PETSC_FALSE);CHKERRQ(ierr);
644           ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
645           ierr = MatSolve(bnk->M, bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
646 
647           *stepType = BNK_SCALED_GRADIENT;
648         } else {
649           ierr = MatLMVMGetUpdateCount(bnk->M, &bfgsUpdates);CHKERRQ(ierr);
650           if (1 == bfgsUpdates) {
651             /* The first BFGS direction is always the scaled gradient */
652             *stepType = BNK_SCALED_GRADIENT;
653           } else {
654             *stepType = BNK_BFGS;
655           }
656         }
657       }
658       /* Make sure the safeguarded fall-back step is zero for actively bounded variables */
659       ierr = VecScale(tao->stepdirection, -1.0);CHKERRQ(ierr);
660       ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
661     } else {
662       /* Computed Newton step is descent */
663       switch (ksp_reason) {
664       case KSP_DIVERGED_NANORINF:
665       case KSP_DIVERGED_BREAKDOWN:
666       case KSP_DIVERGED_INDEFINITE_MAT:
667       case KSP_DIVERGED_INDEFINITE_PC:
668       case KSP_CONVERGED_CG_NEG_CURVE:
669         /* Matrix or preconditioner is indefinite; increase perturbation */
670         if (bnk->pert <= 0.0) {
671           /* Initialize the perturbation */
672           bnk->pert = PetscMin(bnk->imax, PetscMax(bnk->imin, bnk->imfac * bnk->gnorm));
673           if (bnk->is_gltr) {
674             ierr = KSPGLTRGetMinEig(tao->ksp, &e_min);CHKERRQ(ierr);
675             bnk->pert = PetscMax(bnk->pert, -e_min);
676           }
677         } else {
678           /* Increase the perturbation */
679           bnk->pert = PetscMin(bnk->pmax, PetscMax(bnk->pgfac * bnk->pert, bnk->pmgfac * bnk->gnorm));
680         }
681         break;
682 
683       default:
684         /* Newton step computation is good; decrease perturbation */
685         bnk->pert = PetscMin(bnk->psfac * bnk->pert, bnk->pmsfac * bnk->gnorm);
686         if (bnk->pert < bnk->pmin) {
687           bnk->pert = 0.0;
688         }
689         break;
690       }
691       *stepType = BNK_NEWTON;
692     }
693     break;
694 
695   case BNK_BFGS:
696     /* Check for success (descent direction) */
697     ierr = VecDot(tao->stepdirection, tao->gradient, &gdx);CHKERRQ(ierr);
698     if (gdx >= 0 || PetscIsInfOrNanReal(gdx)) {
699       /* Step is not descent or solve was not successful
700          Use steepest descent direction (scaled) */
701       ierr = MatLMVMReset(bnk->M, PETSC_FALSE);CHKERRQ(ierr);
702       ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
703       ierr = MatSolve(bnk->M, tao->gradient, tao->stepdirection);CHKERRQ(ierr);
704       ierr = VecScale(tao->stepdirection,-1.0);CHKERRQ(ierr);
705       ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
706       *stepType = BNK_SCALED_GRADIENT;
707     } else {
708       *stepType = BNK_BFGS;
709     }
710     break;
711 
712   case BNK_SCALED_GRADIENT:
713     break;
714 
715   default:
716     break;
717   }
718 
719   PetscFunctionReturn(0);
720 }
721 
722 /*------------------------------------------------------------*/
723 
724 /* Routine for performing a bound-projected More-Thuente line search.
725 
726   Includes fallbacks to BFGS, scaled gradient, and unscaled gradient steps if the
727   Newton step does not produce a valid step length.
728 */
729 
730 PetscErrorCode TaoBNKPerformLineSearch(Tao tao, PetscInt *stepType, PetscReal *steplen, TaoLineSearchConvergedReason *reason)
731 {
732   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
733   PetscErrorCode ierr;
734   TaoLineSearchConvergedReason ls_reason;
735 
736   PetscReal      e_min, gdx;
737   PetscInt       bfgsUpdates;
738 
739   PetscFunctionBegin;
740   /* Perform the linesearch */
741   ierr = TaoLineSearchApply(tao->linesearch, tao->solution, &bnk->f, bnk->unprojected_gradient, tao->stepdirection, steplen, &ls_reason);CHKERRQ(ierr);
742   ierr = TaoAddLineSearchCounts(tao);CHKERRQ(ierr);
743 
744   while (ls_reason != TAOLINESEARCH_SUCCESS && ls_reason != TAOLINESEARCH_SUCCESS_USER && *stepType != BNK_SCALED_GRADIENT && *stepType != BNK_GRADIENT) {
745     /* Linesearch failed, revert solution */
746     bnk->f = bnk->fold;
747     ierr = VecCopy(bnk->Xold, tao->solution);CHKERRQ(ierr);
748     ierr = VecCopy(bnk->unprojected_gradient_old, bnk->unprojected_gradient);CHKERRQ(ierr);
749 
750     switch(*stepType) {
751     case BNK_NEWTON:
752       /* Failed to obtain acceptable iterate with Newton step
753          Update the perturbation for next time */
754       if (bnk->pert <= 0.0) {
755         /* Initialize the perturbation */
756         bnk->pert = PetscMin(bnk->imax, PetscMax(bnk->imin, bnk->imfac * bnk->gnorm));
757         if (bnk->is_gltr) {
758           ierr = KSPGLTRGetMinEig(tao->ksp,&e_min);CHKERRQ(ierr);
759           bnk->pert = PetscMax(bnk->pert, -e_min);
760         }
761       } else {
762         /* Increase the perturbation */
763         bnk->pert = PetscMin(bnk->pmax, PetscMax(bnk->pgfac * bnk->pert, bnk->pmgfac * bnk->gnorm));
764       }
765 
766       if (!bnk->M) {
767         /* We don't have the bfgs matrix around and being updated
768            Must use gradient direction in this case */
769         ierr = VecCopy(bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
770         *stepType = BNK_GRADIENT;
771       } else {
772         /* Attempt to use the BFGS direction */
773         ierr = MatSolve(bnk->M, bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
774         /* Check for success (descent direction)
775            NOTE: Negative gdx means not a descent direction because the step here is missing a negative sign. */
776         ierr = VecDot(tao->gradient, tao->stepdirection, &gdx);CHKERRQ(ierr);
777         if ((gdx <= 0.0) || PetscIsInfOrNanReal(gdx)) {
778           /* BFGS direction is not descent or direction produced not a number
779              We can assert bfgsUpdates > 1 in this case
780              Use steepest descent direction (scaled) */
781           ierr = MatLMVMReset(bnk->M, PETSC_FALSE);CHKERRQ(ierr);
782           ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
783           ierr = MatSolve(bnk->M, bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
784 
785           bfgsUpdates = 1;
786           *stepType = BNK_SCALED_GRADIENT;
787         } else {
788           ierr = MatLMVMGetUpdateCount(bnk->M, &bfgsUpdates);CHKERRQ(ierr);
789           if (1 == bfgsUpdates) {
790             /* The first BFGS direction is always the scaled gradient */
791             *stepType = BNK_SCALED_GRADIENT;
792           } else {
793             *stepType = BNK_BFGS;
794           }
795         }
796       }
797       break;
798 
799     case BNK_BFGS:
800       /* Can only enter if pc_type == BNK_PC_BFGS
801          Failed to obtain acceptable iterate with BFGS step
802          Attempt to use the scaled gradient direction */
803       ierr = MatLMVMReset(bnk->M, PETSC_FALSE);CHKERRQ(ierr);
804       ierr = MatLMVMUpdate(bnk->M, tao->solution, bnk->unprojected_gradient);CHKERRQ(ierr);
805       ierr = MatSolve(bnk->M, bnk->unprojected_gradient, tao->stepdirection);CHKERRQ(ierr);
806 
807       bfgsUpdates = 1;
808       *stepType = BNK_SCALED_GRADIENT;
809       break;
810     }
811     /* Make sure the safeguarded fall-back step is zero for actively bounded variables */
812     ierr = VecScale(tao->stepdirection, -1.0);CHKERRQ(ierr);
813     ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
814 
815     /* Perform one last line search with the fall-back step */
816     ierr = TaoLineSearchApply(tao->linesearch, tao->solution, &bnk->f, bnk->unprojected_gradient, tao->stepdirection, steplen, &ls_reason);CHKERRQ(ierr);
817     ierr = TaoAddLineSearchCounts(tao);CHKERRQ(ierr);
818   }
819   *reason = ls_reason;
820   PetscFunctionReturn(0);
821 }
822 
823 /*------------------------------------------------------------*/
824 
825 /* Routine for updating the trust radius.
826 
827   Function features three different update methods:
828   1) Line-search step length based
829   2) Predicted decrease on the CG quadratic model
830   3) Interpolation
831 */
832 
833 PetscErrorCode TaoBNKUpdateTrustRadius(Tao tao, PetscReal prered, PetscReal actred, PetscInt updateType, PetscInt stepType, PetscBool *accept)
834 {
835   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
836   PetscErrorCode ierr;
837 
838   PetscReal      step, kappa;
839   PetscReal      gdx, tau_1, tau_2, tau_min, tau_max;
840 
841   PetscFunctionBegin;
842   /* Update trust region radius */
843   *accept = PETSC_FALSE;
844   switch(updateType) {
845   case BNK_UPDATE_STEP:
846     *accept = PETSC_TRUE; /* always accept here because line search succeeded */
847     if (stepType == BNK_NEWTON) {
848       ierr = TaoLineSearchGetStepLength(tao->linesearch, &step);CHKERRQ(ierr);
849       if (step < bnk->nu1) {
850         /* Very bad step taken; reduce radius */
851         tao->trust = bnk->omega1 * PetscMin(bnk->dnorm, tao->trust);
852       } else if (step < bnk->nu2) {
853         /* Reasonably bad step taken; reduce radius */
854         tao->trust = bnk->omega2 * PetscMin(bnk->dnorm, tao->trust);
855       } else if (step < bnk->nu3) {
856         /*  Reasonable step was taken; leave radius alone */
857         if (bnk->omega3 < 1.0) {
858           tao->trust = bnk->omega3 * PetscMin(bnk->dnorm, tao->trust);
859         } else if (bnk->omega3 > 1.0) {
860           tao->trust = PetscMax(bnk->omega3 * bnk->dnorm, tao->trust);
861         }
862       } else if (step < bnk->nu4) {
863         /*  Full step taken; increase the radius */
864         tao->trust = PetscMax(bnk->omega4 * bnk->dnorm, tao->trust);
865       } else {
866         /*  More than full step taken; increase the radius */
867         tao->trust = PetscMax(bnk->omega5 * bnk->dnorm, tao->trust);
868       }
869     } else {
870       /*  Newton step was not good; reduce the radius */
871       tao->trust = bnk->omega1 * PetscMin(bnk->dnorm, tao->trust);
872     }
873     break;
874 
875   case BNK_UPDATE_REDUCTION:
876     if (stepType == BNK_NEWTON) {
877       if ((prered < 0.0) || PetscIsInfOrNanReal(prered)) {
878         /* The predicted reduction has the wrong sign.  This cannot
879            happen in infinite precision arithmetic.  Step should
880            be rejected! */
881         tao->trust = bnk->alpha1 * PetscMin(tao->trust, bnk->dnorm);
882       } else {
883         if (PetscIsInfOrNanReal(actred)) {
884           tao->trust = bnk->alpha1 * PetscMin(tao->trust, bnk->dnorm);
885         } else {
886           if ((PetscAbsScalar(actred) <= PetscMax(1.0, PetscAbsScalar(bnk->f))*bnk->epsilon) && (PetscAbsScalar(prered) <= PetscMax(1.0, PetscAbsScalar(bnk->f))*bnk->epsilon)) {
887             kappa = 1.0;
888           } else {
889             kappa = actred / prered;
890           }
891           /* Accept or reject the step and update radius */
892           if (kappa < bnk->eta1) {
893             /* Reject the step */
894             tao->trust = bnk->alpha1 * PetscMin(tao->trust, bnk->dnorm);
895           } else {
896             /* Accept the step */
897             *accept = PETSC_TRUE;
898             /* Update the trust region radius only if the computed step is at the trust radius boundary */
899             if (bnk->dnorm == tao->trust) {
900               if (kappa < bnk->eta2) {
901                 /* Marginal bad step */
902                 tao->trust = bnk->alpha2 * tao->trust;
903               } else if (kappa < bnk->eta3) {
904                 /* Reasonable step */
905                 tao->trust = bnk->alpha3 * tao->trust;
906               } else if (kappa < bnk->eta4) {
907                 /* Good step */
908                 tao->trust = bnk->alpha4 * tao->trust;
909               } else {
910                 /* Very good step */
911                 tao->trust = bnk->alpha5 * tao->trust;
912               }
913             }
914           }
915         }
916       }
917     } else {
918       /*  Newton step was not good; reduce the radius */
919       tao->trust = bnk->alpha1 * PetscMin(bnk->dnorm, tao->trust);
920     }
921     break;
922 
923   default:
924     if (stepType == BNK_NEWTON) {
925       if (prered < 0.0) {
926         /*  The predicted reduction has the wrong sign.  This cannot */
927         /*  happen in infinite precision arithmetic.  Step should */
928         /*  be rejected! */
929         tao->trust = bnk->gamma1 * PetscMin(tao->trust, bnk->dnorm);
930       } else {
931         if (PetscIsInfOrNanReal(actred)) {
932           tao->trust = bnk->gamma1 * PetscMin(tao->trust, bnk->dnorm);
933         } else {
934           if ((PetscAbsScalar(actred) <= bnk->epsilon) && (PetscAbsScalar(prered) <= bnk->epsilon)) {
935             kappa = 1.0;
936           } else {
937             kappa = actred / prered;
938           }
939 
940           ierr = VecDot(tao->gradient, tao->stepdirection, &gdx);CHKERRQ(ierr);
941           tau_1 = bnk->theta * gdx / (bnk->theta * gdx - (1.0 - bnk->theta) * prered + actred);
942           tau_2 = bnk->theta * gdx / (bnk->theta * gdx + (1.0 + bnk->theta) * prered - actred);
943           tau_min = PetscMin(tau_1, tau_2);
944           tau_max = PetscMax(tau_1, tau_2);
945 
946           if (kappa >= 1.0 - bnk->mu1) {
947             /*  Great agreement */
948             *accept = PETSC_TRUE;
949             if (tau_max < 1.0) {
950               tao->trust = PetscMax(tao->trust, bnk->gamma3 * bnk->dnorm);
951             } else if (tau_max > bnk->gamma4) {
952               tao->trust = PetscMax(tao->trust, bnk->gamma4 * bnk->dnorm);
953             } else {
954               tao->trust = PetscMax(tao->trust, tau_max * bnk->dnorm);
955             }
956           } else if (kappa >= 1.0 - bnk->mu2) {
957             /*  Good agreement */
958             *accept = PETSC_TRUE;
959             if (tau_max < bnk->gamma2) {
960               tao->trust = bnk->gamma2 * PetscMin(tao->trust, bnk->dnorm);
961             } else if (tau_max > bnk->gamma3) {
962               tao->trust = PetscMax(tao->trust, bnk->gamma3 * bnk->dnorm);
963             } else if (tau_max < 1.0) {
964               tao->trust = tau_max * PetscMin(tao->trust, bnk->dnorm);
965             } else {
966               tao->trust = PetscMax(tao->trust, tau_max * bnk->dnorm);
967             }
968           } else {
969             /*  Not good agreement */
970             if (tau_min > 1.0) {
971               tao->trust = bnk->gamma2 * PetscMin(tao->trust, bnk->dnorm);
972             } else if (tau_max < bnk->gamma1) {
973               tao->trust = bnk->gamma1 * PetscMin(tao->trust, bnk->dnorm);
974             } else if ((tau_min < bnk->gamma1) && (tau_max >= 1.0)) {
975               tao->trust = bnk->gamma1 * PetscMin(tao->trust, bnk->dnorm);
976             } else if ((tau_1 >= bnk->gamma1) && (tau_1 < 1.0) && ((tau_2 < bnk->gamma1) || (tau_2 >= 1.0))) {
977               tao->trust = tau_1 * PetscMin(tao->trust, bnk->dnorm);
978             } else if ((tau_2 >= bnk->gamma1) && (tau_2 < 1.0) && ((tau_1 < bnk->gamma1) || (tau_2 >= 1.0))) {
979               tao->trust = tau_2 * PetscMin(tao->trust, bnk->dnorm);
980             } else {
981               tao->trust = tau_max * PetscMin(tao->trust, bnk->dnorm);
982             }
983           }
984         }
985       }
986     } else {
987       /*  Newton step was not good; reduce the radius */
988       tao->trust = bnk->gamma1 * PetscMin(bnk->dnorm, tao->trust);
989     }
990     break;
991   }
992   /* Make sure the radius does not violate min and max settings */
993   tao->trust = PetscMin(tao->trust, bnk->max_radius);
994   tao->trust = PetscMax(tao->trust, bnk->min_radius);
995   PetscFunctionReturn(0);
996 }
997 
998 /* ---------------------------------------------------------- */
999 
1000 PetscErrorCode TaoBNKAddStepCounts(Tao tao, PetscInt stepType)
1001 {
1002   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
1003 
1004   PetscFunctionBegin;
1005   switch (stepType) {
1006   case BNK_NEWTON:
1007     ++bnk->newt;
1008     break;
1009   case BNK_BFGS:
1010     ++bnk->bfgs;
1011     break;
1012   case BNK_SCALED_GRADIENT:
1013     ++bnk->sgrad;
1014     break;
1015   case BNK_GRADIENT:
1016     ++bnk->grad;
1017     break;
1018   default:
1019     break;
1020   }
1021   PetscFunctionReturn(0);
1022 }
1023 
1024 /* ---------------------------------------------------------- */
1025 
1026 PetscErrorCode TaoSetUp_BNK(Tao tao)
1027 {
1028   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
1029   PetscErrorCode ierr;
1030   PetscInt       i;
1031   KSPType        ksp_type;
1032 
1033   PetscFunctionBegin;
1034   if (!tao->gradient) {
1035     ierr = VecDuplicate(tao->solution,&tao->gradient);CHKERRQ(ierr);
1036   }
1037   if (!tao->stepdirection) {
1038     ierr = VecDuplicate(tao->solution,&tao->stepdirection);CHKERRQ(ierr);
1039   }
1040   if (!bnk->W) {
1041     ierr = VecDuplicate(tao->solution,&bnk->W);CHKERRQ(ierr);
1042   }
1043   if (!bnk->Xold) {
1044     ierr = VecDuplicate(tao->solution,&bnk->Xold);CHKERRQ(ierr);
1045   }
1046   if (!bnk->Gold) {
1047     ierr = VecDuplicate(tao->solution,&bnk->Gold);CHKERRQ(ierr);
1048   }
1049   if (!bnk->Xwork) {
1050     ierr = VecDuplicate(tao->solution,&bnk->Xwork);CHKERRQ(ierr);
1051   }
1052   if (!bnk->Gwork) {
1053     ierr = VecDuplicate(tao->solution,&bnk->Gwork);CHKERRQ(ierr);
1054   }
1055   if (!bnk->unprojected_gradient) {
1056     ierr = VecDuplicate(tao->solution,&bnk->unprojected_gradient);CHKERRQ(ierr);
1057   }
1058   if (!bnk->unprojected_gradient_old) {
1059     ierr = VecDuplicate(tao->solution,&bnk->unprojected_gradient_old);CHKERRQ(ierr);
1060   }
1061   if (!bnk->Diag_min) {
1062     ierr = VecDuplicate(tao->solution,&bnk->Diag_min);CHKERRQ(ierr);
1063   }
1064   if (!bnk->Diag_max) {
1065     ierr = VecDuplicate(tao->solution,&bnk->Diag_max);CHKERRQ(ierr);
1066   }
1067   if (bnk->max_cg_its > 0) {
1068     /* Ensure that the important common vectors are shared between BNK and embedded BNCG */
1069     bnk->bncg_ctx = (TAO_BNCG *)bnk->bncg->data;
1070     ierr = PetscObjectReference((PetscObject)(bnk->unprojected_gradient_old));CHKERRQ(ierr);
1071     ierr = VecDestroy(&bnk->bncg_ctx->unprojected_gradient_old);CHKERRQ(ierr);
1072     bnk->bncg_ctx->unprojected_gradient_old = bnk->unprojected_gradient_old;
1073     ierr = PetscObjectReference((PetscObject)(bnk->unprojected_gradient));CHKERRQ(ierr);
1074     ierr = VecDestroy(&bnk->bncg_ctx->unprojected_gradient);CHKERRQ(ierr);
1075     bnk->bncg_ctx->unprojected_gradient = bnk->unprojected_gradient;
1076     ierr = PetscObjectReference((PetscObject)(bnk->Gold));CHKERRQ(ierr);
1077     ierr = VecDestroy(&bnk->bncg_ctx->G_old);CHKERRQ(ierr);
1078     bnk->bncg_ctx->G_old = bnk->Gold;
1079     ierr = PetscObjectReference((PetscObject)(tao->gradient));CHKERRQ(ierr);
1080     ierr = VecDestroy(&bnk->bncg->gradient);CHKERRQ(ierr);
1081     bnk->bncg->gradient = tao->gradient;
1082     ierr = PetscObjectReference((PetscObject)(tao->stepdirection));CHKERRQ(ierr);
1083     ierr = VecDestroy(&bnk->bncg->stepdirection);CHKERRQ(ierr);
1084     bnk->bncg->stepdirection = tao->stepdirection;
1085     ierr = TaoSetInitialVector(bnk->bncg, tao->solution);CHKERRQ(ierr);
1086     /* Copy over some settings from BNK into BNCG */
1087     ierr = TaoSetMaximumIterations(bnk->bncg, bnk->max_cg_its);CHKERRQ(ierr);
1088     ierr = TaoSetTolerances(bnk->bncg, tao->gatol, tao->grtol, tao->gttol);CHKERRQ(ierr);
1089     ierr = TaoSetFunctionLowerBound(bnk->bncg, tao->fmin);CHKERRQ(ierr);
1090     ierr = TaoSetConvergenceTest(bnk->bncg, tao->ops->convergencetest, tao->cnvP);CHKERRQ(ierr);
1091     ierr = TaoSetObjectiveRoutine(bnk->bncg, tao->ops->computeobjective, tao->user_objP);CHKERRQ(ierr);
1092     ierr = TaoSetGradientRoutine(bnk->bncg, tao->ops->computegradient, tao->user_gradP);CHKERRQ(ierr);
1093     ierr = TaoSetObjectiveAndGradientRoutine(bnk->bncg, tao->ops->computeobjectiveandgradient, tao->user_objgradP);CHKERRQ(ierr);
1094     ierr = PetscObjectCopyFortranFunctionPointers((PetscObject)tao, (PetscObject)(bnk->bncg));CHKERRQ(ierr);
1095     for (i=0; i<tao->numbermonitors; ++i) {
1096       ierr = TaoSetMonitor(bnk->bncg, tao->monitor[i], tao->monitorcontext[i], tao->monitordestroy[i]);CHKERRQ(ierr);
1097       ierr = PetscObjectReference((PetscObject)(tao->monitorcontext[i]));CHKERRQ(ierr);
1098     }
1099   }
1100   ierr = KSPGetType(tao->ksp,&ksp_type);CHKERRQ(ierr);
1101   ierr = PetscStrcmp(ksp_type,KSPNASH,&bnk->is_nash);CHKERRQ(ierr);
1102   ierr = PetscStrcmp(ksp_type,KSPSTCG,&bnk->is_stcg);CHKERRQ(ierr);
1103   ierr = PetscStrcmp(ksp_type,KSPGLTR,&bnk->is_gltr);CHKERRQ(ierr);
1104   bnk->X_inactive = NULL;
1105   bnk->G_inactive = NULL;
1106   bnk->inactive_work = NULL;
1107   bnk->active_work = NULL;
1108   bnk->inactive_idx = NULL;
1109   bnk->active_idx = NULL;
1110   bnk->active_lower = NULL;
1111   bnk->active_upper = NULL;
1112   bnk->active_fixed = NULL;
1113   bnk->M = NULL;
1114   bnk->H_inactive = NULL;
1115   bnk->Hpre_inactive = NULL;
1116   PetscFunctionReturn(0);
1117 }
1118 
1119 /*------------------------------------------------------------*/
1120 
1121 PetscErrorCode TaoDestroy_BNK(Tao tao)
1122 {
1123   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
1124   PetscErrorCode ierr;
1125 
1126   PetscFunctionBegin;
1127   if (tao->setupcalled) {
1128     ierr = VecDestroy(&bnk->W);CHKERRQ(ierr);
1129     ierr = VecDestroy(&bnk->Xold);CHKERRQ(ierr);
1130     ierr = VecDestroy(&bnk->Gold);CHKERRQ(ierr);
1131     ierr = VecDestroy(&bnk->Xwork);CHKERRQ(ierr);
1132     ierr = VecDestroy(&bnk->Gwork);CHKERRQ(ierr);
1133     ierr = VecDestroy(&bnk->unprojected_gradient);CHKERRQ(ierr);
1134     ierr = VecDestroy(&bnk->unprojected_gradient_old);CHKERRQ(ierr);
1135     ierr = VecDestroy(&bnk->Diag_min);CHKERRQ(ierr);
1136     ierr = VecDestroy(&bnk->Diag_max);CHKERRQ(ierr);
1137   }
1138   ierr = ISDestroy(&bnk->active_lower);CHKERRQ(ierr);
1139   ierr = ISDestroy(&bnk->active_upper);CHKERRQ(ierr);
1140   ierr = ISDestroy(&bnk->active_fixed);CHKERRQ(ierr);
1141   ierr = ISDestroy(&bnk->active_idx);CHKERRQ(ierr);
1142   ierr = ISDestroy(&bnk->inactive_idx);CHKERRQ(ierr);
1143   ierr = MatDestroy(&bnk->Hpre_inactive);CHKERRQ(ierr);
1144   ierr = MatDestroy(&bnk->H_inactive);CHKERRQ(ierr);
1145   ierr = TaoDestroy(&bnk->bncg);CHKERRQ(ierr);
1146   ierr = PetscFree(tao->data);CHKERRQ(ierr);
1147   PetscFunctionReturn(0);
1148 }
1149 
1150 /*------------------------------------------------------------*/
1151 
1152 PetscErrorCode TaoSetFromOptions_BNK(PetscOptionItems *PetscOptionsObject,Tao tao)
1153 {
1154   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
1155   PetscErrorCode ierr;
1156 
1157   PetscFunctionBegin;
1158   ierr = PetscOptionsHead(PetscOptionsObject,"Newton-Krylov method for bound constrained optimization");CHKERRQ(ierr);
1159   ierr = PetscOptionsEList("-tao_bnk_init_type", "radius initialization type", "", BNK_INIT, BNK_INIT_TYPES, BNK_INIT[bnk->init_type], &bnk->init_type, NULL);CHKERRQ(ierr);
1160   ierr = PetscOptionsEList("-tao_bnk_update_type", "radius update type", "", BNK_UPDATE, BNK_UPDATE_TYPES, BNK_UPDATE[bnk->update_type], &bnk->update_type, NULL);CHKERRQ(ierr);
1161   ierr = PetscOptionsEList("-tao_bnk_as_type", "active set estimation method", "", BNK_AS, BNK_AS_TYPES, BNK_AS[bnk->as_type], &bnk->as_type, NULL);CHKERRQ(ierr);
1162   ierr = PetscOptionsReal("-tao_bnk_sval", "(developer) Hessian perturbation starting value", "", bnk->sval, &bnk->sval,NULL);CHKERRQ(ierr);
1163   ierr = PetscOptionsReal("-tao_bnk_imin", "(developer) minimum initial Hessian perturbation", "", bnk->imin, &bnk->imin,NULL);CHKERRQ(ierr);
1164   ierr = PetscOptionsReal("-tao_bnk_imax", "(developer) maximum initial Hessian perturbation", "", bnk->imax, &bnk->imax,NULL);CHKERRQ(ierr);
1165   ierr = PetscOptionsReal("-tao_bnk_imfac", "(developer) initial merit factor for Hessian perturbation", "", bnk->imfac, &bnk->imfac,NULL);CHKERRQ(ierr);
1166   ierr = PetscOptionsReal("-tao_bnk_pmin", "(developer) minimum Hessian perturbation", "", bnk->pmin, &bnk->pmin,NULL);CHKERRQ(ierr);
1167   ierr = PetscOptionsReal("-tao_bnk_pmax", "(developer) maximum Hessian perturbation", "", bnk->pmax, &bnk->pmax,NULL);CHKERRQ(ierr);
1168   ierr = PetscOptionsReal("-tao_bnk_pgfac", "(developer) Hessian perturbation growth factor", "", bnk->pgfac, &bnk->pgfac,NULL);CHKERRQ(ierr);
1169   ierr = PetscOptionsReal("-tao_bnk_psfac", "(developer) Hessian perturbation shrink factor", "", bnk->psfac, &bnk->psfac,NULL);CHKERRQ(ierr);
1170   ierr = PetscOptionsReal("-tao_bnk_pmgfac", "(developer) merit growth factor for Hessian perturbation", "", bnk->pmgfac, &bnk->pmgfac,NULL);CHKERRQ(ierr);
1171   ierr = PetscOptionsReal("-tao_bnk_pmsfac", "(developer) merit shrink factor for Hessian perturbation", "", bnk->pmsfac, &bnk->pmsfac,NULL);CHKERRQ(ierr);
1172   ierr = PetscOptionsReal("-tao_bnk_eta1", "(developer) threshold for rejecting step (-tao_bnk_update_type reduction)", "", bnk->eta1, &bnk->eta1,NULL);CHKERRQ(ierr);
1173   ierr = PetscOptionsReal("-tao_bnk_eta2", "(developer) threshold for accepting marginal step (-tao_bnk_update_type reduction)", "", bnk->eta2, &bnk->eta2,NULL);CHKERRQ(ierr);
1174   ierr = PetscOptionsReal("-tao_bnk_eta3", "(developer) threshold for accepting reasonable step (-tao_bnk_update_type reduction)", "", bnk->eta3, &bnk->eta3,NULL);CHKERRQ(ierr);
1175   ierr = PetscOptionsReal("-tao_bnk_eta4", "(developer) threshold for accepting good step (-tao_bnk_update_type reduction)", "", bnk->eta4, &bnk->eta4,NULL);CHKERRQ(ierr);
1176   ierr = PetscOptionsReal("-tao_bnk_alpha1", "(developer) radius reduction factor for rejected step (-tao_bnk_update_type reduction)", "", bnk->alpha1, &bnk->alpha1,NULL);CHKERRQ(ierr);
1177   ierr = PetscOptionsReal("-tao_bnk_alpha2", "(developer) radius reduction factor for marginally accepted bad step (-tao_bnk_update_type reduction)", "", bnk->alpha2, &bnk->alpha2,NULL);CHKERRQ(ierr);
1178   ierr = PetscOptionsReal("-tao_bnk_alpha3", "(developer) radius increase factor for reasonable accepted step (-tao_bnk_update_type reduction)", "", bnk->alpha3, &bnk->alpha3,NULL);CHKERRQ(ierr);
1179   ierr = PetscOptionsReal("-tao_bnk_alpha4", "(developer) radius increase factor for good accepted step (-tao_bnk_update_type reduction)", "", bnk->alpha4, &bnk->alpha4,NULL);CHKERRQ(ierr);
1180   ierr = PetscOptionsReal("-tao_bnk_alpha5", "(developer) radius increase factor for very good accepted step (-tao_bnk_update_type reduction)", "", bnk->alpha5, &bnk->alpha5,NULL);CHKERRQ(ierr);
1181   ierr = PetscOptionsReal("-tao_bnk_nu1", "(developer) threshold for small line-search step length (-tao_bnk_update_type step)", "", bnk->nu1, &bnk->nu1,NULL);CHKERRQ(ierr);
1182   ierr = PetscOptionsReal("-tao_bnk_nu2", "(developer) threshold for reasonable line-search step length (-tao_bnk_update_type step)", "", bnk->nu2, &bnk->nu2,NULL);CHKERRQ(ierr);
1183   ierr = PetscOptionsReal("-tao_bnk_nu3", "(developer) threshold for large line-search step length (-tao_bnk_update_type step)", "", bnk->nu3, &bnk->nu3,NULL);CHKERRQ(ierr);
1184   ierr = PetscOptionsReal("-tao_bnk_nu4", "(developer) threshold for very large line-search step length (-tao_bnk_update_type step)", "", bnk->nu4, &bnk->nu4,NULL);CHKERRQ(ierr);
1185   ierr = PetscOptionsReal("-tao_bnk_omega1", "(developer) radius reduction factor for very small line-search step length (-tao_bnk_update_type step)", "", bnk->omega1, &bnk->omega1,NULL);CHKERRQ(ierr);
1186   ierr = PetscOptionsReal("-tao_bnk_omega2", "(developer) radius reduction factor for small line-search step length (-tao_bnk_update_type step)", "", bnk->omega2, &bnk->omega2,NULL);CHKERRQ(ierr);
1187   ierr = PetscOptionsReal("-tao_bnk_omega3", "(developer) radius factor for decent line-search step length (-tao_bnk_update_type step)", "", bnk->omega3, &bnk->omega3,NULL);CHKERRQ(ierr);
1188   ierr = PetscOptionsReal("-tao_bnk_omega4", "(developer) radius increase factor for large line-search step length (-tao_bnk_update_type step)", "", bnk->omega4, &bnk->omega4,NULL);CHKERRQ(ierr);
1189   ierr = PetscOptionsReal("-tao_bnk_omega5", "(developer) radius increase factor for very large line-search step length (-tao_bnk_update_type step)", "", bnk->omega5, &bnk->omega5,NULL);CHKERRQ(ierr);
1190   ierr = PetscOptionsReal("-tao_bnk_mu1_i", "(developer) threshold for accepting very good step (-tao_bnk_init_type interpolation)", "", bnk->mu1_i, &bnk->mu1_i,NULL);CHKERRQ(ierr);
1191   ierr = PetscOptionsReal("-tao_bnk_mu2_i", "(developer) threshold for accepting good step (-tao_bnk_init_type interpolation)", "", bnk->mu2_i, &bnk->mu2_i,NULL);CHKERRQ(ierr);
1192   ierr = PetscOptionsReal("-tao_bnk_gamma1_i", "(developer) radius reduction factor for rejected very bad step (-tao_bnk_init_type interpolation)", "", bnk->gamma1_i, &bnk->gamma1_i,NULL);CHKERRQ(ierr);
1193   ierr = PetscOptionsReal("-tao_bnk_gamma2_i", "(developer) radius reduction factor for rejected bad step (-tao_bnk_init_type interpolation)", "", bnk->gamma2_i, &bnk->gamma2_i,NULL);CHKERRQ(ierr);
1194   ierr = PetscOptionsReal("-tao_bnk_gamma3_i", "(developer) radius increase factor for accepted good step (-tao_bnk_init_type interpolation)", "", bnk->gamma3_i, &bnk->gamma3_i,NULL);CHKERRQ(ierr);
1195   ierr = PetscOptionsReal("-tao_bnk_gamma4_i", "(developer) radius increase factor for accepted very good step (-tao_bnk_init_type interpolation)", "", bnk->gamma4_i, &bnk->gamma4_i,NULL);CHKERRQ(ierr);
1196   ierr = PetscOptionsReal("-tao_bnk_theta_i", "(developer) trust region interpolation factor (-tao_bnk_init_type interpolation)", "", bnk->theta_i, &bnk->theta_i,NULL);CHKERRQ(ierr);
1197   ierr = PetscOptionsReal("-tao_bnk_mu1", "(developer) threshold for accepting very good step (-tao_bnk_update_type interpolation)", "", bnk->mu1, &bnk->mu1,NULL);CHKERRQ(ierr);
1198   ierr = PetscOptionsReal("-tao_bnk_mu2", "(developer) threshold for accepting good step (-tao_bnk_update_type interpolation)", "", bnk->mu2, &bnk->mu2,NULL);CHKERRQ(ierr);
1199   ierr = PetscOptionsReal("-tao_bnk_gamma1", "(developer) radius reduction factor for rejected very bad step (-tao_bnk_update_type interpolation)", "", bnk->gamma1, &bnk->gamma1,NULL);CHKERRQ(ierr);
1200   ierr = PetscOptionsReal("-tao_bnk_gamma2", "(developer) radius reduction factor for rejected bad step (-tao_bnk_update_type interpolation)", "", bnk->gamma2, &bnk->gamma2,NULL);CHKERRQ(ierr);
1201   ierr = PetscOptionsReal("-tao_bnk_gamma3", "(developer) radius increase factor for accepted good step (-tao_bnk_update_type interpolation)", "", bnk->gamma3, &bnk->gamma3,NULL);CHKERRQ(ierr);
1202   ierr = PetscOptionsReal("-tao_bnk_gamma4", "(developer) radius increase factor for accepted very good step (-tao_bnk_update_type interpolation)", "", bnk->gamma4, &bnk->gamma4,NULL);CHKERRQ(ierr);
1203   ierr = PetscOptionsReal("-tao_bnk_theta", "(developer) trust region interpolation factor (-tao_bnk_update_type interpolation)", "", bnk->theta, &bnk->theta,NULL);CHKERRQ(ierr);
1204   ierr = PetscOptionsReal("-tao_bnk_min_radius", "(developer) lower bound on initial radius", "", bnk->min_radius, &bnk->min_radius,NULL);CHKERRQ(ierr);
1205   ierr = PetscOptionsReal("-tao_bnk_max_radius", "(developer) upper bound on radius", "", bnk->max_radius, &bnk->max_radius,NULL);CHKERRQ(ierr);
1206   ierr = PetscOptionsReal("-tao_bnk_epsilon", "(developer) tolerance used when computing actual and predicted reduction", "", bnk->epsilon, &bnk->epsilon,NULL);CHKERRQ(ierr);
1207   ierr = PetscOptionsReal("-tao_bnk_as_tol", "(developer) initial tolerance used when estimating actively bounded variables", "", bnk->as_tol, &bnk->as_tol,NULL);CHKERRQ(ierr);
1208   ierr = PetscOptionsReal("-tao_bnk_as_step", "(developer) step length used when estimating actively bounded variables", "", bnk->as_step, &bnk->as_step,NULL);CHKERRQ(ierr);
1209   ierr = PetscOptionsInt("-tao_bnk_max_cg_its", "number of BNCG iterations to take for each Newton step", "", bnk->max_cg_its, &bnk->max_cg_its,NULL);CHKERRQ(ierr);
1210   ierr = PetscOptionsTail();CHKERRQ(ierr);
1211   ierr = TaoSetFromOptions(bnk->bncg);CHKERRQ(ierr);
1212   ierr = TaoLineSearchSetFromOptions(tao->linesearch);CHKERRQ(ierr);
1213   ierr = KSPSetFromOptions(tao->ksp);CHKERRQ(ierr);
1214   PetscFunctionReturn(0);
1215 }
1216 
1217 /*------------------------------------------------------------*/
1218 
1219 PetscErrorCode TaoView_BNK(Tao tao, PetscViewer viewer)
1220 {
1221   TAO_BNK        *bnk = (TAO_BNK *)tao->data;
1222   PetscInt       nrejects;
1223   PetscBool      isascii;
1224   PetscErrorCode ierr;
1225 
1226   PetscFunctionBegin;
1227   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr);
1228   if (isascii) {
1229     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1230     if (bnk->M) {
1231       ierr = MatLMVMGetRejectCount(bnk->M,&nrejects);CHKERRQ(ierr);
1232       ierr = PetscViewerASCIIPrintf(viewer, "Rejected BFGS updates: %D\n",nrejects);CHKERRQ(ierr);
1233     }
1234     ierr = PetscViewerASCIIPrintf(viewer, "CG steps: %D\n", bnk->tot_cg_its);CHKERRQ(ierr);
1235     ierr = PetscViewerASCIIPrintf(viewer, "Newton steps: %D\n", bnk->newt);CHKERRQ(ierr);
1236     if (bnk->M) {
1237       ierr = PetscViewerASCIIPrintf(viewer, "BFGS steps: %D\n", bnk->bfgs);CHKERRQ(ierr);
1238     }
1239     ierr = PetscViewerASCIIPrintf(viewer, "Scaled gradient steps: %D\n", bnk->sgrad);CHKERRQ(ierr);
1240     ierr = PetscViewerASCIIPrintf(viewer, "Gradient steps: %D\n", bnk->grad);CHKERRQ(ierr);
1241     ierr = PetscViewerASCIIPrintf(viewer, "KSP termination reasons:\n");CHKERRQ(ierr);
1242     ierr = PetscViewerASCIIPrintf(viewer, "  atol: %D\n", bnk->ksp_atol);CHKERRQ(ierr);
1243     ierr = PetscViewerASCIIPrintf(viewer, "  rtol: %D\n", bnk->ksp_rtol);CHKERRQ(ierr);
1244     ierr = PetscViewerASCIIPrintf(viewer, "  ctol: %D\n", bnk->ksp_ctol);CHKERRQ(ierr);
1245     ierr = PetscViewerASCIIPrintf(viewer, "  negc: %D\n", bnk->ksp_negc);CHKERRQ(ierr);
1246     ierr = PetscViewerASCIIPrintf(viewer, "  dtol: %D\n", bnk->ksp_dtol);CHKERRQ(ierr);
1247     ierr = PetscViewerASCIIPrintf(viewer, "  iter: %D\n", bnk->ksp_iter);CHKERRQ(ierr);
1248     ierr = PetscViewerASCIIPrintf(viewer, "  othr: %D\n", bnk->ksp_othr);CHKERRQ(ierr);
1249     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1250   }
1251   PetscFunctionReturn(0);
1252 }
1253 
1254 /* ---------------------------------------------------------- */
1255 
1256 /*MC
1257   TAOBNK - Shared base-type for Bounded Newton-Krylov type algorithms.
1258   At each iteration, the BNK methods solve the symmetric
1259   system of equations to obtain the step diretion dk:
1260               Hk dk = -gk
1261   for free variables only. The step can be globalized either through
1262   trust-region methods, or a line search, or a heuristic mixture of both.
1263 
1264     Options Database Keys:
1265 + -tao_bnk_max_cg_its - maximum number of bounded conjugate-gradient iterations taken in each Newton loop
1266 . -tao_bnk_init_type - trust radius initialization method ("constant", "direction", "interpolation")
1267 . -tao_bnk_update_type - trust radius update method ("step", "direction", "interpolation")
1268 . -tao_bnk_as_type - active-set estimation method ("none", "bertsekas")
1269 . -tao_bnk_as_tol - (developer) initial tolerance used in estimating bounded active variables (-as_type bertsekas)
1270 . -tao_bnk_as_step - (developer) trial step length used in estimating bounded active variables (-as_type bertsekas)
1271 . -tao_bnk_sval - (developer) Hessian perturbation starting value
1272 . -tao_bnk_imin - (developer) minimum initial Hessian perturbation
1273 . -tao_bnk_imax - (developer) maximum initial Hessian perturbation
1274 . -tao_bnk_pmin - (developer) minimum Hessian perturbation
1275 . -tao_bnk_pmax - (developer) aximum Hessian perturbation
1276 . -tao_bnk_pgfac - (developer) Hessian perturbation growth factor
1277 . -tao_bnk_psfac - (developer) Hessian perturbation shrink factor
1278 . -tao_bnk_imfac - (developer) initial merit factor for Hessian perturbation
1279 . -tao_bnk_pmgfac - (developer) merit growth factor for Hessian perturbation
1280 . -tao_bnk_pmsfac - (developer) merit shrink factor for Hessian perturbation
1281 . -tao_bnk_eta1 - (developer) threshold for rejecting step (-update_type reduction)
1282 . -tao_bnk_eta2 - (developer) threshold for accepting marginal step (-update_type reduction)
1283 . -tao_bnk_eta3 - (developer) threshold for accepting reasonable step (-update_type reduction)
1284 . -tao_bnk_eta4 - (developer) threshold for accepting good step (-update_type reduction)
1285 . -tao_bnk_alpha1 - (developer) radius reduction factor for rejected step (-update_type reduction)
1286 . -tao_bnk_alpha2 - (developer) radius reduction factor for marginally accepted bad step (-update_type reduction)
1287 . -tao_bnk_alpha3 - (developer) radius increase factor for reasonable accepted step (-update_type reduction)
1288 . -tao_bnk_alpha4 - (developer) radius increase factor for good accepted step (-update_type reduction)
1289 . -tao_bnk_alpha5 - (developer) radius increase factor for very good accepted step (-update_type reduction)
1290 . -tao_bnk_epsilon - (developer) tolerance for small pred/actual ratios that trigger automatic step acceptance (-update_type reduction)
1291 . -tao_bnk_mu1 - (developer) threshold for accepting very good step (-update_type interpolation)
1292 . -tao_bnk_mu2 - (developer) threshold for accepting good step (-update_type interpolation)
1293 . -tao_bnk_gamma1 - (developer) radius reduction factor for rejected very bad step (-update_type interpolation)
1294 . -tao_bnk_gamma2 - (developer) radius reduction factor for rejected bad step (-update_type interpolation)
1295 . -tao_bnk_gamma3 - (developer) radius increase factor for accepted good step (-update_type interpolation)
1296 . -tao_bnk_gamma4 - (developer) radius increase factor for accepted very good step (-update_type interpolation)
1297 . -tao_bnk_theta - (developer) trust region interpolation factor (-update_type interpolation)
1298 . -tao_bnk_nu1 - (developer) threshold for small line-search step length (-update_type step)
1299 . -tao_bnk_nu2 - (developer) threshold for reasonable line-search step length (-update_type step)
1300 . -tao_bnk_nu3 - (developer) threshold for large line-search step length (-update_type step)
1301 . -tao_bnk_nu4 - (developer) threshold for very large line-search step length (-update_type step)
1302 . -tao_bnk_omega1 - (developer) radius reduction factor for very small line-search step length (-update_type step)
1303 . -tao_bnk_omega2 - (developer) radius reduction factor for small line-search step length (-update_type step)
1304 . -tao_bnk_omega3 - (developer) radius factor for decent line-search step length (-update_type step)
1305 . -tao_bnk_omega4 - (developer) radius increase factor for large line-search step length (-update_type step)
1306 . -tao_bnk_omega5 - (developer) radius increase factor for very large line-search step length (-update_type step)
1307 . -tao_bnk_mu1_i -  (developer) threshold for accepting very good step (-init_type interpolation)
1308 . -tao_bnk_mu2_i -  (developer) threshold for accepting good step (-init_type interpolation)
1309 . -tao_bnk_gamma1_i - (developer) radius reduction factor for rejected very bad step (-init_type interpolation)
1310 . -tao_bnk_gamma2_i - (developer) radius reduction factor for rejected bad step (-init_type interpolation)
1311 . -tao_bnk_gamma3_i - (developer) radius increase factor for accepted good step (-init_type interpolation)
1312 . -tao_bnk_gamma4_i - (developer) radius increase factor for accepted very good step (-init_type interpolation)
1313 - -tao_bnk_theta_i - (developer) trust region interpolation factor (-init_type interpolation)
1314 
1315   Level: beginner
1316 M*/
1317 
1318 PetscErrorCode TaoCreate_BNK(Tao tao)
1319 {
1320   TAO_BNK        *bnk;
1321   const char     *morethuente_type = TAOLINESEARCHMT;
1322   PetscErrorCode ierr;
1323   PC             pc;
1324 
1325   PetscFunctionBegin;
1326   ierr = PetscNewLog(tao,&bnk);CHKERRQ(ierr);
1327 
1328   tao->ops->setup = TaoSetUp_BNK;
1329   tao->ops->view = TaoView_BNK;
1330   tao->ops->setfromoptions = TaoSetFromOptions_BNK;
1331   tao->ops->destroy = TaoDestroy_BNK;
1332 
1333   /*  Override default settings (unless already changed) */
1334   if (!tao->max_it_changed) tao->max_it = 50;
1335   if (!tao->trust0_changed) tao->trust0 = 100.0;
1336 
1337   tao->data = (void*)bnk;
1338 
1339   /*  Hessian shifting parameters */
1340   bnk->computehessian = TaoBNKComputeHessian;
1341   bnk->computestep = TaoBNKComputeStep;
1342 
1343   bnk->sval   = 0.0;
1344   bnk->imin   = 1.0e-4;
1345   bnk->imax   = 1.0e+2;
1346   bnk->imfac  = 1.0e-1;
1347 
1348   bnk->pmin   = 1.0e-12;
1349   bnk->pmax   = 1.0e+2;
1350   bnk->pgfac  = 1.0e+1;
1351   bnk->psfac  = 4.0e-1;
1352   bnk->pmgfac = 1.0e-1;
1353   bnk->pmsfac = 1.0e-1;
1354 
1355   /*  Default values for trust-region radius update based on steplength */
1356   bnk->nu1 = 0.25;
1357   bnk->nu2 = 0.50;
1358   bnk->nu3 = 1.00;
1359   bnk->nu4 = 1.25;
1360 
1361   bnk->omega1 = 0.25;
1362   bnk->omega2 = 0.50;
1363   bnk->omega3 = 1.00;
1364   bnk->omega4 = 2.00;
1365   bnk->omega5 = 4.00;
1366 
1367   /*  Default values for trust-region radius update based on reduction */
1368   bnk->eta1 = 1.0e-4;
1369   bnk->eta2 = 0.25;
1370   bnk->eta3 = 0.50;
1371   bnk->eta4 = 0.90;
1372 
1373   bnk->alpha1 = 0.25;
1374   bnk->alpha2 = 0.50;
1375   bnk->alpha3 = 1.00;
1376   bnk->alpha4 = 2.00;
1377   bnk->alpha5 = 4.00;
1378 
1379   /*  Default values for trust-region radius update based on interpolation */
1380   bnk->mu1 = 0.10;
1381   bnk->mu2 = 0.50;
1382 
1383   bnk->gamma1 = 0.25;
1384   bnk->gamma2 = 0.50;
1385   bnk->gamma3 = 2.00;
1386   bnk->gamma4 = 4.00;
1387 
1388   bnk->theta = 0.05;
1389 
1390   /*  Default values for trust region initialization based on interpolation */
1391   bnk->mu1_i = 0.35;
1392   bnk->mu2_i = 0.50;
1393 
1394   bnk->gamma1_i = 0.0625;
1395   bnk->gamma2_i = 0.5;
1396   bnk->gamma3_i = 2.0;
1397   bnk->gamma4_i = 5.0;
1398 
1399   bnk->theta_i = 0.25;
1400 
1401   /*  Remaining parameters */
1402   bnk->max_cg_its = 0;
1403   bnk->min_radius = 1.0e-10;
1404   bnk->max_radius = 1.0e10;
1405   bnk->epsilon = PetscPowReal(PETSC_MACHINE_EPSILON, 2.0/3.0);
1406   bnk->as_tol = 1.0e-3;
1407   bnk->as_step = 1.0e-3;
1408   bnk->dmin = 1.0e-6;
1409   bnk->dmax = 1.0e6;
1410 
1411   bnk->M               = NULL;
1412   bnk->bfgs_pre        = NULL;
1413   bnk->init_type       = BNK_INIT_INTERPOLATION;
1414   bnk->update_type     = BNK_UPDATE_REDUCTION;
1415   bnk->as_type         = BNK_AS_BERTSEKAS;
1416 
1417   bnk->is_stcg         = PETSC_FALSE;
1418   bnk->is_gltr         = PETSC_FALSE;
1419   bnk->is_nash         = PETSC_FALSE;
1420 
1421   /* Create the embedded BNCG solver */
1422   ierr = TaoCreate(PetscObjectComm((PetscObject)tao), &bnk->bncg);CHKERRQ(ierr);
1423   ierr = PetscObjectIncrementTabLevel((PetscObject)bnk->bncg, (PetscObject)tao, 1);CHKERRQ(ierr);
1424   ierr = TaoSetOptionsPrefix(bnk->bncg, "tao_bnk_");CHKERRQ(ierr);
1425   ierr = TaoSetType(bnk->bncg, TAOBNCG);CHKERRQ(ierr);
1426 
1427   /* Create the line search */
1428   ierr = TaoLineSearchCreate(((PetscObject)tao)->comm,&tao->linesearch);CHKERRQ(ierr);
1429   ierr = PetscObjectIncrementTabLevel((PetscObject)tao->linesearch, (PetscObject)tao, 1);CHKERRQ(ierr);
1430   ierr = TaoLineSearchSetOptionsPrefix(tao->linesearch,tao->hdr.prefix);CHKERRQ(ierr);
1431   ierr = TaoLineSearchSetType(tao->linesearch,morethuente_type);CHKERRQ(ierr);
1432   ierr = TaoLineSearchUseTaoRoutines(tao->linesearch,tao);CHKERRQ(ierr);
1433 
1434   /*  Set linear solver to default for symmetric matrices */
1435   ierr = KSPCreate(((PetscObject)tao)->comm,&tao->ksp);CHKERRQ(ierr);
1436   ierr = PetscObjectIncrementTabLevel((PetscObject)tao->ksp, (PetscObject)tao, 1);CHKERRQ(ierr);
1437   ierr = KSPSetOptionsPrefix(tao->ksp,"tao_bnk_");CHKERRQ(ierr);
1438   ierr = KSPSetType(tao->ksp,KSPSTCG);CHKERRQ(ierr);
1439   ierr = KSPGetPC(tao->ksp, &pc);CHKERRQ(ierr);
1440   ierr = PCSetType(pc, PCLMVM);CHKERRQ(ierr);
1441   PetscFunctionReturn(0);
1442 }
1443