void main () { real_t minin(real_t *, real_t *, real_t *, real_t (*)(real_t), real_t (*)(real_t)); real_t m,x,a,b; a=1.0+tol(1.0); b=4.0-tol(4.0); m=minin(&x,&a,&b,f,tol); printf("Minimum is %e\nFor x is %e\nin the interval with " "endpoints %e %e",m,x,a,b); }
int main() { hm.init(); un.init(); while(scanf("%s %s", a, b)!=EOF) { n++; int ax=hm.get(tol(a)), bx=hm.get(tol(b)); un.set(ax, bx); cnt[ax]++, cnt[bx]++; } int t=0; for(int i=0; i<hm.size(); i++) if(cnt[i]%2) t++; puts(n==0 || (un.size(0)==hm.size() && (t==0 || t==2)) ? "Possible" : "Impossible"); return 0; }
// [[Rcpp::depends(BH)]] // [[Rcpp::depends(RcppArmadillo)]] arma::mat intervals(arma::mat& means, const arma::mat& sds, const arma::vec& probs, unsigned int n_ahead) { boost::math::tools::eps_tolerance<double> tol; arma::mat intv(n_ahead, probs.n_elem); for (unsigned int i = 0; i < n_ahead; i++) { double lower = means.col(i).min() - 2 * sds.col(i).max(); double upper = means.col(i).max() + 2 * sds.col(i).max(); for (unsigned int j = 0; j < probs.n_elem; j++) { boost::uintmax_t max_iter = 1000; objective_gaussian f(means.col(i), sds.col(i), probs(j)); std::pair<double, double> r = boost::math::tools::bisect(f, lower, upper, tol, max_iter); if (!tol(r.first, r.second) || (max_iter >= 1000)) { max_iter = 10000; r = boost::math::tools::bisect(f, 1000 * lower, 1000 * upper, tol, max_iter); } intv(i, j) = r.first + (r.second - r.first) / 2.0; lower = intv(i, j); } } return intv; }
void Multigrid::solve() { smooth(); computeResidual(); while (error() > tol() & n < maxIter()) iterate(); if (n == maxIter()) cout << "Multigrid reached maximum number of iterations" << endl; }
float MgArc::getSweepAngle() const { if (!mgIsZero(_sweepAngle)) { return _sweepAngle; } const float midAngle = (getMidPoint() - getCenter()).angle2(); const float startAngle = getStartAngle(); const float endAngle = getEndAngle(); if (mgEquals(midAngle, startAngle) && mgEquals(startAngle, endAngle)) { return endAngle - startAngle; } Tol tol(getRadius() * 1e-3f, 1e-4f); if (getStartPoint().isEqualTo(getEndPoint(), tol) && (getMidPoint() + (getStartPoint() + getEndPoint()) / 2).isEqualTo(2 * getCenter(), tol)) { return _M_2PI; } float startAngle2 = startAngle; float midAngle2 = midAngle; float endAngle2 = endAngle; // 先尝试看是否为逆时针方向:endAngle2 > midAngle2 > startAngle2 >= 0 if (startAngle2 < 0) startAngle2 += _M_2PI; while (midAngle2 < startAngle2) midAngle2 += _M_2PI; while (endAngle2 < midAngle2) endAngle2 += _M_2PI; if (fabsf(startAngle2 + endAngle2 - 2 * midAngle2) < _M_PI_6 && endAngle2 - startAngle2 < _M_2PI) { return endAngle2 - startAngle2; } // 再尝试看是否为顺时针方向:endAngle2 < midAngle2 < startAngle2 <= 0 startAngle2 = startAngle; midAngle2 = midAngle; endAngle2 = endAngle; if (startAngle2 > 0) startAngle2 -= _M_2PI; while (midAngle2 > startAngle2) midAngle2 -= _M_2PI; while (endAngle2 > midAngle2) endAngle2 -= _M_2PI; if (fabsf(startAngle2 + endAngle2 - 2 * midAngle2) < _M_PI_6) { if (endAngle2 - startAngle2 > -_M_2PI) return endAngle2 - startAngle2; return mgbase::toRange(endAngle2 - startAngle2, -_M_2PI, 0); } return endAngle - startAngle; // error }
Foam::dictionary Foam::ICCG::solverDict ( Istream& is ) { scalar tol(readScalar(is)); scalar relTol(readScalar(is)); return solverDict(tol, relTol); }
double invvfun_bisect(int family, const double theta0, const double theta1, const double theta2, double U, double V, unsigned int n) { typedef boost::math::policies::policy<> pol; int digits = std::numeric_limits<double>::digits; boost::math::tools::eps_tolerance<double> tol(digits); double min = 1e-10; double max = 1-1e-10; return boost::math::tools::bisect(invvfun_bi3<double, pol>(family,theta0,theta1,theta2,U,V), min, max, tol).first; }
static btScalar btShortestAngleUpdate(btScalar accAngle, btScalar curAngle) { btScalar tol(0.3); btScalar result = btShortestAngularDistance(accAngle, curAngle); if (btFabs(result) > tol) return curAngle; else return accAngle + result; return curAngle; }
void length_test() { data_type eps(std::numeric_limits<data__>::epsilon()); typedef eli::geom::curve::bezier<data__, 2> bezier_curve_type; control_point_type cntrl_in[5]; typename bezier_curve_type::control_point_type bez_cntrl[5]; curve_type ebc; bezier_curve_type bc; typename curve_type::point_type eval_out, eval_ref; typename curve_type::data_type length_cal, length_ref; // set control points and create curves cntrl_in[0] << 2.0; cntrl_in[1] << 1.5; cntrl_in[2] << 0.0; cntrl_in[3] << 1.0; cntrl_in[4] << 0.5; bez_cntrl[0] << 0, 2; bez_cntrl[1] << 0.25, 1.5; bez_cntrl[2] << 0.5, 0; bez_cntrl[3] << 0.75, 1; bez_cntrl[4] << 1, 0.5; ebc.resize(4); bc.resize(4); for (index_type i=0; i<5; ++i) { ebc.set_control_point(cntrl_in[i], i); bc.set_control_point(bez_cntrl[i], i); } // calculate the length of curve data_type tol(std::sqrt(eps)); eli::geom::curve::length(length_cal, ebc, tol); eli::geom::curve::length(length_ref, bc, tol); TEST_ASSERT(length_cal==length_ref); // test computing some segment length typename curve_type::data_type t0, t1; t0 = static_cast<data__>(0.2); t1 = static_cast<data__>(0.7); eli::geom::curve::length(length_cal, ebc, t0, t1, tol); eli::geom::curve::length(length_ref, bc, t0, t1, tol); TEST_ASSERT(length_cal==length_ref); }
void compile_and_link_test() { typedef double (*F)(double); typedef std::pair<double, double> (*F2)(double); typedef std::tr1::tuple<double, double, double> (*F3)(double); typedef boost::math::tools::eps_tolerance<double> Tol; Tol tol(u); boost::uintmax_t max_iter = 0; F f = 0; F2 f2 = 0; F3 f3 = 0; check_result<std::pair<double, double> >(boost::math::tools::bisect<F, double, Tol>(f, d, d, tol, max_iter)); check_result<std::pair<double, double> >(boost::math::tools::bisect<F, double, Tol>(f, d, d, tol)); check_result<double>(boost::math::tools::newton_raphson_iterate<F2, double>(f2, d, d, d, i, max_iter)); check_result<double>(boost::math::tools::halley_iterate<F3, double>(f3, d, d, d, i, max_iter)); check_result<double>(boost::math::tools::schroeder_iterate<F3, double>(f3, d, d, d, i, max_iter)); }
typename Dist::value_type generic_quantile(const Dist& dist, const typename Dist::value_type& p, const typename Dist::value_type& guess, bool comp, const char* function) { typedef typename Dist::value_type value_type; typedef typename Dist::policy_type policy_type; typedef typename policies::normalise< policy_type, policies::promote_float<false>, policies::promote_double<false>, policies::discrete_quantile<>, policies::assert_undefined<> >::type forwarding_policy; // // Special cases first: // if(p == 0) { return comp ? check_range_result(range(dist).second, forwarding_policy(), function) : check_range_result(range(dist).first, forwarding_policy(), function); } if(p == 1) { return !comp ? check_range_result(range(dist).second, forwarding_policy(), function) : check_range_result(range(dist).first, forwarding_policy(), function); } generic_quantile_finder<Dist> f(dist, p, comp); tools::eps_tolerance<value_type> tol(policies::digits<value_type, forwarding_policy>() - 3); boost::uintmax_t max_iter = policies::get_max_root_iterations<forwarding_policy>(); std::pair<value_type, value_type> ir = tools::bracket_and_solve_root( f, guess, value_type(2), true, tol, max_iter, forwarding_policy()); value_type result = ir.first + (ir.second - ir.first) / 2; if(max_iter >= policies::get_max_root_iterations<forwarding_policy>()) { policies::raise_evaluation_error<value_type>(function, "Unable to locate solution in a reasonable time:" " either there is no answer to quantile" " or the answer is infinite. Current best guess is %1%", result, forwarding_policy()); } return result; }
bool MgCommandDraw::touchEndedStep(const MgMotion* sender) { Point2d pnt(snapPoint(sender)); Tol tol(sender->displayMmToModel(2.f)); setStepPoint(m_step, pnt); dynshape()->shape()->update(); if (!pnt.isEqualTo(dynshape()->shape()->getPoint(m_step - 1), tol)) { m_step++; if (m_step >= getMaxStep()) { if (!dynshape()->shape()->getExtent().isEmpty(tol, false)) { addShape(sender); delayClear(); } m_step = 0; } } return MgCommandDraw::touchEnded(sender); }
bool MgCmdDrawSplines::touchEnded(const MgMotion* sender) { MgSplines* lines = (MgSplines*)dynshape()->shape(); if (m_freehand) { Tol tol(sender->displayMmToModel(1.f)); if (m_step > 0 && !dynshape()->shape()->getExtent().isEmpty(tol, false)) { MgShape* newsp = addShape(sender); if (newsp) {/* m_step = 0; sender->view->regenAppend(0); newsp = newsp->cloneShape(); lines = (MgSplines*)newsp->shape(); lines->smooth(sender->view->xform()->modelToDisplay(), sender->view->xform()->getWorldToDisplayY() * 0.5f); sender->view->shapes()->updateShape(newsp); sender->view->regenAppend(newsp->getID())*/ } } else { click(sender); // add a point } m_step = 0; } else { float dist = lines->endPoint().distanceTo(dynshape()->shape()->getPoint(0)); while (m_step > 1 && dist < sender->displayMmToModel(1.f)) { lines->setClosed(true); lines->removePoint(m_step--); dist = lines->endPoint().distanceTo(dynshape()->shape()->getPoint(0)); } if (m_step > 1 && lines->isClosed()) { addShape(sender); m_step = 0; } } return MgCommandDraw::touchEnded(sender); }
T ibeta_inv_ab_imp(const T& b, const T& z, const T& p, const T& q, bool swap_ab, const Policy& pol) { BOOST_MATH_STD_USING // for ADL of std lib math functions // // Special cases first: // BOOST_MATH_INSTRUMENT_CODE("b = " << b << " z = " << z << " p = " << p << " q = " << " swap = " << swap_ab); if(p == 0) { return swap_ab ? tools::min_value<T>() : tools::max_value<T>(); } if(q == 0) { return swap_ab ? tools::max_value<T>() : tools::min_value<T>(); } // // Function object, this is the functor whose root // we have to solve: // beta_inv_ab_t<T, Policy> f(b, z, (p < q) ? p : q, (p < q) ? false : true, swap_ab); // // Tolerance: full precision. // tools::eps_tolerance<T> tol(policies::digits<T, Policy>()); // // Now figure out a starting guess for what a may be, // we'll start out with a value that'll put p or q // right bang in the middle of their range, the functions // are quite sensitive so we should need too many steps // to bracket the root from there: // T guess = 0; T factor = 5; // // Convert variables to parameters of a negative binomial distribution: // T n = b; T sf = swap_ab ? z : 1-z; T sfc = swap_ab ? 1-z : z; T u = swap_ab ? p : q; T v = swap_ab ? q : p; if(u <= pow(sf, n)) { // // Result is less than 1, negative binomial approximation // is useless.... // if((p < q) != swap_ab) { guess = (std::min)(T(b * 2), T(1)); } else { guess = (std::min)(T(b / 2), T(1)); } } if(n * n * n * u * sf > 0.005) guess = 1 + inverse_negative_binomial_cornish_fisher(n, sf, sfc, u, v, pol); if(guess < 10) { // // Negative binomial approximation not accurate in this area: // if((p < q) != swap_ab) { guess = (std::min)(T(b * 2), T(10)); } else { guess = (std::min)(T(b / 2), T(10)); } } else factor = (v < sqrt(tools::epsilon<T>())) ? 2 : (guess < 20 ? 1.2f : 1.1f); BOOST_MATH_INSTRUMENT_CODE("guess = " << guess); // // Max iterations permitted: // boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>(); std::pair<T, T> r = bracket_and_solve_root(f, guess, factor, swap_ab ? true : false, tol, max_iter, pol); if(max_iter >= policies::get_max_root_iterations<Policy>()) return policies::raise_evaluation_error<T>("boost::math::ibeta_invab_imp<%1%>(%1%,%1%,%1%)", "Unable to locate the root within a reasonable number of iterations, closest approximation so far was %1%", r.first, pol); return (r.first + r.second) / 2; }
int main(int argc, char *argv[]) { // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided. int iprint = argc - 1; Teuchos::RCP<std::ostream> outStream; Teuchos::oblackholestream bhs; // outputs nothing /*** Initialize communicator. ***/ Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs); Teuchos::RCP<const Teuchos::Comm<int> > comm = Tpetra::DefaultPlatform::getDefaultPlatform().getComm(); const int myRank = comm->getRank(); if ((iprint > 0) && (myRank == 0)) { outStream = Teuchos::rcp(&std::cout, false); } else { outStream = Teuchos::rcp(&bhs, false); } int errorFlag = 0; // *** Example body. try { RealT tol(1e-8), one(1); /*** Read in XML input ***/ std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() ); // Retrieve parameters. const RealT domainWidth = parlist->sublist("Geometry").get("Width", 1.0); const RealT domainHeight = parlist->sublist("Geometry").get("Height", 1.0); const RealT volFraction = parlist->sublist("Problem").get("Volume Fraction", 0.4); const RealT objFactor = parlist->sublist("Problem").get("Objective Scaling", 1e-4); /*** Initialize main data structure. ***/ Teuchos::RCP<MeshManager<RealT> > meshMgr = Teuchos::rcp(new MeshManager_TopoOpt<RealT>(*parlist)); // Initialize PDE describing elasticity equations. Teuchos::RCP<PDE_TopoOpt<RealT> > pde = Teuchos::rcp(new PDE_TopoOpt<RealT>(*parlist)); Teuchos::RCP<ROL::EqualityConstraint_SimOpt<RealT> > con = Teuchos::rcp(new PDE_Constraint<RealT>(pde,meshMgr,comm,*parlist,*outStream)); // Initialize the filter PDE. Teuchos::RCP<PDE_Filter<RealT> > pdeFilter = Teuchos::rcp(new PDE_Filter<RealT>(*parlist)); Teuchos::RCP<ROL::EqualityConstraint_SimOpt<RealT> > conFilter = Teuchos::rcp(new Linear_PDE_Constraint<RealT>(pdeFilter,meshMgr,comm,*parlist,*outStream)); // Cast the constraint and get the assembler. Teuchos::RCP<PDE_Constraint<RealT> > pdecon = Teuchos::rcp_dynamic_cast<PDE_Constraint<RealT> >(con); Teuchos::RCP<Assembler<RealT> > assembler = pdecon->getAssembler(); con->setSolveParameters(*parlist); // Create state vector. Teuchos::RCP<Tpetra::MultiVector<> > u_rcp = assembler->createStateVector(); u_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(u_rcp,pde,assembler,*parlist)); Teuchos::RCP<Tpetra::MultiVector<> > p_rcp = assembler->createStateVector(); p_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(p_rcp,pde,assembler,*parlist)); // Create control vector. Teuchos::RCP<Tpetra::MultiVector<> > z_rcp = assembler->createControlVector(); //z_rcp->randomize(); z_rcp->putScalar(volFraction); //z_rcp->putScalar(0); Teuchos::RCP<ROL::Vector<RealT> > zp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(z_rcp,pde,assembler,*parlist)); // Create residual vector. Teuchos::RCP<Tpetra::MultiVector<> > r_rcp = assembler->createResidualVector(); r_rcp->putScalar(0.0); Teuchos::RCP<ROL::Vector<RealT> > rp = Teuchos::rcp(new PDE_DualSimVector<RealT>(r_rcp,pde,assembler,*parlist)); // Create state direction vector. Teuchos::RCP<Tpetra::MultiVector<> > du_rcp = assembler->createStateVector(); du_rcp->randomize(); //du_rcp->putScalar(0); Teuchos::RCP<ROL::Vector<RealT> > dup = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(du_rcp,pde,assembler,*parlist)); // Create control direction vector. Teuchos::RCP<Tpetra::MultiVector<> > dz_rcp = assembler->createControlVector(); dz_rcp->randomize(); dz_rcp->scale(0.01); Teuchos::RCP<ROL::Vector<RealT> > dzp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(dz_rcp,pde,assembler,*parlist)); // Create control test vector. Teuchos::RCP<Tpetra::MultiVector<> > rz_rcp = assembler->createControlVector(); rz_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > rzp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(rz_rcp,pde,assembler,*parlist)); Teuchos::RCP<Tpetra::MultiVector<> > dualu_rcp = assembler->createStateVector(); Teuchos::RCP<ROL::Vector<RealT> > dualup = Teuchos::rcp(new PDE_DualSimVector<RealT>(dualu_rcp,pde,assembler,*parlist)); Teuchos::RCP<Tpetra::MultiVector<> > dualz_rcp = assembler->createControlVector(); Teuchos::RCP<ROL::Vector<RealT> > dualzp = Teuchos::rcp(new PDE_DualOptVector<RealT>(dualz_rcp,pde,assembler,*parlist)); // Create ROL SimOpt vectors. ROL::Vector_SimOpt<RealT> x(up,zp); ROL::Vector_SimOpt<RealT> d(dup,dzp); // Initialize "filtered" of "unfiltered" constraint. Teuchos::RCP<ROL::EqualityConstraint_SimOpt<RealT> > pdeWithFilter; bool useFilter = parlist->sublist("Problem").get("Use Filter", true); if (useFilter) { pdeWithFilter = Teuchos::rcp(new ROL::CompositeEqualityConstraint_SimOpt<RealT>(con, conFilter, *rp, *rp, *up, *zp, *zp)); } else { pdeWithFilter = con; } pdeWithFilter->setSolveParameters(*parlist); // Initialize compliance objective function. Teuchos::ParameterList list(*parlist); list.sublist("Vector").sublist("Sim").set("Use Riesz Map",true); list.sublist("Vector").sublist("Sim").set("Lump Riesz Map",false); // Has state Riesz map enabled for mesh-independent compliance scaling. Teuchos::RCP<Tpetra::MultiVector<> > f_rcp = assembler->createResidualVector(); f_rcp->putScalar(0.0); Teuchos::RCP<ROL::Vector<RealT> > fp = Teuchos::rcp(new PDE_DualSimVector<RealT>(f_rcp,pde,assembler,list)); up->zero(); con->value(*fp, *up, *zp, tol); RealT objScaling = objFactor, fnorm2 = fp->dot(*fp); if (fnorm2 > 1e2*ROL::ROL_EPSILON<RealT>()) { objScaling /= fnorm2; } u_rcp->randomize(); std::vector<Teuchos::RCP<QoI<RealT> > > qoi_vec(1,Teuchos::null); qoi_vec[0] = Teuchos::rcp(new QoI_TopoOpt<RealT>(pde->getFE(), pde->getLoad(), pde->getFieldHelper(), objScaling)); Teuchos::RCP<ROL::Objective_SimOpt<RealT> > obj = Teuchos::rcp(new PDE_Objective<RealT>(qoi_vec,assembler)); // Initialize volume constraint, Teuchos::RCP<QoI<RealT> > qoi_vol = Teuchos::rcp(new QoI_Volume_TopoOpt<RealT>(pde->getFE(),pde->getFieldHelper(),*parlist)); Teuchos::RCP<IntegralOptConstraint<RealT> > vcon = Teuchos::rcp(new IntegralOptConstraint<RealT>(qoi_vol,assembler)); // Create volume constraint vector and set to zero RealT vecScaling = one / std::pow(domainWidth*domainHeight*(one-volFraction), 2); Teuchos::RCP<std::vector<RealT> > scalevec_rcp = Teuchos::rcp(new std::vector<RealT>(1,vecScaling)); Teuchos::RCP<std::vector<RealT> > c1_rcp = Teuchos::rcp(new std::vector<RealT>(1,0)); Teuchos::RCP<ROL::Vector<RealT> > c1p = Teuchos::rcp(new ROL::PrimalScaledStdVector<RealT>(c1_rcp, scalevec_rcp)); Teuchos::RCP<std::vector<RealT> > c2_rcp = Teuchos::rcp(new std::vector<RealT>(1,1)); Teuchos::RCP<ROL::Vector<RealT> > c2p = Teuchos::rcp(new ROL::DualScaledStdVector<RealT>(c2_rcp, scalevec_rcp)); // Initialize bound constraints. Teuchos::RCP<Tpetra::MultiVector<> > lo_rcp = assembler->createControlVector(); Teuchos::RCP<Tpetra::MultiVector<> > hi_rcp = assembler->createControlVector(); lo_rcp->putScalar(0.0); hi_rcp->putScalar(1.0); Teuchos::RCP<ROL::Vector<RealT> > lop = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(lo_rcp,pde,assembler)); Teuchos::RCP<ROL::Vector<RealT> > hip = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(hi_rcp,pde,assembler)); Teuchos::RCP<ROL::BoundConstraint<RealT> > bnd = Teuchos::rcp(new ROL::BoundConstraint<RealT>(lop,hip)); // Initialize Augmented Lagrangian functional. bool storage = parlist->sublist("Problem").get("Use state storage",true); Teuchos::RCP<ROL::SimController<RealT> > stateStore = Teuchos::rcp(new ROL::SimController<RealT>()); Teuchos::RCP<ROL::Reduced_Objective_SimOpt<RealT> > objRed = Teuchos::rcp(new ROL::Reduced_Objective_SimOpt<RealT>(obj,pdeWithFilter, stateStore,up,zp,pp, storage)); ROL::AugmentedLagrangian<RealT> augLag(objRed,vcon,*c2p,1, *zp,*c1p,*parlist); // Run derivative checks bool checkDeriv = parlist->sublist("Problem").get("Check derivatives",false); if ( checkDeriv ) { *outStream << "\n\nCheck Opt Vector\n"; zp->checkVector(*dzp,*rzp,true,*outStream); *outStream << "\n\nCheck Gradient of Full Objective Function\n"; obj->checkGradient(x,d,true,*outStream); *outStream << "\n\nCheck Hessian of Full Objective Function\n"; obj->checkHessVec(x,d,true,*outStream); *outStream << "\n\nCheck Full Jacobian of PDE Constraint\n"; con->checkApplyJacobian(x,d,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_1 of PDE Constraint\n"; con->checkApplyJacobian_1(*up,*zp,*dup,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_2 of PDE Constraint\n"; con->checkApplyJacobian_2(*up,*zp,*dzp,*rp,true,*outStream); *outStream << "\n\nCheck Full Hessian of PDE Constraint\n"; con->checkApplyAdjointHessian(x,*pp,d,x,true,*outStream); *outStream << "\n\nCheck Hessian_11 of PDE Constraint\n"; con->checkApplyAdjointHessian_11(*up,*zp,*pp,*dup,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_21 of PDE Constraint\n"; con->checkApplyAdjointHessian_21(*up,*zp,*pp,*dzp,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_12 of PDE Constraint\n"; con->checkApplyAdjointHessian_12(*up,*zp,*pp,*dup,*dualzp,true,*outStream); *outStream << "\n\nCheck Hessian_22 of PDE Constraint\n"; con->checkApplyAdjointHessian_22(*up,*zp,*pp,*dzp,*dualzp,true,*outStream); *outStream << "\n"; con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); *outStream << "\n"; con->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n"; con->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n\nCheck Full Jacobian of Filter\n"; conFilter->checkApplyJacobian(x,d,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_1 of Filter\n"; conFilter->checkApplyJacobian_1(*up,*zp,*dup,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_2 of Filter\n"; conFilter->checkApplyJacobian_2(*up,*zp,*dzp,*rp,true,*outStream); *outStream << "\n\nCheck Full Hessian of Filter\n"; conFilter->checkApplyAdjointHessian(x,*pp,d,x,true,*outStream); *outStream << "\n\nCheck Hessian_11 of Filter\n"; conFilter->checkApplyAdjointHessian_11(*up,*zp,*pp,*dup,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_21 of Filter\n"; conFilter->checkApplyAdjointHessian_21(*up,*zp,*pp,*dzp,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_12 of Filter\n"; conFilter->checkApplyAdjointHessian_12(*up,*zp,*pp,*dup,*dualzp,true,*outStream); *outStream << "\n\nCheck Hessian_22 of Filter\n"; conFilter->checkApplyAdjointHessian_22(*up,*zp,*pp,*dzp,*dualzp,true,*outStream); *outStream << "\n"; conFilter->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); *outStream << "\n"; conFilter->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n"; conFilter->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n\nCheck Full Jacobian of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyJacobian(x,d,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_1 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyJacobian_1(*up,*zp,*dup,*rp,true,*outStream); *outStream << "\n\nCheck Jacobian_2 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyJacobian_2(*up,*zp,*dzp,*rp,true,*outStream); *outStream << "\n\nCheck Full Hessian of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyAdjointHessian(x,*pp,d,x,true,*outStream); *outStream << "\n\nCheck Hessian_11 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyAdjointHessian_11(*up,*zp,*pp,*dup,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_21 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyAdjointHessian_21(*up,*zp,*pp,*dzp,*dualup,true,*outStream); *outStream << "\n\nCheck Hessian_12 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyAdjointHessian_12(*up,*zp,*pp,*dup,*dualzp,true,*outStream); *outStream << "\n\nCheck Hessian_22 of Filtered PDE Constraint\n"; pdeWithFilter->checkApplyAdjointHessian_22(*up,*zp,*pp,*dzp,*dualzp,true,*outStream); *outStream << "\n"; pdeWithFilter->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); *outStream << "\n"; pdeWithFilter->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n"; pdeWithFilter->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); *outStream << "\n\nCheck Gradient of Reduced Objective Function\n"; objRed->checkGradient(*zp,*dzp,true,*outStream); *outStream << "\n\nCheck Hessian of Reduced Objective Function\n"; objRed->checkHessVec(*zp,*dzp,true,*outStream); *outStream << "\n\nCheck Full Jacobian of Volume Constraint\n"; vcon->checkApplyJacobian(*zp,*dzp,*c1p,true,*outStream); *outStream << "\n"; vcon->checkAdjointConsistencyJacobian(*c1p,*dzp,*zp,true,*outStream); *outStream << "\n\nCheck Full Hessian of Volume Constraint\n"; vcon->checkApplyAdjointHessian(*zp,*c2p,*dzp,*zp,true,*outStream); *outStream << "\n\nCheck Gradient of Augmented Lagrangian Function\n"; augLag.checkGradient(*zp,*dzp,true,*outStream); *outStream << "\n\nCheck Hessian of Augmented Lagrangian Function\n"; augLag.checkHessVec(*zp,*dzp,true,*outStream); *outStream << "\n"; } ROL::Algorithm<RealT> algo("Augmented Lagrangian",*parlist,false); Teuchos::Time algoTimer("Algorithm Time", true); algo.run(*zp,*c2p,augLag,*vcon,*bnd,true,*outStream); algoTimer.stop(); *outStream << "Total optimization time = " << algoTimer.totalElapsedTime() << " seconds.\n"; // Output. pdecon->printMeshData(*outStream); con->solve(*rp,*up,*zp,tol); pdecon->outputTpetraVector(u_rcp,"state.txt"); pdecon->outputTpetraVector(z_rcp,"density.txt"); //Teuchos::Array<RealT> res(1,0); //con->value(*rp,*up,*zp,tol); //r_rcp->norm2(res.view(0,1)); //*outStream << "Residual Norm: " << res[0] << std::endl; //errorFlag += (res[0] > 1.e-6 ? 1 : 0); //pdecon->outputTpetraData(); // Get a summary from the time monitor. Teuchos::TimeMonitor::summarize(); } catch (std::logic_error err) { *outStream << err.what() << "\n"; errorFlag = -1000; }; // end try if (errorFlag != 0) std::cout << "End Result: TEST FAILED\n"; else std::cout << "End Result: TEST PASSED\n"; return 0; }
int main(int argc, char *argv[]) { // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided. int iprint = argc - 1; Teuchos::RCP<std::ostream> outStream; Teuchos::oblackholestream bhs; // outputs nothing /*** Initialize communicator. ***/ Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs); Teuchos::RCP<const Teuchos::Comm<int> > comm = Tpetra::DefaultPlatform::getDefaultPlatform().getComm(); const int myRank = comm->getRank(); if ((iprint > 0) && (myRank == 0)) { outStream = Teuchos::rcp(&std::cout, false); } else { outStream = Teuchos::rcp(&bhs, false); } int errorFlag = 0; // *** Example body. try { /*** Read in XML input ***/ std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() ); /*** Initialize main data structure. ***/ Teuchos::RCP<MeshManager<RealT> > meshMgr = Teuchos::rcp(new MeshManager_Stefan_Boltzmann<RealT>(*parlist)); std::cout << "Created mesh manager" << std::endl; // Initialize PDE describe Stefan Boltzmann's equation Teuchos::RCP<PDE_Stefan_Boltzmann<RealT> > pde = Teuchos::rcp(new PDE_Stefan_Boltzmann<RealT>(*parlist)); std::cout << "Created PDE" << std::endl; Teuchos::RCP<PDE_Constraint<RealT> > con = Teuchos::rcp(new PDE_Constraint<RealT>(pde,meshMgr,comm,*parlist,*outStream)); std::cout << "Created constraint" << std::endl; con->getAssembler()->printMeshData(*outStream); // Initialize quadratic objective function std::vector<Teuchos::RCP<QoI<RealT> > > qoi_vec(2,Teuchos::null); qoi_vec[0] = Teuchos::rcp(new QoI_L2Tracking_Stefan_Boltzmann<RealT>(pde->getFE_VOL())); qoi_vec[1] = Teuchos::rcp(new QoI_L2Penalty_Stefan_Boltzmann <RealT>(pde->getFE_VOL())); Teuchos::RCP<StdObjective_Stefan_Boltzmann<RealT> > std_obj = Teuchos::rcp(new StdObjective_Stefan_Boltzmann<RealT>(*parlist)); Teuchos::RCP<PDE_Objective<RealT> > obj = Teuchos::rcp(new PDE_Objective<RealT>(qoi_vec,std_obj,con->getAssembler())); // Create state vector and set to zeroes Teuchos::RCP<Tpetra::MultiVector<> > u_rcp = con->getAssembler()->createStateVector(); u_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(u_rcp,pde,con->getAssembler())); // Create control vector and set to ones Teuchos::RCP<Tpetra::MultiVector<> > z_rcp = con->getAssembler()->createControlVector(); z_rcp->putScalar(1.0); Teuchos::RCP<ROL::Vector<RealT> > zp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(z_rcp,pde,con->getAssembler())); // Create residual vector and set to zeros Teuchos::RCP<Tpetra::MultiVector<> > r_rcp = con->getAssembler()->createResidualVector(); r_rcp->putScalar(0.0); Teuchos::RCP<ROL::Vector<RealT> > rp = Teuchos::rcp(new PDE_DualSimVector<RealT>(r_rcp,pde,con->getAssembler())); // Create state direction vector and set to random Teuchos::RCP<Tpetra::MultiVector<> > du_rcp = con->getAssembler()->createStateVector(); du_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > dup = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(du_rcp,pde,con->getAssembler())); // Create control direction vector and set to random Teuchos::RCP<Tpetra::MultiVector<> > dz_rcp = con->getAssembler()->createControlVector(); dz_rcp->putScalar(0.0); //dz_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > dzp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(dz_rcp,pde,con->getAssembler())); // Create ROL SimOpt vectors ROL::Vector_SimOpt<RealT> x(up,zp); ROL::Vector_SimOpt<RealT> d(dup,dzp); // Run derivative checks obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); con->checkApplyJacobian(x,d,*up,true,*outStream); con->checkApplyAdjointHessian(x,*dup,d,x,true,*outStream); con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); con->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); con->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); ROL::Algorithm<RealT> algo("Composite Step",*parlist,false); algo.run(x,*rp,*obj,*con,true,*outStream); RealT tol(1.e-8); con->solve(*rp,*up,*zp,tol); con->getAssembler()->outputTpetraVector(u_rcp,"state.txt"); con->getAssembler()->outputTpetraVector(z_rcp,"control.txt"); Teuchos::Array<RealT> res(1,0); con->value(*rp,*up,*zp,tol); r_rcp->norm2(res.view(0,1)); *outStream << "Residual Norm: " << res[0] << std::endl; errorFlag += (res[0] > 1.e-6 ? 1 : 0); } catch (std::logic_error err) { *outStream << err.what() << "\n"; errorFlag = -1000; }; // end try if (errorFlag != 0) std::cout << "End Result: TEST FAILED\n"; else std::cout << "End Result: TEST PASSED\n"; return 0; }
void omxInvokeNLOPT(double *est, GradientOptimizerContext &goc) { goc.optName = "SLSQP"; goc.setupSimpleBounds(); goc.useGradient = true; FitContext *fc = goc.fc; int oldWanted = fc->wanted; fc->wanted = 0; omxState *globalState = fc->state; nlopt_opt opt = nlopt_create(NLOPT_LD_SLSQP, fc->numParam); goc.extraData = opt; //local_opt = nlopt_create(NLOPT_LD_SLSQP, n); // Subsidiary algorithm //nlopt_set_local_optimizer(opt, local_opt); nlopt_set_lower_bounds(opt, goc.solLB.data()); nlopt_set_upper_bounds(opt, goc.solUB.data()); int eq, ieq; globalState->countNonlinearConstraints(eq, ieq); if (fc->CI) { nlopt_set_xtol_rel(opt, 5e-3); std::vector<double> tol(fc->numParam, std::numeric_limits<double>::epsilon()); nlopt_set_xtol_abs(opt, tol.data()); } else { // The *2 is there to roughly equate accuracy with NPSOL. nlopt_set_ftol_rel(opt, goc.ControlTolerance * 2); nlopt_set_ftol_abs(opt, std::numeric_limits<double>::epsilon()); } nlopt_set_min_objective(opt, SLSQP::nloptObjectiveFunction, &goc); double feasibilityTolerance = Global->feasibilityTolerance; SLSQP::context ctx(goc); if (eq + ieq) { ctx.origeq = eq; if (ieq > 0){ goc.inequality.resize(ieq); std::vector<double> tol(ieq, feasibilityTolerance); nlopt_add_inequality_mconstraint(opt, ieq, SLSQP::nloptInequalityFunction, &goc, tol.data()); } if (eq > 0){ goc.equality.resize(eq); std::vector<double> tol(eq, feasibilityTolerance); nlopt_add_equality_mconstraint(opt, eq, SLSQP::nloptEqualityFunction, &ctx, tol.data()); } } int priorIterations = fc->iterations; int code = nlopt_optimize(opt, est, &fc->fit); if (ctx.eqredundent) { nlopt_remove_equality_constraints(opt); eq -= ctx.eqredundent; std::vector<double> tol(eq, feasibilityTolerance); nlopt_add_equality_mconstraint(opt, eq, SLSQP::nloptEqualityFunction, &ctx, tol.data()); code = nlopt_optimize(opt, est, &fc->fit); } if (goc.verbose >= 2) mxLog("nlopt_optimize returned %d", code); nlopt_destroy(opt); fc->wanted = oldWanted; if (code == NLOPT_INVALID_ARGS) { Rf_error("NLOPT invoked with invalid arguments"); } else if (code == NLOPT_OUT_OF_MEMORY) { Rf_error("NLOPT ran out of memory"); } else if (code == NLOPT_FORCED_STOP) { if (fc->iterations - priorIterations <= 1) { goc.informOut = INFORM_STARTING_VALUES_INFEASIBLE; } else { goc.informOut = INFORM_ITERATION_LIMIT; } } else if (code == NLOPT_ROUNDOFF_LIMITED) { if (fc->iterations - priorIterations <= 2) { Rf_error("%s: Failed due to singular matrix E or C in LSQ subproblem or " "rank-deficient equality constraint subproblem or " "positive directional derivative in line search", goc.optName); } else { goc.informOut = INFORM_NOT_AT_OPTIMUM; // is this correct? TODO } } else if (code < 0) { Rf_error("NLOPT fatal error %d", code); } else if (code == NLOPT_MAXEVAL_REACHED) { goc.informOut = INFORM_ITERATION_LIMIT; } else { goc.informOut = INFORM_CONVERGED_OPTIMUM; } }
void Orbit::integrate(PotentialField& potentialField, ElectricField& electricField, Field<int>& faceTypeField, CodeField& vertexTypeField, ShortestEdgeField shortestEdgeField, FILE *outFile, double orbitLabelValue) { // TODO: need some clever way to set tMax and/or detect trapped orbits // double dt=min(0.005,0.005/initialVelocity.norm()), tMax=100; // double dt=min(0.01,0.01/initialVelocity.norm()), tMax=100; double dt=min(0.02,0.02/initialVelocity.norm()), tMax=100; // vect3d currentPosition = initialPosition; // TODO: should be consistent about starting position vect3d currentPosition = initialPosition + (initialVelocity+extern_VEXB)*SMALL_TIME; vect3d currentVelocity = initialVelocity; // TODO: shouldn't hard-code quasi-neutral operation double phiSurface = -4; vertexType = vertexTypeField.getField(initialNode); vect3d vertexNormalVector; vect3d initialNormalVelocity; if (vertexType==4 && charge<0.) { vertexNormalVector = mesh_ptr->getVertexNormalVector(initialNode, faceTypeField); vect3d coords = mesh_ptr->getCoordinates(initialNode); initialNormalVelocity = currentVelocity.dot(vertexNormalVector)*vertexNormalVector; // TODO: could do something like below to get distribution at surface // currentVelocity += sqrt(2.*charge*phiSurface)*vertexNormalVector; } // initialEnergy = 0.5*pow(initialVelocity.norm(),2.) // + charge*potentialField.getField(initialNode); // Don't integrate orbit if doesn't have enough energy to escape potential // TODO: this should be refined // if (0.5*pow(initialVelocity.norm(),2.)+0.22 < // if ((0.5*pow(initialVelocity.norm(),2.) + // if ((0.5*pow(initialVelocity[2],2.) + // charge*potentialField.getField(initialNode)) < 0.) { // negativeEnergy = true; // tMax = 0.; // } else { negativeEnergy = false; // } // TODO: treat inwards electrons in a better way? if (vertexType==4 && 0.5*pow(initialNormalVelocity.norm(),2.)<charge*phiSurface && currentVelocity.dot(vertexNormalVector)<0.) { currentVelocity -= 2.*initialNormalVelocity; } int nSteps=0; double potential=0.; bool endLoop=false; bool foundTet=false; boost::array<Eigen::Matrix<double,NDIM,1>, 2> positionAndVelocity; boost::array<Eigen::Matrix<double,NDIM,1>, 2> positionAndVelocityOut; positionAndVelocity[0] = currentPosition; positionAndVelocity[1] = currentVelocity; // VelocityVerletStepper<NDIM> timestepper; // CyclotronicStepper timestepper; // TaylorStepper timestepper; DriftStepper timestepper; // boost::numeric::odeint::runge_kutta4<boost::array<vect3d,2> > // timestepper; VelocityAndAcceleration<NDIM> velocityAndAcceleration(potentialField, // electricField, charge, initialNode, initialVelocity, false); electricField, charge, initialNode, initialVelocity, true); foundTet = velocityAndAcceleration.foundTet; // assert(foundTet); // TODO: do this more cleanly if (foundTet) { initialPotential = velocityAndAcceleration.currentPotential; double driftPotential=extern_E.dot(initialPosition); initialPotential += driftPotential; initialEnergy = 0.5*pow((initialVelocity+extern_VEXB).norm(),2.) // initialEnergy = 0.5*pow(initialVelocity.norm(),2.) + charge*initialPotential; double currentPotential=initialPotential; double currentEnergy=initialEnergy; MinimumBasisFunction minimumBasisFunction(mesh_ptr, &positionAndVelocity, &velocityAndAcceleration, ×tepper); // // For second order leap-frog, offset position from velocity in time // currentPosition -= currentVelocity*dt/2.; // for (double t=0.; t<tMax; t+=dt) { double t=0; double numberOfStepsPerRegion = 3.; int numberOfSteps = 100000*numberOfStepsPerRegion; // TODO: set max number of steps more cleverly (since also need to limit by accel) for (int iT=0; iT<numberOfSteps && !negativeEnergy; iT++) { dt = shortestEdgeField[velocityAndAcceleration.currentRegionIndex] /(fabs(currentVelocity[2])+extern_VEXB.norm()+SMALL_VELOCITY)/ // /(fabs(currentVelocity[2])+DELTA_LENGTH)/ numberOfStepsPerRegion; // /currentVelocity.norm()/5.; // TODO: Need acceleration info as well, since v_z changes during time-step // dt = min(0.01,dt); // dt = 0.01; // TODO: can this fail (need to ensure minimumBasisFunction(0.)>0.? dt = SMALL_TIME; t += dt; try { timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, dt); } catch (...) { cout << "Failed to do SMALL_TIME step into interior." << endl; } // TODO: optimise this or replace with better way? double dtMultiplier=10.; double dtAtWhichNegative=sqrt(SMALL_TIME)/dtMultiplier; // TODO: minimumBasisFunction() should not throw provided positionAndVelocity[0] is within tet try { while (dtAtWhichNegative<tMax && minimumBasisFunction(dtAtWhichNegative)>0.) { dtAtWhichNegative *= dtMultiplier; } } catch (...) { cout << "Failed to evaluate minimumBasisFunction(" << dtAtWhichNegative << ")" << endl; } // // TODO: debugging //// cout << minimumBasisFunction(-dtAtWhichNegative) << endl; // cout << minimumBasisFunction(SMALL_TIME) << endl; // cout << minimumBasisFunction(dtAtWhichNegative) << endl << endl; //// cout << mesh_ptr->minimumBasisFunction(positionAndVelocity[0]+dtAtWhichNegative*( //// positionAndVelocity[1]+VEXB), //// velocityAndAcceleration.currentRegionIndex) << endl; // if (extern_orbitNumber==64313 7328) { // if (extern_orbitNumber==64313) { // cout << velocityAndAcceleration.currentPosition.transpose() << endl; // cout << dtAtWhichNegative << endl; // cout << minimumBasisFunction(0.) << " " << minimumBasisFunction(dtAtWhichNegative) << endl; //// cout << minimumBasisFunction(SMALL_TIME) << " " << minimumBasisFunction(dtAtWhichNegative) << endl; // } boost::uintmax_t max_iter=500; // tolerance is number of bits boost::math::tools::eps_tolerance<double> tol(8); std::pair<double, double> dtInterval; dtInterval.first=0.; dtInterval.second=SMALL_TIME; try { dtInterval = boost::math::tools::toms748_solve(minimumBasisFunction, 0., dtAtWhichNegative, tol, max_iter); // boost::math::tools::toms748_solve(minimumBasisFunction, SMALL_TIME, // dtAtWhichNegative, tol, max_iter); } catch (...) { cout << "toms748 failed to find root." << endl; } // dt = dtInterval.first; // TODO: find better way to ensure next point is not in same region dt = dtInterval.second+SMALL_TIME; // double additionalDtToExitRegion = (dtInterval.second-dtInterval.first); double additionalDtToExitRegion = 0.; // TODO: debugging // cout << minimumBasisFunction(dt) << endl; // cout << minimumBasisFunction(dt+additionalDtToExitRegion) << endl << endl; t += dt; nSteps++; // // TODO: debugging // cout << nSteps << " : " << t << endl; // cout << positionAndVelocity[0].transpose() << endl; // TODO: DriftStepper::do_step() should not throw, but others might... try { timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, dt); } catch (...) { cout << "Failed to step out of tet." << endl; } currentPosition = positionAndVelocity[0]; currentVelocity = positionAndVelocity[1]; // // TODO: debugging // cout << positionAndVelocity[0].transpose() << endl; // timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, -dt); // cout << positionAndVelocity[0].transpose() << endl; // timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, dt/2.); // cout << positionAndVelocity[0].transpose() << endl; // timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, dt/2.); // cout << positionAndVelocity[0].transpose() << endl; dt = additionalDtToExitRegion; t+=dt; if (isnan(currentPosition.norm())) throw string("currentPosition is NaN in Orbit.cpp"); vect3d previousPosition = currentPosition; vect3d previousVelocity = currentVelocity; entHandle previousElement = velocityAndAcceleration.currentElement; // currentPosition += dt*currentVelocity; // vect3d currentAcceleration(0.,0.,0.); // // TODO: replace this hack // if (t==0.) { // currentElement = mesh_ptr->findTet(previousPosition, // currentPosition, initialNode, &foundTet, false); // // TODO: figure out why sometimes throw here (grazing orbits?) //// if (!foundTet) //// throw; // int dimension=mesh_ptr->getEntityDimension(currentElement); // if (dimension!=iBase_REGION) // foundTet = false; // } //// if (!foundTet) //// break; // if (foundTet) { try { positionAndVelocity[0] = currentPosition; positionAndVelocity[1] = currentVelocity; // TODO: debugging // cout << minimumBasisFunction(SMALL_TIME) << endl; // cout << minimumBasisFunction(dt) << endl << endl; timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t, dt); // // TODO: always exit with small time-step to minimize energy error...do better? // timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t+dt, // additionalDtToExitRegion); // TODO: replace this hack to update currentElement? timestepper.do_step(boost::ref(velocityAndAcceleration), positionAndVelocity, t+dt, SMALL_TIME); // // TODO: figure out why inout arg leads to problems // // (Eigen not liking certain optimization tricks in odeint?. // Actually, just missing initialization) // timestepper.do_step(boost::ref(velocityAndAcceleration), // positionAndVelocity, t, positionAndVelocityOut, dt); // positionAndVelocity[0] = positionAndVelocityOut[0]; // positionAndVelocity[1] = positionAndVelocityOut[1]; // timestepper.do_step(velocityAndAcceleration, positionAndVelocity, t, dt); currentPosition = positionAndVelocity[0]; currentVelocity = positionAndVelocity[1]; currentElement = velocityAndAcceleration.currentElement; if (currentElement==previousElement) throw string("Did not step to new element...something is wrong."); // TODO: change this to use regionIndex foundTet = mesh_ptr->checkIfInTet(currentPosition, currentElement); if (!foundTet) { // TODO: figure out why sometimes lose track of tet throw int(OUTSIDE_DOMAIN); // currentElement = mesh_ptr->findTet(previousPosition, currentPosition, // currentElement, &foundTet); } // finalEnergy = 0.5*pow(currentVelocity.norm(),2.) // + charge*potentialField.getField(currentPosition); // TODO: this doesn't account for final step, but as long as boundary // is at potential zero it shouldn't matter for orbits with non-zero weight // (actually, am using finalPotential later) driftPotential = extern_E.dot(currentPosition); currentPotential = velocityAndAcceleration.currentPotential; currentPotential += driftPotential; currentEnergy = 0.5*pow((currentVelocity+extern_VEXB).norm(),2.) // currentEnergy = 0.5*pow(currentVelocity.norm(),2.) // + charge*velocityAndAcceleration.currentPotential; + charge*(currentPotential); // // TODO: set order through input parameter? // int interpolationOrder = INTERPOLATIONORDER; //// currentAcceleration = charge* //// electricField.getField(currentPosition, ¤tElement); // potential = potentialField.getField(currentPosition, ¤tElement, // interpolationOrder); // if (isnan(potential)) // potential = potentialField.getField(currentPosition, // ¤tElement, 1); // // TODO: hard-coding dimension here... // for (int i=0; i<3; i++) { // vect3d perturbedPosition = currentPosition + // vect3d::Unit(i)*DELTA_LENGTH; // double perturbedPotential = potentialField.getField( // perturbedPosition, ¤tElement, interpolationOrder); // // TODO: track down why perturbedPotential sometimes is NaN //// cout << "calculation of error term succeeded." << //// i << " " << currentElement << endl; // if (isnan(perturbedPotential)) { // perturbedPotential = potentialField.getField( // perturbedPosition, ¤tElement, 1); // cout << "calculation of error term failed." << // i << " " << currentElement << endl; // } //// if (isnan(potential) || isnan(perturbedPotential)) { //// cout << potential << " " << perturbedPotential << //// " " << currentPosition.transpose() << endl; //// throw; //// } // currentAcceleration[i] = // -charge*(perturbedPotential-potential)/DELTA_LENGTH; // } } catch (int signal) { switch (signal) { case OUTSIDE_DOMAIN: foundTet = false; // TODO: not guaranteed that outside domain (since different than stepper) // TODO: Revisit this in magnetized case // currentPosition += dt*currentVelocity; currentPosition = positionAndVelocity[0]; currentVelocity = positionAndVelocity[1]; break; default: // TODO: handle other exceptions? throw; break; } } catch (...) { // TODO: handle other exceptions? throw; } // } if (foundTet==false) { // TODO: if near vertex could leave domain through non-boundary face // by crossing sliver of other tet in one time-step // entHandle faceCrossed = mesh_ptr->findFaceCrossed( // previousElement, previousPosition, currentPosition); int faceCrossedIndex = mesh_ptr->findBoundaryFaceCrossed( mesh_ptr->indicesOfEntities[previousElement], previousPosition, currentPosition, faceTypeField, vertexTypeField); entHandle faceCrossed = NULL; if (faceCrossedIndex>=0) { faceCrossed = mesh_ptr->entitiesVectors[iBase_FACE][faceCrossedIndex]; } // TODO: grazing orbits don't enter domain in first time-step int faceType; vect3d normalVector(0.,0.,0.), normalVelocity(0.,0.,0.); if (faceCrossed!=NULL) { faceType = faceTypeField.getField(faceCrossed); normalVector = mesh_ptr->getNormalVector(faceCrossed, previousPosition); normalVelocity = currentVelocity.dot(normalVector)*normalVector; // // TODO: debugging // if (extern_orbitNumber==15) { // cout << currentPotential << endl; // } // finalPotential = 0.; // vector<entHandle> vertices = // mesh_ptr->getVertices(faceCrossed); // for (int i=0; i<vertices.size(); i++) { // // TODO: should use point where left domain here // finalPotential += 1./3.*potentialField.getField(vertices[i]); // } // // TODO: debugging // if (extern_orbitNumber==15) { // cout << finalPotential << endl; // } vect3d exitPosition; vector<vect3d> vertexVectors = mesh_ptr->getVertexVectors(faceCrossed); // TODO: straight line intersection may not be accurate for magnetized orbits mesh_ptr->checkIfIntersectsTriangle(previousPosition, currentPosition, vertexVectors, &exitPosition); vect3d centroid(0.,0.,0.); // vector<vect3d> vVs = mesh_ptr->getVertexVectors(i,iBase_REGION); // centroid = (vVs[0]+vVs[1]+vVs[2]+vVs[3])/4.; // vect3d interiorDirection=centroid-exitPosition; // interiorDirection /= interiorDirection.norm(); // TODO: Don't hard-code this correction // exitPosition += sqrt(LENGTH_TOLERANCE)*interiorDirection; exitPosition -= sqrt(LENGTH_TOLERANCE)*normalVector; // TODO: figure out why this fails with interpolationorder=1 // currentPotential = potentialField.getField(exitPosition); // TODO: for consistency should strictly evaluate everything at exitPosition // driftPotential = E.dot(currentPosition); // currentPotential += driftPotential; // currentEnergy = 0.5*pow((currentVelocity+VEXB).norm(),2.) //// currentEnergy = 0.5*pow(currentVelocity.norm(),2.) // + charge*currentPotential; finalPotential = currentPotential; finalEnergy = currentEnergy; // // TODO: debugging // if (extern_orbitNumber==15) { // cout << finalPotential << endl; //// cout << previousPosition.transpose() << endl; //// cout << exitPosition.transpose() << endl; //// cout << currentPosition.transpose() << endl; //// cout << potentialField.getField(previousPosition) << endl; //// cout << potentialField.getField(exitPosition) << endl; // } // TODO: shouldn't hard-code boundary code } else { faceType = 0; } // if (faceType==0) { // cout << previousElement << " " << // faceCrossed << " " << currentPosition.norm() << // " " << previousPosition.norm() << endl; // } finalFaceType = faceType; // TODO: need to account for shielding potential here if (faceType==4 && 0.5*pow(normalVelocity.norm(),2.)<charge*phiSurface) { currentElement = previousElement; foundTet = true; // TODO: resetting position isn't quite right currentPosition = previousPosition; // TODO: revisit this in magnetized case // TODO: calc this from previousVelocity? currentVelocity -= 2.*normalVelocity; } else { // if (faceType==0) // cout << "last face crossed was an interior one" << endl; endLoop=true; } } // if (nSteps==1 && !foundTet) { // cout << currentPosition.transpose() << " " << // currentVelocity.transpose() << " " << // currentPosition.dot(currentVelocity) << endl; // } // double eFieldR = currentAcceleration.dot(currentPosition)/ // currentPosition.norm(); //// // TODO: comment out this //// currentAcceleration = -charge*currentPosition/ //// pow(currentPosition.norm(),3.); // currentVelocity += dt*currentAcceleration; // vect3d velocityAtPosition = currentVelocity - 1./2.*dt*currentAcceleration; // double energy = 1./2.*pow(velocityAtPosition.norm(),2.) + charge*potential; // if (foundTet) { // potential = potentialField.getField(currentPosition, // &velocityAndAcceleration.currentElement, // velocityAndAcceleration.interpolationOrder); // } else { potential = 0.; // } // assert(currentPosition.norm()<10.); double energy = 0.; // double energy = 1./2.*pow(currentVelocity.norm(),2.) + charge*finalPotential; if (outFile) { // if (outFile && (extern_orbitNumber==15 || extern_orbitNumber==790)) { // fprintf(outFile, "%f %f %f %p\n", currentPosition[0], currentPosition[1], // currentPosition[2], (void*)currentElement); // TODO: fix occasional very large coordinate values // // TODO: comment this out unless using spheres mesh // if (currentPosition.norm()<=5.) // fprintf(outFile, "%f %f %f %d\n", currentPosition[0], currentPosition[1], // currentPosition[2], extern_orbitNumber); fprintf(outFile, "%f %f %f %f\n", currentPosition[0], currentPosition[1], // currentPosition[2], currentEnergy); // currentPosition[2], currentPotential); // currentPosition[2], 0.5*pow((currentVelocity+VEXB).norm(),2.)); // currentPosition[2], eFieldR); currentPosition[2], orbitLabelValue); } if (endLoop) break; } } else { // !foundTet // TODO: check that only get here if starting from node on boundary finalFaceType = vertexTypeField.getField(initialNode); finalPotential = potentialField.getField(initialNode); } // cout << "Final radius=" << currentPosition.norm() << " nSteps=" << // nSteps << "faceType =" << finalFaceType << endl; finalPosition = currentPosition; // TODO: correct for time-step offset? finalVelocity = currentVelocity; // TODO: debugging double fractionalEnergyChange = (finalEnergy-initialEnergy)/initialEnergy; // if (fabs(fractionalEnergyChange) > 0.0 && finalPotential-driftPotential > -1.) { // if (fabs(fractionalEnergyChange) > 0.0 && finalPotential > -1.) { // cout << fractionalEnergyChange << " energy change for orbit " << // extern_orbitNumber << " : " << finalPotential << " / " << // initialPotential << " " << finalVelocity.norm() << " / " << // initialVelocity.norm() << " " << finalEnergy << " / " << // initialEnergy << endl; // } }
void testMean() { EXPECT_NEAR(ms_full["data"].template mean<value_type>(), ms_half1["data"].template mean<value_type>(), tol()); }
int main(int argc, char *argv[]) { // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided. int iprint = argc - 1; Teuchos::RCP<std::ostream> outStream; Teuchos::oblackholestream bhs; // outputs nothing /*** Initialize communicator. ***/ Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs); Teuchos::RCP<const Teuchos::Comm<int> > comm = Tpetra::DefaultPlatform::getDefaultPlatform().getComm(); const int myRank = comm->getRank(); if ((iprint > 0) && (myRank == 0)) { outStream = Teuchos::rcp(&std::cout, false); } else { outStream = Teuchos::rcp(&bhs, false); } int errorFlag = 0; // *** Example body. try { /*** Read in XML input ***/ std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() ); /*** Initialize main data structure. ***/ Teuchos::RCP<MeshManager<RealT> > meshMgr = Teuchos::rcp(new MeshManager_BackwardFacingStepChannel<RealT>(*parlist)); // Initialize PDE describing Navier-Stokes equations. Teuchos::RCP<PDE_NavierStokes<RealT> > pde = Teuchos::rcp(new PDE_NavierStokes<RealT>(*parlist)); Teuchos::RCP<ROL::EqualityConstraint_SimOpt<RealT> > con = Teuchos::rcp(new PDE_Constraint<RealT>(pde,meshMgr,comm,*parlist,*outStream)); // Cast the constraint and get the assembler. Teuchos::RCP<PDE_Constraint<RealT> > pdecon = Teuchos::rcp_dynamic_cast<PDE_Constraint<RealT> >(con); Teuchos::RCP<Assembler<RealT> > assembler = pdecon->getAssembler(); con->setSolveParameters(*parlist); // Create state vector and set to zeroes Teuchos::RCP<Tpetra::MultiVector<> > u_rcp = assembler->createStateVector(); u_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(u_rcp,pde,assembler)); Teuchos::RCP<Tpetra::MultiVector<> > p_rcp = assembler->createStateVector(); p_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(p_rcp,pde,assembler)); // Create control vector and set to ones Teuchos::RCP<Tpetra::MultiVector<> > z_rcp = assembler->createControlVector(); z_rcp->randomize(); //putScalar(1.0); Teuchos::RCP<ROL::Vector<RealT> > zp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(z_rcp,pde,assembler)); // Create residual vector and set to zeros Teuchos::RCP<Tpetra::MultiVector<> > r_rcp = assembler->createResidualVector(); r_rcp->putScalar(0.0); Teuchos::RCP<ROL::Vector<RealT> > rp = Teuchos::rcp(new PDE_DualSimVector<RealT>(r_rcp,pde,assembler)); // Create state direction vector and set to random Teuchos::RCP<Tpetra::MultiVector<> > du_rcp = assembler->createStateVector(); du_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > dup = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(du_rcp,pde,assembler)); // Create control direction vector and set to random Teuchos::RCP<Tpetra::MultiVector<> > dz_rcp = assembler->createControlVector(); dz_rcp->randomize(); Teuchos::RCP<ROL::Vector<RealT> > dzp = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(dz_rcp,pde,assembler)); // Create ROL SimOpt vectors ROL::Vector_SimOpt<RealT> x(up,zp); ROL::Vector_SimOpt<RealT> d(dup,dzp); // Initialize quadratic objective function. std::vector<Teuchos::RCP<QoI<RealT> > > qoi_vec(2,Teuchos::null); qoi_vec[0] = Teuchos::rcp(new QoI_State_NavierStokes<RealT>(*parlist, pde->getVelocityFE(), pde->getPressureFE(), pde->getFieldHelper())); qoi_vec[1] = Teuchos::rcp(new QoI_L2Penalty_NavierStokes<RealT>(pde->getVelocityFE(), pde->getPressureFE(), pde->getVelocityBdryFE(), pde->getBdryCellLocIds(), pde->getFieldHelper())); Teuchos::RCP<StdObjective_NavierStokes<RealT> > std_obj = Teuchos::rcp(new StdObjective_NavierStokes<RealT>(*parlist)); Teuchos::RCP<ROL::Objective_SimOpt<RealT> > obj = Teuchos::rcp(new PDE_Objective<RealT>(qoi_vec,std_obj,assembler)); Teuchos::RCP<ROL::Reduced_Objective_SimOpt<RealT> > robj = Teuchos::rcp(new ROL::Reduced_Objective_SimOpt<RealT>(obj, con, up, zp, pp, true, false)); up->zero(); zp->zero(); //z_rcp->putScalar(1.e0); //dz_rcp->putScalar(0); // Run derivative checks bool checkDeriv = parlist->sublist("Problem").get("Check derivatives",false); if ( checkDeriv ) { obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); con->checkApplyJacobian(x,d,*up,true,*outStream); con->checkApplyAdjointHessian(x,*dup,d,x,true,*outStream); con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); con->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); con->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); robj->checkGradient(*zp,*dzp,true,*outStream); robj->checkHessVec(*zp,*dzp,true,*outStream); } bool useCompositeStep = parlist->sublist("Problem").get("Full space",false); Teuchos::RCP<ROL::Algorithm<RealT> > algo; if ( useCompositeStep ) { algo = Teuchos::rcp(new ROL::Algorithm<RealT>("Composite Step",*parlist,false)); algo->run(x,*rp,*obj,*con,true,*outStream); } else { algo = Teuchos::rcp(new ROL::Algorithm<RealT>("Trust Region",*parlist,false)); algo->run(*zp,*robj,true,*outStream); } // Output. assembler->printMeshData(*outStream); RealT tol(1.e-8); Teuchos::Array<RealT> res(1,0); con->solve(*rp,*up,*zp,tol); pdecon->outputTpetraVector(u_rcp,"state.txt"); pdecon->outputTpetraVector(z_rcp,"control.txt"); con->value(*rp,*up,*zp,tol); r_rcp->norm2(res.view(0,1)); *outStream << "Residual Norm: " << res[0] << std::endl; errorFlag += (res[0] > 1.e-6 ? 1 : 0); //pdecon->outputTpetraData(); } catch (std::logic_error err) { *outStream << err.what() << "\n"; errorFlag = -1000; }; // end try if (errorFlag != 0) std::cout << "End Result: TEST FAILED\n"; else std::cout << "End Result: TEST PASSED\n"; return 0; }
void testErrorBar() { if (is_mean_acc) return; EXPECT_NEAR(ms_full["data"].template error<value_type>(), ms_half1["data"].template error<value_type>(), tol()); }
int main(int argc, char *argv[]) { // feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided. int iprint = argc - 1; Teuchos::RCP<std::ostream> outStream; Teuchos::oblackholestream bhs; // outputs nothing /*** Initialize communicator. ***/ Teuchos::GlobalMPISession mpiSession (&argc, &argv, &bhs); Teuchos::RCP<const Teuchos::Comm<int> > comm = Tpetra::DefaultPlatform::getDefaultPlatform().getComm(); Teuchos::RCP<const Teuchos::Comm<int> > serial_comm = Teuchos::rcp(new Teuchos::SerialComm<int>()); const int myRank = comm->getRank(); if ((iprint > 0) && (myRank == 0)) { outStream = Teuchos::rcp(&std::cout, false); } else { outStream = Teuchos::rcp(&bhs, false); } int errorFlag = 0; // *** Example body. try { /*** Read in XML input ***/ std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() ); // Problem dimensions const int stochDim = 32, controlDim = 1; const RealT one(1); /*************************************************************************/ /***************** BUILD GOVERNING PDE ***********************************/ /*************************************************************************/ /*** Initialize main data structure. ***/ Teuchos::RCP<MeshManager<RealT> > meshMgr = Teuchos::rcp(new MeshManager_BackwardFacingStepChannel<RealT>(*parlist)); // = Teuchos::rcp(new StochasticStefanBoltzmannMeshManager<RealT>(*parlist)); // Initialize PDE describing advection-diffusion equation Teuchos::RCP<StochasticStefanBoltzmannPDE<RealT> > pde = Teuchos::rcp(new StochasticStefanBoltzmannPDE<RealT>(*parlist)); Teuchos::RCP<ROL::ParametrizedEqualityConstraint_SimOpt<RealT> > con = Teuchos::rcp(new PDE_Constraint<RealT>(pde,meshMgr,serial_comm,*parlist,*outStream)); // Get the assembler. Teuchos::RCP<Assembler<RealT> > assembler = (Teuchos::rcp_dynamic_cast<PDE_Constraint<RealT> >(con))->getAssembler(); con->setSolveParameters(*parlist); assembler->printMeshData(*outStream); /*************************************************************************/ /***************** BUILD VECTORS *****************************************/ /*************************************************************************/ Teuchos::RCP<Tpetra::MultiVector<> > u_rcp = assembler->createStateVector(); Teuchos::RCP<Tpetra::MultiVector<> > p_rcp = assembler->createStateVector(); Teuchos::RCP<Tpetra::MultiVector<> > du_rcp = assembler->createStateVector(); u_rcp->randomize(); //u_rcp->putScalar(static_cast<RealT>(1)); p_rcp->randomize(); //p_rcp->putScalar(static_cast<RealT>(1)); du_rcp->randomize(); //du_rcp->putScalar(static_cast<RealT>(0)); Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(u_rcp,pde,assembler)); Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(p_rcp,pde,assembler)); Teuchos::RCP<ROL::Vector<RealT> > dup = Teuchos::rcp(new PDE_PrimalSimVector<RealT>(du_rcp,pde,assembler)); // Create residual vectors Teuchos::RCP<Tpetra::MultiVector<> > r_rcp = assembler->createResidualVector(); r_rcp->randomize(); //r_rcp->putScalar(static_cast<RealT>(1)); Teuchos::RCP<ROL::Vector<RealT> > rp = Teuchos::rcp(new PDE_DualSimVector<RealT>(r_rcp,pde,assembler)); // Create control vector and set to ones Teuchos::RCP<std::vector<RealT> > z_rcp = Teuchos::rcp(new std::vector<RealT>(controlDim)); Teuchos::RCP<std::vector<RealT> > dz_rcp = Teuchos::rcp(new std::vector<RealT>(controlDim)); Teuchos::RCP<std::vector<RealT> > yz_rcp = Teuchos::rcp(new std::vector<RealT>(controlDim)); // Create control direction vector and set to random for (int i = 0; i < controlDim; ++i) { (*z_rcp)[i] = random<RealT>(*comm); (*dz_rcp)[i] = 1e-3*random<RealT>(*comm); (*yz_rcp)[i] = random<RealT>(*comm); } Teuchos::RCP<ROL::Vector<RealT> > zp = Teuchos::rcp(new PDE_OptVector<RealT>(Teuchos::rcp(new ROL::StdVector<RealT>(z_rcp)))); Teuchos::RCP<ROL::Vector<RealT> > dzp = Teuchos::rcp(new PDE_OptVector<RealT>(Teuchos::rcp(new ROL::StdVector<RealT>(dz_rcp)))); Teuchos::RCP<ROL::Vector<RealT> > yzp = Teuchos::rcp(new PDE_OptVector<RealT>(Teuchos::rcp(new ROL::StdVector<RealT>(yz_rcp)))); //Teuchos::RCP<Tpetra::MultiVector<> > z_rcp = assembler->createControlVector(); //Teuchos::RCP<Tpetra::MultiVector<> > dz_rcp = assembler->createControlVector(); //Teuchos::RCP<Tpetra::MultiVector<> > yz_rcp = assembler->createControlVector(); //z_rcp->randomize(); z_rcp->putScalar(static_cast<RealT>(280)); //dz_rcp->randomize(); //dz_rcp->putScalar(static_cast<RealT>(0)); //yz_rcp->randomize(); //yz_rcp->putScalar(static_cast<RealT>(0)); //Teuchos::RCP<ROL::TpetraMultiVector<RealT> > zpde // = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(z_rcp,pde,assembler)); //Teuchos::RCP<ROL::TpetraMultiVector<RealT> > dzpde // = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(dz_rcp,pde,assembler)); //Teuchos::RCP<ROL::TpetraMultiVector<RealT> > yzpde // = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(yz_rcp,pde,assembler)); //Teuchos::RCP<ROL::Vector<RealT> > zp = Teuchos::rcp(new PDE_OptVector<RealT>(zpde)); //Teuchos::RCP<ROL::Vector<RealT> > dzp = Teuchos::rcp(new PDE_OptVector<RealT>(dzpde)); //Teuchos::RCP<ROL::Vector<RealT> > yzp = Teuchos::rcp(new PDE_OptVector<RealT>(yzpde)); // Create ROL SimOpt vectors ROL::Vector_SimOpt<RealT> x(up,zp); ROL::Vector_SimOpt<RealT> d(dup,dzp); /*************************************************************************/ /***************** BUILD COST FUNCTIONAL *********************************/ /*************************************************************************/ std::vector<Teuchos::RCP<QoI<RealT> > > qoi_vec(2,Teuchos::null); qoi_vec[0] = Teuchos::rcp(new QoI_StateCost<RealT>(pde->getVolFE(),*parlist)); //qoi_vec[1] = Teuchos::rcp(new QoI_ControlCost<RealT>( // pde->getVolFE(),pde->getBdryFE(0),pde->getBdryCellLocIds(0),*parlist)); qoi_vec[1] = Teuchos::rcp(new QoI_AdvectionCost<RealT>()); Teuchos::RCP<StochasticStefanBoltzmannStdObjective<RealT> > std_obj = Teuchos::rcp(new StochasticStefanBoltzmannStdObjective<RealT>(*parlist)); Teuchos::RCP<ROL::ParametrizedObjective_SimOpt<RealT> > obj = Teuchos::rcp(new PDE_Objective<RealT>(qoi_vec,std_obj,assembler)); Teuchos::RCP<ROL::Reduced_ParametrizedObjective_SimOpt<RealT> > objReduced = Teuchos::rcp(new ROL::Reduced_ParametrizedObjective_SimOpt<RealT>(obj, con, up, pp, true, false)); /*************************************************************************/ /***************** BUILD BOUND CONSTRAINT ********************************/ /*************************************************************************/ RealT upper = parlist->sublist("Problem").get("Upper Advection Bound", 100.0); RealT lower = parlist->sublist("Problem").get("Lower Advection Bound",-100.0); Teuchos::RCP<std::vector<RealT> > zlo_rcp = Teuchos::rcp(new std::vector<RealT>(controlDim,lower)); Teuchos::RCP<std::vector<RealT> > zhi_rcp = Teuchos::rcp(new std::vector<RealT>(controlDim,upper)); Teuchos::RCP<ROL::Vector<RealT> > zlop = Teuchos::rcp(new PDE_OptVector<RealT>(Teuchos::rcp(new ROL::StdVector<RealT>(zlo_rcp)))); Teuchos::RCP<ROL::Vector<RealT> > zhip = Teuchos::rcp(new PDE_OptVector<RealT>(Teuchos::rcp(new ROL::StdVector<RealT>(zhi_rcp)))); //Teuchos::RCP<Tpetra::MultiVector<> > zlo_rcp = assembler->createControlVector(); //Teuchos::RCP<Tpetra::MultiVector<> > zhi_rcp = assembler->createControlVector(); //zlo_rcp->putScalar(static_cast<RealT>(280)); //zhi_rcp->putScalar(static_cast<RealT>(370)); //Teuchos::RCP<ROL::TpetraMultiVector<RealT> > zlopde // = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(zlo_rcp,pde,assembler)); //Teuchos::RCP<ROL::TpetraMultiVector<RealT> > zhipde // = Teuchos::rcp(new PDE_PrimalOptVector<RealT>(zhi_rcp,pde,assembler)); //Teuchos::RCP<ROL::Vector<RealT> > zlop = Teuchos::rcp(new PDE_OptVector<RealT>(zlopde)); //Teuchos::RCP<ROL::Vector<RealT> > zhip = Teuchos::rcp(new PDE_OptVector<RealT>(zhipde)); Teuchos::RCP<ROL::BoundConstraint<RealT> > bnd = Teuchos::rcp(new ROL::BoundConstraint<RealT>(zlop,zhip)); /*************************************************************************/ /***************** BUILD SAMPLER *****************************************/ /*************************************************************************/ int nsamp = parlist->sublist("Problem").get("Number of Samples",100); std::vector<RealT> tmp = {-one,one}; std::vector<std::vector<RealT> > bounds(stochDim,tmp); Teuchos::RCP<ROL::BatchManager<RealT> > bman = Teuchos::rcp(new PDE_OptVector_BatchManager<RealT>(comm)); Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler = Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nsamp,bounds,bman)); /*************************************************************************/ /***************** BUILD STOCHASTIC PROBLEM ******************************/ /*************************************************************************/ ROL::StochasticProblem<RealT> opt(*parlist,objReduced,sampler,zp,bnd); opt.setSolutionStatistic(one); /*************************************************************************/ /***************** RUN VECTOR AND DERIVATIVE CHECKS **********************/ /*************************************************************************/ bool checkDeriv = parlist->sublist("Problem").get("Check Derivatives",false); if ( checkDeriv ) { up->checkVector(*pp,*dup,true,*outStream); zp->checkVector(*yzp,*dzp,true,*outStream); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); con->checkApplyJacobian(x,d,*up,true,*outStream); con->checkApplyAdjointHessian(x,*dup,d,x,true,*outStream); con->checkAdjointConsistencyJacobian(*dup,d,x,true,*outStream); con->checkInverseJacobian_1(*up,*up,*up,*zp,true,*outStream); con->checkInverseAdjointJacobian_1(*up,*up,*up,*zp,true,*outStream); objReduced->checkGradient(*zp,*dzp,true,*outStream); objReduced->checkHessVec(*zp,*dzp,true,*outStream); opt.checkObjectiveGradient(*dzp,true,*outStream); opt.checkObjectiveHessVec(*dzp,true,*outStream); } /*************************************************************************/ /***************** SOLVE OPTIMIZATION PROBLEM ****************************/ /*************************************************************************/ ROL::Algorithm<RealT> algo("Trust Region",*parlist,false); (*z_rcp)[0] = parlist->sublist("Problem").get("Advection Magnitude",0.0); u_rcp->putScalar(450.0); std::clock_t timer = std::clock(); algo.run(opt,true,*outStream); *outStream << "Optimization time: " << static_cast<RealT>(std::clock()-timer)/static_cast<RealT>(CLOCKS_PER_SEC) << " seconds." << std::endl << std::endl; /*************************************************************************/ /***************** OUTPUT RESULTS ****************************************/ /*************************************************************************/ std::clock_t timer_print = std::clock(); // Output control to file //assembler->outputTpetraVector(z_rcp,"control.txt"); *outStream << std::endl << "Advection value: " << (*z_rcp)[0] << std::endl; // Output expected state and samples to file *outStream << std::endl << "Print Expected Value of State" << std::endl; up->zero(); pp->zero(); dup->zero(); RealT tol(1.e-8); Teuchos::RCP<ROL::BatchManager<RealT> > bman_Eu = Teuchos::rcp(new ROL::TpetraTeuchosBatchManager<RealT>(comm)); std::vector<RealT> sample(stochDim); std::stringstream name_samp; name_samp << "samples_" << bman->batchID() << ".txt"; std::ofstream file_samp; file_samp.open(name_samp.str()); file_samp << std::scientific << std::setprecision(15); for (int i = 0; i < sampler->numMySamples(); ++i) { *outStream << "Sample i = " << i << std::endl; sample = sampler->getMyPoint(i); con->setParameter(sample); con->solve(*rp,*dup,*zp,tol); up->axpy(sampler->getMyWeight(i),*dup); for (int j = 0; j < stochDim; ++j) { file_samp << std::setw(25) << std::left << sample[j]; } file_samp << std::endl; } file_samp.close(); bman_Eu->sumAll(*up,*pp); assembler->outputTpetraVector(p_rcp,"mean_state.txt"); // Build objective function distribution *outStream << std::endl << "Print Objective CDF" << std::endl; RealT val1(0), val2(0); int nsamp_dist = parlist->sublist("Problem").get("Number of Output Samples",100); Teuchos::RCP<ROL::ParametrizedObjective_SimOpt<RealT> > stateCost = Teuchos::rcp(new IntegralObjective<RealT>(qoi_vec[0],assembler)); Teuchos::RCP<ROL::Reduced_ParametrizedObjective_SimOpt<RealT> > redStateCost = Teuchos::rcp(new ROL::Reduced_ParametrizedObjective_SimOpt<RealT>(stateCost, con, up, pp, true, false)); Teuchos::RCP<ROL::ParametrizedObjective_SimOpt<RealT> > ctrlCost = Teuchos::rcp(new IntegralObjective<RealT>(qoi_vec[1],assembler)); Teuchos::RCP<ROL::Reduced_ParametrizedObjective_SimOpt<RealT> > redCtrlCost = Teuchos::rcp(new ROL::Reduced_ParametrizedObjective_SimOpt<RealT>(ctrlCost, con, up, pp, true, false)); Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler_dist = Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nsamp_dist,bounds,bman)); std::stringstream name; name << "obj_samples_" << bman->batchID() << ".txt"; std::ofstream file; file.open(name.str()); file << std::scientific << std::setprecision(15); for (int i = 0; i < sampler_dist->numMySamples(); ++i) { sample = sampler_dist->getMyPoint(i); redStateCost->setParameter(sample); val1 = redStateCost->value(*zp,tol); redCtrlCost->setParameter(sample); val2 = redCtrlCost->value(*zp,tol); for (int j = 0; j < stochDim; ++j) { file << std::setw(25) << std::left << sample[j]; } file << std::setw(25) << std::left << val1; file << std::setw(25) << std::left << val2 << std::endl; } file.close(); *outStream << "Output time: " << static_cast<RealT>(std::clock()-timer_print)/static_cast<RealT>(CLOCKS_PER_SEC) << " seconds." << std::endl << std::endl; Teuchos::Array<RealT> res(1,0); con->value(*rp,*up,*zp,tol); r_rcp->norm2(res.view(0,1)); /*************************************************************************/ /***************** CHECK RESIDUAL NORM ***********************************/ /*************************************************************************/ *outStream << "Residual Norm: " << res[0] << std::endl << std::endl; errorFlag += (res[0] > 1.e-6 ? 1 : 0); } catch (std::logic_error err) { *outStream << err.what() << "\n"; errorFlag = -1000; }; // end try if (errorFlag != 0) std::cout << "End Result: TEST FAILED\n"; else std::cout << "End Result: TEST PASSED\n"; return 0; }