void main() { define_cameraInfo(cameraInfomation); mat H_rel_abs(5, 5); mat H_abs_phi(5, 5); mat H_phi_sphi(5, 5); mat H_T(5, 5); mat H_M(5, 5); mat H_sphi_phi(5, 5); define_H(H_rel_abs, H_abs_phi, H_phi_sphi, H_T, H_M, H_sphi_phi, cameraInfomation); mat sol(5, 1, fill::zeros); mat input(5, 1); //-------------------------------------------------------------------------- int lens = cameraInfomation.K;//마이크로렌즈갯수 int sensor = cameraInfomation.N;//마이크로레즈 한개당 센서 갯수 mat imageCoord(4, 3); imageCoord <<0 << 0 << 2000 << endr << 0 << 1000 << 2000 << endr << 1000 << 1000 << 2000 << endr << 1000 <<1000 << 2000 << endr; int world_x = 1000, world_y = 1000; //이미지 크기 int input_width, input_height; colorimg** inputimg = ReadImage_color("C:\\Users\\김송란\\Documents\\GitHub\\Study\\lightfield\\cat.jpg", &input_width, &input_height); mat Pl1(1, 3), Pl2(1, 3); //s,t,u,v 저장할 변수 mat unitvector(1, 3); mat Pp1(1, 3), Pp2(1, 3), Pp3(1, 3); //평면의 모서리 3개 좌표 변수 mat nomalvector(1, 3); //법선벡터 mat x(1, 3);//직선과 평면이 만나는 점 colorimg** outimg = (colorimg**)IntAlloc2(lens*sensor, lens*sensor); colorimg** SubApertureImg = (colorimg**)IntAlloc2(lens*sensor, lens*sensor); mat a, b, c, d, sub_xy; int InOutFlag = 0; for (int k = 0; k < lens; k++) { for (int l = 0; l < lens; l++) { for (int i = 0; i < sensor; i++) { for (int j = 0; j < sensor; j++) { input << i << endr << j << endr << k << endr << l << endr << 1 << endr; sol = H_sphi_phi * H_M * H_T * H_phi_sphi * H_abs_phi * H_rel_abs *input; //cout << "행렬 원소 보기: " << endl << sol << endl; LineEquation(sol(0,0), sol(1,0), sol(2,0), sol(3,0), cameraInfomation.D, Pl1, Pl2, unitvector);//직선의 방정식 PlaneEquation(imageCoord, Pp1, Pp2, Pp3, nomalvector); //이미지평면의 방정식 CrossLinePlane(unitvector, nomalvector, Pp1, Pl1, x); //직선과 이미지평면이 만나는 점 InterpolationCoor(x, a, b, c, d, sub_xy, input_width, input_height, world_x, world_y); //선형보간법 좌표 생성 InOutFlag=detectInOut(imageCoord, x); rawimage(InOutFlag,sensor*k+i,sensor*l+j,input_width,input_height, inputimg, outimg, a, b, c, d, sub_xy); //이미지생성 } } } } for (int i = 0; i < sensor; i++) { for (int j = 0; j < sensor; j++) { MakeSubApertureImages(i, j, lens, sensor, outimg, SubApertureImg); } } WriteImage_color("C:\\Users\\김송란\\Documents\\GitHub\\Study\\lightfield\\영상출력테스트5.bmp", outimg, lens*sensor, lens*sensor); WriteImage_color("C:\\Users\\김송란\\Documents\\GitHub\\Study\\lightfield\\영상출력테스트sub5.bmp", SubApertureImg, lens*sensor, lens*sensor); }
cv::Mat WavefrontSensor::WavefrontSensing(const std::vector<cv::Mat>& d, const double& meanPowerNoise) { unsigned int numberOfZernikes = 20; //total number of zernikes to be considered int M = numberOfZernikes; int K = d.size(); cv::Mat Q2; //We introduce here the lineal relationship between parameter phases of each optical path partlyKnownDifferencesInPhaseConstraints(M, K, Q2); std::vector<cv::Mat> Q2_v = {Q2, cv::Mat::zeros(Q2.size(), Q2.type())}; cv::Mat LEC; //Linear equality constraints cv::merge(Q2_v, LEC); //Build also the complex version of Q2 //process each patch independently cv::Mat dd; std::vector<cv::Mat> d_w; std::vector<Metric> mtrc_v; std::vector<std::pair<cv::Range,cv::Range> > rngs; unsigned int pixelsBetweenTiles = (int)(d.front().cols); unsigned int tileSize = 34; OpticalSetup tsettings( tileSize ); std::shared_ptr<Zernike> zrnk = std::make_shared<Zernike>(tsettings.pupilRadiousPixels(), tileSize, numberOfZernikes); divideIntoTiles(d.front().size(), pixelsBetweenTiles, tileSize, rngs); //Random row selector: Pick incoherent measurements cv::Mat eye_nn = cv::Mat::eye(K*tileSize*tileSize, K*tileSize*tileSize, cv::DataType<double>::type); unsigned int a = 400; //number of incoheren measurements cv::Mat shuffle_eye; shuffleRows(eye_nn, shuffle_eye); //Split 'a' into rngs.size() pieces std::vector<cv::Mat> A_v = {shuffle_eye(cv::Range(0, a), cv::Range::all()), cv::Mat::zeros(a, K*tileSize*tileSize, cv::DataType<double>::type)}; cv::Mat A; cv::merge(A_v, A); std::cout << "Number of anisoplanatic patches to annalize at once: " << rngs.size() << std::endl; for(auto rng_i : rngs) { cv::Mat d_col; //get ready dataset format std::vector<cv::Mat> D; std::vector<cv::Mat> d_col_v; for(cv::Mat di : d) { cv::Mat Di; cv::dft(di(rng_i.first, rng_i.second), Di, cv::DFT_COMPLEX_OUTPUT + cv::DFT_SCALE); fftShift(Di); D.push_back(Di); cv::Mat Di_t(Di.t()); d_col_v.push_back(Di_t.reshape(0, Di_t.total() )); } cv::vconcat(d_col_v, d_col); cv::gemm(A, d_col, 1.0, cv::Mat(), 1.0, d_col); //Picks rows randomly d_w.push_back( d_col ); mtrc_v.push_back( Metric(D, zrnk, meanPowerNoise) ); } cv::vconcat(d_w, dd); //-----------------------BY MEANS OF CONVEX OPTIMIZATION: //Objective function and gradient of the objective function if(false) { for(auto mtrc : mtrc_v) { std::function<double(cv::Mat)> func = std::bind(&Metric::objective, &mtrc, std::placeholders::_1); std::function<cv::Mat(cv::Mat)> dfunc = std::bind(&Metric::gradient, &mtrc, std::placeholders::_1); ConvexOptimization minimizationKit; cv::Mat x0_conv = cv::Mat::zeros(M*K, 1, cv::DataType<double>::type); //reset starting point //Lambda function that turn minimize function + constraints problem into minimize function lower dimension problem auto F_constrained = [] (cv::Mat x, std::function<double(cv::Mat)> func, const cv::Mat& Q2) -> double { return func(Q2*x); }; auto DF_constrained = [] (cv::Mat x, std::function<cv::Mat(cv::Mat)> dfunc, const cv::Mat& Q2) -> cv::Mat { return Q2.t() * dfunc(Q2*x); }; std::function<double(cv::Mat)> f_constrained = std::bind(F_constrained, std::placeholders::_1, func, Q2); std::function<cv::Mat(cv::Mat)> df_constrained = std::bind(DF_constrained, std::placeholders::_1, dfunc, Q2); //Define a new starting point with lower dimensions after reduction with contraints cv::Mat p_constrained = Q2.t() * x0_conv; ConvexOptimization min; min.perform_BFGS(p_constrained, f_constrained, df_constrained); x0_conv = Q2 * p_constrained; //Go back to original dimensional std::cout << "mimumum: " << x0_conv.t() << std::endl; } std::cout << "END OF CONVEX OPTIMIZATION" << std::endl; } //-----------------------BY MEANS OF SPARSE RECOVERY: //Create phase_div bias: only for the case of two diversity images!! // cv::Mat phase_div = cv::Mat::zeros(rngs.size()*M*K, 1, cv::DataType<double>::type); // phase_div.at<double>(M + 3, 0) = tsettings.k() * 3.141592/(2.0*std::sqrt(3.0)); cv::Mat x0 = cv::Mat::zeros(rngs.size()*M*K, 1, cv::DataType<double>::type); //Starting point std::vector<double> gamma_v(M*K, 1.0); for(unsigned int count=0;count<600;++count) { std::vector<cv::Mat> x0_vvv; cv::split(x0, x0_vvv); x0_vvv.at(0).copyTo(x0); cv::Mat_<std::complex<double> > blockMatrix_M; std::vector<cv::Mat> De_v; for(unsigned int t=0; t < rngs.size(); ++t) { cv::Mat jacob_i; mtrc_v.at(t).jacobian( x0(cv::Range(t*M*K, (t*M*K) + (M*K)), cv::Range::all()), jacob_i ); cv::gemm(A, jacob_i, 1.0, cv::Mat(), 1.0, jacob_i); //Picks rows randomly cv::gemm(jacob_i, LEC, 1.0, cv::Mat(), 1.0, jacob_i); //Apply constraints LECs cv::copyMakeBorder(blockMatrix_M, blockMatrix_M, 0, jacob_i.size().height, 0, jacob_i.size().width, cv::BORDER_CONSTANT, cv::Scalar(0.0, 0.0) ); cv::Rect rect(cv::Point(t*jacob_i.size().width, t*jacob_i.size().height), jacob_i.size() ); jacob_i.copyTo(blockMatrix_M( rect )); cv::Mat De_i; mtrc_v.at(t).phi( x0(cv::Range(t*M*K, (t*M*K) + (M*K)), cv::Range::all()), De_i ); cv::gemm(A, De_i, 1.0, cv::Mat(), 1.0, De_i); //Picks rows randomly De_v.push_back( De_i ); } cv::Mat De; cv::vconcat(De_v, De); std::vector<cv::Mat> x0_v = {x0, cv::Mat::zeros(x0.size(), x0.type())}; cv::merge(x0_v, x0); //Apply algorithm to get solution unsigned int blkLen = rngs.size(); cv::Mat blockMatrix_M_r; reorderColumns(blockMatrix_M, M, blockMatrix_M_r); //reorder columns so correlated data form a single block gamma_v = std::vector<double>(M*K, 1.0); //cv::Mat coeffs = perform_BSBL(blockMatrix_M_r, dd - De, NoiseLevel::Noiseless, gamma_v, blkLen); //Noiseless, LittleNoise //cv::Mat coeffs = perform_SBL(blockMatrix_M_r, dd - De, NoiseLevel::Noiseless, gamma_v); //Noiseless, LittleNoise cv::Mat coeffs = perform_projection(blockMatrix_M_r, dd - De); //Noiseless, LittleNoise cv::Mat coeffs_r; reorderColumns(coeffs.t(), blockMatrix_M.cols/M, coeffs_r); cv::Mat coeffs_r_n(coeffs_r.t()); //Undo constraints cv::Mat sol = cv::Mat::zeros(x0.size(), cv::DataType<std::complex<double> >::type); for(unsigned int t=0; t < rngs.size(); ++t) { cv::Mat sol_i; cv::gemm(LEC, coeffs_r_n(cv::Range(t*LEC.cols, (t*LEC.cols) + (LEC.cols)), cv::Range::all()), 1.0, cv::Mat(), 1.0, sol_i); sol_i.copyTo(sol(cv::Range(t*M*K, (t*M*K) + (M*K)), cv::Range::all())); } std::cout << "cv::norm(sol): " << cv::norm(sol) << std::endl; if(cv::norm(sol) < 1e-4 ) {std::cout << "Solution found" << std::endl; break;} x0 = x0 - sol; std::cout << "Solution number: " << count << std::endl; std::cout << "x0: " << x0.t() << std::endl; } return cv::Mat(); //mtrc.F(); }
int main(int argc, char *argv[]) { Teuchos::GlobalMPISession mpiSession(&argc, &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 if (iprint > 0) outStream = Teuchos::rcp(&std::cout, false); else outStream = Teuchos::rcp(&bhs, false); int errorFlag = 0; // *** Example body. try { Teuchos::RCP<ROL::Objective<RealT> > obj; Teuchos::RCP<ROL::EqualityConstraint<RealT> > constr; Teuchos::RCP<std::vector<RealT> > x_rcp = Teuchos::rcp( new std::vector<RealT> (0, 0.0) ); Teuchos::RCP<std::vector<RealT> > sol_rcp = Teuchos::rcp( new std::vector<RealT> (0, 0.0) ); ROL::StdVector<RealT> x(x_rcp); // Iteration vector. ROL::StdVector<RealT> sol(sol_rcp); // Reference solution vector. // Retrieve objective, constraint, iteration vector, solution vector. ROL::ZOO::getSimpleEqConstrained <RealT, ROL::StdVector<RealT>, ROL::StdVector<RealT>, ROL::StdVector<RealT>, ROL::StdVector<RealT> > (obj, constr, x, sol); Teuchos::ParameterList parlist; // Define Step parlist.set("Nominal SQP Optimality Solver Tolerance", 1.e-2); ROL::CompositeStepSQP<RealT> step(parlist); // Run derivative checks, etc. int dim = 5; int nc = 3; RealT left = -1e0, right = 1e0; Teuchos::RCP<std::vector<RealT> > xtest_rcp = Teuchos::rcp( new std::vector<RealT> (dim, 0.0) ); Teuchos::RCP<std::vector<RealT> > g_rcp = Teuchos::rcp( new std::vector<RealT> (dim, 0.0) ); Teuchos::RCP<std::vector<RealT> > d_rcp = Teuchos::rcp( new std::vector<RealT> (dim, 0.0) ); Teuchos::RCP<std::vector<RealT> > v_rcp = Teuchos::rcp( new std::vector<RealT> (dim, 0.0) ); Teuchos::RCP<std::vector<RealT> > vc_rcp = Teuchos::rcp( new std::vector<RealT> (nc, 0.0) ); Teuchos::RCP<std::vector<RealT> > vl_rcp = Teuchos::rcp( new std::vector<RealT> (nc, 0.0) ); ROL::StdVector<RealT> xtest(xtest_rcp); ROL::StdVector<RealT> g(g_rcp); ROL::StdVector<RealT> d(d_rcp); ROL::StdVector<RealT> v(v_rcp); ROL::StdVector<RealT> vc(vc_rcp); ROL::StdVector<RealT> vl(vl_rcp); // set xtest, d, v for (int i=0; i<dim; i++) { (*xtest_rcp)[i] = ( (RealT)rand() / (RealT)RAND_MAX ) * (right - left) + left; (*d_rcp)[i] = ( (RealT)rand() / (RealT)RAND_MAX ) * (right - left) + left; (*v_rcp)[i] = ( (RealT)rand() / (RealT)RAND_MAX ) * (right - left) + left; } // set vc, vl for (int i=0; i<nc; i++) { (*vc_rcp)[i] = ( (RealT)rand() / (RealT)RAND_MAX ) * (right - left) + left; (*vl_rcp)[i] = ( (RealT)rand() / (RealT)RAND_MAX ) * (right - left) + left; } obj->checkGradient(xtest, d, true, *outStream); *outStream << "\n"; obj->checkHessVec(xtest, v, true, *outStream); *outStream << "\n"; obj->checkHessSym(xtest, d, v, true, *outStream); *outStream << "\n"; constr->checkApplyJacobian(xtest, v, vc, true, *outStream); *outStream << "\n"; constr->checkApplyAdjointJacobian(xtest, vl, vc, xtest, true, *outStream); *outStream << "\n"; constr->checkApplyAdjointHessian(xtest, vl, d, xtest, true, *outStream); *outStream << "\n"; Teuchos::RCP<std::vector<RealT> > v1_rcp = Teuchos::rcp( new std::vector<RealT> (dim, 0.0) ); Teuchos::RCP<std::vector<RealT> > v2_rcp = Teuchos::rcp( new std::vector<RealT> (nc, 0.0) ); ROL::StdVector<RealT> v1(v1_rcp); ROL::StdVector<RealT> v2(v2_rcp); RealT augtol = 1e-8; constr->solveAugmentedSystem(v1, v2, d, vc, xtest, augtol); // Define Status Test RealT gtol = 1e-12; // norm of gradient tolerance RealT ctol = 1e-12; // norm of constraint tolerance RealT stol = 1e-18; // norm of step tolerance int maxit = 1000; // maximum number of iterations ROL::StatusTestSQP<RealT> status(gtol, ctol, stol, maxit); // Define Algorithm ROL::DefaultAlgorithm<RealT> algo(step, status, false); // Run Algorithm vl.zero(); //(*x_rcp)[0] = 3.0; (*x_rcp)[1] = 2.0; (*x_rcp)[2] = 2.0; (*x_rcp)[3] = 1.0; (*x_rcp)[4] = 1.0; //(*x_rcp)[0] = -5.0; (*x_rcp)[1] = -5.0; (*x_rcp)[2] = -5.0; (*x_rcp)[3] = -6.0; (*x_rcp)[4] = -6.0; std::vector<std::string> output = algo.run(x, g, vl, vc, *obj, *constr, false); for ( unsigned i = 0; i < output.size(); i++ ) { *outStream << output[i]; } // Compute Error *outStream << "\nReference solution x_r =\n"; *outStream << std::scientific << " " << (*sol_rcp)[0] << "\n"; *outStream << std::scientific << " " << (*sol_rcp)[1] << "\n"; *outStream << std::scientific << " " << (*sol_rcp)[2] << "\n"; *outStream << std::scientific << " " << (*sol_rcp)[3] << "\n"; *outStream << std::scientific << " " << (*sol_rcp)[4] << "\n"; *outStream << "\nOptimal solution x =\n"; *outStream << std::scientific << " " << (*x_rcp)[0] << "\n"; *outStream << std::scientific << " " << (*x_rcp)[1] << "\n"; *outStream << std::scientific << " " << (*x_rcp)[2] << "\n"; *outStream << std::scientific << " " << (*x_rcp)[3] << "\n"; *outStream << std::scientific << " " << (*x_rcp)[4] << "\n"; x.axpy(-1.0, sol); RealT abserr = x.norm(); RealT relerr = abserr/sol.norm(); *outStream << std::scientific << "\n Absolute Error: " << abserr; *outStream << std::scientific << "\n Relative Error: " << relerr << "\n"; if ( relerr > sqrt(ROL::ROL_EPSILON) ) { errorFlag += 1; } } 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() { sol(); }
Solution::Solution(const Problem& pbm):_pbm(pbm) { vector<double> sol (pbm.dimension()); _solution = sol; }
// Methode d'apprentissage d'un PRFA prefixe RESULT PPRFA::DEES (T_ModeVariables modeVariables, Sample & S, double prec, double epsprime, bool verbose, T_ModeReturn moderet, T_ModeEpsilon modeeps, unsigned int maxstates, unsigned int seuil, int maxmots, int maxsearches, bool bestsearch, bool stepssave) { try { // ------------------------- affichage des informations ---------------------- // if (verbose) { cout << "\t\t=== DEES ==="; cout << "\nSample size = " << S.size (); cout << "\nprecision = " << prec; cout << "\nbound = " << epsprime; cout << "\nmoderet = "; switch (moderet) { case ::begin: cout << "begin"; break; case ::end: cout << "end"; } cout << "\nmodeeps = "; switch (modeeps) { case epsfixed: cout << "epsfixed"; break; case variable: cout << "variable"; break; case word_variable: cout << "word_variable"; break; } cout << "\nmaxstates = " << maxstates; cout << "\nseuil = " << seuil; cout << "\nmaxmots = " << maxmots << endl; } if (prec == 0) { return becomePrefixTree(S); } // -------------------------- INITIALISATION ---------------------- vide (); // on initialise le PFA. if (S.size () == 0) throw 0; // on verifie que l'echantillon n'est pas vide. S.prefixialise (); // Transformation de l'Èchantillon en echantillon prefixiel. Sigma = S.alphabet (); // on met ‡† jour l'alphabet alph = S.dictionnaire (); // et le dictionnaire associÈ. // Declaration Word v; // the word v which represent the word associated to the state to add. list < Word > X; // The set of words which are potential prime residuals. Sample::const_iterator u; // current word of the sample. float val; // a floating value used to calculate tau. Word w; // a word Word ww; // another word Lettre a; // a letter (we will have v=wa) Alphabet::const_iterator b; // pour enumerer toutes les lettres SFunc solution; // the system solution SFunc solutiontemp; // a temporary solution StateSet::iterator q; // Pour enumerer les √©tats Simplex simplx; // L'objet simplexe qui contient les algorithmes de resolution de systemes. set < Word, ordre_mot > W; // L'ensemble de mots à tester Word::iterator z; // last letter // --- init variables --- v.clear (); // v = epsilon (empty word) // X is the set of one letter words of S when prefixialised val = 0; for (u = ++(S.begin ()); (u != S.end ()) && (u->first.size () < 2); ++u) { X.push_back (u->first); val += u->second; } // We create the first state (epsilon) addState (v, 1, 1 - (float(val) / float(S.size ()))); W.clear (); // liste_mots_associes(W,v,S,maxmots); ajoute_mots_associes(W,v,S,maxmots); // There may be a general state State generalstate = -1; // Step saving string svgfile="etape-"; // -------------------------- LEARNING LOOP ----------------------- if (verbose) cout << "Ajout des états : " << endl; // For each element in X (the temporary list) while (!X.empty ()) { v = *(X.begin ()); // v <-- min X; X.pop_front (); // X <-- X\{v} ; // wa=v w = v; a = *(w.rbegin ()); z = w.end (); --z; w.erase (z); //w.pop_back (); //~ if (verbose) { //~ cout << "["; //~ cout << affiche(v) <<"]"; //~ cout.flush(); //~ } if (stepssave) { save(svgfile+affiche(v)); } /// 3 possible cases : /// (1) not enought data (make a loop to the general state) /// (2) there is no solution (add a new state and update X) /// (3) there is a solution (make a return of transitions) if (S[v] < seuil) // case (1) not enought data { // cout << "CASE (1)" << endl; if (generalstate == -1) { // if the general state was not created, we create it generalstate = addState (v, 0, 1 / float(Sigma.size () + 1)); for (b = Sigma.begin (); b != Sigma.end (); ++b) { MA::addTransition (generalstate, *b, generalstate, 1 / float(Sigma.size () + 1)); } } addTransition (w, a, generalstate, ((double) S[v] / (double) S[w])); XR[w + a] = generalstate; if (verbose) { cout << "S"; cout.flush (); } } else { solution.clear (); // init solutions // calculate the solution of the linear system sol (modeVariables, solution, v, S, simplx, prec / pow(float(S[v]), float(0.4)), moderet, modeeps, W, maxmots, false); if (solution.empty ()) // if there is no solution (case (2) add a new state and update X { // cout << "CASE (2)" << endl; // if there is no solution then we add the state associated with v // updating X and tau (val will contain tau[v]) val = 0; for (b = Sigma.begin (); b != Sigma.end (); b++) { // pour toute les lettres de l'alphabet v += *b; //v.push_back (*b); // on ajoute b a la fin de v if (S.find (v) != S.end ()) { // si vb appartient a l'echantillon, alors X.push_back (v); // on l'ajoute a X val += S[v]; // et val = val + S(vb\Sigma^*) } z = v.end (); --z; v.erase (z); //v.pop_back (); // on efface la derniere lettre pour que la variable v = le mot v. } if (verbose) { cout << "A"; cout.flush (); } addState (v,0, 1 - (val / (double) S[v])); // adding the new state if (size () > maxstates) throw 1; addTransition (w, a, v, ((double) S[v] / (double) S[w])); // updating phi : phi(w,a,wa) = S(wa)/S(w) } else { // cout << "CASE (3)" << endl; // else we return transitions if (verbose) { cout << "R"; cout.flush (); } for (q = Q.begin (); q != Q.end (); q++) { val = (float) solution[*q] * ((double) S[v] / (double) S[w]); if (val != 0) { addTransition (w, a, *q, val); } } } } } if (verbose) cout << endl; erase_transitions (epsprime, -epsprime); // deleting transitions less than epsprime //best_transition_delete(S,verbose); if (modeVariables == nonconstrained) { return VAL(0); } else { return renormalise (); // renormalisation in order to disable borders effects } } catch (int erreur) { if (PFA_VERBOSE) { if (erreur != 1) { cerr << "PFA::DEES(Sample S)" << endl; } switch (erreur) { case 0: cerr << "Sample vide !!!" << endl; break; case 1: // il y a trop d'etats erase_transitions (epsprime); return renormalise (); break; default: cerr << "Erreur n∞" << erreur << endl; } } return ERR (erreur); } }
int main(){ while(init()) sol(); return 0; }
void HBIO::write( const std::string filename ) const { int totcrd, ptrcrd, indcrd, valcrd, rhscrd; int n, m, nz, nfelm, nrhs, nrhsix; int ptrcount, ptrlen, indcount, indlen, valcount, vallen, rhscount, rhslen; char mxtype[4], rhstype[4]; std::fstream fstr( filename.c_str(), std::fstream::out ); if( !fstr.is_open() ) throw( Error( ERROR_LOCATION, "Could not open file " + filename ) ); // Make checks if( rhs.size() != 0 && mat.columns() != rhs.size() ) throw( Error( ERROR_LOCATION, "Matrix dimension does not match vector dimension" ) ); // Set file parameters n = mat.rows(); m = mat.columns(); nz = mat.nz_elements(); nfelm = 0; nrhs = 0; nrhsix = 0; strcpy( mxtype, "RUA" ); strcpy( rhstype, "F " ); if( sol.size() != 0 ) { rhstype[2] = 'X'; nrhs++; } if( rhs.size() != 0 ) nrhs++; ptrlen = (int)log10( nz+1 ) + 2; ptrcount = 80 / ptrlen; ptrcrd = (int)ceil( (m+1) / (double)ptrcount ); indlen = (int)log10( n+1 ) + 2; indcount = 80 / indlen; indcrd = (int)ceil( nz / (double)indcount ); vallen = valacc+8; valcount = 80 / vallen; valcrd = (int)ceil( nz / (double)valcount ); if( rhs.size() != 0 || sol.size() != 0 ) { rhslen = rhsacc+8; rhscount = 80 / rhslen; rhscrd = (int)ceil( nrhs*n / (double)rhscount ); } else { rhslen = 0; rhscount = 0; rhscrd = 0; } totcrd = ptrcrd + indcrd + valcrd + rhscrd; // Write line 1 fstr.unsetf( std::ios::adjustfield ); fstr.setf( std::ios::left ); fstr << std::setw(72) << title.substr(0,72); fstr << std::setw(8) << key.substr(0,8) << "\n"; // Write line 2 fstr.unsetf( std::ios::adjustfield ); fstr.setf( std::ios::right ); fstr << std::setw(14) << totcrd; fstr << std::setw(14) << ptrcrd; fstr << std::setw(14) << indcrd; fstr << std::setw(14) << valcrd; fstr << std::setw(14) << rhscrd << "\n"; // Write line 3 fstr << std::setw(3) << mxtype; fstr << std::setw(11) << " "; fstr << std::setw(14) << n; fstr << std::setw(14) << m; fstr << std::setw(14) << nz; fstr << std::setw(14) << nfelm << "\n"; // Write line 4 fstr.unsetf( std::ios::adjustfield ); fstr.setf( std::ios::left ); std::ostringstream ss1, ss2, ss3, ss4; ss1 << '(' << ptrcount << 'I' << ptrlen << ')'; fstr << std::setw(16) << ss1.str(); ss2 << '(' << indcount << 'I' << indlen << ')'; fstr << std::setw(16) << ss2.str(); ss3 << '(' << valcount << 'E' << vallen << '.' << valacc << ')'; fstr << std::setw(20) << ss3.str(); if( rhs.size() != 0 || sol.size() != 0 ) { ss4 << '(' << rhscount << 'E' << rhslen << '.' << rhsacc << ')'; fstr << std::setw(20) << ss4.str(); } fstr << "\n"; if( rhscrd > 0 ) { // Write line 5 fstr << std::setw(3) << rhstype; fstr << std::setw(11) << " "; fstr.unsetf( std::ios::adjustfield ); fstr.setf( std::ios::right ); fstr << std::setw(14) << nrhs; fstr << std::setw(14) << nrhsix << "\n"; } fstr.unsetf( std::ios::adjustfield ); fstr.setf( std::ios::right ); // Write matrix pointers for( int k = 0; k < m+1; ) { for( int i = 0; i < ptrcount && k < m+1; i++ ) fstr << std::setw(ptrlen) << mat.ptr(k++) + 1; fstr << "\n"; } // Write matrix indices for( int k = 0; k < nz; ) { for( int i = 0; i < indcount && k < nz; i++ ) fstr << std::setw(indlen) << mat.row(k++) + 1; fstr << "\n"; } fstr.unsetf( std::ios::floatfield ); fstr.setf( std::ios::scientific ); fstr.precision( valacc ); // Write matrix values for( int k = 0; k < nz; ) { for( int i = 0; i < valcount && k < nz; i++ ) fstr << std::setw(vallen) << mat.val(k++); fstr << "\n"; } fstr.precision( rhsacc ); // Write right hand side vectors if( rhs.size() != 0 ) { for( int k = 0; k < n; ) { for( int i = 0; i < rhscount && k < n; i++ ) fstr << std::setw(rhslen) << rhs(k++); fstr << "\n"; } } if( sol.size() != 0 ) { for( int k = 0; k < n; ) { for( int i = 0; i < rhscount && k < n; i++ ) fstr << std::setw(rhslen) << sol(k++); fstr << "\n"; } } fstr.close(); }
int main(int argc, char *argv[]) { //first argument, lowercase, if any std::string fl = argc>1 ? lowercase(argv[1]) : ""; if (argc<=2) { if (fl=="" || fl=="--help" || fl=="-h" || fl=="/?" || fl=="/help") { std::cerr << "usage:\t" << argv[0] << " graph [''|solution|'='|'%'|color]" << std::endl; std::cerr << "where:\t" << "graph and solution are filenames" << std::endl; std::cerr << "\tcolor is an id in the default color palette" << std::endl; return 1; } else { try { Graph graph = Graph::load(argv[1]); signal(SIGUSR1, Metaheuristic::dump_handler); std::vector<int> v(graph.succ.size(), 0); Solution sol(v, graph); sol.initSolution(); //TODO adjust parameters here! float alpha = 0.9f; float temperature = 10.0f; float epsilon = 1.0f; int niter = 10; //std::cerr << "HIT before create recuit" << std::endl; Recuit meta(sol, alpha, niter, temperature, epsilon); //std::cerr << "HIT before starting recuit" << std::endl; //LocalSearch meta(graph); sol = meta.getSolution(); sol.dump(); if(sol.isAdmissible()) std::cerr << "GOOD" << std::endl; return 0; } catch (GraphException& e) { std::cerr << "error: " << e.what() << std::endl; return 2; } } } else { try { Graph g = Graph::load(argv[1]); #ifdef USE_SDL Solution *s = NULL; int pattern = get_positive(argv[2]); if (pattern == -1) { std::string a2 = argv[2]; if (a2 == "=") pattern = -1; else if (a2 == "%") pattern = -2; else s = new Solution(Solution::load(a2, g)); } if (!s) s = new Solution(Solution::load(g, pattern)); ui_main(g, s); delete s; #else g.dump(); #endif //USE_SDL return 0; } catch (SolutionException& e) { std::cerr << "error: " << e.what() << std::endl; return 3; } catch (GraphException& e) { std::cerr << "error: " << e.what() << std::endl; return 2; } } }
int main() { int i, j; input(); for (i = 1; i <= num; i++) { for (j = 1; j <= num; j++) { if (visited[i][j] == 0) { if (graph[i][j] == 1) { save = 1; visited[i][j] = 1; enqueue(i * 10000 + j); sol(); count++; } else if (graph[i][j] == 2) { save = 2; visited[i][j] = 1; enqueue(i * 10000 + j); sol(); count++; } else if (graph[i][j] == 3) { save = 3; visited[i][j] = 1; enqueue(i * 10000 + j); sol(); count++; } save = 0; } } } printf("%d ", count); count = 0; for (i = 0; i <= num; i++) { for (j = 0; j <= num; j++) { visited[i][j] = 0; graph[i][j] = graph2[i][j]; } } for (i = 1; i <= num; i++) { for (j = 1; j <= num; j++) { if (visited[i][j] == 0) { if (graph[i][j] == 1) { save = 1; visited[i][j] = 1; enqueue(i * 10000 + j); sol(); count++; } else if (graph[i][j] == 3) { save = 3; visited[i][j] = 1; enqueue(i * 10000 + j); sol(); count++; } save = 0; } } } printf("%d", count); /*for (i = 0; i <= num + 1; i++) { for (j = 0; j <= num + 1; j++) { printf("%d ", visited[i][j]); } printf("\n"); }*/ return 0; }
VertexExtensionOptimal<DIM> :: VertexExtensionOptimal () { if (!initialized) { // ofstream tout ("test1.out"); int i, j, k; Matrix<double> a(SIZE, SIZE); Matrix<double> b(2, SIZE); try { const IntegrationRule & ir = GetIntegrationRules().SelectIntegrationRule (ET_SEGM, 2*SIZE+2); Vector<double> diff_leg(SIZE); a = 0; b = 0; for (i = 0; i < ir.GetNIP(); i++) { double x = ir[i](0); DerivedLegendrePolynomial (SIZE-2, 2*x-1, diff_leg); for (j = SIZE-1; j >= 1; j--) diff_leg(j) = 2 * diff_leg(j-1); diff_leg(0) = 0; double fac = ir[i].Weight(); for (j = 0; j < DIM-1; j++) fac *= (1-x); for (j = 0; j < SIZE; j++) for (k = 0; k < SIZE; k++) a(j,k) += fac * diff_leg(j) * diff_leg(k); } double fac = 1; for (j = 0; j < SIZE; j++) { b(0,j) = fac; b(1,j) = 1; fac *= -1; } // compute coefficients for (i = 1; i < SIZE; i++) { Matrix<double> mat(i+3, i+3); Vector<double> rhs(i+3), sol(i+3); mat = 0; for (j = 0; j <= i; j++) for (k = 0; k <= i; k++) mat(j,k) = a(j,k); for (j = 0; j <= i; j++) { mat(i+1, j) = mat(j,i+1) = b(0,j); mat(i+2, j) = mat(j,i+2) = b(1,j); } rhs = 0; rhs(i+2) = 1; // stabilize A for (j = 0; j <= i; j++) { for (k = 0; k <= i; k++) mat(j,k) += b(0,j) * b(0,j) + b(1,j) * b(1,k); rhs(j) += b(1,j); } CholeskyFactors<double> inv(mat); inv.Mult (rhs, sol); // tout << "sol = " << sol << endl; for (j = 0; j <= i; j++) coefs[j][i] = sol(j); } /* // // testing ofstream out ("vext.dat"); ofstream dout ("dvext.dat"); for (double x = 0; x <= 1; x += 0.01) { out << x << " "; for (i = 1; i <= 10; i++) out << Calc (i, x) << " "; out << endl; dout << x << " "; for (i = 1; i <= 10; i++) dout << CalcDeriv (i, x) << " "; dout << endl; } */ initialized = 1; } catch (Exception e) { cout << "Caught in VertexExtensionOptimal:" << e.What() << endl; } } }
void ESDIRK::solveTimeStep( const scalar t0 ) { if ( adaptiveTimeStepper->isPreviousStepAccepted() ) solver->nextTimeStep(); fsi::matrix solStages( nbStages, N ), F( nbStages, N ); F.setZero(); fsi::vector sol( N ), f( N ), qold( N ), result( N ), rhs( N ); solver->getSolution( sol, f ); solStages.row( 0 ) = sol; qold = sol; scalar t = t0; solver->evaluateFunction( 0, sol, t, f ); F.row( 0 ) = f; // Keep the solution of the first stage and function evaluate // in memory in case the time step is rejected fsi::vector solOld = sol; fsi::vector fOld = f; // Loop over the stages solver->initTimeStep(); int iImplicitStage = 0; for ( int j = 0; j < nbStages; j++ ) { if ( !isStageImplicit( A( j, j ) ) ) continue; t = t0 + C( j ) * dt; Info << "\nTime = " << t << ", ESDIRK stage = " << j + 1 << "/" << nbStages << nl << endl; rhs.setZero(); // Calculate sum of the stage residuals for ( int iStage = 0; iStage < j; iStage++ ) rhs += A( j, iStage ) * F.row( iStage ).transpose(); rhs.array() *= dt; solver->implicitSolve( false, iImplicitStage, 0, t, A( j, j ) * dt, qold, rhs, f, result ); assert( (1.0 / (A( j, j ) * dt) * (result - qold - rhs) - f).array().abs().maxCoeff() < 1.0e-8 ); solStages.row( j ) = result; F.row( j ) = f; iImplicitStage++; } if ( adaptiveTimeStepper->isEnabled() ) { scalar newTimeStep = 0; fsi::vector errorEstimate( N ); errorEstimate.setZero(); for ( int iStage = 0; iStage < nbStages; iStage++ ) errorEstimate += ( B( iStage ) - Bhat( iStage ) ) * F.row( iStage ); errorEstimate *= dt; bool accepted = adaptiveTimeStepper->determineNewTimeStep( errorEstimate, result, dt, newTimeStep ); dt = newTimeStep; if ( not accepted ) solver->setSolution( solOld, fOld ); } if ( adaptiveTimeStepper->isAccepted() ) solver->finalizeTimeStep(); }
int main(){ init(); if(sol()) puts("YES"); else puts("NO"); return 0; }
arma::vec DIIS::get_w_diis_wrk(const arma::mat & errs) const { // Size of LA problem int N=(int) errs.n_cols; // DIIS weights arma::vec sol(N); sol.zeros(); if(c1diis) { // Original, Pulay's DIIS (C1-DIIS) // Array holding the errors arma::mat B(N+1,N+1); B.zeros(); // Compute errors for(int i=0;i<N;i++) for(int j=0;j<N;j++) { B(i,j)=arma::dot(errs.col(i),errs.col(j)); } // Fill in the rest of B for(int i=0;i<N;i++) { B(i,N)=-1.0; B(N,i)=-1.0; } // RHS vector arma::vec A(N+1); A.zeros(); A(N)=-1.0; // Solve B*X = A arma::vec X; bool succ; succ=arma::solve(X,B,A); if(succ) { // Solution is (last element of X is DIIS error) sol=X.subvec(0,N-1); // Check that weights are within tolerance if(arma::max(arma::abs(sol))>=MAXWEIGHT) { printf("Large coefficient produced by DIIS. Reducing to %i matrices.\n",N-1); arma::vec w0=get_w_diis_wrk(errs.submat(1,1,errs.n_rows-1,errs.n_cols-1)); // Helper vector arma::vec w(N); w.zeros(); w.subvec(w.n_elem-w0.n_elem,w.n_elem-1)=w0; return w; } } if(!succ) { // Failed to invert matrix. Use the two last iterations instead. printf("C1-DIIS was not succesful, mixing matrices instead.\n"); sol.zeros(); sol(0)=0.5; sol(1)=0.5; } } else { // C2-DIIS // Array holding the errors arma::mat B(N,N); B.zeros(); // Compute errors for(int i=0;i<N;i++) for(int j=0;j<N;j++) { B(i,j)=arma::dot(errs.col(i),errs.col(j)); } // Solve eigenvectors of B arma::mat Q; arma::vec lambda; eig_sym_ordered(lambda,Q,B); // Normalize weights for(int i=0;i<N;i++) { Q.col(i)/=arma::sum(Q.col(i)); } // Choose solution by picking out solution with smallest error arma::vec errors(N); arma::mat eQ=errs*Q; // The weighted error is for(int i=0;i<N;i++) { errors(i)=arma::norm(eQ.col(i),2); } // Find minimal error double mine=DBL_MAX; int minloc=-1; for(int i=0;i<N;i++) { if(errors[i]<mine) { // Check weights bool ok=arma::max(arma::abs(Q.col(i)))<MAXWEIGHT; if(ok) { mine=errors(i); minloc=i; } } } if(minloc!=-1) { // Solution is sol=Q.col(minloc); } else { printf("C2-DIIS did not find a suitable solution. Mixing matrices instead.\n"); sol.zeros(); sol(0)=0.5; sol(1)=0.5; } } return sol; }
// Main algorithm. void MOGA::compute() { if ( num_bits_ == 0 ) return; double p; // Build initial population. initialization(); // Do generations. for ( int i = 0; i < num_generations_; ++i ) { while ( (int)population_.size() < 2 * num_individuals_ ) { // Select a pair of individuals. std::pair<int, int> s( selection() ); p = (double)std::rand() / (double)RAND_MAX; if ( p <= Pc_ ) { // Cross them. std::pair<individual, individual> children( crossover( population_[s.first], population_[s.second] ) ); p = (double)std::rand() / (double)RAND_MAX; if ( p <= Pm_ ) { // Mutate children. mutation( children.first ); mutation( children.second ); } // Repair children. repair( children.first ); repair( children.second ); population_.push_back( children.first ); population_.push_back( children.second ); } else { population_.push_back( population_[s.first] ); population_.push_back( population_[s.second] ); } } // Keep the best individuals. elitism(); print(); } // LOCAL SEARCH solutions_.clear(); if ( Argument::local_search ) { LocalSearch local( data_, cust_, fac_ ); local.pipe_fp_ = pipe_fp_; for ( unsigned int i = 0; i < population_.size(); ++i ) { local.search( population_[i] ); solutions_.merge( local.solutions_ ); } } // FINISHED - KEEP BEST VALUES // Keep only "first rank" solutions. for ( unsigned int i = 0; i < population_.size(); ++i ) { #if STRICT_CHECK if ( population_[i].rank == 1 && is_feasible( population_[i] ) && population_[i].is_feasible() ) #else if ( population_[i].rank == 1 && population_[i].is_feasible() ) #endif { #if STRICT_CHECK // Check objective is_valid( population_[i] ); #endif Solution sol( getNbObjective() ); for ( int k = 0; k < getNbObjective(); ++k ) { sol.setObj( k, population_[i].obj[k] ); } solutions_.push_back( sol ); } } }
void PressureTable::ComputeDatabaseInputs( const double rho, const double Z, const double Zv, const double Yc, double &P, double &Sz , double &C, double P0, double C0) { // Compute normalized variance double eps = 1.0e-3; if ((Z <= 1-eps)||(Z >= eps)) { Sz = Zv/(Z*(1.0-Z)); } else { Sz = 0.0; } Sz = max(0.0, min(1.0, Sz)); // Compute normalized progress variable Z_newton = Z; Zv_newton = Sz; Yc_newton = Yc; rho_newton = rho; // I need to solve ( Yc(C,P) - Yc_target , rho(C,P) - rho_target) = (0 , 0) C_newton = C0; P_newton = P0/P_scale;// Pressure is rescaled verbose_newton = false; Bool check; VecDoub_IO sol2(1, 0.0); VecDoub_IO sol(2, 0.0); int Newton_mode; try { //Newton : newt(sol, check, usrfunc_wrapper); //Broyden : broydn(sol, check, usrfunc_wrapper); // Get Approximation of Yceq from highest pressure int nPress = GetDimension1(); double P_max = GetCoordinate1(nPress-1); int nC = GetDimension4(); double C_max = GetCoordinate4(nC-2); // Maximum C value before one double Yc_eq = Lookup(P_max,Z_newton,Zv_newton,1.0,"PROG"); double Yc_max = Lookup(P_max,Z_newton,Zv_newton,C_max,"PROG"); // If Yc_eq is small, C is set to 1 and we look for pressure only if ((Yc_eq < eps)||(Yc > Yc_max)) { Newton_mode = 1; sol2[0] = P_newton; C_newton = 1.0; newt(sol2, check, usrfunc_wrapper2); } else { // usual Newton_mode = 2; sol[0] = C_newton; sol[1] = P_newton; try {newt(sol, check, usrfunc_wrapper);} catch (int e) { cout << "relaunched with Newton_mode = 1" << endl; Newton_mode = 1; C_newton = sol[0]; sol2[0] = P0/P_scale; newt(sol2, check, usrfunc_wrapper2); } } } catch (int e) { int tol_failure = 0; if (Newton_mode == 1) { VecDoub out(1, 0.0); out = DensityFromP(sol2); if (abs(out[0]) > 1.0e-5) tol_failure = 1; } else if (Newton_mode == 2) { VecDoub out(2, 0.0); out = YcAndDensityFromCP(sol); if ((abs(out[0])>1.0e-4)||(abs(out[1]))>1.0e-5) tol_failure = 1; } cout << "Newton error. Test tol = " << tol_failure << endl; if (tol_failure == 1) { cout << "Newton inputs : " << Z_newton << " " << Zv_newton << " " << Yc_newton << " " << rho_newton << " " << C_newton << " " << P_newton*P_scale << endl; cout << "C0 : " << C0 << " P0 : " << P0 << endl; cout << " Check : " << check << endl; if (Newton_mode == 2) { cout << " sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl; } else if (Newton_mode == 1) { cout << " sol : P = " << sol2[0]*P_scale << endl; } // Relaunch with verbose verbose_newton = true; try { Int MaxIter = 200; if (Newton_mode == 1) { sol2[0] = P_newton; C_newton = 1.0; cout << "Reinit with " << sol2[0] << " " << MaxIter << endl; newt(sol2, check, usrfunc_wrapper2, MaxIter); } else if (Newton_mode == 2) { // usual sol[0] = C_newton; sol[1] = P_newton; cout << "Reinit with " << sol[0] << " " << sol[1] << " " << MaxIter << endl; newt(sol, check, usrfunc_wrapper, MaxIter); } else {cerr << "Impossible value of Newton_mode: " << Newton_mode << endl;} } catch (int e2) { cout << "Bis Newton inputs : " << Z_newton << " " << Zv_newton << " " << Yc_newton << " " << rho_newton << " " << C_newton << " " << P_newton*P_scale << endl; cout << "Bis Check : " << check << endl; if (Newton_mode == 2) { cout << "Bis sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl; } else if (Newton_mode == 1) { cout << "Bis sol : P = " << sol2[0]*P_scale << endl; } throw(-1); } throw(-1); } } if (Newton_mode == 2) { C_newton = sol[0]; P_newton = sol[1]; } else if (Newton_mode == 1) { P_newton = sol2[0]; } C = C_newton; P = P_newton*P_scale; }
bool AdFront2 :: SameSide (const Point<2> & lp1, const Point<2> & lp2, const Array<int> * testfaces) const { int cnt = 0; if (testfaces) { for (int ii = 0; ii < testfaces->Size(); ii++) if (lines[(*testfaces)[ii]].Valid()) { int i = (*testfaces)[ii]; const Point<3> & p13d = points[lines[i].L().I1()].P(); const Point<3> & p23d = points[lines[i].L().I2()].P(); Point<2> p1(p13d(0), p13d(1)); Point<2> p2(p23d(0), p23d(1)); // p1 + alpha v = lp1 + beta vl Vec<2> v = p2-p1; Vec<2> vl = lp2 - lp1; Mat<2,2> mat, inv; Vec<2> rhs, sol; mat(0,0) = v(0); mat(1,0) = v(1); mat(0,1) = -vl(0); mat(1,1) = -vl(1); rhs = lp1-p1; if (Det(mat) == 0) continue; CalcInverse (mat, inv); sol = inv * rhs; if (sol(0) >= 0 && sol(0) <= 1 & sol(1) >= 0 && sol(1) <= 1) { cnt++; } } } else { for (int i = 0; i < lines.Size(); i++) if (lines[i].Valid()) { const Point<3> & p13d = points[lines[i].L().I1()].P(); const Point<3> & p23d = points[lines[i].L().I2()].P(); Point<2> p1(p13d(0), p13d(1)); Point<2> p2(p23d(0), p23d(1)); // p1 + alpha v = lp1 + beta vl Vec<2> v = p2-p1; Vec<2> vl = lp2 - lp1; Mat<2,2> mat, inv; Vec<2> rhs, sol; mat(0,0) = v(0); mat(1,0) = v(1); mat(0,1) = -vl(0); mat(1,1) = -vl(1); rhs = lp1-p1; if (Det(mat) == 0) continue; CalcInverse (mat, inv); sol = inv * rhs; if (sol(0) >= 0 && sol(0) <= 1 & sol(1) >= 0 && sol(1) <= 1) { cnt++; } } } return ((cnt % 2) == 0); }
void PressureTable::ComputeDatabaseInputs_FromT( const double rho, const double Z, const double Zv, const double Yc, const double T, double &P, double &Sz , double &C, double P0, double C0) { // Compute normalized variance double eps = 1.0e-3; Sz = ComputeNormalizedVariance(Z, Zv); // Compute normalized progress variable Z_newton = Z; Zv_newton = Sz; Yc_newton = Yc; rho_newton = rho; T_newton = T; // I need to solve ( Yc(C,P) - Yc_target , rho(C,P) - rho_target) = (0 , 0) C_newton = C0; P_newton = P0/P_scale;// Pressure is rescaled verbose_newton = false; Bool check; VecDoub_IO sol2(1, 0.0); VecDoub_IO sol(2, 0.0); int Newton_mode; try { // Get Approximation of Yceq from highest pressure int nPress = GetDimension1(); double P_max = GetCoordinate1(nPress-1); int nC = GetDimension4(); double C_max = GetCoordinate4(nC-2); // Maximum C value before one double Yc_eq = Lookup(P_max,Z_newton,Zv_newton,1.0,"PROG"); double Yc_max = Lookup(P_max,Z_newton,Zv_newton,C_max,"PROG"); // If Yc_eq is small, C is set to 1 and we look for pressure only if ((Yc_eq < eps)||(Yc > Yc_max)) { Newton_mode = 1; sol2[0] = P_newton; C_newton = 1.0; newt(sol2, check, usrfunc_wrapper4); } else { // usual Newton_mode = 2; sol[0] = C_newton; sol[1] = P_newton; try {newt(sol, check, usrfunc_wrapper3);} catch (int e) { cout << "relaunched with Newton_mode = 1" << endl; Newton_mode = 1; C_newton = sol[0]; sol2[0] = P0/P_scale; newt(sol2, check, usrfunc_wrapper4); } } } catch (int e) { int tol_failure = 0; if (Newton_mode == 1) { VecDoub out(1, 0.0); out = DensityFromP(sol2); if (abs(out[0]) > 1.0e-5) tol_failure = 1; } else if (Newton_mode == 2) { VecDoub out(2, 0.0); out = YcAndDensityFromCP(sol); if ((abs(out[0])>1.0e-4)||(abs(out[1]))>1.0e-5) tol_failure = 1; } cout << "Newton error. Test tol = " << tol_failure << endl; if (tol_failure == 1) { cout << "Newton inputs : " << Z_newton << " " << Zv_newton << " " << Yc_newton << " " << rho_newton << " " << C_newton << " " << P_newton*P_scale << endl; cout << "C0 : " << C0 << " P0 : " << P0 << endl; cout << " Check : " << check << endl; if (Newton_mode == 2) { cout << " sol : C = " << sol[0] << " , P = " << sol[1]*P_scale << endl; } else if (Newton_mode == 1) { cout << " sol : P = " << sol2[0]*P_scale << endl; } } } if (Newton_mode == 2) { C_newton = sol[0]; P_newton = sol[1]; } else if (Newton_mode == 1) { P_newton = sol2[0]; } C = C_newton; P = P_newton*P_scale; }
/*! * does the anisotropic filtering */ int NLD:: execute() { cout << "Filter options:" << endl; cout << "tau = " << tau << endl; cout << "time_steps = " << time_steps << endl; cout << "precision = " << epsilon << endl; cout << "multigrid levels = " << levels << endl; cout << "fixed_coeffs = " << fixed_coeffs << endl; cout << "anicoeff1 = " << anicoeff1 << endl; cout << "anicoeff2 = " << anicoeff2 << endl; cout << "anicoeff3 = " << anicoeff3 << endl; cout << "dependence_type = " << dependence_type << endl; cout << "lambda = " << lambda << endl; cout << "integration_size_x = " << integration_size_x << endl; cout << "integration_size_y = " << integration_size_y << endl; cout << "integration_size_z = " << integration_size_z << endl; cout << "geometry_type = " << gt << endl; cout << "ip_flag = " << ip_flag << endl; // initialise matrix Array<int> sizes(3); sizes.SetElement(1,dc->GetSize()[1]); sizes.SetElement(2,dc->GetSize()[2]); sizes.SetElement(3,dc->GetSize()[3]); int code; // errorcode; time_t time1, time2, timediff; for ( int i = 1; i <= time_steps; i++ ){ cout << "Time step " << i << " :" << endl; SparseMatrix<NeuraDataType> matA(sizes); //delete marker1; // initialise discretation FV_3d27 disc(&matA,ip_flag); disc.SetLambda(lambda); disc.SetAniCoefficients(anicoeff1, anicoeff2, anicoeff3); disc.SetFixedCoefficients(fixed_coeffs); disc.SetDependenceType(dependence_type); disc.SetIntegrationSizeX(integration_size_x); disc.SetIntegrationSizeY(integration_size_y); disc.SetIntegrationSizeZ(integration_size_z); disc.SetGeometryType(gt); // initialise right hand side MultiVector<NeuraDataType> rhs; dc->CopyIntoMultiVector(rhs); //delete marker2; // initialise solution MultiVector<NeuraDataType> sol(rhs); sol.SetZero(); // initialise multigrid Multigrid<NeuraDataType> multigrid; // important: precision has to be set before initializing multigrid! multigrid.SetPrecision(epsilon); // set multigrid properties // make sure that precision was setted before! multigrid.Initialise(REGULAR, MATRIX_DEPENDENT_INTERPOLATION, MATRIX_DEPENDENT_RESTRICTION, alpha, LEXICOGRAPHIC_GAUSS_SEIDEL, 2, 2, V, BICGSTAB, NODES, levels); multigrid.SaveProlongation(); multigrid.SaveRestriction(); multigrid.SetMaximumSteps(50); dc->CopyIntoMultiVector(rhs); dc->CopyIntoMultiVector(sol); cout << "discretize..." << endl; time1 = time(NULL); code = disc.discretize(*dc); if ( code ) return code; cout << "NLD: Ich komme hier an!" << endl; disc.SetTimeDependent(tau); time2 = time(NULL); cout << "...discretation finished" << endl; timediff = time2-time1; cout << "discretation took " << timediff << " seconds" << endl; cout << "BuildMatrixHierarchy..." << endl; if ( levels > 1 ) { if ( ( !pow_of_two(dc->GetSize()[1]-1) ) || ( !pow_of_two(dc->GetSize()[2]-1) ) || ( !pow_of_two(dc->GetSize()[3]-1) ) ) { return SIZE_NOT_POW_OF_TWO_PLUS_ONE; } } time1 = time(NULL); multigrid.BuildMatrixHierarchy(matA); time2 = time(NULL); cout << "...done" << endl; timediff = time2-time1; cout << "building matrix hierarchy took " << timediff << " seconds" << endl; cout << "solve by multigrid method..." << endl; time1 = time(NULL); multigrid.Solve(rhs,sol); time2 = time(NULL); cout << "......done" << endl; timediff = time2-time1; cout << "soluting took " << timediff << " seconds" << endl; dc->CopyFromMultiVector(sol); } cout <<"quit nld now" << endl; return OK; }
Real MAST::ComplexAssemblyBase::residual_l2_norm(const libMesh::NumericVector<Real>& real, const libMesh::NumericVector<Real>& imag) { START_LOG("complex_solve()", "Residual-L2"); MAST::NonlinearSystem& nonlin_sys = _system->system(); // iterate over each element, initialize it and get the relevant // analysis quantities RealVectorX sol, vec_re; RealMatrixX mat_re; ComplexVectorX delta_sol, vec; ComplexMatrixX mat; std::vector<libMesh::dof_id_type> dof_indices; const libMesh::DofMap& dof_map = nonlin_sys.get_dof_map(); std::unique_ptr<libMesh::NumericVector<Real> > residual_re(nonlin_sys.solution->zero_clone().release()), residual_im(nonlin_sys.solution->zero_clone().release()), localized_base_solution, localized_real_solution(build_localized_vector(nonlin_sys, real).release()), localized_imag_solution(build_localized_vector(nonlin_sys, imag).release()); if (_base_sol) localized_base_solution.reset(build_localized_vector(nonlin_sys, *_base_sol).release()); // if a solution function is attached, initialize it //if (_sol_function) // _sol_function->init( X); libMesh::MeshBase::const_element_iterator el = nonlin_sys.get_mesh().active_local_elements_begin(); const libMesh::MeshBase::const_element_iterator end_el = nonlin_sys.get_mesh().active_local_elements_end(); MAST::ComplexAssemblyElemOperations& ops = dynamic_cast<MAST::ComplexAssemblyElemOperations&>(*_elem_ops); for ( ; el != end_el; ++el) { const libMesh::Elem* elem = *el; dof_map.dof_indices (elem, dof_indices); ops.init(*elem); // get the solution unsigned int ndofs = (unsigned int)dof_indices.size(); sol.setZero(ndofs); delta_sol.setZero(ndofs); vec.setZero(ndofs); mat.setZero(ndofs, ndofs); // set zero velocity for base solution ops.set_elem_velocity(sol); // set the value of the base solution, if provided if (_base_sol) for (unsigned int i=0; i<dof_indices.size(); i++) sol(i) = (*localized_base_solution)(dof_indices[i]); ops.set_elem_solution(sol); // set the value of the small-disturbance solution for (unsigned int i=0; i<dof_indices.size(); i++) delta_sol(i) = Complex((*localized_real_solution)(dof_indices[i]), (*localized_imag_solution)(dof_indices[i])); ops.set_elem_complex_solution(delta_sol); // if (_sol_function) // ops.attach_active_solution_function(*_sol_function); // perform the element level calculations ops.elem_calculations(false, vec, mat); ops.clear_elem(); // ops.detach_active_solution_function(); // add to the real part of the residual vec_re = vec.real(); DenseRealVector v; MAST::copy(v, vec_re); dof_map.constrain_element_vector(v, dof_indices); residual_re->add_vector(v, dof_indices); // now add to the imaginary part of the residual vec_re = vec.imag(); v.zero(); MAST::copy(v, vec_re); dof_map.constrain_element_vector(v, dof_indices); residual_im->add_vector(v, dof_indices); } // if a solution function is attached, clear it if (_sol_function) _sol_function->clear(); residual_re->close(); residual_im->close(); // return the residual Real l2_real = residual_re->l2_norm(), l2_imag = residual_im->l2_norm(); STOP_LOG("complex_solve()", "Residual-L2"); return sqrt(pow(l2_real,2) + pow(l2_imag,2)); }
int main() { int a, b, c; a = 1, b = 2; c = sol( a, b ); }
void MAST::ComplexAssemblyBase:: residual_and_jacobian_field_split (const libMesh::NumericVector<Real>& X_R, const libMesh::NumericVector<Real>& X_I, libMesh::NumericVector<Real>& R_R, libMesh::NumericVector<Real>& R_I, libMesh::SparseMatrix<Real>& J_R, libMesh::SparseMatrix<Real>& J_I) { libmesh_assert(_system); libmesh_assert(_discipline); libmesh_assert(_elem_ops); MAST::NonlinearSystem& nonlin_sys = _system->system(); R_R.zero(); R_I.zero(); J_R.zero(); J_I.zero(); // iterate over each element, initialize it and get the relevant // analysis quantities RealVectorX sol, vec_re; RealMatrixX mat_re; ComplexVectorX delta_sol, vec; ComplexMatrixX mat; std::vector<libMesh::dof_id_type> dof_indices; const libMesh::DofMap& dof_map = _system->system().get_dof_map(); std::unique_ptr<libMesh::NumericVector<Real> > localized_base_solution, localized_real_solution, localized_imag_solution; // localize the base solution, if it was provided if (_base_sol) localized_base_solution.reset(build_localized_vector(nonlin_sys, *_base_sol).release()); // localize sol to real vector localized_real_solution.reset(build_localized_vector(nonlin_sys, X_R).release()); // localize sol to imag vector localized_imag_solution.reset(build_localized_vector(nonlin_sys, X_I).release()); // if a solution function is attached, initialize it //if (_sol_function) // _sol_function->init( X); libMesh::MeshBase::const_element_iterator el = nonlin_sys.get_mesh().active_local_elements_begin(); const libMesh::MeshBase::const_element_iterator end_el = nonlin_sys.get_mesh().active_local_elements_end(); MAST::ComplexAssemblyElemOperations& ops = dynamic_cast<MAST::ComplexAssemblyElemOperations&>(*_elem_ops); for ( ; el != end_el; ++el) { const libMesh::Elem* elem = *el; dof_map.dof_indices (elem, dof_indices); ops.init(*elem); // get the solution unsigned int ndofs = (unsigned int)dof_indices.size(); sol.setZero(ndofs); delta_sol.setZero(ndofs); vec.setZero(ndofs); mat.setZero(ndofs, ndofs); // first set the velocity to be zero ops.set_elem_velocity(sol); // next, set the base solution, if provided if (_base_sol) for (unsigned int i=0; i<dof_indices.size(); i++) sol(i) = (*localized_base_solution)(dof_indices[i]); ops.set_elem_solution(sol); // set the value of the small-disturbance solution for (unsigned int i=0; i<dof_indices.size(); i++) delta_sol(i) = Complex((*localized_real_solution)(dof_indices[i]), (*localized_imag_solution)(dof_indices[i])); ops.set_elem_complex_solution(delta_sol); // if (_sol_function) // physics_elem->attach_active_solution_function(*_sol_function); // perform the element level calculations ops.elem_calculations(true, vec, mat); ops.clear_elem(); vec *= -1.; //physics_elem->detach_active_solution_function(); // extract the real or the imaginary part of the matrix/vector // The complex system of equations // (J_R + i J_I) (x_R + i x_I) + (r_R + i r_I) = 0 // is rewritten as // [ J_R -J_I] {x_R} + {r_R} = {0} // [ J_I J_R] {x_I} + {r_I} = {0} // DenseRealVector v; DenseRealMatrix m; // copy the real part of the residual and Jacobian MAST::copy(v, vec.real()); MAST::copy(m, mat.real()); dof_map.constrain_element_matrix_and_vector(m, v, dof_indices); R_R.add_vector(v, dof_indices); J_R.add_matrix(m, dof_indices); // copy the imag part of the residual and Jacobian v.zero(); m.zero(); MAST::copy(v, vec.imag()); MAST::copy(m, mat.imag()); dof_map.constrain_element_matrix_and_vector(m, v, dof_indices); R_I.add_vector(v, dof_indices); J_I.add_matrix(m, dof_indices); } // if a solution function is attached, clear it //if (_sol_function) // _sol_function->clear(); R_R.close(); R_I.close(); J_R.close(); J_I.close(); libMesh::out << "R_R: " << R_R.l2_norm() << " R_I: " << R_I.l2_norm() << std::endl; }
int main() { #ifdef _AUTODIFF #ifdef FAD const int dim = 3; const int nstate = dim+2; const int nphi = 6; // emulating state variables TPZVec<TPZDiffMatrix<REAL> > Ai, Tau; TPZVec<TPZVec<REAL> > TauDiv; TPZVec<TPZDiffMatrix<REAL> > TaudDiv; /*char ArtDiff[32]="LS";*/ TPZArtDiffType artDiffType = LeastSquares_AD; TPZFMatrix dsol(dim,nstate); TPZFMatrix dphi(dim,nphi); TPZVec<REAL> phi(nphi); TPZVec<REAL> sol(nstate); TPZVec<FADREAL> FADsol(nstate); TPZVec<FADREAL> FADdsol(nstate*dim); TPZVec<TPZVec<FADREAL> > FADTauDiv; // generating data TPZArtDiff ArtDiff(artDiffType, 1.4); //solution sol[0]=2.; sol[1]=3.; sol[2]=5.; sol[3]=7.; sol[4]=11.; //phi phi[0]=2.3; phi[1]=3.5; phi[2]=5.7; phi[3]=7.11; phi[4]=11.13; phi[5]=13.17; //dphi int i; int j; for(i=0;i<dim;i++) for(j=0;j<nphi;j++) dphi(i,j)=45.8*i-3.2*j; // any choice //dsol for(i=0;i<dim;i++) for(j=0;j<nstate;j++) dsol(i,j)=49.8*i-3.1*j; // any choice int k, l; //FADsol for(i=0;i<nstate;i++) { FADsol[i]=sol[i]; FADsol[i].diff(0,nphi*nstate); FADsol[i].fastAccessDx(0)=0.; for(j=0;j<nphi;j++)FADsol[i].fastAccessDx(i+j*nstate)=phi[j]; } /* FADREAL teste; for(i=0;i<FADsol.NElements();i++)teste+=FADsol[i]; cout << "\n\nFADsol\n" << teste; cout << "\n\nphi\n" << phi; */ //FADdSol for(k=0;k<dim;k++) for(i=0;i<nstate;i++) { FADdsol[k+i*dim]=dsol(k,i); FADdsol[k+i*dim].diff(0,nphi*nstate); FADdsol[k+i*dim].fastAccessDx(0)=0.; for(j=0;j<nphi;j++) FADdsol[k+i*dim].fastAccessDx(i+j*nstate)=dphi(k,j); } /* cout << "\n\nFADdsol\n"; teste=0; for(i=0;i<FADdsol.NElements();i+=3)teste+=FADdsol[i]; cout << teste << endl; teste=0; for(i=1;i<FADdsol.NElements();i+=3)teste+=FADdsol[i]; cout << teste << endl; teste=0; for(i=2;i<FADdsol.NElements();i+=3)teste+=FADdsol[i]; cout << teste << endl; //cout << "\n\nFADdsol\n" << FADdsol; cout << "\n\ndphi\n" << dphi; */ TPZFMatrix Jac(dim,dim,1.); ArtDiff.PrepareFastDiff(dim,Jac, sol, dsol, dphi, TauDiv, &TaudDiv); ArtDiff.PrepareFastDiff(dim, Jac, FADsol, FADdsol, FADTauDiv); cout << "\n\nFADTauDiv\n" << FADTauDiv; cout << "\n\nTauDiv\n" << TauDiv; cout << "\n\nTaudDiv\n" << TaudDiv; #endif #endif return 0; }
int main(int argc, char* argv[]) { // STATUS MESSAGE std::string usage("This application solve the problem of the ECMA "); usage += "project, using different solver. You can chose the solver that you want to "; usage += "use with the --solver flag. Usage is defined below. You also have to set a "; usage += "instance file with the flag --instance, and you can define an output file.\n"; usage += "Simple usage : \n\t"; usage += argv[0]; usage += " --solver=frontal --instance=path_to_instance"; gflags::SetUsageMessage(usage); // VERSION MESSAGE gflags::SetVersionString(ecma::helpers::to_string(ECMA_VERSION_MAJOR) + "." + ecma::helpers::to_string(ECMA_VERSION_MINOR) + "." + ecma::helpers::to_string(ECMA_VERSION_PATCH) + " -- Build type : " + CMAKE_BUILD_TYPE); // Parsing flags gflags::ParseCommandLineFlags(&argc, &argv, true); // NoHelp // Initialize Google's logging library. FLAGS_stderrthreshold = 0; FLAGS_log_dir = FLAGS_logFile; google::InitGoogleLogging(argv[0]); if (FLAGS_instance == "") { LOG(ERROR) << "You have to pass an instance through the --instance flag"; LOG(FATAL) << "Wrong Parameters"; } else { // Démarrage d'un chronomètre time_t start_time; time(&start_time); LOG(INFO) << "Reading Data from instance : " << FLAGS_instance; Data data; ecma::reader::read_instance(data, FLAGS_instance); Solution sol(data); double cost; bool is_admissible; std::string description; int borne = 10000; // Computation of the born in any cases. std::string tag = std::string(FLAGS_instance).substr(std::string(FLAGS_instance).find("projet")); ecma::constants::init(); // Si la borne est dans la map de donnée, load it if (ecma::constants::bornes.find(tag) != ecma::constants::bornes.end()) { borne = ecma::constants::bornes[tag]; } // GreedySolverWithoutConnexity greedy_solver_without_connexity(data); // description = greedy_solver_without_connexity.name() + " : " + greedy_solver_without_connexity.description(); // // LOG(INFO) << description; // greedy_solver_without_connexity.solve(); // borne = greedy_solver_without_connexity.sol().compute_cost(); LOG(INFO) << "Borne :\t" << borne; // Solving this instance using "Solver" if (FLAGS_solver == "stupid") { // Solve via Stupid Solver StupidSolver stupid_solver(data); description = stupid_solver.name() + " : " + stupid_solver.description(); LOG(INFO) << description; stupid_solver.solve(); sol.fill_sol(stupid_solver.sol()); } else if (FLAGS_solver == "frontal") { // Solve via Frontal Solver FrontalSolver frontal_solver(data); description = frontal_solver.name() + " : " + frontal_solver.description(); LOG(INFO) << description; frontal_solver.solve(borne); sol.fill_sol(frontal_solver.sol()); } else if (FLAGS_solver == "frontalWconnexity") { // Solve via greedy Solver GreedySolverWithoutConnexity greedy_solver_without_connexity(data); if (not(greedy_solver_without_connexity.solve())) LOG(FATAL) << "Greedy solver failed !"; // Solve via Frontal Solver FrontalSolverWithoutConnexity frontal_solver_without_connexity(data); description = frontal_solver_without_connexity.name() + " : " + frontal_solver_without_connexity.description(); LOG(INFO) << description; frontal_solver_without_connexity.sol_ptr()->fill_sol(greedy_solver_without_connexity.sol()); frontal_solver_without_connexity.solve(borne,true); sol.fill_sol(frontal_solver_without_connexity.sol()); } else if (FLAGS_solver == "warmGreedyFrontal") { // Solve via greedy Solver GreedySolver greedy_solver(data); if (not(greedy_solver.solve())) LOG(FATAL) << "Greedy solver failed !"; // Solve via Frontal Solver FrontalSolver frontal_solver(data); description = frontal_solver.name() + " : " + frontal_solver.description(); LOG(INFO) << description; frontal_solver.sol_ptr()->fill_sol(greedy_solver.sol()); frontal_solver.solve(borne,true); sol.fill_sol(frontal_solver.sol()); } else if (FLAGS_solver == "warmAnnealingFrontal") { AnnealingSolver annealing_solver(data); if (not(annealing_solver.solve(FLAGS_tempInit))) LOG(FATAL) << "Greedy solver failed !"; // Solve via Frontal Solver FrontalSolver frontal_solver(data); description = frontal_solver.name() + " : " + frontal_solver.description(); LOG(INFO) << description; frontal_solver.sol_ptr()->fill_sol(annealing_solver.sol()); frontal_solver.solve(borne,true); sol.fill_sol(frontal_solver.sol()); } else if (FLAGS_solver == "greedy") { // Solve via Greedy Solver GreedySolver greedy_solver(data); description = greedy_solver.name() + " : " + greedy_solver.description(); LOG(INFO) << description; greedy_solver.solve(); sol.fill_sol(greedy_solver.sol()); } else if (FLAGS_solver == "greedyWconnexity") { // Solve via Greedy Solver Without connexity GreedySolverWithoutConnexity greedy_solver_without_connexity(data); description = greedy_solver_without_connexity.name() + " : " + greedy_solver_without_connexity.description(); LOG(INFO) << description; greedy_solver_without_connexity.solve(); sol.fill_sol(greedy_solver_without_connexity.sol()); } else if (FLAGS_solver == "constraint") { // Solve via Constraint Solver ConstraintSolver constaint_solver(data); description = constaint_solver.name() + " : " + constaint_solver.description(); LOG(INFO) << description; constaint_solver.solve(borne); sol.fill_sol(constaint_solver.sol()); } else if (FLAGS_solver == "annealing") { // Solve via Annealing Solver // GreedySolver greedy_solver(data); // if (not(greedy_solver.solve())) LOG(FATAL) << "Greedy solver failed !"; AnnealingSolver annealing_solver(data); description = annealing_solver.name() + " : " + annealing_solver.description(); LOG(INFO) << description; // annealing_solver.sol_ptr()->fill_sol(greedy_solver.sol()); annealing_solver.solve(FLAGS_tempInit); sol.fill_sol(annealing_solver.sol()); } else if (FLAGS_solver == "annealing1") { AnnealingSolver annealing_solver(data); description = annealing_solver.name() + " : " + annealing_solver.description(); LOG(INFO) << description; Solution* sol_i = annealing_solver.sol_ptr(); for (int i = 0; i < sol_i->x_.size(); ++i) for (int j = 0; j < sol_i->x_[i].size(); ++j) sol_i->x_[i][j] = 1; annealing_solver.solve(FLAGS_tempInit,true); sol.fill_sol(annealing_solver.sol()); } else if (FLAGS_solver == "ant") { // Solve via Ant Solver AntSolver ant_solver(data); description = ant_solver.name() + " : " + ant_solver.description(); LOG(INFO) << description; ant_solver.solve(); sol.fill_sol(ant_solver.sol()); } else if (FLAGS_solver == "mix") { // Solve via Annealing Solver GreedySolver greedy_solver(data); if (not(greedy_solver.solve())) LOG(FATAL) << "Greedy solver failed !"; AnnealingSolver annealing_solver(data); description = annealing_solver.name() + " : " + annealing_solver.description(); LOG(INFO) << description; annealing_solver.sol_ptr()->fill_sol(greedy_solver.sol()); annealing_solver.solve(FLAGS_tempInit,true); sol.fill_sol(annealing_solver.sol()); } else if (FLAGS_solver == "test") { // Solve via Test Solver TestSolver test_solver(data); description = test_solver.name() + " : " + test_solver.description(); LOG(INFO) << description; test_solver.solve(); sol.fill_sol(test_solver.sol()); AnnealingSolver annealing_solver(data); LOG(INFO) << description; annealing_solver.sol_ptr()->fill_sol(test_solver.sol()); annealing_solver.solve(FLAGS_tempInit,true); sol.fill_sol(annealing_solver.sol()); } else { LOG(FATAL) << "Wrong solver id, use the --solver tag, with stupid, frontal, or constraint"; } // Arrêt et exploitation du chronomètre time_t end_time; time(&end_time); double diff = difftime(end_time, start_time); // Data exportation data.print(); cost = sol.compute_cost(); is_admissible = sol.ratio() >= 2 && sol.is_connex(); sol.print(); LOG(INFO) << "Temps de calcul:\t" << diff << " seconds"; LOG(INFO) << "Borne :\t" << borne; if (is_admissible || FLAGS_solver == "frontalWconnexity" || FLAGS_solver == "greedyWconnexity") { ecma::writer::write_in_synthetic_res_file( cost, description, FLAGS_instance, diff, FLAGS_synRes); ecma::writer::export_solution(sol, FLAGS_solDir, diff); } else LOG(ERROR) << "The solution is not admissible"; } return 0; }
void TransportGradientPeriodic :: computeTangent(FloatMatrix &k, TimeStep *tStep) { EModelDefaultEquationNumbering fnum; //DofIDEquationNumbering pnum(true, this->grad_ids); EModelDefaultPrescribedEquationNumbering pnum; int nsd = this->domain->giveNumberOfSpatialDimensions(); EngngModel *rve = this->giveDomain()->giveEngngModel(); ///@todo Get this from engineering model std :: unique_ptr< SparseLinearSystemNM > solver( classFactory.createSparseLinSolver( ST_Petsc, this->domain, this->domain->giveEngngModel() ) ); // = rve->giveLinearSolver(); SparseMtrxType stype = solver->giveRecommendedMatrix(true); std :: unique_ptr< SparseMtrx > Kff( classFactory.createSparseMtrx( stype ) ); std :: unique_ptr< SparseMtrx > Kfp( classFactory.createSparseMtrx( stype ) ); std :: unique_ptr< SparseMtrx > Kpp( classFactory.createSparseMtrx( stype ) ); Kff->buildInternalStructure(rve, this->domain->giveNumber(), fnum); int neq = Kff->giveNumberOfRows(); Kfp->buildInternalStructure(rve, this->domain->giveNumber(), fnum, pnum); Kpp->buildInternalStructure(rve, this->domain->giveNumber(), pnum); //Kfp->buildInternalStructure(rve, neq, nsd, {}, {}); //Kpp->buildInternalStructure(rve, nsd, nsd, {}, {}); #if 1 rve->assemble(*Kff, tStep, TangentAssembler(TangentStiffness), fnum, this->domain); rve->assemble(*Kfp, tStep, TangentAssembler(TangentStiffness), fnum, pnum, this->domain); rve->assemble(*Kpp, tStep, TangentAssembler(TangentStiffness), pnum, this->domain); #else auto ma = TangentAssembler(TangentStiffness); IntArray floc, ploc; FloatMatrix mat, R; int nelem = domain->giveNumberOfElements(); #ifdef _OPENMP #pragma omp parallel for shared(Kff, Kfp, Kpp) private(mat, R, floc, ploc) #endif for ( int ielem = 1; ielem <= nelem; ielem++ ) { Element *element = domain->giveElement(ielem); // skip remote elements (these are used as mirrors of remote elements on other domains // when nonlocal constitutive models are used. They introduction is necessary to // allow local averaging on domains without fine grain communication between domains). if ( element->giveParallelMode() == Element_remote || !element->isActivated(tStep) ) { continue; } ma.matrixFromElement(mat, *element, tStep); if ( mat.isNotEmpty() ) { ma.locationFromElement(floc, *element, fnum); ma.locationFromElement(ploc, *element, pnum); ///@todo This rotation matrix is not flexible enough.. it can only work with full size matrices and doesn't allow for flexibility in the matrixassembler. if ( element->giveRotationMatrix(R) ) { mat.rotatedWith(R); } #ifdef _OPENMP #pragma omp critical #endif { Kff->assemble(floc, mat); Kfp->assemble(floc, ploc, mat); Kpp->assemble(ploc, mat); } } } Kff->assembleBegin(); Kfp->assembleBegin(); Kpp->assembleBegin(); Kff->assembleEnd(); Kfp->assembleEnd(); Kpp->assembleEnd(); #endif FloatMatrix grad_pert(nsd, nsd), rhs, sol(neq, nsd); grad_pert.resize(nsd, nsd); grad_pert.beUnitMatrix(); // Workaround since the matrix size is inflexible with custom dof numbering (so far, planned to be fixed). IntArray grad_loc; this->grad->giveLocationArray(this->grad_ids, grad_loc, pnum); FloatMatrix pert(Kpp->giveNumberOfRows(), nsd); pert.assemble(grad_pert, grad_loc, {1,2,3}); //pert.printYourself("pert"); //printf("Kfp = %d x %d\n", Kfp->giveNumberOfRows(), Kfp->giveNumberOfColumns()); //printf("Kff = %d x %d\n", Kff->giveNumberOfRows(), Kff->giveNumberOfColumns()); //printf("Kpp = %d x %d\n", Kpp->giveNumberOfRows(), Kpp->giveNumberOfColumns()); // Compute the solution to each of the pertubation of eps Kfp->times(pert, rhs); //rhs.printYourself("rhs"); // Initial guess (Taylor assumption) helps KSP-iterations for ( auto &n : domain->giveDofManagers() ) { int k1 = n->giveDofWithID( this->dofs[0] )->__giveEquationNumber(); if ( k1 ) { FloatArray *coords = n->giveCoordinates(); for ( int i = 1; i <= nsd; ++i ) { sol.at(k1, i) = -(coords->at(i) - mCenterCoord.at(i)); } } } if ( solver->solve(*Kff, rhs, sol) & NM_NoSuccess ) { OOFEM_ERROR("Failed to solve Kff"); } // Compute the solution to each of the pertubation of eps Kfp->timesT(sol, k); // Assuming symmetry of stiffness matrix // This is probably always zero, but for generality FloatMatrix tmpMat; Kpp->times(pert, tmpMat); k.subtract(tmpMat); k.times( - 1.0 / ( this->domainSize(this->giveDomain(), this->set) + this->domainSize(this->giveDomain(), this->masterSet) )); // Temp workaround on sizing issue mentioned above: FloatMatrix k2 = k; k.beSubMatrixOf(k2, grad_loc, {1,2,3}); }
//===========================================================================// DecompSolution SDPUC_DecompApp::createInitialSolution(){ int a, i, t, colIndex; int numTimeperiods = m_instance.m_numTimeperiods; int numArcs = m_instance.m_numArcs; int numSwitchings = m_instance.m_numSwitchings; int numNodes = m_instance.m_numNodes; int numCols = numArcs //y1-vars + 3 * numTimeperiods * numArcs //y2-, z-, and x-vars + numTimeperiods * numNodes; //theta-vars SDPUC_Instance::arc * arcs = m_instance.m_arcs; SDPUC_Instance::node * nodes = m_instance.m_nodes; SDPUC_Instance::timeseries * ts = m_instance.m_timeseries; int numACArcs = 0; for(a = 0; a < numArcs; a++){ if(arcs[a].acline == 1) { numACArcs++; } } int numRows = numNodes - 1 //balance + 2 * numArcs // capacity + 2 * numACArcs // and kirchoffs constraints + 1; // max. allowed no. of switches employed sum{z} <= k int col_yStartIndex = 0; int col_zStartIndex = numArcs*(1+numTimeperiods); int col_xStartIndex = numArcs * (1 + 2*numTimeperiods); int col_thetaStartIndex = numArcs*(1 + 3*numTimeperiods) ; double bigM = 100; const int size = numCols; double values_[100000]; const double quality = 1e75; //const double * cost[size]; //double my_non_const_array[100000]; //int dummy = read_array_from_file(my_non_const_array); //double const (&array)[100000] = my_non_const_array; //initialise all values to 0 for(i = 0; i < numCols; i++){ values_[i] = 0; } // set z = 1 for(a = 0; a < numArcs; a++){ for(t = 0; t < numTimeperiods; t++){ colIndex = col_zStartIndex + t * numArcs + a; values_[colIndex] = 1.0; } } double const (&values)[100000] = values_; DecompSolution sol(size, values, quality); return sol; }
int main() { input(); sol(1, 0); }
int main ( void ) /******************************************************************************/ /* Purpose: MAIN is the main program for FEM1D_PMETHOD. Discussion: FEM1D_PMETHOD implements the P-version of the finite element method. Program to solve the one dimensional problem: - d/dX (P dU/dX) + Q U = F by the finite-element method using a sequence of polynomials which satisfy the boundary conditions and are orthogonal with respect to the inner product: (U,V) = Integral (-1 to 1) P U' V' + Q U V dx Here U is an unknown scalar function of X defined on the interval [-1,1], and P, Q and F are given functions of X. The boundary values are U(-1) = U(1)=0. Sample problem #1: U=1-x^4, P=1, Q=1, F=1.0+12.0*x^2-x^4 Sample problem #2: U=cos(0.5*pi*x), P=1, Q=0, F=0.25*pi*pi*cos(0.5*pi*x) The program should be able to get the exact solution for the first problem, using NP = 2. Licensing: This code is distributed under the GNU LGPL license. Modified: 04 July 2013 Author: Original FORTRAN77 version by Max Gunzburger, Teresa Hodge. C version by John Burkardt. Local Parameters: Local, double A[NP+1], the squares of the norms of the basis functions. Local, double ALPHA[NP], BETA[NP], the basis function recurrence coefficients. Local, double F[NP+1]. F contains the basis function coefficients that form the representation of the solution U. That is, U(X) = SUM (I=0 to NP) F(I) * BASIS(I)(X) where "BASIS(I)(X)" means the I-th basis function evaluated at the point X. Local, int NP. The highest degree polynomial to use. Local, int NPRINT. The number of points at which the computed solution should be printed out at the end of the computation. Local, int PROBLEM, indicates the problem being solved. 1, U=1-x^4, P=1, Q=1, F=1.0+12.0*x^2-x^4. 2, U=cos(0.5*pi*x), P=1, Q=0, F=0.25*pi*pi*cos(0.5*pi*x). Local, int QUAD_NUM, the order of the quadrature rule. Local, double QUAD_W[QUAD_NUM], the quadrature weights. Local, double QUAD_X[QUAD_NUM], the quadrature abscissas. */ { # define NP 2 # define QUAD_NUM 10 double a[NP+1]; double alpha[NP]; double beta[NP]; double f[NP+1]; int nprint = 10; int problem = 2; double quad_w[QUAD_NUM]; double quad_x[QUAD_NUM]; timestamp ( ); printf ( "\n" ); printf ( "FEM1D_PMETHOD\n" ); printf ( " C version\n" ); printf ( "\n" ); printf ( " Solve the two-point boundary value problem\n" ); printf ( "\n" ); printf ( " - d/dX (P dU/dX) + Q U = F\n" ); printf ( "\n" ); printf ( " on the interval [-1,1], with\n" ); printf ( " U(-1) = U(1) = 0.\n" ); printf ( "\n" ); printf ( " The P method is used, which represents U as\n" ); printf ( " a weighted sum of orthogonal polynomials.\n" ); printf ( "\n" ); printf ( " Highest degree polynomial to use is %d\n", NP ); printf ( " Number of points to be used for output = %d\n", nprint ); if ( problem == 1 ) { printf ( "\n" ); printf ( " Problem #1:\n" ); printf ( " U=1-x^4,\n" ); printf ( " P=1,\n" ); printf ( " Q=1,\n" ); printf ( " F=1 + 12 * x^2 - x^4\n" ); } else if ( problem == 2 ) { printf ( "\n" ); printf ( " Problem #2:\n" ); printf ( " U=cos(0.5*pi*x),\n" ); printf ( " P=1,\n" ); printf ( " Q=0,\n" ); printf ( " F=0.25*pi*pi*cos(0.5*pi*x)\n" ); } /* Get quadrature abscissas and weights for interval [-1,1]. */ quad ( QUAD_NUM, quad_w, quad_x ); /* Compute the constants for the recurrence relationship that defines the basis functions. */ alpbet ( a, alpha, beta, NP, problem, QUAD_NUM, quad_w, quad_x ); /* Test the orthogonality of the basis functions. */ ortho ( a, alpha, beta, NP, problem, QUAD_NUM, quad_w, quad_x ); /* Solve for the solution of the problem, in terms of coefficients of the basis functions. */ sol ( a, alpha, beta, f, NP, problem, QUAD_NUM, quad_w, quad_x ); /* Print out the solution, evaluated at each of the NPRINT points. */ out ( alpha, beta, f, NP, nprint ); /* Compare the computed and exact solutions. */ exact ( alpha, beta, f, NP, nprint, problem, QUAD_NUM, quad_w, quad_x ); /* Terminate. */ printf ( "\n" ); printf ( "FEM1D_PMETHOD\n" ); printf ( " Normal end of execution.\n" ); printf ( "\n" ); timestamp ( ); return 0; # undef NP # undef QUAD_NUM }