int main (int argc, char* argv[]) { int objs[2*N+1]; int i; objs[0]=N; for(i=1; i<=N;i++){ objs[2*i-1]=N+i; objs[2*i]=N-i; } random_permutation(objs, 2*N+1); printf("Test de heap_remove_min\n"); /********************************/ heap h=prof_heap_create(f); for(i=0; i<=2*N; i++) h=prof_heap_insert(h, &objs[i]); heap_dump(h); for(i=0; i<=2*N; i++){ h=heap_remove_min(h); heap_dump(h); } prof_heap_destroy(h); return 0; }
int main (int argc, char* argv[]) { printf("Test de splay_coupe\n"); int i; splay A = prof_splay_create(f); int * objs = malloc(N*sizeof(*objs)); random_permutation(objs, N); for(i = 0 ; i < N ; i++) prof_splay_insert(A, &objs[i]); splay_dump(A); printf("****************************************\n"); splay R=splay_coupe(A, N/2); splay_dump(A); printf("*****************\n"); splay_dump(R); prof_splay_destroy(A); prof_splay_destroy(R); free(objs); return 0; }
int main(){ srand(time(NULL)); int i; for(i=0;i<5;i++){ long* vec = random_permutation(10); print_vec_inline(vec,10); vecfreel(vec); } return 0; }
int main ( int argc, char * argv[]) { unsigned int seed,nelt,keylen; if ( argc!=4){ printf ("Usage: rbtree seed nelt keylen\n"); return EXIT_FAILURE; } sscanf(argv[1],"%u",&seed); srandom(seed); sscanf(argv[2],"%u",&nelt); sscanf(argv[3],"%u",&keylen); RBTREE tree = create_rbtree(lexo,strcopykey,strfreekey); char ** keys = random_keys(nelt,keylen); printf ("Inserting elements\n"); for ( int i=0 ; i<nelt ; i++){ printf ("\tinserting %s\n",keys[i]); insertelt_rbtree(tree,keys[i],"a"); check_rbtree(tree); } unsigned int ntree_elt = nmemb_rbtree(tree); printf ("Tree contains %u elements in total\n",ntree_elt); assert(ntree_elt<=nelt); printf ("Copying tree\n"); RBTREE tree2 = copy_rbtree(tree,strcopykey); check_rbtree(tree2); printf("Freeing copied tree\n"); free_rbtree(tree2,free); printf("Printing tree\n"); unsafemap_rbtree (tree,print_node); printf("Iterating through tree\n"); unsigned int iter_count = 0; for ( RBITER iter = iter_rbtree(tree) ; next_rbtree(iter) ; ){ const char * key = (const char *) iterkey_rbtree(iter); printf("\tfound %s\n",key); iter_count++; } assert(iter_count==ntree_elt); printf ("Removing elements\n"); unsigned int * rperm = random_permutation(nelt); fputs("Permutation: ",stdout); print_rperm(rperm,nelt); for ( int i=0 ; i<nelt ; i++){ printf("\tremoving %s\n",keys[rperm[i]]); removeelt_rbtree(tree,keys[rperm[i]]); check_rbtree(tree); } assert(nmemb_rbtree(tree)==0); free_rbtree(tree,free); }
InitializePermutations() { const size_t Size = noise_impl::Permutations::Size; MersenneTwister rng; random_permutation(Size, g_perms.m_p1, rng); for (size_t i = 0; i < Size; ++i) g_perms.m_p1[i + Size] = g_perms.m_p1[i]; random_permutation(Size, g_perms.m_p2, rng); for (size_t i = 0; i < Size; ++i) g_perms.m_p2[i + Size] = g_perms.m_p2[i]; random_permutation(Size, g_perms.m_p3, rng); for (size_t i = 0; i < Size; ++i) g_perms.m_p3[i + Size] = g_perms.m_p3[i]; random_permutation(Size, g_perms.m_p4, rng); for (size_t i = 0; i < Size; ++i) g_perms.m_p4[i + Size] = g_perms.m_p4[i]; }
/* * computes a vector that is [uncut,cut] and each part is randomly permuted */ long* pa_unsorted_random(struct sparsematrix* A){ int i; int cut_length, uncut_length; long *cut_part, *uncut_part; cut_and_uncut(A,&cut_part,&cut_length,&uncut_part,&uncut_length); long* cut_perm = random_permutation(cut_length); long* uncut_perm = random_permutation(uncut_length); int m = A->m, n=A->n; long* vec = vecallocl(m+n); int index_vec = 0; for(i=0;i<uncut_length;i++) vec[index_vec++] = uncut_part[uncut_perm[i]]; for(i=0;i<cut_length;i++) vec[index_vec++] = cut_part[cut_perm[i]]; vecfreel(cut_part); vecfreel(cut_perm); vecfreel(uncut_part); vecfreel(uncut_perm); return vec; }
static void maximal_independent_vertex_set(SparseMatrix A, int randomize, int **vset, int *nvset, int *nzc){ int i, ii, j, *ia, *ja, m, n, *p = NULL; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *vset = N_GNEW(m,int); for (i = 0; i < m; i++) (*vset)[i] = MAX_IND_VTX_SET_U; *nvset = 0; *nzc = 0; if (!randomize){ for (i = 0; i < m; i++){ if ((*vset)[i] == MAX_IND_VTX_SET_U){ (*vset)[i] = (*nvset)++; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; (*vset)[ja[j]] = MAX_IND_VTX_SET_F; (*nzc)++; } } } } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; if ((*vset)[i] == MAX_IND_VTX_SET_U){ (*vset)[i] = (*nvset)++; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; (*vset)[ja[j]] = MAX_IND_VTX_SET_F; (*nzc)++; } } } FREE(p); } (*nzc) += *nvset; }
static void maximal_independent_edge_set(SparseMatrix A, int randomize, int **matching, int *nmatch){ int i, ii, j, *ia, *ja, m, n, *p = NULL; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *matching = N_GNEW(m,int); for (i = 0; i < m; i++) (*matching)[i] = i; *nmatch = n; if (!randomize){ for (i = 0; i < m; i++){ for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if ((*matching)[ja[j]] == ja[j] && (*matching)[i] == i){ (*matching)[ja[j]] = i; (*matching)[i] = ja[j]; (*nmatch)--; } } } } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if ((*matching)[ja[j]] == ja[j] && (*matching)[i] == i){ (*matching)[ja[j]] = i; (*matching)[i] = ja[j]; (*nmatch)--; } } } FREE(p); } }
void test_bliss() { igraph_t ring1, ring2, directed_ring; igraph_vector_t perm; igraph_bool_t iso; igraph_bliss_info_t info; igraph_vector_int_t color; igraph_vector_ptr_t generators; igraph_ring(&ring1, 100, /*directed=*/ 0, /*mutual=*/ 0, /*circular=*/1); igraph_vector_init_seq(&perm, 0, igraph_vcount(&ring1)-1); random_permutation(&perm); igraph_permute_vertices(&ring1, &ring2, &perm); igraph_ring(&directed_ring, 100, /* directed= */ 1, /* mutual = */0, /* circular = */1); igraph_vector_ptr_init(&generators, 0); IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&generators, igraph_vector_destroy); igraph_isomorphic_bliss(&ring1, &ring2, NULL, NULL, &iso, NULL, NULL, IGRAPH_BLISS_F, NULL, NULL); if (! iso) printf("Bliss failed on ring isomorphism.\n"); igraph_automorphisms(&ring1, NULL, IGRAPH_BLISS_F, &info); if (strcmp(info.group_size, "200") != 0) printf("Biss automorphism count failed: ring1.\n"); igraph_free(info.group_size); igraph_automorphisms(&ring2, NULL, IGRAPH_BLISS_F, &info); if (strcmp(info.group_size, "200") != 0) printf("Biss automorphism count failed: ring2.\n"); igraph_free(info.group_size); igraph_automorphisms(&directed_ring, NULL, IGRAPH_BLISS_F, &info); if (strcmp(info.group_size, "100") != 0) printf("Biss automorphism count failed: directed_ring.\n"); igraph_free(info.group_size); // The follwing test is included so there is at least one call to igraph_automorphism_group // in the test suite. However, the generator set returned may depend on the splitting // heursitics as well as on the Bliss version. If the test fails, please verify manually // that the generating set is valid. For a undirected cycle graph like ring2, there should // be two generators: a cyclic permutation and a reversal of the vertex order. igraph_automorphism_group(&ring2, NULL, &generators, IGRAPH_BLISS_F, NULL); if (igraph_vector_ptr_size(&generators) != 2) printf("Bliss automorphism generators may have failed with ring2. " "Please verify the generators manually. " "Note that the generator set is not guaranteed to be minimal.\n"); igraph_vector_ptr_free_all(&generators); // For a directed ring, the only generator should be a cyclic permutation. igraph_automorphism_group(&directed_ring, NULL, &generators, IGRAPH_BLISS_F, NULL); if (igraph_vector_ptr_size(&generators) != 1) printf("Bliss automorphism generators may have failed with directed_ring. " "Please verify the generators manually. " "Note that the generator set is not guaranteed to be minimal.\n"); igraph_vector_ptr_free_all(&generators); igraph_vector_int_init_seq(&color, 0, igraph_vcount(&ring1)-1); igraph_automorphisms(&ring1, &color, IGRAPH_BLISS_F, &info); if (strcmp(info.group_size, "1") != 0) printf("Biss automorphism count with color failed: ring1.\n"); igraph_free(info.group_size); // There's only one automorphism for this coloured graph, so the generating set is empty. igraph_automorphism_group(&ring1, &color, &generators, IGRAPH_BLISS_F, NULL); if (igraph_vector_ptr_size(&generators) != 0) printf("Bliss automorphism generators failed with colored graph.\n"); igraph_vector_ptr_destroy_all(&generators); igraph_vector_int_destroy(&color); igraph_vector_destroy(&perm); igraph_destroy(&ring1); igraph_destroy(&ring2); igraph_destroy(&directed_ring); }
/* * computes a vector that is just the random permutation of the rows/columns indices */ long* po_unsorted_random(struct sparsematrix* A){ return random_permutation(A->m+A->n); }
void generate_dimacs_random_graph( graph_adapter& g, typename graph_traits<graph_adapter>::size_type scale, typename graph_traits<graph_adapter>::size_type average_degree) { typedef typename graph_traits<graph_adapter>::size_type size_type; size_type n = 1 << scale; size_type m = n * average_degree; // Adjacencies, really. size_type* srcs = (size_type*) malloc(m * sizeof(size_type)); size_type* dests = (size_type*) malloc(m * sizeof(size_type)); // Create Hamiltonian cycle part of graph. #pragma mta assert nodep for (size_type i = 0; i < n - 1; ++i) { srcs[i] = i; dests[i] = i + 1; } srcs[n - 1] = n - 1; dests[n - 1] = 0; // Put the Hamiltonian cycle edges in unique_edges. xmt_hash_set<size_type> unique_edges; #pragma mta assert nodep for (size_type i = 0; i < n - 1; ++i) { size_type key = i * m + i + 1; unique_edges.insert(key); } unique_edges.insert((n - 1) * m); // Create remainder of graph which is random edges. size_type nrvals = m - n; lrand48_generator randVals1(nrvals); lrand48_generator randVals2(nrvals); size_type num_unique_edges = n; #pragma mta assert parallel for (size_type i = n; i < m; ++i) { size_type v1 = randVals1[i - n] % n; size_type v2 = randVals2[i - n] % n; size_type key = v1 * m + v2; // Only add unique edges, and skip self loops. if (v1 != v2 && unique_edges.insert(key).second) { size_type ind = mt_incr(num_unique_edges, 1); srcs[ind] = v1; dests[ind] = v2; } } #ifdef PERMUTE_NODES random_permutation(n, m, srcs, dests); #endif init(n, num_unique_edges, srcs, dests, g); free(srcs); free(dests); }
double VRP::RTR_solve(int heuristics, int intensity, int max_stuck, int max_perturbs, double dev, int nlist_size, int perturb_type, int accept_type, bool verbose) { /// /// Uses the given parameters to generate a /// VRP solution via record-to-record travel. /// Assumes that data has already been imported into V and that we have /// some existing solution. /// Returns the objective function value of the best solution found /// // Make sure accept_type is either VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT - matters only // for the downhill phase as we use VRPH_LI_ACCEPT in the diversification phase if(accept_type!=VRPH_BEST_ACCEPT && accept_type!=VRPH_FIRST_ACCEPT) report_error("%s: accept_type must be VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT\n"); int ctr, n, j, i, R, random, fixed, neighbor_list, objective, tabu; random=fixed=neighbor_list=0; if(heuristics & VRPH_RANDOMIZED) random=VRPH_RANDOMIZED; if(heuristics & VRPH_FIXED_EDGES) fixed=VRPH_FIXED_EDGES; if(heuristics & VRPH_USE_NEIGHBOR_LIST) neighbor_list=VRPH_USE_NEIGHBOR_LIST; objective=VRPH_SAVINGS_ONLY; // default strategy if(heuristics & VRPH_MINIMIZE_NUM_ROUTES) objective=VRPH_MINIMIZE_NUM_ROUTES; if(heuristics & VRPH_TABU) { tabu=VRPH_TABU; // We will use a primitive Tabu Search in the uphill phase // Clear the tabu list this->tabu_list->empty(); } else tabu=0; n=num_nodes; // Define the heuristics we will use OnePointMove OPM; TwoPointMove TPM; TwoOpt TO; OrOpt OR; ThreeOpt ThreeO; CrossExchange CE; ThreePointMove ThreePM; double start_val; int *perm; perm=new int[this->num_nodes]; j=VRPH_ABS(this->next_array[VRPH_DEPOT]); for(i=0;i<this->num_nodes;i++) { perm[i]=j; if(!routed[j]) report_error("%s: Unrouted node in solution!!\n"); j=VRPH_ABS(this->next_array[j]); } if(j!=VRPH_DEPOT) report_error("%s: VRPH_DEPOT is not last node in solution!!\n"); int rules; // Set the neighbor list size used in the improvement search neighbor_list_size=VRPH_MIN(nlist_size, this->num_nodes); // Set the deviation deviation=dev; int num_perturbs=0; record=this->total_route_length; this->best_total_route_length=this->total_route_length; this->export_solution_buff(this->current_sol_buff); this->export_solution_buff(this->best_sol_buff); normalize_route_numbers(); ctr=0; uphill: // Start an uphill phase using the following "rules": double beginning_best=this->best_total_route_length; rules=VRPH_LI_ACCEPT+VRPH_RECORD_TO_RECORD+objective+random+fixed+neighbor_list+tabu; if(verbose) printf("Uphill starting at %5.2f\n",this->total_route_length); for(int k=1;k<intensity;k++) { start_val=total_route_length; if(heuristics & ONE_POINT_MOVE) { if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { #if FIXED_DEBUG if(fixed && !check_fixed_edges("Before 1PM\n")) fprintf(stderr,"Error before OPM search(%d)\n",perm[i-1]); #endif OPM.search(this,perm[i-1],rules); #if FIXED_DEBUG if(fixed && !check_fixed_edges("After 1PM\n")) { fprintf(stderr,"Error after OPM search(%d)\n",perm[i-1]); this->show_route(this->route_num[perm[i-1]]); } #endif } } if(heuristics & TWO_POINT_MOVE) { if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) TPM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY); //check_fixed_edges("After 2PM\n"); } if(heuristics & THREE_POINT_MOVE) { if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) ThreePM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY); //check_fixed_edges("After 3PM\n"); } if(heuristics & TWO_OPT) { if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) TO.search(this,perm[i-1],rules); //check_fixed_edges("After TO\n"); } if(heuristics & OR_OPT) { if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) OR.search(this,perm[i-1],4,rules); for(i=1;i<=n;i++) OR.search(this,perm[i-1],3,rules); for(i=1;i<=n;i++) OR.search(this,perm[i-1],2,rules); //check_fixed_edges("After OR\n"); } if(heuristics & THREE_OPT) { normalize_route_numbers(); R=total_number_of_routes; for(i=1; i<=R; i++) ThreeO.route_search(this,i,rules-neighbor_list); //check_fixed_edges("After 3O\n"); } if(heuristics & CROSS_EXCHANGE) { normalize_route_numbers(); this->find_neighboring_routes(); R=total_number_of_routes; for(i=1; i<=R-1; i++) { for(j=0;j<1;j++) CE.route_search(this,i, route[i].neighboring_routes[j],rules-neighbor_list); } //check_fixed_edges("After CE\n"); } } if(total_route_length<record) record = total_route_length; if(verbose) { printf("Uphill complete\t(%d,%5.2f,%5.2f)\n",count_num_routes(),total_route_length, record); printf("# of recorded routes: %d[%d]\n",total_number_of_routes,count_num_routes()); } if(this->best_total_route_length<beginning_best-VRPH_EPSILON) { if(verbose) printf("New best found in uphill!\n"); // We found a new best solution during the uphill phase that might // now be "forgotten"!! I have seen this happen where it is never recovered // again, so we just import it and start the downhill phase with this solution... //this->import_solution_buff(this->best_sol_buff); } downhill: // Now enter a downhill phase double orig_val=total_route_length; if(verbose) printf("Downhill starting at %f (best=%f)\n",orig_val,this->best_total_route_length); if((heuristics & ONE_POINT_MOVE)|| (heuristics & KITCHEN_SINK) ) { rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type; for(;;) { // One Point Move start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) OPM.search(this,perm[i-1],rules ); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if((heuristics & TWO_POINT_MOVE) || (heuristics & KITCHEN_SINK) ) { rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type; for(;;) { // Two Point Move start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) TPM.search(this,perm[i-1],rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if((heuristics & TWO_OPT)|| (heuristics & KITCHEN_SINK) ) { // Do inter-route first a la Li rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type; for(;;) { start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) TO.search(this,perm[i-1],rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } // Now do both intra and inter rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type; for(;;) { start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) TO.search(this,perm[i-1],rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if((heuristics & THREE_POINT_MOVE) || (heuristics & KITCHEN_SINK) ) { rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+accept_type+neighbor_list; for(;;) { // Three Point Move start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) ThreePM.search(this,perm[i-1],rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if((heuristics & OR_OPT) || (heuristics & KITCHEN_SINK)) { rules=VRPH_DOWNHILL+ objective +random +fixed + accept_type + neighbor_list; for(;;) { // OrOpt start_val=total_route_length; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) OR.search(this,perm[i-1],4,rules); for(i=1;i<=n;i++) OR.search(this,perm[i-1],3,rules); for(i=1;i<=n;i++) OR.search(this,perm[i-1],2,rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if((heuristics & THREE_OPT) || (heuristics & KITCHEN_SINK) ) { normalize_route_numbers(); R= total_number_of_routes; rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type; for(;;) { // 3OPT start_val=total_route_length; for(i=1;i<=R;i++) ThreeO.route_search(this,i,rules); if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON) break; } } if( (heuristics & CROSS_EXCHANGE) ) { normalize_route_numbers(); this->find_neighboring_routes(); R=total_number_of_routes; rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type; for(i=1; i<=R-1; i++) { for(j=0;j<=1;j++) CE.route_search(this,i, route[i].neighboring_routes[j], rules); } } // Repeat the downhill phase until we find no more improvements if(total_route_length<orig_val-VRPH_EPSILON) goto downhill; if(verbose) printf("Downhill complete: %5.2f[downhill started at %f] (%5.2f)\n",total_route_length,orig_val, this->best_total_route_length); if(total_route_length < record-VRPH_EPSILON) { // New record - reset ctr ctr=1; record=total_route_length; } else ctr++; if(ctr<max_stuck) goto uphill; if(ctr==max_stuck) { if(num_perturbs<max_perturbs) { if(verbose) printf("perturbing\n"); if(perturb_type==VRPH_LI_PERTURB) perturb(); else osman_perturb(VRPH_MAX(20,num_nodes/10),.5+lcgrand(20)); // Reset record this->record=this->total_route_length; if(tabu) this->tabu_list->empty(); ctr=1; num_perturbs++; goto uphill; } } if(verbose) { if(has_service_times==false) printf("BEST OBJ: %f\n",best_total_route_length); else printf("BEST OBJ: %f\n",best_total_route_length-total_service_time); } delete [] perm; // Import the best solution found this->import_solution_buff(best_sol_buff); if(has_service_times==false) return best_total_route_length; else return best_total_route_length-total_service_time; }
int main(int argc, char** argv) { int opt_char; enum algorithm_t { e_null = 0, e_permutation = 1, e_subset = 2, }; algorithm_t algorithm = e_null; /** * long options is not portal using getopt, ignored. */ while ((opt_char = getopt(argc, argv, "hs:a:")) != -1) { switch (opt_char) { case 's': { int seed = strtol(optarg, 0, 10); srand(seed); break; } case 'a': switch (*optarg) { case 'p': algorithm = e_permutation; break; case 's': algorithm = e_subset; break; default: fprintf(stderr, "unsupported algorithm %s\n", optarg); exit(1); } break; case 'h': fprintf(stderr, "Usage: %s -s<SEED> integer-list\n", argv[0]); exit(1); case '?': exit(1); } } if (!algorithm) { fprintf(stderr, "algorithm(-a) not specified\n"); exit(1); } switch(algorithm) { case e_permutation: { int len = argc-optind; int* a = new int[len]; for (int i = 0; i < len; ++i) a[i] = strtol(argv[optind+i], 0, 10); random_permutation(len, a); for (int i = 0; i < len; ++i) fprintf(stdout, "%d ", a[i]); fprintf(stdout, "\n"); delete a; break; } case e_subset: { int m = strtol(argv[optind], 0, 10); int len = argc-optind-1; int* b = new int[m]; int* a = new int[len]; for (int i = 0; i < len; ++i) a[i] = strtol(argv[optind+1+i], 0, 10); random_subset(len, a, m, b); std::sort(b, b+m); for (int i = 0; i < m; ++i) fprintf(stdout, "%d ", b[i]); fprintf(stdout, "\n"); delete a; delete b; break; } } return 0; }
static void maximal_independent_edge_set_heavest_edge_pernode_scaled(SparseMatrix A, int randomize, int **matching, int *nmatch){ int i, ii, j, *ia, *ja, m, n, *p = NULL; real *a, amax = 0; int first = TRUE, jamax = 0; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *matching = N_GNEW(m,int); for (i = 0; i < m; i++) (*matching)[i] = i; *nmatch = n; assert(SparseMatrix_is_symmetric(A, FALSE)); assert(A->type == MATRIX_TYPE_REAL); a = (real*) A->a; if (!randomize){ for (i = 0; i < m; i++){ first = TRUE; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if ((*matching)[ja[j]] == ja[j] && (*matching)[i] == i){ if (first) { amax = a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]); jamax = ja[j]; first = FALSE; } else { if (a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]) > amax){ amax = a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]); jamax = ja[j]; } } } } if (!first){ (*matching)[jamax] = i; (*matching)[i] = jamax; (*nmatch)--; } } } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; if ((*matching)[i] != i) continue; first = TRUE; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if ((*matching)[ja[j]] == ja[j] && (*matching)[i] == i){ if (first) { amax = a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]); jamax = ja[j]; first = FALSE; } else { if (a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]) > amax){ amax = a[j]/(ia[i+1]-ia[i])/(ia[ja[j]+1]-ia[ja[j]]); jamax = ja[j]; } } } } if (!first){ (*matching)[jamax] = i; (*matching)[i] = jamax; (*nmatch)--; } } FREE(p); } }
void compute(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], const int atria_preprocessing_given, METRIC dummy) { long bins = 32; double start_dist = 0; double maximal_search_radius = 0; double scale_factor = 1; long opt_flag = 0; // 0 => eucl.norm, upper triangle matrix, 1 => max.norm, utm, 2 => eucl,full matrix, 3 => max.,full matrix long Nref_min; long Nref_max; /* handle matrix I/O */ #ifdef C_STYLE_POINT_SET const long N = mxGetN(prhs[0]); const long dim = mxGetM(prhs[0]); #else // this is the default const long N = mxGetM(prhs[0]); const long dim = mxGetN(prhs[0]); #endif const double* p = (double *)mxGetPr(prhs[0]); const long Npairs = (long) *((double *)mxGetPr(prhs[1])); // number of pairs if (mxGetM(prhs[1])*mxGetN(prhs[1]) == 3) { Nref_min = (long) ((double *)mxGetPr(prhs[1]))[1]; Nref_max = (long) ((double *)mxGetPr(prhs[1]))[2]; } else { Nref_min = 1; Nref_max = N; } const double relative_range = (double) *((double *)mxGetPr(prhs[2])); const long past = (long) *((double *)mxGetPr(prhs[3])); if (nrhs > 4) bins = (long) *((double *)mxGetPr(prhs[4])); if (nrhs > 5) opt_flag = (long) *((double *)mxGetPr(prhs[5])); if (N < 1) { mexErrMsgTxt("Data set must consist of at least two points (row vectors)"); return; } if (dim < 1) { mexErrMsgTxt("Data points must be at least of dimension one"); return; } if (relative_range <= 0) { mexErrMsgTxt("Relative range must be greater zero"); return; } if (bins < 2) { mexErrMsgTxt("Number of bins should be two"); return; } if (Npairs < 1) { mexErrMsgTxt("Number of pairs must be positive"); return; } if ((opt_flag < 0) || (opt_flag > 7)) { mexErrMsgTxt("Flag must be out of 0..7"); return; } if (Nref_min < 1) Nref_min = 1; if (Nref_max > N) Nref_max = N; point_set<METRIC> points(N,dim, p); ATRIA< point_set<METRIC> >* searcher = 0; #ifdef MATLAB_MEX_FILE if (atria_preprocessing_given) { searcher = new ATRIA< point_set<METRIC> >(points, prhs[-1]); // this constructor used the data from the preprocessing if (searcher->geterr()) { delete searcher; searcher = 0; } } #endif if (searcher == 0) { searcher = new ATRIA< point_set<METRIC> >(points); } if (searcher->geterr()) { mexErrMsgTxt("Error preparing searcher"); return; } if (mxGetM(prhs[2])*mxGetN(prhs[2]) == 2) { start_dist = (double) ((double *)mxGetPr(prhs[2]))[0]; maximal_search_radius = (double) ((double *)mxGetPr(prhs[2]))[1]; if (start_dist <= 0) { mexErrMsgTxt("Starting radius is zero or negativ"); return; } if (maximal_search_radius <= start_dist) { mexErrMsgTxt("Maximal search radius must be greater than starting radius"); return; } } else { maximal_search_radius = relative_range * searcher->data_set_radius(); // compute the maximal search radius using information about attractor size // try to determine an estimate for the minimum inter-point distance in the data set, but greater zero for (long n=0; n < 128; n++) { const long actual = (long) (((double)rand() * (double) (N-2))/(double)RAND_MAX); vector<neighbor> v; searcher->search_k_neighbors(v, 1, points.point_begin(actual), actual, actual); // search the nearest neighbor if (v.size() > 0) { if (start_dist == 0) start_dist = v[0].dist(); if (v[0].dist() > 0) { if (v[0].dist() < start_dist) start_dist = v[0].dist(); } } } if (start_dist <= 0) { // first try to search again for a minimum inter-point distance greater zero for (long n=0; n < 512; n++) { const long actual = (long) (((double)rand() * (double) (N-2))/(double)RAND_MAX); vector<neighbor> v; searcher->search_k_neighbors(v, 1, points.point_begin(actual), actual, actual); // search the nearest neighbor if (v.size() > 0) { if (start_dist == 0) start_dist = v[0].dist(); if (v[0].dist() > 0) { if (v[0].dist() < start_dist) start_dist = v[0].dist(); } } } } if (start_dist <= 0) { // give up if we cannot find an interpoint distance greater zero mexErrMsgTxt("Cannot find an interpoint distance greater zero, maybe ill-conditioned data set given"); return; } if (maximal_search_radius <= start_dist) { mexErrMsgTxt("Maximal search radius must be greater than starting radius"); return; } } scale_factor = pow(maximal_search_radius/start_dist, 1.0/(bins-1)); if (be_verbose) { //mexPrintf("Number of reference points : %d\n", R); mexPrintf("Number of data set points : %d\n", N); mexPrintf("Number of pairs to find : %d\n", Npairs); mexPrintf("Miniumum number of reference points : %d\n", Nref_min); mexPrintf("Maximum number of reference points : %d\n", Nref_max); mexPrintf("Upper bound for attractor size : %f\n", 2 * searcher->data_set_radius()); mexPrintf("Number of partitions used : %d\n", bins); mexPrintf("Time window to exclude from search : %d\n", past); mexPrintf("Minimal length scale : %f\n", start_dist); mexPrintf("Starting at maximal length scale : %f\n", maximal_search_radius); } plhs[0] = mxCreateDoubleMatrix(bins, 1, mxREAL); double* corrsums = (double *) mxGetPr(plhs[0]); long* const ref = new long[N]; // needed to create random reference indices long* const total_pairs = new long[bins]; // number of total pairs is not equal for all bins long* const pairs_found = new long[bins]; // number of pairs found within distance dist double* dists; if (nlhs > 1) { plhs[1] = mxCreateDoubleMatrix(bins, 1, mxREAL); dists = (double *) mxGetPr(plhs[1]); } else dists = new double[bins]; double x = start_dist; // initialize vectors // pairs_found[i] counts the number of points/distances (real) smaller than dists[i] for (long bin=0; bin < bins; bin++) { pairs_found[bin] = 0; total_pairs[bin] = 0; dists[bin] = x; x *= scale_factor; } for (long r=0; r < N; r++) ref[r] = r; long R = 0; // number of reference points actually used long bin = bins-1; // the current highest bin (and length scale) that needs to be filled over Npairs while(((R < Nref_min) || (pairs_found[bin] < Npairs)) && (R < Nref_max)) { vector<neighbor> v; long first, last; // all points with indices i so that first <= i <= last are excluded(!) from search long pairs = 0; const long actual = random_permutation(ref, N, R++); // choose random index from 0...N-1, without reoccurences if (opt_flag & (long)2) { first = actual-past; last = actual+past; if (past >= 0) pairs = lmax(0,first) + lmax(N-1-last,0); else pairs = N; } else { if (past >= 0) first = actual-past; else first = actual; last = N; pairs = lmin(first,last); // don't search points from [actual-past .. N-1] } if (pairs <= 0) { continue; } searcher->search_range(v, dists[bin], points.point_begin(actual), first, last); if (v.size() > 0) { for (vector<neighbor>::iterator i = v.begin(); i < v.end(); i++) { // v is unsorted (!!!) const double d = (*i).dist(); for (long n = bin; n >= 0; n--) { if (d > dists[n]) break; pairs_found[n]++; } } } for (long n = 0; n <= bin; n++) { total_pairs[n] += pairs; } // see if we can reduce length scale int bins_changed = 0; while((pairs_found[bin] >= Npairs) && (bin > 0) && (R >= Nref_min)) { bin--; bins_changed = 1; } if (be_verbose) { if (bins_changed) { mexPrintf("Reference points used so far : %d\n", R); mexPrintf("Switching to length scale : %f\n", dists[bin]); } } } if (be_verbose) { mexPrintf("Number of reference points used : %d\n", R); } for (long bin=0; bin < bins; bin++) { corrsums[bin] = ((double) pairs_found[bin]) / ((double) total_pairs[bin]); } if (nlhs > 2) { plhs[2] = mxCreateDoubleMatrix(bins, 1, mxREAL); double* const y = mxGetPr(plhs[2]); for (long b=0; b < bins; b++) y[b] = (double) pairs_found[b]; } if (nlhs > 3) { plhs[3] = mxCreateDoubleMatrix(bins, 1, mxREAL); double* const y = mxGetPr(plhs[3]); for (long b=0; b < bins; b++) y[b] = (double) total_pairs[b]; } if (nlhs > 4) { plhs[4] = mxCreateDoubleMatrix(R, 1, mxREAL); double* const y = mxGetPr(plhs[4]); for (long r=0; r < R; r++) y[r] = (double) ref[r]+1; // C to Matlab means } delete[] total_pairs; delete[] pairs_found; delete[] ref; if (!(nlhs > 1)) delete[] dists; delete searcher; }
static void maximal_independent_edge_set_heavest_edge_pernode_supernodes_first(SparseMatrix A, int randomize, int **cluster, int **clusterp, int *ncluster){ int i, ii, j, *ia, *ja, m, n, *p = NULL; real *a, amax = 0; int first = TRUE, jamax = 0; int *matched, nz, nz0; enum {UNMATCHED = -2, MATCHED = -1}; int nsuper, *super = NULL, *superp = NULL; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *cluster = N_GNEW(m,int); *clusterp = N_GNEW((m+1),int); matched = N_GNEW(m,int); for (i = 0; i < m; i++) matched[i] = i; assert(SparseMatrix_is_symmetric(A, FALSE)); assert(A->type == MATRIX_TYPE_REAL); SparseMatrix_decompose_to_supervariables(A, &nsuper, &super, &superp); *ncluster = 0; (*clusterp)[0] = 0; nz = 0; a = (real*) A->a; for (i = 0; i < nsuper; i++){ if (superp[i+1] - superp[i] <= 1) continue; nz0 = (*clusterp)[*ncluster]; for (j = superp[i]; j < superp[i+1]; j++){ matched[super[j]] = MATCHED; (*cluster)[nz++] = super[j]; if (nz - nz0 >= MAX_CLUSTER_SIZE){ (*clusterp)[++(*ncluster)] = nz; nz0 = nz; } } if (nz > nz0) (*clusterp)[++(*ncluster)] = nz; } if (!randomize){ for (i = 0; i < m; i++){ first = TRUE; if (matched[i] == MATCHED) continue; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if (matched[ja[j]] != MATCHED && matched[i] != MATCHED){ if (first) { amax = a[j]; jamax = ja[j]; first = FALSE; } else { if (a[j] > amax){ amax = a[j]; jamax = ja[j]; } } } } if (!first){ matched[jamax] = MATCHED; matched[i] = MATCHED; (*cluster)[nz++] = i; (*cluster)[nz++] = jamax; (*clusterp)[++(*ncluster)] = nz; } } /* dan yi dian, wu ban */ for (i = 0; i < m; i++){ if (matched[i] == i){ (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } assert(nz == n); } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; first = TRUE; if (matched[i] == MATCHED) continue; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if (matched[ja[j]] != MATCHED && matched[i] != MATCHED){ if (first) { amax = a[j]; jamax = ja[j]; first = FALSE; } else { if (a[j] > amax){ amax = a[j]; jamax = ja[j]; } } } } if (!first){ matched[jamax] = MATCHED; matched[i] = MATCHED; (*cluster)[nz++] = i; (*cluster)[nz++] = jamax; (*clusterp)[++(*ncluster)] = nz; } } /* dan yi dian, wu ban */ for (i = 0; i < m; i++){ if (matched[i] == i){ (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } FREE(p); } FREE(super); FREE(superp); FREE(matched); }
static void maximal_independent_edge_set_heavest_cluster_pernode_leaves_first(SparseMatrix A, int csize, int randomize, int **cluster, int **clusterp, int *ncluster){ int i, ii, j, *ia, *ja, m, n, *p = NULL, q, iv; real *a; int *matched, nz, nz0, nzz,k, nv; enum {UNMATCHED = -2, MATCHED = -1}; real *vlist; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *cluster = N_GNEW(m,int); *clusterp = N_GNEW((m+1),int); matched = N_GNEW(m,int); vlist = N_GNEW(2*m,real); for (i = 0; i < m; i++) matched[i] = i; assert(SparseMatrix_is_symmetric(A, FALSE)); assert(A->type == MATRIX_TYPE_REAL); *ncluster = 0; (*clusterp)[0] = 0; nz = 0; a = (real*) A->a; p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; if (matched[i] == MATCHED || node_degree(i) != 1) continue; q = ja[ia[i]]; assert(matched[q] != MATCHED); matched[q] = MATCHED; (*cluster)[nz++] = q; for (j = ia[q]; j < ia[q+1]; j++){ if (q == ja[j]) continue; if (node_degree(ja[j]) == 1){ matched[ja[j]] = MATCHED; (*cluster)[nz++] = ja[j]; } } nz0 = (*clusterp)[*ncluster]; if (nz - nz0 <= MAX_CLUSTER_SIZE){ (*clusterp)[++(*ncluster)] = nz; } else { (*clusterp)[++(*ncluster)] = ++nz0; nzz = nz0; for (k = nz0; k < nz && nzz < nz; k++){ nzz += MAX_CLUSTER_SIZE - 1; nzz = MIN(nz, nzz); (*clusterp)[++(*ncluster)] = nzz; } } } for (ii = 0; ii < m; ii++){ i = p[ii]; if (matched[i] == MATCHED) continue; nv = 0; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if (matched[ja[j]] != MATCHED && matched[i] != MATCHED){ vlist[2*nv] = ja[j]; vlist[2*nv+1] = a[j]; nv++; } } if (nv > 0){ qsort(vlist, nv, sizeof(real)*2, scomp); for (j = 0; j < MIN(csize - 1, nv); j++){ iv = (int) vlist[2*j]; matched[iv] = MATCHED; (*cluster)[nz++] = iv; } matched[i] = MATCHED; (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } /* dan yi dian, wu ban */ for (i = 0; i < m; i++){ if (matched[i] == i){ (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } FREE(p); FREE(matched); }
static void maximal_independent_edge_set_heavest_edge_pernode_leaves_first(SparseMatrix A, int randomize, int **cluster, int **clusterp, int *ncluster){ int i, ii, j, *ia, *ja, m, n, *p = NULL, q; real *a, amax = 0; int first = TRUE, jamax = 0; int *matched, nz, ncmax = 0, nz0, nzz,k ; enum {UNMATCHED = -2, MATCHED = -1}; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *cluster = N_GNEW(m,int); *clusterp = N_GNEW((m+1),int); matched = N_GNEW(m,int); for (i = 0; i < m; i++) matched[i] = i; assert(SparseMatrix_is_symmetric(A, FALSE)); assert(A->type == MATRIX_TYPE_REAL); *ncluster = 0; (*clusterp)[0] = 0; nz = 0; a = (real*) A->a; if (!randomize){ for (i = 0; i < m; i++){ if (matched[i] == MATCHED || node_degree(i) != 1) continue; q = ja[ia[i]]; assert(matched[q] != MATCHED); matched[q] = MATCHED; (*cluster)[nz++] = q; for (j = ia[q]; j < ia[q+1]; j++){ if (q == ja[j]) continue; if (node_degree(ja[j]) == 1){ matched[ja[j]] = MATCHED; (*cluster)[nz++] = ja[j]; } } ncmax = MAX(ncmax, nz - (*clusterp)[*ncluster]); nz0 = (*clusterp)[*ncluster]; if (nz - nz0 <= MAX_CLUSTER_SIZE){ (*clusterp)[++(*ncluster)] = nz; } else { (*clusterp)[++(*ncluster)] = ++nz0; nzz = nz0; for (k = nz0; k < nz && nzz < nz; k++){ nzz += MAX_CLUSTER_SIZE - 1; nzz = MIN(nz, nzz); (*clusterp)[++(*ncluster)] = nzz; } } } #ifdef DEBUG_print if (Verbose) fprintf(stderr, "%d leaves and parents for %d clusters, largest cluster = %d\n",nz, *ncluster, ncmax); #endif for (i = 0; i < m; i++){ first = TRUE; if (matched[i] == MATCHED) continue; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if (matched[ja[j]] != MATCHED && matched[i] != MATCHED){ if (first) { amax = a[j]; jamax = ja[j]; first = FALSE; } else { if (a[j] > amax){ amax = a[j]; jamax = ja[j]; } } } } if (!first){ matched[jamax] = MATCHED; matched[i] = MATCHED; (*cluster)[nz++] = i; (*cluster)[nz++] = jamax; (*clusterp)[++(*ncluster)] = nz; } } /* dan yi dian, wu ban */ for (i = 0; i < m; i++){ if (matched[i] == i){ (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } assert(nz == n); } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; if (matched[i] == MATCHED || node_degree(i) != 1) continue; q = ja[ia[i]]; assert(matched[q] != MATCHED); matched[q] = MATCHED; (*cluster)[nz++] = q; for (j = ia[q]; j < ia[q+1]; j++){ if (q == ja[j]) continue; if (node_degree(ja[j]) == 1){ matched[ja[j]] = MATCHED; (*cluster)[nz++] = ja[j]; } } ncmax = MAX(ncmax, nz - (*clusterp)[*ncluster]); nz0 = (*clusterp)[*ncluster]; if (nz - nz0 <= MAX_CLUSTER_SIZE){ (*clusterp)[++(*ncluster)] = nz; } else { (*clusterp)[++(*ncluster)] = ++nz0; nzz = nz0; for (k = nz0; k < nz && nzz < nz; k++){ nzz += MAX_CLUSTER_SIZE - 1; nzz = MIN(nz, nzz); (*clusterp)[++(*ncluster)] = nzz; } } } #ifdef DEBUG_print if (Verbose) fprintf(stderr, "%d leaves and parents for %d clusters, largest cluster = %d\n",nz, *ncluster, ncmax); #endif for (ii = 0; ii < m; ii++){ i = p[ii]; first = TRUE; if (matched[i] == MATCHED) continue; for (j = ia[i]; j < ia[i+1]; j++){ if (i == ja[j]) continue; if (matched[ja[j]] != MATCHED && matched[i] != MATCHED){ if (first) { amax = a[j]; jamax = ja[j]; first = FALSE; } else { if (a[j] > amax){ amax = a[j]; jamax = ja[j]; } } } } if (!first){ matched[jamax] = MATCHED; matched[i] = MATCHED; (*cluster)[nz++] = i; (*cluster)[nz++] = jamax; (*clusterp)[++(*ncluster)] = nz; } } /* dan yi dian, wu ban */ for (i = 0; i < m; i++){ if (matched[i] == i){ (*cluster)[nz++] = i; (*clusterp)[++(*ncluster)] = nz; } } FREE(p); } FREE(matched); }
// C++ implementation using std::vector // Create two separate coordinate tables, n_list random lists // amap[ n_list ], bmap[ n_list ], wmap[ n_list ] // // void test_dgsks_list( int rangem, int rangen, int k, int ntask ) { int m, n, i, j, p, nx, iter; int *amap, *bmap, *wmap; int *randperm; double *XA, *XB, *XA2, *XB2, *u, *w, *umkl; double tmp, h, error, flops; double ref_beg, ref_time, dgsks_beg, dgsks_time; ks_t kernel; // ======================== std::vector<double> uvec; // ======================== std::vector< std::vector<int> > alist; std::vector< std::vector<int> > blist; std::vector< std::vector<int> > wlist; int n_list; n_list = ntask; nx = 4096 * 5; //nx = rangem * 5; //k = 256; flops = 0.0; // Initialize alist, blist and wlist alist.resize( n_list ); blist.resize( n_list ); wlist.resize( n_list ); // Random Permutation Array randperm = (int*)malloc( sizeof(int) * nx ); // Random list generation for ( i = 0; i < n_list; i++ ) { // First decide amap.size() and bmap.size() int na = rand() % rangem + 512; int nb = rand() % rangen + 512; //int na = 569; //int nb = 8; flops += (double)( na * nb ); alist[ i ].resize( na ); blist[ i ].resize( nb ); wlist[ i ].resize( nb ); // Random permutation random_permutation( randperm, nx ); // Random amap for ( j = 0; j < na; j++ ) { // TODO: nx should be nxa if XA and XB are with different sizes. // TODO: replace the random generation as random permutation // alist[ i ][ j ] = randperm[ j ]; //if ( alist[ i ][ j ] == 909 ) { // std::cout << j << "\n"; //} } // Random permutation random_permutation( randperm, nx ); // Random bmap and wmap for ( j = 0; j < nb; j++ ) { // TODO: nx should be nxa if XA and XB are with different sizes. blist[ i ][ j ] = randperm[ j ]; wlist[ i ][ j ] = randperm[ j ]; } } std::cout << "Check point after rand list\n"; XA = (double*)malloc( sizeof(double) * k * nx ); XA2 = (double*)malloc( sizeof(double) * nx ); XB = XA; XB2 = XA2; u = (double*)malloc( sizeof(double) * nx ); w = (double*)malloc( sizeof(double) * nx ); umkl = (double*)malloc( sizeof(double) * nx ); uvec.resize( nx, 0.0 ); std::cout << "Check point after malloc\n"; // Initialize u, umkl and w for ( i = 0; i < nx; i ++ ) { u[ i ] = 0.0; umkl[ i ] = 0.0; w[ i ] = 1.0; } std::cout << "Check point after u, umkl, w\n"; // random[ 0, 1 ] for ( i = 0; i < nx; i ++ ) { for ( p = 0; p < k; p ++ ) { XA[ i * k + p ] = (double)( rand() % 100 ) / 1000.0; //XA[ i * k + p ] = 1.0; } } std::cout << "Check point after XA\n"; // Compute XA2 for ( i = 0; i < nx; i ++ ) { tmp = 0.0; for ( p = 0; p < k; p ++ ) { tmp += XA[ i * k + p ] * XA[ i * k + p ]; } XA2[ i ] = tmp; } std::cout << "Check point brfore kernel\n"; // Test Gaussian Kernel kernel.type = KS_GAUSSIAN; kernel.scal = -0.5; //kernel.scal = -5000.0; //kernel.type = KS_GAUSSIAN_VAR_BANDWIDTH; //kernel.hi = (double*)malloc( sizeof(double) * nx ); //kernel.hj = (double*)malloc( sizeof(double) * nx ); //for ( i = 0; i < nx; i ++ ) { // //kernel.h[ i ] = -0.5; // //kernel.h[ i ] = ( -0.5 * i ) / 1000.0 ; // kernel.hi[ i ] = ( 1.0 + 0.5 / ( 1 + exp( -1.0 * XA2[ i ] ) ) ); // kernel.hi[ i ] = -1.0 / ( 2.0 * kernel.hi[ i ] * kernel.hi[ i ] ); // kernel.hj[ i ] = kernel.hi[ i ]; //} //printf( "after allocate h vector\n" ); // Test Polynomial Kernel //kernel.type = KS_POLYNOMIAL; //kernel.powe = 3.0; //kernel.scal = 0.1; //kernel.cons = 0.1; // Test Laplace Kernel //kernel.type = KS_LAPLACE; // Compute u using dgsks dgsks_beg = omp_get_wtime(); omp_dgsks_list_separated_u_symmetric( &kernel, k, uvec, alist, XA, nx, alist, blist, w, wlist ); dgsks_time = omp_get_wtime() - dgsks_beg; printf( "Reference\n" ); // Compute u using mkl reference kernel ref_beg = omp_get_wtime(); for ( i = 0; i < n_list; i++ ) { dgsks_ref( &kernel, alist[ i ].size(), blist[ i ].size(), k, umkl, alist[ i ].data(), // Use a unified ulist XA, XA2, alist[ i ].data(), XB, XB2, blist[ i ].data(), w, wlist[ i ].data() ); } ref_time = omp_get_wtime() - ref_beg; // ======================== // TODO: implement error checking error = 0.0; for ( i = 0; i < nx; i ++ ) { if ( fabs( umkl[ i ] - uvec[ i ] ) / fabs( umkl[ i ] ) > 0.0000000001 ) { printf( "umkl[ %d ] = %E, u[ i ] = %E\n", i, umkl[ i ], uvec[ i ] ); } tmp = umkl[ i ] - uvec[ i ]; error += tmp * tmp; } //printf( "%lf, %lf\n", umkl[ 0 ], u[ 0 ] ); switch ( kernel.type ) { case KS_GAUSSIAN: flops = flops * ( 2 * k + 35 ) / ( 1024 * 1024 * 1024 ); break; case KS_GAUSSIAN_VAR_BANDWIDTH: flops = flops * ( 2 * k + 35 ) / ( 1024 * 1024 * 1024 ); break; case KS_POLYNOMIAL: // Need to be readjusted flops = flops * ( 2 * k + 50 ) / ( 1024 * 1024 * 1024 ); break; case KS_LAPLACE: // Need to be readjusted flops = flops * ( 2 * k + 50 ) / ( 1024 * 1024 * 1024 ); break; default: exit( 1 ); } printf( "dgsks: %6.4lf secs / %4.1lf Gflops, ref: %6.4lf secs / %4.1lf Gflops, Absolute Error: %E\n", dgsks_time, flops / dgsks_time, ref_time, flops / ref_time, sqrt( error ) ); free( XA ); free( XA2 ); }
static void maximal_independent_vertex_set_RS(SparseMatrix A, int randomize, int **vset, int *nvset, int *nzc){ /* The Ruge-Stuben coarsening scheme. Initially all vertices are in the U set (with marker MAX_IND_VTX_SET_U), with gain equal to their degree. Select vertex with highest gain into a C set (with marker >= MAX_IND_VTX_SET_C), and their neighbors j in F set (with marker MAX_IND_VTX_SET_F). The neighbors of j that are in the U set get their gains incremented by 1. So overall gain[k] = |{neighbor of k in U set}|+2*|{neighbors of k in F set}|. nzc is the number of entries in the restriction matrix */ int i, jj, ii, *p = NULL, j, k, *ia, *ja, m, n, gain, removed, nf = 0; PriorityQueue q; assert(A); assert(SparseMatrix_known_strucural_symmetric(A)); ia = A->ia; ja = A->ja; m = A->m; n = A->n; assert(n == m); *vset = N_GNEW(m,int); for (i = 0; i < m; i++) { (*vset)[i] = MAX_IND_VTX_SET_U; } *nvset = 0; *nzc = 0; q = PriorityQueue_new(m, 2*(m-1)); if (!randomize){ for (i = 0; i < m; i++) PriorityQueue_push(q, i, ia[i+1] - ia[i]); } else { p = random_permutation(m); for (ii = 0; ii < m; ii++){ i = p[ii]; PriorityQueue_push(q, i, ia[i+1] - ia[i]); } FREE(p); } while (PriorityQueue_pop(q, &i, &gain)){ assert((*vset)[i] == MAX_IND_VTX_SET_U); (*vset)[i] = (*nvset)++; for (j = ia[i]; j < ia[i+1]; j++){ jj = ja[j]; assert((*vset)[jj] == MAX_IND_VTX_SET_U || (*vset)[jj] == MAX_IND_VTX_SET_F); if (i == jj) continue; if ((*vset)[jj] == MAX_IND_VTX_SET_U){ removed = PriorityQueue_remove(q, jj); assert(removed); (*vset)[jj] = MAX_IND_VTX_SET_F; nf++; for (k = ia[jj]; k < ia[jj+1]; k++){ if (jj == ja[k]) continue; if ((*vset)[ja[k]] == MAX_IND_VTX_SET_U){ gain = PriorityQueue_get_gain(q, ja[k]); assert(gain >= 0); PriorityQueue_push(q, ja[k], gain + 1); } } } (*nzc)++; } } (*nzc) += *nvset; PriorityQueue_delete(q); }
double VRP::SA_solve(int heuristics, double start_temp, double cool_ratio, int iters_per_loop, int num_loops, int nlist_size, bool verbose) { /// /// Uses the given parameters to generate a VRP solution using Simulated Annealing. /// Assumes that data has already been imported into V and that we have /// some existing solution. Returns the total route length of the best solution found. /// this->temperature = start_temp; this->cooling_ratio = cool_ratio; int ctr, n, j, i, R, rules, random, fixed, neighbor_list, objective; if(heuristics & VRPH_RANDOMIZED) random=VRPH_RANDOMIZED; else random=0; if(heuristics & VRPH_FIXED_EDGES) fixed=VRPH_FIXED_EDGES; else fixed=0; if(heuristics & VRPH_USE_NEIGHBOR_LIST) neighbor_list=VRPH_USE_NEIGHBOR_LIST; else neighbor_list=0; objective=VRPH_SAVINGS_ONLY; // default strategy if(heuristics & VRPH_MINIMIZE_NUM_ROUTES) objective=VRPH_MINIMIZE_NUM_ROUTES; n=num_nodes; // The perm[] array will contain all the nodes in the current solution int *perm; perm=new int[this->num_nodes]; j=VRPH_ABS(this->next_array[VRPH_DEPOT]); for(i=0;i<this->num_nodes;i++) { perm[i]=j; if(!routed[j]) report_error("%s: Unrouted node in solution!!\n"); j=VRPH_ABS(this->next_array[j]); } if(j!=VRPH_DEPOT) report_error("%s: VRPH_DEPOT is not last node in solution!!\n"); // Define the heuristics we may use OnePointMove OPM; TwoPointMove TPM; TwoOpt TO; OrOpt OR; ThreeOpt ThreeO; CrossExchange CE; ThreePointMove ThreePM; double start_val; this->export_solution_buff(this->best_sol_buff); // We are assuming we have an existing solution // Set the neighbor list size used in the improvement search this->neighbor_list_size=VRPH_MIN(nlist_size, num_nodes); best_total_route_length=this->total_route_length; normalize_route_numbers(); ctr=0; // The idea is to perform num_loops loops of num_iters iterations each. // For each iteration, run through the given heuristic operation at random // and perform a Simulated Annealing search. rules=VRPH_USE_NEIGHBOR_LIST+VRPH_FIRST_ACCEPT+VRPH_SIMULATED_ANNEALING+VRPH_SAVINGS_ONLY; double worst_obj=0; for(ctr=0;ctr<num_loops;ctr++) { if(verbose) { printf("\nctr=%d of %d, temp=%f, obj=%f (overall best=%f; worst=%f)\n",ctr,num_loops, this->temperature, this->total_route_length,this->best_total_route_length,worst_obj); fflush(stdout); } // Reset worst_obj; worst_obj=0; // Cool it... this->temperature = this->cooling_ratio * this->temperature; for(int k=0; k < iters_per_loop; k++) { start_val=total_route_length; if(heuristics & THREE_OPT) { rules=VRPH_SIMULATED_ANNEALING+VRPH_INTRA_ROUTE_ONLY+random+fixed+objective; normalize_route_numbers(); R=total_number_of_routes; for(i=1; i<=R; i++) { ThreeO.route_search(this,i,rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & ONE_POINT_MOVE) { rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { OPM.search(this,perm[i-1],rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & TWO_POINT_MOVE) { rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { TPM.search(this,perm[i-1],rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & TWO_OPT) { rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { TO.search(this,perm[i-1],rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & THREE_POINT_MOVE) { rules=VRPH_SIMULATED_ANNEALING+VRPH_INTER_ROUTE_ONLY+neighbor_list+random+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { ThreePM.search(this,perm[i-1],rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & OR_OPT) { rules=VRPH_SIMULATED_ANNEALING+neighbor_list+random+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1;i<=n;i++) { OR.search(this,perm[i-1],3,rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } for(i=1;i<=n;i++) { OR.search(this,perm[i-1],2,rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } if(heuristics & CROSS_EXCHANGE) { normalize_route_numbers(); this->find_neighboring_routes(); R=total_number_of_routes; rules=VRPH_SIMULATED_ANNEALING+fixed+objective; if(random) random_permutation(perm, this->num_nodes); for(i=1; i<=R-1; i++) { for(j=0;j<=1;j++) { CE.route_search(this,i, route[i].neighboring_routes[j],rules); if(this->total_route_length > worst_obj) worst_obj=this->total_route_length; } } } } } delete [] perm; // Restore the best sol this->import_solution_buff(this->best_sol_buff); // Now return the obj. function value if(has_service_times==false) return this->best_total_route_length; else return this->best_total_route_length-total_service_time; }
random_solution(tsp_solution *s) { random_permutation(&(s->p[1]),(s->n)-1); }