int main(int argc, const char * argv[]) { /* | x -2y -2z = -1 | x -y +z = -2 | 2x +y +3z = 1 reposta: x = 1, y = 2 e z = –1. */ float **matriz = newMatrix(3,3); matriz[0][0]=12;matriz[0][1]=643;matriz[0][2]=106; matriz[1][0]=643;matriz[1][1]=34.843;matriz[1][2]= 5.779; matriz[2][0]=106;matriz[2][1]= 5.77;matriz[2][2]= 976; float *coll4 = newVector(3); coll4[0]=753; coll4[1]=40830; coll4[2]= 6796; printf("Considerando:\n"); printf("|ax +by +cz = j\n"); printf("|dx +ey +fz = k\n"); printf("|gx +hy +iz = l\n"); printf("\nTemos para:\n"); printf("|ax +by +cz|\n"); printf("|dx +ey +fz|\n"); printf("|gx +hy +iz|\n"); printf("\na matriz:\n"); printMatrix(matriz, 3, 3); printf("e para:\n"); printf("|j|\n|k|\n|l|\n"); printf("\no vetor:\n"); printVector(coll4, 3); float * resposta; // = cramer3x3(1, -2, -2, 1, -1, 1, 2, 1, 3, -1, -2, 1); resposta = cramerMatrizTamanhoVector(matriz, 3, coll4); printf("\nA resposta deve ser: x = 1, y = 2 e z = –1\n"); printf("E a resposta calculada é: x=%f, y:%f, z:%f\n\n", resposta[0], resposta[1], resposta[2]); return 0; }
void testVectorAlgebra(){ double v[]={4,11,8,10}; double vLength=0; double v1[]={3,2,1,-2}; double v2[]={2,-1,4,1}; printf("\nMatrix\n"); vLength=vectorLength(v, 4); printf("vector length: %f\n",vLength); printf("vector addition\n"); vectorAddition(v1, v2, 4); printVector(v1,4); }
void smoothArray2D(float* arr, int width, int height){ // create new vector std::vector<float> vec; float mean; // loop through the whole array arr for (int y = 0; y < height; y++){ for (int x = 0; x < width; x++) { mean = getMean(arr, width, height, x, y); vec.push_back(mean); } } printVector(vec, width, height); }
void testprintVector(void) { Polyonym poly; double * matrix = NULL; matrix=malloc(sizeof(double)*1); matrix[0] = 0.0; poly.matrix=matrix; poly.var = 'y'; poly.d = 1; Vector vector; vector.matrix = &poly; vector.dim = 1; printVector(&vector); free(matrix); }
vector<int> Beauty::chap2_3(){ int id[] = {2, 3, 4}; int num[] = {25, 25, 25, 24}; vector<int> vec; for (int i = 0; i < 3; i++) { while (num[i] > 0) { num[i]--; vec.push_back(id[i]); } } for (int i = 0; i < num[3]; i++) { vec.push_back(rand()%100); } random_shuffle(vec.begin(), vec.end()); vector<int> res = chap2_3(vec); printVector(res); return res; }
int main(void) { int i; time_t *theTime; time(theTime); srand(*theTime); for(i=0;i < MAXSIZE; i++) { int nextRand = rand()/((double)INT_MAX+1)*10; append(nextRand); } printf("The Vector: \n"); printVector(); int result; #ifdef OLD_VERSION for(i = 0; i < 10; i++) { printf("Vorkommen der Zahl :%d\n", i); result=findelem(i, START_SEARCH); while(result != NOT_FOUND) { printf("%d, ", result); result = findelem(i, result); } printf("\n"); } #else for(i = 0; i < 10; i++) { printf("Vorkommen der Zahl :%d\n", i); result = find(i); while(result != NOT_FOUND) { printf("%d, ", result); result = find(i); } printf("\n"); } #endif }
int main(){ double l; tnn_reg l1; tnn_reg l2; gsl_vector *w; gsl_vector *d; int i; //Initializing regularizers printf("Initializing l1 regularizer: %s\n", TEST_FUNC(tnn_reg_init_l1(&l1))); printf("Initializing l2 regularizer: %s\n", TEST_FUNC(tnn_reg_init_l2(&l2))); printf("Debugging l1 regularizer: %s\n", TEST_FUNC(tnn_reg_debug(&l1))); printf("Debugging l2 regularizer: %s\n", TEST_FUNC(tnn_reg_debug(&l2))); //Allocating vectors printf("Allocating vectors\n"); w = gsl_vector_alloc(A); d = gsl_vector_alloc(A); for(i = 0; i < w->size; i = i + 1){ gsl_vector_set(w, i, (double)(B - i)); } printf("w:"); printVector(w); printf("d:"); printVector(d); printf("Test l1 loss: %s\n", TEST_FUNC(tnn_reg_l(&l1, w, &l))); printf("%g\n", l); printf("Test l2 loss: %s\n", TEST_FUNC(tnn_reg_l(&l2, w, &l))); printf("%g\n", l); printf("TEST l1 derivatives: %s\n", TEST_FUNC(tnn_reg_d(&l1, w, d))); printVector(d); printf("TEST l2 derivatives: %s\n", TEST_FUNC(tnn_reg_d(&l2, w, d))); printVector(d); printf("Test l1 add loss: %s\n", TEST_FUNC(tnn_reg_addl(&l1, w, &l))); printf("%g\n", l); printf("Test l2 add loss: %s\n", TEST_FUNC(tnn_reg_addl(&l2, w, &l))); printf("%g\n", l); printf("Test l1 add derivatives: %s\n", TEST_FUNC(tnn_reg_addd(&l1, w, d, 0.5))); printVector(d); printf("Test l2 add derivatives: %s\n", TEST_FUNC(tnn_reg_addd(&l2, w, d, 0.5))); printVector(d); printf("Destroying l1 regularizer: %s\n", TEST_FUNC(tnn_reg_destroy(&l1))); printf("Destroying l2 regularizer: %s\n", TEST_FUNC(tnn_reg_destroy(&l2))); return 0; }
int main(int arg, char *argv[]) { // insert code here... printf("LeetCode 023 Merge k Sorted Lists, C ...\n"); struct ListNode *a1 = 0;//(struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *a2 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *a3 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *b1 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *b2 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *b3 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *c1 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *c2 = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode *c3 = (struct ListNode*)malloc(sizeof(struct ListNode)); //a1->val = 1; a2->val = 4; a3->val = 7; b1->val = 2; b2->val = 5; b3->val = 8; c1->val = 3; c2->val = 6; c3->val = 9; //a1->next = a2; a2->next = a3; b1->next = b2; b2->next = b3; c1->next = c2; c2->next = c3; //printList(a1); //printList(mergeTwoLists(a1, b1)); int n = 3; struct ListNode **lists = (struct ListNode**)malloc(sizeof(struct ListNode*) * n); lists[0] = a1; lists[1] = b1; lists[2] = c1; printVector(lists, n); mergeKLists(lists, n); return 0; }
//print all possible paths from root to leaves void allPossiblePaths(TreeNode* node, IntVector prev_values) { if (!node) { //printVector(prev_values); return; } prev_values.push_back(node->val); if (!node->left && !node->right) { printVector(prev_values); } allPossiblePaths(node->left, prev_values); allPossiblePaths(node->right, prev_values); }
void Misc::findContinuousSequence(const vector<int> &A, int k) { vector<int> psum; partial_sum(A.begin(), A.end(), back_inserter(psum)); int left=0, right=1; while( right < A.size() && left <= right) { int sum=psum[right]-psum[left]+A[left]; if (sum==k) { printVector(vector<int>(A.begin()+left, A.begin()+right+1)); left++; right++; } else if (sum<k) { right++; } else left++; } }
void oberkatVerwalten(const std::string kat, std::vector<std::string>& vec, const size_t MAXSIZE) { clrScreen(); if(vec.empty()) std::cout << "\n\n\tBisher noch keine " << kat << " vorhanden\n\n"; else { std::cout << "\n\n\tErfasste " << kat << ":\n"; std::cout << "\t========="; for(size_t i = 0; i != kat.size()+1; ++i) std::cout << "="; std::cout << "\n\n"; } printVector(vec); std::cout << "\n\n"; std::cout << "\t" << kat << " verwalten" << std::endl; std::cout << "\t"; for(size_t i = 0; i != kat.size()+1; ++i) std::cout << "="; std::cout << "========="; showOberkatMenu(); std::string line; while( getline(std::cin, line) ) { if ( (line.empty()) || (line.size() > 1) || (!isdigit(line[0])) ){ wrongInput(); clrScreen(); printVector(vec); showOberkatMenu(); continue; } const char input = (char)line[0]; // is this a good cast (ok casts are never friends) switch(input) { case '1': clrScreen(); printVector(vec); addOberkat(kat, vec, MAXSIZE); printVector(vec); oberkatVerwalten(kat, vec, MAXSIZE); return; case '2': clrScreen(); printVector(vec); loeschenOberkat(kat, vec); printVector(vec); oberkatVerwalten(kat, vec, MAXSIZE); return; case '0': clrScreen(); return; default: assert("should never get here"); } } }
int main() { srand(time(NULL)); int n = 0; vector<pair<int,int> > req; // req.push_back(pair<int,int>(1,0)); // req.push_back(pair<int,int>(0,2)); // req.push_back(pair<int,int>(0,2)); // req.push_back(pair<int,int>(2,0)); // req.push_back(pair<int,int>(3,1)); // req.push_back(pair<int,int>(3,2)); // req.push_back(pair<int,int>(2,3)); vector<int> ans = findOrder(n, req); printVector(ans); return 0; }
bool Repository::pbiArchiver(Solution &candidate){ //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7020200 //double weight[]={0.1,0.9}; insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; double solNorm[objectiveNumber]; // double *solNorm; for(int i=0;i<actualSize;i++){ double norm; double pbi=0; normalizeObjectives(solNorm, solutions[i].objectiveVector); // solNorm=solutions[i].objectiveVector; pbi=PBI(solNorm, weight); if(pbi > highDistanceValue){ highDistanceValue=pbi; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nPBI ARCHIVER ERROR %f %f\n", PBI(solNorm, weight), highDistanceValue); candidate.print(); printf("\nweight: "); printVector(weight, objectiveNumber); printf("\n"); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
void Boundary::print () const // --------------------------------------------------------------------------- // (Debugging) utility to print internal information. // --------------------------------------------------------------------------- { char info[StrMax]; cout << "** Boundary id: " << _id + 1 << " -> "; cout << _elmt -> ID() + 1 << "." << _side + 1; cout << " (Element id.side)" << endl; _bcond -> describe (info); cout << info << endl; cout << " " << _np << " (number of points along edge)" << endl; cout << " nx ny area"; cout << endl; printVector (cout, "rrr", _np, _nx, _ny, _area); }
//Change 16-elements vector to 4x4 matrix void MarkerVis::vectorToTransform(cv::vector<double> v, int found) { if (found == 1) { tf::Vector3 translation_gC = tf::Vector3(v[3], v[7], v[11]); tf::Matrix3x3 rotation_gC = tf::Matrix3x3(v[0], v[1], v[2], v[4], v[5], v[6], v[8], v[9], v[10]); std::cout<<"trans:"<<std::endl; printVector(translation_gC); std::cout<<"rot:"<<std::endl; printMatrix3x3(rotation_gC); T_gC = tf::Transform(rotation_gC, translation_gC); } else { tf::Vector3 translation_gC = tf::Vector3(0, 0, 0); tf::Matrix3x3 rotation_gC = tf::Matrix3x3(1, 0, 0, 0, 1, 0, 0, 0, 1); T_gC = tf::Transform(rotation_gC, translation_gC); std::cout<<"not found"<<std::endl; } return; }
static void appendExteriorPoints(zhull_t *zh) { index_t i; vector_t center = initVector(0.0f,0.0f,0.0f); list_t facet_delete_list=emptyList(); facet_t *f; center=averageListedPoints(zh->pts,zh->used_pts); printf("central point\n"); printVector(center); printf("\n"); for (i=0; i<getLength(zh->facets); i++) { f=getFacetByIndex(zh->facets,i); printf("distance of plane %lu, d=%5.2f\n",(unsigned long)i, distancePointPlane(center,f->plane)); if (distancePointPlane(center,f->plane)>-0.5f) { appendToList(&facet_delete_list,entry_makePointer(f)); } } printList(facet_delete_list); removeFacetByPointerList(zh,facet_delete_list); freeList(&facet_delete_list); }
int main(int argc, char **argv) { int n, m; double A[MAX][MAX]; double b[MAX]; int map[MAX]; double sigma[MAX]; int rank; readMatrix(A, b, &n, &m); getColNorms(A, sigma, n, m); //printVector(sigma, m); rank = qr(A, b, sigma, map, n, m); printf("posto: %d\n", rank); //printVector(b, n); qr_solve(A, b, sigma, m, rank); printf("residuo: %lf\n", findResidual(b, n, rank)); remap(b, map, m); printf("resultado:\n"); printVector(b, m); plotSolution(m, b); return 0; }
bool Warmup::RecCanMakeSum2(Vector<int> & soFar, Vector<int> & nums, int targetSum, Set<Vector<int> > & numSet ) { cout << endl << "rec2..." << endl; printVector(soFar); if (nums.size() == 0) return TargetIsEqual(soFar, targetSum); if (TargetIsEqual(soFar, targetSum)) { cout << "this should print" << endl; return true; } else { for (int i = 0; i < nums.size(); i++) { cout << "i: " << i << endl; Vector<int> newSoFar = soFar; Vector<int> newNums = nums; int newNumber = nums[0]; newNums.removeAt(0); newSoFar.add(newNumber); bool a = RecCanMakeSum2(newSoFar , newNums , targetSum, numSet ); bool b = RecCanMakeSum2(soFar , newNums , targetSum, numSet ); return a || b; } } }
//------------------------------------------------------------------------------ // serialize() -- print the value of this object to the output stream sout. //------------------------------------------------------------------------------ std::ostream& Table3::serialize(std::ostream& sout, const int i, const bool slotsOnly) const { int j = 0; if (!slotsOnly) { sout << "( " << getFactoryName() << std::endl; j = 4; } indent(sout, i + j); sout << "z: "; printVector(sout, ztable, nz); sout << std::endl; BaseClass::serialize(sout, i + j, true); if (!slotsOnly) { indent(sout, i); sout << ")" << std::endl; } return sout; }
bool Repository::tchArchiver(Solution &candidate){ //http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7020200 insert(candidate); organize(); double highDistanceValue=MAXDOUBLE*-1; int higherIndex=-1; double solNorm[objectiveNumber]; // double *solNorm; for(int i=0;i<actualSize;i++){ double norm; double tch=0; normalizeObjectives(solNorm, solutions[i].objectiveVector); // solNorm=solutions[i].objectiveVector; tch=TCH(solNorm, weight); if(tch > highDistanceValue){ highDistanceValue=tch; higherIndex=i; } } if(higherIndex==-1){ fprintf(stderr,"\nTCH ARCHIVER ERROR %f\n", highDistanceValue); printVector(solNorm, objectiveNumber); fprintf(stderr,"\n"); exit(1); } bool ret=true; if(candidate.isEqual(solutions[higherIndex])) ret=false; exclude(higherIndex); return ret; }
/** * Main function. Reads vector, sorts it, and prints the sorted vector. * @param argc Command line arguments no. * @param argv Command line arguments. * @return Success/error code. (0 is a success, anything else is error). */ int main(int argc, char** argv) { printf("------ Begin MergeSort ------\n"); int n, i = 0; int *vectorToSort, *sortedVector; clock_t start, end; char error[128]; /* read vector */ if (argc == 1) { err("Err. The input file must be given as an argument.\n"); } if (!readVectorFromFile(&vectorToSort, &n, argv[1], error)) { err(error); } /* print read vector */ //printf("The read vector is: "); //printVector(vectorToSort, n); //printf("\n"); /* sort vector */ start = clock(); sortedVector = mergeSort(n, vectorToSort); end = clock(); /* print sorted vector */ printf("The sorted vector is: "); printVector(sortedVector, n); printf("\n"); /* free memory */ free(vectorToSort); free(sortedVector); printf("Elapsed: %f seconds while sorting.\n", (double) (end - start) / CLOCKS_PER_SEC); printf("------- End MergeSort -------\n"); return EXIT_SUCCESS; }
/** * The function receives the shared memory segment and it gets it's values and prints the top 10 results * The function also receives the number of results that need to be printed. * The function also receives the number of processes so it knows how to loop. */ void printResults(float* shm, unsigned int n, unsigned int process_count, unsigned int vector_size) { unsigned int i=0; //total entries in the shared memory const unsigned int shm_size = process_count*n*4; ResultType one; std::vector<ResultType> results; //run through the shared memory and insert the values in ResultType //structures and stored them into the results vector. for(i=0; i<shm_size; i++) { one.x = shm[i]; one.y = shm[i+1]; one.offset = shm[i+2]; one.dist = shm[i+3]; results.push_back(one); i+=3; } //sort and resize the results to keep only the top 10 std::sort(results.begin(), results.end()); results.resize(n); //print the actual results printVector(n, results, vector_size); }
void testLUSolver(){ double **A, *x; int n; n=3; double b[n]; A=allocateDoubleMatrix(n, n); A[0][0]=6.0; A[0][1]=0.0; A[0][2]=2.0; A[1][0]=24.0; A[1][1]=1.0; A[1][2]=8.0; A[2][0]=-12.0; A[2][1]=1.0; A[2][2]=-3.0; b[0]=4.0; b[1]=19.0; b[2]=-6.0; x=LUSolver(A,b,n); fprintf(stdout,"LU solver U:\n"); printVector(x,n); }
void testGaussianElimination(){ double **A; int n; double *x; n=3; double b[n]; A=allocateDoubleMatrix(3, 3); A[0][0]=1.0; A[0][1]=1.0; A[0][2]=-1.0; A[1][0]=1.0; A[1][1]=2.0; A[1][2]=1.0; A[2][0]=2.0; A[2][1]=-1.0; A[2][2]=1.0; b[0]=2.0; b[1]=6.0; b[2]=1.0; x=gaussianElimination (n, A, b); fprintf(stdout,"Gaussian Elimination\n"); printVector(x,n); }
void printResult(SDPA& Problem1) { fprintf(stdout, "\nStop iteration = %d\n", Problem1.getIteration()); char phase_string[30]; Problem1.getPhaseString(phase_string); fprintf(stdout, "Phase = %s\n", phase_string); fprintf(stdout, "objValPrimal = %+10.6e\n", Problem1.getPrimalObj()); fprintf(stdout, "objValDual = %+10.6e\n", Problem1.getDualObj()); fprintf(stdout, "p. feas. error = %+10.6e\n", Problem1.getPrimalError()); fprintf(stdout, "d. feas. error = %+10.6e\n\n", Problem1.getDualError()); #if 0 fprintf(stdout, "xVec = \n"); // Problem1.printResultXVec(); printVector(Problem1.getResultXVec(), Problem1.getConstraintNumber(), (char*)"%+8.3e", stdout); fprintf(stdout, "xMat = \n"); // Problem1.printResultXMat(); for (int l=0; l<Problem1.getBlockNumber(); ++l) { if (Problem1.getBlockType(l+1) == SDPA::SDP) { printMatrix(Problem1.getResultXMat(l+1), Problem1.getBlockSize(l+1), (char*)"%+8.3e", stdout); } else if (Problem1.getBlockType(l+1) == SDPA::SOCP) { printf("current version does not support SOCP\n"); } if (Problem1.getBlockType(l+1) == SDPA::LP) { printVector(Problem1.getResultXMat(l+1), Problem1.getBlockSize(l+1), (char*)"%+8.3e", stdout); } } fprintf(stdout, "yMat = \n"); // Problem1.printResultYMat(); for (int l=0; l<Problem1.getBlockNumber(); ++l) { if (Problem1.getBlockType(l+1) == SDPA::SDP) { printMatrix(Problem1.getResultYMat(l+1), Problem1.getBlockSize(l+1), (char*)"%+8.3e", stdout); } else if (Problem1.getBlockType(l+1) == SDPA::SOCP) { printf("current version does not support SOCP\n"); } if (Problem1.getBlockType(l+1) == SDPA::LP) { printVector(Problem1.getResultYMat(l+1), Problem1.getBlockSize(l+1), (char*)"%+8.3e", stdout); } } #endif double dimacs_error[7]; Problem1.getDimacsError(dimacs_error); printDimacsError(dimacs_error,(char*)"%+8.3e",stdout); }
void HCComponent::checkModel( vector< Literal >& assumptions ) { assert( !checker.conflictDetected() ); assert( checker.getCurrentDecisionLevel() == 0 ); trace_action( modelchecker, 2, { printVector( assumptions, "Assumptions" ); } );
void run() { vsx_mesh* p = mesh_in->get_addr(); if (!p) { mesh_empty.timestamp = (int)(engine->real_vtime*1000.0f); mesh_out->set_p(mesh_empty); prev_timestamp = 0xFFFFFFFF; return; } debug = false; bool newMeshLoaded = false; //after a mesh change clone the mesh if (p && (prev_timestamp != p->timestamp)) { prev_timestamp = p->timestamp; mesh.data->vertices.reset_used(0); mesh.data->vertex_normals.reset_used(0); mesh.data->vertex_tex_coords.reset_used(0); mesh.data->vertex_colors.reset_used(0); mesh.data->faces.reset_used(0); for (unsigned int i = 0; i < p->data->vertices.size(); i++) { mesh.data->vertices[i] = p->data->vertices[i] + v; verticesSpeed[i] = vsx_vector(0, 0, 0); } for (unsigned int i = 0; i < p->data->vertex_normals.size(); i++) mesh.data->vertex_normals[i] = p->data->vertex_normals[i]; for (unsigned int i = 0; i < p->data->vertex_tangents.size(); i++) mesh.data->vertex_tangents[i] = p->data->vertex_tangents[i]; for (unsigned int i = 0; i < p->data->vertex_tex_coords.size(); i++) mesh.data->vertex_tex_coords[i] = p->data->vertex_tex_coords[i]; for (unsigned int i = 0; i < p->data->vertex_colors.size(); i++) mesh.data->vertex_colors[i] = p->data->vertex_colors[i]; for (unsigned int i = 0; i < p->data->faces.size(); i++) mesh.data->faces[i] = p->data->faces[i]; //calc and store original face lengths faceLengths.reset_used(); vsx_vector normal; vsx_vector len; vsx_vector hypVec; for (unsigned int i = 0; i < p->data->faces.size(); i++) { vsx_face& f = mesh.data->faces[i]; vsx_vector& v0 = mesh.data->vertices[f.a]; vsx_vector& v1 = mesh.data->vertices[f.b]; vsx_vector& v2 = mesh.data->vertices[f.c]; //calc face area normal.assign_face_normal(&v0, &v1, &v2); float area = normal.length() / 2.0f; faceAreas[i] = area; //facelengths a, b, c stored in vector x, y, z len.x = (v1 - v0).length(); len.y = (v2 - v1).length(); len.z = (v0 - v2).length(); faceLengths.push_back(len); } mesh.timestamp++; param_updates = 0; newMeshLoaded = true; dtimeRest = 0.0f; } float stepSize = step_size->get(); //float stepsPerSecond = steps_per_second->get(); float gasExpansionFactor = gas_expansion_factor->get(); float gridStiffnessFactor = grid_stiffness_factor->get(); float dampingFactor = damping_factor->get(); float materialWeight = material_weight->get(); float lowerBoundary = lower_boundary->get(); //use engine->dtime; and dtimeRest //to repeat the calculation several times ((dtime + rest) * stepsPerSecond) //calculate volume float volume = 0.0f; vsx_face* face_p = mesh.data->faces.get_pointer(); vsx_vector* vertex_p = mesh.data->vertices.get_pointer(); vsx_vector* faces_length_p = faceLengths.get_pointer(); verticesSpeed.allocate(mesh.data->vertices.size()); vsx_vector* vertices_speed_p = verticesSpeed.get_pointer(); float onedivsix = (1.0f / 6.0f); for(unsigned int i = 0; i < mesh.data->faces.size(); i++) { vsx_face& f = face_p[i];//mesh.data->faces[i]; vsx_vector& v0 = vertex_p[f.a]; vsx_vector& v2 = vertex_p[f.b]; vsx_vector& v1 = vertex_p[f.c]; volume += (v0.x * (v1.y - v2.y) + v1.x * (v2.y - v0.y) + v2.x * (v0.y - v1.y)) * (v0.z + v1.z + v2.z) * onedivsix; } //default gas_amount to volume of a new mesh i.e. no pressure if(newMeshLoaded) { gas_amount->set(volume); } float pressure = (gas_amount->get() - volume) / volume; //mesh.data->face_normals.reset_used(0); //mesh.data->vertex_normals.reset_used(0); //calculate face areas, normals, forces and add to speed for(unsigned int i = 0; i < mesh.data->faces.size(); i++) { vsx_face& f = face_p[i];//mesh.data->faces[i]; vsx_vector& v0 = vertex_p[f.a];//mesh.data->vertices[f.a]; vsx_vector& v1 = vertex_p[f.b];//mesh.data->vertices[f.b]; vsx_vector& v2 = vertex_p[f.c];//mesh.data->vertices[f.c]; printVector("v0", i, v0); printVector("v1", i, v1); printVector("v2", i, v2); //vsx_vector normal = mesh.data->get_face_normal(i); vsx_vector a = vertex_p[face_p[i].b] - vertex_p[face_p[i].a]; vsx_vector b = vertex_p[face_p[i].c] - vertex_p[face_p[i].a]; vsx_vector normal; normal.cross(a,b); printVector("normal", i, normal); //float len = normal.length(); //float area = len / 2; printFloat("length", i, len); printFloat("area", i, len); vsx_vector edgeA = (v1 - v0); vsx_vector edgeB = (v2 - v1); vsx_vector edgeC = (v0 - v2); printVector("edgeA", i, edgeA); printVector("edgeB", i, edgeB); printVector("edgeC", i, edgeC); float lenA = edgeA.length(); float lenB = edgeB.length(); float lenC = edgeC.length(); printFloat("lenA", i, lenA); printFloat("lenB", i, lenB); printFloat("lenC", i, lenC); float edgeForceA = (faces_length_p[i].x - lenA) / faces_length_p[i].x; float edgeForceB = (faces_length_p[i].y - lenB) / faces_length_p[i].y; float edgeForceC = (faces_length_p[i].z - lenC) / faces_length_p[i].z; printFloat("edgeForceA", i, edgeForceA); printFloat("edgeForceB", i, edgeForceB); printFloat("edgeForceC", i, edgeForceC); float edgeAccA = edgeForceA / lenA; float edgeAccB = edgeForceB / lenB; float edgeAccC = edgeForceC / lenC; printFloat("edgeAccA", i, edgeAccA); printFloat("edgeAccB", i, edgeAccB); printFloat("edgeAccC", i, edgeAccC); vsx_vector accA = edgeA * edgeAccA; vsx_vector accB = edgeB * edgeAccB; vsx_vector accC = edgeC * edgeAccC; printVector("accA", i, accA); printVector("accB", i, accB); printVector("accC", i, accC); vertices_speed_p[f.a] -= (accA - accC) * gridStiffnessFactor; vertices_speed_p[f.b] -= (accB - accA) * gridStiffnessFactor; vertices_speed_p[f.c] -= (accC - accB) * gridStiffnessFactor; //applying pressure to areas of faces vsx_vector pressureAcc = normal * pressure * gasExpansionFactor; vertices_speed_p[f.a] -= pressureAcc; vertices_speed_p[f.b] -= pressureAcc; vertices_speed_p[f.c] -= pressureAcc; //apply material weight float gravityAcc = materialWeight; vertices_speed_p[f.a].y -= gravityAcc; vertices_speed_p[f.b].y -= gravityAcc; vertices_speed_p[f.c].y -= gravityAcc; } //apply speeds to vertices for(unsigned int i = 0; i < mesh.data->vertices.size(); i++) { vertex_p[i] += vertices_speed_p[i] * stepSize; if(vertex_p[i].y < lowerBoundary) { vertex_p[i].y = lowerBoundary; } vertices_speed_p[i] = vertices_speed_p[i] * dampingFactor; } mesh.data->vertex_normals.allocate(mesh.data->vertices.size()); mesh.data->vertex_normals.memory_clear(); vsx_vector* vertex_normals_p = mesh.data->vertex_normals.get_pointer(); /*for(unsigned int i = 0; i < mesh.data->vertices.size(); i++) { mesh.data->vertex_normals[i] = vsx_vector(0, 0, 0); }*/ //TODO: create vertex normals, for rendering... should be a separate module... for(unsigned int i = 0; i < mesh.data->faces.size(); i++) { vsx_vector a = vertex_p[face_p[i].b] - vertex_p[face_p[i].a]; vsx_vector b = vertex_p[face_p[i].c] - vertex_p[face_p[i].a]; vsx_vector normal; normal.cross(a,b); //vsx_vector normal = mesh.data->get_face_normal(i); normal = -normal; normal.normalize(); vertex_normals_p[face_p[i].a] += normal; vertex_normals_p[face_p[i].b] += normal; vertex_normals_p[face_p[i].c] += normal; } volume_out->set(volume); //printf("***************Pressure %f ", pressure); //printf(" Volume %f\n", volume); mesh_out->set_p(mesh); }
void cma_es(Swarm &sw){ if(logCMAES){ printf("\n--------------------------------------------------------------\n"); printf("Repository (%d)\n", sw.repository.getActualSize()); for(int i=0;i<sw.repository.getActualSize();i++){ printVector(sw.repository.getSolution(i).decisionVector, decisionNumber); printf("\n"); } } double sigmaPrev=sw.sigma; myLearn(sw); // if(fabs(sigmaPrev-sw.sigma) > 10000){ // fprintf(stderr, "\nWARNING!, sigma changed too much: %f -> %f. resetting...\n",sigmaPrev, sw.sigma); //shows warning message // sw.init=true; //set the init flag, so all the CMA-ES variables are reset // myLearn(sw); //learn again using the default values as base // } if(sw.sigma != sw.sigma || sw.sigma >= MAXDOUBLE){ //check for invalid numbers NaN or inf fprintf(stderr, "WARNING!, sigma: %f. resetting...\n", sw.sigma); //shows warning message // exit(1); sw.init=true; //set the init flag, so all the CMA-ES variables are reset myLearn(sw); //learn again using the default values as base } //four reset criteria as in the paper "injecting cma-es into moea/d" //NoEffectCoord for (int iKoo = 0; iKoo < decisionNumber; ++iKoo){ if (sw.mean[iKoo] == sw.mean[iKoo] + 0.2*sw.sigma*sqrt(sw.C[iKoo][iKoo])){ fprintf(stderr, "NoEffectCoordinate: standard deviation 0.2*%7.2e in coordinate %d without effect\n", sw.sigma*sqrt(sw.C[iKoo][iKoo]), iKoo); //shows warning message sw.init=true; //set the init flag, so all the CMA-ES variables are reset myLearn(sw); //learn again using the default values as base break; } } //NoEffectAxis int iKoo; for (int iAchse = 0; iAchse < decisionNumber; ++iAchse){ double fac = 0.1 * sw.sigma * sw.D[iAchse]; for (iKoo = 0; iKoo < decisionNumber; ++iKoo){ if (sw.mean[iKoo] != sw.mean[iKoo] + fac * sw.B[iKoo][iAchse]) break; } if (iKoo == decisionNumber){ /* t->sigma *= exp(0.2+t->sp.cs/t->sp.damps); */ fprintf(stderr, "NoEffectAxis: standard deviation 0.1*%7.2e in principal axis %d without effect\n", fac/0.1, iAchse); sw.init=true; //set the init flag, so all the CMA-ES variables are reset myLearn(sw); //learn again using the default values as base break; } } //TolXUp double stopTolUpXFactor=1e3; double initialStds=0.3; int i; for(i=0; i<decisionNumber; ++i) { if (sw.sigma * sqrt(sw.C[i][i]) > stopTolUpXFactor * initialStds) break; } if (i < decisionNumber) { fprintf(stderr, "TolUpX: standard deviation increased by more than %7.2e, larger initial standard deviation recommended \n", stopTolUpXFactor); sw.init=true; //set the init flag, so all the CMA-ES variables are reset myLearn(sw); //learn again using the default values as base } //ConditionCov double dMaxSignifKond=1e13; if (rgdouMax(sw.D, decisionNumber) >= rgdouMin(sw.D, decisionNumber) * dMaxSignifKond) { fprintf(stderr, "ConditionNumber: maximal condition number %7.2e reached. maxEW=%7.2e,minEW=%7.2e\n", dMaxSignifKond, rgdouMax(sw.D, decisionNumber), rgdouMin(sw.D, decisionNumber)); sw.init=true; //set the init flag, so all the CMA-ES variables are reset myLearn(sw); //learn again using the default values as base } //************************************* RESAMPLE SOLUTIONS FROM THE GOOD FRONTS ******************************// //re-learn and re-sample when errors in the covariance matrix are detected in the sampling phase bool success=mySample(sw); while(!success){ myLearn(sw); success=mySample(sw); fprintf(stderr,"Resample\n"); } // Neighbor orderedSwarms[swarmNumber]; // for(int i=0;i<swarmNumber;i++){ // orderedSwarms[i].index=i; // orderedSwarms[i].distance=swarms[i].modelQuality*-1;//inverted model quality because we will use the preexisting sort, that sorts based on the smallest value (distance) // } // std::sort(orderedSwarms, orderedSwarms+swarmNumber, neighborsComparator); // // // for(int i=0;i<swarmNumber;i++){ // // printf("swarm: %d has quality %f sz: %d\n", orderedSwarms[i].index, orderedSwarms[i].distance*-1, repGlobal->getActualSize()); // // } // // printf("\n\n\n"); // // bool good=false; // for(int i=0;i<100;i++){ // if(sw.neighborhood[0].index == orderedSwarms[i].index){ // good=true; // break; // } // } // // if(good){ // //re-learn and re-sample when errors in the covariance matrix are detected in the sampling phase // bool success=mySampleReplacement(sw, 10); // while(!success){ // myLearn(sw); // success=mySampleReplacement(sw, 10); // fprintf(stderr,"Resample\n"); // } // }else{ // for(int i=0;i<sw.getSize();i++) // sw.particles[i].solution.evalSolution=false; // // //re-learn and re-sample when errors in the covariance matrix are detected in the sampling phase // // bool success=mySample(sw); // // while(!success){ // // myLearn(sw); // // success=mySample(sw); // // fprintf(stderr,"Resample\n"); // // } // } //************************************* END OF RESAMPLING SOLUTIONS FROM THE GOOD FRONTS ******************************// if(logCMAES){ printf("\n\npop after \n\n"); for(int i=0; i<sw.getSize();i++){ //printVector(evo.rgrgx[i],N+2); printVector(sw.particles[i].solution.decisionVector,decisionNumber); printf("\n"); } } }
bool mySample (Swarm &sw){ int N=decisionNumber; /* calculate eigensystem */ if(logCMAES){ printf("\n----------------------before eigen calculation ---------------------- "); // printf("\nCov mat: \n"); // for (int i = 0; i < N; ++i){ // printVector(sw.C[i], N); // printf("\n"); // } printf("\nB mat: \n"); for (int i = 0; i < N; ++i){ printVector(sw.B[i], N); printf("\n"); } printf("\nD mat: \n"); printVector(sw.D, N); printf("\n"); printf("---------------------end before ---------------------- \n"); printf("\nCov mat: \n"); for (int i = 0; i < N; ++i){ printVector(sw.C[i], N); printf("\n"); } } double rgdTmp[N]; Eigen( N, sw.C, sw.D, sw.B, rgdTmp); //By using Cholesky decomposition, it turns out that the determinant of a matrix is equal to the product of its eigenvalues sw.det=sw.D[0]; for(int i=1;i<N;i++) sw.det*=sw.D[i]; double lg=log(sw.det); if(lg >= MAXDOUBLE || lg != lg){ fprintf(stderr, "WARNING!, log of the covariance matrix determinant: %f. ", lg); //shows warning message sw.init=true; //set the init flag, so all the CMA-ES variables are reset return false; } for (int i = 0; i < N; ++i) sw.D[i] = sqrt(sw.D[i]); for(int i=0;i<N;i++){ if(sw.D[i] != sw.D[i] || sw.D[i] >= MAXDOUBLE || sw.D[i] < 0){//tests for 1)null 2)inf 3) positive definiteness of the covariance matrix // if(sw.det != sw.det || sw.det <= MAXDOUBLE*-1 || sw.D[i] != sw.D[i] || sw.D[i] >= MAXDOUBLE || sw.D[i] < 0){//tests for 1) determinant null or invalid 2)null 3)inf 4) positive definiteness of the covariance matrix fprintf(stderr, "WARNING!, value: %f in eigenValues vector. ", sw.D[i]); //shows warning message sw.init=true; //set the init flag, so all the CMA-ES variables are reset return false; // exit(1); //myLearn(sw, neighboringSwarms); //learn again using the default values as base } } if(logCMAES){ printf("---------------------after eigen calculation ---------------------- \n"); // printf("\nCov mat: \n"); // for (int i = 0; i < N; ++i){ // printVector(sw.C[i], N); // printf("\n"); // } printf("B mat: \n"); for (int i = 0; i < N; ++i){ printVector(sw.B[i], N); printf("\n"); } printf("\nD mat: \n"); printVector(sw.D, N); printf("\n"); printf("---------------------end after ---------------------- \n"); printf("\nsigma: %f (%e)\n",sw.sigma, sw.sigma); for (int i = 0; i < N; ++i) rgdTmp[i] = sw.D[i] * 3; printf("\nD (sample) (* 3) : "); for (int i = 0; i < N; ++i){ double sum = 0.0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * rgdTmp[j]; if((sw.mean[i] + sw.sigma * sum ) >= 0 ) printf(" "); printf("%.3f ", /*fabs*/(sw.mean[i] + sw.sigma * sum ) ); } for (int i = 0; i < N; ++i) rgdTmp[i] = sw.D[i] * 0; printf("\nD (sample) (* 0) : "); for (int i = 0; i < N; ++i){ double sum = 0.0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * rgdTmp[j]; if((sw.mean[i] + sw.sigma * sum ) >= 0 ) printf(" "); printf("%.3f ", /*fabs*/(sw.mean[i] + sw.sigma * sum ) ); } for (int i = 0; i < N; ++i) rgdTmp[i] = sw.D[i] * -3; printf("\nD (sample) (* -3): "); for (int i = 0; i < N; ++i){ double sum = 0.0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * rgdTmp[j]; if((sw.mean[i] + sw.sigma * sum ) >= 0 ) printf(" "); printf("%.3f ", /*fabs*/(sw.mean[i] + sw.sigma * sum ) ); } } // // printVector(sw.mean, decisionNumber); //show the average decision vector per iteration // // printf("\n"); // printf("\nD (sample) (difsum): "); // for (int i = 0; i < N; ++i){ // for (j = 0, sum = 0.0; j < N; ++j) // sum += sw.B[i][j] * rgdTmp[j]; // printf("%f ", fabs(sw.mean[i] + sw.sigma * sw.D[i]*-3 )+fabs(sw.mean[i] + sw.sigma * sqrt(sw.D[i])*3 ) ); // } /*************************/ double previousSol[N]; if(sw.getSize() == 1) memcpy(previousSol, sw.particles[0].solution.decisionVector, sizeof(double)*N); // original sampling for (int iNk = 0; iNk < sw.getSize(); ++iNk){ /* generate scaled cmaes_random vector (D * z) */ // int rescount=0; // while(true){//resample when invalid // bool resample=false; for (int i = 0; i < N; ++i) rgdTmp[i] = sw.D[i] * cmaes_random_Gauss(); /* add mutation (sigma * B * (D*z)) */ for (int i = 0; i < N; ++i) { double sum = 0.0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * rgdTmp[j]; double value=sw.mean[i] + sw.sigma * sum;//normalized new solution // if(value < 0 || value > 1){ // resample=true; // // printf("\nresample: %f (%d, %d)\n", value, i, rescount); // }else sw.particles[iNk].solution.evalSolution=true; sw.particles[iNk].solution.decisionVector[i] = (value*(superiorPositionLimit[i]-inferiorPositionLimit[i]))+inferiorPositionLimit[i]; //unormalize solution } // if(!resample || rescount > 100) // break; // else // rescount++; // } // if(rescount >= 100){ // printf("\n GAVE UP \n"); // exit(1); // } } // //ranking for the new surrogate functions // if(repGlobal->getActualSize() >0 ){ // repGlobal->organize(); // for(int i=0;i<repGlobal->getActualSize();i++) // repGlobal->getSolutions()[i].crowdingDistance=logLikelihood(repGlobal->getSolution(i).decisionVector, sw);//stores temporarily in the crowding distance field // // std::sort(repGlobal->getSolutions(), repGlobal->getSolutions()+repGlobal->getActualSize(), crowdingComparatorSol); // // // double likelihood=logLikelihood(sw.particles[0].solution.decisionVector, sw); // // double rank = likelihoodRanking(sw.particles[0].solution, *repGlobal, sw); // // if(rank >0 && rank < repGlobal->getActualSize()) // printf("rank: %.1f lik before: %f lik: %f lik after: %f\n", rank, repGlobal->getSolution((int)rank).crowdingDistance,likelihood,repGlobal->getSolution((int)rank+1).crowdingDistance); // else // printf("rank: %f\n", rank); // } // // // for (int iNk = 0; iNk < sw.getSize(); ++iNk){//using the likelihood as surrogate // // // // double best[N], bestValue=MAXDOUBLE*-1;//using best as highest likelihood to get convergence // // // double best[N], bestValue=MAXDOUBLE;//using the best as lowest likelihood to get diversity // // // for(int t=0;t<10;t++){//ten trials per particle and choose the best // // // double candidate[N]; // // // // // // for (int i = 0; i < N; ++i) // // // rgdTmp[i] = sw.D[i] * cmaes_random_Gauss(); // // // /* add mutation (sigma * B * (D*z)) */ // // // for (int i = 0; i < N; ++i) { // // // double sum = 0.0; // // // for (int j = 0; j < N; ++j) // // // sum += sw.B[i][j] * rgdTmp[j]; // // // // // // candidate[i]=sw.mean[i] + sw.sigma * sum;//normalized new solution // // // } // // // double opinion=neighborhoodOpinion(sw, candidate); // // // // printf("opinion: %f of: ",opinion); // // // // printVector(candidate, N); // // // // printf("\n"); // // // // if(opinion > bestValue){//using best as highest likelihood to get convergence // // // if(opinion < bestValue){//using the best as lowest likelihood to get diversity // // // for (int i = 0; i < N; ++i) // // // best[i]=candidate[i]; // // // bestValue=opinion; // // // } // // // } // // // // // // for (int i = 0; i < N; ++i) // // // sw.particles[iNk].solution.decisionVector[i] = (best[i]*(superiorPositionLimit[i]-inferiorPositionLimit[i]))+inferiorPositionLimit[i]; //unormalize solution // // // } /* Test if function values are identical, escape flat fitness */ //original comment //Check if the sampled solutions are equal, or if only one solution is sampled, if it is equal to the previous solution // if (t->rgFuncValue[t->index[0]] == t->rgFuncValue[t->index[(int)t->sp.lambda/2]]) { // t->sigma *= exp(0.2+t->sp.cs/t->sp.damps); // ERRORMESSAGE("Warning: sigma increased due to equal function values\n", // " Reconsider the formulation of the objective function",0,0); // } if(sw.getSize() == 1){ if(isEqual(previousSol, sw.particles[0].solution.decisionVector, N)){ sw.sigma *= exp(0.2+cSigma/dSigma); fprintf(stderr, "Warning: sigma increased due to equal decision vectors.\n"); return false; } // else // for(int i=0;i<N;i++) // printf("%.14f ", abs(previousSol[i]-sw.particles[0].solution.decisionVector[i])); // printf("\n"); }else{ if(isEqual(sw.particles[0].solution.decisionVector, sw.particles[sw.getSize()-1].solution.decisionVector, N)){ sw.sigma *= exp(0.2+cSigma/dSigma); fprintf(stderr, "Warning: sigma increased due to equal decision vectors.\n"); return false; } } return true; } /* SamplePopulation() */
void myLearn(Swarm &sw){ int N=decisionNumber, hsig; double oldMean[N], initialStds[N], BDz[N]; double muEff, cc, muCov, cCov, trace=0.0, chiN; cSigma=0; dSigma=0; //double sigma, C[N][N], pC[N], pSigma[N], D[N], mean[N], B[N][N]; //****************** treating the input data ********************// Repository repTemp; //gathering the solutions to be used to learn and putting them on repTemp if(decomposition){ mergeNeighboringRepositories(repTemp, sw); }else{ repTemp.initialize(archSubSwarms, sw.getSize()+sw.repository.getActualSize()); if(!strcmp(solSet, "population") || !strcmp(solSet, "both")) for(int i=0;i<sw.getSize();i++) if(!sw.particles[i].solution.dominated) repTemp.add(sw.particles[i].solution); if(!strcmp(solSet, "repository") || repTemp.getActualSize()==0 || !strcmp(solSet, "both")) repTemp.add(sw.repository); } repTemp.organize(); // if(!strcmp(archSubSwarms, "p-ideal") || !strcmp(archSubSwarms, "w-ideal") || !strcmp(archSubSwarms, "r-ideal")){ if(decomposition){ updateWeightedDistances(repTemp.getSolutions(), repTemp.getActualSize(), sw.repository.weight); std::sort(repTemp.getSolutions(), repTemp.getSolutions()+repTemp.getActualSize(), weightedDistanceComparatorSol); }else{ if(!strcmp(cmaRanking, "cd")){ updateCrowdingDistances(repTemp.getSolutions(), repTemp.getActualSize()); std::sort(repTemp.getSolutions(), repTemp.getSolutions()+repTemp.getActualSize(), crowdingComparatorSol); } if(!strcmp(cmaRanking, "hv")){ updateContributingHypervolume(repTemp); //stores in the crowding distance field, since both are the higher the contribution, the better, there is no problem std::sort(repTemp.getSolutions(), repTemp.getSolutions()+repTemp.getActualSize(), crowdingComparatorSol); } if(!strcmp(cmaRanking, "r2")){ if(refSize==-1){ perror("ERROR ON CMA-ES R2 RANKING! Reference file not set."); } updateContributingR2(repTemp); //stores in the crowding distance field, stores in the crowding distance field //if the value of the r2 increase after I take this solution, it is important, so the higher is the contribution, the better std::sort(repTemp.getSolutions(), repTemp.getSolutions()+repTemp.getActualSize(), crowdingComparatorSol); } } //normalizing non dominated solutions double nonDominated[repTemp.getActualSize()][N]; int nonDom=0; // for(int i=0;i<repTemp.getActualSize()/2;i++){ for(int i=0;i<repTemp.getActualSize();i++){ // printVector(repTemp.getSolution(i).decisionVector, decisionNumber); // printVector(repTemp.getSolution(i).objectiveVector, objectiveNumber); // printf("sol:%d: %e\n", i, repTemp.getSolution(i).crowdingDistance); for(int j=0;j<N;j++) nonDominated[nonDom][j]=normalize(repTemp.getSolution(i).decisionVector[j], inferiorPositionLimit[j], superiorPositionLimit[j]); nonDom++; //mu } int mu = nonDom; double weights[mu]; //**************************** end of treatment of input data***************// /***************setting default parameters according to****************/ //https://www.lri.fr/~hansen/hansenedacomparing.pdf // in my strategy lambda = mu = solSize double weightSquare=0, weightSum=0, value=0; double smaller=MAXDOUBLE, larger=-MAXDOUBLE; if(mu > 2){ if(!strcmp(weightDistribution, "metric")){ //uses the value of the ranking metric as weight for(int i=mu-1;i>=0;i--){// find the smaller > 0 if(decomposition){ value=repTemp.getSolution(i).weightedDistance; if(value < MAXDOUBLE){ larger=value; break; } } else{ value=repTemp.getSolution(i).crowdingDistance; if(value > 0){ //a little higher than 0 smaller=value; break; } } } for(int i=0;i<mu;i++){ //find the larger < MAXDOUBLE if(decomposition){ value=repTemp.getSolution(i).weightedDistance; if(value > 0){ //a little higher than 0 smaller=value; break; } } else{ value=repTemp.getSolution(i).crowdingDistance; if(value < MAXDOUBLE){ larger=value; break; } } } if(larger == -MAXDOUBLE || smaller == MAXDOUBLE){ fprintf(stderr, "\nERROR ON ASSIGNING WEIGHTS FOR CMA-ES!!\n"); fprintf(stderr, "\nsm: %f lg: %f mu: %d\n", smaller, larger, mu); exit(1); } } }else{ larger=1; smaller=0; } for(int i=0;i<mu;i++){ if(!strcmp(weightDistribution, "equal")) weights[i]=1.0; //equal weight distribution if(!strcmp(weightDistribution, "log")) weights[i]=log(mu+1)-log(i+1.0); //according to code if(!strcmp(weightDistribution, "linear")) weights[i]=mu-i; //according to code if(!strcmp(weightDistribution, "metric")){ //uses the value of the ranking metric as weight if(decomposition){ value=repTemp.getSolution(i).weightedDistance; weights[i]=1-(normalize(value, (smaller-(smaller/100.0)), larger)); }else{ value=repTemp.getSolution(i).crowdingDistance; weights[i]=(normalize(value, (smaller-(smaller/100.0)), larger)); } // weights[i]=exp(normalize(repTemp.getSolution(i).crowdingDistance, smaller, larger)); // if(repTemp.getSolution(i).crowdingDistance<=0) // weights[i]=exp(0); // if(repTemp.getSolution(i).crowdingDistance>=MAXDOUBLE) // weights[i]=exp(1); // weights[i]=(normalize(value, (smaller-(smaller/100.0)), larger)); if(weights[i]<= 0) weights[i]=normalize(smaller, (smaller-(smaller/100.0)), larger);//weights[i-1]/2.0; if(weights[i]>1) weights[i]=1; // weights[i]=log(1+weights[i]); } weightSum+=weights[i]; //sum of the weights for posterior normalization } for(int i=0;i<mu;i++){ //normalization of the weights weightSquare+=weights[i]*weights[i]; weights[i]/=weightSum; // printf("\n %f - %f",repTemp.getSolution(i).weightedDistance, weights[i]); } // muEff=1.0/weightSquare;//paper muEff=weightSum*weightSum/weightSquare;//code cSigma= (muEff+2.0)/(N+muEff+3.0); //code // cSigma= (muEff+2.0)/(N+muEff+5.0); //paper dSigma= (1.0 + 2.0*std::max(0.0, sqrt((muEff-1.0)/(N+1.0)) - 1.0)) * std::max(0.3, 1.0 -(double)N / (1e-6+maxIterations)) + cSigma;//code // dSigma= 1.0+ 2.0*( std::max(0.0, sqrt( (muEff-1.0)/(N+1.0) )-1.0 )) +cSigma; //paper cc= 4.0/(N+4.0); //code // cc= (4.0+(muEff/N))/ (N+4.0+(2.0*muEff/N)); //paper muCov=muEff; // cCov=((1.0/muCov)*(2.0/( (N+sqrt(2.0))*(N+sqrt(2.0)) )))+((1.0- (1.0/muCov))*std::min(1.0, ((2.0*muEff)-1.0)/( ((N+2.0)*(N+2.0))+muEff ) )); //paper (probably more precise) double t1 = 2.0 / ((N+1.4142)*(N+1.4142)); double t2 = (2.0*muEff-1.) / ((N+2.0)*(N+2.0)+muEff); t2 = (t2 > 1) ? 1 : t2; t2 = (1.0/muCov) * t1 + (1.0-1.0/muCov) * t2; cCov = t2; //code chiN = sqrt((double) N) * (1.0 - 1.0/(4.0*N) + 1./(21.0*N*N)); /***************setting default parameters ****************/ if(sw.init){ for (int i = 0; i < N; ++i){ //avoid memory garbage for (int j = 0; j < N; j++) sw.B[i][j]=0.0; //need to keep sw.B[i][i]=1.0; //need to keep initialStds[i] = 0.3; //does not change //code trace += initialStds[i]*initialStds[i]; //does not change } sw.sigma=sqrt(trace/N); //need to keep for (int i = 0; i < N; ++i){ //avoid memory garbage for (int j = 0; j < N; j++) sw.C[i][j]=0.0; //need to keep sw.pC[i] = sw.pSigma[i] = 0.0; //need to keep // sw.mean[i]=0.5; //need to keep // sw.mean[i]=normalize(sw.centroid[i], inferiorPositionLimit[i], superiorPositionLimit[i]); if(sw.gen>0) sw.mean[i]=(rand()/(double)RAND_MAX);//already initialized within the swarm, when restart does not need to restart, does it? } for (int i = 0; i < N; ++i) { sw.C[i][i] = sw.D[i] = initialStds[i] * sqrt(N / trace); //need to keep sw.C[i][i] *= sw.C[i][i]; //need to keep } sw.gen=0; sw.init=false; if(logCMAES) printf("\n INIT \n"); // cmaes_init(&evo, decisionNumber, NULL, NULL, 0, mu, "cmaes_initials.par"); // printf("\nlambda: %d\n",evo.sp.lambda); }else sw.gen++; //exit(1); //******************************************// //http://arxiv.org/pdf/1110.4181v1.pdf https://hal.inria.fr/hal-01146738/document //injecting external solutions into moead sw.solsKept=0; double clipped[mu][N], in[N], t[N]; for (int i = 0; i < N; i++) oldMean[i]=sw.mean[i]; for(int s=0;s<mu;s++){ //for all solutions bool injected=true; for(int r=0;r<sw.getSize();r++){//check if the current solution is in the population from the previous generation, otherwise it was injected for(int d=0;d<N;d++) t[d]=normalize(sw.particles[r].solution.decisionVector[d], inferiorPositionLimit[d], superiorPositionLimit[d]); if(isEqual(nonDominated[s],t,N)){//if this solution is in the population, it is not injected injected=false; sw.solsKept++; } } for (int i = 0; i < N; i++)// eq(2) turning x_i into y_i in[i]=(nonDominated[s][i]-oldMean[i])/sw.sigma; if(injected){//first step eq(3) : y_i <-- clip(cy,||C^{-1/2}y_i||) double sum, tmp[N], sum2=0; for (int i = 0; i < N; i++) { sum=0; for (int j = 0; j < N; ++j) sum += sw.B[j][i]*in[i];//B^T*y_i tmp[i] = sum / sw.D[i]; //B^T*y_i*D^-1 } for (int i = 0; i < N; i++) { sum=0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * tmp[j];//B^T*y_i*B*D^-1 sum2+=sum*sum; } sum2=sqrt(sum2); double cy=sqrt(N)+((2*N)/N+2); double clip=cy/sum2; //clip(c,x) = min(1,c/x) clip=std::min(1.0,clip); // double * in = nonDominated[s];//x_i // double sum2=0;//C^{-1/2} * y_i // for (int i = 0; i < N; ++i) { // double sum = 0.0; // for (int j = 0; j < N; ++j) // sum += sw.B[i][j] * sw.D[i] * ((in[i]-oldMean[i])/sw.sigma ); //y_i // sum2+=sum*sum; // } // sum2=sqrt(sum2); // double cy=sqrt(N)+((2*N)/N+2); // double clip=cy/sum2; //clip(c,x) = min(1,c/x) // clip=std::min(1.0,clip); // printf(" -- %f %f %f\n----------------------\n",sum2, cy, clip); for (int i = 0; i < N; ++i) clipped[s][i]=in[i]*clip; }else for (int i = 0; i < N; ++i) clipped[s][i]=in[i]; }//end of first step, clipping y_i //second step: \Delta m //As far as I understood, the differentiation in eq (4) is optional, to be used only if we want a strong impact with an injection, it is not used in the MOEA/D-CMA-ES paper, and is not going to be used here. double deltaM[N]; for (int i = 0; i < N; ++i){ //update of the delta mean using the second part of eq (4) deltaM[i]=0; for(int j=0;j<mu;++j) deltaM[i]+=weights[j]*clipped[j][i]; }//end of delta m update //mean update eq(5) double cm=1; for (int i = 0; i < N; ++i) sw.mean[i]=oldMean[i]+cm*sw.sigma*deltaM[i]; //end of mean update // // //delta mean clip eq(6), but only if strong injection of mean shift, we do not use this // // if(injected){ // // double * in = deltaM;//deltaM // // double sum, tmp[N], sum2=0; // // for (int i = 0; i < N; i++) { // // sum=0; // // for (int j = 0; j < N; ++j) // // sum += sw.B[j][i]*in[i];//B^T*deltaM // // tmp[i] = sum / sw.D[i]; //B^T*deltaM*D^-1 // // } // // for (int i = 0; i < N; i++) { // // sum=0; // // for (int j = 0; j < N; ++j) // // sum += sw.B[i][j] * tmp[j];//B^T*deltaM*B*D^-1 // // sum2+=sum*sum; // // } // // sum2=sqrt(sum2); // // double cym=sqrt(2*N)+((2*N)/N+2); // // double clip=cym/(sqrt(muEff)*sum2); //clip(c,x) = min(1,c/x) // // clip=std::min(1.0,clip); // // for (int i = 0; i < N; ++i) // // deltaM[i]*=clip;//if not injected, deltaM keeps the same // // } // // //end of the delta mean clip //Equations 7 and 9 were updated by changing the BDz calculation, now it is sqrt(muEff)*deltaM //Equation 8 is a little different, but there is no apparent reason for it, so we did not change it yet //Equation 10 is changed in the cov matrix //Equation 11 is changed in the sigma update //------------------------------------------------------------// // for (int i = 0; i < N; ++i) {//update of the mean and BDz //original CMA-ES update // oldMean[i]=sw.mean[i]; // sw.mean[i]=0; // for(int j=0;j<mu;++j) // sw.mean[i]+=weights[j]*nonDominated[j][i]; // in the paper sw.mean = m ;; y_w = (mean-oldMean)/sigma // BDz[i] = sqrt(muEff)*(sw.mean[i] - oldMean[i])/sw.sigma; // BDz * sqrt(muEff) = y_w * sqrt(muEff) // } for (int i = 0; i < N; ++i)//BDz with deltaM, as in the paper of injecting solutions into CMA-ES BDz[i]=sqrt(muEff)*deltaM[i]; // if(decomposition && sw.neighborhood[0].index==swarmNumber/2){//if the first neighbor of it (itself) is zero // double sum=0; // for(int i=0;i<N;i++) // sum+=abs(sw.mean[i]-oldMean[i]); // printf("%d -- %f\n",repTemp.getActualSize(), sw.sigma); // for(int i=0;i<mu;i++){ // // printf("%f -- ", repTemp.getSolution(i).weightedDistance); // for(int d=0;d<N;d++){ // printf("%.4f ", nonDominated[i][d]); // // printf("%.4f ", repTemp.getSolution(i).decisionVector[d]); // } // printf(" (%.4f)\n", getScalarValue(repTemp.getSolution(i).objectiveVector, sw.repository.weight)); // } // printf("-----------------------------------------\ncovMat:\n"); // for(int i=0;i<N;i++){ // for(int j=0;j<N;j++) // printf("%.4f ",sw.C[i][j]); // printf("\n"); // } // printf("---------------------------------------\n"); // printf("mean: "); // for(int d=0;d<N;d++){ // // printf("%.4f ", sw.mean[i]); // printf("%.4f ", sw.mean[d]); // } // printf("\nbest: "); // for(int d=0;d<N;d++){ // printf("%.4f ", normalize(sw.repository.getSolution(0).decisionVector[d], inferiorPositionLimit[d], superiorPositionLimit[d]) ); // } // printf("\n---------------------------------------------------\n"); // } double sum, tmp[N], psxps=0.0; //calculate z := D^(-1) * B^(-1) * BDz into tmp // orignal comment for (int i = 0; i < N; i++) { sum=0; for (int j = 0; j < N; ++j) sum += sw.B[j][i] * BDz[j]; tmp[i] = sum / sw.D[i]; //tmp = z = D^(-1) * B' * BDz } //cumulation for sigma (ps) using B*z //original comment for (int i = 0; i < N; i++) { sum=0; for (int j = 0; j < N; ++j) sum += sw.B[i][j] * tmp[j]; //sum = sqrt(muEff)*C^(1/2)*y_w = sqrt(muEff)*BD^−1B'*y_w sw.pSigma[i] = (1.0 - cSigma) * sw.pSigma[i] + sqrt(cSigma * (2.0 - cSigma)) * sum; /* calculate norm(ps)^2 */ psxps += sw.pSigma[i] * sw.pSigma[i]; } /* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */ hsig = sqrt(psxps) / sqrt(1.0 - pow(1.0-cSigma, 2*(sw.gen+1))) / chiN < 1.4 + 2.0/(N+1); for (int i = 0; i < N; ++i) sw.pC[i] = (1.0 - cc) * sw.pC[i] + hsig * sqrt(cc * (2.0 - cc)) * BDz[i]; //************ Adapt_C2 *********// Update covariance matrix double ccov1 = std::min(cCov * (1.0/muCov) * 1.0, 1.0); //code // double ccov1 = 2.0/(((N+1.3)*(N+1.3))+muEff); //paper double ccovmu = std::min(cCov * (1-1.0/muCov)* 1.0, 1.0-ccov1); //code // double ccovmu = std::min(1.0-ccov1, 2 * ( ( (muEff-2.0)+(1.0/muEff) )/( (N+2.0)*(N+2.0) + (2.0*muEff)/2.0 ) )); //paper double sigmasquare = sw.sigma * sw.sigma; /* update covariance matrix */ for (int i = 0; i < N; ++i) for (int j = 0; j <= i; ++j) { sw.C[i][j] = (1.0 - ccov1 - ccovmu) * sw.C[i][j] + ccov1* (sw.pC[i] * sw.pC[j] + (1.0-hsig)*cc*(2.0-cc) * sw.C[i][j]); for (int k = 0; k < mu; ++k) { /* additional rank mu update */ // sw.C[i][j] += ccovmu * weights[k]* (nonDominated[k][i] - oldMean[i]) * (nonDominated[k][j] - oldMean[j])/ sigmasquare;//original equation sw.C[i][j] += ccovmu * weights[k] * clipped[k][i] * clipped[k][j];//changed on eq (10) of the injecting solutions into cmaes paper } } //**************************************// // dSigma= (1.0 + 2.0*std::max(0.0, sqrt((muEff-1.0)/(N+1.0)) - 1.0)) * std::max(0.3, 1.0 -(double)N / (1e-6+std::min(evo.sp.stopMaxIter, evo.sp.stopMaxFunEvals/evo.sp.lambda))) + cSigma;//code (used to compare our algorithm to the implemented) /* update of sigma */ // sw.sigma *= exp(((sqrt(psxps)/chiN)-1.0)*cSigma/dSigma);//original equation double deltaSigmaMax=1; sw.sigma *= exp(std::min(deltaSigmaMax, ((sqrt(psxps)/chiN)-1.0)*cSigma/dSigma ) );//Changed on eq (11) of the injecting solutions into cmaes paper if(logCMAES){ printf("\n\nmueff %f, cSigma %f, dSigma %f, ccumcov %f, sigma %f", muEff, cSigma, dSigma, cc, sw.sigma); printf("\nhsig %d, psxps %f, chiN %f, gen %d \n", hsig, psxps, chiN, sw.gen); // printf("\n\nweights - mu: %d : ", mu); // printVector(weights, mu); printf("\navg_old : "); printVector(oldMean, N); printf("\navg : "); printVector(sw.mean, N); // printf("\n\nD mat:"); // printVector(sw.D, N); printf("\n\nBDz: "); printVector(BDz, N); printf("\ntmp : "); printVector(tmp, N); printf("\nps : "); printVector(sw.pSigma, N); printf("\npc : "); printVector(sw.pC, N); } // t->rgBDz[i] = sqrt(t->sp.mueff)*(t->rgxmean[i] - t->rgxold[i])/t->sigma; // printf("\n\nrgD (new): "); // printVector(D, N); // printf("\n\nB (new): \n"); // for (int i = 0; i < N; ++i){ // printVector(B[i], N); // printf("\n"); // } // printf("\n\nCov mat: \n"); // for (int i = 0; i < N; ++i){ // printVector(sw.C[i], N); // printf("\n"); // } //****************comparing the implemented CMA-ES with our version**********************// // evo.sp.mu=mu; // evo.sp.lambda=mu; // // for(int i=0;i<mu;i++) // for(int j=0;j<N;j++) // evo.rgrgx[i][j]=nonDominated[i][j]; // cmaes_SamplePopulation(&evo); /* do not change content of pop */ // for(int i=0;i<mu;i++) // for(int j=0;j<N;j++) // evo.rgrgx[i][j]=nonDominated[i][j]; // // for(int i=0;i<N;i++) // evo.rgxmean[i]=oldMean[i]; // // printf("\nccov1 %f", ccov1); // printf("\nccovmu %f", ccovmu); // printf("\nsigmasquare %.20f", sigmasquare); // printf("\nhsig %d", hsig); // printf("\nccumcov %f", cc); // printf("\nccov %.20f", cCov); // printf("\nmucov %.20f", muCov); // printf("\nmueff: %.20f", muEff); // printf("\nBDz: "); // printVector(BDz, N); // printf("\npSigma: "); // printVector(sw.pSigma, N); // printf("\npC: "); // printVector(sw.pC, N); // printf("\nD: "); // for(int i=0;i<N;i++) // printf("%.15f ",sw.D[i]); // printf("\npsxps: %f", psxps); // printf("\nchin: %f", chiN); // printf("\ncSigma: %f", cSigma); // printf("\ndSigma: %f", dSigma); // printf("\nsigma: %f", sw.sigma); // printf("\nmean: "); // printVector(sw.mean, N); // printf("\nold: "); // printVector(oldMean, N); // printf("\nweights: "); // printVector(weights, mu); // // cmaes_UpdateDistribution(&evo, weights); // // if(evo.sp.ccov != cCov){ // printf("\ncCov different\n"); // exit(1); // } // if(evo.sp.mucov != muCov){ // printf("\nmuCov different\n"); // exit(1); // } // if(evo.sp.ccumcov != cc){ // printf("\ncc different\n"); // exit(1); // } // if(evo.sp.mueff != muEff){ // printf("\nmuEff different\n"); // exit(1); // } // if(evo.sp.cs != cSigma){ // printf("\ncSigma different\n"); // exit(1); // } // if(evo.sp.damps != dSigma){ // printf("\ndSigma different\n"); // exit(1); // } // for(int i=0;i<N;i++){ // if(evo.rgBDz[i] != BDz[i]){ // printf("\nBDz on %d different\n", i); // exit(1); // } // if(evo.rgD[i] != sw.D[i]){ // printf("\nD on %d different\n", i); // exit(1); // } // if(evo.rgdTmp[i] != tmp[i]){ // printf("\ntmp on %d different\n", i); // exit(1); // } // if(evo.rgps[i] != sw.pSigma[i]){ // printf("\npSigma on %d different (%.20f)\n", i, abs(evo.rgps[i] - sw.pSigma[i])); // exit(1); // } // if(evo.rgpc[i] != sw.pC[i]){ // printf("\npC on %d different\n", i); // exit(1); // } // } // // printf("\nevo mean: "); // printVector(evo.rgxmean, N); // printf("\nevo old: "); // printVector(evo.rgxold, N); // printf("\nevo weights: "); // printVector(evo.sp.weights, mu); // // printf("\n\norig-cmaes\n"); // for(int i=0; i<cmaes_Get(&evo, "dim");i++){ // for(int j=0;j<cmaes_Get(&evo, "dim");j++) // printf("%f ",evo.C[i][j]); // printf("\n"); // } // // printf("\nmodif-cmaes\n"); // for(int i=0; i<N;i++){ // for(int j=0;j<N;j++) // printf("%f ",sw.C[i][j]); // printf("\n"); // } // // for(int i=0; i<N;i++){ // for(int j=0;j<N;j++){ // if(((int)(evo.C[i][j]*1000000))/1000000.0 != ((int)(sw.C[i][j]*1000000))/1000000.0){ // printf("Different %f -- %f \t (%e) (%d,%d)\n", evo.C[i][j], sw.C[i][j], abs(evo.C[i][j] - sw.C[i][j]), i, j ); // maxDifference=std::max(maxDifference, abs(evo.C[i][j] - sw.C[i][j])); // // exit(1); // } // } // } // printf("maxDifference: %.20f, sigmaDifference: %.20f\n", maxDifference, abs(evo.sigma-sw.sigma)); // if(maxDifference > 1 ){ // printf("%d\n", mu); // exit(1); // } //**************************************************************************************// }