42 #ifndef THYRA_DIRECTIONAL_FINITE_DIFF_CALCULATOR_DEF_HPP
43 #define THYRA_DIRECTIONAL_FINITE_DIFF_CALCULATOR_DEF_HPP
46 #include "Thyra_DirectionalFiniteDiffCalculator_decl.hpp"
47 #include "Thyra_ModelEvaluatorHelpers.hpp"
48 #include "Thyra_DetachedVectorView.hpp"
49 #include "Thyra_DetachedMultiVectorView.hpp"
50 #include "Thyra_StateFuncModelEvaluatorBase.hpp"
51 #include "Thyra_MultiVectorStdOps.hpp"
52 #include "Thyra_VectorStdOps.hpp"
53 #include "Teuchos_TimeMonitor.hpp"
54 #include "Teuchos_VerboseObjectParameterListHelpers.hpp"
60 namespace DirectionalFiniteDiffCalculatorTypes {
73 template<
class Scalar>
74 class OutArgsCreator :
public StateFuncModelEvaluatorBase<Scalar>
78 RCP<const VectorSpaceBase<Scalar> > get_x_space()
const
80 RCP<const VectorSpaceBase<Scalar> > get_f_space()
const
82 ModelEvaluatorBase::InArgs<Scalar> createInArgs()
const
84 ModelEvaluatorBase::OutArgs<Scalar> createOutArgs()
const
87 const ModelEvaluatorBase::InArgs<Scalar> &inArgs,
88 const ModelEvaluatorBase::OutArgs<Scalar> &outArgs
92 static ModelEvaluatorBase::OutArgs<Scalar> createOutArgs(
93 const ModelEvaluator<Scalar> &model,
94 const SelectedDerivatives &fdDerivatives
100 const MEB::OutArgs<Scalar> wrappedOutArgs = model.createOutArgs();
101 const int Np = wrappedOutArgs.Np(),
Ng = wrappedOutArgs.Ng();
102 MEB::OutArgsSetup<Scalar> outArgs;
104 outArgs.setModelEvalDescription(
105 "DirectionalFiniteDiffCalculator: " + model.description()
111 outArgs.set_Np_Ng(Np,Ng);
112 outArgs.setSupports(wrappedOutArgs);
116 const SelectedDerivatives::supports_DfDp_t
117 &supports_DfDp = fdDerivatives.supports_DfDp_;
119 SelectedDerivatives::supports_DfDp_t::const_iterator
120 itr = supports_DfDp.begin();
121 itr != supports_DfDp.end();
126 assert_p_space(model,l);
127 outArgs.setSupports(MEB::OUT_ARG_DfDp,l,MEB::DERIV_MV_BY_COL);
132 const SelectedDerivatives::supports_DgDp_t
133 &supports_DgDp = fdDerivatives.supports_DgDp_;
135 SelectedDerivatives::supports_DgDp_t::const_iterator
136 itr = supports_DgDp.begin();
137 itr != supports_DgDp.end();
141 const int j = itr->first;
142 const int l = itr->second;
143 assert_p_space(model,l);
144 outArgs.setSupports(MEB::OUT_ARG_DgDp,j,l,MEB::DERIV_MV_BY_COL);
153 static void assert_p_space(
const ModelEvaluator<Scalar> &model,
const int l )
156 const bool p_space_l_is_in_core = model.get_p_space(l)->hasInCoreView();
158 !p_space_l_is_in_core, std::logic_error,
159 "Error, for the model " << model.description()
160 <<
", the space p_space("<<l<<
") must be in-core so that they can"
161 " act as the domain space for the multi-vector derivative!"
175 template<
class Scalar>
176 const std::string& DirectionalFiniteDiffCalculator<Scalar>::FDMethod_name()
178 static std::string loc_FDMethod_name =
"FD Method";
179 return loc_FDMethod_name;
183 template<
class Scalar>
186 Thyra::DirectionalFiniteDiffCalculatorTypes::EFDMethodType
189 DirectionalFiniteDiffCalculator<Scalar>::fdMethodValidator()
191 static RCP<Teuchos::StringToIntegralParameterEntryValidator<EFDMethodType> >
192 loc_fdMethodValidator
195 Teuchos::tuple<std::string>(
201 ,
"order-four-central"
204 ,Teuchos::tuple<std::string>(
205 "Use O(eps) one sided finite differences (cramped bounds)"
206 ,
"Use O(eps^2) one sided finite differences (cramped bounds)"
207 ,
"Use O(eps^2) two sided central finite differences"
208 ,
"Use \"order-two-central\" when not cramped by bounds, otherwise use \"order-two\""
209 ,
"Use O(eps^4) one sided finite differences (cramped bounds)"
210 ,
"Use O(eps^4) two sided central finite differences"
211 ,
"Use \"order-four-central\" when not cramped by bounds, otherwise use \"order-four\""
213 ,Teuchos::tuple<Thyra::DirectionalFiniteDiffCalculatorTypes::EFDMethodType>(
214 Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_ONE
215 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_TWO
216 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_TWO_CENTRAL
217 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_TWO_AUTO
218 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_FOUR
219 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_FOUR_CENTRAL
220 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_ORDER_FOUR_AUTO
225 return loc_fdMethodValidator;
229 template<
class Scalar>
231 DirectionalFiniteDiffCalculator<Scalar>::FDMethod_default()
233 static std::string loc_FDMethod_default =
"order-one";
234 return loc_FDMethod_default;
238 template<
class Scalar>
240 DirectionalFiniteDiffCalculator<Scalar>::FDStepSelectType_name()
242 static std::string loc_FDStepSelectType_name =
"FD Step Select Type";
243 return loc_FDStepSelectType_name;
247 template<
class Scalar>
250 Thyra::DirectionalFiniteDiffCalculatorTypes::EFDStepSelectType
253 DirectionalFiniteDiffCalculator<Scalar>::fdStepSelectTypeValidator()
255 static const RCP<Teuchos::StringToIntegralParameterEntryValidator<EFDStepSelectType> >
256 loc_fdStepSelectTypeValidator
259 Teuchos::tuple<std::string>(
263 ,Teuchos::tuple<std::string>(
264 "Use absolute step size \""+FDStepLength_name()+
"\""
265 ,
"Use relative step size \""+FDStepLength_name()+
"\"*||xo||inf"
267 ,Teuchos::tuple<Thyra::DirectionalFiniteDiffCalculatorTypes::EFDStepSelectType>(
268 Thyra::DirectionalFiniteDiffCalculatorTypes::FD_STEP_ABSOLUTE
269 ,Thyra::DirectionalFiniteDiffCalculatorTypes::FD_STEP_RELATIVE
274 return loc_fdStepSelectTypeValidator;
278 template<
class Scalar>
280 DirectionalFiniteDiffCalculator<Scalar>::FDStepSelectType_default()
282 static std::string loc_FDStepSelectType_default =
"Absolute";
283 return loc_FDStepSelectType_default;
287 template<
class Scalar>
289 DirectionalFiniteDiffCalculator<Scalar>::FDStepLength_name()
291 static std::string loc_FDStepLength_name =
"FD Step Length";
292 return loc_FDStepLength_name;
296 template<
class Scalar>
298 DirectionalFiniteDiffCalculator<Scalar>::FDStepLength_default()
300 static double loc_FDStepLength_default = -1.0;
301 return loc_FDStepLength_default;
308 template<
class Scalar>
315 :fd_method_type_(fd_method_type_in)
316 ,fd_step_select_type_(fd_step_select_type_in)
317 ,fd_step_size_(fd_step_size_in)
318 ,fd_step_size_min_(fd_step_size_min_in)
325 template<
class Scalar>
332 paramList_ = paramList;
334 *paramList_, FDMethod_name(), FDMethod_default());
335 fd_step_select_type_ = fdStepSelectTypeValidator()->getIntegralValue(
336 *paramList_, FDStepSelectType_name(), FDStepSelectType_default());
337 fd_step_size_ = paramList_->get(
338 FDStepLength_name(),FDStepLength_default());
339 Teuchos::readVerboseObjectSublist(&*paramList_,
this);
343 template<
class Scalar>
351 template<
class Scalar>
356 paramList_ = Teuchos::null;
361 template<
class Scalar>
369 template<
class Scalar>
373 using Teuchos::rcp_implicit_cast;
377 pl = Teuchos::parameterList();
379 FDMethod_name(), FDMethod_default(),
380 "The method used to compute the finite differences.",
381 rcp_implicit_cast<const PEV>(fdMethodValidator())
384 FDStepSelectType_name(), FDStepSelectType_default(),
385 "Method used to select the finite difference step length.",
386 rcp_implicit_cast<const PEV>(fdStepSelectTypeValidator())
389 FDStepLength_name(), FDStepLength_default()
390 ,
"The length of the finite difference step to take.\n"
391 "A value of < 0.0 means that the step length will be determined automatically."
393 Teuchos::setupVerboseObjectSublist(&*pl);
399 template<
class Scalar>
406 return DirectionalFiniteDiffCalculatorTypes::OutArgsCreator<Scalar>::createOutArgs(
407 model, fdDerivatives );
411 template<
class Scalar>
423 THYRA_FUNC_TIME_MONITOR(
424 string(
"Thyra::DirectionalFiniteDiffCalculator<")+ST::name()+
">::calcVariations(...)"
432 namespace DFDCT = DirectionalFiniteDiffCalculatorTypes;
440 if(out.
get() && trace)
441 *out <<
"\nEntering DirectionalFiniteDiffCalculator<Scalar>::calcVariations(...)\n";
443 if(out.
get() && trace)
445 <<
"\nbasePoint=\n" << describe(bp,verbLevel)
446 <<
"\ndirections=\n" << describe(dir,verbLevel)
447 <<
"\nbaseFunctionValues=\n" << describe(bfunc,verbLevel)
452 var.
isEmpty(), std::logic_error,
453 "Error, all of the variations can not be null!"
485 switch(this->fd_method_type()) {
486 case DFDCT::FD_ORDER_ONE:
487 if(out.
get()&&trace) *out<<
"\nUsing one-sided, first-order finite differences ...\n";
489 case DFDCT::FD_ORDER_TWO:
490 if(out.
get()&&trace) *out<<
"\nUsing one-sided, second-order finite differences ...\n";
492 case DFDCT::FD_ORDER_TWO_CENTRAL:
493 if(out.
get()&&trace) *out<<
"\nUsing second-order central finite differences ...\n";
495 case DFDCT::FD_ORDER_TWO_AUTO:
496 if(out.
get()&&trace) *out<<
"\nUsing auto selection of some second-order finite difference method ...\n";
498 case DFDCT::FD_ORDER_FOUR:
499 if(out.
get()&&trace) *out<<
"\nUsing one-sided, fourth-order finite differences ...\n";
501 case DFDCT::FD_ORDER_FOUR_CENTRAL:
502 if(out.
get()&&trace) *out<<
"\nUsing fourth-order central finite differences ...\n";
504 case DFDCT::FD_ORDER_FOUR_AUTO:
505 if(out.
get()&&trace) *out<<
"\nUsing auto selection of some fourth-order finite difference method ...\n";
519 sqrt_epsilon = SMT::squareroot(SMT::eps()),
520 u_optimal_1 = sqrt_epsilon,
521 u_optimal_2 = SMT::squareroot(sqrt_epsilon),
522 u_optimal_4 = SMT::squareroot(u_optimal_2);
525 bp_norm = SMT::zero();
530 switch(this->fd_method_type()) {
531 case DFDCT::FD_ORDER_ONE:
532 uh_opt = u_optimal_1 * ( fd_step_select_type() == DFDCT::FD_STEP_ABSOLUTE ? 1.0 : bp_norm + 1.0 );
534 case DFDCT::FD_ORDER_TWO:
535 case DFDCT::FD_ORDER_TWO_CENTRAL:
536 case DFDCT::FD_ORDER_TWO_AUTO:
537 uh_opt = u_optimal_2 * ( fd_step_select_type() == DFDCT::FD_STEP_ABSOLUTE ? 1.0 : bp_norm + 1.0 );
539 case DFDCT::FD_ORDER_FOUR:
540 case DFDCT::FD_ORDER_FOUR_CENTRAL:
541 case DFDCT::FD_ORDER_FOUR_AUTO:
542 uh_opt = u_optimal_4 * ( fd_step_select_type() == DFDCT::FD_STEP_ABSOLUTE ? 1.0 : bp_norm + 1.0 );
548 if(out.
get()&&trace) *out<<
"\nDefault optimal step length uh_opt = " << uh_opt <<
" ...\n";
555 uh = this->fd_step_size();
559 else if( fd_step_select_type() == DFDCT::FD_STEP_RELATIVE )
560 uh *= (bp_norm + 1.0);
562 if(out.
get()&&trace) *out<<
"\nStep size to be used uh="<<uh<<
"\n";
576 DFDCT::EFDMethodType l_fd_method_type = this->fd_method_type();
577 switch(l_fd_method_type) {
578 case DFDCT::FD_ORDER_TWO_AUTO:
579 l_fd_method_type = DFDCT::FD_ORDER_TWO_CENTRAL;
581 case DFDCT::FD_ORDER_FOUR_AUTO:
582 l_fd_method_type = DFDCT::FD_ORDER_FOUR_CENTRAL;
592 p_saved = out->precision();
597 const int Np = var.
Np(), Ng = var.
Ng();
600 VectorPtr per_x, per_x_dot, per_x_dot_dot;
601 std::vector<VectorPtr> per_p(Np);
605 if( dir.
get_x().get() )
608 pp.set_x(bp.
get_x());
610 if( bp.
supports(MEB::IN_ARG_x_dot) ) {
612 pp.set_x_dot(per_x_dot=createMember(model.
get_x_space()));
616 if( bp.
supports(MEB::IN_ARG_x_dot_dot) ) {
618 pp.set_x_dot_dot(per_x_dot_dot=createMember(model.
get_x_space()));
622 for(
int l = 0; l < Np; ++l ) {
623 if( dir.
get_p(l).get() )
624 pp.set_p(l,per_p[l]=createMember(model.
get_p_space(l)));
626 pp.set_p(l,bp.
get_p(l));
628 if(out.
get() && trace)
630 <<
"\nperturbedPoint after initial setup (with some uninitialized vectors) =\n"
631 << describe(pp,verbLevel);
634 bool all_funcs_at_base_computed =
true;
638 if( var.
supports(MEB::OUT_ARG_f) && (f=var.
get_f()).get() ) {
640 assign(f.ptr(),ST::zero());
641 if(!bfunc.
get_f().get()) all_funcs_at_base_computed =
false;
643 for(
int j = 0; j < Ng; ++j ) {
645 if( (g_j=var.
get_g(j)).get() ) {
647 assign(g_j.ptr(),ST::zero());
648 if(!bfunc.
get_g(j).get()) all_funcs_at_base_computed =
false;
652 if(out.
get() && trace)
654 <<
"\nperturbedFunctions after initial setup (with some uninitialized vectors) =\n"
655 << describe(pfunc,verbLevel);
657 const int dbl_p = 15;
659 *out << std::setprecision(dbl_p);
667 switch(l_fd_method_type) {
668 case DFDCT::FD_ORDER_ONE:
672 case DFDCT::FD_ORDER_TWO:
676 case DFDCT::FD_ORDER_TWO_CENTRAL:
680 case DFDCT::FD_ORDER_FOUR:
684 case DFDCT::FD_ORDER_FOUR_CENTRAL:
691 for(
int eval_i = 1; eval_i <= num_evals; ++eval_i ) {
696 switch(l_fd_method_type) {
697 case DFDCT::FD_ORDER_ONE: {
710 case DFDCT::FD_ORDER_TWO: {
727 case DFDCT::FD_ORDER_TWO_CENTRAL: {
740 case DFDCT::FD_ORDER_FOUR: {
765 case DFDCT::FD_ORDER_FOUR_CENTRAL: {
786 case DFDCT::FD_ORDER_TWO_AUTO:
787 case DFDCT::FD_ORDER_FOUR_AUTO:
793 if(out.
get() && trace)
794 *out <<
"\neval_i="<<eval_i<<
", uh_i="<<uh_i<<
", wgt_i="<<wgt_i<<
"\n";
798 if(uh_i == ST::zero()) {
799 MEB::OutArgs<Scalar> bfuncall;
800 if(!all_funcs_at_base_computed) {
803 if( pfunc.supports(MEB::OUT_ARG_f) && pfunc.get_f().get() && !bfunc.
get_f().get() ) {
806 for(
int j = 0; j < Ng; ++j ) {
807 if( pfunc.get_g(j).get() && !bfunc.
get_g(j).get() ) {
808 bfuncall.set_g(j,createMember(model.
get_g_space(j)));
812 bfuncall.setArgs(bfunc);
818 if(out.
get() && trace)
819 *out <<
"\nSetting variations = wgt_i * basePoint ...\n";
821 if( pfunc.supports(MEB::OUT_ARG_f) && (f=var.
get_f()).get() ) {
822 V_StV<Scalar>(f.ptr(), wgt_i, *bfuncall.get_f());
824 for(
int j = 0; j < Ng; ++j ) {
826 if( (g_j=var.
get_g(j)).get() ) {
827 V_StV<Scalar>(g_j.ptr(), wgt_i, *bfuncall.get_g(j));
832 if(out.
get() && trace)
833 *out <<
"\nSetting perturbedPoint = basePoint + uh_i*uh*direction ...\n";
837 V_StVpV(per_x.ptr(),as<Scalar>(uh_i*uh),*dir.
get_x(),*bp.
get_x());
842 for (
int l = 0; l < Np; ++l ) {
843 if( dir.
get_p(l).get() )
844 V_StVpV(per_p[l].ptr(), as<Scalar>(uh_i*uh), *dir.
get_p(l), *bp.
get_p(l));
847 if(out.
get() && trace)
848 *out <<
"\nperturbedPoint=\n" << describe(pp,verbLevel);
850 if(out.
get() && trace)
851 *out <<
"\nCompute perturbedFunctions at perturbedPoint...\n";
853 if(out.
get() && trace)
854 *out <<
"\nperturbedFunctions=\n" << describe(pfunc,verbLevel);
858 if(out.
get() && trace)
859 *out <<
"\nComputing variations += wgt_i*perturbedfunctions ...\n";
861 if( pfunc.supports(MEB::OUT_ARG_f) && (f=pfunc.get_f()).get() )
862 Vp_StV<Scalar>(var.
get_f().ptr(), wgt_i, *f);
863 for(
int j = 0; j < Ng; ++j ) {
865 if( (g_j=pfunc.get_g(j)).get() )
866 Vp_StV<Scalar>(var.
get_g(j).ptr(), wgt_i, *g_j);
870 if(out.
get() && trace)
871 *out <<
"\nvariations=\n" << describe(var,verbLevel);
880 const Scalar alpha = ST::one()/(dwgt*uh);
881 if(out.
get() && trace)
883 <<
"\nComputing variations *= (1.0)/(dwgt*uh),"
884 <<
" where (1.0)/(dwgt*uh) = (1.0)/("<<dwgt<<
"*"<<uh<<
") = "<<alpha<<
" ...\n";
888 for(
int j = 0; j < Ng; ++j ) {
890 if( (g_j=var.
get_g(j)).get() )
891 Vt_S(g_j.ptr(),alpha);
893 if(out.
get() && trace)
894 *out <<
"\nFinal variations=\n" << describe(var,verbLevel);
898 *out << std::setprecision(p_saved);
900 if(out.
get() && trace)
901 *out <<
"\nLeaving DirectionalFiniteDiffCalculator<Scalar>::calcVariations(...)\n";
906 template<
class Scalar>
918 THYRA_FUNC_TIME_MONITOR(
919 string(
"Thyra::DirectionalFiniteDiffCalculator<")+ST::name()+
">::calcDerivatives(...)"
931 if(out.
get() && trace)
932 *out <<
"\nEntering DirectionalFiniteDiffCalculator<Scalar>::calcDerivatives(...)\n";
934 if(out.
get() && trace)
936 <<
"\nbasePoint=\n" << describe(bp,verbLevel)
937 <<
"\nbaseFunctionValues=\n" << describe(bfunc,verbLevel)
943 const int Np = bp.
Np(), Ng = bfunc.
Ng();
946 MultiVectorPtr DfDp_l;
947 std::vector<MEB::DerivativeMultiVector<Scalar> > DgDp_l(Ng);
948 std::vector<VectorPtr> var_g(Ng);
949 for(
int l = 0; l < Np; ++l ) {
950 if(out.
get() && trace)
951 *out <<
"\nComputing derivatives for parameter subvector p("<<l<<
") ...\n";
956 bool hasDerivObject =
false;
959 !deriv.
supports(MEB::OUT_ARG_DfDp,l).none()
963 hasDerivObject =
true;
964 std::ostringstream name; name <<
"DfDp("<<l<<
")";
965 DfDp_l = get_mv(deriv.
get_DfDp(l),name.str(),MEB::DERIV_MV_BY_COL);
968 DfDp_l = Teuchos::null;
971 for (
int j = 0; j < Ng; ++j ) {
973 !deriv.
supports(MEB::OUT_ARG_DgDp,j,l).none()
978 hasDerivObject =
true;
979 std::ostringstream name; name <<
"DgDp("<<j<<
","<<l<<
")";
980 DgDp_l[j] = get_dmv(deriv.
get_DgDp(j,l),name.str());
981 if( DgDp_l[j].getMultiVector().get() && !var_g[j].get() )
988 DgDp_l[j] = MEB::DerivativeMultiVector<Scalar>();
989 var_g[j] = Teuchos::null;
995 if (hasDerivObject) {
996 VectorPtr e_i = createMember(model.
get_p_space(l));
998 assign(e_i.ptr(),ST::zero());
999 const int np_l = e_i->space()->dim();
1000 for(
int i = 0 ; i < np_l; ++ i ) {
1001 if(out.
get() && trace)
1002 *out <<
"\nComputing derivatives for single variable p("<<l<<
")("<<i<<
") ...\n";
1004 if(DfDp_l.get()) var.set_f(DfDp_l->col(i));
1005 for(
int j = 0; j < Ng; ++j) {
1006 MultiVectorPtr DgDp_j_l;
1007 if( (DgDp_j_l=DgDp_l[j].getMultiVector()).get() ) {
1008 var.set_g(j,var_g[j]);
1011 set_ele(i,ST::one(),e_i.ptr());
1012 this->calcVariations(
1013 model,bp,dir,bfunc,var
1015 set_ele(i,ST::zero(),e_i.ptr());
1016 if (DfDp_l.get()) var.set_f(Teuchos::null);
1017 for (
int j = 0; j < Ng; ++j) {
1018 MultiVectorPtr DgDp_j_l;
1019 if ( !
is_null(DgDp_j_l=DgDp_l[j].getMultiVector()) ) {
1020 assign( DgDp_j_l->col(i).ptr(), *var_g[j] );
1024 dir.set_p(l,Teuchos::null);
1028 if(out.
get() && trace)
1030 <<
"\nderivatives=\n" << describe(deriv,verbLevel);
1032 if(out.
get() && trace)
1033 *out <<
"\nLeaving DirectionalFiniteDiffCalculator<Scalar>::calcDerivatives(...)\n";
1041 #endif // THYRA_DIRECTIONAL_FINITE_DIFF_CALCULATOR_DEF_HPP