static void printBody(vsop87_body_et body, char *name, double T, DT v_e[3], double e) { DT v[3], v_g[3], v_ec[3], v_eq[3]; sexangle_st ang; if (vsop87_getCoords(v, s_datadir, VSOP87_HELIO_RECT_DATE, body, T)!=0) return; printf("%s\theliocentric:\t", name); printVect(v); printf("\tgeocentric:\t"); VECT3_DIFF(v_g, v, v_e); printVect(v_g); printf("\tecliptic geo:\t"); amsp_coord_rect2ecliptic(v_ec, v_g); amsp_angle_deg2sex(&ang, v_ec[0]*CRG); amsp_angle_sexprint(&ang); printf(" "); amsp_angle_deg2sex(&ang, v_ec[1]*CRG); amsp_angle_sexprint(&ang); printf(" "); printf("%0.9lf\n", v_ec[2]); printf("\tequatorial geo:\t"); amsp_coord_ecliptic2equatorial(v_eq, v_ec, e); amsp_angle_deg2sex(&ang, v_eq[0]*CRG); amsp_angle_sexprint(&ang); printf(" "); amsp_angle_deg2sex(&ang, v_eq[1]*CRG); amsp_angle_sexprint(&ang); printf(" "); printf("%0.9lf\n", v_eq[2]); }
int main() { std::vector<int> vec1{ 1, 99, 99, 4, 8, 98, 96, 3, 5, 19, 23, 17, 84, 23 }; printVect(vec1); if ( containsDuplicate(vec1) ) { std::cout << "Above vector contains duplicates\n"; } else { std::cout << "Above vector does not contain duplicates\n"; } return 0; }
int main(const int argc, char * const *argv) { dtm_st dtm; time_t t; DT T, e; DT v_e[3], v_g[3]; sexangle_st ang; if (argc!=2) { printUsage(); return EXIT_FAILURE; } s_datadir = argv[1]; t = time(NULL); gmtime_r(&t, &dtm.tm); dtm.sec = 0.; T = amsp_date_tm2julian(&dtm); e = amsp_coord_earthEclipticAtDate(T); printf("Earth ecliptic: %f ", e); amsp_angle_deg2sex(&ang, e*CRG); amsp_angle_sexprint(&ang); printf("\n"); if (vsop87_getCoords(v_e, s_datadir, VSOP87_HELIO_RECT_DATE, BODY_EARTH, T)!=0) return EXIT_FAILURE; printf("Earth heliocentric:\t"); printVect(v_e); printf(" geocentric:\t"); VECT3_DIFF(v_g, v_e, v_e); printVect(v_g); printBody(BODY_MERCURY, "Mercury", T, v_e, e); printBody(BODY_VENUS, "Venus", T, v_e, e); printBody(BODY_MARS, "Mars", T, v_e, e); printBody(BODY_JUPITER, "Jupiter", T, v_e, e); printBody(BODY_SATURN, "Saturn", T, v_e, e); printBody(BODY_URANUS, "Uranus", T, v_e, e); vsop87_clearDataCache(); return 0; }
void Engine::stopSearch() { if (isVerbose()) { Rprintf("Emini is: %.10g\n", eMini_); Rprintf("xmini are:\n"); printVect(xMini_); } endTime_ = clock(); timeSpan_ = (double) (endTime_ - startTime_) / CLOCKS_PER_SEC; if (isVerbose()) { Rprintf("Totally it used %.10g secs\n", timeSpan_); Rprintf("No. of function call is: %d\n", nbFctCall_); } }
//Cal saber que a la diagonal hi ha 1. int triinf (int n, double **L, double *b, double tol){ int i, j; for (i = 0; i < n; i++){ if (fabs(L[i][i]) < tol){ printf("Error en els elements de la diagonal: alguns son 0 \n"); return 1; } } //Metode de substitucio endarrere. for (i = 1; i < n; i ++){ for (j = i-1; j >= 0; j--){ b[i] = b[i] - L[i][j] * b[j]; } } printVect(b, n); printf("Calcul realitzat satisfactoriament \n"); return 0; }
int trisup (int n, double **U, double *b, double tol){ int i, j; for (i = 0; i < n; i++){ if (fabs(U[i][i]) < tol){ printf("Error en els elements de la diagonal: alguns son 0 \n"); return 1; } } //Metode de substitucio endarrere. b[n-1] = b[n-1] / U[n-1][n-1]; for (i = n-2; i >= 0; i --){ for (j = i+1; j < n; j++){ b[i] = b[i] - U[i][j] * b[j]; } b[i] = b[i]/U[i][i]; } printVect(b, n); printf("Calcul realitzat satisfactoriament \n"); return 0; }
int Engine::hardSearch() { SEXP s, t, val; SEXP uiMatrix, ciVector; SEXP thetaVector; SEXP xlow; SEXP xhigh; //int lsConvergence = 0; int counts = 0; double mu; int xSize = x_.size(); PROTECT(uiMatrix = allocMatrix(REALSXP, xSize * 2, xSize)); //protect 1 PROTECT(ciVector = allocVector(REALSXP, xSize * 2)); //protect 2 PROTECT(thetaVector = allocVector(REALSXP, xSize)); //protect 3 PROTECT(xlow = allocVector(REALSXP, xSize)); // protect 4 PROTECT(xhigh = allocVector(REALSXP, xSize)); // protect 5 mu = 1.e-4; // Initialize ui with zeros for (int i = 0; i < xSize * 2; ++i) { for (int j = 0; j < xSize; ++j) { REAL(uiMatrix)[i * xSize + j] = 0.; } } for (int i = 0; i < xSize; ++i) { // Initialize theta REAL(thetaVector)[i] = xBuffer_[i]; // Initialize ci REAL(ciVector)[i * 2] = lower_[i]; REAL(ciVector)[i * 2 + 1] = -upper_[i]; REAL(uiMatrix)[i * 2 * xSize + i * 2] = 1.0; REAL(uiMatrix)[i * 2 * xSize + i * 2 + 1] = -1.0; REAL(xlow)[i] = lower_[i]; REAL(xhigh)[i] = upper_[i]; } PROTECT(t = s = allocList(8)); //protect 6 SET_TYPEOF(s, LANGSXP); SETCAR(t, install("LSE")); t = CDR(t); SETCAR(t, thetaVector); SET_TAG(t, install("theta")); t = CDR(t); SETCAR(t, uiMatrix); SET_TAG(t, install("ui")); t = CDR(t); SETCAR(t, ciVector); SET_TAG(t, install("ci")); t = CDR(t); SETCAR(t, ScalarReal(mu)); SET_TAG(t, install("mu")); t = CDR(t); SETCAR(t, xlow); SET_TAG(t, install("xlow")); t = CDR(t); SETCAR(t, xhigh); SET_TAG(t, install("xhigh")); t = CDR(t); SETCAR(t, ScalarInteger(nbFctCall_)); SET_TAG(t, install("count")); for (unsigned int i = 0; i < xBuffer_.size(); ++i) { if (xBuffer_[i] < lower_[i] || xBuffer_[i] > upper_[i]) { Rprintf("PROBLEM WITH x(%d):\n", i); printVect(xBuffer_); } } val = eval(s, rEnv_->R_env); fValue_ = REAL(VECTOR_ELT(val, 0))[0]; //lsConvergence = INTEGER(VECTOR_ELT(val, 1))[0]; for (unsigned int i = 0; i < xBuffer_.size(); ++i) { xBuffer_[i] = REAL(VECTOR_ELT(val, 2))[i]; } counts = INTEGER(VECTOR_ELT(val, 3))[0]; nbFctCall_ = counts; UNPROTECT(6); return 0; }
int Engine::initialize() { // For Tracing std::vector < std::string > keys; keys.push_back("currentEnergy"); keys.push_back("minEnergy"); keys.push_back("nSteps"); keys.push_back("temperature"); tracer_.clear(); tracer_.setKeyList(keys); if (isVerbose()) { Rprintf("Initialization...\n"); } // Init x related vectors try { xRange_.resize(x_.size()); xBackup_.resize(x_.size()); xMini_.resize(x_.size()); xBuffer_.resize(x_.size()); g_.resize(x_.size()); } catch (std::length_error& le) { Rprintf("Engine: Length error: %s\n",le.what()); } itSoftMax_ = x_.size() * 6; factr_ = 1000; pgTol_ = 1.e-6; reps_ = 1.e-6; nbFctCall_ = 0; idum_ = -100377; indTrace_ = 0; // Check markov chain length if (0 != markovLength_ % x_.size()) { Rprintf( "LMarkov should be size of 'x' (recommended) or 2*n or 3*n ... since component.change is 1\n"); return -1; } // if (lsEnd_) // { // markovLength_ = 200 * x_.size(); // if (markovLength_ < 1000) // { // markovLength_ = 1000; // } // else if (markovLength_ > 10000) // { // markovLength_ = 10000; // } // } if (isVerbose()) { Rprintf("LMarkov= %i\n", markovLength_); } for (unsigned int i = 0; i < x_.size(); ++i) { xRange_[i] = upper_[i] - lower_[i]; } if (isVerbose()) { Rprintf("xrange: "); printVect(xRange_); } // Check if starting point is in constraint bool inConstraint = true; bool initError = true; unsigned int reinitCount = 0; while (initError) { if (inConstraint) { if (hasConstraint_) { inConstraint = judgeConstraint(); while (!inConstraint) { coordin(idum_, x_); inConstraint = judgeConstraint(); } } } if (isVerbose()) { Rprintf("The random intial x coordinates:\n"); printVect(x_); } energy(x_); if (isVerbose()) { Rprintf("The energy of initial x = %.10g\n", etot_); } if (etot_ >= BIG_VALUE) { if (isVerbose()) { Rprintf("x: "); printVect(x_); Rprintf( " give NaN, NA, or inf, generating new starting point\n"); } if (reinitCount >= MAX_REINIT_COUNT) { Rprintf("Stopping algorithm because function to optimize create NaN or (+/-) infinity values even with trying new random parameters"); return -1; } double rd = 0; for (unsigned int i=0; i < x_.size(); ++i) { // lower + runif(length(lower))*(upper-lower) rd = Utils::ran2(&idum_); x_[i] = lower_[i] + rd * (upper_[i] - lower_[i]); } reinitCount++; } else { initError = false; } } return 0; }
int Engine::startSearch() { if (isVerbose()) { Rprintf("Starting...\n"); } double temQa; double visit, a, b; int itNew = 0, itDev; double s1, s, t1, t2, r, pqa, pqa1; bool inConstraint = false; bool eMini_NotChanged = true; double eMiniMarkov = 0; int indexNoEminiUpdate = 0; int indexTolEminiUpdate = 1000; dVec xMiniMarkov(x_.size()); if (getIsSimpleFunction()) { indexTolEminiUpdate = x_.size(); } // if (x_.size() <= 2) // { // indexTolEminiUpdate = 3; // } // else if (x_.size() > 2 && x_.size() <= 4) // { // indexTolEminiUpdate = 4 * x_.size(); // } // else if (x_.size() > 4 && x_.size() <= 10) // { // indexTolEminiUpdate = 4 * x_.size(); // } startTime_ = clock(); eMini_ = etot_; xMini_ = x_; etot0_ = etot_; if (isVerbose()) { Rprintf("first time, ind_trace is: %i\n", indTrace_); } // Initialize etot0 and temp if (!lsEnd_) { etot_ = lsEnergy(x_); if (etot_ < eMini_) { eMini_ = etot_; xMini_ = x_; } ++indTrace_; // Do the tracing here tracer_.addValue("currentEnergy", etot0_); tracer_.addValue("minEnergy", eMini_); tracer_.addValue("nSteps", itNew); tracer_.addValue("temperature", temSta_); } if (etot_ < eMini_) { eMini_ = etot_; xMini_ = x_; } etot0_ = etot_; tem_ = temSta_; if (isVerbose()) { Rprintf("The transformed xinitial x: \n"); printVect(x_); Rprintf("The energy of transformed initial x = %.10g\n", etot_); } if (isVerbose()) { Rprintf("At the beginning, etot0= %.10g\n", etot0_); Rprintf("Emini= %.10g\n", eMini_); Rprintf("Current x: "); printVect(x_); Rprintf("Current xmini: "); printVect(xMini_); } if (checkStoping()) { stopSearch(); return 0; } if (isVerbose()) { Rprintf("Number of function call: %i\n", nbFctCall_); } int stepRecord = 0; L2435: // Main loop for (int i = 0; i < maxStep_; ++i) { itNew = i + 1; s1 = (double) itNew; s = s1 + 1.; t1 = exp((qv_ - 1.) * log(2.)) - 1.; t2 = exp((qv_ - 1.) * log(s)) - 1.; tem_ = temSta_ * t1 / t2; stepRecord += 1; if (stepRecord == maxStep_) { break; } if (tem_ < temRestart_) { //printf("*\n"); goto L2435; } temQa = tem_ / (double) itNew; indexNoEminiUpdate++; // Markov loop for (unsigned int j = 0; j < (unsigned) markovLength_; ++j) { if (j == 0) { eMini_NotChanged = true; } if (j == 0 && i == 0) { eMini_NotChanged = false; } xBackup_ = x_; inConstraint = false; while (!inConstraint) { // Loop on coordinates if (j < x_.size()) { for (unsigned int k = 0; k < x_.size(); ++k) { if (isVerbose()) { Rprintf("IDUM before visit: %d\n", idum_); } visit = visita(&qv_, &tem_, &idum_); if (visit > 1.e8) { visit = 1.e8 * Utils::ran2(&idum_); } else if (visit < -1.e8) { visit = -1.e8 * Utils::ran2(&idum_); } x_[k] = visit + xBackup_[k]; a = x_[k] - lower_[k]; b = Utils::dMod(&a, &xRange_[k]) + xRange_[k]; x_[k] = Utils::dMod(&b, &xRange_[k]) + lower_[k]; if (fabs(x_[k] - lower_[k]) < 1.e-10) { x_[k] += 1.e-10; } if (isVerbose()) { Rprintf( "visit: %.10g a: %.10g b: %.10g idum: %d x: %.10g\n", visit, a, b, idum_, x_[k]); } } // end coordinates loop } else { // Now change only one component at a time visit = visita(&qv_, &tem_, &idum_); if (visit > 1.e8) { visit = 1.e8 * Utils::ran2(&idum_); } else if (visit < -1.e8) { visit = -1.e8 * Utils::ran2(&idum_); } int index = j - x_.size(); x_[index] = visit + xBackup_[index]; a = x_[index] - lower_[index]; b = Utils::dMod(&a, &xRange_[index]) + xRange_[index]; x_[index] = Utils::dMod(&b, &xRange_[index]) + lower_[index]; if (fabs(x_[index] - lower_[index]) < 1.e-10) { x_[index] += 1.e-10; } } if (isVerbose()) { Rprintf("\ntem: %.10g temqa: %.10g itnew: %d markov j=%d\n", tem_, temQa, itNew, j); Rprintf("fx are: "); printVect(xBackup_); Rprintf("x are: "); printVect(x_); } if (hasConstraint_) { inConstraint = judgeConstraint(); } else { inConstraint = true; } if (inConstraint) { if (lsEnd_) { if (isVerbose()) { Rprintf("Calling energy\n"); } energy(x_); } else { if (isVerbose()) { Rprintf("Calling lsEnergy\n"); } etot_ = lsEnergy(x_); } if (isVerbose()) { Rprintf("Before judge, etot0= %.10g etot= %.10g\n", etot0_, etot_); } if (etot_ < etot0_) { etot0_ = etot_; if (isVerbose()) { Rprintf("etot is smaller than etot0\n"); } if (etot_ < eMini_) { eMini_ = etot_; xMini_ = x_; eMini_NotChanged = false; indexNoEminiUpdate = 0; } } else { r = Utils::ran2(&idum_); pqa1 = (qa_ - 1.) * (etot_ - etot0_) / temQa + 1.; /* write(*,*)' etot0=',etot0,', etot=',etot,', pqa1=',pqa1 ! r */ if (pqa1 < 0.) { pqa = 0.; } else { pqa = exp(log(pqa1) / (1. - qa_)); } if (isVerbose()) { Rprintf("pqa= %.10g r= %.10g \n", pqa, r); } if (r > pqa) { x_ = xBackup_; } else { etot0_ = etot_; } } // endif etot_ < eMini_ tracer_.addValue("currentEnergy", etot0_); tracer_.addValue("minEnergy", eMini_); tracer_.addValue("nSteps", itNew); tracer_.addValue("temperature", tem_); if (checkStoping()) { stopSearch(); return 0; } } // end else hasConstraint } // end while !inconstraint if (indexNoEminiUpdate >= indexTolEminiUpdate - 1) { if (j == 0) { eMiniMarkov = etot0_; std::copy(x_.begin(), x_.end(), xMiniMarkov.begin()); } else { if (etot0_ < eMiniMarkov) { eMiniMarkov = etot0_; std::copy(x_.begin(), x_.end(), xMiniMarkov.begin()); } } } } // end markov chain loop if (lsEnd_) { if (!eMini_NotChanged) { dVec temp(x_.size()); std::copy(xMini_.begin(), xMini_.end(), temp.begin()); //Rprintf("Xmini:\n"); //printVect(xMini_); // if (isUserVerbose()) // { // Rprintf("Before lsEnergy, itNew: %d eTemp: %.15g x: %.15g %15g\n", itNew, eMini_, temp[0], temp[1]); // } double eTemp = lsEnergy(temp); // if (isUserVerbose()) // { // Rprintf("lsEnergy called, itNew: %d eTemp: %.15g x: %.15g %.15g\n", itNew, eTemp, temp[0], temp[1]); // } if (eTemp < eMini_) { if (isUserVerbose()) { Rprintf("It: %d, obj value: %.10g\n", itNew, eTemp); } std::copy(temp.begin(), temp.end(), xMini_.begin()); eMini_ = eTemp; indexNoEminiUpdate = 0; tracer_.updateLastValue("currentEnergy", etot0_); tracer_.updateLastValue("minEnergy", eMini_); tracer_.updateLastValue("nSteps", itNew); tracer_.updateLastValue("temperature", tem_); } } if (indexNoEminiUpdate >= indexTolEminiUpdate) { //Rprintf("Before lsEnergy, itNew: %d x: %.15g %.15g\n", itNew, xMiniMarkov[0], xMiniMarkov[1]); eMiniMarkov = lsEnergy(xMiniMarkov); //Rprintf("lsEnergy called, itNew: %d eMiniMarkov: %.15g x: %.15g %.15g\n", itNew, eMiniMarkov, xMiniMarkov[0], xMiniMarkov[1]); if (isUserVerbose()) { Rprintf("."); } indexNoEminiUpdate = 0; indexTolEminiUpdate = x_.size(); if (eMiniMarkov < eMini_) { std::copy(xMiniMarkov.begin(), xMiniMarkov.end(), xMini_.begin()); eMini_ = eMiniMarkov; tracer_.updateLastValue("currentEnergy", etot0_); tracer_.updateLastValue("minEnergy", eMini_); tracer_.updateLastValue("nSteps", itNew); tracer_.updateLastValue("temperature", tem_); if (isUserVerbose()) { Rprintf("\nIt: %d, obj value: %.10g\n", itNew, eMini_); } if (checkStoping()) { stopSearch(); return 0; } } } } itDev = itNew % interval_; if (0 == itDev) { if (isVerbose()) { Rprintf(">After one search %d %.10g %.10g %.10g <-- Emini\n", itNew, tem_, etot0_, eMini_); Rprintf("Current x: "); printVect(x_); Rprintf("\nCurrent xmini: "); printVect(xMini_); Rprintf( "\n__________________________________________________\n"); } } } // end step loop stopSearch(); return 0; }
int main (void){ int i, j, n, res, *p, cont = 0; double *b, **mat, **L, **U; printf("Introdueix la dimensio desitjada \n"); scanf(" %d", &n); //Control d'errors, si la dimensio es negativa o 0, hi ha un error. if (n <= 0){ printf("La dimensio introduida no es valida \n"); exit(-1); } /** -----------------------------------------INICIALITZACIONS DELS VECTORS ----------------------------------------------------**/ /** Guardam memoria per la matriu inicial que volem. Per la matriu U que despres necessitarem. Pel vector b de termes indepentents. Pel vector p que ens controla les permutacions **/ //Guardam memoria primer per cada fila de la matriu i despres per cada columna. mat = (double **)malloc(n*sizeof(double *)); U = (double **)malloc(n*sizeof(double *)); if (mat == NULL){ printf("Error a l'assignar memoria de la matriu \n"); exit(1); } if (U == NULL){ printf("Error a l'assignar memoria \n"); } for(i = 0; i < n; i++){ mat[i] = (double *)malloc(n*sizeof(double)); U[i] = (double *)malloc(n*sizeof(double)); if (mat == NULL || U == NULL){ printf("Error a l'assignar memoria de la matriu \n "); exit(1); } } //Guardam memoria per el vector de termes independents de la matriu. p = (int *) malloc(n*sizeof(int)); b = (double *)malloc(n*sizeof(double)); if (p == NULL || b == NULL){ printf("Error a l'assignar memoria del vector \n"); exit(1); } //Inicialitzam els valors de b a 0. for (i = 0; i < n; i++){ p[i] = i+1; b[i] = 0.0; } /** ---------------------------------------------------GENERACIO DE LA MATRIU I DELS TERMES INDEPENTENTS ------------------------------------------------ **/ /* //Generacio de la matriu de Hilbert i del vector de termes independents: for (i = 0; i < n; i++){ for (j = 0; j < n; j++){ mat[i][j] = (double) 1/(i + j + 1); b[i] += mat[i][j]; } } */ for(i = 0; i < n; i ++){ printf("Introdueix els nombres de la fila \n"); for (j = 0; j < n; j++){ scanf("%le", &mat[i][j]); } } //Generam una matriu la solucio del sistema de la qual sigui 1. for (i = 0; i < n; i++){ b[i] = 0; for (j = 0; j < n; j++){ b[i] += mat[i][j]; } } printVect(b, n); /** ----------------------------------------------------OPERACIONS NECESSARIES DEL PROGRAMA ------------------------------------------ **/ //Imprimim la matriu i el seu vector de termes independents per informar a l'usuari: //printf("Matriu generada: \n"); //printMat(mat, n, n); //1. APLICAM ELIMINACIO GAUSSIANA AMB PIVOTATGE: //Resolem pel metode de palu. Si el resultat ens dona -1 vol dir que hem fet algun error. Sortim. res = palu(n, mat, p, TOL, &cont); if (res == -1){ exit(-1); } //2. COMPROVACIO DE QUE L'ELIMINACIO GAUSSIANA HA FUNCIONAT CORRECTAMENT: printf("Matriu obtinguda despres d'haver fet el metode PALU \n"); printMat(mat, n, n); printf("Vector de trasposicions \n"); printVectint(p, n); //3. CONTROL DE QUANTES PERMUTACIONS HEM FET: printf("Hem fet %d permutacions \n", cont); //4. SEPARAM LES MATRIUS L i U PER PODER CALCULAR EL DETERMINANT: L = separateLU(mat, U, n); //printf("La matriu L queda: \n"); //printMat(L, n, n); //printf("La matriu U queda: \n"); //printMat(U, n, n); printf("El determinant de la matriu es %le \n", detPALU(U, n, cont)); //5: RESOLEM EL SISTEMA SEGONS ELS TERMES INDEPENTENTS b I LA MATRIU QUE ENS HAVIEN DONAT (ara modificada): res = resol(n, mat, b, p); //Si el resultat es > 0 hem d'acabar perque vol dir que hi ha hagut algun problema if (res > 0){ exit(1); } //6. DONAM LA SOLUCIO DEL SISTEMA: printf("Vector solucio del sistema: \n"); printVect(b, n); //printf("Matriu resultat de multiplicar L * U \n"); //printMat(matrixProduct(L, U, n, n, n), n, n); /** -------------------------------------------- OPERACIONS D'ALLIBERACIO DE MEMORIA ----------------------------------- **/ //Alliberam memoria. free(p); free(b); for (i = 0; i < n; i++){ free(mat[i]); } free(mat); return 0; }