vec3_t SimpleFoamWriter::face_t::normal(vtkUnstructuredGrid *m_Grid) { if (node.size() < 3) EG_BUG; vec3_t xc(0,0,0); QVector<vec3_t> x(node.size()); for (int i = 0; i < node.size(); ++i) { m_Grid->GetPoint(node[i],x[i].data()); xc += x[i]; } xc *= 1.0/node.size(); vec3_t n(0,0,0); for (int i = 0; i < node.size()-1; ++i) { vec3_t a = x[i] - xc; vec3_t b = x[i+1] - xc; n += 0.5*(a.cross(b)); } vec3_t a = x[node.size()-1] - xc; vec3_t b = x[0] - xc; n += 0.5*(a.cross(b)); return n; }
void TPZHelmholtzComplex1D::Contribute(TPZMaterialData &data, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef) { TPZManVector<STATE,2> alphaval(1), betaval(1), phiaval(1); fAlpha->Execute(data.x, alphaval); fBeta->Execute(data.x, betaval); fPhi->Execute(data.x, phiaval); #ifdef LOG4CXX { std::stringstream sout; sout << "Coordenate x: " << data.x << " alpha = " << alphaval << " beta = " << betaval << " phi = " << phiaval; LOGPZ_DEBUG(logger, sout.str()); } #endif TPZFNMatrix<4, STATE> xk(1, 1), xb(1, 1), xc(1, 1, 0.), xf(1, 1); xk(0,0) = alphaval[0]; xb(0,0) = betaval[0]; xf(0,0) = -phiaval[0]; SetMaterial(xk, xc, xb, xf); TPZMat1dLin::Contribute(data, weight, ek, ef); }
void ReprojectionError3D::computeXc(const T * const _pp, const T * const _distortionParams, const T * const _focals, const T * const _xc, T *residuals) const { Eigen::Map<Eigen::Matrix<T, 3, 1>> xc((T*)_xc); Eigen::Map<Eigen::Matrix<T, 2, 1>> pp((T*)_pp); Eigen::Map<Eigen::Matrix<T, TDistortionParamVector::RowsAtCompileTime, 1>> distortionParams((T*)_distortionParams); Eigen::Map<Eigen::Matrix<T, 2, 1>> focals((T*)_focals); if (CeresUtils::ToDouble(xc[2]) <= 0) { //Negative point residuals[0] = T(1e3); residuals[1] = T(1e3); } else { //Point in front of camera, proceed Eigen::Matrix<T,2,1> p; CameraModel::ProjectFromWorld(pp, distortionParams, focals, xc, p); residuals[0] = (p[0] - T(mImgPoint[0])) / T(mScale); residuals[1] = (p[1] - T(mImgPoint[1])) / T(mScale); } }
int main(int argc,char *argv[]) { int i,j; double sum; printf("n e\n"); printf("- -----------\n"); for(i = 0;i < 10;i++) { sum = 0.0; for(j = 0;j <= i;j++) { if(0 == j) { sum += 1; } else { sum += xc(j); } } if(i <= 2) //格式控制 { printf("%d %g\n",i,sum); } else { printf("%d %.9g\n",i,sum); } } return 0; }
void OptCG::optimize() //------------------------------------------------------------------------ // Nonlinear Preconditioned Conjugate Gradient // // Given a nonlinear operator objfcn find the minimizer using a // nonlinear conjugate gradient method // This version uses the Polak-Ribiere formula. // and a line search routine due to More and Thuente as implemented // in the routines mcsrch and mcstep // // Notes: The parameters ftol and gtol should be set so that // 0 < ftol < gtol < 0.5 // Default values: ftol = 1.e-1, gtol = 5.e-1 // This results in a fairly accurate line search // // Here is the mathematical description of the algorithm // (g = grad f). // -1 // 1. set z = M g, search = -z; // // 2. for i=0 until convergence // // find alpha that minimizes f(x + alpha*search) // subject to the strong Wolfe conditions // // Test for convergence // // // beta = -( g , (z - z ) ) / ( g , z ) // i+1 i + 1 i i i // // search = - z + beta * search // i+1 i+1 i // //---------------------------------------------------------------------------- { int i, nlcg_iter; int convgd = 0; int step_type; double beta; double delta, delta_old, delta_mid, delta_new; double slope, gnorm; double step; double zero = 0.; // Allocate local vectors int n = dim; int maxiter; double fvalue; ColumnVector search(n), grad(n), z(n), diag(n), xc(n); // Initialize iteration maxiter = tol.getMaxIter(); initOpt(); if (ret_code == 0) { // compute preconditioned gradient diag = getFcnScale(); grad = nlp->getGrad(); for (i=1; i<=n; i++) z(i) = grad(i)/diag(i); search = -z; delta_old = delta_new = Dot(grad,z); gnorm = sqrt(Dot(grad,grad)); step = 1.0/gnorm; //--------------------------------------------------------------------------- // // // // //--------------------------------------------------------------------------- for (nlcg_iter=1; nlcg_iter <= maxiter; nlcg_iter++) { iter_taken = nlcg_iter; // compute a step along the direction search if ((step_type = computeStep(search)) < 0) { setMesg("Algorithm terminated - No longer able to compute step with sufficient decrease"); ret_code = step_type; setReturnCode(ret_code); return; } // Accept this step and update the nonlinear model acceptStep(nlcg_iter, step_type); updateModel(nlcg_iter, n, xprev); xc = nlp->getXc(); mem_step = xc - xprev; step = Norm2(mem_step); fvalue = nlp->getF(); grad = nlp->getGrad(); gnorm = sqrt(Dot(grad,grad)); slope = Dot(grad,search); // Test for Convergence convgd = checkConvg(); if (convgd > 0) { ret_code = convgd; setReturnCode(ret_code); *optout << d(nlcg_iter,5) << " " << e(fvalue,12,4) << " " << e(gnorm,12,4) << e(step,12,4) << "\n"; return; } // // compute a new search direction // 1. compute preconditioned gradient, z = grad; // 2. beta is computed using Polak-Ribiere Formula constrained // so that beta > 0 // 3 Update search direction and norms delta_old = delta_new; delta_mid = Dot(grad,z); for (i=1; i<=n; i++) z(i) = grad(i)/diag(i); delta_new = Dot(grad,z); delta = delta_new - delta_mid; beta = max(zero,delta/delta_old); search = -z + search*beta; xprev = nlp->getXc(); fprev = fvalue; gprev = grad; *optout << d(nlcg_iter,5) << " " << e(fvalue,12,4) << " " << e(gnorm,12,4) << e(step,12,4) << " " << e(beta,12,4) << " " << e(slope,12,4) << d(fcn_evals,4) << " " << d(grad_evals,4) << endl; } setMesg("Algorithm terminated - Number of iterations exceeds the specified limit"); ret_code = 4; setReturnCode(ret_code); } }
void BinaryStar::set_refine_flags() { double refine_adjustment = 1; ChildIndex c; if (get_level() < 1) { for (int i = 0; i < OCT_NCHILD; i++) { set_refine_flag(i, true); } } else if (get_level() < get_max_level_allowed()) { Real mass_min, dxmin, vmin, this_mass; dxmin = dynamic_cast<BinaryStar*>(get_root())->get_dx() / Real(1 << OctNode::get_max_level_allowed()); vmin = dxmin * dxmin * dxmin; mass_min = refine_floor * vmin * refine_adjustment; for (int k = BW; k < GNX - BW; k++) { c.set_z(2 * k / GNX); for (int j = BW; j < GNX - BW; j++) { c.set_y(2 * j / GNX); for (int i = BW; i < GNX - BW; i++) { c.set_x(2 * i / GNX); #ifdef REFINE_ACC_MORE if ((get_level() == get_max_level_allowed() - 1 && (*this)(i, j, k).frac(0) > refine_floor * refine_adjustment) || get_level() < get_max_level_allowed() - 1) { #else if (get_level() < get_max_level_allowed()) { #endif if (!get_refine_flag(c)) { // set_refine_flag(c, true); Real ra = (X(i, j, k) - bparam.x1).mag(); Real rd = (X(i, j, k) - bparam.x2).mag(); if ((*this)(i, j, k).rho() > refine_floor * refine_adjustment) { set_refine_flag(c, true); } else if (get_time() == 0.0 && (ra < get_dx() || rd < get_dx())) { set_refine_flag(c, true); } else/* if (get_time() != 0.0)*/{ this_mass = pow(get_dx(), 3) * (*this)(i, j, k).rho(); if (this_mass > mass_min) { set_refine_flag(c, true); } } } } } } } } } /* void BinaryStar::set_refine_flags() { ChildIndex c; if (get_level() < 1) { for (int i = 0; i < OCT_NCHILD; i++) { set_refine_flag(i, true); } } else if (get_level() < get_max_level_allowed()) { Real mass_min, dxmin, vmin, this_mass; dxmin = dynamic_cast<BinaryStar*>(get_root())->get_dx() / Real(1 << OctNode::get_max_level_allowed()); vmin = dxmin * dxmin * dxmin; mass_min = refine_floor * vmin; for (int k = BW; k < GNX - BW; k++) { c.set_z(2 * k / GNX); for (int j = BW; j < GNX - BW; j++) { c.set_y(2 * j / GNX); for (int i = BW; i < GNX - BW; i++) { c.set_x(2 * i / GNX); if ((get_level() == get_max_level_allowed() - 1 && (*this)(i, j, k).frac(0) > refine_floor) || get_level() < get_max_level_allowed() - 1) { if (!get_refine_flag(c)) { // set_refine_flag(c, true); Real ra = (X(i, j, k) - a0).mag(); Real rd = (X(i, j, k) - d0).mag(); if ((*this)(i, j, k).rho() > refine_floor) { set_refine_flag(c, true); } else if (get_time() == 0.0 && (ra < get_dx() || rd < get_dx())) { set_refine_flag(c, true); } else{ this_mass = pow(get_dx(), 3) * (*this)(i, j, k).rho(); if (this_mass > mass_min) { set_refine_flag(c, true); } } } } } } } } } */ void BinaryStar::initialize() { if (!bparam_init) { bparam_init = true; bparam.fill_factor = 0.97; binary_parameters_compute(&bparam); State::rho_floor = 1.0e-12 * bparam.rho1; refine_floor = 1.0e-4 * bparam.rho1; dynamic_cast<HydroGrid*>(get_root())->HydroGrid::mult_dx(bparam.a * 5.0); #ifndef USE_FMM dynamic_cast<MultiGrid*>(get_root())->MultiGrid::mult_dx(bparam.a * 5.0); #endif State::set_omega(bparam.omega); } for (int k = BW - 1; k < GNX - BW + 1; k++) { for (int j = BW - 1; j < GNX - BW + 1; j++) { for (int i = BW - 1; i < GNX - BW + 1; i++) { int id; State U = Vector<Real, STATE_NF>(0.0); Real R2 = (xc(i) * xc(i) + yc(j) * yc(j)); Real rho = density_at(&bparam, xc(i), yc(j), zc(k), &id); rho = max(rho, State::rho_floor); Real tau = pow(State::ei_floor, 1.0 / State::gamma); U.set_rho(rho); U.set_et(U.ed()); U.set_tau(tau); U.set_sx(0.0); U.set_sy(bparam.omega * R2 * U.rho()); U.set_sz(0.0); if (id == 1) { U.set_frac(0, U.rho()); U.set_frac(1, 0.0); } else if (id == -1) { U.set_frac(1, U.rho()); U.set_frac(0, 0.0); } else { U.set_frac(1, 0.0); U.set_frac(0, 0.0); } (*this)(i, j, k) = U; } } } /*Real K, E1, E2, period, rho_c1, rho_c2; a0 = d0 = 0.0; if (scf_code) { const Real a = 0.075; const Real R2 = 0.0075; const Real n = 1.5; rho_c2 = q_ratio * M1 * (pow(3.65375 / R2, 3.0) / (2.71406 * 4.0 * M_PI)); rho_c1 = rho_c2 / pow(q_ratio, 2.0 * n / (3.0 - n)); a0[0] = a * q_ratio / (q_ratio + 1.0); d0[0] = -a / (q_ratio + 1.0); K = pow(R2 / 3.65375, 2) * 4.0 * M_PI / (2.5) * pow(rho_c2, 1.0 / 3.0); Ka = Kd = (5.0 / 8.0) * K; polyK = K; E1 = 1.0 / (sqrt((4.0 * M_PI * pow(rho_c1, 1.0 - 1.0 / n)) / ((n + 1.0) * K))); E2 = 1.0 / (sqrt((4.0 * M_PI * pow(rho_c2, 1.0 - 1.0 / n)) / ((n + 1.0) * K))); // printf("%e %e %e %e\n", rho_c1, rho_c2, E1, E2); period = sqrt(pow(a, 3) / (q_ratio + 1.0) / M1) * 2.0 * M_PI; } else { rho_c1 = rho_c2 = 1.0; a0[0] = 0.025; d0[0] = -0.025; E1 = E2 = 0.0015; K = pow(E1, 2) * 4.0 * M_PI / (2.5); period = sqrt(pow((a0 - d0).mag(), 3) / 2.303394e-07) * 2.0 * M_PI; } State U; Real d, e, gamma, tau; gamma = 5.0 / 3.0; Real ra, rd, r0, ek; _3Vec v; const Real Omega = 2.0 * M_PI / period; State::set_omega(Omega); Real f1, f2; if (get_level() == 0) { printf("Period = %e Omega = %e\n", period, Omega); } Real d_floor = 10.0 * State::rho_floor; for (int k = BW - 1; k < GNX - BW + 1; k++) { for (int j = BW - 1; j < GNX - BW + 1; j++) { for (int i = BW - 1; i < GNX - BW + 1; i++) { U = Vector<Real, STATE_NF>(0.0); ra = (X(i, j, k) - a0).mag(); rd = (X(i, j, k) - d0).mag(); d = +rho_c1 * pow(lane_emden(ra / E1), 1.5); d += rho_c2 * pow(lane_emden(rd / E2), 1.5); d = max(d, d_floor); if (ra < rd) { f1 = d - d_floor / 2.0; f2 = d_floor / 2.0; } else { f2 = d - d_floor / 2.0; f1 = d_floor / 2.0; } if (State::cylindrical) { Real R2 = (HydroGrid::xc(i) * HydroGrid::xc(i) + HydroGrid::yc(j) * HydroGrid::yc(j)); v[0] = 0.0; v[1] = R2 * State::get_omega(); } else { v[0] = -HydroGrid::yc(j) * State::get_omega(); v[1] = +HydroGrid::xc(i) * State::get_omega(); } v[2] = 0.0; e = K * pow(d, gamma) / (gamma - 1.0); tau = pow(e, 1.0 / gamma); U.set_rho(d); U.set_frac(0, f1); U.set_frac(1, f2); U.set_et(e); U.set_tau(tau); U.set_sx(d * v[0]); U.set_sy(d * v[1]); U.set_sz(d * v[2]); (*this)(i, j, k) = U; } } } */ }
Real BinaryStar::radius(int i, int j, int k) { return sqrt(xc(i) * xc(i) + yc(j) * yc(j) + zc(k) * zc(k)); }
void StrandBlockSolver::rhsViscousFine() { int c1,c2,n1,n2,fc,jm,jp,npts=1; double dx1,dy1,dx2,dy2,ds,dq1,dq2,eps=1.e-14, qxe[nq],qye[nq],qaxe[nqa],qaye[nqa],qe[nq],qae[nqa],fv[nq]; // unstructured faces for (int n=0; n<nEdges; n++){ c1 = edge(0,n); c2 = edge(1,n); n1 = edgn(n); fc = fClip(c1); if (fClip(c2) > fc) fc = fClip(c2); for (int j=1; j<fc+1; j++){ jm = j-1; dx1 = x (0,j,n1)-x (0,jm,n1); dy1 = x (1,j,n1)-x (1,jm,n1); dx2 = xc(0,j,c2)-xc(0,j ,c1); dy2 = xc(1,j,c2)-xc(1,j ,c1); ds = 1./(dx1*dy2-dx2*dy1); for (int k=0; k<nq; k++){ dq1 = qp(k,j,n1)-qp(k,jm,n1); dq2 = q (k,j,c2)-q (k,j ,c1); qxe[k] = ds*( dy2*dq1-dy1*dq2); qye[k] = ds*(-dx2*dq1+dx1*dq2); qe[k] = .5*(qp (k,j,n1)+qp (k,jm,n1)); } for (int k=0; k<nqa; k++){ dq1 = qap(k,j,n1)-qap(k,jm,n1); dq2 = qa (k,j,c2)-qa (k,j ,c1); qaxe[k] = ds*( dy2*dq1-dy1*dq2); qaye[k] = ds*(-dx2*dq1+dx1*dq2); qae[k] = .5*(qap(k,j,n1)+qap(k,jm,n1)); } sys->rhsVisFlux(npts,&facs(0,j,n),&qe[0],&qae[0],&qxe[0],&qye[0], &qaxe[0],&qaye[0],&fv[0]); for (int k=0; k<nq; k++){ r(k,j,c1) -= fv[k]; r(k,j,c2) += fv[k]; }}} // structured faces for (int n=0; n<nFaces-nGfaces; n++){ n1 = face(0,n); n2 = face(1,n); for (int j=0; j<fClip(n)+1; j++){ jp = j+1; dx1 = x (0,j ,n2)-x (0,j,n1); dy1 = x (1,j ,n2)-x (1,j,n1); dx2 = xc(0,jp,n )-xc(0,j,n ); dy2 = xc(1,jp,n )-xc(1,j,n ); ds = dx1*dy2-dx2*dy1; if (fabs(ds) < eps) for (int k=0; k<nq; k++) fv[k] = 0.; else{ ds = 1./ds; for (int k=0; k<nq; k++){ dq1 = qp(k,j ,n2)-qp(k,j,n1); dq2 = q (k,jp,n )-q (k,j,n ); qxe[k] = ds*( dy2*dq1-dy1*dq2); qye[k] = ds*(-dx2*dq1+dx1*dq2); qe[k] = .5*(qp (k,j,n1)+qp (k,j,n2)); } for (int k=0; k<nqa; k++){ dq1 = qap(k,j ,n2)-qap(k,j,n1); dq2 = qa (k,jp,n )-qa (k,j,n ); qaxe[k] = ds*( dy2*dq1-dy1*dq2); qaye[k] = ds*(-dx2*dq1+dx1*dq2); qae[k] = .5*(qap(k,j,n1)+qap(k,j,n2)); } sys->rhsVisFlux(npts,&facu(0,j,n),&qe[0],&qae[0],&qxe[0],&qye[0], &qaxe[0],&qaye[0],&fv[0]); } for (int k=0; k<nq; k++){ r(k,j ,n) -= fv[k]; r(k,jp,n) += fv[k]; }}} }
bool HomotopyConcrete< RT, FixedPrecisionHomotopyAlgorithm >::track(const MutableMatrix* inputs, MutableMatrix* outputs, MutableMatrix* output_extras, gmp_RR init_dt, gmp_RR min_dt, gmp_RR epsilon, // o.CorrectorTolerance, int max_corr_steps, gmp_RR infinity_threshold ) { std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); size_t solveLinearTime = 0, solveLinearCount = 0, evaluateTime = 0; // std::cout << "inside HomotopyConcrete<RT,FixedPrecisionHomotopyAlgorithm>::track" << std::endl; // double the_smallest_number = 1e-13; const Ring* matRing = inputs->get_ring(); if (outputs->get_ring()!= matRing) { ERROR("outputs and inputs are in different rings"); return false; } auto inp = dynamic_cast<const MutableMat< DMat<RT> >*>(inputs); auto out = dynamic_cast<MutableMat< DMat<RT> >*>(outputs); auto out_extras = dynamic_cast<MutableMat< DMat<M2::ARingZZGMP> >*>(output_extras); if (inp == nullptr) { ERROR("inputs: expected a dense mutable matrix"); return false; } if (out == nullptr) { ERROR("outputs: expected a dense mutable matrix"); return false; } if (out_extras == nullptr) { ERROR("output_extras: expected a dense mutable matrix"); return false; } auto& in = inp->getMat(); auto& ou = out->getMat(); auto& oe = out_extras->getMat(); size_t n_sols = in.numColumns(); size_t n = in.numRows()-1; // number of x vars if (ou.numColumns() != n_sols or ou.numRows() != n+2) { ERROR("output: wrong shape"); return false; } if (oe.numColumns() != n_sols or oe.numRows() != 2) { ERROR("output_extras: wrong shape"); return false; } const RT& C = in.ring(); typename RT::RealRingType R = C.real_ring(); typedef typename RT::ElementType ElementType; typedef typename RT::RealRingType::ElementType RealElementType; typedef MatElementaryOps< DMat< RT > > MatOps; RealElementType t_step; RealElementType min_step2; RealElementType epsilon2; RealElementType infinity_threshold2; R.init(t_step); R.init(min_step2); R.init(epsilon2); R.init(infinity_threshold2); R.set_from_BigReal(t_step,init_dt); // initial step R.set_from_BigReal(min_step2,min_dt); R.mult(min_step2, min_step2, min_step2); //min_step^2 R.set_from_BigReal(epsilon2,epsilon); int tolerance_bits = -R.log2abs(epsilon2); R.mult(epsilon2, epsilon2, epsilon2); //epsilon^2 R.set_from_BigReal(infinity_threshold2,infinity_threshold); R.mult(infinity_threshold2, infinity_threshold2, infinity_threshold2); int num_successes_before_increase = 3; RealElementType t0,dt,one_minus_t0,dx_norm2,x_norm2,abs2dc; R.init(t0); R.init(dt); R.init(one_minus_t0); R.init(dx_norm2); R.init(x_norm2); R.init(abs2dc); // constants RealElementType one,two,four,six,one_half,one_sixth; RealElementType& dt_factor = one_half; R.init(one); R.set_from_long(one,1); R.init(two); R.set_from_long(two,2); R.init(four); R.set_from_long(four,4); R.init(six); R.set_from_long(six,6); R.init(one_half); R.divide(one_half,one,two); R.init(one_sixth); R.divide(one_sixth,one,six); ElementType c_init,c_end,dc,one_half_dc; C.init(c_init); C.init(c_end); C.init(dc); C.init(one_half_dc); // think: x_0..x_(n-1), c // c = the homotopy continuation parameter "t" upstair, varies on a (staight line) segment of complex plane (from c_init to c_end) // t = a real running in the interval [0,1] DMat<RT> x0c0(C,n+1,1); DMat<RT> x1c1(C,n+1,1); DMat<RT> xc(C,n+1,1); DMat<RT> HxH(C,n,n+1); DMat<RT>& Hxt = HxH; // the matrix has the same shape: reuse memory DMat<RT> LHSmat(C,n,n); auto LHS = submatrix(LHSmat); DMat<RT> RHSmat(C,n,1); auto RHS = submatrix(RHSmat); DMat<RT> dx(C,n,1); DMat<RT> dx1(C,n,1); DMat<RT> dx2(C,n,1); DMat<RT> dx3(C,n,1); DMat<RT> dx4(C,n,1); DMat<RT> Jinv_times_random(C,n,1); ElementType& c0 = x0c0.entry(n,0); ElementType& c1 = x1c1.entry(n,0); ElementType& c = xc.entry(n,0); RealElementType& tol2 = epsilon2; // current tolerance squared bool linearSolve_success; for(size_t s=0; s<n_sols; s++) { SolutionStatus status = PROCESSING; // set initial solution and initial value of the continuation parameter //for(size_t i=0; i<=n; i++) // C.set(x0c0.entry(i,0), in.entry(i,s)); submatrix(x0c0) = submatrix(const_cast<DMat<RT>&>(in), 0,s, n+1,1); C.set(c_init,c0); C.set(c_end,ou.entry(n,s)); R.set_zero(t0); bool t0equals1 = false; // t_step is actually the initial (absolute) length of step on the interval [c_init,c_end] // dt is an increment for t on the interval [0,1] R.set(dt,t_step); C.subtract(dc,c_end,c_init); C.abs(abs2dc,dc); // don't wnat to create new temporary elts: reusing dc and abs2dc R.divide(dt,dt,abs2dc); int predictor_successes = 0; int count = 0; // number of steps // track the real segment (1-t)*c0 + t*c1, a\in [0,1] while (status == PROCESSING and not t0equals1) { if (M2_numericalAlgebraicGeometryTrace>3) { buffer o; R.elem_text_out(o,t0,true,false,false); std::cout << "t0 = " << o.str(); o.reset(); C.elem_text_out(o,c0,true,false,false); std::cout << ", c0 = " << o.str() << std::endl; } R.subtract(one_minus_t0,one,t0); if (R.compare_elems(dt,one_minus_t0)>0) { R.set(dt,one_minus_t0); t0equals1 = true; C.subtract(dc,c_end,c0); C.set(c1,c_end); } else { C.subtract(dc,c_end,c0); C.mult(dc,dc,dt); C.divide(dc,dc,one_minus_t0); C.add(c1,c0,dc); } // PREDICTOR in: x0c0,dt // out: dx /* top-level code for Runge-Kutta-4 dx1 := solveHxTimesDXequalsMinusHt(x0,t0); dx2 := solveHxTimesDXequalsMinusHt(x0+(1/2)*dx1*dt,t0+(1/2)*dt); dx3 := solveHxTimesDXequalsMinusHt(x0+(1/2)*dx2*dt,t0+(1/2)*dt); dx4 := solveHxTimesDXequalsMinusHt(x0+dx3*dt,t0+dt); (1/6)*dt*(dx1+2*dx2+2*dx3+dx4) */ C.mult(one_half_dc, dc, one_half); // dx1 submatrix(xc) = submatrix(x0c0); TIME(evaluateTime, mHxt.evaluate(xc,Hxt) ) LHS = submatrix(Hxt, 0,0, n,n); RHS = submatrix(Hxt, 0,n, n,1); MatrixOps::negateInPlace(RHSmat); TIME(solveLinearTime, linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx1) ); solveLinearCount++; // dx2 if (linearSolve_success) { submatrix(dx1) *= one_half_dc; // "dx1" := (1/2)*dx1*dt submatrix(xc, 0,0, n,1) += submatrix(dx1); C.add(c,c,one_half_dc); TIME(evaluateTime, mHxt.evaluate(xc,Hxt) ) LHS = submatrix(Hxt, 0,0, n,n); RHS = submatrix(Hxt, 0,n, n,1); MatrixOps::negateInPlace(RHSmat); TIME(solveLinearTime, linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx2); ) solveLinearCount++; } // dx3 if (linearSolve_success) { submatrix(dx2) *= one_half_dc; // "dx2" := (1/2)*dx2*dt submatrix(xc, 0,0, n,1) = submatrix(x0c0, 0,0, n,1); submatrix(xc, 0,0, n,1) += submatrix(dx2); // C.add(c,c,one_half_dc); // c should not change here??? or copy c two lines above??? TIME(evaluateTime, mHxt.evaluate(xc,Hxt) ); LHS = submatrix(Hxt, 0,0, n,n); RHS = submatrix(Hxt, 0,n, n,1); MatrixOps::negateInPlace(RHSmat); TIME(solveLinearTime, linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx3); ); solveLinearCount++; } // dx4 if (linearSolve_success) { submatrix(dx3) *= dc; // "dx3" := dx3*dt submatrix(xc) = submatrix(x0c0); // sets c=c0 as well (not needed for dx2???,dx3) submatrix(xc, 0,0, n,1) += submatrix(dx3); C.add(c,c,dc); TIME(evaluateTime, mHxt.evaluate(xc,Hxt) ); LHS = submatrix(Hxt, 0,0, n,n); RHS = submatrix(Hxt, 0,n, n,1); MatrixOps::negateInPlace(RHSmat); TIME(solveLinearTime, linearSolve_success = MatrixOps::solveLinear(LHSmat,RHSmat,dx4); ); solveLinearCount++; }
bool TuneForBest(int maxIteration, double tol = 1E8 * std::numeric_limits<float>::epsilon(), std::vector<std::vector<float> > x = std::vector< std::vector<float> >()) { std::vector<float> init; for(size_t pi=0;pi<paramsCount;pi++) { init.push_back(parameters[pi].data); } int N = paramsCount; //space dimension const double a = 1.0, b = 1.0, g = 0.5, h = 0.5; //coefficients //a: reflection -> xr //b: expansion -> xe //g: contraction -> xc //h: full contraction to x1 std::vector<float> xcentroid_old(N, 0); //simplex center * (N+1) std::vector<float> xcentroid_new(N, 0); //simplex center * (N+1) std::vector<float> vf(N + 1, 0); //f evaluated at simplex vertexes int x1 = 0, xn = 0, xnp1 = 0; //x1: f(x1) = min { f(x1), f(x2)...f(x_{n+1} } //xnp1: f(xnp1) = max { f(x1), f(x2)...f(x_{n+1} } //xn: f(xn)<f(xnp1) && f(xn)> all other f(x_i) int cnt = 0; //iteration step number if (x.size() == 0) //if no initial simplex is specified { //construct the trial simplex //based upon the initial guess parameters std::vector<float> del(init); std::transform(del.begin(), del.end(), del.begin(), std::bind2nd(std::divides<float>(), 20)); //'20' is picked //assuming initial trail close to true for (int i = 0; i < N; ++i) { std::vector<float> tmp(init); tmp[i] += del[i]; x.push_back(tmp); } x.push_back(init); //x.size()=N+1, x[i].size()=N //xcentriod std::transform(init.begin(), init.end(), xcentroid_old.begin(), std::bind2nd(std::multiplies<float>(), N + 1)); } //constructing the simplex finished //optimization begins for (cnt = 0; cnt < maxIteration; ++cnt) { for (int i = 0; i < N + 1; ++i) { vf[i] = (obj.*pFunc)(x[i]); } x1 = 0; xn = 0; xnp1 = 0; //find index of max, second max, min of vf. for (size_t i = 0; i < vf.size(); ++i) { if (vf[i] < vf[x1]) { x1 = i; } if (vf[i] > vf[xnp1]) { xnp1 = i; } } xn = x1; for (size_t i = 0; i < vf.size(); ++i) { if (vf[i] < vf[xnp1] && vf[i] > vf[xn]) xn = i; } //x1, xn, xnp1 are found std::vector<float> xg(N, 0); //xg: centroid of the N best vertexes for (size_t i = 0; i < x.size(); ++i) { if (i != (size_t)xnp1) std::transform(xg.begin(), xg.end(), x[i].begin(), xg.begin(), std::plus<float>()); } std::transform(xg.begin(), xg.end(), x[xnp1].begin(), xcentroid_new.begin(), std::plus<float>()); std::transform(xg.begin(), xg.end(), xg.begin(), std::bind2nd(std::divides<float>(), N)); //xg found, xcentroid_new updated //termination condition float diff = 0; //calculate the difference of the simplex centers //see if the difference is less than the termination criteria for (int i = 0; i < N; ++i) diff += fabs(xcentroid_old[i] - xcentroid_new[i]); if (diff / N < tol) break; //terminate the optimizer else xcentroid_old.swap(xcentroid_new); //update simplex center //reflection: std::vector<float> xr(N, 0); for (int i = 0; i < N; ++i) xr[i] = xg[i] + a * (xg[i] - x[xnp1][i]); //reflection, xr found float fxr = (obj.*pFunc)(xr); //record function at xr if (vf[x1] <= fxr && fxr <= vf[xn]) std::copy(xr.begin(), xr.end(), x[xnp1].begin()); //expansion: else if (fxr < vf[x1]) { std::vector<float> xe(N, 0); for (int i = 0; i < N; ++i) xe[i] = xr[i] + b * (xr[i] - xg[i]); if ((obj.*pFunc)(xe) < fxr) std::copy(xe.begin(), xe.end(), x[xnp1].begin()); else std::copy(xr.begin(), xr.end(), x[xnp1].begin()); } //expansion finished, xe is not used outside the scope //contraction: else if (fxr > vf[xn]) { std::vector<float> xc(N, 0); for (int i = 0; i < N; ++i) xc[i] = xg[i] + g * (x[xnp1][i] - xg[i]); if ((obj.*pFunc)(xc) < vf[xnp1]) std::copy(xc.begin(), xc.end(), x[xnp1].begin()); else { for (size_t i = 0; i < x.size(); ++i) { if (i != (size_t)x1) { for (int j = 0; j < N; ++j) x[i][j] = x[x1][j] + h * (x[i][j] - x[x1][j]); } } } } //contraction finished, xc is not used outside the scope } //optimization is finished for(size_t pi=0;pi<x[x1].size();pi++) { parameters[pi].data = x[x1][pi]; } cout << " Tune counter = " << cnt << endl; if (cnt == maxIteration) { return false; } return true; }
void RegularizedHingeIntegration::getWeightsDeriv(int numSections, double L, double dLdh, double *dwtsdh) { double oneOverL = 1.0/L; const int Nc = 4; int Nf = numSections - Nc; double dxcdh[Nc]; double dwcdh[Nc]; double dxfdh[100]; for (int i = 0; i < numSections; i++) { dwtsdh[i] = 0.0; dxfdh[i] = 0.0; } for (int i = 0; i < Nc; i++) { dwcdh[i] = 0.0; dxcdh[i] = 0.0; } if (parameterID == 1 || parameterID == 3) { // lpI dwcdh[0] = oneOverL; dwcdh[1] = -oneOverL; } if (parameterID == 2 || parameterID == 3) { // lpJ dwcdh[2] = -oneOverL; dwcdh[3] = oneOverL; } if (parameterID == 4 || parameterID == 6) // epsI dxcdh[1] = oneOverL; if (parameterID == 5 || parameterID == 6) // epsJ dxcdh[2] = -oneOverL; dwtsdh[0] = dwcdh[0]; dwtsdh[1] = dwcdh[1]; dwtsdh[2] = dwcdh[2]; dwtsdh[3] = dwcdh[3]; if (Nf > 0) { double wt[100]; this->getSectionWeights(numSections, L, wt); double pt[100]; this->getSectionLocations(numSections, L, pt); Vector wc(wt, Nc); Vector xc(pt, Nc); Vector xf(&pt[Nc], Nf); Vector R(Nf); double sum = 0.0; for (int j = 0; j < Nc; j++) sum += dwcdh[j]; R(0) = -sum; for (int i = 1; i < Nf; i++) { sum = 0.0; for (int j = 0; j < Nf; j++) sum += i*pow(xf(j),i-1)*dxfdh[j]*wt[Nc+j]; for (int j = 0; j < Nc; j++) sum += i*pow(xc(j),i-1)*dxcdh[j]*wc[j]; for (int j = 0; j < Nc; j++) sum += pow(xc(j),i)*dwcdh[j]; R(i) = -sum; } Matrix J(Nf,Nf); for (int i = 0; i < Nf; i++) for (int j = 0; j < Nf; j++) J(i,j) = pow(xf(j),i); Vector dwfdh(Nf); J.Solve(R,dwfdh); for (int i = 0; i < Nf; i++) dwtsdh[i+Nc] = dwfdh(i); } if (dLdh != 0.0) { // STILL TO DO opserr << "getWeightsDeriv -- to do" << endln; } return; }
void StrandBlockSolver::lspMap() { int mm,nn,jj,ii,j1,j2,jm,jmax,nmax,info,ldu,ldvt,rows,cols,lwork; double dsm,dx,dy,ds,w,r1,r2,rs,cond,rcond,xn,yn,ax,ay,xu,xl,bu,bl,xcn,ycn; double b[4]; double* sv; double* work1; double* uu; double* vt; double* dr; double** lspT; char u='U',jobu='n',jobvt='a'; cond = 0.; ldu = 1; ldvt = 2; cols = 2; for (int n=0; n<nNodes-nGnodes; n++){ mm = ncsp(n); rows = mm; ii = cols; if (rows < ii) ii = rows; jj = cols; if (rows > jj) jj = rows; lwork = 1; if (3*ii+jj > lwork) lwork = 3*ii+jj; if (5*ii > lwork) lwork = 5*ii; uu = new double[ldu*ldu]; sv = new double[cols]; vt = new double[ldvt*cols]; work1 = new double[lwork]; dr = new double[rows*2]; lspT = new double*[nPstr+1]; for (int j=0; j<nPstr+1; j++) lspT[j] = new double[rows]; rcond = 0.; info = 0; for (int m=0; m<ldu*ldu; m++) uu [m] = 0.; for (int m=0; m<cols; m++) sv [m] = 0.; for (int m=0; m<ldvt*cols; m++) vt [m] = 0.; for (int m=0; m<lwork; m++) work1[m] = 0.; double work [2] = {0.,0.}; double work2[4] = {0.,0.,0.,0.}; int iwork[2] = {0,0}; int ipiv [2] = {0,0}; for (int j=1; j<nPstr+1; j++){ //mid strand nodes // coordinates of the mid-strand location in question jm = j-1; xn = .5*(x(0,j,n)+x(0,jm,n)); yn = .5*(x(1,j,n)+x(1,jm,n)); // find data centroid xcn = 0.; ycn = 0.; for (int m=0; m<mm; m++){ nn = csp[n][m]; xcn = xcn+xc(0,j,nn); ycn = ycn+xc(1,j,nn); } xcn = xcn/double(mm); ycn = ycn/double(mm); // find plane which most closely fits surrounding cell centers for (int m=0; m<mm; m++){ nn = csp[n][m]; dr[m ] = xc(0,j,nn)-xcn; dr[m+mm] = xc(1,j,nn)-ycn; } sgesvd_(jobu,jobvt,rows,cols,dr,rows,sv,uu,ldu,vt,ldvt,work1,lwork,info); if (info != 0){ cout << "\n*** svd procedure failure in lspMap ***" << endl; exit(0); } ax = vt[0]; ay = vt[2]; ds = 1./sqrt(ax*ax+ay*ay); ax = ax*ds; ay = ay*ds; // compute 2d least squares problem with projected distances // largest distance in stencil dsm = 0.; for (int m=0; m<mm; m++){ nn = csp[n][m]; dx = xc(0,j,nn)-xn; dy = xc(1,j,nn)-yn; ds = dx*ax+dy*ay; ds = ds*ds; if (ds > dsm) dsm = ds; } dsm = 1./sqrt(dsm); // form least squares matrix jj = jm; for (int m=0; m<4; m++) b[m] = 0.; for (int m=0; m<mm; m++){ nn = csp[n][m]; dx = xc(0,j,nn)-xn; dy = xc(1,j,nn)-yn; ds =(dx*ax+dy*ay)*dsm; w = 1./(ds*ds); b[0] = b[0]+w; b[2] = b[2]+w*ds; b[3] = b[3]+w*ds*ds; } // find max abs row sum for condition number computation r1 = fabs(b[0])+fabs(b[2]); r2 = fabs(b[1])+fabs(b[3]); rs = r1; if (r2 > rs) rs = r2; // invert matrix and determine condition number ii = 2; ssytrf_(u,ii,b,ii,ipiv,work,ii,info); ssycon_(u,ii,b,ii,ipiv,rs,rcond,work2,iwork,info); ssytri_(u,ii,b,ii,ipiv,work,info); rcond = 1./rcond; if (rcond > cond){ nmax = n; jmax = j; cond = rcond; } // form and store least squares coefficient for (int m=0; m<mm; m++){ nn = csp[n][m]; dx = xc(0,j,nn)-xn; dy = xc(1,j,nn)-yn; ds =(dx*ax+dy*ay)*dsm; w = 1./(ds*ds); lspT[j][m] =(b[0]*w + b[2]*w*ds); } } // interpolate projected coefficients to the nodal positions along each strand for (int j=0; j<nPstr+1; j++){ if (j == 0 ){ j1 = 1; j2 = 2; } else if (j == nPstr){ j1 = nPstr-1; j2 = nPstr; } else{ j1 = j; j2 = j+1; } xn = xStr(j); jm = j1-1; xl = .5*(xStr(jm)+xStr(j1)); jm = j2-1; xu = .5*(xStr(jm)+xStr(j2)); bl =(xu-xn)/(xu-xl); bu =(xn-xl)/(xu-xl); indlsp(0,j,n,ii); for (int m=0; m<mm; m++){ lsp[ii ][m] = bl*lspT[j1][m]; lsp[ii+1][m] = bu*lspT[j2][m]; } } delete [] sv; delete [] uu; delete [] vt; delete [] work1; delete [] dr; for (int j=0; j<nPstr+1; j++) delete [] lspT[j]; delete [] lspT; } // output condition information xn = x(0,jmax,nmax); yn = x(1,jmax,nmax); cout << "\nMaximum condition number for LS procedure: " << cond << endl << "Index of maximum condition number: " << nmax << "\t" << jmax << endl << "Coordinates of maximum condition number: " << xn << "\t" << yn << "\n" << endl; /* // try using volume averaging on outer boundary nodes for (int n=0; n<nNodes-nGnodes; n++){ mm = ncsp(n); for (int j=nPstr; j<nPstr+1; j++){ if (j == 0 ) jj = 1; else if (j == nPstr) jj = nPstr-1; else jj = j; w = 0.; for (int k=0; k<2; k++){ indlsp(k,j,n,ii); for (int m=0; m<mm; m++){ nn = csp[n][m]; lsp[ii][m] = v(jj,nn); w += v(jj,nn); } jj++; } w = 1./w; for (int k=0; k<2; k++){ indlsp(k,j,n,ii); for (int m=0; m<mm; m++){ lsp[ii][m] = lsp[ii][m]*w; }}}} */ }
void TPZSurface::MakeSphereFromQuadrilateral() { fgeometricmesh = new TPZGeoMesh; fgeometricmesh->SetDimension(fdimension); int nodes = 8; fgeometricmesh->SetMaxNodeId(nodes-1); fgeometricmesh->NodeVec().Resize(nodes); TPZManVector<TPZGeoNode,4> Node(nodes); TPZManVector<int64_t,2> TopolQuad(4); TPZManVector<REAL,3> coord(3,0.); TPZVec<REAL> xc(3,0.); REAL cphi = atan(sqrt(2.0)); int nodeindex = 0; coord = ParametricSphere(Pi-cphi,Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(cphi,Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(cphi,-Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi-cphi,-Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi-cphi,3.0*Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(cphi,3.0*Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(cphi,-3.0*Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi-cphi,-3.0*Pi/4.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; int id = 0; int matid = 1; TopolQuad[0] = 0; TopolQuad[1] = 1; TopolQuad[2] = 2; TopolQuad[3] = 3; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad1 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad1->Geom().SetData(fradius, xc); id++; TopolQuad[0] = 4; TopolQuad[1] = 5; TopolQuad[2] = 6; TopolQuad[3] = 7; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad2 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad2->Geom().SetData(fradius, xc); id++; TopolQuad[0] = 0; TopolQuad[1] = 4; TopolQuad[2] = 5; TopolQuad[3] = 1; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad3 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad3->Geom().SetData(fradius, xc); id++; TopolQuad[0] = 3; TopolQuad[1] = 7; TopolQuad[2] = 6; TopolQuad[3] = 2; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad4 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad4->Geom().SetData(fradius, xc); id++; TopolQuad[0] = 0; TopolQuad[1] = 4; TopolQuad[2] = 7; TopolQuad[3] = 3; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad5 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad5->Geom().SetData(fradius, xc); id++; TopolQuad[0] = 1; TopolQuad[1] = 5; TopolQuad[2] = 6; TopolQuad[3] = 2; TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > * quad6 = new TPZGeoElRefPattern< pzgeom::TPZQuadSphere< pzgeom::TPZGeoQuad > > (id,TopolQuad,matid,*fgeometricmesh); quad6->Geom().SetData(fradius, xc); id++; fgeometricmesh->BuildConnectivity(); }
int main(int argc, char **argv) { ap::real_1d_array x; ap::real_1d_array y; ap::real_1d_array w; ap::real_1d_array xc; ap::real_1d_array yc; ap::integer_1d_array dc; int n; int i; int info; spline1dinterpolant s; double t; spline1dfitreport rep; // // Fitting by constrained Hermite spline // printf("FITTING BY CONSTRAINED HERMITE SPLINE\n\n"); printf("F(x)=sin(x) function being fitted\n"); printf("[0, pi] interval\n"); printf("M=6 number of basis functions to use\n"); printf("S(0)=0 first constraint\n"); printf("S(pi)=0 second constraint\n"); printf("N=100 number of points to fit\n"); // // Create and fit: // * X contains points // * Y contains values // * W contains weights // * XC contains constraints locations // * YC contains constraints values // * DC contains derivative indexes (0 = constrained function value) // n = 100; x.setlength(n); y.setlength(n); w.setlength(n); for(i = 0; i <= n-1; i++) { x(i) = ap::pi()*i/(n-1); y(i) = sin(x(i)); w(i) = 1; } xc.setlength(2); yc.setlength(2); dc.setlength(2); xc(0) = 0; yc(0) = 0; dc(0) = 0; xc(0) = ap::pi(); yc(0) = 0; dc(0) = 0; spline1dfithermitewc(x, y, w, n, xc, yc, dc, 2, 6, info, s, rep); // // Output results // if( info>0 ) { printf("\nOK, we have finished\n\n"); printf(" x F(x) S(x) Error\n"); t = 0; while(ap::fp_less(t,0.999999*ap::pi())) { printf("%6.3lf %6.3lf %6.3lf %6.3lf\n", double(t), double(sin(t)), double(spline1dcalc(s, t)), double(fabs(spline1dcalc(s, t)-sin(t)))); t = ap::minreal(ap::pi(), t+0.25); } printf("%6.3lf %6.3lf %6.3lf %6.3lf\n\n", double(t), double(sin(t)), double(spline1dcalc(s, t)), double(fabs(spline1dcalc(s, t)-sin(t)))); printf("rms error is %6.3lf\n", double(rep.rmserror)); printf("max error is %6.3lf\n", double(rep.maxerror)); printf("S(0) = S(pi) = 0 (exactly)\n\n"); } else { printf("\nSomething wrong, Info=%0ld", long(info)); } return 0; }
int main(int argc, char **argv) { char fdir[200]; char fdint[200]; char fbint[200]; char fint[200]; char fbase[200]; char fcount[200]; char flist_A[200]; char flist_B[200]; char fdata_A[200]; char fdata_B[200]; char foutput[200]; char fnints[200]; char fdtrace[200]; char fbranch[200]; int ishock = 0; int imin = 700; int imax = 901; int iA; int iB; long nA; long nB; long tt; long ss; float dr = sqrt(3)/512.; int nsearch = 10; float frac_A; float frac_B; float d_A; float d_B; float x_A[3]; float x_B[3]; vector<shock> sA; vector<shock> sB; vector<tracer> tA; vector<tracer> tB; vector<long> n_ints; vector<long> o_ints; long n_ints_total; long n_ints_snap; long n_ints_in; int fflag = 0; //forward mode? //vector<long> l_ia; //vector<long> o_ia; vector<interaction> ia; vector<interaction> ia_tmp; vector<interaction> ia_shock; interaction ia_new; vector<long> nbranches; vector<long> nbinteractions; kdtree2 *bp_tree; kdtree2_result_vector res; array2dfloat bp_tree_data; vector<float> xc(3); long ioff = 0; float fdr = 3.; //how many cell distances? double time_A; double time_B; const int max_red = 5; array<vector<long>, max_red> islist; vector<long>::iterator il; int *snap_list; //list of snapshots to use in tracking int n_snaps; //total number of snapshots to use FILE *fp_times; char fname_times[200]; int n_times; float *times; int n_redundancy = 1; time_A = timer(); if(argc<4) { printf("./trace_shocks imin imax ishock [fname] [n_redundancy] [forward_flag]\n"); exit(-1); } //if we've supplied a range of snapshots //to search, use that if(argc>=4) { imin = atoi(argv[1]); imax = atoi(argv[2]); ishock = atoi(argv[3]); } if(argc>=6) { n_redundancy = atoi(argv[5]); } printf("n_redundancy = %d\n",n_redundancy); if(argc>=5) { char fname_snap_list[200]; sprintf(fname_snap_list,"%s",argv[4]); FILE *fp_snap_list; if(!(fp_snap_list = fopen(fname_snap_list,"r"))) { printf("Error opening %s\n",fname_snap_list); exit(-1); } fscanf(fp_snap_list,"%d\n",&n_snaps); printf("n_snaps = %d\n",n_snaps); snap_list = (int *)malloc(n_snaps*sizeof(int)); for(int i=0;i<n_snaps;i++) { fscanf(fp_snap_list,"%d\n",&snap_list[i]); //printf("snap_list[%d] = %d\n",i,snap_list[i]); } fclose(fp_snap_list); if(argc>=6) fflag = atoi(argv[5]); if(fflag) { //forward imax = snap_list[n_snaps-1]; imin = snap_list[0]; }else{ //backward imin = snap_list[n_snaps-1]; imax = snap_list[0]; } }else{ n_snaps = imax-imin+1; snap_list = (int *)malloc(n_snaps*sizeof(int)); for(int i=0;i<n_snaps;i++) snap_list[i] = imax - i; } //load snapshot times sprintf(fname_times,"times.txt"); if(!(fp_times = fopen(fname_times,"r"))) { printf("Error opening %s.\n",fname_times); exit(-1); } fscanf(fp_times,"%d\n",&n_times); times = (float *) malloc(n_times*sizeof(float)); for(int i=0;i<n_times;i++) fscanf(fp_times,"%f\n",×[i]); fclose(fp_times); printf("ishock = %d\n",ishock); printf("imin = %d %d\n",imin,snap_list[n_snaps-1]); printf("imax = %d %d\n",imax,snap_list[0]); sprintf(fdir,"data/"); sprintf(fdint,"interactions/"); sprintf(fbint,"interactions"); sprintf(fbase,"peak.blended"); sprintf(fdtrace,"traces/"); sprintf(fint,"%s%s.%04d.%04d.%d.txt",fdint,fbint,imin,imax,n_redundancy); sprintf(foutput,"%strace.%04d.%04d.%d.%08d.txt",fdtrace,imin,imax,n_redundancy,ishock); sprintf(fbranch,"%sbranches.%04d.%04d.%d.%08d.txt",fdtrace,imin,imax,n_redundancy,ishock); //Read interactions printf("Reading %s\n",fint); read_interactions(fint,&ia); printf("ia.size() %ld\n",ia.size()); long m; // for(iA = imax; iA>imin; iA--) //need to adjust islist to allow for //tracking of shocks in each of the redundant //snapshot times //the first list of shocks is just the //ishock of interest islist[0].push_back(ishock); for(int i_snap = 0;i_snap<n_snaps-n_redundancy; i_snap++) { iA = snap_list[i_snap]; for(int i_red=1;i_red <= n_redundancy; i_red++) { iB = snap_list[i_snap+i_red]; printf("i_red %d iA %d iB %d\n",i_red,iA,iB); if(fflag) { sprintf(fcount,"%sinteraction_count.%04d.%04d.txt",fdint,iA,iB); }else{ sprintf(fcount,"%sinteraction_count.%04d.%04d.txt",fdint,iB,iA); } printf("reading %s\n",fcount); read_interaction_counts(fcount,&n_ints,&o_ints); printf("******\n"); for(int ss=0;ss<islist[0].size();ss++) { ishock = islist[0][ss]; if(ishock>=n_ints.size()) { printf("ERROR iA %04d iB %04d ishock %d n_ints.size() %ld\n",iA,iB,ishock,n_ints.size()); exit(-1); } //print information about interaction counts printf("iA %04d iB %04d ishock %d n_ins %ld o_ints %ld\n",iA,iB,ishock,n_ints[ishock],o_ints[ishock]); for(int i=0;i<n_ints[ishock];i++) { ia_tmp.push_back(ia[ioff + o_ints[ishock] + i]); m = ia_tmp.size()-1; printf("iA %04d idxA %6ld idxB %6ld nints %4ld idA %10ld idB %10ld nex %8ld fA %5.4e fB %5.4e fdA %5.4e fdB %5.4e f %5.4e\n",ia_tmp[m].snap_A,ia_tmp[m].idx_A,ia_tmp[m].idx_B,n_ints[ishock],ia_tmp[m].id_A,ia_tmp[m].id_B,ia_tmp[m].n,ia_tmp[m].frac_A,ia_tmp[m].frac_B,ia_tmp[m].frac_A_dense,ia_tmp[m].frac_B_dense,ia_tmp[m].frac_dense); } //end loop over interactions }// end loop over list of traced shocks //reset the shock list //vector<long>().swap(islist[i_red]); for(int i=0;i<ia_tmp.size();i++) { ia_shock.push_back(ia_tmp[i]); islist[i_red].push_back(ia_tmp[i].idx_B); } //remember the number of interactions nbinteractions.push_back(ia_tmp.size()); //keep unique std::sort(islist[i_red].begin(), islist[i_red].end()); il = std::unique(islist[i_red].begin(), islist[i_red].end()); islist[i_red].resize( std::distance(islist[i_red].begin(), il) ); for(int i=0;i<islist[i_red].size();i++) printf("i_red %d i %d islist[%d] %ld\n",i_red,i,i,islist[i_red][i]); //if there are no interactions, break the loop if(ia_tmp.size()==0) break; printf("HERE\n"); //remember the current number of branches //nbranches.push_back(ia_tmp.size()); nbranches.push_back(islist[i_red].size()); printf("nbranches %ld\n",nbranches[nbranches.size()-1]); //reset temporary interaction list vector<interaction>().swap(ia_tmp); //advance ioff long n_int_sum = 0; for(int i=0;i<n_ints.size();i++) n_int_sum += n_ints[i]; //ioff += n_ints.size(); ioff += n_int_sum; printf("ioff = %ld n_int_sum %ld n_ints.size() %ld\n",ioff,n_int_sum,n_ints.size()); vector<long>().swap(n_ints); vector<long>().swap(o_ints); }//end loop over second snapshots for(int i=0;i<n_redundancy-1;i++) islist[i].swap(islist[i+1]); vector<long>().swap(islist[n_redundancy-1]); }//end loop over first snapshots //for(int i=0;i<ia.size();i++) //printf("snap_A %04d\tia %10ld\tib %10ld\tn %10ld\tfrac A %5.4e\tfrac B %5.4e\txA %e %e %e\txB %e %e %e\n",ia[i].snap_A,ia[i].id_A,ia[i].id_B,ia[i].n,ia[i].frac_A,ia[i].frac_B,ia[i].x_A[0],ia[i].x_A[1],ia[i].x_A[2],ia[i].x_B[0],ia[i].x_B[1],ia[i].x_B[2]); //save the interactions to a file write_interactions(foutput,ia_shock,times); write_branches(fbranch,nbranches,nbinteractions); time_B = timer(); printf("Total time = %es.\n",time_B-time_A); return 0; }
int main(int argc, char **argv) { int m; int n; int d; ap::real_1d_array x; ap::real_1d_array y; ap::real_1d_array w; ap::real_1d_array xc; ap::real_1d_array yc; ap::integer_1d_array dc; barycentricfitreport rep; int info; barycentricinterpolant r; int i; int j; double a; double b; double v; double dv; printf("\n\nFitting exp(2*x) at [-1,+1] by:\n1. constrained/unconstrained Floater-Hormann functions\n"); printf("\n"); printf("Fit type rms.err max.err p(0) dp(0) DBest\n"); // // Prepare points // m = 5; a = -1; b = +1; n = 10000; x.setlength(n); y.setlength(n); w.setlength(n); for(i = 0; i <= n-1; i++) { x(i) = a+(b-a)*i/(n-1); y(i) = exp(2*x(i)); w(i) = 1.0; } // // Fitting: // a) f(x)=exp(2*x) at [-1,+1] // b) by 5 Floater-Hormann functions // c) without constraints // barycentricfitfloaterhormann(x, y, n, m, info, r, rep); barycentricdiff1(r, 0.0, v, dv); printf("Unconstrained FH %7.4lf %7.4lf %7.4lf %7.4lf %0ld\n", double(rep.rmserror), double(rep.maxerror), double(v), double(dv), long(rep.dbest)); // // Fitting: // a) f(x)=exp(2*x) at [-1,+1] // b) by 5 Floater-Hormann functions // c) constrained: p(0)=1 // xc.setlength(1); yc.setlength(1); dc.setlength(1); xc(0) = 0; yc(0) = 1; dc(0) = 0; barycentricfitfloaterhormannwc(x, y, w, n, xc, yc, dc, 1, m, info, r, rep); barycentricdiff1(r, 0.0, v, dv); printf("Constrained FH, p(0)=1 %7.4lf %7.4lf %7.4lf %7.4lf %0ld\n", double(rep.rmserror), double(rep.maxerror), double(v), double(dv), long(rep.dbest)); // // Fitting: // a) f(x)=exp(2*x) at [-1,+1] // b) by 5 Floater-Hormann functions // c) constrained: dp(0)=2 // xc.setlength(1); yc.setlength(1); dc.setlength(1); xc(0) = 0; yc(0) = 2; dc(0) = 1; barycentricfitfloaterhormannwc(x, y, w, n, xc, yc, dc, 1, m, info, r, rep); barycentricdiff1(r, 0.0, v, dv); printf("Constrained FH, dp(0)=2 %7.4lf %7.4lf %7.4lf %7.4lf %0ld\n", double(rep.rmserror), double(rep.maxerror), double(v), double(dv), long(rep.dbest)); // // Fitting: // a) f(x)=exp(2*x) at [-1,+1] // b) by 5 Floater-Hormann functions // c) constrained: p(0)=1, dp(0)=2 // xc.setlength(2); yc.setlength(2); dc.setlength(2); xc(0) = 0; yc(0) = 1; dc(0) = 0; xc(1) = 0; yc(1) = 2; dc(1) = 1; barycentricfitfloaterhormannwc(x, y, w, n, xc, yc, dc, 2, m, info, r, rep); barycentricdiff1(r, 0.0, v, dv); printf("Constrained FH, both %7.4lf %7.4lf %7.4lf %7.4lf %0ld\n", double(rep.rmserror), double(rep.maxerror), double(v), double(dv), long(rep.dbest)); printf("\n\n"); return 0; }
int trustregion(NLP1* nlp, std::ostream *fout, SymmetricMatrix& H, ColumnVector& search_dir, ColumnVector& sx, real& TR_size, real& step_length, real stpmax, real stpmin) { /**************************************************************************** * subroutine trustregion * * Purpose * find a step which satisfies the Goldstein-Armijo line search conditions * * Compute the dogleg step * Compute the predicted reduction, pred, of the quadratic model * Compute the actual reduction, ared * IF ared/pred > eta * THEN x_vec = x_vec + d_vec * TR_size >= TR_size * Compute the gradient g_vec at the new point * ELSE TR_size < ||d_vec|| * * Parameters * nlp --> pointer to nonlinear problem object * * search_dir --> Vector of length n which specifies the * newton direction on input. On output it will * contain the step * * step_length <-- is a nonnegative variable. * On output step_length contains the step size taken * * ftol --> default Value = 1.e-4 * ftol should be smaller than 5.e-1 * suggested value = 1.e-4 for newton methods * = 1.e-1 for more exact line searches * xtol --> default Value = 2.2e-16 * gtol --> default Value = 0.9 * gtol should be greater than 1.e-4 * * termination occurs when the sufficient decrease * condition and the directional derivative condition are * satisfied. * * stpmin and TR_size are nonnegative input variables which * specify lower and upper bounds for the step. * stpmin Default Value = 1.e-9 * * Initial version Juan Meza November 1994 * * *****************************************************************************/ // Local variables int n = nlp->getDim(); bool debug = nlp->getDebug(); bool modeOverride = nlp->getModeOverride(); ColumnVector tgrad(n), newton_dir(n), tvec(n), xc(n), xtrial(n); real fvalue, fplus, dnorm; real eta1 = .001; real eta2 = .1; real eta3 = .75; real rho_k; int iter = 0; int iter_max = 100; real dd1, dd2; real ared, pred; int dog_step; real TR_MAX = stpmax; static char *steps[] = {"C", "D", "N", "B"}; static bool accept; // // Initialize variables // fvalue = nlp->getF(); xc = nlp->getXc(); step_length = 1.0; tgrad = nlp->getGrad(); newton_dir = search_dir; if (debug) { *fout << "\n***************************************"; *fout << "***************************************\n"; *fout << "\nComputeStep using trustregion\n"; *fout << "\tStep ||step|| ared pred TR_size \n"; } while (iter < iter_max) { iter++; // // Compute the dogleg step // search_dir = newton_dir; dog_step = dogleg(nlp, fout, H, tgrad, search_dir, sx, dnorm, TR_size, stpmax); step_length = dnorm; // // Compute pred = -g'd - 1/2 d'Hd // dd1 = Dot(tgrad,search_dir); tvec = H * search_dir; dd2 = Dot(search_dir,tvec); pred = -dd1 - dd2/2.0; // // Compute objective function at trial point // xtrial = xc + search_dir; if (modeOverride) { nlp->setX(xtrial); nlp->eval(); fplus = nlp->getF(); } else fplus = nlp->evalF(xtrial); ared = fvalue - fplus; // // Should we take this step ? // rho_k = ared/pred; accept = false; if (rho_k >= eta1) accept = true; // // Update the trust region // if (accept) { // // Do the standard updating // if (rho_k <= eta2) { // Model is just sort of bad // New trust region will be TR_size/2 if (debug) { *fout << "trustregion: rho_k = " << e(rho_k,14,4) << " eta2 = " << e(eta2,14,4) << "\n"; } TR_size = step_length / 2.0; if (TR_size < stpmin) { *fout << "***** Trust region too small to continue.\n"; nlp->setX(xc); nlp->setF(fvalue); nlp->setGrad(tgrad); return(-1); } } else if ((eta3 <= rho_k) && (rho_k <= (2.0 - eta3))) { // Model is PRETTY good // Double trust region if (debug) { *fout << "trustregion: rho_k = " << e(rho_k,14,4) << " eta3 = " << e(eta3,14,4) << "\n"; } TR_size = min(2.0*TR_size, TR_MAX); } else { // // All other cases // TR_size = max(2.0*step_length,TR_size); TR_size = min(TR_size, TR_MAX); if (debug) { *fout << "trustregion: rho_k = " << e(rho_k,14,4) << "\n"; } } } else { // Model is REALLY bad // TR_size = step_length/10.0; if (debug) { *fout << "trustregion: rho_k = " << e(rho_k,14,4) << "n" << " eta1 = " << e(eta1,14,4) << "\n"; } if (TR_size < stpmin) { *fout << "***** Trust region too small to continue.\n"; nlp->setX(xc); nlp->setF(fvalue); nlp->setGrad(tgrad); return(-1); } } // // Accept/Reject Step // if (accept) { // // Update x, f, and grad // if (!modeOverride) { nlp->setX(xtrial); nlp->setF(fplus); nlp->evalG(); } if (debug) { *fout << "\t Step ||step|| ared pred TR_size \n"; *fout << "Accept " << steps[dog_step] << e(step_length,14,4) << e(ared,14,4) << e(pred,14,4) << e(TR_size,14,4) << "\n"; } return(dog_step); } else { // // Reject step // if (debug) { *fout << "\t Step ||step|| ared pred TR_size \n"; *fout << "Reject " << steps[dog_step] << e(step_length,14,4) << e(ared,14,4) << e(pred,14,4) << e(TR_size,14,4) << "\n"; } } } nlp->setX(xc); nlp->setF(fvalue); nlp->setGrad(tgrad); return(-1); // Too many iterations }
void TPZSurface::MakeSphereFromTriangle() { fgeometricmesh = new TPZGeoMesh; fgeometricmesh->SetDimension(fdimension); int nodes = 6; fgeometricmesh->SetMaxNodeId(nodes-1); fgeometricmesh->NodeVec().Resize(nodes); TPZManVector<TPZGeoNode,4> Node(nodes); TPZManVector<int64_t,2> TopolTriangle(3); TPZManVector<REAL,3> coord(3,0.); TPZVec<REAL> xc(3,0.); int nodeindex = 0; coord = ParametricSphere(Pi/2.0,0.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi/2.0,Pi/2.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi/2.0,Pi); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi/2.0,-Pi/2.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(0.0,0.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; coord = ParametricSphere(Pi,0.0); fgeometricmesh->NodeVec()[nodeindex].SetCoord(coord); fgeometricmesh->NodeVec()[nodeindex].SetNodeId(nodeindex); nodeindex++; int id = 0; int matid = 1; TopolTriangle[0] = 0; TopolTriangle[1] = 1; TopolTriangle[2] = 4; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad1 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad1->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 1; TopolTriangle[1] = 2; TopolTriangle[2] = 4; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad2 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad2->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 2; TopolTriangle[1] = 3; TopolTriangle[2] = 4; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad3 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad3->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 3; TopolTriangle[1] = 0; TopolTriangle[2] = 4; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad4 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad4->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 0; TopolTriangle[1] = 1; TopolTriangle[2] = 5; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad5 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad5->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 1; TopolTriangle[1] = 2; TopolTriangle[2] = 5; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad6 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad6->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 2; TopolTriangle[1] = 3; TopolTriangle[2] = 5; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad7 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad7->Geom().SetData(fradius, xc); id++; TopolTriangle[0] = 3; TopolTriangle[1] = 0; TopolTriangle[2] = 5; TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > * quad8 = new TPZGeoElRefPattern< pzgeom::TPZTriangleSphere< pzgeom::TPZGeoTriangle > > (id,TopolTriangle,matid,*fgeometricmesh); quad8->Geom().SetData(fradius, xc); id++; fgeometricmesh->BuildConnectivity(); }
void StrandBlockSolver::gradQa(const int& mglevel) { if (mglevel == 0 && gradient != 0 && gradQaFlag == 0){ // compute nodal values nodalQa(mglevel); // initialize gradients for (int n=0; n<nFaces+nBedges; n++) for (int j=0; j<nPstr+2; j++) for (int k=0; k<ndim; k++) for (int m=0; m<nqa; m++) qax(m,k,j,n) = 0.; // loop through unstructured edges int c1,c2,n1,n2,jm,jp,k; double Ax,Ay,sqa; for (int n=0; n<nEdges; n++){ c1 = edge(0,n); c2 = edge(1,n); n1 = edgn(n); for (int j=1; j<nPstr+1; j++){ jm = j-1; Ax = facs(0,j,n); Ay = facs(1,j,n); for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); sqa = qap(k,jm,n1)+qap(k,j,n1); qax(k,0,j,c1) += Ax*sqa; qax(k,1,j,c1) += Ay*sqa; qax(k,0,j,c2) -= Ax*sqa; qax(k,1,j,c2) -= Ay*sqa; }}} // loop through structured edges for (int n=0; n<nFaces-nGfaces; n++){ n1 = face(0,n); n2 = face(1,n); for (int j=0; j<nPstr+1; j++){ jp = j+1; Ax = facu(0,j,n); Ay = facu(1,j,n); for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); sqa = qap(k,j,n1)+qap(k,j,n2); qax(k,0,j ,n) += Ax*sqa; qax(k,1,j ,n) += Ay*sqa; qax(k,0,jp,n) -= Ax*sqa; qax(k,1,jp,n) -= Ay*sqa; }}} // divide by twice the volume for the interior cells for (int n=0; n<nFaces-nGfaces; n++) for (int j=1; j<nPstr+1; j++) for (int m=0; m<ndim; m++) for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); qax(k,m,j,n) /= (2.*v(j,n)); } // surface, end, and boundary gradients double dx1,dy1,dx2,dy2,ds,l11,l12,l21,l22,sqa1,sqa2,eps=1.e-14; int j=0; jp = 1; for (int n=0; n<nFaces-nGfaces; n++){ n1 = face(0,n); n2 = face(1,n); dx1 = x (0,j ,n2)-x (0,j,n1); dy1 = x (1,j ,n2)-x (1,j,n1); dx2 = xc(0,jp,n )-xc(0,j,n ); dy2 = xc(1,jp,n )-xc(1,j,n ); ds = dx1*dy2-dx2*dy1; if (fabs(ds) < eps) ds = 0.; // on sharp corners qax = 0. else ds = 1./ds; l11 = ds*dy2; l12 =-ds*dy1; l21 =-ds*dx2; l22 = ds*dx1; for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); sqa1 = qap(k,j ,n2)-qap(k,j,n1); sqa2 = qa (k,jp,n )-qa (k,j,n ); qax(k,0,j,n) = l11*sqa1+l12*sqa2; qax(k,1,j,n) = l21*sqa1+l22*sqa2; }} j = nPstr+1; jm = nPstr; for (int n=0; n<nFaces-nGfaces; n++){ n1 = face(0,n); n2 = face(1,n); dx1 = x (0,j ,n2)-x (0,j,n1); dy1 = x (1,j ,n2)-x (1,j,n1); dx2 = xc(0,jm,n )-xc(0,j,n ); dy2 = xc(1,jm,n )-xc(1,j,n ); ds = dx1*dy2-dx2*dy1; if (fabs(ds) < eps) ds = 0.; else ds = 1./ds; l11 = ds*dy2; l12 =-ds*dy1; l21 =-ds*dx2; l22 = ds*dx1; for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); sqa1 = qap(k,j ,n2)-qap(k,j,n1); sqa2 = qa (k,jm,n )-qa (k,j,n ); qax(k,0,j,n) = l11*sqa1+l12*sqa2; qax(k,1,j,n) = l21*sqa1+l22*sqa2; }} for (int n=nEdges-nBedges; n<nEdges; n++){ c1 = edge(0,n); c2 = edge(1,n); n1 = edgn( n); for (int j=1; j<nPstr+1; j++){ jm = j-1; dx1 = x (0,j,n1)-x (0,jm,n1); dy1 = x (1,j,n1)-x (1,jm,n1); dx2 = xc(0,j,c1)-xc(0,j ,c2); dy2 = xc(1,j,c1)-xc(1,j ,c2); ds = dx1*dy2-dx2*dy1; if (fabs(ds) < eps) ds = 0.; else ds = 1./ds; l11 = ds*dy2; l12 =-ds*dy1; l21 =-ds*dx2; l22 = ds*dx1; for (int kk=0; kk<nqaGradQa; kk++){ k = iqagrad(kk); sqa1 = qap(k,j,n1)-qap(k,jm,n1); sqa2 = qa (k,j,c1)-qa (k,j ,c2); qax(k,0,j,c2) = l11*sqa1+l12*sqa2; qax(k,1,j,c2) = l21*sqa1+l22*sqa2; }}} gradQaFlag = 1; } }
/************************************************************************* Dense solver. This subroutine solves a system A*X=B, where A is NxN non-denegerate real matrix, X and B are NxM real matrices. Additional features include: * automatic detection of degenerate cases * iterative improvement INPUT PARAMETERS A - array[0..N-1,0..N-1], system matrix N - size of A B - array[0..N-1,0..M-1], right part M - size of right part OUTPUT PARAMETERS Info - return code: * -3 if A is singular, or VERY close to singular. X is filled by zeros in such cases. * -1 if N<=0 or M<=0 was passed * 1 if task is solved (matrix A may be near singular, check R1/RInf parameters for condition numbers). Rep - solver report, see below for more info X - array[0..N-1,0..M-1], it contains: * solution of A*X=B if A is non-singular (well-conditioned or ill-conditioned, but not very close to singular) * zeros, if A is singular or VERY close to singular (in this case Info=-3). SOLVER REPORT Subroutine sets following fields of the Rep structure: * R1 reciprocal of condition number: 1/cond(A), 1-norm. * RInf reciprocal of condition number: 1/cond(A), inf-norm. SEE ALSO: DenseSolverR() - solves A*x = b, where x and b are Nx1 matrices. -- ALGLIB -- Copyright 24.08.2009 by Bochkanov Sergey *************************************************************************/ void rmatrixsolvem(const ap::real_2d_array& a, int n, const ap::real_2d_array& b, int m, int& info, densesolverreport& rep, ap::real_2d_array& x) { int i; int j; int k; int rfs; int nrfs; ap::integer_1d_array p; ap::real_1d_array xc; ap::real_1d_array y; ap::real_1d_array bc; ap::real_1d_array xa; ap::real_1d_array xb; ap::real_1d_array tx; ap::real_2d_array da; double v; double verr; bool smallerr; bool terminatenexttime; // // prepare: check inputs, allocate space... // if( n<=0||m<=0 ) { info = -1; return; } da.setlength(n, n); x.setlength(n, m); y.setlength(n); xc.setlength(n); bc.setlength(n); tx.setlength(n+1); xa.setlength(n+1); xb.setlength(n+1); // // factorize matrix, test for exact/near singularity // for(i = 0; i <= n-1; i++) { ap::vmove(&da(i, 0), &a(i, 0), ap::vlen(0,n-1)); } rmatrixlu(da, n, n, p); rep.r1 = rmatrixlurcond1(da, n); rep.rinf = rmatrixlurcondinf(da, n); if( ap::fp_less(rep.r1,10*ap::machineepsilon)||ap::fp_less(rep.rinf,10*ap::machineepsilon) ) { for(i = 0; i <= n-1; i++) { for(j = 0; j <= m-1; j++) { x(i,j) = 0; } } rep.r1 = 0; rep.rinf = 0; info = -3; return; } info = 1; // // solve // for(k = 0; k <= m-1; k++) { // // First, non-iterative part of solution process: // * pivots // * L*y = b // * U*x = y // ap::vmove(bc.getvector(0, n-1), b.getcolumn(k, 0, n-1)); for(i = 0; i <= n-1; i++) { if( p(i)!=i ) { v = bc(i); bc(i) = bc(p(i)); bc(p(i)) = v; } } y(0) = bc(0); for(i = 1; i <= n-1; i++) { v = ap::vdotproduct(&da(i, 0), &y(0), ap::vlen(0,i-1)); y(i) = bc(i)-v; } xc(n-1) = y(n-1)/da(n-1,n-1); for(i = n-2; i >= 0; i--) { v = ap::vdotproduct(&da(i, i+1), &xc(i+1), ap::vlen(i+1,n-1)); xc(i) = (y(i)-v)/da(i,i); } // // Iterative improvement of xc: // * calculate r = bc-A*xc using extra-precise dot product // * solve A*y = r // * update x:=x+r // // This cycle is executed until one of two things happens: // 1. maximum number of iterations reached // 2. last iteration decreased error to the lower limit // nrfs = densesolverrfsmax(n, rep.r1, rep.rinf); terminatenexttime = false; for(rfs = 0; rfs <= nrfs-1; rfs++) { if( terminatenexttime ) { break; } // // generate right part // smallerr = true; for(i = 0; i <= n-1; i++) { ap::vmove(&xa(0), &a(i, 0), ap::vlen(0,n-1)); xa(n) = -1; ap::vmove(&xb(0), &xc(0), ap::vlen(0,n-1)); xb(n) = b(i,k); xdot(xa, xb, n+1, tx, v, verr); bc(i) = -v; smallerr = smallerr&&ap::fp_less(fabs(v),4*verr); } if( smallerr ) { terminatenexttime = true; } // // solve // for(i = 0; i <= n-1; i++) { if( p(i)!=i ) { v = bc(i); bc(i) = bc(p(i)); bc(p(i)) = v; } } y(0) = bc(0); for(i = 1; i <= n-1; i++) { v = ap::vdotproduct(&da(i, 0), &y(0), ap::vlen(0,i-1)); y(i) = bc(i)-v; } tx(n-1) = y(n-1)/da(n-1,n-1); for(i = n-2; i >= 0; i--) { v = ap::vdotproduct(&da(i, i+1), &tx(i+1), ap::vlen(i+1,n-1)); tx(i) = (y(i)-v)/da(i,i); } // // update // ap::vadd(&xc(0), &tx(0), ap::vlen(0,n-1)); } // // Store xc // ap::vmove(x.getcolumn(k, 0, n-1), xc.getvector(0, n-1)); } }
void StrandBlockSolver::shiftTime(const int& step, const int& mglevel) { if (mglevel == 0){ // fine MG level cout << "\n*** Preparing to solve step " << step << " ***" << endl; cout << "physical time " << double(step)*dtUnsteady << endl; cout << "time step " << dtUnsteady << endl; // advance q, v, and x if (step == 1){ for (int n=0; n<nFaces+nBedges; n++) for (int j=0; j<nPstr+2; j++){ for (int k=0; k<nq; k++){ q1(k,j,n) = q(k,j,n); q2(k,j,n) = q(k,j,n); } v2(j,n) = v(j,n); v1(j,n) = v(j,n); } for (int n=0; n<nNodes; n++) for (int j=0; j<nPstr+1; j++){ for (int k=0; k<ndim; k++){ x0(k,j,n) = x(k,j,n); x1(k,j,n) = x(k,j,n); x2(k,j,n) = x(k,j,n); }} } else{ for (int n=0; n<nFaces+nBedges; n++) for (int j=0; j<nPstr+2; j++){ for (int k=0; k<nq; k++){ q2(k,j,n) = q1(k,j,n); q1(k,j,n) = q(k,j,n); } v2(j,n) = v1(j,n); v1(j,n) = v(j,n); } for (int n=0; n<nNodes; n++) for (int j=0; j<nPstr+1; j++){ for (int k=0; k<ndim; k++){ x2(k,j,n) = x1(k,j,n); x1(k,j,n) = x(k,j,n); //x(k,j,n) = ?; }} } // compute face areas, cell-centers, and volumes facearea_(pid, ndim, nFaces, nGfaces, nNodes, nGnodes, nEdges, nBedges, nPstr, &face(0,0), &edge(0,0), &edgn(0), &x(0,0,0), &facs(0,0,0), &facu(0,0,0)); cellcoord_(pid, ndim, nFaces, nGfaces, nNodes, nGnodes, nEdges, nBedges, nPstr, &face(0,0), &edge(0,0), &edgn(0), &x(0,0,0), &facs(0,0,0), &facu(0,0,0), &xc(0,0,0)); volume_(pid, ndim, nFaces, nGfaces, nNodes, nGnodes, nEdges, nBedges, nPstr, &face(0,0), &edge(0,0), &edgn(0), &fClip(0), &x(0,0,0), &facs(0,0,0), &facu(0,0,0), &xc(0,0,0), &v(0,0)); // compute least squares coefficients if (nodeVal == 1) lspVol(); else if (nodeVal == 2) lspLS(); else if (nodeVal == 3) lspMap(); else{ cout << "\nvalue of nodeVal not recognized" << endl; exit(0); } } else{ // coarse MG level // compute coarse level face areas and volumes coarseMetrics(); } // face velocities cout << "\n*** face velocity computation not yet implemented ***" << endl; }
int main(int argc, char* argv[]) { Teuchos::RCP<Epetra_Comm> comm; #ifdef HAVE_MPI Teuchos::GlobalMPISession mpiSession(&argc, &argv,0); comm = Teuchos::rcp(new Epetra_MpiComm(MPI_COMM_WORLD)); #else comm = Teuchos::rcp(new Epetra_SerialComm()); #endif // 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 if (iprint > 0 && comm->MyPID()==0) outStream = Teuchos::rcp(&std::cout, false); else outStream = Teuchos::rcp(&bhs, false); int errorFlag = 0; try { /**********************************************************************************************/ /************************* CONSTRUCT ROL ALGORITHM ********************************************/ /**********************************************************************************************/ // Get ROL parameterlist std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, Teuchos::Ptr<Teuchos::ParameterList>(&*parlist) ); // Build ROL algorithm double gtol = parlist->get("Gradient Tolerance",1.e-6); double stol = parlist->get("Step Tolerance",1.e-12); int maxit = parlist->get("Maximum Number of Iterations",100); ROL::StatusTest<double> status(gtol,stol,maxit); //ROL::LineSearchStep<double> step(*parlist); Teuchos::RCP<ROL::Step<double> > step; Teuchos::RCP<ROL::DefaultAlgorithm<double> > algo; /**********************************************************************************************/ /************************* CONSTRUCT SOL COMPONENTS *******************************************/ /**********************************************************************************************/ // Build vectors unsigned dim = 4; Teuchos::RCP<std::vector<double> > x_rcp = Teuchos::rcp( new std::vector<double>(dim,0.0) ); ROL::StdVector<double> x(x_rcp); Teuchos::RCP<std::vector<double> > x0_rcp = Teuchos::rcp( new std::vector<double>(dim,0.0) ); ROL::StdVector<double> x0(x0_rcp); Teuchos::RCP<std::vector<double> > xr_rcp = Teuchos::rcp( new std::vector<double>(dim,0.0) ); ROL::StdVector<double> xr(xr_rcp); Teuchos::RCP<std::vector<double> > d_rcp = Teuchos::rcp( new std::vector<double>(dim,0.0) ); ROL::StdVector<double> d(d_rcp); for ( unsigned i = 0; i < dim; i++ ) { (*x0_rcp)[i] = 1.0/(double)dim; (*xr_rcp)[i] = random<double>(comm); (*d_rcp)[i] = random<double>(comm); } // Build samplers int nSamp = 1000; std::vector<std::vector<double> > bounds(dim); std::vector<double> tmp(2,0.0); double inc = 0.125; double val = -0.5; for (unsigned i = 0; i < dim; i++) { tmp[0] = val-inc; tmp[1] = val+inc; bounds[i] = tmp; inc *= 2.0; } Teuchos::RCP<ROL::BatchManager<double> > bman = Teuchos::rcp(new ROL::StdEpetraBatchManager<double>(comm)); Teuchos::RCP<ROL::SampleGenerator<double> > sampler = Teuchos::rcp(new ROL::MonteCarloGenerator<double>(nSamp,bounds,bman,false,false,100)); // Build risk-averse objective function bool storage = true; Teuchos::RCP<ROL::ParametrizedObjective<double> > pObj = Teuchos::rcp(new ParametrizedObjectiveEx1<double>(1.e1)); Teuchos::RCP<ROL::RiskMeasure<double> > rm; Teuchos::RCP<ROL::Objective<double> > obj; // Build bound constraints std::vector<double> l(dim,0.0); std::vector<double> u(dim,1.0); Teuchos::RCP<ROL::BoundConstraint<double> > con = Teuchos::rcp( new ROL::StdBoundConstraint<double>(l,u) ); // Test parametrized objective functions *outStream << "Check Derivatives of Parametrized Objective Function\n"; x.set(xr); pObj->setParameter(sampler->getMyPoint(0)); pObj->checkGradient(x,d,true,*outStream); pObj->checkHessVec(x,d,true,*outStream); /**********************************************************************************************/ /************************* RISK NEUTRAL *******************************************************/ /**********************************************************************************************/ *outStream << "\nRISK NEUTRAL\n"; rm = Teuchos::rcp( new ROL::RiskMeasure<double>() ); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); clock_t start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* RISK NEUTRAL *******************************************************/ /**********************************************************************************************/ *outStream << "\nRISK NEUTRAL\n"; obj = Teuchos::rcp( new ROL::RiskNeutralObjective<double>(pObj,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS DEVIATION ************************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS DEVIATION\n"; // Absolute value approximation double gamma = 0.0; ROL::EAbsoluteValue eav = ROL::ABSOLUTEVALUE_C2; Teuchos::RCP<ROL::PositiveFunction<double> > pf = Teuchos::rcp( new ROL::AbsoluteValue<double>(gamma,eav) ); // Moment vector std::vector<double> order(2,0.0); order[0] = 2.0; order[1] = 4.0; // Moment coefficients std::vector<double> coeff(2,0.1); rm = Teuchos::rcp( new ROL::MeanDeviation<double>(order,coeff,pf) ); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS VARIANCE *************************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS VARIANCE\n"; rm = Teuchos::rcp( new ROL::MeanVariance<double>(order,coeff,pf) ); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS DEVIATION FROM TARGET ************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS DEVIATION FROM TARGET\n"; // Moment targets std::vector<double> target(2,-0.1); // Risk measure rm = Teuchos::rcp( new ROL::MeanDeviationFromTarget<double>(target,order,coeff,pf) ); // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS VARIANCE FROM TARGET *************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS VARIANCE FROM TARGET\n"; // Risk measure coeff[1] = 0.0; rm = Teuchos::rcp( new ROL::MeanVarianceFromTarget<double>(target,order,coeff,pf) ); coeff[1] = 0.1; // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS SEMIDEVIATION ********************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS SEMIDEVIATION\n"; // Plus function approximation gamma = 1.e2; std::vector<double> data2(2,0.0); data2[0] = 0.0; data2[1] = 1.0; Teuchos::RCP<ROL::Distribution<double> > dist2 = Teuchos::rcp(new ROL::Distribution<double>(ROL::DISTRIBUTION_PARABOLIC,data2)); Teuchos::RCP<ROL::PlusFunction<double> > plusf = Teuchos::rcp(new ROL::PlusFunction<double>(dist2,1.0/gamma)); pf = Teuchos::rcp(new ROL::PlusFunction<double>(dist2,1.0/gamma)); // Risk measure rm = Teuchos::rcp( new ROL::MeanDeviation<double>(order,coeff,pf) ); // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS SEMIVARIANCE *********************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS SEMIVARIANCE\n"; // Risk measure rm = Teuchos::rcp( new ROL::MeanVariance<double>(order,coeff,pf) ); // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS SEMIDEVIATION FROM TARGET ********************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS SEMIDEVIATION FROM TARGET\n"; // Risk measure rm = Teuchos::rcp( new ROL::MeanDeviationFromTarget<double>(target,order,coeff,pf) ); // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS SEMIVARIANCE FROM TARGET *********************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS SEMIVARIANCE FROM TARGET\n"; // Risk measure rm = Teuchos::rcp( new ROL::MeanVarianceFromTarget<double>(target,order,coeff,pf) ); // Risk averse objective obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* MEAN PLUS CVAR *****************************************************/ /**********************************************************************************************/ *outStream << "\nMEAN PLUS CONDITIONAL VALUE AT RISK\n"; double prob = 0.8; double c = 0.8; rm = Teuchos::rcp( new ROL::CVaR<double>(prob,c,plusf) ); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); Teuchos::RCP<ROL::BoundConstraint<double> > CVaRcon = Teuchos::rcp( new ROL::CVaRBoundConstraint<double>(con) ); // Test objective functions double xv = 10.0*random<double>(comm)-5.0; double dv = 10.0*random<double>(comm)-5.0; Teuchos::RCP<ROL::Vector<double> > xp = Teuchos::rcp(&x,false); Teuchos::RCP<ROL::Vector<double> > dp = Teuchos::rcp(&d,false); ROL::CVaRVector<double> xc(xv,xp); ROL::CVaRVector<double> dc(dv,dp); *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(xc,dc,true,*outStream); obj->checkHessVec(xc,dc,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(xc,*obj,*CVaRcon,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "t = " << xc.getVaR() << "\n"; *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* SMOOTHED CVAR QUADRANGLE *******************************************/ /**********************************************************************************************/ *outStream << "\nSMOOTHED CONDITIONAL VALUE AT RISK \n"; prob = 0.9; ROL::CVaRQuadrangle<double> scq(prob,1.0/gamma,plusf); //scq.checkRegret(); rm = Teuchos::rcp(&scq,false); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions xv = 10.0*random<double>(comm)-5.0; dv = 10.0*random<double>(comm)-5.0; xp = Teuchos::rcp(&x,false); dp = Teuchos::rcp(&d,false); ROL::CVaRVector<double> xq(xv,xp); ROL::CVaRVector<double> dq(dv,dp); *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(xr); obj->checkGradient(xq,dq,true,*outStream); obj->checkHessVec(xq,dq,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(xq,*obj,*CVaRcon,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "t = " << xq.getVaR() << "\n"; *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; /**********************************************************************************************/ /************************* EXPONENTIAL UTILITY FUNCTION ***************************************/ /**********************************************************************************************/ *outStream << "\nEXPONENTIAL UTILITY FUNCTION\n"; rm = Teuchos::rcp( new ROL::ExpUtility<double> ); obj = Teuchos::rcp( new ROL::RiskAverseObjective<double>(pObj,rm,sampler,storage) ); // Test objective functions *outStream << "\nCheck Derivatives of Risk-Averse Objective Function\n"; x.set(x0); obj->checkGradient(x,d,true,*outStream); obj->checkHessVec(x,d,true,*outStream); // Run ROL algorithm step = Teuchos::rcp( new ROL::TrustRegionStep<double>(*parlist) ); algo = Teuchos::rcp( new ROL::DefaultAlgorithm<double>(*step,status,false) ); x.set(x0); start = clock(); algo->run(x,*obj,*con,true,*outStream); *outStream << "Optimization time: " << (double)(clock()-start)/(double)CLOCKS_PER_SEC << " seconds.\n"; // Print Solution *outStream << "x = ("; for ( unsigned i = 0; i < dim-1; i++ ) { *outStream << (*x_rcp)[i] << ", "; } *outStream << (*x_rcp)[dim-1] << ")\n"; } 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; }