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