xref: /petsc/src/tao/interface/taosolver.c (revision 19b5c1014729ac30c47582d143b001f1b9cdc336)
1 #define TAO_DLL
2 
3 #include <petsc/private/taoimpl.h> /*I "petsctao.h" I*/
4 
5 PetscBool TaoRegisterAllCalled = PETSC_FALSE;
6 PetscFunctionList TaoList = NULL;
7 
8 PetscClassId TAO_CLASSID;
9 PetscLogEvent Tao_Solve, Tao_ObjectiveEval, Tao_GradientEval, Tao_ObjGradientEval, Tao_HessianEval, Tao_ConstraintsEval, Tao_JacobianEval;
10 
11 const char *TaoSubSetTypes[] = {  "subvec","mask","matrixfree","TaoSubSetType","TAO_SUBSET_",0};
12 
13 struct _n_TaoMonitorDrawCtx {
14   PetscViewer viewer;
15   PetscInt    howoften;  /* when > 0 uses iteration % howoften, when negative only final solution plotted */
16 };
17 
18 /*@
19   TaoCreate - Creates a TAO solver
20 
21   Collective on MPI_Comm
22 
23   Input Parameter:
24 . comm - MPI communicator
25 
26   Output Parameter:
27 . newtao - the new Tao context
28 
29   Available methods include:
30 +    nls - Newton's method with line search for unconstrained minimization
31 .    ntr - Newton's method with trust region for unconstrained minimization
32 .    ntl - Newton's method with trust region, line search for unconstrained minimization
33 .    lmvm - Limited memory variable metric method for unconstrained minimization
34 .    cg - Nonlinear conjugate gradient method for unconstrained minimization
35 .    nm - Nelder-Mead algorithm for derivate-free unconstrained minimization
36 .    tron - Newton Trust Region method for bound constrained minimization
37 .    gpcg - Newton Trust Region method for quadratic bound constrained minimization
38 .    blmvm - Limited memory variable metric method for bound constrained minimization
39 .    lcl - Linearly constrained Lagrangian method for pde-constrained minimization
40 -    pounders - Model-based algorithm for nonlinear least squares
41 
42    Options Database Keys:
43 .   -tao_type - select which method TAO should use
44 
45    Level: beginner
46 
47 .seealso: TaoSolve(), TaoDestroy()
48 @*/
49 PetscErrorCode TaoCreate(MPI_Comm comm, Tao *newtao)
50 {
51   PetscErrorCode ierr;
52   Tao            tao;
53 
54   PetscFunctionBegin;
55   PetscValidPointer(newtao,2);
56   *newtao = NULL;
57 
58   ierr = TaoInitializePackage();CHKERRQ(ierr);
59   ierr = TaoLineSearchInitializePackage();CHKERRQ(ierr);
60 
61   ierr = PetscHeaderCreate(tao,TAO_CLASSID,"Tao","Optimization solver","Tao",comm,TaoDestroy,TaoView);CHKERRQ(ierr);
62   tao->ops->computeobjective=0;
63   tao->ops->computeobjectiveandgradient=0;
64   tao->ops->computegradient=0;
65   tao->ops->computehessian=0;
66   tao->ops->computeseparableobjective=0;
67   tao->ops->computeconstraints=0;
68   tao->ops->computejacobian=0;
69   tao->ops->computejacobianequality=0;
70   tao->ops->computejacobianinequality=0;
71   tao->ops->computeequalityconstraints=0;
72   tao->ops->computeinequalityconstraints=0;
73   tao->ops->convergencetest=TaoDefaultConvergenceTest;
74   tao->ops->convergencedestroy=0;
75   tao->ops->computedual=0;
76   tao->ops->setup=0;
77   tao->ops->solve=0;
78   tao->ops->view=0;
79   tao->ops->setfromoptions=0;
80   tao->ops->destroy=0;
81 
82   tao->solution=NULL;
83   tao->gradient=NULL;
84   tao->sep_objective = NULL;
85   tao->constraints=NULL;
86   tao->constraints_equality=NULL;
87   tao->constraints_inequality=NULL;
88   tao->sep_weights_v=NULL;
89   tao->sep_weights_w=NULL;
90   tao->stepdirection=NULL;
91   tao->niter=0;
92   tao->ntotalits=0;
93   tao->XL = NULL;
94   tao->XU = NULL;
95   tao->IL = NULL;
96   tao->IU = NULL;
97   tao->DI = NULL;
98   tao->DE = NULL;
99   tao->gradient_norm = NULL;
100   tao->gradient_norm_tmp = NULL;
101   tao->hessian = NULL;
102   tao->hessian_pre = NULL;
103   tao->jacobian = NULL;
104   tao->jacobian_pre = NULL;
105   tao->jacobian_state = NULL;
106   tao->jacobian_state_pre = NULL;
107   tao->jacobian_state_inv = NULL;
108   tao->jacobian_design = NULL;
109   tao->jacobian_design_pre = NULL;
110   tao->jacobian_equality = NULL;
111   tao->jacobian_equality_pre = NULL;
112   tao->jacobian_inequality = NULL;
113   tao->jacobian_inequality_pre = NULL;
114   tao->state_is = NULL;
115   tao->design_is = NULL;
116 
117   tao->max_it     = 10000;
118   tao->max_funcs   = 10000;
119 #if defined(PETSC_USE_REAL_SINGLE)
120   tao->gatol       = 1e-5;
121   tao->grtol       = 1e-5;
122 #else
123   tao->gatol       = 1e-8;
124   tao->grtol       = 1e-8;
125 #endif
126   tao->crtol       = 0.0;
127   tao->catol       = 0.0;
128   tao->gttol       = 0.0;
129   tao->steptol     = 0.0;
130   tao->trust0      = PETSC_INFINITY;
131   tao->fmin        = PETSC_NINFINITY;
132   tao->hist_malloc = PETSC_FALSE;
133   tao->hist_reset = PETSC_TRUE;
134   tao->hist_max = 0;
135   tao->hist_len = 0;
136   tao->hist_obj = NULL;
137   tao->hist_resid = NULL;
138   tao->hist_cnorm = NULL;
139   tao->hist_lits = NULL;
140 
141   tao->numbermonitors=0;
142   tao->viewsolution=PETSC_FALSE;
143   tao->viewhessian=PETSC_FALSE;
144   tao->viewgradient=PETSC_FALSE;
145   tao->viewjacobian=PETSC_FALSE;
146   tao->viewconstraints = PETSC_FALSE;
147 
148   /* These flags prevents algorithms from overriding user options */
149   tao->max_it_changed   =PETSC_FALSE;
150   tao->max_funcs_changed=PETSC_FALSE;
151   tao->gatol_changed    =PETSC_FALSE;
152   tao->grtol_changed    =PETSC_FALSE;
153   tao->gttol_changed    =PETSC_FALSE;
154   tao->steptol_changed  =PETSC_FALSE;
155   tao->trust0_changed   =PETSC_FALSE;
156   tao->fmin_changed     =PETSC_FALSE;
157   tao->catol_changed    =PETSC_FALSE;
158   tao->crtol_changed    =PETSC_FALSE;
159   ierr = TaoResetStatistics(tao);CHKERRQ(ierr);
160   *newtao = tao;
161   PetscFunctionReturn(0);
162 }
163 
164 /*@
165   TaoSolve - Solves an optimization problem min F(x) s.t. l <= x <= u
166 
167   Collective on Tao
168 
169   Input Parameters:
170 . tao - the Tao context
171 
172   Notes:
173   The user must set up the Tao with calls to TaoSetInitialVector(),
174   TaoSetObjectiveRoutine(),
175   TaoSetGradientRoutine(), and (if using 2nd order method) TaoSetHessianRoutine().
176 
177   You should call TaoGetConvergedReason() or run with -tao_converged_reason to determine if the optimization algorithm actually succeeded or
178   why it failed.
179 
180   Level: beginner
181 
182 .seealso: TaoCreate(), TaoSetObjectiveRoutine(), TaoSetGradientRoutine(), TaoSetHessianRoutine(), TaoGetConvergedReason()
183  @*/
184 PetscErrorCode TaoSolve(Tao tao)
185 {
186   PetscErrorCode   ierr;
187   static PetscBool set = PETSC_FALSE;
188 
189   PetscFunctionBegin;
190   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
191   ierr = PetscCitationsRegister("@TechReport{tao-user-ref,\n"
192                                 "title   = {Toolkit for Advanced Optimization (TAO) Users Manual},\n"
193                                 "author  = {Todd Munson and Jason Sarich and Stefan Wild and Steve Benson and Lois Curfman McInnes},\n"
194                                 "Institution = {Argonne National Laboratory},\n"
195                                 "Year   = 2014,\n"
196                                 "Number = {ANL/MCS-TM-322 - Revision 3.5},\n"
197                                 "url    = {http://www.mcs.anl.gov/tao}\n}\n",&set);CHKERRQ(ierr);
198 
199   ierr = TaoSetUp(tao);CHKERRQ(ierr);
200   ierr = TaoResetStatistics(tao);CHKERRQ(ierr);
201   if (tao->linesearch) {
202     ierr = TaoLineSearchReset(tao->linesearch);CHKERRQ(ierr);
203   }
204 
205   ierr = PetscLogEventBegin(Tao_Solve,tao,0,0,0);CHKERRQ(ierr);
206   if (tao->ops->solve){ ierr = (*tao->ops->solve)(tao);CHKERRQ(ierr); }
207   ierr = PetscLogEventEnd(Tao_Solve,tao,0,0,0);CHKERRQ(ierr);
208 
209   ierr = VecViewFromOptions(tao->solution,(PetscObject)tao,"-tao_view_solution");CHKERRQ(ierr);
210 
211   tao->ntotalits += tao->niter;
212   ierr = TaoViewFromOptions(tao,NULL,"-tao_view");CHKERRQ(ierr);
213 
214   if (tao->printreason) {
215     if (tao->reason > 0) {
216       ierr = PetscPrintf(((PetscObject)tao)->comm,"TAO solve converged due to %s iterations %D\n",TaoConvergedReasons[tao->reason],tao->niter);CHKERRQ(ierr);
217     } else {
218       ierr = PetscPrintf(((PetscObject)tao)->comm,"TAO solve did not converge due to %s iteration %D\n",TaoConvergedReasons[tao->reason],tao->niter);CHKERRQ(ierr);
219     }
220   }
221   PetscFunctionReturn(0);
222 }
223 
224 /*@
225   TaoSetUp - Sets up the internal data structures for the later use
226   of a Tao solver
227 
228   Collective on tao
229 
230   Input Parameters:
231 . tao - the TAO context
232 
233   Notes:
234   The user will not need to explicitly call TaoSetUp(), as it will
235   automatically be called in TaoSolve().  However, if the user
236   desires to call it explicitly, it should come after TaoCreate()
237   and any TaoSetSomething() routines, but before TaoSolve().
238 
239   Level: advanced
240 
241 .seealso: TaoCreate(), TaoSolve()
242 @*/
243 PetscErrorCode TaoSetUp(Tao tao)
244 {
245   PetscErrorCode ierr;
246 
247   PetscFunctionBegin;
248   PetscValidHeaderSpecific(tao, TAO_CLASSID,1);
249   if (tao->setupcalled) PetscFunctionReturn(0);
250 
251   if (!tao->solution) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TaoSetInitialVector");
252   if (tao->ops->setup) {
253     ierr = (*tao->ops->setup)(tao);CHKERRQ(ierr);
254   }
255   tao->setupcalled = PETSC_TRUE;
256   PetscFunctionReturn(0);
257 }
258 
259 /*@
260   TaoDestroy - Destroys the TAO context that was created with
261   TaoCreate()
262 
263   Collective on Tao
264 
265   Input Parameter:
266 . tao - the Tao context
267 
268   Level: beginner
269 
270 .seealso: TaoCreate(), TaoSolve()
271 @*/
272 PetscErrorCode TaoDestroy(Tao *tao)
273 {
274   PetscErrorCode ierr;
275 
276   PetscFunctionBegin;
277   if (!*tao) PetscFunctionReturn(0);
278   PetscValidHeaderSpecific(*tao,TAO_CLASSID,1);
279   if (--((PetscObject)*tao)->refct > 0) {*tao=0;PetscFunctionReturn(0);}
280 
281   if ((*tao)->ops->destroy) {
282     ierr = (*((*tao))->ops->destroy)(*tao);CHKERRQ(ierr);
283   }
284   ierr = KSPDestroy(&(*tao)->ksp);CHKERRQ(ierr);
285   ierr = TaoLineSearchDestroy(&(*tao)->linesearch);CHKERRQ(ierr);
286 
287   if ((*tao)->ops->convergencedestroy) {
288     ierr = (*(*tao)->ops->convergencedestroy)((*tao)->cnvP);CHKERRQ(ierr);
289     if ((*tao)->jacobian_state_inv) {
290       ierr = MatDestroy(&(*tao)->jacobian_state_inv);CHKERRQ(ierr);
291     }
292   }
293   ierr = VecDestroy(&(*tao)->solution);CHKERRQ(ierr);
294   ierr = VecDestroy(&(*tao)->gradient);CHKERRQ(ierr);
295 
296   if ((*tao)->gradient_norm) {
297     ierr = PetscObjectDereference((PetscObject)(*tao)->gradient_norm);CHKERRQ(ierr);
298     ierr = VecDestroy(&(*tao)->gradient_norm_tmp);CHKERRQ(ierr);
299   }
300 
301   ierr = VecDestroy(&(*tao)->XL);CHKERRQ(ierr);
302   ierr = VecDestroy(&(*tao)->XU);CHKERRQ(ierr);
303   ierr = VecDestroy(&(*tao)->IL);CHKERRQ(ierr);
304   ierr = VecDestroy(&(*tao)->IU);CHKERRQ(ierr);
305   ierr = VecDestroy(&(*tao)->DE);CHKERRQ(ierr);
306   ierr = VecDestroy(&(*tao)->DI);CHKERRQ(ierr);
307   ierr = VecDestroy(&(*tao)->constraints_equality);CHKERRQ(ierr);
308   ierr = VecDestroy(&(*tao)->constraints_inequality);CHKERRQ(ierr);
309   ierr = VecDestroy(&(*tao)->stepdirection);CHKERRQ(ierr);
310   ierr = MatDestroy(&(*tao)->hessian_pre);CHKERRQ(ierr);
311   ierr = MatDestroy(&(*tao)->hessian);CHKERRQ(ierr);
312   ierr = MatDestroy(&(*tao)->jacobian_pre);CHKERRQ(ierr);
313   ierr = MatDestroy(&(*tao)->jacobian);CHKERRQ(ierr);
314   ierr = MatDestroy(&(*tao)->jacobian_state_pre);CHKERRQ(ierr);
315   ierr = MatDestroy(&(*tao)->jacobian_state);CHKERRQ(ierr);
316   ierr = MatDestroy(&(*tao)->jacobian_state_inv);CHKERRQ(ierr);
317   ierr = MatDestroy(&(*tao)->jacobian_design);CHKERRQ(ierr);
318   ierr = MatDestroy(&(*tao)->jacobian_equality);CHKERRQ(ierr);
319   ierr = MatDestroy(&(*tao)->jacobian_equality_pre);CHKERRQ(ierr);
320   ierr = MatDestroy(&(*tao)->jacobian_inequality);CHKERRQ(ierr);
321   ierr = MatDestroy(&(*tao)->jacobian_inequality_pre);CHKERRQ(ierr);
322   ierr = ISDestroy(&(*tao)->state_is);CHKERRQ(ierr);
323   ierr = ISDestroy(&(*tao)->design_is);CHKERRQ(ierr);
324   ierr = VecDestroy(&(*tao)->sep_weights_v);CHKERRQ(ierr);
325   ierr = TaoCancelMonitors(*tao);CHKERRQ(ierr);
326   if ((*tao)->hist_malloc) {
327     ierr = PetscFree((*tao)->hist_obj);CHKERRQ(ierr);
328     ierr = PetscFree((*tao)->hist_resid);CHKERRQ(ierr);
329     ierr = PetscFree((*tao)->hist_cnorm);CHKERRQ(ierr);
330     ierr = PetscFree((*tao)->hist_lits);CHKERRQ(ierr);
331   }
332   if ((*tao)->sep_weights_n) {
333     ierr = PetscFree((*tao)->sep_weights_rows);CHKERRQ(ierr);
334     ierr = PetscFree((*tao)->sep_weights_cols);CHKERRQ(ierr);
335     ierr = PetscFree((*tao)->sep_weights_w);CHKERRQ(ierr);
336   }
337   ierr = PetscHeaderDestroy(tao);CHKERRQ(ierr);
338   PetscFunctionReturn(0);
339 }
340 
341 /*@
342   TaoSetFromOptions - Sets various Tao parameters from user
343   options.
344 
345   Collective on Tao
346 
347   Input Paremeter:
348 . tao - the Tao solver context
349 
350   options Database Keys:
351 + -tao_type <type> - The algorithm that TAO uses (lmvm, nls, etc.)
352 . -tao_gatol <gatol> - absolute error tolerance for ||gradient||
353 . -tao_grtol <grtol> - relative error tolerance for ||gradient||
354 . -tao_gttol <gttol> - reduction of ||gradient|| relative to initial gradient
355 . -tao_max_it <max> - sets maximum number of iterations
356 . -tao_max_funcs <max> - sets maximum number of function evaluations
357 . -tao_fmin <fmin> - stop if function value reaches fmin
358 . -tao_steptol <tol> - stop if trust region radius less than <tol>
359 . -tao_trust0 <t> - initial trust region radius
360 . -tao_monitor - prints function value and residual at each iteration
361 . -tao_smonitor - same as tao_monitor, but truncates very small values
362 . -tao_cmonitor - prints function value, residual, and constraint norm at each iteration
363 . -tao_view_solution - prints solution vector at each iteration
364 . -tao_view_separableobjective - prints separable objective vector at each iteration
365 . -tao_view_step - prints step direction vector at each iteration
366 . -tao_view_gradient - prints gradient vector at each iteration
367 . -tao_draw_solution - graphically view solution vector at each iteration
368 . -tao_draw_step - graphically view step vector at each iteration
369 . -tao_draw_gradient - graphically view gradient at each iteration
370 . -tao_fd_gradient - use gradient computed with finite differences
371 . -tao_fd_hessian - use hessian computed with finite differences
372 . -tao_mf_hessian - use matrix-free hessian computed with finite differences
373 . -tao_cancelmonitors - cancels all monitors (except those set with command line)
374 . -tao_view - prints information about the Tao after solving
375 - -tao_converged_reason - prints the reason TAO stopped iterating
376 
377   Notes:
378   To see all options, run your program with the -help option or consult the
379   user's manual. Should be called after TaoCreate() but before TaoSolve()
380 
381   Level: beginner
382 @*/
383 PetscErrorCode TaoSetFromOptions(Tao tao)
384 {
385   PetscErrorCode ierr;
386   const TaoType  default_type = TAOLMVM;
387   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
388   PetscViewer    monviewer;
389   PetscBool      flg;
390   MPI_Comm       comm;
391 
392   PetscFunctionBegin;
393   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
394   ierr = PetscObjectGetComm((PetscObject)tao,&comm);CHKERRQ(ierr);
395 
396   /* So no warnings are given about unused options */
397   ierr = PetscOptionsHasName(((PetscObject)tao)->options,((PetscObject)tao)->prefix,"-tao_ls_type",&flg);CHKERRQ(ierr);
398 
399   ierr = PetscObjectOptionsBegin((PetscObject)tao);CHKERRQ(ierr);
400   {
401     ierr = TaoRegisterAll();CHKERRQ(ierr);
402     if (((PetscObject)tao)->type_name) {
403       default_type = ((PetscObject)tao)->type_name;
404     }
405     /* Check for type from options */
406     ierr = PetscOptionsFList("-tao_type","Tao Solver type","TaoSetType",TaoList,default_type,type,256,&flg);CHKERRQ(ierr);
407     if (flg) {
408       ierr = TaoSetType(tao,type);CHKERRQ(ierr);
409     } else if (!((PetscObject)tao)->type_name) {
410       ierr = TaoSetType(tao,default_type);CHKERRQ(ierr);
411     }
412 
413     ierr = PetscOptionsReal("-tao_catol","Stop if constraints violations within","TaoSetConstraintTolerances",tao->catol,&tao->catol,&flg);CHKERRQ(ierr);
414     if (flg) tao->catol_changed=PETSC_TRUE;
415     ierr = PetscOptionsReal("-tao_crtol","Stop if relative contraint violations within","TaoSetConstraintTolerances",tao->crtol,&tao->crtol,&flg);CHKERRQ(ierr);
416     if (flg) tao->crtol_changed=PETSC_TRUE;
417     ierr = PetscOptionsReal("-tao_gatol","Stop if norm of gradient less than","TaoSetTolerances",tao->gatol,&tao->gatol,&flg);CHKERRQ(ierr);
418     if (flg) tao->gatol_changed=PETSC_TRUE;
419     ierr = PetscOptionsReal("-tao_grtol","Stop if norm of gradient divided by the function value is less than","TaoSetTolerances",tao->grtol,&tao->grtol,&flg);CHKERRQ(ierr);
420     if (flg) tao->grtol_changed=PETSC_TRUE;
421     ierr = PetscOptionsReal("-tao_gttol","Stop if the norm of the gradient is less than the norm of the initial gradient times tol","TaoSetTolerances",tao->gttol,&tao->gttol,&flg);CHKERRQ(ierr);
422     if (flg) tao->gttol_changed=PETSC_TRUE;
423     ierr = PetscOptionsInt("-tao_max_it","Stop if iteration number exceeds","TaoSetMaximumIterations",tao->max_it,&tao->max_it,&flg);CHKERRQ(ierr);
424     if (flg) tao->max_it_changed=PETSC_TRUE;
425     ierr = PetscOptionsInt("-tao_max_funcs","Stop if number of function evaluations exceeds","TaoSetMaximumFunctionEvaluations",tao->max_funcs,&tao->max_funcs,&flg);CHKERRQ(ierr);
426     if (flg) tao->max_funcs_changed=PETSC_TRUE;
427     ierr = PetscOptionsReal("-tao_fmin","Stop if function less than","TaoSetFunctionLowerBound",tao->fmin,&tao->fmin,&flg);CHKERRQ(ierr);
428     if (flg) tao->fmin_changed=PETSC_TRUE;
429     ierr = PetscOptionsReal("-tao_steptol","Stop if step size or trust region radius less than","",tao->steptol,&tao->steptol,&flg);CHKERRQ(ierr);
430     if (flg) tao->steptol_changed=PETSC_TRUE;
431     ierr = PetscOptionsReal("-tao_trust0","Initial trust region radius","TaoSetTrustRegionRadius",tao->trust0,&tao->trust0,&flg);CHKERRQ(ierr);
432     if (flg) tao->trust0_changed=PETSC_TRUE;
433     ierr = PetscOptionsString("-tao_view_solution","view solution vector after each evaluation","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
434     if (flg) {
435       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
436       ierr = TaoSetMonitor(tao,TaoSolutionMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
437     }
438 
439     ierr = PetscOptionsBool("-tao_converged_reason","Print reason for TAO converged","TaoSolve",tao->printreason,&tao->printreason,NULL);CHKERRQ(ierr);
440     ierr = PetscOptionsString("-tao_view_gradient","view gradient vector after each evaluation","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
441     if (flg) {
442       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
443       ierr = TaoSetMonitor(tao,TaoGradientMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
444     }
445 
446     ierr = PetscOptionsString("-tao_view_stepdirection","view step direction vector after each iteration","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
447     if (flg) {
448       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
449       ierr = TaoSetMonitor(tao,TaoStepDirectionMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
450     }
451 
452     ierr = PetscOptionsString("-tao_view_separableobjective","view separable objective vector after each evaluation","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
453     if (flg) {
454       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
455       ierr = TaoSetMonitor(tao,TaoSeparableObjectiveMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
456     }
457 
458     ierr = PetscOptionsString("-tao_monitor","Use the default convergence monitor","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
459     if (flg) {
460       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
461       ierr = TaoSetMonitor(tao,TaoMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
462     }
463 
464     ierr = PetscOptionsString("-tao_smonitor","Use the short convergence monitor","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
465     if (flg) {
466       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
467       ierr = TaoSetMonitor(tao,TaoDefaultSMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
468     }
469 
470     ierr = PetscOptionsString("-tao_cmonitor","Use the default convergence monitor with constraint norm","TaoSetMonitor","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
471     if (flg) {
472       ierr = PetscViewerASCIIOpen(comm,monfilename,&monviewer);CHKERRQ(ierr);
473       ierr = TaoSetMonitor(tao,TaoDefaultCMonitor,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
474     }
475 
476 
477     flg = PETSC_FALSE;
478     ierr = PetscOptionsBool("-tao_cancelmonitors","cancel all monitors and call any registered destroy routines","TaoCancelMonitors",flg,&flg,NULL);CHKERRQ(ierr);
479     if (flg) {ierr = TaoCancelMonitors(tao);CHKERRQ(ierr);}
480 
481     flg = PETSC_FALSE;
482     ierr = PetscOptionsBool("-tao_draw_solution","Plot solution vector at each iteration","TaoSetMonitor",flg,&flg,NULL);CHKERRQ(ierr);
483     if (flg) {
484       TaoMonitorDrawCtx drawctx;
485       PetscInt          howoften = 1;
486       ierr = TaoMonitorDrawCtxCreate(PetscObjectComm((PetscObject)tao),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&drawctx);CHKERRQ(ierr);
487       ierr = TaoSetMonitor(tao,TaoDrawSolutionMonitor,drawctx,(PetscErrorCode (*)(void**))TaoMonitorDrawCtxDestroy);CHKERRQ(ierr);
488     }
489 
490     flg = PETSC_FALSE;
491     ierr = PetscOptionsBool("-tao_draw_step","plots step direction at each iteration","TaoSetMonitor",flg,&flg,NULL);CHKERRQ(ierr);
492     if (flg) {
493       ierr = TaoSetMonitor(tao,TaoDrawStepMonitor,NULL,NULL);CHKERRQ(ierr);
494     }
495 
496     flg = PETSC_FALSE;
497     ierr = PetscOptionsBool("-tao_draw_gradient","plots gradient at each iteration","TaoSetMonitor",flg,&flg,NULL);CHKERRQ(ierr);
498     if (flg) {
499       TaoMonitorDrawCtx drawctx;
500       PetscInt          howoften = 1;
501       ierr = TaoMonitorDrawCtxCreate(PetscObjectComm((PetscObject)tao),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&drawctx);CHKERRQ(ierr);
502       ierr = TaoSetMonitor(tao,TaoDrawGradientMonitor,drawctx,(PetscErrorCode (*)(void**))TaoMonitorDrawCtxDestroy);CHKERRQ(ierr);
503     }
504     flg = PETSC_FALSE;
505     ierr = PetscOptionsBool("-tao_fd_gradient","compute gradient using finite differences","TaoDefaultComputeGradient",flg,&flg,NULL);CHKERRQ(ierr);
506     if (flg) {
507       ierr = TaoSetGradientRoutine(tao,TaoDefaultComputeGradient,NULL);CHKERRQ(ierr);
508     }
509     flg = PETSC_FALSE;
510     ierr = PetscOptionsBool("-tao_fd_hessian","compute hessian using finite differences","TaoDefaultComputeHessian",flg,&flg,NULL);CHKERRQ(ierr);
511     if (flg) {
512       Mat H;
513 
514       ierr = MatCreate(PetscObjectComm((PetscObject)tao),&H);CHKERRQ(ierr);
515       ierr = MatSetType(H,MATAIJ);CHKERRQ(ierr);
516       ierr = TaoSetHessianRoutine(tao,H,H,TaoDefaultComputeHessian,NULL);CHKERRQ(ierr);
517       ierr = MatDestroy(&H);CHKERRQ(ierr);
518     }
519     flg = PETSC_FALSE;
520     ierr = PetscOptionsBool("-tao_mf_hessian","compute matrix-free hessian using finite differences","TaoDefaultComputeHessianMFFD",flg,&flg,NULL);CHKERRQ(ierr);
521     if (flg) {
522       Mat H;
523 
524       ierr = MatCreate(PetscObjectComm((PetscObject)tao),&H);CHKERRQ(ierr);
525       ierr = TaoSetHessianRoutine(tao,H,H,TaoDefaultComputeHessianMFFD,NULL);CHKERRQ(ierr);
526       ierr = MatDestroy(&H);CHKERRQ(ierr);
527     }
528     ierr = PetscOptionsEnum("-tao_subset_type","subset type","",TaoSubSetTypes,(PetscEnum)tao->subset_type,(PetscEnum*)&tao->subset_type,NULL);CHKERRQ(ierr);
529 
530     if (tao->ops->setfromoptions) {
531       ierr = (*tao->ops->setfromoptions)(PetscOptionsObject,tao);CHKERRQ(ierr);
532     }
533   }
534   ierr = PetscOptionsEnd();CHKERRQ(ierr);
535   PetscFunctionReturn(0);
536 }
537 
538 /*@C
539   TaoView - Prints information about the Tao
540 
541   Collective on Tao
542 
543   InputParameters:
544 + tao - the Tao context
545 - viewer - visualization context
546 
547   Options Database Key:
548 . -tao_view - Calls TaoView() at the end of TaoSolve()
549 
550   Notes:
551   The available visualization contexts include
552 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
553 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
554          output where only the first processor opens
555          the file.  All other processors send their
556          data to the first processor to print.
557 
558   Level: beginner
559 
560 .seealso: PetscViewerASCIIOpen()
561 @*/
562 PetscErrorCode TaoView(Tao tao, PetscViewer viewer)
563 {
564   PetscErrorCode      ierr;
565   PetscBool           isascii,isstring;
566   const TaoType type;
567 
568   PetscFunctionBegin;
569   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
570   if (!viewer) {
571     ierr = PetscViewerASCIIGetStdout(((PetscObject)tao)->comm,&viewer);CHKERRQ(ierr);
572   }
573   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
574   PetscCheckSameComm(tao,1,viewer,2);
575 
576   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr);
577   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
578   if (isascii) {
579     ierr = PetscViewerASCIIAddTab(viewer, ((PetscObject)tao)->tablevel);CHKERRQ(ierr);
580     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)tao,viewer);CHKERRQ(ierr);
581 
582     if (tao->ops->view) {
583       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
584       ierr = (*tao->ops->view)(tao,viewer);CHKERRQ(ierr);
585       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
586     }
587     if (tao->linesearch) {
588       ierr = TaoLineSearchView(tao->linesearch,viewer);CHKERRQ(ierr);
589     }
590     if (tao->ksp) {
591       ierr = KSPView(tao->ksp,viewer);CHKERRQ(ierr);
592       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
593       ierr = PetscViewerASCIIPrintf(viewer,"total KSP iterations: %D\n",tao->ksp_tot_its);CHKERRQ(ierr);
594       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
595     }
596 
597     ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
598 
599     if (tao->XL || tao->XU) {
600       ierr = PetscViewerASCIIPrintf(viewer,"Active Set subset type: %s\n",TaoSubSetTypes[tao->subset_type]);CHKERRQ(ierr);
601     }
602 
603     ierr = PetscViewerASCIIPrintf(viewer,"convergence tolerances: gatol=%g,",(double)tao->gatol);CHKERRQ(ierr);
604     ierr = PetscViewerASCIIPrintf(viewer," steptol=%g,",(double)tao->steptol);CHKERRQ(ierr);
605     ierr = PetscViewerASCIIPrintf(viewer," gttol=%g\n",(double)tao->gttol);CHKERRQ(ierr);
606     ierr = PetscViewerASCIIPrintf(viewer,"Residual in Function/Gradient:=%g\n",(double)tao->residual);CHKERRQ(ierr);
607 
608     if (tao->cnorm>0 || tao->catol>0 || tao->crtol>0){
609       ierr=PetscViewerASCIIPrintf(viewer,"convergence tolerances:");CHKERRQ(ierr);
610       ierr=PetscViewerASCIIPrintf(viewer," catol=%g,",(double)tao->catol);CHKERRQ(ierr);
611       ierr=PetscViewerASCIIPrintf(viewer," crtol=%g\n",(double)tao->crtol);CHKERRQ(ierr);
612       ierr = PetscViewerASCIIPrintf(viewer,"Residual in Constraints:=%g\n",(double)tao->cnorm);CHKERRQ(ierr);
613     }
614 
615     if (tao->trust < tao->steptol){
616       ierr=PetscViewerASCIIPrintf(viewer,"convergence tolerances: steptol=%g\n",(double)tao->steptol);CHKERRQ(ierr);
617       ierr=PetscViewerASCIIPrintf(viewer,"Final trust region radius:=%g\n",(double)tao->trust);CHKERRQ(ierr);
618     }
619 
620     if (tao->fmin>-1.e25){
621       ierr=PetscViewerASCIIPrintf(viewer,"convergence tolerances: function minimum=%g\n",(double)tao->fmin);CHKERRQ(ierr);
622     }
623     ierr = PetscViewerASCIIPrintf(viewer,"Objective value=%g\n",(double)tao->fc);CHKERRQ(ierr);
624 
625     ierr = PetscViewerASCIIPrintf(viewer,"total number of iterations=%D,          ",tao->niter);CHKERRQ(ierr);
626     ierr = PetscViewerASCIIPrintf(viewer,"              (max: %D)\n",tao->max_it);CHKERRQ(ierr);
627 
628     if (tao->nfuncs>0){
629       ierr = PetscViewerASCIIPrintf(viewer,"total number of function evaluations=%D,",tao->nfuncs);CHKERRQ(ierr);
630       ierr = PetscViewerASCIIPrintf(viewer,"                max: %D\n",tao->max_funcs);CHKERRQ(ierr);
631     }
632     if (tao->ngrads>0){
633       ierr = PetscViewerASCIIPrintf(viewer,"total number of gradient evaluations=%D,",tao->ngrads);CHKERRQ(ierr);
634       ierr = PetscViewerASCIIPrintf(viewer,"                max: %D\n",tao->max_funcs);CHKERRQ(ierr);
635     }
636     if (tao->nfuncgrads>0){
637       ierr = PetscViewerASCIIPrintf(viewer,"total number of function/gradient evaluations=%D,",tao->nfuncgrads);CHKERRQ(ierr);
638       ierr = PetscViewerASCIIPrintf(viewer,"    (max: %D)\n",tao->max_funcs);CHKERRQ(ierr);
639     }
640     if (tao->nhess>0){
641       ierr = PetscViewerASCIIPrintf(viewer,"total number of Hessian evaluations=%D\n",tao->nhess);CHKERRQ(ierr);
642     }
643     /*  if (tao->linear_its>0){
644      ierr = PetscViewerASCIIPrintf(viewer,"  total Krylov method iterations=%D\n",tao->linear_its);CHKERRQ(ierr);
645      }*/
646     if (tao->nconstraints>0){
647       ierr = PetscViewerASCIIPrintf(viewer,"total number of constraint function evaluations=%D\n",tao->nconstraints);CHKERRQ(ierr);
648     }
649     if (tao->njac>0){
650       ierr = PetscViewerASCIIPrintf(viewer,"total number of Jacobian evaluations=%D\n",tao->njac);CHKERRQ(ierr);
651     }
652 
653     if (tao->reason>0){
654       ierr = PetscViewerASCIIPrintf(viewer,    "Solution converged: ");CHKERRQ(ierr);
655       switch (tao->reason) {
656       case TAO_CONVERGED_GATOL:
657         ierr = PetscViewerASCIIPrintf(viewer," ||g(X)|| <= gatol\n");CHKERRQ(ierr);
658         break;
659       case TAO_CONVERGED_GRTOL:
660         ierr = PetscViewerASCIIPrintf(viewer," ||g(X)||/|f(X)| <= grtol\n");CHKERRQ(ierr);
661         break;
662       case TAO_CONVERGED_GTTOL:
663         ierr = PetscViewerASCIIPrintf(viewer," ||g(X)||/||g(X0)|| <= gttol\n");CHKERRQ(ierr);
664         break;
665       case TAO_CONVERGED_STEPTOL:
666         ierr = PetscViewerASCIIPrintf(viewer," Steptol -- step size small\n");CHKERRQ(ierr);
667         break;
668       case TAO_CONVERGED_MINF:
669         ierr = PetscViewerASCIIPrintf(viewer," Minf --  f < fmin\n");CHKERRQ(ierr);
670         break;
671       case TAO_CONVERGED_USER:
672         ierr = PetscViewerASCIIPrintf(viewer," User Terminated\n");CHKERRQ(ierr);
673         break;
674       default:
675         ierr = PetscViewerASCIIPrintf(viewer,"\n");CHKERRQ(ierr);
676         break;
677       }
678 
679     } else {
680       ierr = PetscViewerASCIIPrintf(viewer,"Solver terminated: %d",tao->reason);CHKERRQ(ierr);
681       switch (tao->reason) {
682       case TAO_DIVERGED_MAXITS:
683         ierr = PetscViewerASCIIPrintf(viewer," Maximum Iterations\n");CHKERRQ(ierr);
684         break;
685       case TAO_DIVERGED_NAN:
686         ierr = PetscViewerASCIIPrintf(viewer," NAN or Inf encountered\n");CHKERRQ(ierr);
687         break;
688       case TAO_DIVERGED_MAXFCN:
689         ierr = PetscViewerASCIIPrintf(viewer," Maximum Function Evaluations\n");CHKERRQ(ierr);
690         break;
691       case TAO_DIVERGED_LS_FAILURE:
692         ierr = PetscViewerASCIIPrintf(viewer," Line Search Failure\n");CHKERRQ(ierr);
693         break;
694       case TAO_DIVERGED_TR_REDUCTION:
695         ierr = PetscViewerASCIIPrintf(viewer," Trust Region too small\n");CHKERRQ(ierr);
696         break;
697       case TAO_DIVERGED_USER:
698         ierr = PetscViewerASCIIPrintf(viewer," User Terminated\n");CHKERRQ(ierr);
699         break;
700       default:
701         ierr = PetscViewerASCIIPrintf(viewer,"\n");CHKERRQ(ierr);
702         break;
703       }
704     }
705     ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
706     ierr = PetscViewerASCIISubtractTab(viewer, ((PetscObject)tao)->tablevel);CHKERRQ(ierr);
707   } else if (isstring) {
708     ierr = TaoGetType(tao,&type);CHKERRQ(ierr);
709     ierr = PetscViewerStringSPrintf(viewer," %-3.3s",type);CHKERRQ(ierr);
710   }
711   PetscFunctionReturn(0);
712 }
713 
714 /*@
715   TaoSetTolerances - Sets parameters used in TAO convergence tests
716 
717   Logically collective on Tao
718 
719   Input Parameters:
720 + tao - the Tao context
721 . gatol - stop if norm of gradient is less than this
722 . grtol - stop if relative norm of gradient is less than this
723 - gttol - stop if norm of gradient is reduced by this factor
724 
725   Options Database Keys:
726 + -tao_gatol <gatol> - Sets gatol
727 . -tao_grtol <grtol> - Sets grtol
728 - -tao_gttol <gttol> - Sets gttol
729 
730   Stopping Criteria:
731 $ ||g(X)||                            <= gatol
732 $ ||g(X)|| / |f(X)|                   <= grtol
733 $ ||g(X)|| / ||g(X0)||                <= gttol
734 
735   Notes:
736   Use PETSC_DEFAULT to leave one or more tolerances unchanged.
737 
738   Level: beginner
739 
740 .seealso: TaoGetTolerances()
741 
742 @*/
743 PetscErrorCode TaoSetTolerances(Tao tao, PetscReal gatol, PetscReal grtol, PetscReal gttol)
744 {
745   PetscErrorCode ierr;
746 
747   PetscFunctionBegin;
748   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
749 
750   if (gatol != PETSC_DEFAULT) {
751     if (gatol<0) {
752       ierr = PetscInfo(tao,"Tried to set negative gatol -- ignored.\n");CHKERRQ(ierr);
753     } else {
754       tao->gatol = PetscMax(0,gatol);
755       tao->gatol_changed=PETSC_TRUE;
756     }
757   }
758 
759   if (grtol != PETSC_DEFAULT) {
760     if (grtol<0) {
761       ierr = PetscInfo(tao,"Tried to set negative grtol -- ignored.\n");CHKERRQ(ierr);
762     } else {
763       tao->grtol = PetscMax(0,grtol);
764       tao->grtol_changed=PETSC_TRUE;
765     }
766   }
767 
768   if (gttol != PETSC_DEFAULT) {
769     if (gttol<0) {
770       ierr = PetscInfo(tao,"Tried to set negative gttol -- ignored.\n");CHKERRQ(ierr);
771     } else {
772       tao->gttol = PetscMax(0,gttol);
773       tao->gttol_changed=PETSC_TRUE;
774     }
775   }
776   PetscFunctionReturn(0);
777 }
778 
779 /*@
780   TaoSetConstraintTolerances - Sets constraint tolerance parameters used in TAO  convergence tests
781 
782   Logically collective on Tao
783 
784   Input Parameters:
785 + tao - the Tao context
786 . catol - absolute constraint tolerance, constraint norm must be less than catol for used for gatol convergence criteria
787 - crtol - relative contraint tolerance, constraint norm must be less than crtol for used for gatol, gttol convergence criteria
788 
789   Options Database Keys:
790 + -tao_catol <catol> - Sets catol
791 - -tao_crtol <crtol> - Sets crtol
792 
793   Notes:
794   Use PETSC_DEFAULT to leave any tolerance unchanged.
795 
796   Level: intermediate
797 
798 .seealso: TaoGetTolerances(), TaoGetConstraintTolerances(), TaoSetTolerances()
799 
800 @*/
801 PetscErrorCode TaoSetConstraintTolerances(Tao tao, PetscReal catol, PetscReal crtol)
802 {
803   PetscErrorCode ierr;
804 
805   PetscFunctionBegin;
806   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
807 
808   if (catol != PETSC_DEFAULT) {
809     if (catol<0) {
810       ierr = PetscInfo(tao,"Tried to set negative catol -- ignored.\n");CHKERRQ(ierr);
811     } else {
812       tao->catol = PetscMax(0,catol);
813       tao->catol_changed=PETSC_TRUE;
814     }
815   }
816 
817   if (crtol != PETSC_DEFAULT) {
818     if (crtol<0) {
819       ierr = PetscInfo(tao,"Tried to set negative crtol -- ignored.\n");CHKERRQ(ierr);
820     } else {
821       tao->crtol = PetscMax(0,crtol);
822       tao->crtol_changed=PETSC_TRUE;
823     }
824   }
825   PetscFunctionReturn(0);
826 }
827 
828 /*@
829   TaoGetConstraintTolerances - Gets constraint tolerance parameters used in TAO  convergence tests
830 
831   Not ollective
832 
833   Input Parameter:
834 . tao - the Tao context
835 
836   Output Parameter:
837 + catol - absolute constraint tolerance, constraint norm must be less than catol for used for gatol convergence criteria
838 - crtol - relative contraint tolerance, constraint norm must be less than crtol for used for gatol, gttol convergence criteria
839 
840   Level: intermediate
841 
842 .seealso: TaoGetTolerances(), TaoSetTolerances(), TaoSetConstraintTolerances()
843 
844 @*/
845 PetscErrorCode TaoGetConstraintTolerances(Tao tao, PetscReal *catol, PetscReal *crtol)
846 {
847   PetscFunctionBegin;
848   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
849   if (catol) *catol = tao->catol;
850   if (crtol) *crtol = tao->crtol;
851   PetscFunctionReturn(0);
852 }
853 
854 /*@
855    TaoSetFunctionLowerBound - Sets a bound on the solution objective value.
856    When an approximate solution with an objective value below this number
857    has been found, the solver will terminate.
858 
859    Logically Collective on Tao
860 
861    Input Parameters:
862 +  tao - the Tao solver context
863 -  fmin - the tolerance
864 
865    Options Database Keys:
866 .    -tao_fmin <fmin> - sets the minimum function value
867 
868    Level: intermediate
869 
870 .seealso: TaoSetTolerances()
871 @*/
872 PetscErrorCode TaoSetFunctionLowerBound(Tao tao,PetscReal fmin)
873 {
874   PetscFunctionBegin;
875   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
876   tao->fmin = fmin;
877   tao->fmin_changed=PETSC_TRUE;
878   PetscFunctionReturn(0);
879 }
880 
881 /*@
882    TaoGetFunctionLowerBound - Gets the bound on the solution objective value.
883    When an approximate solution with an objective value below this number
884    has been found, the solver will terminate.
885 
886    Not collective on Tao
887 
888    Input Parameters:
889 .  tao - the Tao solver context
890 
891    OutputParameters:
892 .  fmin - the minimum function value
893 
894    Level: intermediate
895 
896 .seealso: TaoSetFunctionLowerBound()
897 @*/
898 PetscErrorCode TaoGetFunctionLowerBound(Tao tao,PetscReal *fmin)
899 {
900   PetscFunctionBegin;
901   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
902   *fmin = tao->fmin;
903   PetscFunctionReturn(0);
904 }
905 
906 /*@
907    TaoSetMaximumFunctionEvaluations - Sets a maximum number of
908    function evaluations.
909 
910    Logically Collective on Tao
911 
912    Input Parameters:
913 +  tao - the Tao solver context
914 -  nfcn - the maximum number of function evaluations (>=0)
915 
916    Options Database Keys:
917 .    -tao_max_funcs <nfcn> - sets the maximum number of function evaluations
918 
919    Level: intermediate
920 
921 .seealso: TaoSetTolerances(), TaoSetMaximumIterations()
922 @*/
923 
924 PetscErrorCode TaoSetMaximumFunctionEvaluations(Tao tao,PetscInt nfcn)
925 {
926   PetscFunctionBegin;
927   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
928   tao->max_funcs = PetscMax(0,nfcn);
929   tao->max_funcs_changed=PETSC_TRUE;
930   PetscFunctionReturn(0);
931 }
932 
933 /*@
934    TaoGetMaximumFunctionEvaluations - Sets a maximum number of
935    function evaluations.
936 
937    Not Collective
938 
939    Input Parameters:
940 .  tao - the Tao solver context
941 
942    Output Parameters:
943 .  nfcn - the maximum number of function evaluations
944 
945    Level: intermediate
946 
947 .seealso: TaoSetMaximumFunctionEvaluations(), TaoGetMaximumIterations()
948 @*/
949 
950 PetscErrorCode TaoGetMaximumFunctionEvaluations(Tao tao,PetscInt *nfcn)
951 {
952   PetscFunctionBegin;
953   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
954   *nfcn = tao->max_funcs;
955   PetscFunctionReturn(0);
956 }
957 
958 /*@
959    TaoGetCurrentFunctionEvaluations - Get current number of
960    function evaluations.
961 
962    Not Collective
963 
964    Input Parameters:
965 .  tao - the Tao solver context
966 
967    Output Parameters:
968 .  nfuncs - the current number of function evaluations
969 
970    Level: intermediate
971 
972 .seealso: TaoSetMaximumFunctionEvaluations(), TaoGetMaximumFunctionEvaluations(), TaoGetMaximumIterations()
973 @*/
974 
975 PetscErrorCode TaoGetCurrentFunctionEvaluations(Tao tao,PetscInt *nfuncs)
976 {
977   PetscFunctionBegin;
978   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
979   *nfuncs=PetscMax(tao->nfuncs,tao->nfuncgrads);
980   PetscFunctionReturn(0);
981 }
982 
983 /*@
984    TaoSetMaximumIterations - Sets a maximum number of iterates.
985 
986    Logically Collective on Tao
987 
988    Input Parameters:
989 +  tao - the Tao solver context
990 -  maxits - the maximum number of iterates (>=0)
991 
992    Options Database Keys:
993 .    -tao_max_it <its> - sets the maximum number of iterations
994 
995    Level: intermediate
996 
997 .seealso: TaoSetTolerances(), TaoSetMaximumFunctionEvaluations()
998 @*/
999 PetscErrorCode TaoSetMaximumIterations(Tao tao,PetscInt maxits)
1000 {
1001   PetscFunctionBegin;
1002   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1003   tao->max_it = PetscMax(0,maxits);
1004   tao->max_it_changed=PETSC_TRUE;
1005   PetscFunctionReturn(0);
1006 }
1007 
1008 /*@
1009    TaoGetMaximumIterations - Sets a maximum number of iterates.
1010 
1011    Not Collective
1012 
1013    Input Parameters:
1014 .  tao - the Tao solver context
1015 
1016    Output Parameters:
1017 .  maxits - the maximum number of iterates
1018 
1019    Level: intermediate
1020 
1021 .seealso: TaoSetMaximumIterations(), TaoGetMaximumFunctionEvaluations()
1022 @*/
1023 PetscErrorCode TaoGetMaximumIterations(Tao tao,PetscInt *maxits)
1024 {
1025   PetscFunctionBegin;
1026   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1027   *maxits = tao->max_it;
1028   PetscFunctionReturn(0);
1029 }
1030 
1031 /*@
1032    TaoSetInitialTrustRegionRadius - Sets the initial trust region radius.
1033 
1034    Logically collective on Tao
1035 
1036    Input Parameter:
1037 +  tao - a TAO optimization solver
1038 -  radius - the trust region radius
1039 
1040    Level: intermediate
1041 
1042    Options Database Key:
1043 .  -tao_trust0 <t0> - sets initial trust region radius
1044 
1045 .seealso: TaoGetTrustRegionRadius(), TaoSetTrustRegionTolerance()
1046 @*/
1047 PetscErrorCode TaoSetInitialTrustRegionRadius(Tao tao, PetscReal radius)
1048 {
1049   PetscFunctionBegin;
1050   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1051   tao->trust0 = PetscMax(0.0,radius);
1052   tao->trust0_changed=PETSC_TRUE;
1053   PetscFunctionReturn(0);
1054 }
1055 
1056 /*@
1057    TaoGetInitialTrustRegionRadius - Sets the initial trust region radius.
1058 
1059    Not Collective
1060 
1061    Input Parameter:
1062 .  tao - a TAO optimization solver
1063 
1064    Output Parameter:
1065 .  radius - the trust region radius
1066 
1067    Level: intermediate
1068 
1069 .seealso: TaoSetInitialTrustRegionRadius(), TaoGetCurrentTrustRegionRadius()
1070 @*/
1071 PetscErrorCode TaoGetInitialTrustRegionRadius(Tao tao, PetscReal *radius)
1072 {
1073   PetscFunctionBegin;
1074   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1075   *radius = tao->trust0;
1076   PetscFunctionReturn(0);
1077 }
1078 
1079 /*@
1080    TaoGetCurrentTrustRegionRadius - Gets the current trust region radius.
1081 
1082    Not Collective
1083 
1084    Input Parameter:
1085 .  tao - a TAO optimization solver
1086 
1087    Output Parameter:
1088 .  radius - the trust region radius
1089 
1090    Level: intermediate
1091 
1092 .seealso: TaoSetInitialTrustRegionRadius(), TaoGetInitialTrustRegionRadius()
1093 @*/
1094 PetscErrorCode TaoGetCurrentTrustRegionRadius(Tao tao, PetscReal *radius)
1095 {
1096   PetscFunctionBegin;
1097   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1098   *radius = tao->trust;
1099   PetscFunctionReturn(0);
1100 }
1101 
1102 /*@
1103   TaoGetTolerances - gets the current values of tolerances
1104 
1105   Not Collective
1106 
1107   Input Parameters:
1108 . tao - the Tao context
1109 
1110   Output Parameters:
1111 + gatol - stop if norm of gradient is less than this
1112 . grtol - stop if relative norm of gradient is less than this
1113 - gttol - stop if norm of gradient is reduced by a this factor
1114 
1115   Note: NULL can be used as an argument if not all tolerances values are needed
1116 
1117 .seealso TaoSetTolerances()
1118 
1119   Level: intermediate
1120 @*/
1121 PetscErrorCode TaoGetTolerances(Tao tao, PetscReal *gatol, PetscReal *grtol, PetscReal *gttol)
1122 {
1123   PetscFunctionBegin;
1124   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1125   if (gatol) *gatol=tao->gatol;
1126   if (grtol) *grtol=tao->grtol;
1127   if (gttol) *gttol=tao->gttol;
1128   PetscFunctionReturn(0);
1129 }
1130 
1131 /*@
1132   TaoGetKSP - Gets the linear solver used by the optimization solver.
1133   Application writers should use TaoGetKSP if they need direct access
1134   to the PETSc KSP object.
1135 
1136   Not Collective
1137 
1138    Input Parameters:
1139 .  tao - the TAO solver
1140 
1141    Output Parameters:
1142 .  ksp - the KSP linear solver used in the optimization solver
1143 
1144    Level: intermediate
1145 
1146 @*/
1147 PetscErrorCode TaoGetKSP(Tao tao, KSP *ksp)
1148 {
1149   PetscFunctionBegin;
1150   *ksp = tao->ksp;
1151   PetscFunctionReturn(0);
1152 }
1153 
1154 /*@
1155    TaoGetLinearSolveIterations - Gets the total number of linear iterations
1156    used by the TAO solver
1157 
1158    Not Collective
1159 
1160    Input Parameter:
1161 .  tao - TAO context
1162 
1163    Output Parameter:
1164 .  lits - number of linear iterations
1165 
1166    Notes:
1167    This counter is reset to zero for each successive call to TaoSolve()
1168 
1169    Level: intermediate
1170 
1171 .keywords: TAO
1172 
1173 .seealso:  TaoGetKSP()
1174 @*/
1175 PetscErrorCode  TaoGetLinearSolveIterations(Tao tao,PetscInt *lits)
1176 {
1177   PetscFunctionBegin;
1178   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1179   PetscValidIntPointer(lits,2);
1180   *lits = tao->ksp_tot_its;
1181   PetscFunctionReturn(0);
1182 }
1183 
1184 /*@
1185   TaoGetLineSearch - Gets the line search used by the optimization solver.
1186   Application writers should use TaoGetLineSearch if they need direct access
1187   to the TaoLineSearch object.
1188 
1189   Not Collective
1190 
1191    Input Parameters:
1192 .  tao - the TAO solver
1193 
1194    Output Parameters:
1195 .  ls - the line search used in the optimization solver
1196 
1197    Level: intermediate
1198 
1199 @*/
1200 PetscErrorCode TaoGetLineSearch(Tao tao, TaoLineSearch *ls)
1201 {
1202   PetscFunctionBegin;
1203   *ls = tao->linesearch;
1204   PetscFunctionReturn(0);
1205 }
1206 
1207 /*@
1208   TaoAddLineSearchCounts - Adds the number of function evaluations spent
1209   in the line search to the running total.
1210 
1211    Input Parameters:
1212 +  tao - the TAO solver
1213 -  ls - the line search used in the optimization solver
1214 
1215    Level: developer
1216 
1217 .seealso: TaoLineSearchApply()
1218 @*/
1219 PetscErrorCode TaoAddLineSearchCounts(Tao tao)
1220 {
1221   PetscErrorCode ierr;
1222   PetscBool      flg;
1223   PetscInt       nfeval,ngeval,nfgeval;
1224 
1225   PetscFunctionBegin;
1226   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1227   if (tao->linesearch) {
1228     ierr = TaoLineSearchIsUsingTaoRoutines(tao->linesearch,&flg);CHKERRQ(ierr);
1229     if (!flg) {
1230       ierr = TaoLineSearchGetNumberFunctionEvaluations(tao->linesearch,&nfeval,&ngeval,&nfgeval);CHKERRQ(ierr);
1231       tao->nfuncs+=nfeval;
1232       tao->ngrads+=ngeval;
1233       tao->nfuncgrads+=nfgeval;
1234     }
1235   }
1236   PetscFunctionReturn(0);
1237 }
1238 
1239 /*@
1240   TaoGetSolutionVector - Returns the vector with the current TAO solution
1241 
1242   Not Collective
1243 
1244   Input Parameter:
1245 . tao - the Tao context
1246 
1247   Output Parameter:
1248 . X - the current solution
1249 
1250   Level: intermediate
1251 
1252   Note:  The returned vector will be the same object that was passed into TaoSetInitialVector()
1253 @*/
1254 PetscErrorCode TaoGetSolutionVector(Tao tao, Vec *X)
1255 {
1256   PetscFunctionBegin;
1257   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1258   *X = tao->solution;
1259   PetscFunctionReturn(0);
1260 }
1261 
1262 /*@
1263   TaoGetGradientVector - Returns the vector with the current TAO gradient
1264 
1265   Not Collective
1266 
1267   Input Parameter:
1268 . tao - the Tao context
1269 
1270   Output Parameter:
1271 . G - the current solution
1272 
1273   Level: intermediate
1274 @*/
1275 PetscErrorCode TaoGetGradientVector(Tao tao, Vec *G)
1276 {
1277   PetscFunctionBegin;
1278   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1279   *G = tao->gradient;
1280   PetscFunctionReturn(0);
1281 }
1282 
1283 /*@
1284    TaoResetStatistics - Initialize the statistics used by TAO for all of the solvers.
1285    These statistics include the iteration number, residual norms, and convergence status.
1286    This routine gets called before solving each optimization problem.
1287 
1288    Collective on Tao
1289 
1290    Input Parameters:
1291 .  solver - the Tao context
1292 
1293    Level: developer
1294 
1295 .seealso: TaoCreate(), TaoSolve()
1296 @*/
1297 PetscErrorCode TaoResetStatistics(Tao tao)
1298 {
1299   PetscFunctionBegin;
1300   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1301   tao->niter        = 0;
1302   tao->nfuncs       = 0;
1303   tao->nfuncgrads   = 0;
1304   tao->ngrads       = 0;
1305   tao->nhess        = 0;
1306   tao->njac         = 0;
1307   tao->nconstraints = 0;
1308   tao->ksp_its      = 0;
1309   tao->ksp_tot_its  = 0;
1310   tao->reason       = TAO_CONTINUE_ITERATING;
1311   tao->residual     = 0.0;
1312   tao->cnorm        = 0.0;
1313   tao->step         = 0.0;
1314   tao->lsflag       = PETSC_FALSE;
1315   if (tao->hist_reset) tao->hist_len=0;
1316   PetscFunctionReturn(0);
1317 }
1318 
1319 /*@C
1320   TaoSetConvergenceTest - Sets the function that is to be used to test
1321   for convergence o fthe iterative minimization solution.  The new convergence
1322   testing routine will replace TAO's default convergence test.
1323 
1324   Logically Collective on Tao
1325 
1326   Input Parameters:
1327 + tao - the Tao object
1328 . conv - the routine to test for convergence
1329 - ctx - [optional] context for private data for the convergence routine
1330         (may be NULL)
1331 
1332   Calling sequence of conv:
1333 $   PetscErrorCode conv(Tao tao, void *ctx)
1334 
1335 + tao - the Tao object
1336 - ctx - [optional] convergence context
1337 
1338   Note: The new convergence testing routine should call TaoSetConvergedReason().
1339 
1340   Level: advanced
1341 
1342 .seealso: TaoSetConvergedReason(), TaoGetSolutionStatus(), TaoGetTolerances(), TaoSetMonitor
1343 
1344 @*/
1345 PetscErrorCode TaoSetConvergenceTest(Tao tao, PetscErrorCode (*conv)(Tao,void*), void *ctx)
1346 {
1347   PetscFunctionBegin;
1348   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1349   (tao)->ops->convergencetest = conv;
1350   (tao)->cnvP = ctx;
1351   PetscFunctionReturn(0);
1352 }
1353 
1354 /*@C
1355    TaoSetMonitor - Sets an ADDITIONAL function that is to be used at every
1356    iteration of the solver to display the iteration's
1357    progress.
1358 
1359    Logically Collective on Tao
1360 
1361    Input Parameters:
1362 +  tao - the Tao solver context
1363 .  mymonitor - monitoring routine
1364 -  mctx - [optional] user-defined context for private data for the
1365           monitor routine (may be NULL)
1366 
1367    Calling sequence of mymonitor:
1368 $     int mymonitor(Tao tao,void *mctx)
1369 
1370 +    tao - the Tao solver context
1371 -    mctx - [optional] monitoring context
1372 
1373 
1374    Options Database Keys:
1375 +    -tao_monitor        - sets TaoMonitorDefault()
1376 .    -tao_smonitor       - sets short monitor
1377 .    -tao_cmonitor       - same as smonitor plus constraint norm
1378 .    -tao_view_solution   - view solution at each iteration
1379 .    -tao_view_gradient   - view gradient at each iteration
1380 .    -tao_view_separableobjective - view separable objective function at each iteration
1381 -    -tao_cancelmonitors - cancels all monitors that have been hardwired into a code by calls to TaoSetMonitor(), but does not cancel those set via the options database.
1382 
1383 
1384    Notes:
1385    Several different monitoring routines may be set by calling
1386    TaoSetMonitor() multiple times; all will be called in the
1387    order in which they were set.
1388 
1389    Fortran Notes: Only one monitor function may be set
1390 
1391    Level: intermediate
1392 
1393 .seealso: TaoMonitorDefault(), TaoCancelMonitors(),  TaoSetDestroyRoutine()
1394 @*/
1395 PetscErrorCode TaoSetMonitor(Tao tao, PetscErrorCode (*func)(Tao, void*), void *ctx,PetscErrorCode (*dest)(void**))
1396 {
1397   PetscErrorCode ierr;
1398   PetscInt       i;
1399 
1400   PetscFunctionBegin;
1401   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1402   if (tao->numbermonitors >= MAXTAOMONITORS) SETERRQ1(PETSC_COMM_SELF,1,"Cannot attach another monitor -- max=",MAXTAOMONITORS);
1403 
1404   for (i=0; i<tao->numbermonitors;i++) {
1405     if (func == tao->monitor[i] && dest == tao->monitordestroy[i] && ctx == tao->monitorcontext[i]) {
1406       if (dest) {
1407         ierr = (*dest)(&ctx);CHKERRQ(ierr);
1408       }
1409       PetscFunctionReturn(0);
1410     }
1411   }
1412   tao->monitor[tao->numbermonitors] = func;
1413   tao->monitorcontext[tao->numbermonitors] = ctx;
1414   tao->monitordestroy[tao->numbermonitors] = dest;
1415   ++tao->numbermonitors;
1416   PetscFunctionReturn(0);
1417 }
1418 
1419 /*@
1420    TaoCancelMonitors - Clears all the monitor functions for a Tao object.
1421 
1422    Logically Collective on Tao
1423 
1424    Input Parameters:
1425 .  tao - the Tao solver context
1426 
1427    Options Database:
1428 .  -tao_cancelmonitors - cancels all monitors that have been hardwired
1429     into a code by calls to TaoSetMonitor(), but does not cancel those
1430     set via the options database
1431 
1432    Notes:
1433    There is no way to clear one specific monitor from a Tao object.
1434 
1435    Level: advanced
1436 
1437 .seealso: TaoMonitorDefault(), TaoSetMonitor()
1438 @*/
1439 PetscErrorCode TaoCancelMonitors(Tao tao)
1440 {
1441   PetscInt       i;
1442   PetscErrorCode ierr;
1443 
1444   PetscFunctionBegin;
1445   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
1446   for (i=0;i<tao->numbermonitors;i++) {
1447     if (tao->monitordestroy[i]) {
1448       ierr = (*tao->monitordestroy[i])(&tao->monitorcontext[i]);CHKERRQ(ierr);
1449     }
1450   }
1451   tao->numbermonitors=0;
1452   PetscFunctionReturn(0);
1453 }
1454 
1455 /*@
1456    TaoMonitorDefault - Default routine for monitoring progress of the
1457    Tao solvers (default).  This monitor prints the function value and gradient
1458    norm at each iteration.  It can be turned on from the command line using the
1459    -tao_monitor option
1460 
1461    Collective on Tao
1462 
1463    Input Parameters:
1464 +  tao - the Tao context
1465 -  ctx - PetscViewer context or NULL
1466 
1467    Options Database Keys:
1468 .  -tao_monitor
1469 
1470    Level: advanced
1471 
1472 .seealso: TaoDefaultSMonitor(), TaoSetMonitor()
1473 @*/
1474 PetscErrorCode TaoMonitorDefault(Tao tao, void *ctx)
1475 {
1476   PetscErrorCode ierr;
1477   PetscInt       its;
1478   PetscReal      fct,gnorm;
1479   PetscViewer    viewer = (PetscViewer)ctx;
1480 
1481   PetscFunctionBegin;
1482   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1483   its=tao->niter;
1484   fct=tao->fc;
1485   gnorm=tao->residual;
1486   ierr=PetscViewerASCIIPrintf(viewer,"%3D TAO,",its);CHKERRQ(ierr);
1487   ierr=PetscViewerASCIIPrintf(viewer," Function value: %g,",(double)fct);CHKERRQ(ierr);
1488   if (gnorm >= PETSC_INFINITY) {
1489     ierr=PetscViewerASCIIPrintf(viewer,"  Residual: Inf \n");CHKERRQ(ierr);
1490   } else {
1491     ierr=PetscViewerASCIIPrintf(viewer,"  Residual: %g \n",(double)gnorm);CHKERRQ(ierr);
1492   }
1493   PetscFunctionReturn(0);
1494 }
1495 
1496 /*@
1497    TaoDefaultSMonitor - Default routine for monitoring progress of the
1498    solver. Same as TaoMonitorDefault() except
1499    it prints fewer digits of the residual as the residual gets smaller.
1500    This is because the later digits are meaningless and are often
1501    different on different machines; by using this routine different
1502    machines will usually generate the same output. It can be turned on
1503    by using the -tao_smonitor option
1504 
1505    Collective on Tao
1506 
1507    Input Parameters:
1508 +  tao - the Tao context
1509 -  ctx - PetscViewer context of type ASCII
1510 
1511    Options Database Keys:
1512 .  -tao_smonitor
1513 
1514    Level: advanced
1515 
1516 .seealso: TaoMonitorDefault(), TaoSetMonitor()
1517 @*/
1518 PetscErrorCode TaoDefaultSMonitor(Tao tao, void *ctx)
1519 {
1520   PetscErrorCode ierr;
1521   PetscInt       its;
1522   PetscReal      fct,gnorm;
1523   PetscViewer    viewer = (PetscViewer)ctx;
1524 
1525   PetscFunctionBegin;
1526   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1527   its=tao->niter;
1528   fct=tao->fc;
1529   gnorm=tao->residual;
1530   ierr=PetscViewerASCIIPrintf(viewer,"iter = %3D,",its);CHKERRQ(ierr);
1531   ierr=PetscViewerASCIIPrintf(viewer," Function value %g,",(double)fct);CHKERRQ(ierr);
1532   if (gnorm >= PETSC_INFINITY) {
1533     ierr=PetscViewerASCIIPrintf(viewer," Residual: Inf \n");CHKERRQ(ierr);
1534   } else if (gnorm > 1.e-6) {
1535     ierr=PetscViewerASCIIPrintf(viewer," Residual: %g \n",(double)gnorm);CHKERRQ(ierr);
1536   } else if (gnorm > 1.e-11) {
1537     ierr=PetscViewerASCIIPrintf(viewer," Residual: < 1.0e-6 \n");CHKERRQ(ierr);
1538   } else {
1539     ierr=PetscViewerASCIIPrintf(viewer," Residual: < 1.0e-11 \n");CHKERRQ(ierr);
1540   }
1541   PetscFunctionReturn(0);
1542 }
1543 
1544 /*@
1545    TaoDefaultCMonitor - same as TaoMonitorDefault() except
1546    it prints the norm of the constraints function. It can be turned on
1547    from the command line using the -tao_cmonitor option
1548 
1549    Collective on Tao
1550 
1551    Input Parameters:
1552 +  tao - the Tao context
1553 -  ctx - PetscViewer context or NULL
1554 
1555    Options Database Keys:
1556 .  -tao_cmonitor
1557 
1558    Level: advanced
1559 
1560 .seealso: TaoMonitorDefault(), TaoSetMonitor()
1561 @*/
1562 PetscErrorCode TaoDefaultCMonitor(Tao tao, void *ctx)
1563 {
1564   PetscErrorCode ierr;
1565   PetscInt       its;
1566   PetscReal      fct,gnorm;
1567   PetscViewer    viewer = (PetscViewer)ctx;
1568 
1569   PetscFunctionBegin;
1570   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1571   its=tao->niter;
1572   fct=tao->fc;
1573   gnorm=tao->residual;
1574   ierr=PetscViewerASCIIPrintf(viewer,"iter = %D,",its);CHKERRQ(ierr);
1575   ierr=PetscViewerASCIIPrintf(viewer," Function value: %g,",(double)fct);CHKERRQ(ierr);
1576   ierr=PetscViewerASCIIPrintf(viewer,"  Residual: %g ",(double)gnorm);CHKERRQ(ierr);
1577   ierr = PetscViewerASCIIPrintf(viewer,"  Constraint: %g \n",(double)tao->cnorm);CHKERRQ(ierr);
1578   PetscFunctionReturn(0);
1579 }
1580 
1581 /*@C
1582    TaoSolutionMonitor - Views the solution at each iteration
1583    It can be turned on from the command line using the
1584    -tao_view_solution option
1585 
1586    Collective on Tao
1587 
1588    Input Parameters:
1589 +  tao - the Tao context
1590 -  ctx - PetscViewer context or NULL
1591 
1592    Options Database Keys:
1593 .  -tao_view_solution
1594 
1595    Level: advanced
1596 
1597 .seealso: TaoDefaultSMonitor(), TaoSetMonitor()
1598 @*/
1599 PetscErrorCode TaoSolutionMonitor(Tao tao, void *ctx)
1600 {
1601   PetscErrorCode ierr;
1602   PetscViewer    viewer  = (PetscViewer)ctx;;
1603 
1604   PetscFunctionBegin;
1605   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1606   ierr = VecView(tao->solution, viewer);CHKERRQ(ierr);
1607   PetscFunctionReturn(0);
1608 }
1609 
1610 /*@C
1611    TaoGradientMonitor - Views the gradient at each iteration
1612    It can be turned on from the command line using the
1613    -tao_view_gradient option
1614 
1615    Collective on Tao
1616 
1617    Input Parameters:
1618 +  tao - the Tao context
1619 -  ctx - PetscViewer context or NULL
1620 
1621    Options Database Keys:
1622 .  -tao_view_gradient
1623 
1624    Level: advanced
1625 
1626 .seealso: TaoDefaultSMonitor(), TaoSetMonitor()
1627 @*/
1628 PetscErrorCode TaoGradientMonitor(Tao tao, void *ctx)
1629 {
1630   PetscErrorCode ierr;
1631   PetscViewer    viewer = (PetscViewer)ctx;
1632 
1633   PetscFunctionBegin;
1634   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1635   ierr = VecView(tao->gradient, viewer);CHKERRQ(ierr);
1636   PetscFunctionReturn(0);
1637 }
1638 
1639 /*@C
1640    TaoStepDirectionMonitor - Views the gradient at each iteration
1641    It can be turned on from the command line using the
1642    -tao_view_gradient option
1643 
1644    Collective on Tao
1645 
1646    Input Parameters:
1647 +  tao - the Tao context
1648 -  ctx - PetscViewer context or NULL
1649 
1650    Options Database Keys:
1651 .  -tao_view_gradient
1652 
1653    Level: advanced
1654 
1655 .seealso: TaoDefaultSMonitor(), TaoSetMonitor()
1656 @*/
1657 PetscErrorCode TaoStepDirectionMonitor(Tao tao, void *ctx)
1658 {
1659   PetscErrorCode ierr;
1660   PetscViewer    viewer = (PetscViewer)ctx;
1661 
1662   PetscFunctionBegin;
1663   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1664   ierr = VecView(tao->stepdirection, viewer);CHKERRQ(ierr);
1665   PetscFunctionReturn(0);
1666 }
1667 
1668 /*@C
1669    TaoDrawSolutionMonitor - Plots the solution at each iteration
1670    It can be turned on from the command line using the
1671    -tao_draw_solution option
1672 
1673    Collective on Tao
1674 
1675    Input Parameters:
1676 +  tao - the Tao context
1677 -  ctx - TaoMonitorDraw context
1678 
1679    Options Database Keys:
1680 .  -tao_draw_solution
1681 
1682    Level: advanced
1683 
1684 .seealso: TaoSolutionMonitor(), TaoSetMonitor(), TaoDrawGradientMonitor
1685 @*/
1686 PetscErrorCode TaoDrawSolutionMonitor(Tao tao, void *ctx)
1687 {
1688   PetscErrorCode    ierr;
1689   TaoMonitorDrawCtx ictx = (TaoMonitorDrawCtx)ctx;
1690 
1691   PetscFunctionBegin;
1692   if (!(((ictx->howoften > 0) && (!(tao->niter % ictx->howoften))) || ((ictx->howoften == -1) && tao->reason))) PetscFunctionReturn(0);
1693   ierr = VecView(tao->solution,ictx->viewer);CHKERRQ(ierr);
1694   PetscFunctionReturn(0);
1695 }
1696 
1697 /*@C
1698    TaoDrawGradientMonitor - Plots the gradient at each iteration
1699    It can be turned on from the command line using the
1700    -tao_draw_gradient option
1701 
1702    Collective on Tao
1703 
1704    Input Parameters:
1705 +  tao - the Tao context
1706 -  ctx - PetscViewer context
1707 
1708    Options Database Keys:
1709 .  -tao_draw_gradient
1710 
1711    Level: advanced
1712 
1713 .seealso: TaoGradientMonitor(), TaoSetMonitor(), TaoDrawSolutionMonitor
1714 @*/
1715 PetscErrorCode TaoDrawGradientMonitor(Tao tao, void *ctx)
1716 {
1717   PetscErrorCode    ierr;
1718   TaoMonitorDrawCtx ictx = (TaoMonitorDrawCtx)ctx;
1719 
1720   PetscFunctionBegin;
1721   if (!(((ictx->howoften > 0) && (!(tao->niter % ictx->howoften))) || ((ictx->howoften == -1) && tao->reason))) PetscFunctionReturn(0);
1722   ierr = VecView(tao->gradient,ictx->viewer);CHKERRQ(ierr);
1723   PetscFunctionReturn(0);
1724 }
1725 
1726 /*@C
1727    TaoDrawStepMonitor - Plots the step direction at each iteration
1728    It can be turned on from the command line using the
1729    -tao_draw_step option
1730 
1731    Collective on Tao
1732 
1733    Input Parameters:
1734 +  tao - the Tao context
1735 -  ctx - PetscViewer context
1736 
1737    Options Database Keys:
1738 .  -tao_draw_step
1739 
1740    Level: advanced
1741 
1742 .seealso: TaoSetMonitor(), TaoDrawSolutionMonitor
1743 @*/
1744 PetscErrorCode TaoDrawStepMonitor(Tao tao, void *ctx)
1745 {
1746   PetscErrorCode ierr;
1747   PetscViewer    viewer = (PetscViewer)(ctx);
1748 
1749   PetscFunctionBegin;
1750   ierr = VecView(tao->stepdirection, viewer);CHKERRQ(ierr);
1751   PetscFunctionReturn(0);
1752 }
1753 
1754 /*@C
1755    TaoSeparableObjectiveMonitor - Views the separable objective function at each iteration
1756    It can be turned on from the command line using the
1757    -tao_view_separableobjective option
1758 
1759    Collective on Tao
1760 
1761    Input Parameters:
1762 +  tao - the Tao context
1763 -  ctx - PetscViewer context or NULL
1764 
1765    Options Database Keys:
1766 .  -tao_view_separableobjective
1767 
1768    Level: advanced
1769 
1770 .seealso: TaoDefaultSMonitor(), TaoSetMonitor()
1771 @*/
1772 PetscErrorCode TaoSeparableObjectiveMonitor(Tao tao, void *ctx)
1773 {
1774   PetscErrorCode ierr;
1775   PetscViewer    viewer  = (PetscViewer)ctx;
1776 
1777   PetscFunctionBegin;
1778   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1779   ierr = VecView(tao->sep_objective,viewer);CHKERRQ(ierr);
1780   PetscFunctionReturn(0);
1781 }
1782 
1783 /*@
1784    TaoDefaultConvergenceTest - Determines whether the solver should continue iterating
1785    or terminate.
1786 
1787    Collective on Tao
1788 
1789    Input Parameters:
1790 +  tao - the Tao context
1791 -  dummy - unused dummy context
1792 
1793    Output Parameter:
1794 .  reason - for terminating
1795 
1796    Notes:
1797    This routine checks the residual in the optimality conditions, the
1798    relative residual in the optimity conditions, the number of function
1799    evaluations, and the function value to test convergence.  Some
1800    solvers may use different convergence routines.
1801 
1802    Level: developer
1803 
1804 .seealso: TaoSetTolerances(),TaoGetConvergedReason(),TaoSetConvergedReason()
1805 @*/
1806 
1807 PetscErrorCode TaoDefaultConvergenceTest(Tao tao,void *dummy)
1808 {
1809   PetscInt           niter=tao->niter, nfuncs=PetscMax(tao->nfuncs,tao->nfuncgrads);
1810   PetscInt           max_funcs=tao->max_funcs;
1811   PetscReal          gnorm=tao->residual, gnorm0=tao->gnorm0;
1812   PetscReal          f=tao->fc, steptol=tao->steptol,trradius=tao->step;
1813   PetscReal          gatol=tao->gatol,grtol=tao->grtol,gttol=tao->gttol;
1814   PetscReal          catol=tao->catol,crtol=tao->crtol;
1815   PetscReal          fmin=tao->fmin, cnorm=tao->cnorm;
1816   TaoConvergedReason reason=tao->reason;
1817   PetscErrorCode     ierr;
1818 
1819   PetscFunctionBegin;
1820   PetscValidHeaderSpecific(tao, TAO_CLASSID,1);
1821   if (reason != TAO_CONTINUE_ITERATING) {
1822     PetscFunctionReturn(0);
1823   }
1824 
1825   if (PetscIsInfOrNanReal(f)) {
1826     ierr = PetscInfo(tao,"Failed to converged, function value is Inf or NaN\n");CHKERRQ(ierr);
1827     reason = TAO_DIVERGED_NAN;
1828   } else if (f <= fmin && cnorm <=catol) {
1829     ierr = PetscInfo2(tao,"Converged due to function value %g < minimum function value %g\n", (double)f,(double)fmin);CHKERRQ(ierr);
1830     reason = TAO_CONVERGED_MINF;
1831   } else if (gnorm<= gatol && cnorm <=catol) {
1832     ierr = PetscInfo2(tao,"Converged due to residual norm ||g(X)||=%g < %g\n",(double)gnorm,(double)gatol);CHKERRQ(ierr);
1833     reason = TAO_CONVERGED_GATOL;
1834   } else if ( f!=0 && PetscAbsReal(gnorm/f) <= grtol && cnorm <= crtol) {
1835     ierr = PetscInfo2(tao,"Converged due to residual ||g(X)||/|f(X)| =%g < %g\n",(double)(gnorm/f),(double)grtol);CHKERRQ(ierr);
1836     reason = TAO_CONVERGED_GRTOL;
1837   } else if (gnorm0 != 0 && ((gttol == 0 && gnorm == 0) || gnorm/gnorm0 < gttol) && cnorm <= crtol) {
1838     ierr = PetscInfo2(tao,"Converged due to relative residual norm ||g(X)||/||g(X0)|| = %g < %g\n",(double)(gnorm/gnorm0),(double)gttol);CHKERRQ(ierr);
1839     reason = TAO_CONVERGED_GTTOL;
1840   } else if (nfuncs > max_funcs){
1841     ierr = PetscInfo2(tao,"Exceeded maximum number of function evaluations: %D > %D\n", nfuncs,max_funcs);CHKERRQ(ierr);
1842     reason = TAO_DIVERGED_MAXFCN;
1843   } else if ( tao->lsflag != 0 ){
1844     ierr = PetscInfo(tao,"Tao Line Search failure.\n");CHKERRQ(ierr);
1845     reason = TAO_DIVERGED_LS_FAILURE;
1846   } else if (trradius < steptol && niter > 0){
1847     ierr = PetscInfo2(tao,"Trust region/step size too small: %g < %g\n", (double)trradius,(double)steptol);CHKERRQ(ierr);
1848     reason = TAO_CONVERGED_STEPTOL;
1849   } else if (niter > tao->max_it) {
1850     ierr = PetscInfo2(tao,"Exceeded maximum number of iterations: %D > %D\n",niter,tao->max_it);CHKERRQ(ierr);
1851     reason = TAO_DIVERGED_MAXITS;
1852   } else {
1853     reason = TAO_CONTINUE_ITERATING;
1854   }
1855   tao->reason = reason;
1856   PetscFunctionReturn(0);
1857 }
1858 
1859 /*@C
1860    TaoSetOptionsPrefix - Sets the prefix used for searching for all
1861    TAO options in the database.
1862 
1863 
1864    Logically Collective on Tao
1865 
1866    Input Parameters:
1867 +  tao - the Tao context
1868 -  prefix - the prefix string to prepend to all TAO option requests
1869 
1870    Notes:
1871    A hyphen (-) must NOT be given at the beginning of the prefix name.
1872    The first character of all runtime options is AUTOMATICALLY the hyphen.
1873 
1874    For example, to distinguish between the runtime options for two
1875    different TAO solvers, one could call
1876 .vb
1877       TaoSetOptionsPrefix(tao1,"sys1_")
1878       TaoSetOptionsPrefix(tao2,"sys2_")
1879 .ve
1880 
1881    This would enable use of different options for each system, such as
1882 .vb
1883       -sys1_tao_method blmvm -sys1_tao_gtol 1.e-3
1884       -sys2_tao_method lmvm  -sys2_tao_gtol 1.e-4
1885 .ve
1886 
1887 
1888    Level: advanced
1889 
1890 .seealso: TaoAppendOptionsPrefix(), TaoGetOptionsPrefix()
1891 @*/
1892 
1893 PetscErrorCode TaoSetOptionsPrefix(Tao tao, const char p[])
1894 {
1895   PetscErrorCode ierr;
1896 
1897   PetscFunctionBegin;
1898   ierr = PetscObjectSetOptionsPrefix((PetscObject)tao,p);CHKERRQ(ierr);
1899   if (tao->linesearch) {
1900     ierr = TaoLineSearchSetOptionsPrefix(tao->linesearch,p);CHKERRQ(ierr);
1901   }
1902   if (tao->ksp) {
1903     ierr = KSPSetOptionsPrefix(tao->ksp,p);CHKERRQ(ierr);
1904   }
1905   PetscFunctionReturn(0);
1906 }
1907 
1908 /*@C
1909    TaoAppendOptionsPrefix - Appends to the prefix used for searching for all
1910    TAO options in the database.
1911 
1912 
1913    Logically Collective on Tao
1914 
1915    Input Parameters:
1916 +  tao - the Tao solver context
1917 -  prefix - the prefix string to prepend to all TAO option requests
1918 
1919    Notes:
1920    A hyphen (-) must NOT be given at the beginning of the prefix name.
1921    The first character of all runtime options is AUTOMATICALLY the hyphen.
1922 
1923 
1924    Level: advanced
1925 
1926 .seealso: TaoSetOptionsPrefix(), TaoGetOptionsPrefix()
1927 @*/
1928 PetscErrorCode TaoAppendOptionsPrefix(Tao tao, const char p[])
1929 {
1930   PetscErrorCode ierr;
1931 
1932   PetscFunctionBegin;
1933   ierr = PetscObjectAppendOptionsPrefix((PetscObject)tao,p);CHKERRQ(ierr);
1934   if (tao->linesearch) {
1935     ierr = TaoLineSearchSetOptionsPrefix(tao->linesearch,p);CHKERRQ(ierr);
1936   }
1937   if (tao->ksp) {
1938     ierr = KSPSetOptionsPrefix(tao->ksp,p);CHKERRQ(ierr);
1939   }
1940   PetscFunctionReturn(0);
1941 }
1942 
1943 /*@C
1944   TaoGetOptionsPrefix - Gets the prefix used for searching for all
1945   TAO options in the database
1946 
1947   Not Collective
1948 
1949   Input Parameters:
1950 . tao - the Tao context
1951 
1952   Output Parameters:
1953 . prefix - pointer to the prefix string used is returned
1954 
1955   Notes: On the fortran side, the user should pass in a string 'prefix' of
1956   sufficient length to hold the prefix.
1957 
1958   Level: advanced
1959 
1960 .seealso: TaoSetOptionsPrefix(), TaoAppendOptionsPrefix()
1961 @*/
1962 PetscErrorCode TaoGetOptionsPrefix(Tao tao, const char *p[])
1963 {
1964    return PetscObjectGetOptionsPrefix((PetscObject)tao,p);
1965 }
1966 
1967 /*@C
1968    TaoSetType - Sets the method for the unconstrained minimization solver.
1969 
1970    Collective on Tao
1971 
1972    Input Parameters:
1973 +  solver - the Tao solver context
1974 -  type - a known method
1975 
1976    Options Database Key:
1977 .  -tao_type <type> - Sets the method; use -help for a list
1978    of available methods (for instance, "-tao_type lmvm" or "-tao_type tron")
1979 
1980    Available methods include:
1981 +    nls - Newton's method with line search for unconstrained minimization
1982 .    ntr - Newton's method with trust region for unconstrained minimization
1983 .    ntl - Newton's method with trust region, line search for unconstrained minimization
1984 .    lmvm - Limited memory variable metric method for unconstrained minimization
1985 .    cg - Nonlinear conjugate gradient method for unconstrained minimization
1986 .    nm - Nelder-Mead algorithm for derivate-free unconstrained minimization
1987 .    tron - Newton Trust Region method for bound constrained minimization
1988 .    gpcg - Newton Trust Region method for quadratic bound constrained minimization
1989 .    blmvm - Limited memory variable metric method for bound constrained minimization
1990 -    pounders - Model-based algorithm pounder extended for nonlinear least squares
1991 
1992   Level: intermediate
1993 
1994 .seealso: TaoCreate(), TaoGetType(), TaoType
1995 
1996 @*/
1997 PetscErrorCode TaoSetType(Tao tao, const TaoType type)
1998 {
1999   PetscErrorCode ierr;
2000   PetscErrorCode (*create_xxx)(Tao);
2001   PetscBool      issame;
2002 
2003   PetscFunctionBegin;
2004   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2005 
2006   ierr = PetscObjectTypeCompare((PetscObject)tao,type,&issame);CHKERRQ(ierr);
2007   if (issame) PetscFunctionReturn(0);
2008 
2009   ierr = PetscFunctionListFind(TaoList, type, (void(**)(void))&create_xxx);CHKERRQ(ierr);
2010   if (!create_xxx) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested Tao type %s",type);
2011 
2012   /* Destroy the existing solver information */
2013   if (tao->ops->destroy) {
2014     ierr = (*tao->ops->destroy)(tao);CHKERRQ(ierr);
2015   }
2016   ierr = KSPDestroy(&tao->ksp);CHKERRQ(ierr);
2017   ierr = TaoLineSearchDestroy(&tao->linesearch);CHKERRQ(ierr);
2018   ierr = VecDestroy(&tao->gradient);CHKERRQ(ierr);
2019   ierr = VecDestroy(&tao->stepdirection);CHKERRQ(ierr);
2020 
2021   tao->ops->setup = 0;
2022   tao->ops->solve = 0;
2023   tao->ops->view  = 0;
2024   tao->ops->setfromoptions = 0;
2025   tao->ops->destroy = 0;
2026 
2027   tao->setupcalled = PETSC_FALSE;
2028 
2029   ierr = (*create_xxx)(tao);CHKERRQ(ierr);
2030   ierr = PetscObjectChangeTypeName((PetscObject)tao,type);CHKERRQ(ierr);
2031   PetscFunctionReturn(0);
2032 }
2033 
2034 /*MC
2035    TaoRegister - Adds a method to the TAO package for unconstrained minimization.
2036 
2037    Synopsis:
2038    TaoRegister(char *name_solver,char *path,char *name_Create,int (*routine_Create)(Tao))
2039 
2040    Not collective
2041 
2042    Input Parameters:
2043 +  sname - name of a new user-defined solver
2044 -  func - routine to Create method context
2045 
2046    Notes:
2047    TaoRegister() may be called multiple times to add several user-defined solvers.
2048 
2049    Sample usage:
2050 .vb
2051    TaoRegister("my_solver",MySolverCreate);
2052 .ve
2053 
2054    Then, your solver can be chosen with the procedural interface via
2055 $     TaoSetType(tao,"my_solver")
2056    or at runtime via the option
2057 $     -tao_type my_solver
2058 
2059    Level: advanced
2060 
2061 .seealso: TaoRegisterAll(), TaoRegisterDestroy()
2062 M*/
2063 PetscErrorCode TaoRegister(const char sname[], PetscErrorCode (*func)(Tao))
2064 {
2065   PetscErrorCode ierr;
2066 
2067   PetscFunctionBegin;
2068   ierr = PetscFunctionListAdd(&TaoList,sname, (void (*)(void))func);CHKERRQ(ierr);
2069   PetscFunctionReturn(0);
2070 }
2071 
2072 /*@C
2073    TaoRegisterDestroy - Frees the list of minimization solvers that were
2074    registered by TaoRegisterDynamic().
2075 
2076    Not Collective
2077 
2078    Level: advanced
2079 
2080 .seealso: TaoRegisterAll(), TaoRegister()
2081 @*/
2082 PetscErrorCode TaoRegisterDestroy(void)
2083 {
2084   PetscErrorCode ierr;
2085   PetscFunctionBegin;
2086   ierr = PetscFunctionListDestroy(&TaoList);CHKERRQ(ierr);
2087   TaoRegisterAllCalled = PETSC_FALSE;
2088   PetscFunctionReturn(0);
2089 }
2090 
2091 /*@
2092    TaoGetIterationNumber - Gets the number of Tao iterations completed
2093    at this time.
2094 
2095    Not Collective
2096 
2097    Input Parameter:
2098 .  tao - Tao context
2099 
2100    Output Parameter:
2101 .  iter - iteration number
2102 
2103    Notes:
2104    For example, during the computation of iteration 2 this would return 1.
2105 
2106 
2107    Level: intermediate
2108 
2109 .keywords: Tao, nonlinear, get, iteration, number,
2110 
2111 .seealso:   TaoGetLinearSolveIterations(), TaoGetResidualNorm(), TaoGetObjective()
2112 @*/
2113 PetscErrorCode  TaoGetIterationNumber(Tao tao,PetscInt *iter)
2114 {
2115   PetscFunctionBegin;
2116   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2117   PetscValidIntPointer(iter,2);
2118   *iter = tao->niter;
2119   PetscFunctionReturn(0);
2120 }
2121 
2122 /*@
2123    TaoGetObjective - Gets the current value of the objective function
2124    at this time.
2125 
2126    Not Collective
2127 
2128    Input Parameter:
2129 .  tao - Tao context
2130 
2131    Output Parameter:
2132 .  value - the current value
2133 
2134    Level: intermediate
2135 
2136 .keywords: Tao, nonlinear, get, iteration, number,
2137 
2138 .seealso:   TaoGetLinearSolveIterations(), TaoGetIterationNumber(), TaoGetResidualNorm()
2139 @*/
2140 PetscErrorCode  TaoGetObjective(Tao tao,PetscReal *value)
2141 {
2142   PetscFunctionBegin;
2143   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2144   PetscValidRealPointer(value,2);
2145   *value = tao->fc;
2146   PetscFunctionReturn(0);
2147 }
2148 
2149 /*@
2150    TaoGetResidualNorm - Gets the current value of the norm of the residual
2151    at this time.
2152 
2153    Not Collective
2154 
2155    Input Parameter:
2156 .  tao - Tao context
2157 
2158    Output Parameter:
2159 .  value - the current value
2160 
2161    Level: intermediate
2162 
2163    Developer Note: This is the 2-norm of the residual, we cannot use TaoGetGradientNorm() because that has
2164                    a different meaning. For some reason Tao sometimes calls the gradient the residual.
2165 
2166 .keywords: Tao, nonlinear, get, iteration, number,
2167 
2168 .seealso:   TaoGetLinearSolveIterations(), TaoGetIterationNumber(), TaoGetObjective()
2169 @*/
2170 PetscErrorCode  TaoGetResidualNorm(Tao tao,PetscReal *value)
2171 {
2172   PetscFunctionBegin;
2173   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2174   PetscValidRealPointer(value,2);
2175   *value = tao->residual;
2176   PetscFunctionReturn(0);
2177 }
2178 
2179 /*@
2180    TaoSetIterationNumber - Sets the current iteration number.
2181 
2182    Not Collective
2183 
2184    Input Parameter:
2185 .  tao - Tao context
2186 .  iter - iteration number
2187 
2188    Level: developer
2189 
2190 .keywords: Tao, nonlinear, set, iteration, number,
2191 
2192 .seealso:   TaoGetLinearSolveIterations()
2193 @*/
2194 PetscErrorCode  TaoSetIterationNumber(Tao tao,PetscInt iter)
2195 {
2196   PetscErrorCode ierr;
2197 
2198   PetscFunctionBegin;
2199   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2200   ierr       = PetscObjectSAWsTakeAccess((PetscObject)tao);CHKERRQ(ierr);
2201   tao->niter = iter;
2202   ierr       = PetscObjectSAWsGrantAccess((PetscObject)tao);CHKERRQ(ierr);
2203   PetscFunctionReturn(0);
2204 }
2205 
2206 /*@
2207    TaoGetTotalIterationNumber - Gets the total number of Tao iterations
2208    completed. This number keeps accumulating if multiple solves
2209    are called with the Tao object.
2210 
2211    Not Collective
2212 
2213    Input Parameter:
2214 .  tao - Tao context
2215 
2216    Output Parameter:
2217 .  iter - iteration number
2218 
2219    Notes:
2220    The total iteration count is updated after each solve, if there is a current
2221    TaoSolve() in progress then those iterations are not yet counted.
2222 
2223    Level: intermediate
2224 
2225 .keywords: Tao, nonlinear, get, iteration, number,
2226 
2227 .seealso:   TaoGetLinearSolveIterations()
2228 @*/
2229 PetscErrorCode  TaoGetTotalIterationNumber(Tao tao,PetscInt *iter)
2230 {
2231   PetscFunctionBegin;
2232   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2233   PetscValidIntPointer(iter,2);
2234   *iter = tao->ntotalits;
2235   PetscFunctionReturn(0);
2236 }
2237 
2238 /*@
2239    TaoSetTotalIterationNumber - Sets the current total iteration number.
2240 
2241    Not Collective
2242 
2243    Input Parameter:
2244 .  tao - Tao context
2245 .  iter - iteration number
2246 
2247    Level: developer
2248 
2249 .keywords: Tao, nonlinear, set, iteration, number,
2250 
2251 .seealso:   TaoGetLinearSolveIterations()
2252 @*/
2253 PetscErrorCode  TaoSetTotalIterationNumber(Tao tao,PetscInt iter)
2254 {
2255   PetscErrorCode ierr;
2256 
2257   PetscFunctionBegin;
2258   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2259   ierr       = PetscObjectSAWsTakeAccess((PetscObject)tao);CHKERRQ(ierr);
2260   tao->ntotalits = iter;
2261   ierr       = PetscObjectSAWsGrantAccess((PetscObject)tao);CHKERRQ(ierr);
2262   PetscFunctionReturn(0);
2263 }
2264 
2265 /*@
2266   TaoSetConvergedReason - Sets the termination flag on a Tao object
2267 
2268   Logically Collective on Tao
2269 
2270   Input Parameters:
2271 + tao - the Tao context
2272 - reason - one of
2273 $     TAO_CONVERGED_ATOL (2),
2274 $     TAO_CONVERGED_RTOL (3),
2275 $     TAO_CONVERGED_STEPTOL (4),
2276 $     TAO_CONVERGED_MINF (5),
2277 $     TAO_CONVERGED_USER (6),
2278 $     TAO_DIVERGED_MAXITS (-2),
2279 $     TAO_DIVERGED_NAN (-4),
2280 $     TAO_DIVERGED_MAXFCN (-5),
2281 $     TAO_DIVERGED_LS_FAILURE (-6),
2282 $     TAO_DIVERGED_TR_REDUCTION (-7),
2283 $     TAO_DIVERGED_USER (-8),
2284 $     TAO_CONTINUE_ITERATING (0)
2285 
2286    Level: intermediate
2287 
2288 @*/
2289 PetscErrorCode TaoSetConvergedReason(Tao tao, TaoConvergedReason reason)
2290 {
2291   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2292   PetscFunctionBegin;
2293   tao->reason = reason;
2294   PetscFunctionReturn(0);
2295 }
2296 
2297 /*@
2298    TaoGetConvergedReason - Gets the reason the Tao iteration was stopped.
2299 
2300    Not Collective
2301 
2302    Input Parameter:
2303 .  tao - the Tao solver context
2304 
2305    Output Parameter:
2306 .  reason - one of
2307 $  TAO_CONVERGED_GATOL (3)           ||g(X)|| < gatol
2308 $  TAO_CONVERGED_GRTOL (4)           ||g(X)|| / f(X)  < grtol
2309 $  TAO_CONVERGED_GTTOL (5)           ||g(X)|| / ||g(X0)|| < gttol
2310 $  TAO_CONVERGED_STEPTOL (6)         step size small
2311 $  TAO_CONVERGED_MINF (7)            F < F_min
2312 $  TAO_CONVERGED_USER (8)            User defined
2313 $  TAO_DIVERGED_MAXITS (-2)          its > maxits
2314 $  TAO_DIVERGED_NAN (-4)             Numerical problems
2315 $  TAO_DIVERGED_MAXFCN (-5)          fevals > max_funcsals
2316 $  TAO_DIVERGED_LS_FAILURE (-6)      line search failure
2317 $  TAO_DIVERGED_TR_REDUCTION (-7)    trust region failure
2318 $  TAO_DIVERGED_USER(-8)             (user defined)
2319  $  TAO_CONTINUE_ITERATING (0)
2320 
2321    where
2322 +  X - current solution
2323 .  X0 - initial guess
2324 .  f(X) - current function value
2325 .  f(X*) - true solution (estimated)
2326 .  g(X) - current gradient
2327 .  its - current iterate number
2328 .  maxits - maximum number of iterates
2329 .  fevals - number of function evaluations
2330 -  max_funcsals - maximum number of function evaluations
2331 
2332    Level: intermediate
2333 
2334 .seealso: TaoSetConvergenceTest(), TaoSetTolerances()
2335 
2336 @*/
2337 PetscErrorCode TaoGetConvergedReason(Tao tao, TaoConvergedReason *reason)
2338 {
2339   PetscFunctionBegin;
2340   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2341   PetscValidPointer(reason,2);
2342   *reason = tao->reason;
2343   PetscFunctionReturn(0);
2344 }
2345 
2346 /*@
2347   TaoGetSolutionStatus - Get the current iterate, objective value,
2348   residual, infeasibility, and termination
2349 
2350   Not Collective
2351 
2352    Input Parameters:
2353 .  tao - the Tao context
2354 
2355    Output Parameters:
2356 +  iterate - the current iterate number (>=0)
2357 .  f - the current function value
2358 .  gnorm - the square of the gradient norm, duality gap, or other measure indicating distance from optimality.
2359 .  cnorm - the infeasibility of the current solution with regard to the constraints.
2360 .  xdiff - the step length or trust region radius of the most recent iterate.
2361 -  reason - The termination reason, which can equal TAO_CONTINUE_ITERATING
2362 
2363    Level: intermediate
2364 
2365    Note:
2366    TAO returns the values set by the solvers in the routine TaoMonitor().
2367 
2368    Note:
2369    If any of the output arguments are set to NULL, no corresponding value will be returned.
2370 
2371 .seealso: TaoMonitor(), TaoGetConvergedReason()
2372 @*/
2373 PetscErrorCode TaoGetSolutionStatus(Tao tao, PetscInt *its, PetscReal *f, PetscReal *gnorm, PetscReal *cnorm, PetscReal *xdiff, TaoConvergedReason *reason)
2374 {
2375   PetscFunctionBegin;
2376   if (its) *its=tao->niter;
2377   if (f) *f=tao->fc;
2378   if (gnorm) *gnorm=tao->residual;
2379   if (cnorm) *cnorm=tao->cnorm;
2380   if (reason) *reason=tao->reason;
2381   if (xdiff) *xdiff=tao->step;
2382   PetscFunctionReturn(0);
2383 }
2384 
2385 /*@C
2386    TaoGetType - Gets the current Tao algorithm.
2387 
2388    Not Collective
2389 
2390    Input Parameter:
2391 .  tao - the Tao solver context
2392 
2393    Output Parameter:
2394 .  type - Tao method
2395 
2396    Level: intermediate
2397 
2398 @*/
2399 PetscErrorCode TaoGetType(Tao tao, const TaoType *type)
2400 {
2401   PetscFunctionBegin;
2402   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2403   PetscValidPointer(type,2);
2404   *type=((PetscObject)tao)->type_name;
2405   PetscFunctionReturn(0);
2406 }
2407 
2408 /*@C
2409   TaoMonitor - Monitor the solver and the current solution.  This
2410   routine will record the iteration number and residual statistics,
2411   call any monitors specified by the user, and calls the convergence-check routine.
2412 
2413    Input Parameters:
2414 +  tao - the Tao context
2415 .  its - the current iterate number (>=0)
2416 .  f - the current objective function value
2417 .  res - the gradient norm, square root of the duality gap, or other measure indicating distince from optimality.  This measure will be recorded and
2418           used for some termination tests.
2419 .  cnorm - the infeasibility of the current solution with regard to the constraints.
2420 -  steplength - multiple of the step direction added to the previous iterate.
2421 
2422    Output Parameters:
2423 .  reason - The termination reason, which can equal TAO_CONTINUE_ITERATING
2424 
2425    Options Database Key:
2426 .  -tao_monitor - Use the default monitor, which prints statistics to standard output
2427 
2428 .seealso TaoGetConvergedReason(), TaoMonitorDefault(), TaoSetMonitor()
2429 
2430    Level: developer
2431 
2432 @*/
2433 PetscErrorCode TaoMonitor(Tao tao, PetscInt its, PetscReal f, PetscReal res, PetscReal cnorm, PetscReal steplength, TaoConvergedReason *reason)
2434 {
2435   PetscErrorCode ierr;
2436   PetscInt       i;
2437 
2438   PetscFunctionBegin;
2439   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2440   tao->fc = f;
2441   tao->residual = res;
2442   tao->cnorm = cnorm;
2443   tao->step = steplength;
2444   if (!its) {
2445     tao->cnorm0 = cnorm; tao->gnorm0 = res;
2446   }
2447   TaoLogConvergenceHistory(tao,f,res,cnorm,tao->ksp_its);
2448   if (PetscIsInfOrNanReal(f) || PetscIsInfOrNanReal(res)) SETERRQ(PETSC_COMM_SELF,1, "User provided compute function generated Inf or NaN");
2449   if (tao->ops->convergencetest) {
2450     ierr = (*tao->ops->convergencetest)(tao,tao->cnvP);CHKERRQ(ierr);
2451   }
2452   for (i=0;i<tao->numbermonitors;i++) {
2453     ierr = (*tao->monitor[i])(tao,tao->monitorcontext[i]);CHKERRQ(ierr);
2454   }
2455   *reason = tao->reason;
2456   PetscFunctionReturn(0);
2457 }
2458 
2459 /*@
2460    TaoSetConvergenceHistory - Sets the array used to hold the convergence history.
2461 
2462    Logically Collective on Tao
2463 
2464    Input Parameters:
2465 +  tao - the Tao solver context
2466 .  obj   - array to hold objective value history
2467 .  resid - array to hold residual history
2468 .  cnorm - array to hold constraint violation history
2469 .  lits - integer array holds the number of linear iterations for each Tao iteration
2470 .  na  - size of obj, resid, and cnorm
2471 -  reset - PetscTrue indicates each new minimization resets the history counter to zero,
2472            else it continues storing new values for new minimizations after the old ones
2473 
2474    Notes:
2475    If set, TAO will fill the given arrays with the indicated
2476    information at each iteration.  If 'obj','resid','cnorm','lits' are
2477    *all* NULL then space (using size na, or 1000 if na is PETSC_DECIDE or
2478    PETSC_DEFAULT) is allocated for the history.
2479    If not all are NULL, then only the non-NULL information categories
2480    will be stored, the others will be ignored.
2481 
2482    Any convergence information after iteration number 'na' will not be stored.
2483 
2484    This routine is useful, e.g., when running a code for purposes
2485    of accurate performance monitoring, when no I/O should be done
2486    during the section of code that is being timed.
2487 
2488    Level: intermediate
2489 
2490 .seealso: TaoGetConvergenceHistory()
2491 
2492 @*/
2493 PetscErrorCode TaoSetConvergenceHistory(Tao tao, PetscReal obj[], PetscReal resid[], PetscReal cnorm[], PetscInt lits[], PetscInt na,PetscBool reset)
2494 {
2495   PetscErrorCode ierr;
2496 
2497   PetscFunctionBegin;
2498   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2499   if (obj) PetscValidScalarPointer(obj,2);
2500   if (resid) PetscValidScalarPointer(resid,3);
2501   if (cnorm) PetscValidScalarPointer(cnorm,4);
2502   if (lits) PetscValidIntPointer(lits,5);
2503 
2504   if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
2505   if (!obj && !resid && !cnorm && !lits) {
2506     ierr = PetscCalloc1(na,&obj);CHKERRQ(ierr);
2507     ierr = PetscCalloc1(na,&resid);CHKERRQ(ierr);
2508     ierr = PetscCalloc1(na,&cnorm);CHKERRQ(ierr);
2509     ierr = PetscCalloc1(na,&lits);CHKERRQ(ierr);
2510     tao->hist_malloc=PETSC_TRUE;
2511   }
2512 
2513   tao->hist_obj = obj;
2514   tao->hist_resid = resid;
2515   tao->hist_cnorm = cnorm;
2516   tao->hist_lits = lits;
2517   tao->hist_max   = na;
2518   tao->hist_reset = reset;
2519   tao->hist_len = 0;
2520   PetscFunctionReturn(0);
2521 }
2522 
2523 /*@C
2524    TaoGetConvergenceHistory - Gets the arrays used to hold the convergence history.
2525 
2526    Collective on Tao
2527 
2528    Input Parameter:
2529 .  tao - the Tao context
2530 
2531    Output Parameters:
2532 +  obj   - array used to hold objective value history
2533 .  resid - array used to hold residual history
2534 .  cnorm - array used to hold constraint violation history
2535 .  lits  - integer array used to hold linear solver iteration count
2536 -  nhist  - size of obj, resid, cnorm, and lits (will be less than or equal to na given in TaoSetHistory)
2537 
2538    Notes:
2539     This routine must be preceded by calls to TaoSetConvergenceHistory()
2540     and TaoSolve(), otherwise it returns useless information.
2541 
2542     The calling sequence for this routine in Fortran is
2543 $   call TaoGetConvergenceHistory(Tao tao, PetscInt nhist, PetscErrorCode ierr)
2544 
2545    This routine is useful, e.g., when running a code for purposes
2546    of accurate performance monitoring, when no I/O should be done
2547    during the section of code that is being timed.
2548 
2549    Level: advanced
2550 
2551 .seealso: TaoSetConvergenceHistory()
2552 
2553 @*/
2554 PetscErrorCode TaoGetConvergenceHistory(Tao tao, PetscReal **obj, PetscReal **resid, PetscReal **cnorm, PetscInt **lits, PetscInt *nhist)
2555 {
2556   PetscFunctionBegin;
2557   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2558   if (obj)   *obj   = tao->hist_obj;
2559   if (cnorm) *cnorm = tao->hist_cnorm;
2560   if (resid) *resid = tao->hist_resid;
2561   if (nhist) *nhist   = tao->hist_len;
2562   PetscFunctionReturn(0);
2563 }
2564 
2565 /*@
2566    TaoSetApplicationContext - Sets the optional user-defined context for
2567    a solver.
2568 
2569    Logically Collective on Tao
2570 
2571    Input Parameters:
2572 +  tao  - the Tao context
2573 -  usrP - optional user context
2574 
2575    Level: intermediate
2576 
2577 .seealso: TaoGetApplicationContext(), TaoSetApplicationContext()
2578 @*/
2579 PetscErrorCode  TaoSetApplicationContext(Tao tao,void *usrP)
2580 {
2581   PetscFunctionBegin;
2582   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2583   tao->user = usrP;
2584   PetscFunctionReturn(0);
2585 }
2586 
2587 /*@
2588    TaoGetApplicationContext - Gets the user-defined context for a
2589    TAO solvers.
2590 
2591    Not Collective
2592 
2593    Input Parameter:
2594 .  tao  - Tao context
2595 
2596    Output Parameter:
2597 .  usrP - user context
2598 
2599    Level: intermediate
2600 
2601 .seealso: TaoSetApplicationContext()
2602 @*/
2603 PetscErrorCode  TaoGetApplicationContext(Tao tao,void *usrP)
2604 {
2605   PetscFunctionBegin;
2606   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2607   *(void**)usrP = tao->user;
2608   PetscFunctionReturn(0);
2609 }
2610 
2611 /*@
2612    TaoSetGradientNorm - Sets the matrix used to define the inner product that measures the size of the gradient.
2613 
2614    Collective on tao
2615 
2616    Input Parameters:
2617 +  tao  - the Tao context
2618 -  M    - gradient norm
2619 
2620    Level: beginner
2621 
2622 .seealso: TaoGetGradientNorm(), TaoGradientNorm()
2623 @*/
2624 PetscErrorCode  TaoSetGradientNorm(Tao tao, Mat M)
2625 {
2626   PetscErrorCode ierr;
2627 
2628   PetscFunctionBegin;
2629   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2630 
2631   if (tao->gradient_norm) {
2632     ierr = PetscObjectDereference((PetscObject)tao->gradient_norm);CHKERRQ(ierr);
2633     ierr = VecDestroy(&tao->gradient_norm_tmp);CHKERRQ(ierr);
2634   }
2635 
2636   ierr = PetscObjectReference((PetscObject)M);CHKERRQ(ierr);
2637   tao->gradient_norm = M;
2638   ierr = MatCreateVecs(M, NULL, &tao->gradient_norm_tmp);CHKERRQ(ierr);
2639   PetscFunctionReturn(0);
2640 }
2641 
2642 /*@
2643    TaoGetGradientNorm - Returns the matrix used to define the inner product for measuring the size of the gradient.
2644 
2645    Not Collective
2646 
2647    Input Parameter:
2648 .  tao  - Tao context
2649 
2650    Output Parameter:
2651 .  M - gradient norm
2652 
2653    Level: beginner
2654 
2655 .seealso: TaoSetGradientNorm(), TaoGradientNorm()
2656 @*/
2657 PetscErrorCode  TaoGetGradientNorm(Tao tao, Mat *M)
2658 {
2659   PetscFunctionBegin;
2660   PetscValidHeaderSpecific(tao,TAO_CLASSID,1);
2661   *M = tao->gradient_norm;
2662   PetscFunctionReturn(0);
2663 }
2664 
2665 /*c
2666    TaoGradientNorm - Compute the norm with respect to the inner product the user has set.
2667 
2668    Collective on tao
2669 
2670    Input Parameter:
2671 .  tao      - the Tao context
2672 .  gradient - the gradient to be computed
2673 .  norm     - the norm type
2674 
2675    Output Parameter:
2676 .  gnorm    - the gradient norm
2677 
2678    Level: developer
2679 
2680 .seealso: TaoSetGradientNorm(), TaoGetGradientNorm()
2681 @*/
2682 PetscErrorCode  TaoGradientNorm(Tao tao, Vec gradient, NormType type, PetscReal *gnorm)
2683 {
2684   PetscErrorCode ierr;
2685 
2686   PetscFunctionBegin;
2687   PetscValidHeaderSpecific(gradient,VEC_CLASSID,1);
2688 
2689   if (tao->gradient_norm) {
2690     PetscScalar gnorms;
2691 
2692     if (type != NORM_2) SETERRQ(PetscObjectComm((PetscObject)gradient), PETSC_ERR_ARG_WRONGSTATE, "Norm type must be NORM_2 if an inner product for the gradient norm is set.");
2693     ierr = MatMult(tao->gradient_norm, gradient, tao->gradient_norm_tmp);CHKERRQ(ierr);
2694     ierr = VecDot(gradient, tao->gradient_norm_tmp, &gnorms);CHKERRQ(ierr);
2695     *gnorm = PetscRealPart(PetscSqrtScalar(gnorms));
2696   } else {
2697     ierr = VecNorm(gradient, type, gnorm);CHKERRQ(ierr);
2698   }
2699   PetscFunctionReturn(0);
2700 }
2701 
2702 /*@C
2703    TaoMonitorDrawCtxCreate - Creates the monitor context for TaoMonitorDrawCtx
2704 
2705    Collective on Tao
2706 
2707    Output Patameter:
2708 .    ctx - the monitor context
2709 
2710    Options Database:
2711 .   -tao_draw_solution_initial - show initial guess as well as current solution
2712 
2713    Level: intermediate
2714 
2715 .keywords: Tao,  vector, monitor, view
2716 
2717 .seealso: TaoMonitorSet(), TaoMonitorDefault(), VecView(), TaoMonitorDrawCtx()
2718 @*/
2719 PetscErrorCode  TaoMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TaoMonitorDrawCtx *ctx)
2720 {
2721   PetscErrorCode   ierr;
2722 
2723   PetscFunctionBegin;
2724   ierr = PetscNew(ctx);CHKERRQ(ierr);
2725   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
2726   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
2727   (*ctx)->howoften = howoften;
2728   PetscFunctionReturn(0);
2729 }
2730 
2731 /*@C
2732    TaoMonitorDrawCtxDestroy - Destroys the monitor context for TaoMonitorDrawSolution()
2733 
2734    Collective on Tao
2735 
2736    Input Parameters:
2737 .    ctx - the monitor context
2738 
2739    Level: intermediate
2740 
2741 .keywords: Tao,  vector, monitor, view
2742 
2743 .seealso: TaoMonitorSet(), TaoMonitorDefault(), VecView(), TaoMonitorDrawSolution()
2744 @*/
2745 PetscErrorCode  TaoMonitorDrawCtxDestroy(TaoMonitorDrawCtx *ictx)
2746 {
2747   PetscErrorCode ierr;
2748 
2749   PetscFunctionBegin;
2750   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
2751   ierr = PetscFree(*ictx);CHKERRQ(ierr);
2752   PetscFunctionReturn(0);
2753 }
2754